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
6c2ff75fab78b62432cc98ee24e8de93db9e1168
2eab05920d6eeb06665e1a6df77b3157354316ad
/src/number_theory/arithmetic_function.lean
2326486d77b920e2c91d12d697a91d8d1f11bdaa
[ "Apache-2.0" ]
permissive
ayush1801/mathlib
78949b9f789f488148142221606bf15c02b960d2
ce164e28f262acbb3de6281b3b03660a9f744e3c
refs/heads/master
1,692,886,907,941
1,635,270,866,000
1,635,270,866,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
32,574
lean
/- Copyright (c) 2020 Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson -/ import algebra.big_operators.ring import number_theory.divisors import algebra.squarefree import algebra.invertible /-! # Arithmetic Functions and Dirichlet Convolution This file defines arithmetic functions, which are functions from `ℕ` to a specified type that map 0 to 0. In the literature, they are often instead defined as functions from `ℕ+`. These arithmetic functions are endowed with a multiplication, given by Dirichlet convolution, and pointwise addition, to form the Dirichlet ring. ## Main Definitions * `arithmetic_function R` consists of functions `f : ℕ → R` such that `f 0 = 0`. * An arithmetic function `f` `is_multiplicative` when `x.coprime y → f (x * y) = f x * f y`. * The pointwise operations `pmul` and `ppow` differ from the multiplication and power instances on `arithmetic_function R`, which use Dirichlet multiplication. * `ζ` is the arithmetic function such that `ζ x = 1` for `0 < x`. * `σ k` is the arithmetic function such that `σ k x = ∑ y in divisors x, y ^ k` for `0 < x`. * `pow k` is the arithmetic function such that `pow k x = x ^ k` for `0 < x`. * `id` is the identity arithmetic function on `ℕ`. * `ω n` is the number of distinct prime factors of `n`. * `Ω n` is the number of prime factors of `n` counted with multiplicity. * `μ` is the Möbius function. ## Main Results * Several forms of Möbius inversion: * `sum_eq_iff_sum_mul_moebius_eq` for functions to a `comm_ring` * `sum_eq_iff_sum_smul_moebius_eq` for functions to an `add_comm_group` * `prod_eq_iff_prod_pow_moebius_eq` for functions to a `comm_group` * `prod_eq_iff_prod_pow_moebius_eq_of_nonzero` for functions to a `comm_group_with_zero` ## Notation The arithmetic functions `ζ` and `σ` have Greek letter names, which are localized notation in the namespace `arithmetic_function`. ## Tags arithmetic functions, dirichlet convolution, divisors -/ open finset open_locale big_operators namespace nat variable (R : Type*) /-- An arithmetic function is a function from `ℕ` that maps 0 to 0. In the literature, they are often instead defined as functions from `ℕ+`. Multiplication on `arithmetic_functions` is by Dirichlet convolution. -/ @[derive [has_zero, inhabited]] def arithmetic_function [has_zero R] := zero_hom ℕ R variable {R} namespace arithmetic_function section has_zero variable [has_zero R] instance : has_coe_to_fun (arithmetic_function R) (λ _, ℕ → R) := zero_hom.has_coe_to_fun @[simp] lemma to_fun_eq (f : arithmetic_function R) : f.to_fun = f := rfl @[simp] lemma map_zero {f : arithmetic_function R} : f 0 = 0 := zero_hom.map_zero' f theorem coe_inj {f g : arithmetic_function R} : (f : ℕ → R) = g ↔ f = g := ⟨λ h, zero_hom.coe_inj h, λ h, h ▸ rfl⟩ @[simp] lemma zero_apply {x : ℕ} : (0 : arithmetic_function R) x = 0 := zero_hom.zero_apply x @[ext] theorem ext ⦃f g : arithmetic_function R⦄ (h : ∀ x, f x = g x) : f = g := zero_hom.ext h theorem ext_iff {f g : arithmetic_function R} : f = g ↔ ∀ x, f x = g x := zero_hom.ext_iff section has_one variable [has_one R] instance : has_one (arithmetic_function R) := ⟨⟨λ x, ite (x = 1) 1 0, rfl⟩⟩ @[simp] lemma one_one : (1 : arithmetic_function R) 1 = 1 := rfl @[simp] lemma one_apply_ne {x : ℕ} (h : x ≠ 1) : (1 : arithmetic_function R) x = 0 := if_neg h end has_one end has_zero instance nat_coe [has_zero R] [has_one R] [has_add R] : has_coe (arithmetic_function ℕ) (arithmetic_function R) := ⟨λ f, ⟨↑(f : ℕ → ℕ), by { transitivity ↑(f 0), refl, simp }⟩⟩ @[simp] lemma nat_coe_nat (f : arithmetic_function ℕ) : (↑f : arithmetic_function ℕ) = f := ext $ λ _, cast_id _ @[simp] lemma nat_coe_apply [has_zero R] [has_one R] [has_add R] {f : arithmetic_function ℕ} {x : ℕ} : (f : arithmetic_function R) x = f x := rfl instance int_coe [has_zero R] [has_one R] [has_add R] [has_neg R] : has_coe (arithmetic_function ℤ) (arithmetic_function R) := ⟨λ f, ⟨↑(f : ℕ → ℤ), by { transitivity ↑(f 0), refl, simp }⟩⟩ @[simp] lemma int_coe_int (f : arithmetic_function ℤ) : (↑f : arithmetic_function ℤ) = f := ext $ λ _, int.cast_id _ @[simp] lemma int_coe_apply [has_zero R] [has_one R] [has_add R] [has_neg R] {f : arithmetic_function ℤ} {x : ℕ} : (f : arithmetic_function R) x = f x := rfl @[simp] lemma coe_coe [has_zero R] [has_one R] [has_add R] [has_neg R] {f : arithmetic_function ℕ} : ((f : arithmetic_function ℤ) : arithmetic_function R) = f := by { ext, simp, } section add_monoid variable [add_monoid R] instance : has_add (arithmetic_function R) := ⟨λ f g, ⟨λ n, f n + g n, by simp⟩⟩ @[simp] lemma add_apply {f g : arithmetic_function R} {n : ℕ} : (f + g) n = f n + g n := rfl instance : add_monoid (arithmetic_function R) := { add_assoc := λ _ _ _, ext (λ _, add_assoc _ _ _), zero_add := λ _, ext (λ _, zero_add _), add_zero := λ _, ext (λ _, add_zero _), .. arithmetic_function.has_zero R, .. arithmetic_function.has_add } end add_monoid instance [add_comm_monoid R] : add_comm_monoid (arithmetic_function R) := { add_comm := λ _ _, ext (λ _, add_comm _ _), .. arithmetic_function.add_monoid } instance [add_group R] : add_group (arithmetic_function R) := { neg := λ f, ⟨λ n, - f n, by simp⟩, add_left_neg := λ _, ext (λ _, add_left_neg _), .. arithmetic_function.add_monoid } instance [add_comm_group R] : add_comm_group (arithmetic_function R) := { .. arithmetic_function.add_comm_monoid, .. arithmetic_function.add_group } section has_scalar variables {M : Type*} [has_zero R] [add_comm_monoid M] [has_scalar R M] /-- The Dirichlet convolution of two arithmetic functions `f` and `g` is another arithmetic function such that `(f * g) n` is the sum of `f x * g y` over all `(x,y)` such that `x * y = n`. -/ instance : has_scalar (arithmetic_function R) (arithmetic_function M) := ⟨λ f g, ⟨λ n, ∑ x in divisors_antidiagonal n, f x.fst • g x.snd, by simp⟩⟩ @[simp] lemma smul_apply {f : arithmetic_function R} {g : arithmetic_function M} {n : ℕ} : (f • g) n = ∑ x in divisors_antidiagonal n, f x.fst • g x.snd := rfl end has_scalar /-- The Dirichlet convolution of two arithmetic functions `f` and `g` is another arithmetic function such that `(f * g) n` is the sum of `f x * g y` over all `(x,y)` such that `x * y = n`. -/ instance [semiring R] : has_mul (arithmetic_function R) := ⟨(•)⟩ @[simp] lemma mul_apply [semiring R] {f g : arithmetic_function R} {n : ℕ} : (f * g) n = ∑ x in divisors_antidiagonal n, f x.fst * g x.snd := rfl section module variables {M : Type*} [semiring R] [add_comm_monoid M] [module R M] lemma mul_smul' (f g : arithmetic_function R) (h : arithmetic_function M) : (f * g) • h = f • g • h := begin ext n, simp only [mul_apply, smul_apply, sum_smul, mul_smul, smul_sum, finset.sum_sigma'], apply finset.sum_bij, swap 5, { rintros ⟨⟨i,j⟩, ⟨k,l⟩⟩ H, exact ⟨(k, l*j), (l, j)⟩ }, { rintros ⟨⟨i,j⟩, ⟨k,l⟩⟩ H, simp only [finset.mem_sigma, mem_divisors_antidiagonal] at H ⊢, rcases H with ⟨⟨rfl, n0⟩, rfl, i0⟩, refine ⟨⟨(mul_assoc _ _ _).symm, n0⟩, rfl, _⟩, rw mul_ne_zero_iff at *, exact ⟨i0.2, n0.2⟩, }, { rintros ⟨⟨i,j⟩, ⟨k,l⟩⟩ H, simp only [mul_assoc] }, { rintros ⟨⟨a,b⟩, ⟨c,d⟩⟩ ⟨⟨i,j⟩, ⟨k,l⟩⟩ H₁ H₂, simp only [finset.mem_sigma, mem_divisors_antidiagonal, and_imp, prod.mk.inj_iff, add_comm, heq_iff_eq] at H₁ H₂ ⊢, rintros rfl h2 rfl rfl, exact ⟨⟨eq.trans H₁.2.1.symm H₂.2.1, rfl⟩, rfl, rfl⟩ }, { rintros ⟨⟨i,j⟩, ⟨k,l⟩⟩ H, refine ⟨⟨(i*k, l), (i, k)⟩, _, _⟩, { simp only [finset.mem_sigma, mem_divisors_antidiagonal] at H ⊢, rcases H with ⟨⟨rfl, n0⟩, rfl, j0⟩, refine ⟨⟨mul_assoc _ _ _, n0⟩, rfl, _⟩, rw mul_ne_zero_iff at *, exact ⟨n0.1, j0.1⟩ }, { simp only [true_and, mem_divisors_antidiagonal, and_true, prod.mk.inj_iff, eq_self_iff_true, ne.def, mem_sigma, heq_iff_eq] at H ⊢, rw H.2.1 } } end lemma one_smul' (b : arithmetic_function M) : (1 : arithmetic_function R) • b = b := begin ext, rw smul_apply, by_cases x0 : x = 0, {simp [x0]}, have h : {(1,x)} ⊆ divisors_antidiagonal x := by simp [x0], rw ← sum_subset h, {simp}, intros y ymem ynmem, have y1ne : y.fst ≠ 1, { intro con, simp only [con, mem_divisors_antidiagonal, one_mul, ne.def] at ymem, simp only [mem_singleton, prod.ext_iff] at ynmem, tauto }, simp [y1ne], end end module section semiring variable [semiring R] instance : monoid (arithmetic_function R) := { one_mul := one_smul', mul_one := λ f, begin ext, rw mul_apply, by_cases x0 : x = 0, {simp [x0]}, have h : {(x,1)} ⊆ divisors_antidiagonal x := by simp [x0], rw ← sum_subset h, {simp}, intros y ymem ynmem, have y2ne : y.snd ≠ 1, { intro con, simp only [con, mem_divisors_antidiagonal, mul_one, ne.def] at ymem, simp only [mem_singleton, prod.ext_iff] at ynmem, tauto }, simp [y2ne], end, mul_assoc := mul_smul', .. arithmetic_function.has_one, .. arithmetic_function.has_mul } instance : semiring (arithmetic_function R) := { zero_mul := λ f, by { ext, simp only [mul_apply, zero_mul, sum_const_zero, zero_apply] }, mul_zero := λ f, by { ext, simp only [mul_apply, sum_const_zero, mul_zero, zero_apply] }, left_distrib := λ a b c, by { ext, simp only [←sum_add_distrib, mul_add, mul_apply, add_apply] }, right_distrib := λ a b c, by { ext, simp only [←sum_add_distrib, add_mul, mul_apply, add_apply] }, .. arithmetic_function.has_zero R, .. arithmetic_function.has_mul, .. arithmetic_function.has_add, .. arithmetic_function.add_comm_monoid, .. arithmetic_function.monoid } end semiring instance [comm_semiring R] : comm_semiring (arithmetic_function R) := { mul_comm := λ f g, by { ext, rw [mul_apply, ← map_swap_divisors_antidiagonal, sum_map], simp [mul_comm] }, .. arithmetic_function.semiring } instance [comm_ring R] : comm_ring (arithmetic_function R) := { .. arithmetic_function.add_comm_group, .. arithmetic_function.comm_semiring } instance {M : Type*} [semiring R] [add_comm_monoid M] [module R M] : module (arithmetic_function R) (arithmetic_function M) := { one_smul := one_smul', mul_smul := mul_smul', smul_add := λ r x y, by { ext, simp only [sum_add_distrib, smul_add, smul_apply, add_apply] }, smul_zero := λ r, by { ext, simp only [smul_apply, sum_const_zero, smul_zero, zero_apply] }, add_smul := λ r s x, by { ext, simp only [add_smul, sum_add_distrib, smul_apply, add_apply] }, zero_smul := λ r, by { ext, simp only [smul_apply, sum_const_zero, zero_smul, zero_apply] }, } section zeta /-- `ζ 0 = 0`, otherwise `ζ x = 1`. The Dirichlet Series is the Riemann ζ. -/ def zeta : arithmetic_function ℕ := ⟨λ x, ite (x = 0) 0 1, rfl⟩ localized "notation `ζ` := zeta" in arithmetic_function @[simp] lemma zeta_apply {x : ℕ} : ζ x = if (x = 0) then 0 else 1 := rfl lemma zeta_apply_ne {x : ℕ} (h : x ≠ 0) : ζ x = 1 := if_neg h @[simp] theorem coe_zeta_mul_apply [semiring R] {f : arithmetic_function R} {x : ℕ} : (↑ζ * f) x = ∑ i in divisors x, f i := begin rw mul_apply, transitivity ∑ i in divisors_antidiagonal x, f i.snd, { apply sum_congr rfl, intros i hi, rcases mem_divisors_antidiagonal.1 hi with ⟨rfl, h⟩, rw [nat_coe_apply, zeta_apply_ne (left_ne_zero_of_mul h), cast_one, one_mul] }, { apply sum_bij (λ i h, prod.snd i), { rintros ⟨a, b⟩ h, simp [snd_mem_divisors_of_mem_antidiagonal h] }, { rintros ⟨a, b⟩ h, refl }, { rintros ⟨a1, b1⟩ ⟨a2, b2⟩ h1 h2 h, dsimp at h, rw h at *, rw mem_divisors_antidiagonal at *, ext, swap, {refl}, simp only [prod.fst, prod.snd] at *, apply nat.eq_of_mul_eq_mul_right _ (eq.trans h1.1 h2.1.symm), rcases h1 with ⟨rfl, h⟩, apply nat.pos_of_ne_zero (right_ne_zero_of_mul h) }, { intros a ha, rcases mem_divisors.1 ha with ⟨⟨b, rfl⟩, ne0⟩, use (b, a), simp [ne0, mul_comm] } } end theorem coe_zeta_smul_apply {M : Type*} [comm_ring R] [add_comm_group M] [module R M] {f : arithmetic_function M} {x : ℕ} : ((↑ζ : arithmetic_function R) • f) x = ∑ i in divisors x, f i := begin rw smul_apply, transitivity ∑ i in divisors_antidiagonal x, f i.snd, { apply sum_congr rfl, intros i hi, rcases mem_divisors_antidiagonal.1 hi with ⟨rfl, h⟩, rw [nat_coe_apply, zeta_apply_ne (left_ne_zero_of_mul h), cast_one, one_smul] }, { apply sum_bij (λ i h, prod.snd i), { rintros ⟨a, b⟩ h, simp [snd_mem_divisors_of_mem_antidiagonal h] }, { rintros ⟨a, b⟩ h, refl }, { rintros ⟨a1, b1⟩ ⟨a2, b2⟩ h1 h2 h, dsimp at h, rw h at *, rw mem_divisors_antidiagonal at *, ext, swap, {refl}, simp only [prod.fst, prod.snd] at *, apply nat.eq_of_mul_eq_mul_right _ (eq.trans h1.1 h2.1.symm), rcases h1 with ⟨rfl, h⟩, apply nat.pos_of_ne_zero (right_ne_zero_of_mul h) }, { intros a ha, rcases mem_divisors.1 ha with ⟨⟨b, rfl⟩, ne0⟩, use (b, a), simp [ne0, mul_comm] } } end @[simp] theorem coe_mul_zeta_apply [semiring R] {f : arithmetic_function R} {x : ℕ} : (f * ζ) x = ∑ i in divisors x, f i := begin apply opposite.op_injective, rw [op_sum], convert @coe_zeta_mul_apply Rᵒᵖ _ { to_fun := opposite.op ∘ f, map_zero' := by simp} x, rw [mul_apply, mul_apply, op_sum], conv_lhs { rw ← map_swap_divisors_antidiagonal, }, rw sum_map, apply sum_congr rfl, intros y hy, by_cases h1 : y.fst = 0, { simp [function.comp_apply, h1] }, { simp only [h1, mul_one, one_mul, prod.fst_swap, function.embedding.coe_fn_mk, prod.snd_swap, if_false, zeta_apply, zero_hom.coe_mk, nat_coe_apply, cast_one] } end theorem zeta_mul_apply {f : arithmetic_function ℕ} {x : ℕ} : (ζ * f) x = ∑ i in divisors x, f i := by rw [← nat_coe_nat ζ, coe_zeta_mul_apply] theorem mul_zeta_apply {f : arithmetic_function ℕ} {x : ℕ} : (f * ζ) x = ∑ i in divisors x, f i := by rw [← nat_coe_nat ζ, coe_mul_zeta_apply] end zeta open_locale arithmetic_function section pmul /-- This is the pointwise product of `arithmetic_function`s. -/ def pmul [mul_zero_class R] (f g : arithmetic_function R) : arithmetic_function R := ⟨λ x, f x * g x, by simp⟩ @[simp] lemma pmul_apply [mul_zero_class R] {f g : arithmetic_function R} {x : ℕ} : f.pmul g x = f x * g x := rfl lemma pmul_comm [comm_monoid_with_zero R] (f g : arithmetic_function R) : f.pmul g = g.pmul f := by { ext, simp [mul_comm] } variable [semiring R] @[simp] lemma pmul_zeta (f : arithmetic_function R) : f.pmul ↑ζ = f := begin ext x, cases x; simp [nat.succ_ne_zero], end @[simp] lemma zeta_pmul (f : arithmetic_function R) : (ζ : arithmetic_function R).pmul f = f := begin ext x, cases x; simp [nat.succ_ne_zero], end /-- This is the pointwise power of `arithmetic_function`s. -/ def ppow (f : arithmetic_function R) (k : ℕ) : arithmetic_function R := if h0 : k = 0 then ζ else ⟨λ x, (f x) ^ k, by { rw [map_zero], exact zero_pow (nat.pos_of_ne_zero h0) }⟩ @[simp] lemma ppow_zero {f : arithmetic_function R} : f.ppow 0 = ζ := by rw [ppow, dif_pos rfl] @[simp] lemma ppow_apply {f : arithmetic_function R} {k x : ℕ} (kpos : 0 < k) : f.ppow k x = (f x) ^ k := by { rw [ppow, dif_neg (ne_of_gt kpos)], refl } lemma ppow_succ {f : arithmetic_function R} {k : ℕ} : f.ppow (k + 1) = f.pmul (f.ppow k) := begin ext x, rw [ppow_apply (nat.succ_pos k), pow_succ], induction k; simp, end lemma ppow_succ' {f : arithmetic_function R} {k : ℕ} {kpos : 0 < k} : f.ppow (k + 1) = (f.ppow k).pmul f := begin ext x, rw [ppow_apply (nat.succ_pos k), pow_succ'], induction k; simp, end end pmul /-- Multiplicative functions -/ def is_multiplicative [monoid_with_zero R] (f : arithmetic_function R) : Prop := f 1 = 1 ∧ (∀ {m n : ℕ}, m.coprime n → f (m * n) = f m * f n) namespace is_multiplicative section monoid_with_zero variable [monoid_with_zero R] @[simp] lemma map_one {f : arithmetic_function R} (h : f.is_multiplicative) : f 1 = 1 := h.1 @[simp] lemma map_mul_of_coprime {f : arithmetic_function R} (hf : f.is_multiplicative) {m n : ℕ} (h : m.coprime n) : f (m * n) = f m * f n := hf.2 h end monoid_with_zero lemma nat_cast {f : arithmetic_function ℕ} [semiring R] (h : f.is_multiplicative) : is_multiplicative (f : arithmetic_function R) := ⟨by simp [h], λ m n cop, by simp [cop, h]⟩ lemma int_cast {f : arithmetic_function ℤ} [ring R] (h : f.is_multiplicative) : is_multiplicative (f : arithmetic_function R) := ⟨by simp [h], λ m n cop, by simp [cop, h]⟩ lemma mul [comm_semiring R] {f g : arithmetic_function R} (hf : f.is_multiplicative) (hg : g.is_multiplicative) : is_multiplicative (f * g) := ⟨by { simp [hf, hg], }, begin simp only [mul_apply], intros m n cop, rw sum_mul_sum, symmetry, apply sum_bij (λ (x : (ℕ × ℕ) × ℕ × ℕ) h, (x.1.1 * x.2.1, x.1.2 * x.2.2)), { rintros ⟨⟨a1, a2⟩, ⟨b1, b2⟩⟩ h, simp only [mem_divisors_antidiagonal, ne.def, mem_product] at h, rcases h with ⟨⟨rfl, ha⟩, ⟨rfl, hb⟩⟩, simp only [mem_divisors_antidiagonal, nat.mul_eq_zero, ne.def], split, {ring}, rw nat.mul_eq_zero at *, apply not_or ha hb }, { rintros ⟨⟨a1, a2⟩, ⟨b1, b2⟩⟩ h, simp only [mem_divisors_antidiagonal, ne.def, mem_product] at h, rcases h with ⟨⟨rfl, ha⟩, ⟨rfl, hb⟩⟩, dsimp only, rw [hf.map_mul_of_coprime cop.coprime_mul_right.coprime_mul_right_right, hg.map_mul_of_coprime cop.coprime_mul_left.coprime_mul_left_right], ring, }, { rintros ⟨⟨a1, a2⟩, ⟨b1, b2⟩⟩ ⟨⟨c1, c2⟩, ⟨d1, d2⟩⟩ hab hcd h, simp only [mem_divisors_antidiagonal, ne.def, mem_product] at hab, rcases hab with ⟨⟨rfl, ha⟩, ⟨rfl, hb⟩⟩, simp only [mem_divisors_antidiagonal, ne.def, mem_product] at hcd, simp only [prod.mk.inj_iff] at h, ext; dsimp only, { transitivity nat.gcd (a1 * a2) (a1 * b1), { rw [nat.gcd_mul_left, cop.coprime_mul_left.coprime_mul_right_right.gcd_eq_one, mul_one] }, { rw [← hcd.1.1, ← hcd.2.1] at cop, rw [← hcd.1.1, h.1, nat.gcd_mul_left, cop.coprime_mul_left.coprime_mul_right_right.gcd_eq_one, mul_one] } }, { transitivity nat.gcd (a1 * a2) (a2 * b2), { rw [mul_comm, nat.gcd_mul_left, cop.coprime_mul_right.coprime_mul_left_right.gcd_eq_one, mul_one] }, { rw [← hcd.1.1, ← hcd.2.1] at cop, rw [← hcd.1.1, h.2, mul_comm, nat.gcd_mul_left, cop.coprime_mul_right.coprime_mul_left_right.gcd_eq_one, mul_one] } }, { transitivity nat.gcd (b1 * b2) (a1 * b1), { rw [mul_comm, nat.gcd_mul_right, cop.coprime_mul_right.coprime_mul_left_right.symm.gcd_eq_one, one_mul] }, { rw [← hcd.1.1, ← hcd.2.1] at cop, rw [← hcd.2.1, h.1, mul_comm c1 d1, nat.gcd_mul_left, cop.coprime_mul_right.coprime_mul_left_right.symm.gcd_eq_one, mul_one] } }, { transitivity nat.gcd (b1 * b2) (a2 * b2), { rw [nat.gcd_mul_right, cop.coprime_mul_left.coprime_mul_right_right.symm.gcd_eq_one, one_mul] }, { rw [← hcd.1.1, ← hcd.2.1] at cop, rw [← hcd.2.1, h.2, nat.gcd_mul_right, cop.coprime_mul_left.coprime_mul_right_right.symm.gcd_eq_one, one_mul] } } }, { rintros ⟨b1, b2⟩ h, simp only [mem_divisors_antidiagonal, ne.def, mem_product] at h, use ((b1.gcd m, b2.gcd m), (b1.gcd n, b2.gcd n)), simp only [exists_prop, prod.mk.inj_iff, ne.def, mem_product, mem_divisors_antidiagonal], rw [← cop.gcd_mul _, ← cop.gcd_mul _, ← h.1, nat.gcd_mul_gcd_of_coprime_of_mul_eq_mul cop h.1, nat.gcd_mul_gcd_of_coprime_of_mul_eq_mul cop.symm _], { rw [nat.mul_eq_zero, decidable.not_or_iff_and_not] at h, simp [h.2.1, h.2.2] }, rw [mul_comm n m, h.1] } end⟩ lemma pmul [comm_semiring R] {f g : arithmetic_function R} (hf : f.is_multiplicative) (hg : g.is_multiplicative) : is_multiplicative (f.pmul g) := ⟨by { simp [hf, hg], }, λ m n cop, begin simp only [pmul_apply, hf.map_mul_of_coprime cop, hg.map_mul_of_coprime cop], ring, end⟩ end is_multiplicative section special_functions /-- The identity on `ℕ` as an `arithmetic_function`. -/ def id : arithmetic_function ℕ := ⟨id, rfl⟩ @[simp] lemma id_apply {x : ℕ} : id x = x := rfl /-- `pow k n = n ^ k`, except `pow 0 0 = 0`. -/ def pow (k : ℕ) : arithmetic_function ℕ := id.ppow k @[simp] lemma pow_apply {k n : ℕ} : pow k n = if (k = 0 ∧ n = 0) then 0 else n ^ k := begin cases k, { simp [pow] }, simp [pow, (ne_of_lt (nat.succ_pos k)).symm], end /-- `σ k n` is the sum of the `k`th powers of the divisors of `n` -/ def sigma (k : ℕ) : arithmetic_function ℕ := ⟨λ n, ∑ d in divisors n, d ^ k, by simp⟩ localized "notation `σ` := sigma" in arithmetic_function @[simp] lemma sigma_apply {k n : ℕ} : σ k n = ∑ d in divisors n, d ^ k := rfl lemma sigma_one_apply {n : ℕ} : σ 1 n = ∑ d in divisors n, d := by simp lemma zeta_mul_pow_eq_sigma {k : ℕ} : ζ * pow k = σ k := begin ext, rw [sigma, zeta_mul_apply], apply sum_congr rfl, intros x hx, rw [pow_apply, if_neg (not_and_of_not_right _ _)], contrapose! hx, simp [hx], end lemma is_multiplicative_zeta : is_multiplicative ζ := ⟨by simp, λ m n cop, begin cases m, {simp}, cases n, {simp}, simp [nat.succ_ne_zero] end⟩ lemma is_multiplicative_id : is_multiplicative arithmetic_function.id := ⟨rfl, λ _ _ _, rfl⟩ lemma is_multiplicative.ppow [comm_semiring R] {f : arithmetic_function R} (hf : f.is_multiplicative) {k : ℕ} : is_multiplicative (f.ppow k) := begin induction k with k hi, { exact is_multiplicative_zeta.nat_cast }, { rw ppow_succ, apply hf.pmul hi }, end lemma is_multiplicative_pow {k : ℕ} : is_multiplicative (pow k) := is_multiplicative_id.ppow lemma is_multiplicative_sigma {k : ℕ} : is_multiplicative (sigma k) := begin rw [← zeta_mul_pow_eq_sigma], apply ((is_multiplicative_zeta).mul is_multiplicative_pow) end /-- `Ω n` is the number of prime factors of `n`. -/ def card_factors : arithmetic_function ℕ := ⟨λ n, n.factors.length, by simp⟩ localized "notation `Ω` := card_factors" in arithmetic_function lemma card_factors_apply {n : ℕ} : Ω n = n.factors.length := rfl @[simp] lemma card_factors_one : Ω 1 = 0 := by simp [card_factors] lemma card_factors_eq_one_iff_prime {n : ℕ} : Ω n = 1 ↔ n.prime := begin refine ⟨λ h, _, λ h, list.length_eq_one.2 ⟨n, factors_prime h⟩⟩, cases n, { contrapose! h, simp }, rcases list.length_eq_one.1 h with ⟨x, hx⟩, rw [← prod_factors n.succ_pos, hx, list.prod_singleton], apply prime_of_mem_factors, rw [hx, list.mem_singleton] end lemma card_factors_mul {m n : ℕ} (m0 : m ≠ 0) (n0 : n ≠ 0) : Ω (m * n) = Ω m + Ω n := by rw [card_factors_apply, card_factors_apply, card_factors_apply, ← multiset.coe_card, ← factors_eq, unique_factorization_monoid.normalized_factors_mul m0 n0, factors_eq, factors_eq, multiset.card_add, multiset.coe_card, multiset.coe_card] lemma card_factors_multiset_prod {s : multiset ℕ} (h0 : s.prod ≠ 0) : Ω s.prod = (multiset.map Ω s).sum := begin revert h0, apply s.induction_on, by simp, intros a t h h0, rw [multiset.prod_cons, mul_ne_zero_iff] at h0, simp [h0, card_factors_mul, h], end /-- `ω n` is the number of distinct prime factors of `n`. -/ def card_distinct_factors : arithmetic_function ℕ := ⟨λ n, n.factors.erase_dup.length, by simp⟩ localized "notation `ω` := card_distinct_factors" in arithmetic_function lemma card_distinct_factors_zero : ω 0 = 0 := by simp lemma card_distinct_factors_apply {n : ℕ} : ω n = n.factors.erase_dup.length := rfl lemma card_distinct_factors_eq_card_factors_iff_squarefree {n : ℕ} (h0 : n ≠ 0) : ω n = Ω n ↔ squarefree n := begin rw [squarefree_iff_nodup_factors h0, card_distinct_factors_apply], split; intro h, { rw ← list.eq_of_sublist_of_length_eq n.factors.erase_dup_sublist h, apply list.nodup_erase_dup }, { rw h.erase_dup, refl } end /-- `μ` is the Möbius function. If `n` is squarefree with an even number of distinct prime factors, `μ n = 1`. If `n` is squarefree with an odd number of distinct prime factors, `μ n = -1`. If `n` is not squarefree, `μ n = 0`. -/ def moebius : arithmetic_function ℤ := ⟨λ n, if squarefree n then (-1) ^ (card_factors n) else 0, by simp⟩ localized "notation `μ` := moebius" in arithmetic_function @[simp] lemma moebius_apply_of_squarefree {n : ℕ} (h : squarefree n): μ n = (-1) ^ (card_factors n) := if_pos h @[simp] lemma moebius_eq_zero_of_not_squarefree {n : ℕ} (h : ¬ squarefree n): μ n = 0 := if_neg h lemma moebius_ne_zero_iff_squarefree {n : ℕ} : μ n ≠ 0 ↔ squarefree n := begin split; intro h, { contrapose! h, simp [h] }, { simp [h, pow_ne_zero] } end lemma moebius_ne_zero_iff_eq_or {n : ℕ} : μ n ≠ 0 ↔ μ n = 1 ∨ μ n = -1 := begin split; intro h, { rw moebius_ne_zero_iff_squarefree at h, rw moebius_apply_of_squarefree h, apply neg_one_pow_eq_or }, { rcases h with h | h; simp [h] } end open unique_factorization_monoid @[simp] lemma coe_moebius_mul_coe_zeta [comm_ring R] : (μ * ζ : arithmetic_function R) = 1 := begin ext x, cases x, { simp only [divisors_zero, sum_empty, ne.def, not_false_iff, coe_mul_zeta_apply, zero_ne_one, one_apply_ne] }, cases x, { simp only [moebius_apply_of_squarefree, card_factors_one, squarefree_one, divisors_one, int.cast_one, sum_singleton, coe_mul_zeta_apply, one_one, int_coe_apply, pow_zero] }, rw [coe_mul_zeta_apply, one_apply_ne (ne_of_gt (succ_lt_succ (nat.succ_pos _)))], simp_rw [int_coe_apply], rw [←int.cast_sum, ← sum_filter_ne_zero], convert int.cast_zero, simp only [moebius_ne_zero_iff_squarefree], suffices : ∑ (y : finset ℕ) in (unique_factorization_monoid.normalized_factors x.succ.succ).to_finset.powerset, ite (squarefree y.val.prod) ((-1:ℤ) ^ Ω y.val.prod) 0 = 0, { have h : ∑ i in _, ite (squarefree i) ((-1:ℤ) ^ Ω i) 0 = _ := (sum_divisors_filter_squarefree (nat.succ_ne_zero _)), exact (eq.trans (by congr') h).trans this }, apply eq.trans (sum_congr rfl _) (sum_powerset_neg_one_pow_card_of_nonempty _), { intros y hy, rw [finset.mem_powerset, ← finset.val_le_iff, multiset.to_finset_val] at hy, have h : unique_factorization_monoid.normalized_factors y.val.prod = y.val, { apply factors_multiset_prod_of_irreducible, intros z hz, apply irreducible_of_normalized_factor _ (multiset.subset_of_le (le_trans hy (multiset.erase_dup_le _)) hz) }, rw [if_pos], { rw [card_factors_apply, ← multiset.coe_card, ← factors_eq, h, finset.card] }, rw [unique_factorization_monoid.squarefree_iff_nodup_normalized_factors, h], { apply y.nodup }, rw [ne.def, multiset.prod_eq_zero_iff], intro con, rw ← h at con, exact not_irreducible_zero (irreducible_of_normalized_factor 0 con) }, { rw finset.nonempty, rcases wf_dvd_monoid.exists_irreducible_factor _ (nat.succ_ne_zero _) with ⟨i, hi⟩, { rcases exists_mem_normalized_factors_of_dvd (nat.succ_ne_zero _) hi.1 hi.2 with ⟨j, hj, hj2⟩, use j, apply multiset.mem_to_finset.2 hj }, rw nat.is_unit_iff, norm_num }, end @[simp] lemma coe_zeta_mul_coe_moebius [comm_ring R] : (ζ * μ : arithmetic_function R) = 1 := by rw [mul_comm, coe_moebius_mul_coe_zeta] @[simp] lemma moebius_mul_coe_zeta : (μ * ζ : arithmetic_function ℤ) = 1 := by rw [← int_coe_int μ, coe_moebius_mul_coe_zeta] @[simp] lemma coe_zeta_mul_moebius : (ζ * μ : arithmetic_function ℤ) = 1 := by rw [← int_coe_int μ, coe_zeta_mul_coe_moebius] section comm_ring variable [comm_ring R] instance : invertible (ζ : arithmetic_function R) := { inv_of := μ, inv_of_mul_self := coe_moebius_mul_coe_zeta, mul_inv_of_self := coe_zeta_mul_coe_moebius} /-- A unit in `arithmetic_function R` that evaluates to `ζ`, with inverse `μ`. -/ def zeta_unit : units (arithmetic_function R) := ⟨ζ, μ, coe_zeta_mul_coe_moebius, coe_moebius_mul_coe_zeta⟩ @[simp] lemma coe_zeta_unit : ((zeta_unit : units (arithmetic_function R)) : arithmetic_function R) = ζ := rfl @[simp] lemma inv_zeta_unit : ((zeta_unit⁻¹ : units (arithmetic_function R)) : arithmetic_function R) = μ := rfl end comm_ring /-- Möbius inversion for functions to an `add_comm_group`. -/ theorem sum_eq_iff_sum_smul_moebius_eq [add_comm_group R] {f g : ℕ → R} : (∀ (n : ℕ), 0 < n → ∑ i in (n.divisors), f i = g n) ↔ ∀ (n : ℕ), 0 < n → ∑ (x : ℕ × ℕ) in n.divisors_antidiagonal, μ x.fst • g x.snd = f n := begin let f' : arithmetic_function R := ⟨λ x, if x = 0 then 0 else f x, if_pos rfl⟩, let g' : arithmetic_function R := ⟨λ x, if x = 0 then 0 else g x, if_pos rfl⟩, transitivity (ζ : arithmetic_function ℤ) • f' = g', { rw ext_iff, apply forall_congr, intro n, cases n, { simp }, rw coe_zeta_smul_apply, simp only [n.succ_ne_zero, forall_prop_of_true, succ_pos', if_false, zero_hom.coe_mk], rw sum_congr rfl (λ x hx, _), rw (if_neg (ne_of_gt (nat.pos_of_mem_divisors hx))) }, transitivity μ • g' = f', { split; intro h, { rw [← h, ← mul_smul, moebius_mul_coe_zeta, one_smul] }, { rw [← h, ← mul_smul, coe_zeta_mul_moebius, one_smul] } }, { rw ext_iff, apply forall_congr, intro n, cases n, { simp }, simp only [n.succ_ne_zero, forall_prop_of_true, succ_pos', smul_apply, if_false, zero_hom.coe_mk], rw sum_congr rfl (λ x hx, _), rw (if_neg (ne_of_gt (nat.pos_of_mem_divisors (snd_mem_divisors_of_mem_antidiagonal hx)))) }, end /-- Möbius inversion for functions to a `comm_ring`. -/ theorem sum_eq_iff_sum_mul_moebius_eq [comm_ring R] {f g : ℕ → R} : (∀ (n : ℕ), 0 < n → ∑ i in (n.divisors), f i = g n) ↔ ∀ (n : ℕ), 0 < n → ∑ (x : ℕ × ℕ) in n.divisors_antidiagonal, (μ x.fst : R) * g x.snd = f n := begin rw sum_eq_iff_sum_smul_moebius_eq, apply forall_congr, intro a, apply imp_congr (iff.refl _) (eq.congr_left (sum_congr rfl (λ x hx, _))), rw [gsmul_eq_mul], end /-- Möbius inversion for functions to a `comm_group`. -/ theorem prod_eq_iff_prod_pow_moebius_eq [comm_group R] {f g : ℕ → R} : (∀ (n : ℕ), 0 < n → ∏ i in (n.divisors), f i = g n) ↔ ∀ (n : ℕ), 0 < n → ∏ (x : ℕ × ℕ) in n.divisors_antidiagonal, g x.snd ^ (μ x.fst) = f n := @sum_eq_iff_sum_smul_moebius_eq (additive R) _ _ _ /-- Möbius inversion for functions to a `comm_group_with_zero`. -/ theorem prod_eq_iff_prod_pow_moebius_eq_of_nonzero [comm_group_with_zero R] {f g : ℕ → R} (hf : ∀ (n : ℕ), 0 < n → f n ≠ 0) (hg : ∀ (n : ℕ), 0 < n → g n ≠ 0) : (∀ (n : ℕ), 0 < n → ∏ i in (n.divisors), f i = g n) ↔ ∀ (n : ℕ), 0 < n → ∏ (x : ℕ × ℕ) in n.divisors_antidiagonal, g x.snd ^ (μ x.fst) = f n := begin refine iff.trans (iff.trans (forall_congr (λ n, _)) (@prod_eq_iff_prod_pow_moebius_eq (units R) _ (λ n, if h : 0 < n then units.mk0 (f n) (hf n h) else 1) (λ n, if h : 0 < n then units.mk0 (g n) (hg n h) else 1))) (forall_congr (λ n, _)); refine imp_congr_right (λ hn, _), { dsimp, rw [dif_pos hn, ← units.eq_iff, ← units.coe_hom_apply, monoid_hom.map_prod, units.coe_mk0, prod_congr rfl _], intros x hx, rw [dif_pos (nat.pos_of_mem_divisors hx), units.coe_hom_apply, units.coe_mk0] }, { dsimp, rw [dif_pos hn, ← units.eq_iff, ← units.coe_hom_apply, monoid_hom.map_prod, units.coe_mk0, prod_congr rfl _], intros x hx, rw [dif_pos (nat.pos_of_mem_divisors (nat.snd_mem_divisors_of_mem_antidiagonal hx)), units.coe_hom_apply, units.coe_gpow₀, units.coe_mk0] } end end special_functions end arithmetic_function end nat
a44f1481947bbed6e43c9c1c68f08fcce084e13c
57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d
/src/Init/Control/Lawful.lean
d400331b7ea03912778cfef9d9dd5a7424d1526d
[ "Apache-2.0" ]
permissive
collares/lean4
861a9269c4592bce49b71059e232ff0bfe4594cc
52a4f535d853a2c7c7eea5fee8a4fa04c682c1ee
refs/heads/master
1,691,419,031,324
1,618,678,138,000
1,618,678,138,000
358,989,750
0
0
Apache-2.0
1,618,696,333,000
1,618,696,333,000
null
UTF-8
Lean
false
false
14,439
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sebastian Ullrich, Leonardo de Moura -/ prelude import Init.SimpLemmas import Init.Control.Except import Init.Control.StateRef open Function @[simp] theorem monadLift_self [Monad m] (x : m α) : monadLift x = x := rfl class LawfulFunctor (f : Type u → Type v) [Functor f] : Prop where map_const : (Functor.mapConst : α → f β → f α) = Functor.map ∘ const β id_map (x : f α) : id <$> x = x comp_map (g : α → β) (h : β → γ) (x : f α) : (h ∘ g) <$> x = h <$> g <$> x export LawfulFunctor (map_const id_map comp_map) attribute [simp] id_map @[simp] theorem id_map' [Functor m] [LawfulFunctor m] (x : m α) : (fun a => a) <$> x = x := id_map x class LawfulApplicative (f : Type u → Type v) [Applicative f] extends LawfulFunctor f : Prop where seqLeft_eq (x : f α) (y : f β) : x <* y = const β <$> x <*> y seqRight_eq (x : f α) (y : f β) : x *> y = const α id <$> x <*> y pure_seq (g : α → β) (x : f α) : pure g <*> x = g <$> x map_pure (g : α → β) (x : α) : g <$> (pure x : f α) = pure (g x) seq_pure {α β : Type u} (g : f (α → β)) (x : α) : g <*> pure x = (fun h => h x) <$> g seq_assoc {α β γ : Type u} (x : f α) (g : f (α → β)) (h : f (β → γ)) : h <*> (g <*> x) = ((@comp α β γ) <$> h) <*> g <*> x comp_map g h x := by repeat rw [← pure_seq] simp [seq_assoc, map_pure, seq_pure] export LawfulApplicative (seqLeft_eq seqRight_eq pure_seq map_pure seq_pure seq_assoc) attribute [simp] map_pure seq_pure @[simp] theorem pure_id_seq [Applicative f] [LawfulApplicative f] (x : f α) : pure id <*> x = x := by simp [pure_seq] class LawfulMonad (m : Type u → Type v) [Monad m] extends LawfulApplicative m : Prop where bind_pure_comp (f : α → β) (x : m α) : x >>= pure ∘ f = f <$> x bind_map {α β : Type u} (f : m (α → β)) (x : m α) : f >>= (. <$> x) = f <*> x pure_bind (x : α) (f : α → m β) : pure x >>= f = f x bind_assoc (x : m α) (f : α → m β) (g : β → m γ) : x >>= f >>= g = x >>= fun x => f x >>= g map_pure g x := by rw [← bind_pure_comp, pure_bind] seq_pure g x := by rw [← bind_map]; simp [map_pure, bind_pure_comp] seq_assoc x g h := by -- TODO: support for applying `symm` at `simp` arguments let bind_pure_comp_symm {α β : Type u} (f : α → β) (x : m α) : f <$> x = x >>= pure ∘ f := by rw [bind_pure_comp] let bind_map_symm {α β : Type u} (f : m (α → (β : Type u))) (x : m α) : f <*> x = f >>= (. <$> x) := by rw [bind_map] simp[bind_pure_comp_symm, bind_map_symm, bind_assoc, pure_bind] export LawfulMonad (bind_pure_comp bind_map pure_bind bind_assoc) attribute [simp] pure_bind bind_assoc @[simp] theorem bind_pure [Monad m] [LawfulMonad m] (x : m α) : x >>= pure = x := by show x >>= pure ∘ id = x rw [bind_pure_comp, id_map] theorem map_eq_pure_bind [Monad m] [LawfulMonad m] (f : α → β) (x : m α) : f <$> x = x >>= fun a => pure (f a) := by rw [← bind_pure_comp] theorem seq_eq_bind_map {α β : Type u} [Monad m] [LawfulMonad m] (f : m (α → β)) (x : m α) : f <*> x = f >>= (. <$> x) := by rw [← bind_map] theorem bind_congr [Bind m] {x : m α} {f g : α → m β} (h : ∀ a, f a = g a) : x >>= f = x >>= g := by simp [funext h] @[simp] theorem bind_pure_unit [Monad m] [LawfulMonad m] {x : m PUnit} : (x >>= fun _ => pure ⟨⟩) = x := by have (x >>= fun _ => pure ⟨⟩) = (x >>= pure) by apply bind_congr; intro u cases u; simp rw [bind_pure] at this assumption theorem map_congr [Functor m] {x : m α} {f g : α → β} (h : ∀ a, f a = g a) : (f <$> x : m β) = g <$> x := by simp [funext h] theorem seq_eq_bind {α β : Type u} [Monad m] [LawfulMonad m] (mf : m (α → β)) (x : m α) : mf <*> x = mf >>= fun f => f <$> x := by rw [bind_map] theorem seqRight_eq_bind [Monad m] [LawfulMonad m] (x : m α) (y : m β) : x *> y = x >>= fun _ => y := by rw [seqRight_eq]; simp [map_eq_pure_bind, seq_eq_bind_map] theorem seqLeft_eq_bind [Monad m] [LawfulMonad m] (x : m α) (y : m β) : x <* y = x >>= fun a => y >>= fun _ => pure a := by rw [seqLeft_eq]; simp [map_eq_pure_bind, seq_eq_bind_map] /- Id -/ namespace Id @[simp] theorem map_eq (x : Id α) (f : α → β) : f <$> x = f x := rfl @[simp] theorem bind_eq (x : Id α) (f : α → id β) : x >>= f = f x := rfl @[simp] theorem pure_eq (a : α) : (pure a : Id α) = a := rfl instance : LawfulMonad Id := by refine' { .. } <;> intros <;> rfl end Id /- ExceptT -/ namespace ExceptT theorem ext [Monad m] {x y : ExceptT ε m α} (h : x.run = y.run) : x = y := by simp [run] at h assumption @[simp] theorem run_pure [Monad m] : run (pure x : ExceptT ε m α) = pure (Except.ok x) := rfl @[simp] theorem run_lift [Monad m] (x : m α) : run (ExceptT.lift x : ExceptT ε m α) = (Except.ok <$> x : m (Except ε α)) := rfl @[simp] theorem run_throw [Monad m] : run (throw e : ExceptT ε m β) = pure (Except.error e) := rfl @[simp] theorem run_bind_lift [Monad m] [LawfulMonad m] (x : m α) (f : α → ExceptT ε m β) : run (ExceptT.lift x >>= f : ExceptT ε m β) = x >>= fun a => run (f a) := by simp[ExceptT.run, ExceptT.lift, bind, ExceptT.bind, ExceptT.mk, ExceptT.bindCont, map_eq_pure_bind] @[simp] theorem bind_throw [Monad m] [LawfulMonad m] (f : α → ExceptT ε m β) : (throw e >>= f) = throw e := by simp [throw, throwThe, MonadExceptOf.throw, bind, ExceptT.bind, ExceptT.bindCont, ExceptT.mk] theorem run_bind [Monad m] (x : ExceptT ε m α) : run (x >>= f : ExceptT ε m β) = run x >>= fun | Except.ok x => run (f x) | Except.error e => pure (Except.error e) := rfl @[simp] theorem lift_pure [Monad m] [LawfulMonad m] (a : α) : ExceptT.lift (pure a) = (pure a : ExceptT ε m α) := by simp [ExceptT.lift, pure, ExceptT.pure] @[simp] theorem run_map [Monad m] [LawfulMonad m] (f : α → β) (x : ExceptT ε m α) : (f <$> x).run = Except.map f <$> x.run := by simp [Functor.map, ExceptT.map, map_eq_pure_bind] apply bind_congr intro a; cases a <;> simp [Except.map] protected theorem seq_eq {α β ε : Type u} [Monad m] (mf : ExceptT ε m (α → β)) (x : ExceptT ε m α) : mf <*> x = mf >>= fun f => f <$> x := rfl protected theorem bind_pure_comp [Monad m] [LawfulMonad m] (f : α → β) (x : ExceptT ε m α) : x >>= pure ∘ f = f <$> x := by intros; rfl protected theorem seqLeft_eq {α β ε : Type u} {m : Type u → Type v} [Monad m] [LawfulMonad m] (x : ExceptT ε m α) (y : ExceptT ε m β) : x <* y = const β <$> x <*> y := by show (x >>= fun a => y >>= fun _ => pure a) = (const (α := α) β <$> x) >>= fun f => f <$> y rw [← ExceptT.bind_pure_comp] apply ext simp [run_bind] apply bind_congr intro | Except.error _ => simp | Except.ok _ => simp [map_eq_pure_bind]; apply bind_congr; intro b; cases b <;> simp [comp, Except.map, const] protected theorem seqRight_eq [Monad m] [LawfulMonad m] (x : ExceptT ε m α) (y : ExceptT ε m β) : x *> y = const α id <$> x <*> y := by show (x >>= fun _ => y) = (const α id <$> x) >>= fun f => f <$> y rw [← ExceptT.bind_pure_comp] apply ext simp [run_bind] apply bind_congr intro a; cases a <;> simp instance [Monad m] [LawfulMonad m] : LawfulMonad (ExceptT ε m) where id_map := by intros; apply ext; simp map_const := by intros; rfl seqLeft_eq := ExceptT.seqLeft_eq seqRight_eq := ExceptT.seqRight_eq pure_seq := by intros; apply ext; simp [ExceptT.seq_eq, run_bind] bind_pure_comp := ExceptT.bind_pure_comp bind_map := by intros; rfl pure_bind := by intros; apply ext; simp [run_bind] bind_assoc := by intros; apply ext; simp [run_bind]; apply bind_congr; intro a; cases a <;> simp end ExceptT /- ReaderT -/ namespace ReaderT theorem ext [Monad m] {x y : ReaderT ρ m α} (h : ∀ ctx, x.run ctx = y.run ctx) : x = y := by simp [run] at h exact funext h @[simp] theorem run_pure [Monad m] (a : α) (ctx : ρ) : (pure a : ReaderT ρ m α).run ctx = pure a := rfl @[simp] theorem run_bind [Monad m] (x : ReaderT ρ m α) (f : α → ReaderT ρ m β) (ctx : ρ) : (x >>= f).run ctx = x.run ctx >>= λ a => (f a).run ctx := rfl @[simp] theorem run_map [Monad m] (f : α → β) (x : ReaderT ρ m α) (ctx : ρ) : (f <$> x).run ctx = f <$> x.run ctx := rfl @[simp] theorem run_monadLift [MonadLiftT n m] (x : n α) (ctx : ρ) : (monadLift x : ReaderT ρ m α).run ctx = (monadLift x : m α) := rfl @[simp] theorem run_monadMap [Monad m] [MonadFunctor n m] (f : {β : Type u} → n β → n β) (x : ReaderT ρ m α) (ctx : ρ) : (monadMap @f x : ReaderT ρ m α).run ctx = monadMap @f (x.run ctx) := rfl @[simp] theorem run_read [Monad m] (ctx : ρ) : (ReaderT.read : ReaderT ρ m ρ).run ctx = pure ctx := rfl @[simp] theorem run_seq {α β : Type u} [Monad m] [LawfulMonad m] (f : ReaderT ρ m (α → β)) (x : ReaderT ρ m α) (ctx : ρ) : (f <*> x).run ctx = (f.run ctx <*> x.run ctx) := by rw [seq_eq_bind (m := m)]; rfl @[simp] theorem run_seqRight [Monad m] [LawfulMonad m] (x : ReaderT ρ m α) (y : ReaderT ρ m β) (ctx : ρ) : (x *> y).run ctx = (x.run ctx *> y.run ctx) := by rw [seqRight_eq_bind (m := m)]; rfl @[simp] theorem run_seqLeft [Monad m] [LawfulMonad m] (x : ReaderT ρ m α) (y : ReaderT ρ m β) (ctx : ρ) : (x <* y).run ctx = (x.run ctx <* y.run ctx) := by rw [seqLeft_eq_bind (m := m)]; rfl instance [Monad m] [LawfulMonad m] : LawfulMonad (ReaderT ρ m) where id_map := by intros; apply ext; intros; simp map_const := by intros; rfl seqLeft_eq := by intros; apply ext; intros; simp; apply LawfulApplicative.seqLeft_eq seqRight_eq := by intros; apply ext; intros; simp; apply LawfulApplicative.seqRight_eq pure_seq := by intros; apply ext; intros; simp; apply LawfulApplicative.pure_seq bind_pure_comp := by intros; apply ext; intros; simp; apply LawfulMonad.bind_pure_comp bind_map := by intros; rfl pure_bind := by intros; apply ext; intros; simp bind_assoc := by intros; apply ext; intros; simp end ReaderT /- StateRefT -/ instance [Monad m] [LawfulMonad m] : LawfulMonad (StateRefT' ω σ m) := inferInstanceAs (LawfulMonad (ReaderT (ST.Ref ω σ) m)) /- StateT -/ namespace StateT theorem ext {x y : StateT σ m α} (h : ∀ s, x.run s = y.run s) : x = y := funext h @[simp] theorem run'_eq [Monad m] (x : StateT σ m α) (s : σ) : run' x s = (·.1) <$> run x s := rfl @[simp] theorem run_pure [Monad m] (a : α) (s : σ) : (pure a : StateT σ m α).run s = pure (a, s) := rfl @[simp] theorem run_bind [Monad m] (x : StateT σ m α) (f : α → StateT σ m β) (s : σ) : (x >>= f).run s = x.run s >>= λ p => (f p.1).run p.2 := by simp [bind, StateT.bind, run] apply bind_congr intro p; cases p; rfl @[simp] theorem run_map {α β σ : Type u} [Monad m] [LawfulMonad m] (f : α → β) (x : StateT σ m α) (s : σ) : (f <$> x).run s = (fun (p : α × σ) => (f p.1, p.2)) <$> x.run s := by simp [Functor.map, StateT.map, run, map_eq_pure_bind] apply bind_congr intro p; cases p; rfl @[simp] theorem run_get [Monad m] (s : σ) : (get : StateT σ m σ).run s = pure (s, s) := rfl @[simp] theorem run_set [Monad m] (s s' : σ) : (set s' : StateT σ m PUnit).run s = pure (⟨⟩, s') := rfl @[simp] theorem run_modify [Monad m] (f : σ → σ) (s : σ) : (modify f : StateT σ m PUnit).run s = pure (⟨⟩, f s) := rfl @[simp] theorem run_modifyGet [Monad m] (f : σ → α × σ) (s : σ) : (modifyGet f : StateT σ m α).run s = pure ((f s).1, (f s).2) := by simp [modifyGet, MonadStateOf.modifyGet, StateT.modifyGet, run]; cases f s <;> rfl @[simp] theorem run_lift {α σ : Type u} [Monad m] (x : m α) (s : σ) : (StateT.lift x : StateT σ m α).run s = x >>= fun a => pure (a, s) := rfl @[simp] theorem run_bind_lift {α σ : Type u} [Monad m] [LawfulMonad m] (x : m α) (f : α → StateT σ m β) (s : σ) : (StateT.lift x >>= f).run s = x >>= fun a => (f a).run s := by simp [StateT.lift, StateT.run, bind, StateT.bind] @[simp] theorem run_monadLift {α σ : Type u} [Monad m] [MonadLiftT n m] (x : n α) (s : σ) : (monadLift x : StateT σ m α).run s = (monadLift x : m α) >>= fun a => pure (a, s) := rfl @[simp] theorem run_monadMap [Monad m] [MonadFunctor n m] (f : {β : Type u} → n β → n β) (x : StateT σ m α) (s : σ) : (monadMap @f x : StateT σ m α).run s = monadMap @f (x.run s) := rfl @[simp] theorem run_seq {α β σ : Type u} [Monad m] [LawfulMonad m] (f : StateT σ m (α → β)) (x : StateT σ m α) (s : σ) : (f <*> x).run s = (f.run s >>= fun fs => (fun (p : α × σ) => (fs.1 p.1, p.2)) <$> x.run fs.2) := by show (f >>= fun g => g <$> x).run s = _ simp @[simp] theorem run_seqRight [Monad m] [LawfulMonad m] (x : StateT σ m α) (y : StateT σ m β) (s : σ) : (x *> y).run s = (x.run s >>= fun p => y.run p.2) := by show (x >>= fun _ => y).run s = _ simp @[simp] theorem run_seqLeft {α β σ : Type u} [Monad m] [LawfulMonad m] (x : StateT σ m α) (y : StateT σ m β) (s : σ) : (x <* y).run s = (x.run s >>= fun p => y.run p.2 >>= fun p' => pure (p.1, p'.2)) := by show (x >>= fun a => y >>= fun _ => pure a).run s = _ simp theorem seqRight_eq [Monad m] [LawfulMonad m] (x : StateT σ m α) (y : StateT σ m β) : x *> y = const α id <$> x <*> y := by apply ext; intro s simp [map_eq_pure_bind] apply bind_congr; intro p; cases p simp [Prod.ext] theorem seqLeft_eq [Monad m] [LawfulMonad m] (x : StateT σ m α) (y : StateT σ m β) : x <* y = const β <$> x <*> y := by apply ext; intro s simp [map_eq_pure_bind] instance [Monad m] [LawfulMonad m] : LawfulMonad (StateT σ m) where id_map := by intros; apply ext; intros; simp[Prod.ext] map_const := by intros; rfl seqLeft_eq := seqLeft_eq seqRight_eq := seqRight_eq pure_seq := by intros; apply ext; intros; simp bind_pure_comp := by intros; apply ext; intros; simp; apply LawfulMonad.bind_pure_comp bind_map := by intros; rfl pure_bind := by intros; apply ext; intros; simp bind_assoc := by intros; apply ext; intros; simp end StateT
703f57c73652234acf9a88fda64ade3018006e33
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/data/polynomial/hasse_deriv.lean
deb2b4d9968f5494df3cd78e628ec116ad51ff10
[ "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
8,566
lean
/- Copyright (c) 2021 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import data.nat.choose.cast import data.nat.choose.vandermonde import data.polynomial.derivative /-! # Hasse derivative of polynomials The `k`th Hasse derivative of a polynomial `∑ a_i X^i` is `∑ (i.choose k) a_i X^(i-k)`. It is a variant of the usual derivative, and satisfies `k! * (hasse_deriv k f) = derivative^[k] f`. The main benefit is that is gives an atomic way of talking about expressions such as `(derivative^[k] f).eval r / k!`, that occur in Taylor expansions, for example. ## Main declarations In the following, we write `D k` for the `k`-th Hasse derivative `hasse_deriv k`. * `polynomial.hasse_deriv`: the `k`-th Hasse derivative of a polynomial * `polynomial.hasse_deriv_zero`: the `0`th Hasse derivative is the identity * `polynomial.hasse_deriv_one`: the `1`st Hasse derivative is the usual derivative * `polynomial.factorial_smul_hasse_deriv`: the identity `k! • (D k f) = derivative^[k] f` * `polynomial.hasse_deriv_comp`: the identity `(D k).comp (D l) = (k+l).choose k • D (k+l)` * `polynomial.hasse_deriv_mul`: the "Leibniz rule" `D k (f * g) = ∑ ij in antidiagonal k, D ij.1 f * D ij.2 g` For the identity principle, see `polynomial.eq_zero_of_hasse_deriv_eq_zero` in `data/polynomial/taylor.lean`. ## Reference https://math.fontein.de/2009/08/12/the-hasse-derivative/ -/ noncomputable theory namespace polynomial open_locale nat big_operators open function nat (hiding nsmul_eq_mul) variables {R : Type*} [semiring R] (k : ℕ) (f : polynomial R) /-- The `k`th Hasse derivative of a polynomial `∑ a_i X^i` is `∑ (i.choose k) a_i X^(i-k)`. It satisfies `k! * (hasse_deriv k f) = derivative^[k] f`. -/ def hasse_deriv (k : ℕ) : polynomial R →ₗ[R] polynomial R := lsum (λ i, (monomial (i-k)) ∘ₗ distrib_mul_action.to_linear_map R R (i.choose k)) lemma hasse_deriv_apply : hasse_deriv k f = f.sum (λ i r, monomial (i - k) (↑(i.choose k) * r)) := by simpa only [← nsmul_eq_mul] lemma hasse_deriv_coeff (n : ℕ) : (hasse_deriv k f).coeff n = (n + k).choose k * f.coeff (n + k) := begin rw [hasse_deriv_apply, coeff_sum, sum_def, finset.sum_eq_single (n + k), coeff_monomial], { simp only [if_true, nat.add_sub_cancel, eq_self_iff_true], }, { intros i hi hink, rw [coeff_monomial], by_cases hik : i < k, { simp only [nat.choose_eq_zero_of_lt hik, if_t_t, nat.cast_zero, zero_mul], }, { push_neg at hik, rw if_neg, contrapose! hink, exact (nat.sub_eq_iff_eq_add hik).mp hink, } }, { intro h, simp only [not_mem_support_iff.mp h, monomial_zero_right, mul_zero, coeff_zero] } end lemma hasse_deriv_zero' : hasse_deriv 0 f = f := by simp only [hasse_deriv_apply, nat.sub_zero, nat.choose_zero_right, nat.cast_one, one_mul, sum_monomial_eq] @[simp] lemma hasse_deriv_zero : @hasse_deriv R _ 0 = linear_map.id := linear_map.ext $ hasse_deriv_zero' lemma hasse_deriv_one' : hasse_deriv 1 f = derivative f := by simp only [hasse_deriv_apply, derivative_apply, monomial_eq_C_mul_X, nat.choose_one_right, (nat.cast_commute _ _).eq] @[simp] lemma hasse_deriv_one : @hasse_deriv R _ 1 = derivative := linear_map.ext $ hasse_deriv_one' @[simp] lemma hasse_deriv_monomial (n : ℕ) (r : R) : hasse_deriv k (monomial n r) = monomial (n - k) (↑(n.choose k) * r) := begin ext i, simp only [hasse_deriv_coeff, coeff_monomial], by_cases hnik : n = i + k, { rw [if_pos hnik, if_pos, ← hnik], apply sub_eq_of_eq_add_rev, rwa add_comm }, { rw [if_neg hnik, mul_zero], by_cases hkn : k ≤ n, { rw [← nat.sub_eq_iff_eq_add hkn] at hnik, rw [if_neg hnik] }, { push_neg at hkn, rw [nat.choose_eq_zero_of_lt hkn, nat.cast_zero, zero_mul, if_t_t] } } end lemma hasse_deriv_C (r : R) (hk : 0 < k) : hasse_deriv k (C r) = 0 := by rw [← monomial_zero_left, hasse_deriv_monomial, nat.choose_eq_zero_of_lt hk, nat.cast_zero, zero_mul, monomial_zero_right] lemma hasse_deriv_apply_one (hk : 0 < k) : hasse_deriv k (1 : polynomial R) = 0 := by rw [← C_1, hasse_deriv_C k _ hk] lemma hasse_deriv_X (hk : 1 < k) : hasse_deriv k (X : polynomial R) = 0 := by rw [← monomial_one_one_eq_X, hasse_deriv_monomial, nat.choose_eq_zero_of_lt hk, nat.cast_zero, zero_mul, monomial_zero_right] lemma factorial_smul_hasse_deriv : ⇑(k! • @hasse_deriv R _ k) = ((@derivative R _)^[k]) := begin induction k with k ih, { rw [hasse_deriv_zero, factorial_zero, iterate_zero, one_smul, linear_map.id_coe], }, ext f n : 2, rw [iterate_succ_apply', ← ih], simp only [linear_map.smul_apply, coeff_smul, linear_map.map_smul_of_tower, coeff_derivative, hasse_deriv_coeff, ← @choose_symm_add _ k], simp only [nsmul_eq_mul, factorial_succ, mul_assoc, succ_eq_add_one, ← add_assoc, add_right_comm n 1 k, ← cast_succ], rw ← (cast_commute (n+1) (f.coeff (n + k + 1))).eq, simp only [← mul_assoc], norm_cast, congr' 2, apply @cast_injective ℚ, have h1 : n + 1 ≤ n + k + 1 := succ_le_succ le_self_add, have h2 : k + 1 ≤ n + k + 1 := succ_le_succ le_add_self, have H : ∀ (n : ℕ), (n! : ℚ) ≠ 0, { exact_mod_cast factorial_ne_zero }, -- why can't `field_simp` help me here? simp only [cast_mul, cast_choose ℚ, h1, h2, -one_div, -mul_eq_zero, succ_sub_succ_eq_sub, nat.add_sub_cancel, add_sub_cancel_left] with field_simps, rw [eq_div_iff_mul_eq (mul_ne_zero (H _) (H _)), eq_comm, div_mul_eq_mul_div, eq_div_iff_mul_eq (mul_ne_zero (H _) (H _))], norm_cast, simp only [factorial_succ, succ_eq_add_one], ring, end lemma hasse_deriv_comp (k l : ℕ) : (@hasse_deriv R _ k).comp (hasse_deriv l) = (k+l).choose k • hasse_deriv (k+l) := begin ext i : 2, simp only [linear_map.smul_apply, comp_app, linear_map.coe_comp, smul_monomial, hasse_deriv_apply, mul_one, monomial_eq_zero_iff, sum_monomial_index, mul_zero, nat.sub_sub, add_comm l k], rw_mod_cast nsmul_eq_mul, congr' 2, by_cases hikl : i < k + l, { rw [choose_eq_zero_of_lt hikl, mul_zero], by_cases hil : i < l, { rw [choose_eq_zero_of_lt hil, mul_zero] }, { push_neg at hil, rw [← sub_lt_iff_right hil] at hikl, rw [choose_eq_zero_of_lt hikl , zero_mul], }, }, push_neg at hikl, apply @cast_injective ℚ, have h1 : l ≤ i := nat.le_of_add_le_right hikl, have h2 : k ≤ i - l := le_sub_of_add_le_right' hikl, have h3 : k ≤ k + l := le_self_add, have H : ∀ (n : ℕ), (n! : ℚ) ≠ 0, { exact_mod_cast factorial_ne_zero }, -- why can't `field_simp` help me here? simp only [cast_mul, cast_choose ℚ, h1, h2, h3, hikl, -one_div, -mul_eq_zero, succ_sub_succ_eq_sub, nat.add_sub_cancel, add_sub_cancel_left] with field_simps, rw [eq_div_iff_mul_eq, eq_comm, div_mul_eq_mul_div, eq_div_iff_mul_eq, nat.sub_sub, add_comm l k], { ring, }, all_goals { apply_rules [mul_ne_zero, H] } end section open add_monoid_hom finset.nat lemma hasse_deriv_mul (f g : polynomial R) : hasse_deriv k (f * g) = ∑ ij in antidiagonal k, hasse_deriv ij.1 f * hasse_deriv ij.2 g := begin let D := λ k, (@hasse_deriv R _ k).to_add_monoid_hom, let Φ := @add_monoid_hom.mul (polynomial R) _, show (comp_hom (D k)).comp Φ f g = ∑ (ij : ℕ × ℕ) in antidiagonal k, ((comp_hom.comp ((comp_hom Φ) (D ij.1))).flip (D ij.2) f) g, simp only [← finset_sum_apply], congr' 2, clear f g, ext m r n s : 4, simp only [finset_sum_apply, coe_mul_left, coe_comp, flip_apply, comp_app, hasse_deriv_monomial, linear_map.to_add_monoid_hom_coe, comp_hom_apply_apply, coe_mul, monomial_mul_monomial], have aux : ∀ (x : ℕ × ℕ), x ∈ antidiagonal k → monomial (m - x.1 + (n - x.2)) (↑(m.choose x.1) * r * (↑(n.choose x.2) * s)) = monomial (m + n - k) (↑(m.choose x.1) * ↑(n.choose x.2) * (r * s)), { intros x hx, rw [finset.nat.mem_antidiagonal] at hx, subst hx, by_cases hm : m < x.1, { simp only [nat.choose_eq_zero_of_lt hm, nat.cast_zero, zero_mul, monomial_zero_right], }, by_cases hn : n < x.2, { simp only [nat.choose_eq_zero_of_lt hn, nat.cast_zero, zero_mul, mul_zero, monomial_zero_right], }, push_neg at hm hn, rw [← nat.sub_add_comm hm, ← nat.add_sub_assoc hn, nat.sub_sub, add_comm x.2 x.1, mul_assoc, ← mul_assoc r, ← (nat.cast_commute _ r).eq, mul_assoc, mul_assoc], }, conv_rhs { apply_congr, skip, rw aux _ H, }, rw_mod_cast [← linear_map.map_sum, ← finset.sum_mul, ← nat.add_choose_eq], end end end polynomial
db1a40615ecf95bb626c6fbce20a5b0383751e0b
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/data/list/min_max.lean
f38af432cc5ecd0f9d22e2cec1043f675a6d7167
[ "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
12,899
lean
/- Copyright (c) 2019 Minchao Wu. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Minchao Wu, Chris Hughes -/ import data.list.basic /-! # Minimum and maximum of lists ## Main definitions The main definitions are `argmax`, `argmin`, `minimum` and `maximum` for lists. `argmax f l` returns `some a`, where `a` of `l` that maximises `f a`. If there are `a b` such that `f a = f b`, it returns whichever of `a` or `b` comes first in the list. `argmax f []` = none` `minimum l` returns an `with_top α`, the smallest element of `l` for nonempty lists, and `⊤` for `[]` -/ namespace list variables {α : Type*} {β : Type*} [linear_order β] /-- Auxiliary definition to define `argmax` -/ def argmax₂ (f : α → β) (a : option α) (b : α) : option α := option.cases_on a (some b) (λ c, if f b ≤ f c then some c else some b) /-- `argmax f l` returns `some a`, where `a` of `l` that maximises `f a`. If there are `a b` such that `f a = f b`, it returns whichever of `a` or `b` comes first in the list. `argmax f []` = none` -/ def argmax (f : α → β) (l : list α) : option α := l.foldl (argmax₂ f) none /-- `argmin f l` returns `some a`, where `a` of `l` that minimises `f a`. If there are `a b` such that `f a = f b`, it returns whichever of `a` or `b` comes first in the list. `argmin f []` = none` -/ def argmin (f : α → β) (l : list α) := @argmax _ (order_dual β) _ f l @[simp] lemma argmax_two_self (f : α → β) (a : α) : argmax₂ f (some a) a = a := if_pos le_rfl @[simp] lemma argmax_nil (f : α → β) : argmax f [] = none := rfl @[simp] lemma argmin_nil (f : α → β) : argmin f [] = none := rfl @[simp] lemma argmax_singleton {f : α → β} {a : α} : argmax f [a] = some a := rfl @[simp] lemma argmin_singleton {f : α → β} {a : α} : argmin f [a] = a := rfl @[simp] lemma foldl_argmax₂_eq_none {f : α → β} {l : list α} {o : option α} : l.foldl (argmax₂ f) o = none ↔ l = [] ∧ o = none := list.reverse_rec_on l (by simp) $ (assume tl hd, by simp [argmax₂]; cases foldl (argmax₂ f) o tl; simp; try {split_ifs}; simp) private theorem le_of_foldl_argmax₂ {f : α → β} {l} : Π {a m : α} {o : option α}, a ∈ l → m ∈ foldl (argmax₂ f) o l → f a ≤ f m := list.reverse_rec_on l (λ _ _ _ h, absurd h $ not_mem_nil _) begin intros tl _ ih _ _ _ h ho, rw [foldl_append, foldl_cons, foldl_nil, argmax₂] at ho, cases hf : foldl (argmax₂ f) o tl, { rw [hf] at ho, rw [foldl_argmax₂_eq_none] at hf, simp [hf.1, hf.2, *] at * }, rw [hf, option.mem_def] at ho, dsimp only at ho, cases mem_append.1 h with h h, { refine le_trans (ih h hf) _, have := @le_of_lt _ _ (f val) (f m), split_ifs at ho; simp * at * }, { split_ifs at ho; simp * at * } end private theorem foldl_argmax₂_mem (f : α → β) (l) : Π (a m : α), m ∈ foldl (argmax₂ f) (some a) l → m ∈ a :: l := list.reverse_rec_on l (by simp [eq_comm]) begin assume tl hd ih a m, simp only [foldl_append, foldl_cons, foldl_nil, argmax₂], cases hf : foldl (argmax₂ f) (some a) tl, { simp {contextual := tt} }, { dsimp only, split_ifs, { -- `finish [ih _ _ hf]` closes this goal rcases ih _ _ hf with rfl | H, { simp only [mem_cons_iff, mem_append, mem_singleton, option.mem_def], tauto }, { apply λ hm, or.inr (list.mem_append.mpr $ or.inl _), exact (option.mem_some_iff.mp hm ▸ H)} }, { simp {contextual := tt} } } end theorem argmax_mem {f : α → β} : Π {l : list α} {m : α}, m ∈ argmax f l → m ∈ l | [] m := by simp | (hd::tl) m := by simpa [argmax, argmax₂] using foldl_argmax₂_mem f tl hd m theorem argmin_mem {f : α → β} : Π {l : list α} {m : α}, m ∈ argmin f l → m ∈ l := @argmax_mem _ (order_dual β) _ _ @[simp] theorem argmax_eq_none {f : α → β} {l : list α} : l.argmax f = none ↔ l = [] := by simp [argmax] @[simp] theorem argmin_eq_none {f : α → β} {l : list α} : l.argmin f = none ↔ l = [] := @argmax_eq_none _ (order_dual β) _ _ _ theorem le_argmax_of_mem {f : α → β} {a m : α} {l : list α} : a ∈ l → m ∈ argmax f l → f a ≤ f m := le_of_foldl_argmax₂ theorem argmin_le_of_mem {f : α → β} {a m : α} {l : list α} : a ∈ l → m ∈ argmin f l → f m ≤ f a:= @le_argmax_of_mem _ (order_dual β) _ _ _ _ _ theorem argmax_concat (f : α → β) (a : α) (l : list α) : argmax f (l ++ [a]) = option.cases_on (argmax f l) (some a) (λ c, if f a ≤ f c then some c else some a) := by rw [argmax, argmax]; simp [argmax₂] theorem argmin_concat (f : α → β) (a : α) (l : list α) : argmin f (l ++ [a]) = option.cases_on (argmin f l) (some a) (λ c, if f c ≤ f a then some c else some a) := @argmax_concat _ (order_dual β) _ _ _ _ theorem argmax_cons (f : α → β) (a : α) (l : list α) : argmax f (a :: l) = option.cases_on (argmax f l) (some a) (λ c, if f c ≤ f a then some a else some c) := list.reverse_rec_on l rfl $ assume hd tl ih, begin rw [← cons_append, argmax_concat, ih, argmax_concat], cases h : argmax f hd with m, { simp [h] }, { simp [h], dsimp, by_cases ham : f m ≤ f a, { rw if_pos ham, dsimp, by_cases htlm : f tl ≤ f m, { rw if_pos htlm, dsimp, rw [if_pos (le_trans htlm ham), if_pos ham] }, { rw if_neg htlm } }, { rw if_neg ham, dsimp, by_cases htlm : f tl ≤ f m, { rw if_pos htlm, dsimp, rw if_neg ham }, { rw if_neg htlm, dsimp, rw [if_neg (not_le_of_gt (lt_trans (lt_of_not_ge ham) (lt_of_not_ge htlm)))] } } } end theorem argmin_cons (f : α → β) (a : α) (l : list α) : argmin f (a :: l) = option.cases_on (argmin f l) (some a) (λ c, if f a ≤ f c then some a else some c) := @argmax_cons _ (order_dual β) _ _ _ _ theorem index_of_argmax [decidable_eq α] {f : α → β} : Π {l : list α} {m : α}, m ∈ argmax f l → ∀ {a}, a ∈ l → f m ≤ f a → l.index_of m ≤ l.index_of a | [] m _ _ _ _ := by simp | (hd::tl) m hm a ha ham := begin simp only [index_of_cons, argmax_cons, option.mem_def] at ⊢ hm, cases h : argmax f tl, { rw h at hm, simp * at * }, { rw h at hm, dsimp only at hm, cases ha with hahd hatl, { clear index_of_argmax, subst hahd, split_ifs at hm, { subst hm }, { subst hm, contradiction } }, { have := index_of_argmax h hatl, clear index_of_argmax, split_ifs at *; refl <|> exact nat.zero_le _ <|> simp [*, nat.succ_le_succ_iff, -not_le] at * } } end theorem index_of_argmin [decidable_eq α] {f : α → β} : Π {l : list α} {m : α}, m ∈ argmin f l → ∀ {a}, a ∈ l → f a ≤ f m → l.index_of m ≤ l.index_of a := @index_of_argmax _ (order_dual β) _ _ _ theorem mem_argmax_iff [decidable_eq α] {f : α → β} {m : α} {l : list α} : m ∈ argmax f l ↔ m ∈ l ∧ (∀ a ∈ l, f a ≤ f m) ∧ (∀ a ∈ l, f m ≤ f a → l.index_of m ≤ l.index_of a) := ⟨λ hm, ⟨argmax_mem hm, λ a ha, le_argmax_of_mem ha hm, λ _, index_of_argmax hm⟩, begin rintros ⟨hml, ham, hma⟩, cases harg : argmax f l with n, { simp * at * }, { have := le_antisymm (hma n (argmax_mem harg) (le_argmax_of_mem hml harg)) (index_of_argmax harg hml (ham _ (argmax_mem harg))), rw [(index_of_inj hml (argmax_mem harg)).1 this, option.mem_def] } end⟩ theorem argmax_eq_some_iff [decidable_eq α] {f : α → β} {m : α} {l : list α} : argmax f l = some m ↔ m ∈ l ∧ (∀ a ∈ l, f a ≤ f m) ∧ (∀ a ∈ l, f m ≤ f a → l.index_of m ≤ l.index_of a) := mem_argmax_iff theorem mem_argmin_iff [decidable_eq α] {f : α → β} {m : α} {l : list α} : m ∈ argmin f l ↔ m ∈ l ∧ (∀ a ∈ l, f m ≤ f a) ∧ (∀ a ∈ l, f a ≤ f m → l.index_of m ≤ l.index_of a) := @mem_argmax_iff _ (order_dual β) _ _ _ _ _ theorem argmin_eq_some_iff [decidable_eq α] {f : α → β} {m : α} {l : list α} : argmin f l = some m ↔ m ∈ l ∧ (∀ a ∈ l, f m ≤ f a) ∧ (∀ a ∈ l, f a ≤ f m → l.index_of m ≤ l.index_of a) := mem_argmin_iff variable [linear_order α] /-- `maximum l` returns an `with_bot α`, the largest element of `l` for nonempty lists, and `⊥` for `[]` -/ def maximum (l : list α) : with_bot α := argmax id l /-- `minimum l` returns an `with_top α`, the smallest element of `l` for nonempty lists, and `⊤` for `[]` -/ def minimum (l : list α) : with_top α := argmin id l @[simp] lemma maximum_nil : maximum ([] : list α) = ⊥ := rfl @[simp] lemma minimum_nil : minimum ([] : list α) = ⊤ := rfl @[simp] lemma maximum_singleton (a : α) : maximum [a] = a := rfl @[simp] lemma minimum_singleton (a : α) : minimum [a] = a := rfl theorem maximum_mem {l : list α} {m : α} : (maximum l : with_top α) = m → m ∈ l := argmax_mem theorem minimum_mem {l : list α} {m : α} : (minimum l : with_bot α) = m → m ∈ l := argmin_mem @[simp] theorem maximum_eq_none {l : list α} : l.maximum = none ↔ l = [] := argmax_eq_none @[simp] theorem minimum_eq_none {l : list α} : l.minimum = none ↔ l = [] := argmin_eq_none theorem le_maximum_of_mem {a m : α} {l : list α} : a ∈ l → (maximum l : with_bot α) = m → a ≤ m := le_argmax_of_mem theorem minimum_le_of_mem {a m : α} {l : list α} : a ∈ l → (minimum l : with_top α) = m → m ≤ a := argmin_le_of_mem theorem le_maximum_of_mem' {a : α} {l : list α} (ha : a ∈ l) : (a : with_bot α) ≤ maximum l := option.cases_on (maximum l) (λ _ h, absurd ha ((h rfl).symm ▸ not_mem_nil _)) (λ m hm _, with_bot.coe_le_coe.2 $ hm _ rfl) (λ m, @le_maximum_of_mem _ _ _ m _ ha) (@maximum_eq_none _ _ l).1 theorem le_minimum_of_mem' {a : α} {l : list α} (ha : a ∈ l) : minimum l ≤ (a : with_top α) := @le_maximum_of_mem' (order_dual α) _ _ _ ha theorem maximum_concat (a : α) (l : list α) : maximum (l ++ [a]) = max (maximum l) a := begin rw max_comm, simp only [maximum, argmax_concat, id], cases h : argmax id l, { rw [max_eq_left], refl, exact bot_le }, change (coe : α → with_bot α) with some, rw [max_comm], simp [max_def] end theorem minimum_concat (a : α) (l : list α) : minimum (l ++ [a]) = min (minimum l) a := @maximum_concat (order_dual α) _ _ _ theorem maximum_cons (a : α) (l : list α) : maximum (a :: l) = max a (maximum l) := list.reverse_rec_on l (by simp [@max_eq_left (with_bot α) _ _ _ bot_le]) (λ tl hd ih, by rw [← cons_append, maximum_concat, ih, maximum_concat, max_assoc]) theorem minimum_cons (a : α) (l : list α) : minimum (a :: l) = min a (minimum l) := @maximum_cons (order_dual α) _ _ _ theorem maximum_eq_coe_iff {m : α} {l : list α} : maximum l = m ↔ m ∈ l ∧ (∀ a ∈ l, a ≤ m) := begin unfold_coes, simp only [maximum, argmax_eq_some_iff, id], split, { simp only [true_and, forall_true_iff] {contextual := tt} }, { simp only [true_and, forall_true_iff] {contextual := tt}, intros h a hal hma, rw [le_antisymm hma (h.2 a hal)] } end theorem minimum_eq_coe_iff {m : α} {l : list α} : minimum l = m ↔ m ∈ l ∧ (∀ a ∈ l, m ≤ a) := @maximum_eq_coe_iff (order_dual α) _ _ _ section fold variables {M : Type*} [canonically_linear_ordered_add_monoid M] /-! Note: since there is no typeclass typeclass dual to `canonically_linear_ordered_add_monoid α` we cannot express these lemmas generally for `minimum`; instead we are limited to doing so on `order_dual α`. -/ lemma maximum_eq_coe_foldr_max_of_ne_nil (l : list M) (h : l ≠ []) : l.maximum = (l.foldr max ⊥ : M) := begin induction l with hd tl IH, { contradiction }, { rw [maximum_cons, foldr, with_bot.coe_max], by_cases h : tl = [], { simp [h, -with_top.coe_zero] }, { simp [IH h] } } end lemma minimum_eq_coe_foldr_min_of_ne_nil (l : list (order_dual M)) (h : l ≠ []) : l.minimum = (l.foldr min ⊤ : order_dual M) := maximum_eq_coe_foldr_max_of_ne_nil l h lemma maximum_nat_eq_coe_foldr_max_of_ne_nil (l : list ℕ) (h : l ≠ []) : l.maximum = (l.foldr max 0 : ℕ) := maximum_eq_coe_foldr_max_of_ne_nil l h lemma max_le_of_forall_le (l : list M) (n : M) (h : ∀ (x ∈ l), x ≤ n) : l.foldr max ⊥ ≤ n := begin induction l with y l IH, { simp }, { specialize IH (λ x hx, h x (mem_cons_of_mem _ hx)), have hy : y ≤ n := h y (mem_cons_self _ _), simpa [hy] using IH } end lemma le_min_of_le_forall (l : list (order_dual M)) (n : (order_dual M)) (h : ∀ (x ∈ l), n ≤ x) : n ≤ l.foldr min ⊤ := max_le_of_forall_le l n h lemma max_nat_le_of_forall_le (l : list ℕ) (n : ℕ) (h : ∀ (x ∈ l), x ≤ n) : l.foldr max 0 ≤ n := max_le_of_forall_le l n h end fold end list
7428557ac2dbecd21d3647178c164d196f60248f
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/topology/algebra/group_with_zero.lean
91620671d73a67e38a1bdade9e3dfe812ba974bf
[ "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
11,369
lean
/- Copyright (c) 2020 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov -/ import topology.algebra.monoid import algebra.group.pi import topology.homeomorph /-! # Topological group with zero In this file we define `has_continuous_inv'` to be a mixin typeclass a type with `has_inv` and `has_zero` (e.g., a `group_with_zero`) such that `λ x, x⁻¹` is continuous at all nonzero points. Any normed (semi)field has this property. Currently the only example of `has_continuous_inv'` in `mathlib` which is not a normed field is the type `nnnreal` (a.k.a. `ℝ≥0`) of nonnegative real numbers. Then we prove lemmas about continuity of `x ↦ x⁻¹` and `f / g` providing dot-style `*.inv'` and `*.div` operations on `filter.tendsto`, `continuous_at`, `continuous_within_at`, `continuous_on`, and `continuous`. As a special case, we provide `*.div_const` operations that require only `group_with_zero` and `has_continuous_mul` instances. All lemmas about `(⁻¹)` use `inv'` in their names because lemmas without `'` are used for `topological_group`s. We also use `'` in the typeclass name `has_continuous_inv'` for the sake of consistency of notation. On a `group_with_zero` with continuous multiplication, we also define left and right multiplication as homeomorphisms. -/ open_locale topological_space filter open filter function /-! ### A group with zero with continuous multiplication If `G₀` is a group with zero with continuous `(*)`, then `(/y)` is continuous for any `y`. In this section we prove lemmas that immediately follow from this fact providing `*.div_const` dot-style operations on `filter.tendsto`, `continuous_at`, `continuous_within_at`, `continuous_on`, and `continuous`. -/ variables {α β G₀ : Type*} section div_const variables [group_with_zero G₀] [topological_space G₀] [has_continuous_mul G₀] {f : α → G₀} {s : set α} {l : filter α} lemma filter.tendsto.div_const {x y : G₀} (hf : tendsto f l (𝓝 x)) : tendsto (λa, f a / y) l (𝓝 (x / y)) := by simpa only [div_eq_mul_inv] using hf.mul tendsto_const_nhds variables [topological_space α] lemma continuous_at.div_const {a : α} (hf : continuous_at f a) {y : G₀} : continuous_at (λ x, f x / y) a := by simpa only [div_eq_mul_inv] using hf.mul continuous_at_const lemma continuous_within_at.div_const {a} (hf : continuous_within_at f s a) {y : G₀} : continuous_within_at (λ x, f x / y) s a := hf.div_const lemma continuous_on.div_const (hf : continuous_on f s) {y : G₀} : continuous_on (λ x, f x / y) s := by simpa only [div_eq_mul_inv] using hf.mul continuous_on_const @[continuity] lemma continuous.div_const (hf : continuous f) {y : G₀} : continuous (λ x, f x / y) := by simpa only [div_eq_mul_inv] using hf.mul continuous_const end div_const /-- A type with `0` and `has_inv` such that `λ x, x⁻¹` is continuous at all nonzero points. Any normed (semi)field has this property. -/ class has_continuous_inv₀ (G₀ : Type*) [has_zero G₀] [has_inv G₀] [topological_space G₀] := (continuous_at_inv₀ : ∀ ⦃x : G₀⦄, x ≠ 0 → continuous_at has_inv.inv x) export has_continuous_inv₀ (continuous_at_inv₀) section inv₀ variables [has_zero G₀] [has_inv G₀] [topological_space G₀] [has_continuous_inv₀ G₀] {l : filter α} {f : α → G₀} {s : set α} {a : α} /-! ### Continuity of `λ x, x⁻¹` at a non-zero point We define `topological_group_with_zero` to be a `group_with_zero` such that the operation `x ↦ x⁻¹` is continuous at all nonzero points. In this section we prove dot-style `*.inv'` lemmas for `filter.tendsto`, `continuous_at`, `continuous_within_at`, `continuous_on`, and `continuous`. -/ lemma tendsto_inv₀ {x : G₀} (hx : x ≠ 0) : tendsto has_inv.inv (𝓝 x) (𝓝 x⁻¹) := continuous_at_inv₀ hx lemma continuous_on_inv₀ : continuous_on (has_inv.inv : G₀ → G₀) {0}ᶜ := λ x hx, (continuous_at_inv₀ hx).continuous_within_at /-- If a function converges to a nonzero value, its inverse converges to the inverse of this value. We use the name `tendsto.inv₀` as `tendsto.inv` is already used in multiplicative topological groups. -/ lemma filter.tendsto.inv₀ {a : G₀} (hf : tendsto f l (𝓝 a)) (ha : a ≠ 0) : tendsto (λ x, (f x)⁻¹) l (𝓝 a⁻¹) := (tendsto_inv₀ ha).comp hf variables [topological_space α] lemma continuous_within_at.inv₀ (hf : continuous_within_at f s a) (ha : f a ≠ 0) : continuous_within_at (λ x, (f x)⁻¹) s a := hf.inv₀ ha lemma continuous_at.inv₀ (hf : continuous_at f a) (ha : f a ≠ 0) : continuous_at (λ x, (f x)⁻¹) a := hf.inv₀ ha @[continuity] lemma continuous.inv₀ (hf : continuous f) (h0 : ∀ x, f x ≠ 0) : continuous (λ x, (f x)⁻¹) := continuous_iff_continuous_at.2 $ λ x, (hf.tendsto x).inv₀ (h0 x) lemma continuous_on.inv₀ (hf : continuous_on f s) (h0 : ∀ x ∈ s, f x ≠ 0) : continuous_on (λ x, (f x)⁻¹) s := λ x hx, (hf x hx).inv₀ (h0 x hx) end inv₀ /-! ### Continuity of division If `G₀` is a `group_with_zero` with `x ↦ x⁻¹` continuous at all nonzero points and `(*)`, then division `(/)` is continuous at any point where the denominator is continuous. -/ section div variables [group_with_zero G₀] [topological_space G₀] [has_continuous_inv₀ G₀] [has_continuous_mul G₀] {f g : α → G₀} lemma filter.tendsto.div {l : filter α} {a b : G₀} (hf : tendsto f l (𝓝 a)) (hg : tendsto g l (𝓝 b)) (hy : b ≠ 0) : tendsto (f / g) l (𝓝 (a / b)) := by simpa only [div_eq_mul_inv] using hf.mul (hg.inv₀ hy) variables [topological_space α] [topological_space β] {s : set α} {a : α} lemma continuous_within_at.div (hf : continuous_within_at f s a) (hg : continuous_within_at g s a) (h₀ : g a ≠ 0) : continuous_within_at (f / g) s a := hf.div hg h₀ lemma continuous_on.div (hf : continuous_on f s) (hg : continuous_on g s) (h₀ : ∀ x ∈ s, g x ≠ 0) : continuous_on (f / g) s := λ x hx, (hf x hx).div (hg x hx) (h₀ x hx) /-- Continuity at a point of the result of dividing two functions continuous at that point, where the denominator is nonzero. -/ lemma continuous_at.div (hf : continuous_at f a) (hg : continuous_at g a) (h₀ : g a ≠ 0) : continuous_at (f / g) a := hf.div hg h₀ @[continuity] lemma continuous.div (hf : continuous f) (hg : continuous g) (h₀ : ∀ x, g x ≠ 0) : continuous (f / g) := by simpa only [div_eq_mul_inv] using hf.mul (hg.inv₀ h₀) lemma continuous_on_div : continuous_on (λ p : G₀ × G₀, p.1 / p.2) {p | p.2 ≠ 0} := continuous_on_fst.div continuous_on_snd $ λ _, id /-- The function `f x / g x` is discontinuous when `g x = 0`. However, under appropriate conditions, `h x (f x / g x)` is still continuous. The condition is that if `g a = 0` then `h x y` must tend to `h a 0` when `x` tends to `a`, with no information about `y`. This is represented by the `⊤` filter. Note: `filter.tendsto_prod_top_iff` characterizes this convergence in uniform spaces. See also `filter.prod_top` and `filter.mem_prod_top`. -/ lemma continuous_at.comp_div_cases {f g : α → G₀} (h : α → G₀ → β) (hf : continuous_at f a) (hg : continuous_at g a) (hh : g a ≠ 0 → continuous_at ↿h (a, f a / g a)) (h2h : g a = 0 → tendsto ↿h (𝓝 a ×ᶠ ⊤) (𝓝 (h a 0))) : continuous_at (λ x, h x (f x / g x)) a := begin show continuous_at (↿h ∘ (λ x, (x, f x / g x))) a, by_cases hga : g a = 0, { rw [continuous_at], simp_rw [comp_app, hga, div_zero], exact (h2h hga).comp (continuous_at_id.prod_mk tendsto_top) }, { exact continuous_at.comp (hh hga) (continuous_at_id.prod (hf.div hg hga)) } end /-- `h x (f x / g x)` is continuous under certain conditions, even if the denominator is sometimes `0`. See docstring of `continuous_at.comp_div_cases`. -/ lemma continuous.comp_div_cases {f g : α → G₀} (h : α → G₀ → β) (hf : continuous f) (hg : continuous g) (hh : ∀ a, g a ≠ 0 → continuous_at ↿h (a, f a / g a)) (h2h : ∀ a, g a = 0 → tendsto ↿h (𝓝 a ×ᶠ ⊤) (𝓝 (h a 0))) : continuous (λ x, h x (f x / g x)) := continuous_iff_continuous_at.mpr $ λ a, hf.continuous_at.comp_div_cases _ hg.continuous_at (hh a) (h2h a) end div /-! ### Left and right multiplication as homeomorphisms -/ namespace homeomorph variables [topological_space α] [group_with_zero α] [has_continuous_mul α] /-- Left multiplication by a nonzero element in a `group_with_zero` with continuous multiplication is a homeomorphism of the underlying type. -/ protected def mul_left₀ (c : α) (hc : c ≠ 0) : α ≃ₜ α := { continuous_to_fun := continuous_mul_left _, continuous_inv_fun := continuous_mul_left _, .. equiv.mul_left₀ c hc } /-- Right multiplication by a nonzero element in a `group_with_zero` with continuous multiplication is a homeomorphism of the underlying type. -/ protected def mul_right₀ (c : α) (hc : c ≠ 0) : α ≃ₜ α := { continuous_to_fun := continuous_mul_right _, continuous_inv_fun := continuous_mul_right _, .. equiv.mul_right₀ c hc } @[simp] lemma coe_mul_left₀ (c : α) (hc : c ≠ 0) : ⇑(homeomorph.mul_left₀ c hc) = (*) c := rfl @[simp] lemma mul_left₀_symm_apply (c : α) (hc : c ≠ 0) : ((homeomorph.mul_left₀ c hc).symm : α → α) = (*) c⁻¹ := rfl @[simp] lemma coe_mul_right₀ (c : α) (hc : c ≠ 0) : ⇑(homeomorph.mul_right₀ c hc) = λ x, x * c := rfl @[simp] lemma mul_right₀_symm_apply (c : α) (hc : c ≠ 0) : ((homeomorph.mul_right₀ c hc).symm : α → α) = λ x, x * c⁻¹ := rfl end homeomorph section zpow variables [group_with_zero G₀] [topological_space G₀] [has_continuous_inv₀ G₀] [has_continuous_mul G₀] lemma continuous_at_zpow (x : G₀) (m : ℤ) (h : x ≠ 0 ∨ 0 ≤ m) : continuous_at (λ x, x ^ m) x := begin cases m, { simpa only [zpow_of_nat] using continuous_at_pow x m }, { simp only [zpow_neg_succ_of_nat], have hx : x ≠ 0, from h.resolve_right (int.neg_succ_of_nat_lt_zero m).not_le, exact (continuous_at_pow x (m + 1)).inv₀ (pow_ne_zero _ hx) } end lemma continuous_on_zpow (m : ℤ) : continuous_on (λ x : G₀, x ^ m) {0}ᶜ := λ x hx, (continuous_at_zpow _ _ (or.inl hx)).continuous_within_at lemma filter.tendsto.zpow {f : α → G₀} {l : filter α} {a : G₀} (hf : tendsto f l (𝓝 a)) (m : ℤ) (h : a ≠ 0 ∨ 0 ≤ m) : tendsto (λ x, (f x) ^ m) l (𝓝 (a ^ m)) := (continuous_at_zpow _ m h).tendsto.comp hf variables {X : Type*} [topological_space X] {a : X} {s : set X} {f : X → G₀} lemma continuous_at.zpow (hf : continuous_at f a) (m : ℤ) (h : f a ≠ 0 ∨ 0 ≤ m) : continuous_at (λ x, (f x) ^ m) a := hf.zpow m h lemma continuous_within_at.zpow (hf : continuous_within_at f s a) (m : ℤ) (h : f a ≠ 0 ∨ 0 ≤ m) : continuous_within_at (λ x, f x ^ m) s a := hf.zpow m h lemma continuous_on.zpow (hf : continuous_on f s) (m : ℤ) (h : ∀ a ∈ s, f a ≠ 0 ∨ 0 ≤ m) : continuous_on (λ x, f x ^ m) s := λ a ha, (hf a ha).zpow m (h a ha) @[continuity] lemma continuous.zpow (hf : continuous f) (m : ℤ) (h0 : ∀ a, f a ≠ 0 ∨ 0 ≤ m) : continuous (λ x, (f x) ^ m) := continuous_iff_continuous_at.2 $ λ x, (hf.tendsto x).zpow m (h0 x) end zpow
c4d8345fa8bf624ff6d8a1fd271bfb3e1d4755d4
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/buffer/parser/basic.lean
30f1b1f17d5ef2edd6791fbea540e3ed4a140d4a
[ "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
110,117
lean
/- Copyright (c) 2020 Yakov Pechersky. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yakov Pechersky -/ import data.string.basic import data.buffer.basic import data.nat.digits import data.buffer.parser /-! # Parsers > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. `parser α` is the type that describes a computation that can ingest a `char_buffer` and output, if successful, a term of type `α`. This file expands on the definitions in the core library, proving that all the core library parsers are `mono`. There are also lemmas on the composability of parsers. ## Main definitions * `parse_result.pos` : The position of a `char_buffer` at which a `parser α` has finished. * `parser.mono` : The property that a parser only moves forward within a buffer, in both cases of success or failure. ## Implementation details Lemmas about how parsers are mono are in the `mono` namespace. That allows using projection notation for shorter term proofs that are parallel to the definitions of the parsers in structure. -/ open parser parse_result /-- For some `parse_result α`, give the position at which the result was provided, in either the `done` or the `fail` case. -/ @[simp] def parse_result.pos {α} : parse_result α → ℕ | (done n _) := n | (fail n _) := n namespace parser section defn_lemmas variables {α β : Type} (msgs : thunk (list string)) (msg : thunk string) variables (p q : parser α) (cb : char_buffer) (n n' : ℕ) {err : dlist string} variables {a : α} {b : β} /-- A `p : parser α` is defined to be `mono` if the result `p cb n` it gives, for some `cb : char_buffer` and `n : ℕ`, (whether `done` or `fail`), is always at a `parse_result.pos` that is at least `n`. The `mono` property is used mainly for proper `orelse` behavior. -/ class mono : Prop := (le' : ∀ (cb : char_buffer) (n : ℕ), n ≤ (p cb n).pos) lemma mono.le [p.mono] : n ≤ (p cb n).pos := mono.le' cb n /-- A `parser α` is defined to be `static` if it does not move on success. -/ class static : Prop := (of_done : ∀ {cb : char_buffer} {n n' : ℕ} {a : α}, p cb n = done n' a → n = n') /-- A `parser α` is defined to be `err_static` if it does not move on error. -/ class err_static : Prop := (of_fail : ∀ {cb : char_buffer} {n n' : ℕ} {err : dlist string}, p cb n = fail n' err → n = n') /-- A `parser α` is defined to be `step` if it always moves exactly one char forward on success. -/ class step : Prop := (of_done : ∀ {cb : char_buffer} {n n' : ℕ} {a : α}, p cb n = done n' a → n' = n + 1) /-- A `parser α` is defined to be `prog` if it always moves forward on success. -/ class prog : Prop := (of_done : ∀ {cb : char_buffer} {n n' : ℕ} {a : α}, p cb n = done n' a → n < n') /-- A `parser a` is defined to be `bounded` if it produces a `fail` `parse_result` when it is parsing outside the provided `char_buffer`. -/ class bounded : Prop := (ex' : ∀ {cb : char_buffer} {n : ℕ}, cb.size ≤ n → ∃ (n' : ℕ) (err : dlist string), p cb n = fail n' err) lemma bounded.exists (p : parser α) [p.bounded] {cb : char_buffer} {n : ℕ} (h : cb.size ≤ n) : ∃ (n' : ℕ) (err : dlist string), p cb n = fail n' err := bounded.ex' h /-- A `parser a` is defined to be `unfailing` if it always produces a `done` `parse_result`. -/ class unfailing : Prop := (ex' : ∀ (cb : char_buffer) (n : ℕ), ∃ (n' : ℕ) (a : α), p cb n = done n' a) /-- A `parser a` is defined to be `conditionally_unfailing` if it produces a `done` `parse_result` as long as it is parsing within the provided `char_buffer`. -/ class conditionally_unfailing : Prop := (ex' : ∀ {cb : char_buffer} {n : ℕ}, n < cb.size → ∃ (n' : ℕ) (a : α), p cb n = done n' a) lemma fail_iff : (∀ pos' result, p cb n ≠ done pos' result) ↔ ∃ (pos' : ℕ) (err : dlist string), p cb n = fail pos' err := by cases p cb n; simp lemma success_iff : (∀ pos' err, p cb n ≠ fail pos' err) ↔ ∃ (pos' : ℕ) (result : α), p cb n = done pos' result := by cases p cb n; simp variables {p q cb n n' msgs msg} lemma mono.of_done [p.mono] (h : p cb n = done n' a) : n ≤ n' := by simpa [h] using mono.le p cb n lemma mono.of_fail [p.mono] (h : p cb n = fail n' err) : n ≤ n' := by simpa [h] using mono.le p cb n lemma bounded.of_done [p.bounded] (h : p cb n = done n' a) : n < cb.size := begin contrapose! h, obtain ⟨np, err, hp⟩ := bounded.exists p h, simp [hp] end lemma static.iff : static p ↔ (∀ (cb : char_buffer) (n n' : ℕ) (a : α), p cb n = done n' a → n = n') := ⟨λ h _ _ _ _ hp, by { haveI := h, exact static.of_done hp}, λ h, ⟨h⟩⟩ lemma exists_done (p : parser α) [p.unfailing] (cb : char_buffer) (n : ℕ) : ∃ (n' : ℕ) (a : α), p cb n = done n' a := unfailing.ex' cb n lemma unfailing.of_fail [p.unfailing] (h : p cb n = fail n' err) : false := begin obtain ⟨np, a, hp⟩ := p.exists_done cb n, simpa [hp] using h end @[priority 100] -- see Note [lower instance priority] instance conditionally_unfailing_of_unfailing [p.unfailing] : conditionally_unfailing p := ⟨λ _ _ _, p.exists_done _ _⟩ lemma exists_done_in_bounds (p : parser α) [p.conditionally_unfailing] {cb : char_buffer} {n : ℕ} (h : n < cb.size) : ∃ (n' : ℕ) (a : α), p cb n = done n' a := conditionally_unfailing.ex' h lemma conditionally_unfailing.of_fail [p.conditionally_unfailing] (h : p cb n = fail n' err) (hn : n < cb.size) : false := begin obtain ⟨np, a, hp⟩ := p.exists_done_in_bounds hn, simpa [hp] using h end lemma decorate_errors_fail (h : p cb n = fail n' err) : @decorate_errors α msgs p cb n = fail n ((dlist.lazy_of_list (msgs ()))) := by simp [decorate_errors, h] lemma decorate_errors_success (h : p cb n = done n' a) : @decorate_errors α msgs p cb n = done n' a := by simp [decorate_errors, h] lemma decorate_error_fail (h : p cb n = fail n' err) : @decorate_error α msg p cb n = fail n ((dlist.lazy_of_list ([msg ()]))) := decorate_errors_fail h lemma decorate_error_success (h : p cb n = done n' a) : @decorate_error α msg p cb n = done n' a := decorate_errors_success h @[simp] lemma decorate_errors_eq_done : @decorate_errors α msgs p cb n = done n' a ↔ p cb n = done n' a := by cases h : p cb n; simp [decorate_errors, h] @[simp] lemma decorate_error_eq_done : @decorate_error α msg p cb n = done n' a ↔ p cb n = done n' a := decorate_errors_eq_done @[simp] lemma decorate_errors_eq_fail : @decorate_errors α msgs p cb n = fail n' err ↔ n = n' ∧ err = dlist.lazy_of_list (msgs ()) ∧ ∃ np err', p cb n = fail np err' := by cases h : p cb n; simp [decorate_errors, h, eq_comm] @[simp] lemma decorate_error_eq_fail : @decorate_error α msg p cb n = fail n' err ↔ n = n' ∧ err = dlist.lazy_of_list ([msg ()]) ∧ ∃ np err', p cb n = fail np err' := decorate_errors_eq_fail @[simp] lemma return_eq_pure : (@return parser _ _ a) = pure a := rfl lemma pure_eq_done : (@pure parser _ _ a) = λ _ n, done n a := rfl @[simp] lemma pure_ne_fail : (pure a : parser α) cb n ≠ fail n' err := by simp [pure_eq_done] section bind variable (f : α → parser β) @[simp] lemma bind_eq_bind : p.bind f = p >>= f := rfl variable {f} @[simp] lemma bind_eq_done : (p >>= f) cb n = done n' b ↔ ∃ (np : ℕ) (a : α), p cb n = done np a ∧ f a cb np = done n' b := by cases hp : p cb n; simp [hp, ←bind_eq_bind, parser.bind, and_assoc] @[simp] lemma bind_eq_fail : (p >>= f) cb n = fail n' err ↔ (p cb n = fail n' err) ∨ (∃ (np : ℕ) (a : α), p cb n = done np a ∧ f a cb np = fail n' err) := by cases hp : p cb n; simp [hp, ←bind_eq_bind, parser.bind, and_assoc] @[simp] lemma and_then_eq_bind {α β : Type} {m : Type → Type} [monad m] (a : m α) (b : m β) : a >> b = a >>= (λ _, b) := rfl lemma and_then_fail : (p >> return ()) cb n = parse_result.fail n' err ↔ p cb n = fail n' err := by simp [pure_eq_done] lemma and_then_success : (p >> return ()) cb n = parse_result.done n' () ↔ ∃ a, p cb n = done n' a:= by simp [pure_eq_done] end bind section map variable {f : α → β} @[simp] lemma map_eq_done : (f <$> p) cb n = done n' b ↔ ∃ (a : α), p cb n = done n' a ∧ f a = b := by cases hp : p cb n; simp [←is_lawful_monad.bind_pure_comp_eq_map, hp, and_assoc, pure_eq_done] @[simp] lemma map_eq_fail : (f <$> p) cb n = fail n' err ↔ p cb n = fail n' err := by simp [←bind_pure_comp_eq_map, pure_eq_done] @[simp] lemma map_const_eq_done {b'} : (b <$ p) cb n = done n' b' ↔ ∃ (a : α), p cb n = done n' a ∧ b = b' := by simp [map_const_eq] @[simp] lemma map_const_eq_fail : (b <$ p) cb n = fail n' err ↔ p cb n = fail n' err := by simp only [map_const_eq, map_eq_fail] lemma map_const_rev_eq_done {b'} : (p $> b) cb n = done n' b' ↔ ∃ (a : α), p cb n = done n' a ∧ b = b' := map_const_eq_done lemma map_rev_const_eq_fail : (p $> b) cb n = fail n' err ↔ p cb n = fail n' err := map_const_eq_fail end map @[simp] lemma orelse_eq_orelse : p.orelse q = (p <|> q) := rfl @[simp] lemma orelse_eq_done : (p <|> q) cb n = done n' a ↔ (p cb n = done n' a ∨ (q cb n = done n' a ∧ ∃ err, p cb n = fail n err)) := begin cases hp : p cb n with np resp np errp, { simp [hp, ←orelse_eq_orelse, parser.orelse] }, { by_cases hn : np = n, { cases hq : q cb n with nq resq nq errq, { simp [hp, hn, hq, ←orelse_eq_orelse, parser.orelse] }, { rcases lt_trichotomy nq n with H|rfl|H; simp [hp, hn, hq, H, not_lt_of_lt H, lt_irrefl, ←orelse_eq_orelse, parser.orelse] <|> simp [hp, hn, hq, lt_irrefl, ←orelse_eq_orelse, parser.orelse] } }, { simp [hp, hn, ←orelse_eq_orelse, parser.orelse] } } end @[simp] lemma orelse_eq_fail_eq : (p <|> q) cb n = fail n err ↔ (p cb n = fail n err ∧ ∃ (nq errq), n < nq ∧ q cb n = fail nq errq) ∨ (∃ (errp errq), p cb n = fail n errp ∧ q cb n = fail n errq ∧ errp ++ errq = err) := begin cases hp : p cb n with np resp np errp, { simp [hp, ←orelse_eq_orelse, parser.orelse] }, { by_cases hn : np = n, { cases hq : q cb n with nq resq nq errq, { simp [hp, hn, hq, ←orelse_eq_orelse, parser.orelse] }, { rcases lt_trichotomy nq n with H|rfl|H; simp [hp, hq, hn, ←orelse_eq_orelse, parser.orelse, H, ne_of_gt H, ne_of_lt H, not_lt_of_lt H] <|> simp [hp, hq, hn, ←orelse_eq_orelse, parser.orelse, lt_irrefl] } }, { simp [hp, hn, ←orelse_eq_orelse, parser.orelse] } } end lemma orelse_eq_fail_not_mono_lt (hn : n' < n) : (p <|> q) cb n = fail n' err ↔ (p cb n = fail n' err) ∨ (q cb n = fail n' err ∧ (∃ (errp), p cb n = fail n errp)) := begin cases hp : p cb n with np resp np errp, { simp [hp, ←orelse_eq_orelse, parser.orelse] }, { by_cases h : np = n, { cases hq : q cb n with nq resq nq errq, { simp [hp, h, hn, hq, ne_of_gt hn, ←orelse_eq_orelse, parser.orelse] }, { rcases lt_trichotomy nq n with H|H|H, { simp [hp, hq, h, H, ne_of_gt hn, not_lt_of_lt H, ←orelse_eq_orelse, parser.orelse] }, { simp [hp, hq, h, H, ne_of_gt hn, lt_irrefl, ←orelse_eq_orelse, parser.orelse] }, { simp [hp, hq, h, H, ne_of_gt (hn.trans H), ←orelse_eq_orelse, parser.orelse] } } }, { simp [hp, h, ←orelse_eq_orelse, parser.orelse] } } end lemma orelse_eq_fail_of_mono_ne [q.mono] (hn : n ≠ n') : (p <|> q) cb n = fail n' err ↔ p cb n = fail n' err := begin cases hp : p cb n with np resp np errp, { simp [hp, ←orelse_eq_orelse, parser.orelse] }, { by_cases h : np = n, { cases hq : q cb n with nq resq nq errq, { simp [hp, h, hn, hq, hn, ←orelse_eq_orelse, parser.orelse] }, { have : n ≤ nq := mono.of_fail hq, rcases eq_or_lt_of_le this with rfl|H, { simp [hp, hq, h, hn, lt_irrefl, ←orelse_eq_orelse, parser.orelse] }, { simp [hp, hq, h, hn, H, ←orelse_eq_orelse, parser.orelse] } } }, { simp [hp, h, ←orelse_eq_orelse, parser.orelse] } }, end @[simp] lemma failure_eq_failure : @parser.failure α = failure := rfl @[simp] lemma failure_def : (failure : parser α) cb n = fail n dlist.empty := rfl lemma not_failure_eq_done : ¬ (failure : parser α) cb n = done n' a := by simp lemma failure_eq_fail : (failure : parser α) cb n = fail n' err ↔ n = n' ∧ err = dlist.empty := by simp [eq_comm] lemma seq_eq_done {f : parser (α → β)} {p : parser α} : (f <*> p) cb n = done n' b ↔ ∃ (nf : ℕ) (f' : α → β) (a : α), f cb n = done nf f' ∧ p cb nf = done n' a ∧ f' a = b := by simp [seq_eq_bind_map] lemma seq_eq_fail {f : parser (α → β)} {p : parser α} : (f <*> p) cb n = fail n' err ↔ (f cb n = fail n' err) ∨ (∃ (nf : ℕ) (f' : α → β), f cb n = done nf f' ∧ p cb nf = fail n' err) := by simp [seq_eq_bind_map] lemma seq_left_eq_done {p : parser α} {q : parser β} : (p <* q) cb n = done n' a ↔ ∃ (np : ℕ) (b : β), p cb n = done np a ∧ q cb np = done n' b := begin have : ∀ (p q : ℕ → α → Prop), (∃ (np : ℕ) (x : α), p np x ∧ q np x ∧ x = a) ↔ ∃ (np : ℕ), p np a ∧ q np a := λ _ _, ⟨λ ⟨np, x, hp, hq, rfl⟩, ⟨np, hp, hq⟩, λ ⟨np, hp, hq⟩, ⟨np, a, hp, hq, rfl⟩⟩, simp [seq_left_eq, seq_eq_done, map_eq_done, this] end lemma seq_left_eq_fail {p : parser α} {q : parser β} : (p <* q) cb n = fail n' err ↔ (p cb n = fail n' err) ∨ (∃ (np : ℕ) (a : α), p cb n = done np a ∧ q cb np = fail n' err) := by simp [seq_left_eq, seq_eq_fail] lemma seq_right_eq_done {p : parser α} {q : parser β} : (p *> q) cb n = done n' b ↔ ∃ (np : ℕ) (a : α), p cb n = done np a ∧ q cb np = done n' b := by simp [seq_right_eq, seq_eq_done, map_eq_done, and.comm, and.assoc] lemma seq_right_eq_fail {p : parser α} {q : parser β} : (p *> q) cb n = fail n' err ↔ (p cb n = fail n' err) ∨ (∃ (np : ℕ) (a : α), p cb n = done np a ∧ q cb np = fail n' err) := by simp [seq_right_eq, seq_eq_fail] lemma mmap_eq_done {f : α → parser β} {a : α} {l : list α} {b : β} {l' : list β} : (a :: l).mmap f cb n = done n' (b :: l') ↔ ∃ (np : ℕ), f a cb n = done np b ∧ l.mmap f cb np = done n' l' := by simp [mmap, and.comm, and.assoc, and.left_comm, pure_eq_done] lemma mmap'_eq_done {f : α → parser β} {a : α} {l : list α} : (a :: l).mmap' f cb n = done n' () ↔ ∃ (np : ℕ) (b : β), f a cb n = done np b ∧ l.mmap' f cb np = done n' () := by simp [mmap'] lemma guard_eq_done {p : Prop} [decidable p] {u : unit} : @guard parser _ p _ cb n = done n' u ↔ p ∧ n = n' := by { by_cases hp : p; simp [guard, hp, pure_eq_done] } lemma guard_eq_fail {p : Prop} [decidable p] : @guard parser _ p _ cb n = fail n' err ↔ (¬ p) ∧ n = n' ∧ err = dlist.empty := by { by_cases hp : p; simp [guard, hp, eq_comm, pure_eq_done] } namespace mono variables {sep : parser unit} instance pure : mono (pure a) := ⟨λ _ _, by simp [pure_eq_done]⟩ instance bind {f : α → parser β} [p.mono] [∀ a, (f a).mono] : (p >>= f).mono := begin constructor, intros cb n, cases hx : (p >>= f) cb n, { obtain ⟨n', a, h, h'⟩ := bind_eq_done.mp hx, refine le_trans (of_done h) _, simpa [h'] using of_done h' }, { obtain h | ⟨n', a, h, h'⟩ := bind_eq_fail.mp hx, { simpa [h] using of_fail h }, { refine le_trans (of_done h) _, simpa [h'] using of_fail h' } } end instance and_then {q : parser β} [p.mono] [q.mono] : (p >> q).mono := mono.bind instance map [p.mono] {f : α → β} : (f <$> p).mono := mono.bind instance seq {f : parser (α → β)} [f.mono] [p.mono] : (f <*> p).mono := mono.bind instance mmap : Π {l : list α} {f : α → parser β} [∀ a ∈ l, (f a).mono], (l.mmap f).mono | [] _ _ := mono.pure | (a :: l) f h := begin convert mono.bind, { exact h _ (list.mem_cons_self _ _) }, { intro, convert mono.map, convert mmap, exact (λ _ ha, h _ (list.mem_cons_of_mem _ ha)) } end instance mmap' : Π {l : list α} {f : α → parser β} [∀ a ∈ l, (f a).mono], (l.mmap' f).mono | [] _ _ := mono.pure | (a :: l) f h := begin convert mono.and_then, { exact h _ (list.mem_cons_self _ _) }, { convert mmap', exact (λ _ ha, h _ (list.mem_cons_of_mem _ ha)) } end instance failure : (failure : parser α).mono := ⟨by simp [le_refl]⟩ instance guard {p : Prop} [decidable p] : mono (guard p) := ⟨by { by_cases h : p; simp [h, pure_eq_done, le_refl] }⟩ instance orelse [p.mono] [q.mono] : (p <|> q).mono := begin constructor, intros cb n, cases hx : (p <|> q) cb n with posx resx posx errx, { obtain h | ⟨h, -, -⟩ := orelse_eq_done.mp hx; simpa [h] using of_done h }, { by_cases h : n = posx, { simp [hx, h] }, { simp only [orelse_eq_fail_of_mono_ne h] at hx, exact of_fail hx } } end instance decorate_errors [p.mono] : (@decorate_errors α msgs p).mono := begin constructor, intros cb n, cases h : p cb n, { simpa [decorate_errors, h] using of_done h }, { simp [decorate_errors, h] } end instance decorate_error [p.mono] : (@decorate_error α msg p).mono := mono.decorate_errors instance any_char : mono any_char := begin constructor, intros cb n, by_cases h : n < cb.size; simp [any_char, h], end instance sat {p : char → Prop} [decidable_pred p] : mono (sat p) := begin constructor, intros cb n, simp only [sat], split_ifs; simp end instance eps : mono eps := mono.pure instance ch {c : char} : mono (ch c) := mono.decorate_error instance char_buf {s : char_buffer} : mono (char_buf s) := mono.decorate_error instance one_of {cs : list char} : (one_of cs).mono := mono.decorate_errors instance one_of' {cs : list char} : (one_of' cs).mono := mono.and_then instance str {s : string} : (str s).mono := mono.decorate_error instance remaining : remaining.mono := ⟨λ _ _, le_rfl⟩ instance eof : eof.mono := mono.decorate_error instance foldr_core {f : α → β → β} {b : β} [p.mono] : ∀ {reps : ℕ}, (foldr_core f p b reps).mono | 0 := mono.failure | (reps + 1) := begin convert mono.orelse, { convert mono.bind, { apply_instance }, { exact λ _, @mono.bind _ _ _ _ foldr_core _ } }, { exact mono.pure } end instance foldr {f : α → β → β} [p.mono] : mono (foldr f p b) := ⟨λ _ _, by { convert mono.le (foldr_core f p b _) _ _, exact mono.foldr_core }⟩ instance foldl_core {f : α → β → α} {p : parser β} [p.mono] : ∀ {a : α} {reps : ℕ}, (foldl_core f a p reps).mono | _ 0 := mono.failure | _ (reps + 1) := begin convert mono.orelse, { convert mono.bind, { apply_instance }, { exact λ _, foldl_core } }, { exact mono.pure } end instance foldl {f : α → β → α} {p : parser β} [p.mono] : mono (foldl f a p) := ⟨λ _ _, by { convert mono.le (foldl_core f a p _) _ _, exact mono.foldl_core }⟩ instance many [p.mono] : p.many.mono := mono.foldr instance many_char {p : parser char} [p.mono] : p.many_char.mono := mono.map instance many' [p.mono] : p.many'.mono := mono.and_then instance many1 [p.mono] : p.many1.mono := mono.seq instance many_char1 {p : parser char} [p.mono] : p.many_char1.mono := mono.map instance sep_by1 [p.mono] [sep.mono] : mono (sep_by1 sep p) := mono.seq instance sep_by [p.mono] [hs : sep.mono] : mono (sep_by sep p) := mono.orelse lemma fix_core {F : parser α → parser α} (hF : ∀ (p : parser α), p.mono → (F p).mono) : ∀ (max_depth : ℕ), mono (fix_core F max_depth) | 0 := mono.failure | (max_depth + 1) := hF _ (fix_core _) instance digit : digit.mono := mono.decorate_error instance nat : nat.mono := mono.decorate_error lemma fix {F : parser α → parser α} (hF : ∀ (p : parser α), p.mono → (F p).mono) : mono (fix F) := ⟨λ _ _, by { convert mono.le (parser.fix_core F _) _ _, exact fix_core hF _ }⟩ end mono @[simp] lemma orelse_pure_eq_fail : (p <|> pure a) cb n = fail n' err ↔ p cb n = fail n' err ∧ n ≠ n' := begin by_cases hn : n = n', { simp [hn, pure_eq_done] }, { simp [orelse_eq_fail_of_mono_ne, hn] } end end defn_lemmas section done variables {α β : Type} {cb : char_buffer} {n n' : ℕ} {a a' : α} {b : β} {c : char} {u : unit} {err : dlist string} lemma any_char_eq_done : any_char cb n = done n' c ↔ ∃ (hn : n < cb.size), n' = n + 1 ∧ cb.read ⟨n, hn⟩ = c := begin simp_rw [any_char], split_ifs with h; simp [h, eq_comm] end lemma any_char_eq_fail : any_char cb n = fail n' err ↔ n = n' ∧ err = dlist.empty ∧ cb.size ≤ n := begin simp_rw [any_char], split_ifs with h; simp [←not_lt, h, eq_comm] end lemma sat_eq_done {p : char → Prop} [decidable_pred p] : sat p cb n = done n' c ↔ ∃ (hn : n < cb.size), p c ∧ n' = n + 1 ∧ cb.read ⟨n, hn⟩ = c := begin by_cases hn : n < cb.size, { by_cases hp : p (cb.read ⟨n, hn⟩), { simp only [sat, hn, hp, dif_pos, if_true, exists_prop_of_true], split, { rintro ⟨rfl, rfl⟩, simp [hp] }, { rintro ⟨-, rfl, rfl⟩, simp } }, { simp only [sat, hn, hp, dif_pos, false_iff, not_and, exists_prop_of_true, if_false], rintro H - rfl, exact hp H } }, { simp [sat, hn] } end lemma sat_eq_fail {p : char → Prop} [decidable_pred p] : sat p cb n = fail n' err ↔ n = n' ∧ err = dlist.empty ∧ ∀ (h : n < cb.size), ¬ p (cb.read ⟨n, h⟩) := begin dsimp only [sat], split_ifs; simp [*, eq_comm] end lemma eps_eq_done : eps cb n = done n' u ↔ n = n' := by simp [eps, pure_eq_done] lemma ch_eq_done : ch c cb n = done n' u ↔ ∃ (hn : n < cb.size), n' = n + 1 ∧ cb.read ⟨n, hn⟩ = c := by simp [ch, eps_eq_done, sat_eq_done, and.comm, @eq_comm _ n'] lemma char_buf_eq_done {cb' : char_buffer} : char_buf cb' cb n = done n' u ↔ n + cb'.size = n' ∧ cb'.to_list <+: (cb.to_list.drop n) := begin simp only [char_buf, decorate_error_eq_done, ne.def, ←buffer.length_to_list], induction cb'.to_list with hd tl hl generalizing cb n n', { simp [pure_eq_done, mmap'_eq_done, -buffer.length_to_list, list.nil_prefix] }, { simp only [ch_eq_done, and.comm, and.assoc, and.left_comm, hl, mmap', and_then_eq_bind, bind_eq_done, list.length, exists_and_distrib_left, exists_const], split, { rintro ⟨np, h, rfl, rfl, hn, rfl⟩, simp only [add_comm, add_left_comm, h, true_and, eq_self_iff_true, and_true], have : n < cb.to_list.length := by simpa using hn, rwa [←buffer.nth_le_to_list _ this, ←list.cons_nth_le_drop_succ this, list.prefix_cons_inj] }, { rintro ⟨h, rfl⟩, by_cases hn : n < cb.size, { have : n < cb.to_list.length := by simpa using hn, rw [←list.cons_nth_le_drop_succ this, list.cons_prefix_iff] at h, use [n + 1, h.right], simpa [buffer.nth_le_to_list, add_comm, add_left_comm, add_assoc, hn] using h.left.symm }, { have : cb.to_list.length ≤ n := by simpa using hn, rw list.drop_eq_nil_of_le this at h, simpa using h } } } end lemma one_of_eq_done {cs : list char} : one_of cs cb n = done n' c ↔ ∃ (hn : n < cb.size), c ∈ cs ∧ n' = n + 1 ∧ cb.read ⟨n, hn⟩ = c := by simp [one_of, sat_eq_done] lemma one_of'_eq_done {cs : list char} : one_of' cs cb n = done n' u ↔ ∃ (hn : n < cb.size), cb.read ⟨n, hn⟩ ∈ cs ∧ n' = n + 1 := begin simp only [one_of', one_of_eq_done, eps_eq_done, and.comm, and_then_eq_bind, bind_eq_done, exists_eq_left, exists_and_distrib_left], split, { rintro ⟨c, hc, rfl, hn, rfl⟩, exact ⟨rfl, hn, hc⟩ }, { rintro ⟨rfl, hn, hc⟩, exact ⟨cb.read ⟨n, hn⟩, hc, rfl, hn, rfl⟩ } end lemma str_eq_char_buf (s : string) : str s = char_buf s.to_list.to_buffer := begin ext cb n, rw [str, char_buf], congr, { simp [buffer.to_string, string.as_string_inv_to_list] }, { simp } end lemma str_eq_done {s : string} : str s cb n = done n' u ↔ n + s.length = n' ∧ s.to_list <+: (cb.to_list.drop n) := by simp [str_eq_char_buf, char_buf_eq_done] lemma remaining_eq_done {r : ℕ} : remaining cb n = done n' r ↔ n = n' ∧ cb.size - n = r := by simp [remaining] lemma remaining_ne_fail : remaining cb n ≠ fail n' err := by simp [remaining] lemma eof_eq_done {u : unit} : eof cb n = done n' u ↔ n = n' ∧ cb.size ≤ n := by simp [eof, guard_eq_done, remaining_eq_done, tsub_eq_zero_iff_le, and_comm, and_assoc] @[simp] lemma foldr_core_zero_eq_done {f : α → β → β} {p : parser α} {b' : β} : foldr_core f p b 0 cb n ≠ done n' b' := by simp [foldr_core] lemma foldr_core_eq_done {f : α → β → β} {p : parser α} {reps : ℕ} {b' : β} : foldr_core f p b (reps + 1) cb n = done n' b' ↔ (∃ (np : ℕ) (a : α) (xs : β), p cb n = done np a ∧ foldr_core f p b reps cb np = done n' xs ∧ f a xs = b') ∨ (n = n' ∧ b = b' ∧ ∃ (err), (p cb n = fail n err) ∨ (∃ (np : ℕ) (a : α), p cb n = done np a ∧ foldr_core f p b reps cb np = fail n err)) := by simp [foldr_core, and.comm, and.assoc, pure_eq_done] @[simp] lemma foldr_core_zero_eq_fail {f : α → β → β} {p : parser α} {err : dlist string} : foldr_core f p b 0 cb n = fail n' err ↔ n = n' ∧ err = dlist.empty := by simp [foldr_core, eq_comm] lemma foldr_core_succ_eq_fail {f : α → β → β} {p : parser α} {reps : ℕ} {err : dlist string} : foldr_core f p b (reps + 1) cb n = fail n' err ↔ n ≠ n' ∧ (p cb n = fail n' err ∨ ∃ (np : ℕ) (a : α), p cb n = done np a ∧ foldr_core f p b reps cb np = fail n' err) := by simp [foldr_core, and_comm] lemma foldr_eq_done {f : α → β → β} {p : parser α} {b' : β} : foldr f p b cb n = done n' b' ↔ ((∃ (np : ℕ) (a : α) (x : β), p cb n = done np a ∧ foldr_core f p b (cb.size - n) cb np = done n' x ∧ f a x = b') ∨ (n = n' ∧ b = b' ∧ (∃ (err), p cb n = parse_result.fail n err ∨ ∃ (np : ℕ) (x : α), p cb n = done np x ∧ foldr_core f p b (cb.size - n) cb np = fail n err))) := by simp [foldr, foldr_core_eq_done] lemma foldr_eq_fail_iff_mono_at_end {f : α → β → β} {p : parser α} {err : dlist string} [p.mono] (hc : cb.size ≤ n) : foldr f p b cb n = fail n' err ↔ n < n' ∧ (p cb n = fail n' err ∨ ∃ (a : α), p cb n = done n' a ∧ err = dlist.empty) := begin have : cb.size - n = 0 := tsub_eq_zero_iff_le.mpr hc, simp only [foldr, foldr_core_succ_eq_fail, this, and.left_comm, foldr_core_zero_eq_fail, ne_iff_lt_iff_le, exists_and_distrib_right, exists_eq_left, and.congr_left_iff, exists_and_distrib_left], rintro (h | ⟨⟨a, h⟩, rfl⟩), { exact mono.of_fail h }, { exact mono.of_done h } end lemma foldr_eq_fail {f : α → β → β} {p : parser α} {err : dlist string} : foldr f p b cb n = fail n' err ↔ n ≠ n' ∧ (p cb n = fail n' err ∨ ∃ (np : ℕ) (a : α), p cb n = done np a ∧ foldr_core f p b (cb.size - n) cb np = fail n' err) := by simp [foldr, foldr_core_succ_eq_fail] @[simp] lemma foldl_core_zero_eq_done {f : β → α → β} {p : parser α} {b' : β} : foldl_core f b p 0 cb n = done n' b' ↔ false := by simp [foldl_core] lemma foldl_core_eq_done {f : β → α → β} {p : parser α} {reps : ℕ} {b' : β} : foldl_core f b p (reps + 1) cb n = done n' b' ↔ (∃ (np : ℕ) (a : α), p cb n = done np a ∧ foldl_core f (f b a) p reps cb np = done n' b') ∨ (n = n' ∧ b = b' ∧ ∃ (err), (p cb n = fail n err) ∨ (∃ (np : ℕ) (a : α), p cb n = done np a ∧ foldl_core f (f b a) p reps cb np = fail n err)) := by simp [foldl_core, and.assoc, pure_eq_done] @[simp] lemma foldl_core_zero_eq_fail {f : β → α → β} {p : parser α} {err : dlist string} : foldl_core f b p 0 cb n = fail n' err ↔ n = n' ∧ err = dlist.empty := by simp [foldl_core, eq_comm] lemma foldl_core_succ_eq_fail {f : β → α → β} {p : parser α} {reps : ℕ} {err : dlist string} : foldl_core f b p (reps + 1) cb n = fail n' err ↔ n ≠ n' ∧ (p cb n = fail n' err ∨ ∃ (np : ℕ) (a : α), p cb n = done np a ∧ foldl_core f (f b a) p reps cb np = fail n' err) := by simp [foldl_core, and_comm] lemma foldl_eq_done {f : β → α → β} {p : parser α} {b' : β} : foldl f b p cb n = done n' b' ↔ (∃ (np : ℕ) (a : α), p cb n = done np a ∧ foldl_core f (f b a) p (cb.size - n) cb np = done n' b') ∨ (n = n' ∧ b = b' ∧ ∃ (err), (p cb n = fail n err) ∨ (∃ (np : ℕ) (a : α), p cb n = done np a ∧ foldl_core f (f b a) p (cb.size - n) cb np = fail n err)) := by simp [foldl, foldl_core_eq_done] lemma foldl_eq_fail {f : β → α → β} {p : parser α} {err : dlist string} : foldl f b p cb n = fail n' err ↔ n ≠ n' ∧ (p cb n = fail n' err ∨ ∃ (np : ℕ) (a : α), p cb n = done np a ∧ foldl_core f (f b a) p (cb.size - n) cb np = fail n' err) := by simp [foldl, foldl_core_succ_eq_fail] lemma foldl_eq_fail_iff_mono_at_end {f : β → α → β} {p : parser α} {err : dlist string} [p.mono] (hc : cb.size ≤ n) : foldl f b p cb n = fail n' err ↔ n < n' ∧ (p cb n = fail n' err ∨ ∃ (a : α), p cb n = done n' a ∧ err = dlist.empty) := begin have : cb.size - n = 0 := tsub_eq_zero_iff_le.mpr hc, simp only [foldl, foldl_core_succ_eq_fail, this, and.left_comm, ne_iff_lt_iff_le, exists_eq_left, exists_and_distrib_right, and.congr_left_iff, exists_and_distrib_left, foldl_core_zero_eq_fail], rintro (h | ⟨⟨a, h⟩, rfl⟩), { exact mono.of_fail h }, { exact mono.of_done h } end lemma many_eq_done_nil {p : parser α} : many p cb n = done n' (@list.nil α) ↔ n = n' ∧ ∃ (err), p cb n = fail n err ∨ ∃ (np : ℕ) (a : α), p cb n = done np a ∧ foldr_core list.cons p [] (cb.size - n) cb np = fail n err := by simp [many, foldr_eq_done] lemma many_eq_done {p : parser α} {x : α} {xs : list α} : many p cb n = done n' (x :: xs) ↔ ∃ (np : ℕ), p cb n = done np x ∧ foldr_core list.cons p [] (cb.size - n) cb np = done n' xs := by simp [many, foldr_eq_done, and.comm, and.assoc, and.left_comm] lemma many_eq_fail {p : parser α} {err : dlist string} : many p cb n = fail n' err ↔ n ≠ n' ∧ (p cb n = fail n' err ∨ ∃ (np : ℕ) (a : α), p cb n = done np a ∧ foldr_core list.cons p [] (cb.size - n) cb np = fail n' err) := by simp [many, foldr_eq_fail] lemma many_char_eq_done_empty {p : parser char} : many_char p cb n = done n' string.empty ↔ n = n' ∧ ∃ (err), p cb n = fail n err ∨ ∃ (np : ℕ) (c : char), p cb n = done np c ∧ foldr_core list.cons p [] (cb.size - n) cb np = fail n err := by simp [many_char, many_eq_done_nil, map_eq_done, list.as_string_eq] lemma many_char_eq_done_not_empty {p : parser char} {s : string} (h : s ≠ "") : many_char p cb n = done n' s ↔ ∃ (np : ℕ), p cb n = done np s.head ∧ foldr_core list.cons p list.nil (buffer.size cb - n) cb np = done n' (s.popn 1).to_list := by simp [many_char, list.as_string_eq, string.to_list_nonempty h, many_eq_done] lemma many_char_eq_many_of_to_list {p : parser char} {s : string} : many_char p cb n = done n' s ↔ many p cb n = done n' s.to_list := by simp [many_char, list.as_string_eq] lemma many'_eq_done {p : parser α} : many' p cb n = done n' u ↔ many p cb n = done n' [] ∨ ∃ (np : ℕ) (a : α) (l : list α), many p cb n = done n' (a :: l) ∧ p cb n = done np a ∧ foldr_core list.cons p [] (buffer.size cb - n) cb np = done n' l := begin simp only [many', eps_eq_done, many, foldr, and_then_eq_bind, exists_and_distrib_right, bind_eq_done, exists_eq_right], split, { rintro ⟨_ | ⟨hd, tl⟩, hl⟩, { exact or.inl hl }, { have hl2 := hl, simp only [foldr_core_eq_done, or_false, exists_and_distrib_left, and_false, false_and, exists_eq_right_right] at hl, obtain ⟨np, hp, h⟩ := hl, refine or.inr ⟨np, _, _, hl2, hp, h⟩ } }, { rintro (h | ⟨np, a, l, hp, h⟩), { exact ⟨[], h⟩ }, { refine ⟨a :: l, hp⟩ } } end @[simp] lemma many1_ne_done_nil {p : parser α} : many1 p cb n ≠ done n' [] := by simp [many1, seq_eq_done] lemma many1_eq_done {p : parser α} {l : list α} : many1 p cb n = done n' (a :: l) ↔ ∃ (np : ℕ), p cb n = done np a ∧ many p cb np = done n' l := by simp [many1, seq_eq_done, map_eq_done] lemma many1_eq_fail {p : parser α} {err : dlist string} : many1 p cb n = fail n' err ↔ p cb n = fail n' err ∨ (∃ (np : ℕ) (a : α), p cb n = done np a ∧ many p cb np = fail n' err) := by simp [many1, seq_eq_fail] @[simp] lemma many_char1_ne_empty {p : parser char} : many_char1 p cb n ≠ done n' "" := by simp [many_char1, ←string.nil_as_string_eq_empty] lemma many_char1_eq_done {p : parser char} {s : string} (h : s ≠ "") : many_char1 p cb n = done n' s ↔ ∃ (np : ℕ), p cb n = done np s.head ∧ many_char p cb np = done n' (s.popn 1) := by simp [many_char1, list.as_string_eq, string.to_list_nonempty h, many1_eq_done, many_char_eq_many_of_to_list] @[simp] lemma sep_by1_ne_done_nil {sep : parser unit} {p : parser α} : sep_by1 sep p cb n ≠ done n' [] := by simp [sep_by1, seq_eq_done] lemma sep_by1_eq_done {sep : parser unit} {p : parser α} {l : list α} : sep_by1 sep p cb n = done n' (a :: l) ↔ ∃ (np : ℕ), p cb n = done np a ∧ (sep >> p).many cb np = done n' l := by simp [sep_by1, seq_eq_done] lemma sep_by_eq_done_nil {sep : parser unit} {p : parser α} : sep_by sep p cb n = done n' [] ↔ n = n' ∧ ∃ (err), sep_by1 sep p cb n = fail n err := by simp [sep_by, pure_eq_done] @[simp] lemma fix_core_ne_done_zero {F : parser α → parser α} : fix_core F 0 cb n ≠ done n' a := by simp [fix_core] lemma fix_core_eq_done {F : parser α → parser α} {max_depth : ℕ} : fix_core F (max_depth + 1) cb n = done n' a ↔ F (fix_core F max_depth) cb n = done n' a := by simp [fix_core] lemma digit_eq_done {k : ℕ} : digit cb n = done n' k ↔ ∃ (hn : n < cb.size), n' = n + 1 ∧ k ≤ 9 ∧ (cb.read ⟨n, hn⟩).to_nat - '0'.to_nat = k ∧ '0' ≤ cb.read ⟨n, hn⟩ ∧ cb.read ⟨n, hn⟩ ≤ '9' := begin have c9 : '9'.to_nat - '0'.to_nat = 9 := rfl, have l09 : '0'.to_nat ≤ '9'.to_nat := dec_trivial, have le_iff_le : ∀ {c c' : char}, c ≤ c' ↔ c.to_nat ≤ c'.to_nat := λ _ _, iff.rfl, split, { simp only [digit, sat_eq_done, pure_eq_done, decorate_error_eq_done, bind_eq_done, ←c9], rintro ⟨np, c, ⟨hn, ⟨ge0, le9⟩, rfl, rfl⟩, rfl, rfl⟩, simpa [hn, ge0, le9, true_and, and_true, eq_self_iff_true, exists_prop_of_true, tsub_le_tsub_iff_right, l09] using (le_iff_le.mp le9) }, { simp only [digit, sat_eq_done, pure_eq_done, decorate_error_eq_done, bind_eq_done, ←c9, le_iff_le], rintro ⟨hn, rfl, -, rfl, ge0, le9⟩, use [n + 1, cb.read ⟨n, hn⟩], simp [hn, ge0, le9] } end lemma digit_eq_fail : digit cb n = fail n' err ↔ n = n' ∧ err = dlist.of_list ["<digit>"] ∧ ∀ (h : n < cb.size), ¬ ((λ c, '0' ≤ c ∧ c ≤ '9') (cb.read ⟨n, h⟩)) := by simp [digit, sat_eq_fail] end done namespace static variables {α β : Type} {p q : parser α} {msgs : thunk (list string)} {msg : thunk string} {cb : char_buffer} {n' n : ℕ} {err : dlist string} {a : α} {b : β} {sep : parser unit} lemma not_of_ne (h : p cb n = done n' a) (hne : n ≠ n') : ¬ static p := by { introI, exact hne (of_done h) } instance pure : static (pure a) := ⟨λ _ _ _ _, by { simp_rw pure_eq_done, rw [and.comm], simp }⟩ instance bind {f : α → parser β} [p.static] [∀ a, (f a).static] : (p >>= f).static := ⟨λ _ _ _ _, by { rw bind_eq_done, rintro ⟨_, _, hp, hf⟩, exact trans (of_done hp) (of_done hf) }⟩ instance and_then {q : parser β} [p.static] [q.static] : (p >> q).static := static.bind instance map [p.static] {f : α → β} : (f <$> p).static := ⟨λ _ _ _ _, by { simp_rw map_eq_done, rintro ⟨_, hp, _⟩, exact of_done hp }⟩ instance seq {f : parser (α → β)} [f.static] [p.static] : (f <*> p).static := static.bind instance mmap : Π {l : list α} {f : α → parser β} [∀ a, (f a).static], (l.mmap f).static | [] _ _ := static.pure | (a :: l) _ h := begin convert static.bind, { exact h _ }, { intro, convert static.bind, { convert mmap, exact h }, { exact λ _, static.pure } } end instance mmap' : Π {l : list α} {f : α → parser β} [∀ a, (f a).static], (l.mmap' f).static | [] _ _ := static.pure | (a :: l) _ h := begin convert static.and_then, { exact h _ }, { convert mmap', exact h } end instance failure : @parser.static α failure := ⟨λ _ _ _ _, by simp⟩ instance guard {p : Prop} [decidable p] : static (guard p) := ⟨λ _ _ _ _, by simp [guard_eq_done]⟩ instance orelse [p.static] [q.static] : (p <|> q).static := ⟨λ _ _ _ _, by { simp_rw orelse_eq_done, rintro (h | ⟨h, -⟩); exact of_done h }⟩ instance decorate_errors [p.static] : (@decorate_errors α msgs p).static := ⟨λ _ _ _ _, by { rw decorate_errors_eq_done, exact of_done }⟩ instance decorate_error [p.static] : (@decorate_error α msg p).static := static.decorate_errors lemma any_char : ¬ static any_char := begin have : any_char "s".to_char_buffer 0 = done 1 's', { have : 0 < "s".to_char_buffer.size := dec_trivial, simpa [any_char_eq_done, this] }, exact not_of_ne this zero_ne_one end lemma sat_iff {p : char → Prop} [decidable_pred p] : static (sat p) ↔ ∀ c, ¬ p c := begin split, { introI, intros c hc, have : sat p [c].to_buffer 0 = done 1 c := by simp [sat_eq_done, hc], exact zero_ne_one (of_done this) }, { contrapose!, simp only [iff, sat_eq_done, and_imp, exists_prop, exists_and_distrib_right, exists_and_distrib_left, exists_imp_distrib, not_forall], rintros _ _ _ a h hne rfl hp -, exact ⟨a, hp⟩ } end instance sat : static (sat (λ _, false)) := by { apply sat_iff.mpr, simp } instance eps : static eps := static.pure lemma ch (c : char) : ¬ static (ch c) := begin have : ch c [c].to_buffer 0 = done 1 (), { have : 0 < [c].to_buffer.size := dec_trivial, simp [ch_eq_done, this] }, exact not_of_ne this zero_ne_one end lemma char_buf_iff {cb' : char_buffer} : static (char_buf cb') ↔ cb' = buffer.nil := begin rw ←buffer.size_eq_zero_iff, have : char_buf cb' cb' 0 = done cb'.size () := by simp [char_buf_eq_done], cases hc : cb'.size with n, { simp only [eq_self_iff_true, iff_true], exact ⟨λ _ _ _ _ h, by simpa [hc] using (char_buf_eq_done.mp h).left⟩ }, { rw hc at this, simpa [nat.succ_ne_zero] using not_of_ne this (nat.succ_ne_zero n).symm } end lemma one_of_iff {cs : list char} : static (one_of cs) ↔ cs = [] := begin cases cs with hd tl, { simp [one_of, static.decorate_errors] }, { have : one_of (hd :: tl) (hd :: tl).to_buffer 0 = done 1 hd, { simp [one_of_eq_done] }, simpa using not_of_ne this zero_ne_one } end instance one_of : static (one_of []) := by { apply one_of_iff.mpr, refl } lemma one_of'_iff {cs : list char} : static (one_of' cs) ↔ cs = [] := begin cases cs with hd tl, { simp [one_of', static.bind], }, { have : one_of' (hd :: tl) (hd :: tl).to_buffer 0 = done 1 (), { simp [one_of'_eq_done] }, simpa using not_of_ne this zero_ne_one } end instance one_of' : static (one_of []) := by { apply one_of_iff.mpr, refl } lemma str_iff {s : string} : static (str s) ↔ s = "" := by simp [str_eq_char_buf, char_buf_iff, ←string.to_list_inj, buffer.ext_iff] instance remaining : remaining.static := ⟨λ _ _ _ _ h, (remaining_eq_done.mp h).left⟩ instance eof : eof.static := static.decorate_error instance foldr_core {f : α → β → β} [p.static] : ∀ {b : β} {reps : ℕ}, (foldr_core f p b reps).static | _ 0 := static.failure | _ (reps + 1) := begin simp_rw parser.foldr_core, convert static.orelse, { convert static.bind, { apply_instance }, { intro, convert static.bind, { exact foldr_core }, { apply_instance } } }, { exact static.pure } end instance foldr {f : α → β → β} [p.static] : static (foldr f p b) := ⟨λ _ _ _ _, by { dsimp [foldr], exact of_done }⟩ instance foldl_core {f : α → β → α} {p : parser β} [p.static] : ∀ {a : α} {reps : ℕ}, (foldl_core f a p reps).static | _ 0 := static.failure | _ (reps + 1) := begin convert static.orelse, { convert static.bind, { apply_instance }, { exact λ _, foldl_core } }, { exact static.pure } end instance foldl {f : α → β → α} {p : parser β} [p.static] : static (foldl f a p) := ⟨λ _ _ _ _, by { dsimp [foldl], exact of_done }⟩ instance many [p.static] : p.many.static := static.foldr instance many_char {p : parser char} [p.static] : p.many_char.static := static.map instance many' [p.static] : p.many'.static := static.and_then instance many1 [p.static] : p.many1.static := static.seq instance many_char1 {p : parser char} [p.static] : p.many_char1.static := static.map instance sep_by1 [p.static] [sep.static] : static (sep_by1 sep p) := static.seq instance sep_by [p.static] [sep.static] : static (sep_by sep p) := static.orelse lemma fix_core {F : parser α → parser α} (hF : ∀ (p : parser α), p.static → (F p).static) : ∀ (max_depth : ℕ), static (fix_core F max_depth) | 0 := static.failure | (max_depth + 1) := hF _ (fix_core _) lemma digit : ¬ digit.static := begin have : digit "1".to_char_buffer 0 = done 1 1, { have : 0 < "s".to_char_buffer.size := dec_trivial, simpa [this] }, exact not_of_ne this zero_ne_one end lemma nat : ¬ nat.static := begin have : nat "1".to_char_buffer 0 = done 1 1, { have : 0 < "s".to_char_buffer.size := dec_trivial, simpa [this] }, exact not_of_ne this zero_ne_one end lemma fix {F : parser α → parser α} (hF : ∀ (p : parser α), p.static → (F p).static) : static (fix F) := ⟨λ cb n _ _ h, by { haveI := fix_core hF (cb.size - n + 1), dsimp [fix] at h, exact static.of_done h }⟩ end static namespace bounded variables {α β : Type} {msgs : thunk (list string)} {msg : thunk string} variables {p q : parser α} {cb : char_buffer} {n n' : ℕ} {err : dlist string} variables {a : α} {b : β} lemma done_of_unbounded (h : ¬p.bounded) : ∃ (cb : char_buffer) (n n' : ℕ) (a : α), p cb n = done n' a ∧ cb.size ≤ n := begin contrapose! h, constructor, intros cb n hn, cases hp : p cb n, { exact absurd hn (h _ _ _ _ hp).not_le }, { simp [hp] } end lemma pure : ¬ bounded (pure a) := begin introI, have : (pure a : parser α) buffer.nil 0 = done 0 a := by simp [pure_eq_done], exact absurd (bounded.of_done this) (lt_irrefl _) end instance bind {f : α → parser β} [p.bounded] : (p >>= f).bounded := begin constructor, intros cb n hn, obtain ⟨_, _, hp⟩ := bounded.exists p hn, simp [hp] end instance and_then {q : parser β} [p.bounded] : (p >> q).bounded := bounded.bind instance map [p.bounded] {f : α → β} : (f <$> p).bounded := bounded.bind instance seq {f : parser (α → β)} [f.bounded] : (f <*> p).bounded := bounded.bind instance mmap {a : α} {l : list α} {f : α → parser β} [∀ a, (f a).bounded] : ((a :: l).mmap f).bounded := bounded.bind instance mmap' {a : α} {l : list α} {f : α → parser β} [∀ a, (f a).bounded] : ((a :: l).mmap' f).bounded := bounded.and_then instance failure : @parser.bounded α failure := ⟨by simp⟩ lemma guard_iff {p : Prop} [decidable p] : bounded (guard p) ↔ ¬ p := by simpa [guard, apply_ite bounded, pure, failure] using λ _, bounded.failure instance orelse [p.bounded] [q.bounded] : (p <|> q).bounded := begin constructor, intros cb n hn, cases hx : (p <|> q) cb n with posx resx posx errx, { obtain h | ⟨h, -, -⟩ := orelse_eq_done.mp hx; exact absurd hn (of_done h).not_le }, { simp } end instance decorate_errors [p.bounded] : (@decorate_errors α msgs p).bounded := begin constructor, intros _ _, simpa using bounded.exists p end lemma decorate_errors_iff : (@parser.decorate_errors α msgs p).bounded ↔ p.bounded := begin split, { introI, constructor, intros _ _ hn, obtain ⟨_, _, h⟩ := bounded.exists (@parser.decorate_errors α msgs p) hn, simp [decorate_errors_eq_fail] at h, exact h.right.right }, { introI, constructor, intros _ _ hn, obtain ⟨_, _, h⟩ := bounded.exists p hn, simp [h] } end instance decorate_error [p.bounded] : (@decorate_error α msg p).bounded := bounded.decorate_errors lemma decorate_error_iff : (@parser.decorate_error α msg p).bounded ↔ p.bounded := decorate_errors_iff instance any_char : bounded any_char := ⟨λ cb n hn, by simp [any_char, hn]⟩ instance sat {p : char → Prop} [decidable_pred p] : bounded (sat p) := ⟨λ cb n hn, by simp [sat, hn]⟩ lemma eps : ¬ bounded eps := pure instance ch {c : char} : bounded (ch c) := bounded.decorate_error lemma char_buf_iff {cb' : char_buffer} : bounded (char_buf cb') ↔ cb' ≠ buffer.nil := begin have : cb' ≠ buffer.nil ↔ cb'.to_list ≠ [] := not_iff_not_of_iff ⟨λ h, by simp [h], λ h, by simpa using congr_arg list.to_buffer h⟩, rw [char_buf, decorate_error_iff, this], cases cb'.to_list, { simp [pure, ch] }, { simp only [iff_true, ne.def, not_false_iff], apply_instance } end instance one_of {cs : list char} : (one_of cs).bounded := bounded.decorate_errors instance one_of' {cs : list char} : (one_of' cs).bounded := bounded.and_then lemma str_iff {s : string} : (str s).bounded ↔ s ≠ "" := begin rw [str, decorate_error_iff], cases hs : s.to_list, { have : s = "", { cases s, rw [string.to_list] at hs, simpa [hs] }, simp [pure, this] }, { have : s ≠ "", { intro H, simpa [H] using hs }, simp only [this, iff_true, ne.def, not_false_iff], apply_instance } end lemma remaining : ¬ remaining.bounded := begin introI, have : remaining buffer.nil 0 = done 0 0 := by simp [remaining_eq_done], exact absurd (bounded.of_done this) (lt_irrefl _) end lemma eof : ¬ eof.bounded := begin introI, have : eof buffer.nil 0 = done 0 () := by simp [eof_eq_done], exact absurd (bounded.of_done this) (lt_irrefl _) end section fold instance foldr_core_zero {f : α → β → β} : (foldr_core f p b 0).bounded := bounded.failure instance foldl_core_zero {f : β → α → β} {b : β} : (foldl_core f b p 0).bounded := bounded.failure variables {reps : ℕ} [hpb : p.bounded] (he : ∀ cb n n' err, p cb n = fail n' err → n ≠ n') include hpb he lemma foldr_core {f : α → β → β} : (foldr_core f p b reps).bounded := begin cases reps, { exact bounded.foldr_core_zero }, constructor, intros cb n hn, obtain ⟨np, errp, hp⟩ := bounded.exists p hn, simpa [foldr_core_succ_eq_fail, hp] using he cb n np errp, end lemma foldr {f : α → β → β} : bounded (foldr f p b) := begin constructor, intros cb n hn, haveI : (parser.foldr_core f p b (cb.size - n + 1)).bounded := foldr_core he, obtain ⟨np, errp, hp⟩ := bounded.exists (parser.foldr_core f p b (cb.size - n + 1)) hn, simp [foldr, hp] end lemma foldl_core {f : β → α → β} : (foldl_core f b p reps).bounded := begin cases reps, { exact bounded.foldl_core_zero }, constructor, intros cb n hn, obtain ⟨np, errp, hp⟩ := bounded.exists p hn, simpa [foldl_core_succ_eq_fail, hp] using he cb n np errp, end lemma foldl {f : β → α → β} : bounded (foldl f b p) := begin constructor, intros cb n hn, haveI : (parser.foldl_core f b p (cb.size - n + 1)).bounded := foldl_core he, obtain ⟨np, errp, hp⟩ := bounded.exists (parser.foldl_core f b p (cb.size - n + 1)) hn, simp [foldl, hp] end lemma many : p.many.bounded := foldr he omit hpb lemma many_char {pc : parser char} [pc.bounded] (he : ∀ cb n n' err, pc cb n = fail n' err → n ≠ n'): pc.many_char.bounded := by { convert bounded.map, exact many he } include hpb lemma many' : p.many'.bounded := by { convert bounded.and_then, exact many he } end fold instance many1 [p.bounded] : p.many1.bounded := bounded.seq instance many_char1 {p : parser char} [p.bounded] : p.many_char1.bounded := bounded.map instance sep_by1 {sep : parser unit} [p.bounded] : bounded (sep_by1 sep p) := bounded.seq lemma fix_core {F : parser α → parser α} (hF : ∀ (p : parser α), p.bounded → (F p).bounded) : ∀ (max_depth : ℕ), bounded (fix_core F max_depth) | 0 := bounded.failure | (max_depth + 1) := hF _ (fix_core _) instance digit : digit.bounded := bounded.decorate_error instance nat : nat.bounded := bounded.decorate_error lemma fix {F : parser α → parser α} (hF : ∀ (p : parser α), p.bounded → (F p).bounded) : bounded (fix F) := begin constructor, intros cb n hn, haveI : (parser.fix_core F (cb.size - n + 1)).bounded := fix_core hF _, obtain ⟨np, errp, hp⟩ := bounded.exists (parser.fix_core F (cb.size - n + 1)) hn, simp [fix, hp] end end bounded namespace unfailing variables {α β : Type} {p q : parser α} {msgs : thunk (list string)} {msg : thunk string} {cb : char_buffer} {n' n : ℕ} {err : dlist string} {a : α} {b : β} {sep : parser unit} lemma of_bounded [p.bounded] : ¬ unfailing p := begin introI, cases h : p buffer.nil 0, { simpa [lt_irrefl] using bounded.of_done h }, { exact of_fail h } end instance pure : unfailing (pure a) := ⟨λ _ _, by simp [pure_eq_done]⟩ instance bind {f : α → parser β} [p.unfailing] [∀ a, (f a).unfailing] : (p >>= f).unfailing := ⟨λ cb n, begin obtain ⟨np, a, hp⟩ := exists_done p cb n, simpa [hp, and.comm, and.left_comm, and.assoc] using exists_done (f a) cb np end⟩ instance and_then {q : parser β} [p.unfailing] [q.unfailing] : (p >> q).unfailing := unfailing.bind instance map [p.unfailing] {f : α → β} : (f <$> p).unfailing := unfailing.bind instance seq {f : parser (α → β)} [f.unfailing] [p.unfailing] : (f <*> p).unfailing := unfailing.bind instance mmap {l : list α} {f : α → parser β} [∀ a, (f a).unfailing] : (l.mmap f).unfailing := begin constructor, induction l with hd tl hl, { intros, simp [pure_eq_done] }, { intros, obtain ⟨np, a, hp⟩ := exists_done (f hd) cb n, obtain ⟨n', b, hf⟩ := hl cb np, simp [hp, hf, and.comm, and.left_comm, and.assoc, pure_eq_done] } end instance mmap' {l : list α} {f : α → parser β} [∀ a, (f a).unfailing] : (l.mmap' f).unfailing := begin constructor, induction l with hd tl hl, { intros, simp [pure_eq_done] }, { intros, obtain ⟨np, a, hp⟩ := exists_done (f hd) cb n, obtain ⟨n', b, hf⟩ := hl cb np, simp [hp, hf, and.comm, and.left_comm, and.assoc, pure_eq_done] } end lemma failure : ¬ @parser.unfailing α failure := begin introI h, have : (failure : parser α) buffer.nil 0 = fail 0 dlist.empty := by simp, exact of_fail this end instance guard_true : unfailing (guard true) := unfailing.pure lemma guard : ¬ unfailing (guard false) := unfailing.failure instance orelse [p.unfailing] : (p <|> q).unfailing := ⟨λ cb n, by { obtain ⟨_, _, h⟩ := p.exists_done cb n, simp [success_iff, h] }⟩ instance decorate_errors [p.unfailing] : (@decorate_errors α msgs p).unfailing := ⟨λ cb n, by { obtain ⟨_, _, h⟩ := p.exists_done cb n, simp [success_iff, h] }⟩ instance decorate_error [p.unfailing] : (@decorate_error α msg p).unfailing := unfailing.decorate_errors instance any_char : conditionally_unfailing any_char := ⟨λ _ _ hn, by simp [success_iff, any_char_eq_done, hn]⟩ lemma sat : conditionally_unfailing (sat (λ _, true)) := ⟨λ _ _ hn, by simp [success_iff, sat_eq_done, hn]⟩ instance eps : unfailing eps := unfailing.pure instance remaining : remaining.unfailing := ⟨λ _ _, by simp [success_iff, remaining_eq_done]⟩ lemma foldr_core_zero {f : α → β → β} {b : β} : ¬ (foldr_core f p b 0).unfailing := unfailing.failure instance foldr_core_of_static {f : α → β → β} {b : β} {reps : ℕ} [p.static] [p.unfailing] : (foldr_core f p b (reps + 1)).unfailing := begin induction reps with reps hr, { constructor, intros cb n, obtain ⟨np, a, h⟩ := p.exists_done cb n, simpa [foldr_core_eq_done, h] using (static.of_done h).symm }, { constructor, haveI := hr, intros cb n, obtain ⟨np, a, h⟩ := p.exists_done cb n, obtain rfl : n = np := static.of_done h, obtain ⟨np, b', hf⟩ := exists_done (foldr_core f p b (reps + 1)) cb n, obtain rfl : n = np := static.of_done hf, refine ⟨n, f a b', _⟩, rw foldr_core_eq_done, simp [h, hf, and.comm, and.left_comm, and.assoc] } end instance foldr_core_one_of_err_static {f : α → β → β} {b : β} [p.static] [p.err_static] : (foldr_core f p b 1).unfailing := begin constructor, intros cb n, cases h : p cb n, { simpa [foldr_core_eq_done, h] using (static.of_done h).symm }, { simpa [foldr_core_eq_done, h] using (err_static.of_fail h).symm } end -- TODO: add foldr and foldl, many, etc, fix_core lemma digit : ¬ digit.unfailing := of_bounded lemma nat : ¬ nat.unfailing := of_bounded end unfailing namespace err_static variables {α β : Type} {p q : parser α} {msgs : thunk (list string)} {msg : thunk string} {cb : char_buffer} {n' n : ℕ} {err : dlist string} {a : α} {b : β} {sep : parser unit} lemma not_of_ne (h : p cb n = fail n' err) (hne : n ≠ n') : ¬ err_static p := by { introI, exact hne (of_fail h) } instance pure : err_static (pure a) := ⟨λ _ _ _ _, by { simp [pure_eq_done] }⟩ instance bind {f : α → parser β} [p.static] [p.err_static] [∀ a, (f a).err_static] : (p >>= f).err_static := ⟨λ cb n n' err, begin rw bind_eq_fail, rintro (hp | ⟨_, _, hp, hf⟩), { exact of_fail hp }, { exact trans (static.of_done hp) (of_fail hf) } end⟩ instance bind_of_unfailing {f : α → parser β} [p.err_static] [∀ a, (f a).unfailing] : (p >>= f).err_static := ⟨λ cb n n' err, begin rw bind_eq_fail, rintro (hp | ⟨_, _, hp, hf⟩), { exact of_fail hp }, { exact false.elim (unfailing.of_fail hf) } end⟩ instance and_then {q : parser β} [p.static] [p.err_static] [q.err_static] : (p >> q).err_static := err_static.bind instance and_then_of_unfailing {q : parser β} [p.err_static] [q.unfailing] : (p >> q).err_static := err_static.bind_of_unfailing instance map [p.err_static] {f : α → β} : (f <$> p).err_static := ⟨λ _ _ _ _, by { rw map_eq_fail, exact of_fail }⟩ instance seq {f : parser (α → β)} [f.static] [f.err_static] [p.err_static] : (f <*> p).err_static := err_static.bind instance seq_of_unfailing {f : parser (α → β)} [f.err_static] [p.unfailing] : (f <*> p).err_static := err_static.bind_of_unfailing instance mmap : Π {l : list α} {f : α → parser β} [∀ a, (f a).static] [∀ a, (f a).err_static], (l.mmap f).err_static | [] _ _ _ := err_static.pure | (a :: l) _ h h' := begin convert err_static.bind, { exact h _ }, { exact h' _ }, { intro, convert err_static.bind, { convert static.mmap, exact h }, { apply mmap, { exact h }, { exact h' } }, { exact λ _, err_static.pure } } end instance mmap_of_unfailing : Π {l : list α} {f : α → parser β} [∀ a, (f a).unfailing] [∀ a, (f a).err_static], (l.mmap f).err_static | [] _ _ _ := err_static.pure | (a :: l) _ h h' := begin convert err_static.bind_of_unfailing, { exact h' _ }, { intro, convert unfailing.bind, { convert unfailing.mmap, exact h }, { exact λ _, unfailing.pure } } end instance mmap' : Π {l : list α} {f : α → parser β} [∀ a, (f a).static] [∀ a, (f a).err_static], (l.mmap' f).err_static | [] _ _ _ := err_static.pure | (a :: l) _ h h' := begin convert err_static.and_then, { exact h _ }, { exact h' _ }, { convert mmap', { exact h }, { exact h' } } end instance mmap'_of_unfailing : Π {l : list α} {f : α → parser β} [∀ a, (f a).unfailing] [∀ a, (f a).err_static], (l.mmap' f).err_static | [] _ _ _ := err_static.pure | (a :: l) _ h h' := begin convert err_static.and_then_of_unfailing, { exact h' _ }, { convert unfailing.mmap', exact h } end instance failure : @parser.err_static α failure := ⟨λ _ _ _ _ h, (failure_eq_fail.mp h).left⟩ instance guard {p : Prop} [decidable p] : err_static (guard p) := ⟨λ _ _ _ _ h, (guard_eq_fail.mp h).right.left⟩ instance orelse [p.err_static] [q.mono] : (p <|> q).err_static := ⟨λ _ n n' _, begin by_cases hn : n = n', { exact λ _, hn }, { rw orelse_eq_fail_of_mono_ne hn, { exact of_fail }, { apply_instance } } end⟩ instance decorate_errors : (@decorate_errors α msgs p).err_static := ⟨λ _ _ _ _ h, (decorate_errors_eq_fail.mp h).left⟩ instance decorate_error : (@decorate_error α msg p).err_static := err_static.decorate_errors instance any_char : err_static any_char := ⟨λ _ _ _ _, by { rw [any_char_eq_fail, and.comm], simp }⟩ instance sat_iff {p : char → Prop} [decidable_pred p] : err_static (sat p) := ⟨λ _ _ _ _ h, (sat_eq_fail.mp h).left⟩ instance eps : err_static eps := err_static.pure instance ch (c : char) : err_static (ch c) := err_static.decorate_error instance char_buf {cb' : char_buffer} : err_static (char_buf cb') := err_static.decorate_error instance one_of {cs : list char} : err_static (one_of cs) := err_static.decorate_errors instance one_of' {cs : list char} : err_static (one_of' cs) := err_static.and_then_of_unfailing instance str {s : string} : err_static (str s) := err_static.decorate_error instance remaining : remaining.err_static := ⟨λ _ _ _ _, by simp [remaining_ne_fail]⟩ instance eof : eof.err_static := err_static.decorate_error -- TODO: add foldr and foldl, many, etc, fix_core lemma fix_core {F : parser α → parser α} (hF : ∀ (p : parser α), p.err_static → (F p).err_static) : ∀ (max_depth : ℕ), err_static (fix_core F max_depth) | 0 := err_static.failure | (max_depth + 1) := hF _ (fix_core _) instance digit : digit.err_static := err_static.decorate_error instance nat : nat.err_static := err_static.decorate_error lemma fix {F : parser α → parser α} (hF : ∀ (p : parser α), p.err_static → (F p).err_static) : err_static (fix F) := ⟨λ cb n _ _ h, by { haveI := fix_core hF (cb.size - n + 1), dsimp [fix] at h, exact err_static.of_fail h }⟩ end err_static namespace step variables {α β : Type} {p q : parser α} {msgs : thunk (list string)} {msg : thunk string} {cb : char_buffer} {n' n : ℕ} {err : dlist string} {a : α} {b : β} {sep : parser unit} lemma not_step_of_static_done [static p] (h : ∃ cb n n' a, p cb n = done n' a) : ¬ step p := begin introI, rcases h with ⟨cb, n, n', a, h⟩, have hs := static.of_done h, simpa [←hs] using of_done h end lemma pure (a : α) : ¬ step (pure a) := begin apply not_step_of_static_done, simp [pure_eq_done] end instance bind {f : α → parser β} [p.step] [∀ a, (f a).static] : (p >>= f).step := ⟨λ _ _ _ _, by { simp_rw bind_eq_done, rintro ⟨_, _, hp, hf⟩, exact (static.of_done hf) ▸ (of_done hp) }⟩ instance bind' {f : α → parser β} [p.static] [∀ a, (f a).step] : (p >>= f).step := ⟨λ _ _ _ _, by { simp_rw bind_eq_done, rintro ⟨_, _, hp, hf⟩, rw static.of_done hp, exact of_done hf }⟩ instance and_then {q : parser β} [p.step] [q.static] : (p >> q).step := step.bind instance and_then' {q : parser β} [p.static] [q.step] : (p >> q).step := step.bind' instance map [p.step] {f : α → β} : (f <$> p).step := ⟨λ _ _ _ _, by { simp_rw map_eq_done, rintro ⟨_, hp, _⟩, exact of_done hp }⟩ instance seq {f : parser (α → β)} [f.step] [p.static] : (f <*> p).step := step.bind instance seq' {f : parser (α → β)} [f.static] [p.step] : (f <*> p).step := step.bind' instance mmap {f : α → parser β} [(f a).step] : ([a].mmap f).step := begin convert step.bind, { apply_instance }, { intro, convert static.bind, { exact static.pure }, { exact λ _, static.pure } } end instance mmap' {f : α → parser β} [(f a).step] : ([a].mmap' f).step := begin convert step.and_then, { apply_instance }, { exact static.pure } end instance failure : @parser.step α failure := ⟨λ _ _ _ _, by simp⟩ lemma guard_true : ¬ step (guard true) := pure _ instance guard : step (guard false) := step.failure instance orelse [p.step] [q.step] : (p <|> q).step := ⟨λ _ _ _ _, by { simp_rw orelse_eq_done, rintro (h | ⟨h, -⟩); exact of_done h }⟩ lemma decorate_errors_iff : (@parser.decorate_errors α msgs p).step ↔ p.step := begin split, { introI, constructor, intros cb n n' a h, have : (@parser.decorate_errors α msgs p) cb n = done n' a := by simpa using h, exact of_done this }, { introI, constructor, intros _ _ _ _ h, rw decorate_errors_eq_done at h, exact of_done h } end instance decorate_errors [p.step] : (@decorate_errors α msgs p).step := ⟨λ _ _ _ _, by { rw decorate_errors_eq_done, exact of_done }⟩ lemma decorate_error_iff : (@parser.decorate_error α msg p).step ↔ p.step := decorate_errors_iff instance decorate_error [p.step] : (@decorate_error α msg p).step := step.decorate_errors instance any_char : step any_char := begin constructor, intros cb n, simp_rw [any_char_eq_done], rintro _ _ ⟨_, rfl, -⟩, simp end instance sat {p : char → Prop} [decidable_pred p] : step (sat p) := begin constructor, intros cb n, simp_rw [sat_eq_done], rintro _ _ ⟨_, _, rfl, -⟩, simp end lemma eps : ¬ step eps := step.pure () instance ch {c : char} : step (ch c) := step.decorate_error lemma char_buf_iff {cb' : char_buffer} : (char_buf cb').step ↔ cb'.size = 1 := begin have : char_buf cb' cb' 0 = done cb'.size () := by simp [char_buf_eq_done], split, { introI, simpa using of_done this }, { intro h, constructor, intros cb n n' _, rw [char_buf_eq_done, h], rintro ⟨rfl, -⟩, refl } end instance one_of {cs : list char} : (one_of cs).step := step.decorate_errors instance one_of' {cs : list char} : (one_of' cs).step := step.and_then lemma str_iff {s : string} : (str s).step ↔ s.length = 1 := by simp [str_eq_char_buf, char_buf_iff, ←string.to_list_inj, buffer.ext_iff] lemma remaining : ¬ remaining.step := begin apply not_step_of_static_done, simp [remaining_eq_done] end lemma eof : ¬ eof.step := begin apply not_step_of_static_done, simp only [eof_eq_done, exists_eq_left', exists_const], use [buffer.nil, 0], simp end -- TODO: add foldr and foldl, many, etc, fix_core lemma fix_core {F : parser α → parser α} (hF : ∀ (p : parser α), p.step → (F p).step) : ∀ (max_depth : ℕ), step (fix_core F max_depth) | 0 := step.failure | (max_depth + 1) := hF _ (fix_core _) instance digit : digit.step := step.decorate_error lemma fix {F : parser α → parser α} (hF : ∀ (p : parser α), p.step → (F p).step) : step (fix F) := ⟨λ cb n _ _ h, by { haveI := fix_core hF (cb.size - n + 1), dsimp [fix] at h, exact of_done h }⟩ end step section step variables {α β : Type} {p q : parser α} {msgs : thunk (list string)} {msg : thunk string} {cb : char_buffer} {n' n : ℕ} {err : dlist string} {a : α} {b : β} {sep : parser unit} lemma many1_eq_done_iff_many_eq_done [p.step] [p.bounded] {x : α} {xs : list α} : many1 p cb n = done n' (x :: xs) ↔ many p cb n = done n' (x :: xs) := begin induction hx : (x :: xs) with hd tl IH generalizing x xs n n', { simpa using hx }, split, { simp only [many1_eq_done, and_imp, exists_imp_distrib], intros np hp hm, have : np = n + 1 := step.of_done hp, have hn : n < cb.size := bounded.of_done hp, subst this, obtain ⟨k, hk⟩ : ∃ k, cb.size - n = k + 1 := nat.exists_eq_succ_of_ne_zero (ne_of_gt (tsub_pos_of_lt hn)), cases k, { cases tl; simpa [many_eq_done_nil, nat.sub_succ, hk, many_eq_done, hp, foldr_core_eq_done] using hm }, cases tl with hd' tl', { simpa [many_eq_done_nil, nat.sub_succ, hk, many_eq_done, hp, foldr_core_eq_done] using hm }, { rw ←@IH hd' tl' at hm, swap, refl, simp only [many1_eq_done, many, foldr] at hm, obtain ⟨np, hp', hf⟩ := hm, obtain rfl : np = n + 1 + 1 := step.of_done hp', simpa [nat.sub_succ, many_eq_done, hp, hk, foldr_core_eq_done, hp'] using hf } }, { simp only [many_eq_done, many1_eq_done, and_imp, exists_imp_distrib], intros np hp hm, have : np = n + 1 := step.of_done hp, have hn : n < cb.size := bounded.of_done hp, subst this, obtain ⟨k, hk⟩ : ∃ k, cb.size - n = k + 1 := nat.exists_eq_succ_of_ne_zero (ne_of_gt (tsub_pos_of_lt hn)), cases k, { cases tl; simpa [many_eq_done_nil, nat.sub_succ, hk, many_eq_done, hp, foldr_core_eq_done] using hm }, cases tl with hd' tl', { simpa [many_eq_done_nil, nat.sub_succ, hk, many_eq_done, hp, foldr_core_eq_done] using hm }, { simp [hp], rw ←@IH hd' tl' (n + 1) n', swap, refl, rw [hk, foldr_core_eq_done, or.comm] at hm, obtain (hm | ⟨np, hd', tl', hp', hf, hm⟩) := hm, { simpa using hm }, simp only at hm, obtain ⟨rfl, rfl⟩ := hm, obtain rfl : np = n + 1 + 1 := step.of_done hp', simp [nat.sub_succ, many, many1_eq_done, hp, hk, foldr_core_eq_done, hp', ←hf, foldr] } } end end step namespace prog variables {α β : Type} {p q : parser α} {msgs : thunk (list string)} {msg : thunk string} {cb : char_buffer} {n' n : ℕ} {err : dlist string} {a : α} {b : β} {sep : parser unit} @[priority 100] -- see Note [lower instance priority] instance of_step [step p] : prog p := ⟨λ _ _ _ _ h, by { rw step.of_done h, exact nat.lt_succ_self _ }⟩ lemma pure (a : α) : ¬ prog (pure a) := begin introI h, have : (pure a : parser α) buffer.nil 0 = done 0 a := by simp [pure_eq_done], replace this : 0 < 0 := prog.of_done this, exact (lt_irrefl _) this end instance bind {f : α → parser β} [p.prog] [∀ a, (f a).mono] : (p >>= f).prog := ⟨λ _ _ _ _, by { simp_rw bind_eq_done, rintro ⟨_, _, hp, hf⟩, exact lt_of_lt_of_le (of_done hp) (mono.of_done hf) }⟩ instance and_then {q : parser β} [p.prog] [q.mono] : (p >> q).prog := prog.bind instance map [p.prog] {f : α → β} : (f <$> p).prog := ⟨λ _ _ _ _, by { simp_rw map_eq_done, rintro ⟨_, hp, _⟩, exact of_done hp }⟩ instance seq {f : parser (α → β)} [f.prog] [p.mono] : (f <*> p).prog := prog.bind instance mmap {l : list α} {f : α → parser β} [(f a).prog] [∀ a, (f a).mono] : ((a :: l).mmap f).prog := begin constructor, simp only [and_imp, bind_eq_done, return_eq_pure, mmap, exists_imp_distrib, pure_eq_done], rintro _ _ _ _ _ _ h _ _ hp rfl rfl, exact lt_of_lt_of_le (of_done h) (mono.of_done hp) end instance mmap' {l : list α} {f : α → parser β} [(f a).prog] [∀ a, (f a).mono] : ((a :: l).mmap' f).prog := begin constructor, simp only [and_imp, bind_eq_done, mmap', exists_imp_distrib, and_then_eq_bind], intros _ _ _ _ _ _ h hm, exact lt_of_lt_of_le (of_done h) (mono.of_done hm) end instance failure : @parser.prog α failure := prog.of_step lemma guard_true : ¬ prog (guard true) := pure _ instance guard : prog (guard false) := prog.failure instance orelse [p.prog] [q.prog] : (p <|> q).prog := ⟨λ _ _ _ _, by { simp_rw orelse_eq_done, rintro (h | ⟨h, -⟩); exact of_done h }⟩ lemma decorate_errors_iff : (@parser.decorate_errors α msgs p).prog ↔ p.prog := begin split, { introI, constructor, intros cb n n' a h, have : (@parser.decorate_errors α msgs p) cb n = done n' a := by simpa using h, exact of_done this }, { introI, constructor, intros _ _ _ _ h, rw decorate_errors_eq_done at h, exact of_done h } end instance decorate_errors [p.prog] : (@decorate_errors α msgs p).prog := ⟨λ _ _ _ _, by { rw decorate_errors_eq_done, exact of_done }⟩ lemma decorate_error_iff : (@parser.decorate_error α msg p).prog ↔ p.prog := decorate_errors_iff instance decorate_error [p.prog] : (@decorate_error α msg p).prog := prog.decorate_errors instance any_char : prog any_char := prog.of_step instance sat {p : char → Prop} [decidable_pred p] : prog (sat p) := prog.of_step lemma eps : ¬ prog eps := prog.pure () instance ch {c : char} : prog (ch c) := prog.of_step lemma char_buf_iff {cb' : char_buffer} : (char_buf cb').prog ↔ cb' ≠ buffer.nil := begin have : cb' ≠ buffer.nil ↔ cb'.to_list ≠ [] := not_iff_not_of_iff ⟨λ h, by simp [h], λ h, by simpa using congr_arg list.to_buffer h⟩, rw [char_buf, this, decorate_error_iff], cases cb'.to_list, { simp [pure] }, { simp only [iff_true, ne.def, not_false_iff], apply_instance } end instance one_of {cs : list char} : (one_of cs).prog := prog.decorate_errors instance one_of' {cs : list char} : (one_of' cs).prog := prog.and_then lemma str_iff {s : string} : (str s).prog ↔ s ≠ "" := by simp [str_eq_char_buf, char_buf_iff, ←string.to_list_inj, buffer.ext_iff] lemma remaining : ¬ remaining.prog := begin introI h, have : remaining buffer.nil 0 = done 0 0 := by simp [remaining_eq_done], replace this : 0 < 0 := prog.of_done this, exact (lt_irrefl _) this end lemma eof : ¬ eof.prog := begin introI h, have : eof buffer.nil 0 = done 0 () := by simpa [remaining_eq_done], replace this : 0 < 0 := prog.of_done this, exact (lt_irrefl _) this end -- TODO: add foldr and foldl, many, etc, fix_core instance many1 [p.mono] [p.prog] : p.many1.prog := begin constructor, rintro cb n n' (_ | ⟨hd, tl⟩), { simp }, { rw many1_eq_done, rintro ⟨np, hp, h⟩, exact (of_done hp).trans_le (mono.of_done h) } end lemma fix_core {F : parser α → parser α} (hF : ∀ (p : parser α), p.prog → (F p).prog) : ∀ (max_depth : ℕ), prog (fix_core F max_depth) | 0 := prog.failure | (max_depth + 1) := hF _ (fix_core _) instance digit : digit.prog := prog.of_step instance nat : nat.prog := prog.decorate_error lemma fix {F : parser α → parser α} (hF : ∀ (p : parser α), p.prog → (F p).prog) : prog (fix F) := ⟨λ cb n _ _ h, by { haveI := fix_core hF (cb.size - n + 1), dsimp [fix] at h, exact of_done h }⟩ end prog variables {α β : Type} {msgs : thunk (list string)} {msg : thunk string} variables {p q : parser α} {cb : char_buffer} {n n' : ℕ} {err : dlist string} variables {a : α} {b : β} section many -- TODO: generalize to p.prog instead of p.step lemma many_sublist_of_done [p.step] [p.bounded] {l : list α} (h : p.many cb n = done n' l) : ∀ k < n' - n, p.many cb (n + k) = done n' (l.drop k) := begin induction l with hd tl hl generalizing n, { rw many_eq_done_nil at h, simp [h.left] }, intros m hm, cases m, { exact h }, rw [list.drop, nat.add_succ, ←nat.succ_add], apply hl, { rw [←many1_eq_done_iff_many_eq_done, many1_eq_done] at h, obtain ⟨_, hp, h⟩ := h, convert h, exact (step.of_done hp).symm }, { exact nat.lt_pred_iff.mpr hm }, end lemma many_eq_nil_of_done [p.step] [p.bounded] {l : list α} (h : p.many cb n = done n' l) : p.many cb n' = done n' [] := begin induction l with hd tl hl generalizing n, { convert h, rw many_eq_done_nil at h, exact h.left.symm }, { rw [←many1_eq_done_iff_many_eq_done, many1_eq_done] at h, obtain ⟨_, -, h⟩ := h, exact hl h } end lemma many_eq_nil_of_out_of_bound [p.bounded] {l : list α} (h : p.many cb n = done n' l) (hn : cb.size < n) : n' = n ∧ l = [] := begin cases l, { rw many_eq_done_nil at h, exact ⟨h.left.symm, rfl⟩ }, { rw many_eq_done at h, obtain ⟨np, hp, -⟩ := h, exact absurd (bounded.of_done hp) hn.not_lt } end lemma many1_length_of_done [p.mono] [p.step] [p.bounded] {l : list α} (h : many1 p cb n = done n' l) : l.length = n' - n := begin induction l with hd tl hl generalizing n n', { simpa using h }, { obtain ⟨k, hk⟩ : ∃ k, n' = n + k + 1 := nat.exists_eq_add_of_lt (prog.of_done h), subst hk, simp only [many1_eq_done] at h, obtain ⟨_, hp, h⟩ := h, obtain rfl := step.of_done hp, cases tl, { simp only [many_eq_done_nil, add_left_inj, exists_and_distrib_right, self_eq_add_right] at h, rcases h with ⟨rfl, -⟩, simp }, rw ←many1_eq_done_iff_many_eq_done at h, specialize hl h, simp [hl, add_comm, add_assoc, nat.sub_succ] } end lemma many1_bounded_of_done [p.step] [p.bounded] {l : list α} (h : many1 p cb n = done n' l) : n' ≤ cb.size := begin induction l with hd tl hl generalizing n n', { simpa using h }, { simp only [many1_eq_done] at h, obtain ⟨np, hp, h⟩ := h, obtain rfl := step.of_done hp, cases tl, { simp only [many_eq_done_nil, exists_and_distrib_right] at h, simpa [←h.left] using bounded.of_done hp }, { rw ←many1_eq_done_iff_many_eq_done at h, exact hl h } } end end many section nat /-- The `val : ℕ` produced by a successful parse of a `cb : char_buffer` is the numerical value represented by the string of decimal digits (possibly padded with 0s on the left) starting from the parsing position `n` and ending at position `n'`. The number of characters parsed in is necessarily `n' - n`. This is one of the directions of `nat_eq_done`. -/ lemma nat_of_done {val : ℕ} (h : nat cb n = done n' val) : val = (nat.of_digits 10 ((((cb.to_list.drop n).take (n' - n)).reverse.map (λ c, c.to_nat - '0'.to_nat)))) := begin /- The parser `parser.nat` that generates a decimal number from a string of digit characters does several things. First it ingests in as many digits as it can with `many1 digit`. Then, it folds over the resulting `list ℕ` using a helper function that keeps track of both the running sum an and the magnitude so far, using a `(sum, magnitude) : (ℕ × ℕ)` pair. The final sum is extracted using a `prod.fst`. To prove that the value that `parser.nat` produces, after moving precisely `n' - n` steps, is precisely what `nat.of_digits` would give, if supplied the string that is in the ingested `char_buffer` (modulo conversion from `char` to `ℕ ), we need to induct over the length `n' - n` of `cb : char_buffer` ingested, and prove that the parser must have terminated due to hitting either the end of the `char_buffer` or a non-digit character. The statement of the lemma is phrased using a combination of `list.drop` and `list.map` because there is no currently better way to extract an "interval" from a `char_buffer`. Additionally, the statement uses a `list.reverse` because `nat.of_digits` is little-endian. We try to stop referring to the `cb : char_buffer` as soon as possible, so that we can instead regard a `list char` instead, which lends itself better to proofs via induction. -/ /- We first prove some helper lemmas about the definition of `parser.nat`. Since it is defined in core, we have to work with how it is defined instead of changing its definition. In its definition, the function that folds over the parsed in digits is defined internally, as a lambda with anonymous destructor syntax, which leads to an unpleasant `nat._match_1` term when rewriting the definition of `parser.nat` away. Since we know exactly what the function is, we have a `rfl`-like lemma here to rewrite it back into a readable form. -/ have natm : nat._match_1 = (λ (d : ℕ) p, ⟨p.1 + d * p.2, p.2 * 10⟩), { ext1, ext1 ⟨⟩, refl }, -- We also have to prove what is the `prod.snd` of the result of the fold of a `list (ℕ × ℕ)` with -- the function above. We use this lemma later when we finish our inductive case. have hpow : ∀ l, (list.foldr (λ (digit : ℕ) (x : ℕ × ℕ), (x.fst + digit * x.snd, x.snd * 10)) (0, 1) l).snd = 10 ^ l.length, { intro l, induction l with hd tl hl, { simp }, { simp [hl, pow_succ, mul_comm] } }, -- We convert the hypothesis that `parser.nat` has succeeded into an existential that there is -- some list of digits that it has parsed in, and that those digits, when folded over by the -- function above, give the value at hand. simp only [nat, pure_eq_done, natm, decorate_error_eq_done, bind_eq_done] at h, obtain ⟨n', l, hp, rfl, rfl⟩ := h, -- We now want to stop working with the `cb : char_buffer` and parse positions `n` and `n'`, -- and just deal with the parsed digit list `l : list ℕ`. To do so, we have to show that -- this is precisely the list that could have been parsed in, no smaller and no greater. induction l with lhd ltl IH generalizing n n' cb, { -- Base case: we parsed in no digits whatsoever. But this is impossible because `parser.many1` -- must produce a list that is not `list.nil`, by `many1_ne_done_nil`. simpa using hp }, -- Inductive case: -- We must prove that the first digit parsed in `lhd : ℕ` is precisely the digit that is -- represented by the character at position `n` in `cb : char_buffer`. -- We will also prove the correspondence between the subsequent digits `ltl : list ℕ` and the -- remaining characters past position `n` up to position `n'`. cases hx : (list.drop n (buffer.to_list cb)) with chd ctl, { -- Are there even characters left to parse, at position `n` in the `cb : char_buffer`? In other -- words, are we already out of bounds, and thus could not have parsed in any value -- successfully. But this must be a contradiction because `parser.digit` is a `bounded` parser, -- (due to its being defined via `parser.decorate_error`), which means it only succeeds -- in-bounds, and the `many1` parser combinator retains that property. have : cb.size ≤ n := by simpa using list.drop_eq_nil_iff_le.mp hx, exact absurd (bounded.of_done hp) this.not_lt }, -- We prove that the first digit parsed in is precisely the digit that is represented by the -- character at position `n`, which we now call `chd : char`. have chdh : chd.to_nat - '0'.to_nat = lhd, { simp only [many1_eq_done] at hp, -- We know that `parser.digit` succeeded, so it has moved to a possibly different position. -- In fact, we know that this new position is `n + 1`, by the `step` property of -- `parser.digit`. obtain ⟨_, hp, -⟩ := hp, obtain rfl := step.of_done hp, -- We now unfold what it means for `parser.digit` to succeed, which means that the character -- parsed in was "numeric" (for some definition of that property), and, more importantly, -- that the `n`th character of `cb`, let's say `c`, when converted to a `ℕ` via -- `char.to_nat c - '0'.to_nat`, must be equal to the resulting value, `lhd` in our case. simp only [digit_eq_done, buffer.read_eq_nth_le_to_list, hx, buffer.length_to_list, true_and, add_left_inj, list.length, list.nth_le, eq_self_iff_true, exists_and_distrib_left, fin.coe_mk] at hp, rcases hp with ⟨_, hn, rfl, _, _⟩, -- But we already know the list corresponding to `cb : char_buffer` from position `n` and on -- is equal to `(chd :: ctl) : list char`, so our `c` above must satisfy `c = chd`. have hn' : n < cb.to_list.length := by simpa using hn, rw ←list.cons_nth_le_drop_succ hn' at hx, -- We can ignore proving any correspondence of `ctl : list char` to the other portions of the -- `cb : char_buffer`. simp only at hx, simp [hx] }, -- We know that we parsed in more than one character because of the `prog` property of -- `parser.digit`, which the `many1` parser combinator retains. In other words, we know that -- `n < n'`, and so, the list of digits `ltl` must correspond to the list of digits that -- `digit.many1 cb (n + 1)` would produce. We know that the shift of `1` in `n ↦ n + 1` holds -- due to the `step` property of `parser.digit`. -- We also get here `k : ℕ` which will indicate how many characters we parsed in past position -- `n`. We will prove later that this must be the number of digits we produced as well in `ltl`. obtain ⟨k, hk⟩ : ∃ k, n' = n + k + 1 := nat.exists_eq_add_of_lt (prog.of_done hp), have hdm : ltl = [] ∨ digit.many1 cb (n + 1) = done n' ltl, { cases ltl, { simp }, { rw many1_eq_done at hp, obtain ⟨_, hp, hp'⟩ := hp, simpa [step.of_done hp, many1_eq_done_iff_many_eq_done] using hp' } }, -- Now we case on the two possibilities, that there was only a single digit parsed in, and -- `ltl = []`, or, had we started parsing at `n + 1` instead, we'd parse in the value associated -- with `ltl`. -- We prove that the LHS, which is a fold over a `list ℕ` is equal to the RHS, which is that -- the `val : ℕ` that `nat.of_digits` produces when supplied a `list ℕ that has been produced -- via mapping a `list char` using `char.to_nat`. Specifically, that `list char` are the -- characters in the `cb : char_buffer`, from position `n` to position `n'` (excluding `n'`), -- in reverse. rcases hdm with rfl|hdm, { -- Case that `ltl = []`. simp only [many1_eq_done, many_eq_done_nil, exists_and_distrib_right] at hp, -- This means we must have failed parsing with `parser.digit` at some other position, -- which we prove must be `n + 1` via the `step` property. obtain ⟨_, hp, rfl, hp'⟩ := hp, obtain rfl := step.of_done hp, -- Now we rely on the simplifier, which simplfies the LHS, which is a fold over a singleton -- list. On the RHS, `list.take (n + 1 - n)` also produces a singleton list, which, when -- reversed, is the same list. `nat.of_digits` of a singleton list is precisely the value in -- the list. And we already have that `chd.to_nat - '0'.to_nat = lhd`. simp [chdh] }, -- We now have to deal with the case where we parsed in more than one digit, and thus -- `n + 1 < n'`, which means `ctl` has one or more elements. Similarly, `ltl` has one or more -- elements. -- We finish ridding ourselves of references to `cb : char_buffer`, by relying on the fact that -- our `ctl : list char` must be the appropriate portion of `cb` once enough elements have been -- dropped and taken. have rearr : list.take (n + (k + 1) - (n + 1)) (list.drop (n + 1) (buffer.to_list cb)) = ctl.take k, { simp [←list.tail_drop, hx, nat.sub_succ, hk] }, -- We have to prove that the number of digits produced (given by `ltl`) is equal to the number -- of characters parsed in, as given by `ctl.take k`, and that this is precisely `k`. We phrase it -- in the statement using `min`, because lemmas about `list.length (list.take ...)` simplify to -- a statement that uses `min`. The `list.length` term appears from the reduction of the folding -- function, as proven above. have ltll : min k ctl.length = ltl.length, { -- Here is an example of how statements about the `list.length` of `list.take` simplify. have : (ctl.take k).length = min k ctl.length := by simp, -- We bring back the underlying definition of `ctl` as the result of a sequence of `list.take` -- and `list.drop`, so that lemmas about `list.length` of those can fire. rw [←this, ←rearr, many1_length_of_done hdm], -- Likewise, we rid ourselves of the `k` we generated earlier. have : k = n' - n - 1, { simp [hk, add_assoc] }, subst this, simp only [nat.sub_succ, add_comm, ←nat.pred_sub, buffer.length_to_list, nat.pred_one_add, min_eq_left_iff, list.length_drop, add_tsub_cancel_left, list.length_take, tsub_zero], -- We now have a goal of proving an inequality dealing with `nat` subtraction and `nat.pred`, -- both of which require special care to provide positivity hypotheses. rw [tsub_le_tsub_iff_right, nat.pred_le_iff], { -- We know that `n' ≤ cb.size` because of the `bounded` property, that a parser will not -- produce a `done` result at a position farther than the size of the underlying -- `char_buffer`. convert many1_bounded_of_done hp, -- What is now left to prove is that `0 < cb.size`, which can be rephrased -- as proving that it is nonempty. cases hc : cb.size, { -- Proof by contradiction. Let's say that `cb.size = 0`. But we know that we succeeded -- parsing in at position `n` using a `bounded` parser, so we must have that -- `n < cb.size`. have := bounded.of_done hp, rw hc at this, -- But then `n < 0`, a contradiction. exact absurd n.zero_le this.not_le }, { simp } }, { -- Here, we use the same result as above, that `n < cb.size`, and relate it to -- `n ≤ cb.size.pred`. exact nat.le_pred_of_lt (bounded.of_done hp) } }, -- Finally, we simplify. On the LHS, we have a fold over `lhd :: ltl`, which simplifies to -- the operation of the summing folding function on `lhd` and the fold over `ltl`. To that we can -- apply the induction hypothesis, because we know that our parser would have succeeded had we -- started at position `n + 1`. We replace mentions of `cb : char_buffer` with the appropriate -- `chd :: ctl`, replace `lhd` with the appropriate statement of how it is calculated from `chd`, -- and use the lemmas describing the length of `ltl` and how it is associated with `k`. We also -- remove mentions of `n'` and replace with an expression using solely `n + k + 1`. -- We use the lemma we proved above about how the folding function produces the -- `prod.snd` value, which is `10` to the power of the length of the list provided to the fold. -- Finally, we rely on `nat.of_digits_append` for the related statement of how digits given -- are used in the `nat.of_digits` calculation, which also involves `10 ^ list.length ...`. -- The `list.append` operation appears due to the `list.reverse (chd :: ctl)`. -- We include some addition and multiplication lemmas to help the simplifier rearrange terms. simp [IH _ hdm, hx, hk, rearr, ←chdh, ←ltll, hpow, add_assoc, nat.of_digits_append, mul_comm] end /-- If we know that `parser.nat` was successful, starting at position `n` and ending at position `n'`, then it must be the case that for all `k : ℕ`, `n ≤ k`, `k < n'`, the character at the `k`th position in `cb : char_buffer` is "numeric", that is, is between `'0'` and `'9'` inclusive. This is a necessary part of proving one of the directions of `nat_eq_done`. -/ lemma nat_of_done_as_digit {val : ℕ} (h : nat cb n = done n' val) : ∀ (hn : n' ≤ cb.size) k (hk : k < n'), n ≤ k → '0' ≤ cb.read ⟨k, hk.trans_le hn⟩ ∧ cb.read ⟨k, hk.trans_le hn⟩ ≤ '9' := begin -- The properties to be shown for the characters involved rely solely on the success of -- `parser.digit` at the relevant positions, and not on the actual value `parser.nat` produced. -- We break done the success of `parser.nat` into the `parser.digit` success and throw away -- the resulting value given by `parser.nat`, and focus solely on the `list ℕ` generated by -- `parser.digit.many1`. simp only [nat, pure_eq_done, and.left_comm, decorate_error_eq_done, bind_eq_done, exists_eq_left, exists_and_distrib_left] at h, obtain ⟨xs, h, -⟩ := h, -- We want to avoid having to make statements about the `cb : char_buffer` itself. Instead, we -- induct on the `xs : list ℕ` that `parser.digit.many1` produced. induction xs with hd tl hl generalizing n n', { -- Base case: `xs` is empty. But this is a contradiction because `many1` always produces a -- nonempty list, as proven by `many1_ne_done_nil`. simpa using h }, -- Inductive case: we prove that the `parser.digit.many1` produced a valid `(hd :: tl) : list ℕ`, -- by showing that is the case for the character at position `n`, which gave `hd`, and use the -- induction hypothesis on the remaining `tl`. -- We break apart a `many1` success into a success of the underlying `parser.digit` to give `hd` -- and a `parser.digit.many` which gives `tl`. We first deal with the `hd`. rw many1_eq_done at h, -- Right away, we can throw away the information about the "new" position that `parser.digit` -- ended on because we will soon prove that it must have been `n + 1`. obtain ⟨_, hp, h⟩ := h, -- The main lemma here is `digit_eq_done`, which already proves the necessary conditions about -- the character at hand. What is left to do is properly unpack the information. simp only [digit_eq_done, and.comm, and.left_comm, digit_eq_fail, true_and, exists_eq_left, eq_self_iff_true, exists_and_distrib_left, exists_and_distrib_left] at hp, obtain ⟨rfl, -, hn, ge0, le9, rfl⟩ := hp, -- Let's now consider a position `k` between `n` and `n'`, excluding `n'`. intros hn k hk hk', -- What if we are at `n`? What if we are past `n`? We case on the `n ≤ k`. rcases hk'.eq_or_lt with rfl|hk', { -- The `n = k` case. But this is exactly what we know already, so we provide the -- relevant hypotheses. exact ⟨ge0, le9⟩ }, -- The `n < k` case. First, we check if there would have even been digits parsed in. So, we -- case on `tl : list ℕ` cases tl, { -- Case where `tl = []`. But that means `many` gave us a `[]` so either the character at -- position `k` was not "numeric" or we are out of bounds. More importantly, when `many` -- successfully produces a `[]`, it does not progress the parser head, so we have that -- `n + 1 = n'`. This will lead to a contradiction because now we have `n < k` and `k < n + 1`. simp only [many_eq_done_nil, exists_and_distrib_right] at h, -- Extract out just the `n + 1 = n'`. obtain ⟨rfl, -⟩ := h, -- Form the contradictory hypothesis, and discharge the goal. have : k < k := hk.trans_le (nat.succ_le_of_lt hk'), exact absurd this (lt_irrefl _) }, { -- Case where `tl ≠ []`. But that means that `many` produced a nonempty list as a result, so -- `many1` would have successfully parsed at this position too. We use this statement to -- rewrite our hypothesis into something that works with the induction hypothesis, and apply it. rw ←many1_eq_done_iff_many_eq_done at h, apply hl h, -- All that is left to prove is that our `k` is at least our new "lower bound" `n + 1`, which -- we have from our original split of the `n ≤ k`, since we are now on the `n < k` case. exact nat.succ_le_of_lt hk' } end /-- If we know that `parser.nat` was successful, starting at position `n` and ending at position `n'`, then it must be the case that for the ending position `n'`, either it is beyond the end of the `cb : char_buffer`, or the character at that position is not "numeric", that is, between `'0'` and `'9'` inclusive. This is a necessary part of proving one of the directions of `nat_eq_done`. -/ lemma nat_of_done_bounded {val : ℕ} (h : nat cb n = done n' val) : ∀ (hn : n' < cb.size), '0' ≤ cb.read ⟨n', hn⟩ → '9' < cb.read ⟨n', hn⟩ := begin -- The properties to be shown for the characters involved rely solely on the success of -- `parser.digit` at the relevant positions, and not on the actual value `parser.nat` produced. -- We break done the success of `parser.nat` into the `parser.digit` success and throw away -- the resulting value given by `parser.nat`, and focus solely on the `list ℕ` generated by -- `parser.digit.many1`. -- We deal with the case of `n'` is "out-of-bounds" right away by requiring that -- `∀ (hn : n' < cb.size)`. Thus we only have to prove the lemma for the cases where `n'` is still -- "in-bounds". simp only [nat, pure_eq_done, and.left_comm, decorate_error_eq_done, bind_eq_done, exists_eq_left, exists_and_distrib_left] at h, obtain ⟨xs, h, -⟩ := h, -- We want to avoid having to make statements about the `cb : char_buffer` itself. Instead, we -- induct on the `xs : list ℕ` that `parser.digit.many1` produced. induction xs with hd tl hl generalizing n n', { -- Base case: `xs` is empty. But this is a contradiction because `many1` always produces a -- nonempty list, as proven by `many1_ne_done_nil`. simpa using h }, -- Inductive case: at least one character has been parsed in, starting at position `n`. -- We know that the size of `cb : char_buffer` must be at least `n + 1` because -- `parser.digit.many1` is `bounded` (`n < cb.size`). -- We show that either we parsed in just that one character, or we use the inductive hypothesis. obtain ⟨k, hk⟩ : ∃ k, cb.size = n + k + 1 := nat.exists_eq_add_of_lt (bounded.of_done h), cases tl, { -- Case where `tl = []`, so we parsed in only `hd`. That must mean that `parser.digit` failed -- at `n + 1`. simp only [many1_eq_done, many_eq_done_nil, and.left_comm, exists_and_distrib_right, exists_eq_left] at h, -- We throw away the success information of what happened at position `n`, and we do not need -- the "error" value that the failure produced. obtain ⟨-, _, h⟩ := h, -- If `parser.digit` failed at `n + 1`, then either we hit a non-numeric character, or -- we are out of bounds. `digit_eq_fail` provides us with those two cases. simp only [digit_eq_done, and.comm, and.left_comm, digit_eq_fail, true_and, exists_eq_left, eq_self_iff_true, exists_and_distrib_left] at h, obtain (⟨rfl, h⟩ | ⟨h, -⟩) := h, { -- First case: we are still in bounds, but the character is not numeric. We must prove -- that we are still in bounds. But we know that from our initial requirement. intro hn, simpa using h hn }, { -- Second case: we are out of bounds, and somehow the fold that `many1` relied on failed. -- But we know that `parser.digit` is mono, that is, it never goes backward in position, -- in neither success nor in failure. We also have that `foldr_core` respects `mono`. -- But in this case, `foldr_core` is starting at position `n' + 1` but failing at -- position `n'`, which is a contradiction, because otherwise we would have `n' + 1 ≤ n'`. simpa using mono.of_fail h } }, { -- Case where `tl ≠ []`. But that means that `many` produced a nonempty list as a result, so -- `many1` would have successfully parsed at this position too. We use this statement to -- rewrite our hypothesis into something that works with the induction hypothesis, and apply it. rw many1_eq_done at h, obtain ⟨_, -, h⟩ := h, rw ←many1_eq_done_iff_many_eq_done at h, exact hl h } end /-- The `val : ℕ` produced by a successful parse of a `cb : char_buffer` is the numerical value represented by the string of decimal digits (possibly padded with 0s on the left) starting from the parsing position `n` and ending at position `n'`, where `n < n'`. The number of characters parsed in is necessarily `n' - n`. Additionally, all of the characters in the `cb` starting at position `n` (inclusive) up to position `n'` (exclusive) are "numeric", in that they are between `'0'` and `'9'` inclusive. Such a `char_buffer` would produce the `ℕ` value encoded by its decimal characters. -/ lemma nat_eq_done {val : ℕ} : nat cb n = done n' val ↔ ∃ (hn : n < n'), val = (nat.of_digits 10 ((((cb.to_list.drop n).take (n' - n)).reverse.map (λ c, c.to_nat - '0'.to_nat)))) ∧ (∀ (hn' : n' < cb.size), ('0' ≤ cb.read ⟨n', hn'⟩ → '9' < cb.read ⟨n', hn'⟩)) ∧ ∃ (hn'' : n' ≤ cb.size), (∀ k (hk : k < n'), n ≤ k → '0' ≤ cb.read ⟨k, hk.trans_le hn''⟩ ∧ cb.read ⟨k, hk.trans_le hn''⟩ ≤ '9') := begin -- To prove this iff, we have most of the way in the forward direction, using the lemmas proven -- above. First, we must use that `parser.nat` is `prog`, which means that on success, it must -- move forward. We also have to prove the statement that a success means the parsed in -- characters were properly "numeric". It involves first generating ane existential witness -- that the parse was completely "in-bounds". -- For the reverse direction, we first discharge the goals that deal with proving that our parser -- succeeded because it encountered characters with the proper "numeric" properties, was -- "in-bounds" and hit a nonnumeric character. The more difficult portion is proving that the -- list of characters from positions `n` to `n'`, when folded over by the function defined inside -- `parser.nat` gives exactly the same value as `nat.of_digits` when supplied with the same -- (modulo rearrangement) list. To reach this goal, we try to remove any reliance on the -- underlying `cb : char_buffer` or parsers as soon as possible, via a cased-induction. refine ⟨λ h, ⟨prog.of_done h, nat_of_done h, nat_of_done_bounded h, _⟩, _⟩, { -- To provide the existential witness that `n'` is within the bounds of the `cb : char_buffer`, -- we rely on the fact that `parser.nat` is primarily a `parser.digit.many1`, and that `many1`, -- must finish with the bounds of the `cb`, as long as the underlying parser is `step` and -- `bounded`, which `digit` is. We do not prove this as a separate lemma about `parser.nat` -- because it would almost always be only relevant in this larger theorem. -- We clone the success hypothesis `h` so that we can supply it back later. have H := h, -- We unwrap the `parser.nat` success down to the `many1` success, throwing away other info. rw [nat] at h, simp only [decorate_error_eq_done, bind_eq_done, pure_eq_done, and.left_comm, exists_eq_left, exists_and_distrib_left] at h, obtain ⟨_, h, -⟩ := h, -- Now we get our existential witness that `n' ≤ cb.size`. replace h := many1_bounded_of_done h, -- With that, we can use the lemma proved above that our characters are "numeric" exact ⟨h, nat_of_done_as_digit H h⟩ }, -- We now prove that given the `cb : char_buffer` with characters within the `n ≤ k < n'` interval -- properly "numeric" and such that their `nat.of_digits` generates the `val : ℕ`, `parser.nat` -- of that `cb`, when starting at `n`, will finish at `n'` and produce the same `val`. -- We first introduce the relevant hypotheses, including the fact that we have a valid interval -- where `n < n'` and that characters at `n'` and beyond are no longer numeric. rintro ⟨hn, hv, hb, hn', ho⟩, -- We first unwrap the `parser.nat` definition to the underlying `parser.digit.many1` success -- and the fold function of the digits. rw nat, simp only [and.left_comm, pure_eq_done, hv, decorate_error_eq_done, list.map_reverse, bind_eq_done, exists_eq_left, exists_and_distrib_left], -- We won't actually need the `val : ℕ` itself, since it is entirely characterized by the -- underlying characters. Instead, we will induct over the `list char` of characters from -- position `n` onwards, showing that if we could have provided a list at `n`, we could have -- provided a valid list of characters at `n + 1` too. clear hv val, /- We first prove some helper lemmas about the definition of `parser.nat`. Since it is defined in core, we have to work with how it is defined instead of changing its definition. In its definition, the function that folds over the parsed in digits is defined internally, as a lambda with anonymous destructor syntax, which leads to an unpleasant `nat._match_1` term when rewriting the definition of `parser.nat` away. Since we know exactly what the function is, we have a `rfl`-like lemma here to rewrite it back into a readable form. -/ have natm : nat._match_1 = (λ (d : ℕ) p, ⟨p.1 + d * p.2, p.2 * 10⟩), { ext1, ext1 ⟨⟩, refl }, -- We induct over the characters available at position `n` and onwards. Because `cb` is used -- in other expressions, we utilize the `induction H : ...` tactic to induct separately from -- destructing `cb` itself. induction H : (cb.to_list.drop n) with hd tl IH generalizing n, { -- Base case: there are no characters at position `n` or onwards, which means that -- `cb.size ≤ n`. But this is a contradiction, since we have `n < n' ≤ cb.size`. rw list.drop_eq_nil_iff_le at H, refine absurd ((lt_of_le_of_lt H hn).trans_le hn') _, simp }, { -- Inductive case: we prove that if we could have parsed from `n + 1`, we could have also parsed -- from `n`, if there was a valid numerical character at `n`. Most of the body -- of this inductive case is generating the appropriate conditions for use of the inductive -- hypothesis. specialize @IH (n + 1), -- We have, by the inductive case, that there is at least one character `hd` at position `n`, -- with the rest at `tl`. We rearrange our inductive case to make `tl` be expressed as -- list.drop (n + 1), which fits out induction hypothesis conditions better. To use the -- rearranging lemma, we must prove that we are "dropping" in bounds, which we supply on-the-fly simp only [←list.cons_nth_le_drop_succ (show n < cb.to_list.length, by simpa using hn.trans_le hn')] at H, -- We prove that parsing our `n`th character, `hd`, would have resulted in a success from -- `parser.digit`, with the appropriate `ℕ` success value. We use this later to simplify the -- unwrapped fold, since `hd` is our head character. have hdigit : digit cb n = done (n + 1) (hd.to_nat - '0'.to_nat), { -- By our necessary condition, we know that `n` is in bounds, and that the `n`th character -- has the necessary "numeric" properties. specialize ho n hn le_rfl, -- We prove an additional result that the conversion of `hd : char` to a `ℕ` would give a -- value `x ≤ 9`, since that is part of the iff statement in the `digit_eq_done` lemma. have : (buffer.read cb ⟨n, hn.trans_le hn'⟩).to_nat - '0'.to_nat ≤ 9, { -- We rewrite the statement to be a statement about characters instead, and split the -- inequality into the case that our hypotheses prove, and that `'0' ≤ '9'`, which -- is true by computation, handled by `dec_trivial`. rw [show 9 = '9'.to_nat - '0'.to_nat, from dec_trivial, tsub_le_tsub_iff_right], { exact ho.right }, { dec_trivial } }, -- We rely on the simplifier, mostly powered by `digit_eq_done`, and supply all the -- necessary conditions of bounds and identities about `hd`. simp [digit_eq_done, this, ←H.left, buffer.nth_le_to_list, hn.trans_le hn', ho] }, -- We now case on whether we've moved to the end of our parse or not. We phrase this as -- casing on either `n + 1 < n` or `n ≤ n + 1`. The more difficult goal comes first. cases lt_or_ge (n + 1) n' with hn'' hn'', { -- Case `n + 1 < n'`. We can directly supply this to our induction hypothesis. -- We now have to prove, for the induction hypothesis, that the characters at positions `k`, -- `n + 1 ≤ k < n'` are "numeric". We already had this for `n ≤ k < n`, so we just rearrange -- the hypotheses we already have. specialize IH hn'' _ H.right, { intros k hk hk', apply ho, exact nat.le_of_succ_le hk' }, -- With the induction hypothesis conditions satisfier, we can extract out a list that -- `parser.digit.many1` would have generated from position `n + 1`, as well as the associated -- property of the list, that it folds into what `nat.of_digits` generates from the -- characters in `cb : char_buffer`, now known as `hd :: tl`. obtain ⟨l, hdl, hvl⟩ := IH, -- Of course, the parsed in list from position `n` would be `l` prepended with the result -- of parsing in `hd`, which is provided explicitly. use (hd.to_nat - '0'.to_nat) :: l, -- We case on `l : list ℕ` so that we can make statements about the fold on `l` cases l with lhd ltl, { -- As before, if `l = []` then `many1` produced a `[]` success, which is a contradiction. simpa using hdl }, -- Case `l = lhd :: ltl`. We can rewrite the fold of the function inside `parser.nat` on -- `lhd :: ltl`, which will be used to rewrite in the goal. simp only [natm, list.foldr] at hvl, -- We also expand the fold in the goal, using the expanded fold from our hypothesis, powered -- by `many1_eq_done` to proceed in the parsing. We know exactly what the next `many` will -- produce from `many1_eq_done_iff_many_eq_done.mp` of our `hdl` hypothesis. Finally, -- we also use `hdigit` to express what the single `parser.digit` result would be at `n`. simp only [natm, hvl, many1_eq_done, hdigit, many1_eq_done_iff_many_eq_done.mp hdl, true_and, and_true, eq_self_iff_true, list.foldr, exists_eq_left'], -- Now our goal is solely about the equality of two different folding functions, one from the -- function defined inside `parser.nat` and the other as `nat.of_digits`, when applied to -- similar list inputs. -- First, we rid ourselves of `n'` by replacing with `n + m + 1`, which allows us to -- simplify the term of how many elements we are keeping using a `list.take`. obtain ⟨m, rfl⟩ : ∃ m, n' = n + m + 1 := nat.exists_eq_add_of_lt hn, -- The following rearrangement lemma is to simplify the `list.take (n' - n)` expression we had have : n + m + 1 - n = m + 1, { rw [add_assoc, tsub_eq_iff_eq_add_of_le, add_comm], exact nat.le_add_right _ _ }, -- We also have to prove what is the `prod.snd` of the result of the fold of a `list (ℕ × ℕ)` -- with the function above. We use this lemma to finish our inductive case. have hpow : ∀ l, (list.foldr (λ (digit : ℕ) (x : ℕ × ℕ), (x.fst + digit * x.snd, x.snd * 10)) (0, 1) l).snd = 10 ^ l.length, { intro l, induction l with hd tl hl, { simp }, { simp [hl, pow_succ, mul_comm] } }, -- We prove that the parsed list of digits `(lhd :: ltl) : list ℕ` must be of length `m` -- which is used later when the `parser.nat` fold places `ltl.length` in the exponent. have hml : ltl.length + 1 = m := by simpa using many1_length_of_done hdl, -- A simplified `list.length (list.take ...)` expression refers to the minimum of the -- underlying length and the amount of elements taken. We know that `m ≤ tl.length`, so -- we provide this auxiliary lemma so that the simplified "take-length" can simplify further have ltll : min m tl.length = m, { -- On the way to proving this, we have to actually show that `m ≤ tl.length`, by showing -- that since `tl` was a subsequence in `cb`, and was retrieved from `n + 1` to `n + m + 1`, -- then since `n + m + 1 ≤ cb.size`, we have that `tl` must be at least `m` in length. simpa [←H.right, le_tsub_iff_right (hn''.trans_le hn').le, add_comm, add_assoc, add_left_comm] using hn' }, -- Finally, we rely on the simplifier. We already expressions of `nat.of_digits` on both -- the LHS and RHS. All that is left to do is to prove that the summand on the LHS is produced -- by the fold of `nat.of_digits` on the RHS of `hd :: tl`. The `nat.of_digits_append` is used -- because of the append that forms from the included `list.reverse`. The lengths of the lists -- are placed in the exponents with `10` as a base, and are combined using `←pow_succ 10`. -- Any complicated expression about list lengths is further simplified by the auxiliary -- lemmas we just proved. Finally, we assist the simplifier by rearranging terms with our -- `n + m + 1 - n = m + 1` proof and `mul_comm`. simp [this, hpow, nat.of_digits_append, mul_comm, ←pow_succ 10, hml, ltll] }, { -- Consider the case that `n' ≤ n + 1`. But then since `n < n' ≤ n + 1`, `n' = n + 1`. obtain rfl : n' = n + 1 := le_antisymm hn'' (nat.succ_le_of_lt hn), -- This means we have only parsed in a single character, so the resulting parsed in list -- is explicitly formed from an expression we can construct from `hd`. use [[hd.to_nat - '0'.to_nat]], -- Our list expression simplifies nicely because it is a fold over a singleton, so we -- do not have to supply any auxiliary lemmas for it, other than what we already know about -- `hd` and the function defined in `parser.nat`. However, we will have to prove that our -- parse ended because of a good reason: either we are out of bounds or we hit a nonnumeric -- character. simp only [many1_eq_done, many_eq_done_nil, digit_eq_fail, natm, and.comm, and.left_comm, hdigit, true_and, mul_one, nat.of_digits_singleton, list.take, exists_eq_left, exists_and_distrib_right, add_tsub_cancel_left, eq_self_iff_true, list.reverse_singleton, zero_add, list.foldr, list.map], -- We take the route of proving that we hit a nonnumeric character, since we already have -- a hypothesis that says that characters at `n'` and past it are nonnumeric. (Note, by now -- we have substituted `n + 1` for `n'. -- We are also asked to provide the error value that our failed parse would report. But -- `digit_eq_fail` already knows what it is, so we can discharge that with an inline `rfl`. refine ⟨_, or.inl ⟨rfl, _⟩⟩, -- The nonnumeric condition looks almost exactly like the hypothesis we already have, so -- we let the simplifier align them for us simpa using hb } } end end nat end parser
7408353636a1631ece47314b137d9b98b32728fd
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/src/Lean/Meta/AbstractMVars.lean
50701eb0178fc72a250e452efe08139c86b3a83e
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
EdAyers/lean4
57ac632d6b0789cb91fab2170e8c9e40441221bd
37ba0df5841bde51dbc2329da81ac23d4f6a4de4
refs/heads/master
1,676,463,245,298
1,660,619,433,000
1,660,619,433,000
183,433,437
1
0
Apache-2.0
1,657,612,672,000
1,556,196,574,000
Lean
UTF-8
Lean
false
false
5,666
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.Basic namespace Lean.Meta structure AbstractMVarsResult where paramNames : Array Name numMVars : Nat expr : Expr deriving Inhabited, BEq namespace AbstractMVars open Std (HashMap) structure State where ngen : NameGenerator lctx : LocalContext mctx : MetavarContext nextParamIdx : Nat := 0 paramNames : Array Name := #[] fvars : Array Expr := #[] lmap : HashMap LMVarId Level := {} emap : HashMap MVarId Expr := {} abbrev M := StateM State instance : MonadMCtx M where getMCtx := return (← get).mctx modifyMCtx f := modify fun s => { s with mctx := f s.mctx } def mkFreshId : M Name := do let s ← get let fresh := s.ngen.curr modify fun s => { s with ngen := s.ngen.next } pure fresh def mkFreshFVarId : M FVarId := return { name := (← mkFreshId) } private partial def abstractLevelMVars (u : Level) : M Level := do if !u.hasMVar then return u else match u with | Level.zero => return u | Level.param _ => return u | Level.succ v => return u.updateSucc! (← abstractLevelMVars v) | Level.max v w => return u.updateMax! (← abstractLevelMVars v) (← abstractLevelMVars w) | Level.imax v w => return u.updateIMax! (← abstractLevelMVars v) (← abstractLevelMVars w) | Level.mvar mvarId => let s ← get let depth := s.mctx.getLevelDepth mvarId; if depth != s.mctx.depth then return u -- metavariables from lower depths are treated as constants else match s.lmap.find? mvarId with | some u => pure u | none => let paramId := Name.mkNum `_abstMVar s.nextParamIdx let u := mkLevelParam paramId modify fun s => { s with nextParamIdx := s.nextParamIdx + 1, lmap := s.lmap.insert mvarId u, paramNames := s.paramNames.push paramId } return u partial def abstractExprMVars (e : Expr) : M Expr := do if !e.hasMVar then return e else match e with | e@(Expr.lit _) => return e | e@(Expr.bvar _) => return e | e@(Expr.fvar _) => return e | e@(Expr.sort u) => return e.updateSort! (← abstractLevelMVars u) | e@(Expr.const _ us) => return e.updateConst! (← us.mapM abstractLevelMVars) | e@(Expr.proj _ _ s) => return e.updateProj! (← abstractExprMVars s) | e@(Expr.app f a) => return e.updateApp! (← abstractExprMVars f) (← abstractExprMVars a) | e@(Expr.mdata _ b) => return e.updateMData! (← abstractExprMVars b) | e@(Expr.lam _ d b _) => return e.updateLambdaE! (← abstractExprMVars d) (← abstractExprMVars b) | e@(Expr.forallE _ d b _) => return e.updateForallE! (← abstractExprMVars d) (← abstractExprMVars b) | e@(Expr.letE _ t v b _) => return e.updateLet! (← abstractExprMVars t) (← abstractExprMVars v) (← abstractExprMVars b) | e@(Expr.mvar mvarId) => let decl := (← getMCtx).getDecl mvarId if decl.depth != (← getMCtx).depth then return e else let eNew ← instantiateMVars e if e != eNew then abstractExprMVars eNew else match (← get).emap.find? mvarId with | some e => return e | none => let type ← abstractExprMVars decl.type let fvarId ← mkFreshFVarId let fvar := mkFVar fvarId; let userName := if decl.userName.isAnonymous then (`x).appendIndexAfter (← get).fvars.size else decl.userName modify fun s => { s with emap := s.emap.insert mvarId fvar, fvars := s.fvars.push fvar, lctx := s.lctx.mkLocalDecl fvarId userName type } return fvar end AbstractMVars /-- Abstract (current depth) metavariables occurring in `e`. The result contains - An array of universe level parameters that replaced universe metavariables occurring in `e`. - The number of (expr) metavariables abstracted. - And an expression of the form `fun (m_1 : A_1) ... (m_k : A_k) => e'`, where `k` equal to the number of (expr) metavariables abstracted, and `e'` is `e` after we replace the metavariables. Example: given `f.{?u} ?m1` where `?m1 : ?m2 Nat`, `?m2 : Type -> Type`. This function returns `{ levels := #[u], size := 2, expr := (fun (m2 : Type -> Type) (m1 : m2 Nat) => f.{u} m1) }` This API can be used to "transport" to a different metavariable context. Given a new metavariable context, we replace the `AbstractMVarsResult.levels` with new fresh universe metavariables, and instantiate the `(m_i : A_i)` in the lambda-expression with new fresh metavariables. Application: we use this method to cache the results of type class resolution. -/ def abstractMVars (e : Expr) : MetaM AbstractMVarsResult := do let e ← instantiateMVars e let (e, s) := AbstractMVars.abstractExprMVars e { mctx := (← getMCtx), lctx := (← getLCtx), ngen := (← getNGen) } setNGen s.ngen setMCtx s.mctx let e := s.lctx.mkLambda s.fvars e pure { paramNames := s.paramNames, numMVars := s.fvars.size, expr := e } def openAbstractMVarsResult (a : AbstractMVarsResult) : MetaM (Array Expr × Array BinderInfo × Expr) := do let us ← a.paramNames.mapM fun _ => mkFreshLevelMVar let e := a.expr.instantiateLevelParamsArray a.paramNames us lambdaMetaTelescope e (some a.numMVars) end Lean.Meta
693973890f4e0561a1dc7c0beb36bd267dc5a0d2
5d166a16ae129621cb54ca9dde86c275d7d2b483
/tests/lean/macro_args.lean
b756cf7d788d1ab279ddcb3a07951d0b6914830d
[ "Apache-2.0" ]
permissive
jcarlson23/lean
b00098763291397e0ac76b37a2dd96bc013bd247
8de88701247f54d325edd46c0eed57aeacb64baf
refs/heads/master
1,611,571,813,719
1,497,020,963,000
1,497,021,515,000
93,882,536
1
0
null
1,497,029,896,000
1,497,029,896,000
null
UTF-8
Lean
false
false
61
lean
#eval ``({pos . line := has_zero.zero, col := 1}).to_raw_fmt
cc763b37938c60b4c6d88dafc82ff9cf2a73dc05
3c9dc4ea6cc92e02634ef557110bde9eae393338
/stage0/src/Init/System/ST.lean
2e57269872a87a9ac0f63fd811d8d3ca75b55d3f
[ "Apache-2.0" ]
permissive
shingtaklam1324/lean4
3d7efe0c8743a4e33d3c6f4adbe1300df2e71492
351285a2e8ad0cef37af05851cfabf31edfb5970
refs/heads/master
1,676,827,679,740
1,610,462,623,000
1,610,552,340,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,435
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.Classical import Init.Control.EState import Init.Control.Reader def EST (ε : Type) (σ : Type) : Type → Type := EStateM ε σ abbrev ST (σ : Type) := EST Empty σ instance (ε σ : Type) : Monad (EST ε σ) := inferInstanceAs (Monad (EStateM _ _)) instance (ε σ : Type) : MonadExceptOf ε (EST ε σ) := inferInstanceAs (MonadExceptOf ε (EStateM _ _)) instance {ε σ : Type} {α : Type} [Inhabited ε] : Inhabited (EST ε σ α) := inferInstanceAs (Inhabited (EStateM _ _ _)) instance (σ : Type) : Monad (ST σ) := inferInstanceAs (Monad (EST _ _)) -- Auxiliary class for inferring the "state" of `EST` and `ST` monads class STWorld (σ : outParam Type) (m : Type → Type) instance {σ m n} [STWorld σ m] [MonadLift m n] : STWorld σ n := ⟨⟩ instance {ε σ} : STWorld σ (EST ε σ) := ⟨⟩ @[noinline, nospecialize] def runEST {ε α : Type} (x : forall (σ : Type), EST ε σ α) : Except ε α := match x Unit () with | EStateM.Result.ok a _ => Except.ok a | EStateM.Result.error ex _ => Except.error ex @[noinline, nospecialize] def runST {α : Type} (x : forall (σ : Type), ST σ α) : α := match x Unit () with | EStateM.Result.ok a _ => a | EStateM.Result.error ex _ => nomatch ex instance {ε σ} : MonadLift (ST σ) (EST ε σ) := ⟨fun x s => match x s with | EStateM.Result.ok a s => EStateM.Result.ok a s | EStateM.Result.error ex _ => nomatch ex⟩ namespace ST /- References -/ constant RefPointed : PointedType.{0} structure Ref (σ : Type) (α : Type) : Type where ref : RefPointed.type h : Nonempty α instance {σ α} [Inhabited α] : Inhabited (Ref σ α) where default := { ref := RefPointed.val, h := Nonempty.intro arbitrary } namespace Prim set_option pp.all true /- Auxiliary definition for showing that `ST σ α` is inhabited when we have a `Ref σ α` -/ private noncomputable def inhabitedFromRef {σ α} (r : Ref σ α) : ST σ α := let inh : Inhabited α := Classical.inhabitedOfNonempty r.h pure arbitrary @[extern "lean_st_mk_ref"] constant mkRef {σ α} (a : α) : ST σ (Ref σ α) := pure { ref := RefPointed.val, h := Nonempty.intro a } @[extern "lean_st_ref_get"] constant Ref.get {σ α} (r : @& Ref σ α) : ST σ α := inhabitedFromRef r @[extern "lean_st_ref_set"] constant Ref.set {σ α} (r : @& Ref σ α) (a : α) : ST σ Unit @[extern "lean_st_ref_swap"] constant Ref.swap {σ α} (r : @& Ref σ α) (a : α) : ST σ α := inhabitedFromRef r @[extern "lean_st_ref_take"] unsafe constant Ref.take {σ α} (r : @& Ref σ α) : ST σ α := inhabitedFromRef r @[extern "lean_st_ref_ptr_eq"] constant Ref.ptrEq {σ α} (r1 r2 : @& Ref σ α) : ST σ Bool @[inline] unsafe def Ref.modifyUnsafe {σ α : Type} (r : Ref σ α) (f : α → α) : ST σ Unit := do let v ← Ref.take r Ref.set r (f v) @[inline] unsafe def Ref.modifyGetUnsafe {σ α β : Type} (r : Ref σ α) (f : α → β × α) : ST σ β := do let v ← Ref.take r let (b, a) := f v Ref.set r a pure b @[implementedBy Ref.modifyUnsafe] def Ref.modify {σ α : Type} (r : Ref σ α) (f : α → α) : ST σ Unit := do let v ← Ref.get r Ref.set r (f v) @[implementedBy Ref.modifyGetUnsafe] def Ref.modifyGet {σ α β : Type} (r : Ref σ α) (f : α → β × α) : ST σ β := do let v ← Ref.get r let (b, a) := f v Ref.set r a pure b end Prim section variables {σ : Type} {m : Type → Type} [Monad m] [MonadLiftT (ST σ) m] @[inline] def mkRef {α : Type} (a : α) : m (Ref σ α) := liftM <| Prim.mkRef a @[inline] def Ref.get {α : Type} (r : Ref σ α) : m α := liftM <| Prim.Ref.get r @[inline] def Ref.set {α : Type} (r : Ref σ α) (a : α) : m Unit := liftM <| Prim.Ref.set r a @[inline] def Ref.swap {α : Type} (r : Ref σ α) (a : α) : m α := liftM <| Prim.Ref.swap r a @[inline] unsafe def Ref.take {α : Type} (r : Ref σ α) : m α := liftM <| Prim.Ref.take r @[inline] def Ref.ptrEq {α : Type} (r1 r2 : Ref σ α) : m Bool := liftM <| Prim.Ref.ptrEq r1 r2 @[inline] def Ref.modify {α : Type} (r : Ref σ α) (f : α → α) : m Unit := liftM <| Prim.Ref.modify r f @[inline] def Ref.modifyGet {α : Type} {β : Type} (r : Ref σ α) (f : α → β × α) : m β := liftM <| Prim.Ref.modifyGet r f end end ST
60367fa9ddfdba7864e753d27f8a7d2a5eb9a3df
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/withReducibleAndInstancesCrash.lean
738e5bf59ae17932c5b8ed93cf6fadde324a97b7
[ "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
467
lean
import Lean @[reducible] def foo (x : Nat) := x + 1 @[reducible] def bla (x y : Nat) := foo (foo x) + foo (foo x) @[reducible] def boo (x y : Nat) := foo (bla (foo x) (foo y) * bla (foo y) (foo x) * bla (foo y) (foo x)) open Lean open Lean.Meta def tst : MetaM Unit := do let c ← getConstInfo `boo lambdaTelescope c.value! fun xs b => do withReducibleAndInstances do trace[Meta.debug] "b: {← reduce b}" set_option trace.Meta.debug true #eval tst
453c9802384c9a1e8a3600637bafbefc4f31fd9c
a4673261e60b025e2c8c825dfa4ab9108246c32e
/stage0/src/Lean/Meta/RecursorInfo.lean
ce2104c3ef70863a1be1181daa7eefea71b0b646
[ "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,036
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.AuxRecursor import Lean.Util.FindExpr import Lean.Meta.ExprDefEq namespace Lean.Meta def casesOnSuffix := "casesOn" def recOnSuffix := "recOn" def brecOnSuffix := "brecOn" def binductionOnSuffix := "binductionOn" def mkCasesOnName (indDeclName : Name) : Name := Name.mkStr indDeclName casesOnSuffix def mkRecOnName (indDeclName : Name) : Name := Name.mkStr indDeclName recOnSuffix def mkBRecOnName (indDeclName : Name) : Name := Name.mkStr indDeclName brecOnSuffix def mkBInductionOnName (indDeclName : Name) : Name := Name.mkStr indDeclName binductionOnSuffix inductive RecursorUnivLevelPos := | motive -- marks where the universe of the motive should go | majorType (idx : Nat) -- marks where the #idx universe of the major premise type goes instance : ToString RecursorUnivLevelPos := ⟨fun | RecursorUnivLevelPos.motive => "<motive-univ>" | RecursorUnivLevelPos.majorType idx => toString idx⟩ structure RecursorInfo := (recursorName : Name) (typeName : Name) (univLevelPos : List RecursorUnivLevelPos) (depElim : Bool) (recursive : Bool) (numArgs : Nat) -- Total number of arguments (majorPos : Nat) (paramsPos : List (Option Nat)) -- Position of the recursor parameters in the major premise, instance implicit arguments are `none` (indicesPos : List Nat) -- Position of the recursor indices in the major premise (produceMotive : List Bool) -- If the i-th element is true then i-th minor premise produces the motive namespace RecursorInfo def numParams (info : RecursorInfo) : Nat := info.paramsPos.length def numIndices (info : RecursorInfo) : Nat := info.indicesPos.length def motivePos (info : RecursorInfo) : Nat := info.numParams def firstIndexPos (info : RecursorInfo) : Nat := info.majorPos - info.numIndices def isMinor (info : RecursorInfo) (pos : Nat) : Bool := if pos ≤ info.motivePos then false else if info.firstIndexPos ≤ pos && pos ≤ info.majorPos then false else true def numMinors (info : RecursorInfo) : Nat := let r := info.numArgs let r := r - info.motivePos - 1 r - (info.majorPos + 1 - info.firstIndexPos) instance : ToString RecursorInfo := ⟨fun info => "{\n" ++ " name := " ++ toString info.recursorName ++ "\n" ++ " type := " ++ toString info.typeName ++ "\n" ++ " univs := " ++ toString info.univLevelPos ++ "\n" ++ " depElim := " ++ toString info.depElim ++ "\n" ++ " recursive := " ++ toString info.recursive ++ "\n" ++ " numArgs := " ++ toString info.numArgs ++ "\n" ++ " numParams := " ++ toString info.numParams ++ "\n" ++ " numIndices := " ++ toString info.numIndices ++ "\n" ++ " numMinors := " ++ toString info.numMinors ++ "\n" ++ " major := " ++ toString info.majorPos ++ "\n" ++ " motive := " ++ toString info.motivePos ++ "\n" ++ " paramsAtMajor := " ++ toString info.paramsPos ++ "\n" ++ " indicesAtMajor := " ++ toString info.indicesPos ++ "\n" ++ " produceMotive := " ++ toString info.produceMotive ++ "\n" ++ "}"⟩ end RecursorInfo private def mkRecursorInfoForKernelRec (declName : Name) (val : RecursorVal) : MetaM RecursorInfo := do let ival ← getConstInfoInduct val.getInduct let numLParams := ival.lparams.length let univLevelPos := (List.range numLParams).map RecursorUnivLevelPos.majorType let univLevelPos := if val.lparams.length == numLParams then univLevelPos else RecursorUnivLevelPos.motive :: univLevelPos let produceMotive := List.replicate val.nminors true let paramsPos := (List.range val.nparams).map some let indicesPos := (List.range val.nindices).map fun pos => val.nparams + pos let numArgs := val.nindices + val.nparams + val.nminors + val.nmotives + 1 pure { recursorName := declName, typeName := val.getInduct, univLevelPos := univLevelPos, majorPos := val.getMajorIdx, depElim := true, recursive := ival.isRec, produceMotive := produceMotive, paramsPos := paramsPos, indicesPos := indicesPos, numArgs := numArgs } private def getMajorPosIfAuxRecursor? (declName : Name) (majorPos? : Option Nat) : MetaM (Option Nat) := if majorPos?.isSome then pure majorPos? else do let env ← getEnv if !isAuxRecursor env declName then pure none else match declName with | Name.str p s _ => if s != recOnSuffix && s != casesOnSuffix && s != brecOnSuffix then pure none else do let val ← getConstInfoRec (mkRecName p) pure $ some (val.nparams + val.nindices + (if s == casesOnSuffix then 1 else val.nmotives)) | _ => pure none private def checkMotive (declName : Name) (motive : Expr) (motiveArgs : Array Expr) : MetaM Unit := unless motive.isFVar && motiveArgs.all Expr.isFVar do throwError! "invalid user defined recursor '{declName}', result type must be of the form (C t), where C is a bound variable, and t is a (possibly empty) sequence of bound variables" /- Compute number of parameters for (user-defined) recursor. We assume a parameter is anything that occurs before the motive -/ private partial def getNumParams (xs : Array Expr) (motive : Expr) (i : Nat) : Nat := if h : i < xs.size then let x := xs.get ⟨i, h⟩ if motive == x then i else getNumParams xs motive (i+1) else i private def getMajorPosDepElim (declName : Name) (majorPos? : Option Nat) (xs : Array Expr) (motive : Expr) (motiveArgs : Array Expr) : MetaM (Expr × Nat × Bool) := do match majorPos? with | some majorPos => if h : majorPos < xs.size then let major := xs.get ⟨majorPos, h⟩ let depElim := motiveArgs.contains major pure (major, majorPos, depElim) else throwError! "invalid major premise position for user defined recursor, recursor has only {xs.size} arguments" | none => do if motiveArgs.isEmpty then throwError! "invalid user defined recursor, '{declName}' does not support dependent elimination, and position of the major premise was not specified (solution: set attribute '[recursor <pos>]', where <pos> is the position of the major premise)" let major := motiveArgs.back match xs.getIdx? major with | some majorPos => pure (major, majorPos, true) | none => throwError! "ill-formed recursor '{declName}'" private def getParamsPos (declName : Name) (xs : Array Expr) (numParams : Nat) (Iargs : Array Expr) : MetaM (List (Option Nat)) := do let mut paramsPos := #[] for i in [:numParams] do let x := xs[i] match (← Iargs.findIdxM? fun Iarg => isDefEq Iarg x) with | some j => paramsPos := paramsPos.push (some j) | none => do let localDecl ← getLocalDecl x.fvarId! if localDecl.binderInfo.isInstImplicit then paramsPos := paramsPos.push none else throwError!"invalid user defined recursor '{declName}', type of the major premise does not contain the recursor parameter" pure paramsPos.toList private def getIndicesPos (declName : Name) (xs : Array Expr) (majorPos numIndices : Nat) (Iargs : Array Expr) : MetaM (List Nat) := do let mut indicesPos := #[] for i in [:numIndices] do let i := majorPos - numIndices + i let x := xs[i] match (← Iargs.findIdxM? fun Iarg => isDefEq Iarg x) with | some j => indicesPos := indicesPos.push j | none => throwError! "invalid user defined recursor '{declName}', type of the major premise does not contain the recursor index" pure indicesPos.toList private def getMotiveLevel (declName : Name) (motiveResultType : Expr) : MetaM Level := match motiveResultType with | Expr.sort u@(Level.zero _) _ => pure u | Expr.sort u@(Level.param _ _) _ => pure u | _ => throwError! "invalid user defined recursor '{declName}', motive result sort must be Prop or (Sort u) where u is a universe level parameter" private def getUnivLevelPos (declName : Name) (lparams : List Name) (motiveLvl : Level) (Ilevels : List Level) : MetaM (List RecursorUnivLevelPos) := do let Ilevels := Ilevels.toArray let mut univLevelPos := #[] for p in lparams do if motiveLvl == mkLevelParam p then univLevelPos := univLevelPos.push RecursorUnivLevelPos.motive else match Ilevels.findIdx? fun u => u == mkLevelParam p with | some i => univLevelPos := univLevelPos.push (RecursorUnivLevelPos.majorType i) | none => throwError! "invalid user defined recursor '{declName}', major premise type does not contain universe level parameter '{p}'" pure univLevelPos.toList private def getProduceMotiveAndRecursive (xs : Array Expr) (numParams numIndices majorPos : Nat) (motive : Expr) : MetaM (List Bool × Bool) := do let mut produceMotive := #[] let mut recursor := false for i in [:xs.size] do if i < numParams + 1 then continue --skip parameters and motive if majorPos - numIndices ≤ i && i ≤ majorPos then continue -- skip indices and major premise -- process minor premise let x := xs[i] let xType ← inferType x (produceMotive, recursor) ← forallTelescopeReducing xType fun minorArgs minorResultType => minorResultType.withApp fun res _ => do let produceMotive := produceMotive.push (res == motive) let recursor ← if recursor then pure recursor else minorArgs.anyM fun minorArg => do let minorArgType ← inferType minorArg pure (minorArgType.find? fun e => e == motive).isSome pure (produceMotive, recursor) pure (produceMotive.toList, recursor) private def checkMotiveResultType (declName : Name) (motiveArgs : Array Expr) (motiveResultType : Expr) (motiveTypeParams : Array Expr) : MetaM Unit := do if !motiveResultType.isSort || motiveArgs.size != motiveTypeParams.size then throwError! "invalid user defined recursor '{declName}', motive must have a type of the form (C : Pi (i : B A), I A i -> Type), where A is (possibly empty) sequence of variables (aka parameters), (i : B A) is a (possibly empty) telescope (aka indices), and I is a constant" private def mkRecursorInfoAux (cinfo : ConstantInfo) (majorPos? : Option Nat) : MetaM RecursorInfo := do let declName := cinfo.name let majorPos? ← getMajorPosIfAuxRecursor? declName majorPos? forallTelescopeReducing cinfo.type fun xs type => type.withApp fun motive motiveArgs => do checkMotive declName motive motiveArgs let numParams := getNumParams xs motive 0 let (major, majorPos, depElim) ← getMajorPosDepElim declName majorPos? xs motive motiveArgs let numIndices := if depElim then motiveArgs.size - 1 else motiveArgs.size if majorPos < numIndices then throwError! "invalid user defined recursor '{declName}', indices must occur before major premise" let majorType ← inferType major majorType.withApp fun I Iargs => match I with | Expr.const Iname Ilevels _ => do let paramsPos ← getParamsPos declName xs numParams Iargs let indicesPos ← getIndicesPos declName xs majorPos numIndices Iargs let motiveType ← inferType motive forallTelescopeReducing motiveType fun motiveTypeParams motiveResultType => do checkMotiveResultType declName motiveArgs motiveResultType motiveTypeParams let motiveLvl ← getMotiveLevel declName motiveResultType let univLevelPos ← getUnivLevelPos declName cinfo.lparams motiveLvl Ilevels let (produceMotive, recursive) ← getProduceMotiveAndRecursive xs numParams numIndices majorPos motive pure { recursorName := declName, typeName := Iname, univLevelPos := univLevelPos, majorPos := majorPos, depElim := depElim, recursive := recursive, produceMotive := produceMotive, paramsPos := paramsPos, indicesPos := indicesPos, numArgs := xs.size } | _ => throwError! "invalid user defined recursor '{declName}', type of the major premise must be of the form (I ...), where I is a constant" private def syntaxToMajorPos (stx : Syntax) : Except String Nat := match stx with | Syntax.node _ args => if args.size == 0 then Except.error "unexpected kind of argument" else match args[0].isNatLit? with | some idx => if idx == 0 then Except.error "major premise position must be greater than 0" else pure (idx - 1) | none => Except.error "unexpected kind of argument" | _ => Except.error "unexpected kind of argument" private def mkRecursorInfoCore (declName : Name) (majorPos? : Option Nat := none) : MetaM RecursorInfo := do let cinfo ← getConstInfo declName match cinfo with | ConstantInfo.recInfo val => mkRecursorInfoForKernelRec declName val | _ => mkRecursorInfoAux cinfo majorPos? builtin_initialize recursorAttribute : ParametricAttribute Nat ← registerParametricAttribute { name := `recursor, descr := "user defined recursor, numerical parameter specifies position of the major premise", getParam := fun _ stx => ofExcept $ syntaxToMajorPos stx, afterSet := fun declName majorPos => do (mkRecursorInfoCore declName (some majorPos)).run' pure () } def getMajorPos? (env : Environment) (declName : Name) : Option Nat := recursorAttribute.getParam env declName def mkRecursorInfo (declName : Name) (majorPos? : Option Nat := none) : MetaM RecursorInfo := do let cinfo ← getConstInfo declName match cinfo with | ConstantInfo.recInfo val => mkRecursorInfoForKernelRec declName val | _ => match majorPos? with | none => do mkRecursorInfoAux cinfo (getMajorPos? (← getEnv) declName) | _ => mkRecursorInfoAux cinfo majorPos? end Lean.Meta
f768313926870797ecb2ffcdafe36deba99f3504
e0f9ba56b7fedc16ef8697f6caeef5898b435143
/src/tactic/mk_iff_of_inductive_prop.lean
0541df729ff3810554657bbd115c84dd33f316cb
[ "Apache-2.0" ]
permissive
anrddh/mathlib
6a374da53c7e3a35cb0298b0cd67824efef362b4
a4266a01d2dcb10de19369307c986d038c7bb6a6
refs/heads/master
1,656,710,827,909
1,589,560,456,000
1,589,560,456,000
264,271,800
0
0
Apache-2.0
1,589,568,062,000
1,589,568,061,000
null
UTF-8
Lean
false
false
8,154
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 Generation function for iff rules for inductives, like for `list.chain`: ∀{α : Type*} (R : α → α → Prop) (a : α) (l : list α), chain R a l ↔ l = [] ∨ ∃{b : α} {l' : list α}, R a b ∧ chain R b l ∧ l = b :: l' -/ import tactic.core namespace tactic open tactic expr meta def mk_iff (e₀ : expr) (e₁ : expr) : expr := `(%%e₀ ↔ %%e₁) meta def select : ℕ → ℕ → tactic unit | 0 0 := skip | 0 (n + 1) := left >> skip | (m + 1) (n + 1) := right >> select m n | (n + 1) 0 := failure /-- `compact_relation bs as_ps`: Produce a relation of the form: R as := ∃ bs, Λ_i a_i = p_i[bs] This relation is user visible, so we compact it by removing each `b_j` where a `p_i = b_j`, and hence `a_i = b_j`. We need to take care when there are `p_i` and `p_j` with `p_i = p_j = b_k`. TODO: this is copied from Lean's `coinductive_predicates.lean`, export it there. -/ private meta def compact_relation : list expr → list (expr × expr) → list (option expr) × list (expr × expr) | [] ps := ([], ps) | (b :: bs) ps := match ps.span (λap:expr × expr, ¬ ap.2 =ₐ b) with | (_, []) := let (bs, ps) := compact_relation bs ps in (b::bs, ps) | (ps₁, list.cons (a, _) ps₂) := let i := a.instantiate_local b.local_uniq_name, (bs, ps) := compact_relation (bs.map i) ((ps₁ ++ ps₂).map (λ⟨a, p⟩, (a, i p))) in (none :: bs, ps) end meta def constr_to_prop (univs : list level) (g : list expr) (idxs : list expr) (c : name) : tactic ((list (option expr) × (expr ⊕ ℕ)) × expr) := do e ← get_env, decl ← get_decl c, some type' ← return $ decl.instantiate_type_univ_params univs, type ← drop_pis g type', (args, res) ← mk_local_pis type, let idxs_inst := res.get_app_args.drop g.length, let (bs, eqs) := compact_relation args (idxs.zip idxs_inst), let bs' := bs.filter_map id, eqs ← eqs.mmap (λ⟨idx, inst⟩, do let ty := idx.local_type, inst_ty ← infer_type inst, sort u ← infer_type ty, (is_def_eq ty inst_ty >> return ((const `eq [u] : expr) ty idx inst)) <|> return ((const `heq [u] : expr) ty idx inst_ty inst)), (n, r) ← match bs', eqs with | [], [] := return (sum.inr 0, mk_true) | _, [] := do let t : expr := bs'.ilast.local_type, sort l ← infer_type t, if l = level.zero then do r ← mk_exists_lst bs'.init t, return (sum.inl bs'.ilast, r) else do r ← mk_exists_lst bs' mk_true, return (sum.inr 0, r) | _, _ := do r ← mk_exists_lst bs' (mk_and_lst eqs), return (sum.inr eqs.length, r) end, return ((bs, n), r) private meta def to_cases (s : list $ list (option expr) × (expr ⊕ ℕ)) : tactic unit := do h ← intro1, i ← induction h, focus ((s.zip i).enum.map $ λ⟨p, (shape, t), _, vars, _⟩, do let si := (shape.zip vars).filter_map (λ⟨c, v⟩, c >>= λ _, some v), select p (s.length - 1), match t with | sum.inl e := do si.init.mmap' existsi, some v ← return $ vars.nth (shape.length - 1), exact v | sum.inr n := do si.mmap' existsi, iterate_exactly (n - 1) (split >> constructor >> skip) >> constructor >> skip end, done), done private def list_option_merge {α : Type*} {β : Type*} : list (option α) → list β → list (option β) | [] _ := [] | (none :: xs) ys := none :: list_option_merge xs ys | (some a :: xs) (y :: ys) := some y :: list_option_merge xs ys | (some a :: xs) [] := [] private meta def to_inductive (cs : list name) (gs : list expr) (s : list (list (option expr) × (expr ⊕ ℕ))) (h : expr) : tactic unit := match s.length with | 0 := induction h >> skip | (n + 1) := do r ← elim_gen_sum n h, focus ((cs.zip (r.zip s)).map $ λ⟨constr_name, h, bs, e⟩, do let n := (bs.filter_map id).length, match e with | sum.inl e := elim_gen_prod (n - 1) h [] [] >> skip | sum.inr 0 := do (hs, h, _) ← elim_gen_prod n h [] [], clear h | sum.inr (e + 1) := do (hs, h, _) ← elim_gen_prod n h [] [], (es, eq, _) ← elim_gen_prod e h [] [], let es := es ++ [eq], /- `es.mmap' subst`: fails when we have dependent equalities (heq). `subst will change the dependent hypotheses, so that the uniq local names in `es` are wrong afterwards. Instead we revert them and pull them out one by one -/ revert_lst es, es.mmap' (λ_, intro1 >>= subst) end, ctxt ← local_context, let gs := ctxt.take gs.length, let hs := (ctxt.reverse.take n).reverse, let m := gs.map some ++ list_option_merge bs hs, args ← m.mmap (λa, match a with some v := return v | none := mk_mvar end), c ← mk_const constr_name, exact (c.mk_app args), done), done end /-- `mk_iff_of_inductive_prop i r` makes an iff rule for the inductively defined proposition `i`. The new rule `r` has the shape `∀ps is, i as ↔ ⋁_j, ∃cs, is = cs`, where `ps` are the type parameters, `is` are the indices, `j` ranges over all possible constructors, the `cs` are the parameters for each constructors, the equalities `is = cs` are the instantiations for each constructor for each of the indices to the inductive type `i`. In each case, we remove constructor parameters (i.e. `cs`) when the corresponding equality would be just `c = i` for some index `i`. For example: `mk_iff_of_inductive_prop` on `list.chain` produces: ```lean ∀ {α : Type*} (R : α → α → Prop) (a : α) (l : list α), chain R a l ↔ l = [] ∨ ∃{b : α} {l' : list α}, R a b ∧ chain R b l ∧ l = b :: l' ``` -/ meta def mk_iff_of_inductive_prop (i : name) (r : name) : tactic unit := do e ← get_env, guard (e.is_inductive i), let constrs := e.constructors_of i, let params := e.inductive_num_params i, let indices := e.inductive_num_indices i, let rec := match e.recursor_of i with some rec := rec | none := i.append `rec end, decl ← get_decl i, let type := decl.type, let univ_names := decl.univ_params, let univs := univ_names.map level.param, /- we use these names for our universe parameters, maybe we should construct a copy of them using uniq_name -/ (g, `(Prop)) ← mk_local_pis type | fail "Inductive type is not a proposition", let lhs := (const i univs).mk_app g, shape_rhss ← constrs.mmap (constr_to_prop univs (g.take params) (g.drop params)), let shape := shape_rhss.map prod.fst, let rhss := shape_rhss.map prod.snd, add_theorem_by r univ_names ((mk_iff lhs (mk_or_lst rhss)).pis g) (do gs ← intro_lst (g.map local_pp_name), split, focus [to_cases shape, intro1 >>= to_inductive constrs (gs.take params) shape]), skip end tactic section setup_tactic_parser /-- `mk_iff_of_inductive_prop i r` makes an iff rule for the inductively defined proposition `i`. The new rule `r` has the shape `∀ps is, i as ↔ ⋁_j, ∃cs, is = cs`, where `ps` are the type parameters, `is` are the indices, `j` ranges over all possible constructors, the `cs` are the parameters for each constructors, the equalities `is = cs` are the instantiations for each constructor for each of the indices to the inductive type `i`. In each case, we remove constructor parameters (i.e. `cs`) when the corresponding equality would be just `c = i` for some index `i`. For example: `mk_iff_of_inductive_prop` on `list.chain` produces: ```lean ∀ {α : Type*} (R : α → α → Prop) (a : α) (l : list α), chain R a l ↔ l = [] ∨ ∃{b : α} {l' : list α}, R a b ∧ chain R b l ∧ l = b :: l' ``` -/ @[user_command] meta def mk_iff_of_inductive_prop_cmd (_ : parse (tk "mk_iff_of_inductive_prop")) : parser unit := do i ← ident, r ← ident, tactic.mk_iff_of_inductive_prop i r add_tactic_doc { name := "mk_iff_of_inductive_prop", category := doc_category.cmd, decl_names := [``mk_iff_of_inductive_prop_cmd], tags := ["logic", "environment"] } end
8b2c64232532a03691115c068bc77edc369084e9
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/tactic/interval_cases.lean
5fd7bfac4410fac3541ed9ea7fb99dd5af66d511
[ "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
11,376
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import tactic.fin_cases import data.fin.interval -- These imports aren't required to compile this file, import data.int.interval -- but they are needed at the use site for the tactic to work import data.pnat.interval -- (on values of type fin/int/pnat) import data.pnat.basic /-! # Case bash on variables in finite intervals This file provides the tactic `interval_cases`. `interval_cases n` will: 1. inspect hypotheses looking for lower and upper bounds of the form `a ≤ n` and `n < b` (in `ℕ`, `ℤ`, `ℕ+`, bounds of the form `a < n` and `n ≤ b` are also allowed), and also makes use of lower and upper bounds found via `le_top` and `bot_le` (so for example if `n : ℕ`, then the bound `0 ≤ n` is automatically found). 2. call `fin_cases` on the synthesised hypothesis `n ∈ set.Ico a b`, assuming an appropriate `fintype` instance can be found for the type of `n`. The variable `n` can belong to any type `α`, with the following restrictions: * only bounds on which `expr.to_rat` succeeds will be considered "explicit" (TODO: generalise this?) * an instance of `decidable_eq α` is available, * an explicit lower bound can be found among the hypotheses, or from `bot_le n`, * an explicit upper bound can be found among the hypotheses, or from `le_top n`, * if multiple bounds are located, an instance of `linear_order α` is available, and * an instance of `fintype set.Ico l u` is available for the relevant bounds. You can also explicitly specify a lower and upper bound to use, as `interval_cases using hl hu`, where the hypotheses should be of the form `hl : a ≤ n` and `hu : n < b`. In that case, `interval_cases` calls `fin_cases` on the resulting hypothesis `h : n ∈ set.Ico a b`. -/ open set namespace tactic namespace interval_cases /-- If `e` easily implies `(%%n < %%b)` for some explicit `b`, return that proof. -/ -- We use `expr.to_rat` merely to decide if an `expr` is an explicit number. -- It would be more natural to use `expr.to_int`, but that hasn't been implemented. meta def gives_upper_bound (n e : expr) : tactic expr := do t ← infer_type e >>= instantiate_mvars, match t with | `(%%n' < %%b) := do guard (n = n'), b ← b.to_rat, return e | `(%%b > %%n') := do guard (n = n'), b ← b.to_rat, return e | `(%%n' ≤ %%b) := do guard (n = n'), b ← b.to_rat, tn ← infer_type n >>= instantiate_mvars, match tn with | `(ℕ) := to_expr ``(nat.lt_add_one_iff.mpr %%e) | `(ℕ+) := to_expr ``(pnat.lt_add_one_iff.mpr %%e) | `(ℤ) := to_expr ``(int.lt_add_one_iff.mpr %%e) | _ := failed end | `(%%b ≥ %%n') := do guard (n = n'), b ← b.to_rat, tn ← infer_type n >>= instantiate_mvars, match tn with | `(ℕ) := to_expr ``(nat.lt_add_one_iff.mpr %%e) | `(ℕ+) := to_expr ``(pnat.lt_add_one_iff.mpr %%e) | `(ℤ) := to_expr ``(int.lt_add_one_iff.mpr %%e) | _ := failed end | _ := failed end /-- If `e` easily implies `(%%n ≥ %%b)` for some explicit `b`, return that proof. -/ meta def gives_lower_bound (n e : expr) : tactic expr := do t ← infer_type e >>= instantiate_mvars, match t with | `(%%n' ≥ %%b) := do guard (n = n'), b ← b.to_rat, return e | `(%%b ≤ %%n') := do guard (n = n'), b ← b.to_rat, return e | `(%%n' > %%b) := do guard (n = n'), b ← b.to_rat, tn ← infer_type n >>= instantiate_mvars, match tn with | `(ℕ) := to_expr ``(nat.add_one_le_iff.mpr %%e) | `(ℕ+) := to_expr ``(pnat.add_one_le_iff.mpr %%e) | `(ℤ) := to_expr ``(int.add_one_le_iff.mpr %%e) | _ := failed end | `(%%b < %%n') := do guard (n = n'), b ← b.to_rat, tn ← infer_type n >>= instantiate_mvars, match tn with | `(ℕ) := to_expr ``(nat.add_one_le_iff.mpr %%e) | `(ℕ+) := to_expr ``(pnat.add_one_le_iff.mpr %%e) | `(ℤ) := to_expr ``(int.add_one_le_iff.mpr %%e) | _ := failed end | _ := failed end /-- Combine two upper bounds. -/ meta def combine_upper_bounds : option expr → option expr → tactic (option expr) | none none := return none | (some prf) none := return $ some prf | none (some prf) := return $ some prf | (some prf₁) (some prf₂) := do option.some <$> to_expr ``(lt_min %%prf₁ %%prf₂) /-- Combine two lower bounds. -/ meta def combine_lower_bounds : option expr → option expr → tactic (option expr) | none none := return $ none | (some prf) none := return $ some prf | none (some prf) := return $ some prf | (some prf₁) (some prf₂) := do option.some <$> to_expr ``(max_le %%prf₂ %%prf₁) /-- Inspect a given expression, using it to update a set of upper and lower bounds on `n`. -/ meta def update_bounds (n : expr) (bounds : option expr × option expr) (e : expr) : tactic (option expr × option expr) := do nlb ← try_core $ gives_lower_bound n e, nub ← try_core $ gives_upper_bound n e, clb ← combine_lower_bounds bounds.1 nlb, cub ← combine_upper_bounds bounds.2 nub, return (clb, cub) /-- Attempt to find a lower bound for the variable `n`, by evaluating `bot_le n`. -/ meta def initial_lower_bound (n : expr) : tactic expr := do e ← to_expr ``(@bot_le _ _ _ %%n), t ← infer_type e, match t with | `(%%b ≤ %%n) := do return e | _ := failed end /-- Attempt to find an upper bound for the variable `n`, by evaluating `le_top n`. -/ meta def initial_upper_bound (n : expr) : tactic expr := do e ← to_expr ``(@le_top _ _ _ %%n), match e with | `(%%n ≤ %%b) := do tn ← infer_type n, e ← match tn with | `(ℕ) := to_expr ``(nat.add_one_le_iff.mpr %%e) | `(ℕ+) := to_expr ``(pnat.add_one_le_iff.mpr %%e) | `(ℤ) := to_expr ``(int.add_one_le_iff.mpr %%e) | _ := failed end, return e | _ := failed end /-- Inspect the local hypotheses for upper and lower bounds on a variable `n`. -/ meta def get_bounds (n : expr) : tactic (expr × expr) := do hl ← try_core (initial_lower_bound n), hu ← try_core (initial_upper_bound n), lc ← local_context, r ← lc.mfoldl (update_bounds n) (hl, hu), match r with | (_, none) := fail "No upper bound located." | (none, _) := fail "No lower bound located." | (some lb_prf, some ub_prf) := return (lb_prf, ub_prf) end /-- The finset of elements of a set `s` for which we have `fintype s`. -/ def set_elems {α} [decidable_eq α] (s : set α) [fintype s] : finset α := (fintype.elems s).image subtype.val /-- Each element of `s` is a member of `set_elems s`. -/ lemma mem_set_elems {α} [decidable_eq α] (s : set α) [fintype s] {a : α} (h : a ∈ s) : a ∈ set_elems s := finset.mem_image.2 ⟨⟨a, h⟩, fintype.complete _, rfl⟩ end interval_cases open interval_cases /-- Call `fin_cases` on membership of the finset built from an `Ico` interval corresponding to a lower and an upper bound. Here `hl` should be an expression of the form `a ≤ n`, for some explicit `a`, and `hu` should be of the form `n < b`, for some explicit `b`. By default `interval_cases_using` automatically generates a name for the new hypothesis. The name can be specified via the optional argument `n`. -/ meta def interval_cases_using (hl hu : expr) (n : option name) : tactic unit := to_expr ``(mem_set_elems (Ico _ _) ⟨%%hl, %%hu⟩) >>= (if hn : n.is_some then note (option.get hn) else note_anon none) >>= fin_cases_at none none setup_tactic_parser namespace interactive local postfix (name := parser.optional) `?`:9001 := optional /-- `interval_cases n` searches for upper and lower bounds on a variable `n`, and if bounds are found, splits into separate cases for each possible value of `n`. As an example, in ``` example (n : ℕ) (w₁ : n ≥ 3) (w₂ : n < 5) : n = 3 ∨ n = 4 := begin interval_cases n, all_goals {simp} end ``` after `interval_cases n`, the goals are `3 = 3 ∨ 3 = 4` and `4 = 3 ∨ 4 = 4`. You can also explicitly specify a lower and upper bound to use, as `interval_cases using hl hu`. The hypotheses should be in the form `hl : a ≤ n` and `hu : n < b`, in which case `interval_cases` calls `fin_cases` on the resulting fact `n ∈ set.Ico a b`. You can specify a name `h` for the new hypothesis, as `interval_cases n with h` or `interval_cases n using hl hu with h`. -/ meta def interval_cases (n : parse texpr?) (bounds : parse (tk "using" *> (prod.mk <$> ident <*> ident))?) (lname : parse (tk "with" *> ident)?) : tactic unit := do if h : n.is_some then (do guard bounds.is_none <|> fail "Do not use the `using` keyword if specifying the variable explicitly.", n ← to_expr (option.get h), (hl, hu) ← get_bounds n, tactic.interval_cases_using hl hu lname) else if h' : bounds.is_some then (do [hl, hu] ← [(option.get h').1, (option.get h').2].mmap get_local, tactic.interval_cases_using hl hu lname) else fail ("Call `interval_cases n` (specifying a variable), or `interval_cases lb ub`\n" ++ "(specifying a lower bound and upper bound on the same variable).") /-- `interval_cases n` searches for upper and lower bounds on a variable `n`, and if bounds are found, splits into separate cases for each possible value of `n`. As an example, in ``` example (n : ℕ) (w₁ : n ≥ 3) (w₂ : n < 5) : n = 3 ∨ n = 4 := begin interval_cases n, all_goals {simp} end ``` after `interval_cases n`, the goals are `3 = 3 ∨ 3 = 4` and `4 = 3 ∨ 4 = 4`. You can also explicitly specify a lower and upper bound to use, as `interval_cases using hl hu`. The hypotheses should be in the form `hl : a ≤ n` and `hu : n < b`, in which case `interval_cases` calls `fin_cases` on the resulting fact `n ∈ set.Ico a b`. You can also explicitly specify a name to use for the hypothesis added, as `interval_cases n with hn` or `interval_cases n using hl hu with hn`. In particular, `interval_cases n` 1) inspects hypotheses looking for lower and upper bounds of the form `a ≤ n` and `n < b` (although in `ℕ`, `ℤ`, and `ℕ+` bounds of the form `a < n` and `n ≤ b` are also allowed), and also makes use of lower and upper bounds found via `le_top` and `bot_le` (so for example if `n : ℕ`, then the bound `0 ≤ n` is found automatically), then 2) calls `fin_cases` on the synthesised hypothesis `n ∈ set.Ico a b`, assuming an appropriate `fintype` instance can be found for the type of `n`. The variable `n` can belong to any type `α`, with the following restrictions: * only bounds on which `expr.to_rat` succeeds will be considered "explicit" (TODO: generalise this?) * an instance of `decidable_eq α` is available, * an explicit lower bound can be found amongst the hypotheses, or from `bot_le n`, * an explicit upper bound can be found amongst the hypotheses, or from `le_top n`, * if multiple bounds are located, an instance of `linear_order α` is available, and * an instance of `fintype set.Ico l u` is available for the relevant bounds. -/ add_tactic_doc { name := "interval_cases", category := doc_category.tactic, decl_names := [`tactic.interactive.interval_cases], tags := ["case bashing"] } end interactive end tactic
feb1182dca818609a94da10e3971f90c6975406f
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/control/bitraversable/basic.lean
da7ed08820de84b1f694df87112b125656f9cdb6
[ "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
2,796
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import control.bifunctor import control.traversable.basic /-! # Bitraversable type class Type class for traversing bifunctors. The concepts and laws are taken from <https://hackage.haskell.org/package/base-4.12.0.0/docs/Data-Bitraversable.html> Simple examples of `bitraversable` are `prod` and `sum`. A more elaborate example is to define an a-list as: ``` def alist (key val : Type) := list (key × val) ``` Then we can use `f : key → io key'` and `g : val → io val'` to manipulate the `alist`'s key and value respectively with `bitraverse f g : alist key val → io (alist key' val')` ## Main definitions * bitraversable - exposes the `bitraverse` function * is_lawful_bitraversable - laws similar to is_lawful_traversable ## Tags traversable bitraversable iterator functor bifunctor applicative -/ universes u class bitraversable (t : Type u → Type u → Type u) extends bifunctor t := (bitraverse : Π {m : Type u → Type u} [applicative m] {α α' β β'}, (α → m α') → (β → m β') → t α β → m (t α' β')) export bitraversable ( bitraverse ) def bisequence {t m} [bitraversable t] [applicative m] {α β} : t (m α) (m β) → m (t α β) := bitraverse id id open functor class is_lawful_bitraversable (t : Type u → Type u → Type u) [bitraversable t] extends is_lawful_bifunctor t := (id_bitraverse : ∀ {α β} (x : t α β), bitraverse id.mk id.mk x = id.mk x ) (comp_bitraverse : ∀ {F G} [applicative F] [applicative G] [is_lawful_applicative F] [is_lawful_applicative G] {α α' β β' γ γ'} (f : β → F γ) (f' : β' → F γ') (g : α → G β) (g' : α' → G β') (x : t α α'), bitraverse (comp.mk ∘ map f ∘ g) (comp.mk ∘ map f' ∘ g') x = comp.mk (bitraverse f f' <$> bitraverse g g' x) ) (bitraverse_eq_bimap_id : ∀ {α α' β β'} (f : α → β) (f' : α' → β') (x : t α α'), bitraverse (id.mk ∘ f) (id.mk ∘ f') x = id.mk (bimap f f' x)) (binaturality : ∀ {F G} [applicative F] [applicative G] [is_lawful_applicative F] [is_lawful_applicative G] (η : applicative_transformation F G) {α α' β β'} (f : α → F β) (f' : α' → F β') (x : t α α'), η (bitraverse f f' x) = bitraverse (@η _ ∘ f) (@η _ ∘ f') x) export is_lawful_bitraversable ( id_bitraverse comp_bitraverse bitraverse_eq_bimap_id ) open is_lawful_bitraversable attribute [higher_order bitraverse_id_id] id_bitraverse attribute [higher_order bitraverse_comp] comp_bitraverse attribute [higher_order] binaturality bitraverse_eq_bimap_id export is_lawful_bitraversable (bitraverse_id_id bitraverse_comp)
e6198ea41325dacd1ad944a0ed1ff4109209a608
63abd62053d479eae5abf4951554e1064a4c45b4
/src/algebra/continued_fractions/computation/approximations.lean
7ce314a0f8b925485162827530e0d701280a8629
[ "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
14,569
lean
/- Copyright (c) 2020 Kevin Kappelmann. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Kappelmann -/ import algebra.continued_fractions.computation.translations import algebra.continued_fractions.continuants_recurrence import algebra.continued_fractions.terminated_stable import data.nat.fib /-! # Approximations for Continued Fraction Computations (`gcf.of`) ## Summary Let us write `gcf` for `generalized_continued_fraction`. This file contains useful approximations for the values involved in the continued fractions computation `gcf.of`. ## Main Theorems - `gcf.of_part_num_eq_one`: shows that all partial numerators `aᵢ` are equal to one. - `gcf.exists_int_eq_of_part_denom`: shows that all partial denominators `bᵢ` correspond to an integer. - `gcf.one_le_of_nth_part_denom`: shows that `1 ≤ bᵢ`. - `gcf.succ_nth_fib_le_of_nth_denom`: shows that the `n`th denominator `Bₙ` is greater than or equal to the `n + 1`th fibonacci number `nat.fib (n + 1)`. - `gcf.le_of_succ_nth_denom`: shows that `Bₙ₊₁ ≥ bₙ * Bₙ`, where `bₙ` is the `n`th partial denominator of the continued fraction. ## References - [*Hardy, GH and Wright, EM and Heath-Brown, Roger and Silverman, Joseph*][hardy2008introduction] -/ namespace generalized_continued_fraction open generalized_continued_fraction as gcf variables {K : Type*} {v : K} {n : ℕ} [linear_ordered_field K] [floor_ring K] /- We begin with some lemmas about the stream of `int_fract_pair`s, which presumably are not of great interest for the end user. -/ namespace int_fract_pair /-- Shows that the fractional parts of the stream are in `[0,1)`. -/ lemma nth_stream_fr_nonneg_lt_one {ifp_n : int_fract_pair K} (nth_stream_eq : int_fract_pair.stream v n = some ifp_n) : 0 ≤ ifp_n.fr ∧ ifp_n.fr < 1 := begin cases n, case nat.zero { have : int_fract_pair.of v = ifp_n, by injection nth_stream_eq, simp [fract_lt_one, fract_nonneg, int_fract_pair.of, this.symm] }, case nat.succ { rcases (succ_nth_stream_eq_some_iff.elim_left nth_stream_eq) with ⟨_, _, _, if_of_eq_ifp_n⟩, simp [fract_lt_one, fract_nonneg, int_fract_pair.of, if_of_eq_ifp_n.symm] } end /-- Shows that the fractional parts of the stream are nonnegative. -/ lemma nth_stream_fr_nonneg {ifp_n : int_fract_pair K} (nth_stream_eq : int_fract_pair.stream v n = some ifp_n) : 0 ≤ ifp_n.fr := (nth_stream_fr_nonneg_lt_one nth_stream_eq).left /-- Shows that the fractional parts of the stream smaller than one. -/ lemma nth_stream_fr_lt_one {ifp_n : int_fract_pair K} (nth_stream_eq : int_fract_pair.stream v n = some ifp_n) : ifp_n.fr < 1 := (nth_stream_fr_nonneg_lt_one nth_stream_eq).right /-- Shows that the integer parts of the stream are at least one. -/ lemma one_le_succ_nth_stream_b {ifp_succ_n : int_fract_pair K} (succ_nth_stream_eq : int_fract_pair.stream v (n + 1) = some ifp_succ_n) : 1 ≤ ifp_succ_n.b := begin obtain ⟨ifp_n, nth_stream_eq, stream_nth_fr_ne_zero, ⟨_⟩⟩ : ∃ ifp_n, int_fract_pair.stream v n = some ifp_n ∧ ifp_n.fr ≠ 0 ∧ int_fract_pair.of ifp_n.fr⁻¹ = ifp_succ_n, from succ_nth_stream_eq_some_iff.elim_left succ_nth_stream_eq, change 1 ≤ ⌊ifp_n.fr⁻¹⌋, suffices : 1 ≤ ifp_n.fr⁻¹, { rw_mod_cast [le_floor], assumption }, suffices : ifp_n.fr ≤ 1, { have h : 0 < ifp_n.fr := lt_of_le_of_ne (nth_stream_fr_nonneg nth_stream_eq) stream_nth_fr_ne_zero.symm, apply one_le_inv h this }, simp [(le_of_lt (nth_stream_fr_lt_one nth_stream_eq))] end /-- Shows that the `n + 1`th integer part `bₙ₊₁` of the stream is smaller or equal than the inverse of the `n`th fractional part `frₙ` of the stream. This result is straight-forward as `bₙ₊₁` is defined as the floor of `1 / frₙ` -/ lemma succ_nth_stream_b_le_nth_stream_fr_inv {ifp_n ifp_succ_n : int_fract_pair K} (nth_stream_eq : int_fract_pair.stream v n = some ifp_n) (succ_nth_stream_eq : int_fract_pair.stream v (n + 1) = some ifp_succ_n) : (ifp_succ_n.b : K) ≤ ifp_n.fr⁻¹ := begin suffices : (⌊ifp_n.fr⁻¹⌋ : K) ≤ ifp_n.fr⁻¹, { cases ifp_n with _ ifp_n_fr, have : ifp_n_fr ≠ 0, { intro h, simpa [h, int_fract_pair.stream, nth_stream_eq] using succ_nth_stream_eq }, have : int_fract_pair.of ifp_n_fr⁻¹ = ifp_succ_n, { simpa [this, int_fract_pair.stream, nth_stream_eq, option.coe_def] using succ_nth_stream_eq }, rwa ←this }, exact (floor_le ifp_n.fr⁻¹) end end int_fract_pair /- Next we translate above results about the stream of `int_fract_pair`s to the computed continued fraction `gcf.of`. -/ /-- Shows that the integer parts of the continued fraction are at least one. -/ lemma of_one_le_nth_part_denom {b : K} (nth_part_denom_eq : (gcf.of v).partial_denominators.nth n = some b) : 1 ≤ b := begin obtain ⟨gp_n, nth_s_eq, ⟨_⟩⟩ : ∃ gp_n, (gcf.of v).s.nth n = some gp_n ∧ gp_n.b = b, from exists_s_b_of_part_denom nth_part_denom_eq, obtain ⟨ifp_n, succ_nth_stream_eq, ifp_n_b_eq_gp_n_b⟩ : ∃ ifp, int_fract_pair.stream v (n + 1) = some ifp ∧ (ifp.b : K) = gp_n.b, from int_fract_pair.exists_succ_nth_stream_of_gcf_of_nth_eq_some nth_s_eq, rw [←ifp_n_b_eq_gp_n_b], exact_mod_cast (int_fract_pair.one_le_succ_nth_stream_b succ_nth_stream_eq) end /-- Shows that the partial numerators `aᵢ` of the continued fraction are equal to one and the partial denominators `bᵢ` correspond to integers. -/ lemma of_part_num_eq_one_and_exists_int_part_denom_eq {gp : gcf.pair K} (nth_s_eq : (gcf.of v).s.nth n = some gp) : gp.a = 1 ∧ ∃ (z : ℤ), gp.b = (z : K) := begin obtain ⟨ifp, stream_succ_nth_eq, ifp_b_eq_gp_b⟩ : ∃ ifp, int_fract_pair.stream v (n + 1) = some ifp ∧ (ifp.b : K) = gp.b, from int_fract_pair.exists_succ_nth_stream_of_gcf_of_nth_eq_some nth_s_eq, have : (gcf.of v).s.nth n = some ⟨1, ifp.b⟩, from nth_of_eq_some_of_succ_nth_int_fract_pair_stream stream_succ_nth_eq, have : some gp = some ⟨1, ifp.b⟩, by rwa nth_s_eq at this, have : gp = ⟨1, ifp.b⟩, by injection this, -- We know the shape of gp, so now we just have to split the goal and use this knowledge. cases gp, split, { injection this }, { existsi ifp.b, injection this } end /-- Shows that the partial numerators `aᵢ` are equal to one. -/ lemma of_part_num_eq_one {a : K} (nth_part_num_eq : (gcf.of v).partial_numerators.nth n = some a) : a = 1 := begin obtain ⟨gp, nth_s_eq, gp_a_eq_a_n⟩ : ∃ gp, (gcf.of v).s.nth n = some gp ∧ gp.a = a, from exists_s_a_of_part_num nth_part_num_eq, have : gp.a = 1, from (of_part_num_eq_one_and_exists_int_part_denom_eq nth_s_eq).left, rwa gp_a_eq_a_n at this end /-- Shows that the partial denominators `bᵢ` correspond to an integer. -/ lemma exists_int_eq_of_part_denom {b : K} (nth_part_denom_eq : (gcf.of v).partial_denominators.nth n = some b) : ∃ (z : ℤ), b = (z : K) := begin obtain ⟨gp, nth_s_eq, gp_b_eq_b_n⟩ : ∃ gp, (gcf.of v).s.nth n = some gp ∧ gp.b = b, from exists_s_b_of_part_denom nth_part_denom_eq, have : ∃ (z : ℤ), gp.b = (z : K), from (of_part_num_eq_one_and_exists_int_part_denom_eq nth_s_eq).right, rwa gp_b_eq_b_n at this end /- One of our next goals is to show that `Bₙ₊₁ ≥ bₙ * Bₙ`. For this, we first show that the partial denominators `Bₙ` are bounded from below by the fibonacci sequence `nat.fib`. This then implies that `0 ≤ Bₙ` and hence `Bₙ₊₂ = bₙ₊₁ * Bₙ₊₁ + Bₙ ≥ bₙ₊₁ * Bₙ₊₁ + 0 = bₙ₊₁ * Bₙ₊₁`. -/ -- open `nat` as we will make use of fibonacci numbers. open nat lemma fib_le_of_continuants_aux_b : (n ≤ 1 ∨ ¬(gcf.of v).terminated_at (n - 2)) → (fib n : K) ≤ ((gcf.of v).continuants_aux n).b := nat.strong_induction_on n begin clear n, assume n IH hyp, rcases n with _|_|n, { simp [fib_succ_succ, continuants_aux] }, -- case n = 0 { simp [fib_succ_succ, continuants_aux] }, -- case n = 1 { let g := gcf.of v, -- case 2 ≤ n have : ¬(n + 2 ≤ 1), by linarith, have not_terminated_at_n : ¬g.terminated_at n, from or.resolve_left hyp this, obtain ⟨gp, s_ppred_nth_eq⟩ : ∃ gp, g.s.nth n = some gp, from option.ne_none_iff_exists'.mp not_terminated_at_n, set pconts := g.continuants_aux (n + 1) with pconts_eq, set ppconts := g.continuants_aux n with ppconts_eq, -- use the recurrence of continuants_aux suffices : (fib n : K) + fib (n + 1) ≤ gp.a * ppconts.b + gp.b * pconts.b, by simpa [fib_succ_succ, add_comm, (continuants_aux_recurrence s_ppred_nth_eq ppconts_eq pconts_eq)], -- make use of the fact that gp.a = 1 suffices : (fib n : K) + fib (n + 1) ≤ ppconts.b + gp.b * pconts.b, by simpa [(of_part_num_eq_one $ part_num_eq_s_a s_ppred_nth_eq)], have not_terminated_at_pred_n : ¬g.terminated_at (n - 1), from mt (terminated_stable $ nat.sub_le n 1) not_terminated_at_n, have not_terminated_at_ppred_n : ¬terminated_at g (n - 2), from mt (terminated_stable (n - 1).pred_le) not_terminated_at_pred_n, -- use the IH to get the inequalities for `pconts` and `ppconts` have : (fib (n + 1) : K) ≤ pconts.b, from IH _ (nat.lt.base $ n + 1) (or.inr not_terminated_at_pred_n), have ppred_nth_fib_le_ppconts_B : (fib n : K) ≤ ppconts.b, from IH n (lt_trans (nat.lt.base n) $ nat.lt.base $ n + 1) (or.inr not_terminated_at_ppred_n), suffices : (fib (n + 1) : K) ≤ gp.b * pconts.b, solve_by_elim [(add_le_add ppred_nth_fib_le_ppconts_B)], -- finally use the fact that 1 ≤ gp.b to solve the goal suffices : 1 * (fib (n + 1) : K) ≤ gp.b * pconts.b, by rwa [one_mul] at this, have one_le_gp_b : (1 : K) ≤ gp.b, from of_one_le_nth_part_denom (part_denom_eq_s_b s_ppred_nth_eq), have : (0 : K) ≤ fib (n + 1), by exact_mod_cast (fib (n + 1)).zero_le, have : (0 : K) ≤ gp.b, from le_trans zero_le_one one_le_gp_b, mono } end /-- Shows that the `n`th denominator is greater than or equal to the `n + 1`th fibonacci number, that is `nat.fib (n + 1) ≤ Bₙ`. -/ lemma succ_nth_fib_le_of_nth_denom (hyp: n = 0 ∨ ¬(gcf.of v).terminated_at (n - 1)) : (fib (n + 1) : K) ≤ (gcf.of v).denominators n := begin rw [denom_eq_conts_b, nth_cont_eq_succ_nth_cont_aux], have : (n + 1) ≤ 1 ∨ ¬(gcf.of v).terminated_at (n - 1), by { cases n, case nat.zero : { exact (or.inl $ le_refl 1) }, case nat.succ : { exact or.inr (or.resolve_left hyp n.succ_ne_zero) } }, exact (fib_le_of_continuants_aux_b this) end /- As a simple consequence, we can now derive that all denominators are nonnegative. -/ lemma zero_le_of_continuants_aux_b : 0 ≤ ((gcf.of v).continuants_aux n).b := begin let g := gcf.of v, induction n with n IH, case nat.zero: { refl }, case nat.succ: { cases (decidable.em $ g.terminated_at (n - 1)) with terminated not_terminated, { cases n, { simp[zero_le_one] }, { have : g.continuants_aux (n + 2) = g.continuants_aux (n + 1), from continuants_aux_stable_step_of_terminated terminated, simp[this, IH] } }, { calc (0 : K) ≤ fib (n + 1) : by exact_mod_cast (n + 1).fib.zero_le ... ≤ ((gcf.of v).continuants_aux (n + 1)).b : fib_le_of_continuants_aux_b (or.inr not_terminated) } } end /-- Shows that all denominators are nonnegative. -/ lemma zero_le_of_denom : 0 ≤ (gcf.of v).denominators n := by { rw [denom_eq_conts_b, nth_cont_eq_succ_nth_cont_aux], exact zero_le_of_continuants_aux_b } lemma le_of_succ_succ_nth_continuants_aux_b {b : K} (nth_part_denom_eq : (gcf.of v).partial_denominators.nth n = some b) : b * ((gcf.of v).continuants_aux $ n + 1).b ≤ ((gcf.of v).continuants_aux $ n + 2).b := begin set g := gcf.of v with g_eq, obtain ⟨gp_n, nth_s_eq, ⟨_⟩⟩ : ∃ gp_n, g.s.nth n = some gp_n ∧ gp_n.b = b, from exists_s_b_of_part_denom nth_part_denom_eq, let conts := g.continuants_aux (n + 2), set pconts := g.continuants_aux (n + 1) with pconts_eq, set ppconts := g.continuants_aux n with ppconts_eq, -- use the recurrence of continuants_aux and the fact that gp_n.a = 1 suffices : gp_n.b * pconts.b ≤ ppconts.b + gp_n.b * pconts.b, by { have : gp_n.a = 1, from of_part_num_eq_one (part_num_eq_s_a nth_s_eq), finish [(gcf.continuants_aux_recurrence nth_s_eq ppconts_eq pconts_eq)] }, have : 0 ≤ ppconts.b, from zero_le_of_continuants_aux_b, solve_by_elim [le_add_of_nonneg_of_le, le_refl] end /-- Shows that `Bₙ₊₁ ≥ bₙ * Bₙ`, where `bₙ` is the `n`th partial denominator and `Bₙ₊₁` and `Bₙ` are the `n + 1`th and `n`th denominator of the continued fraction. -/ theorem le_of_succ_nth_denom {b : K} (nth_part_denom_eq : (gcf.of v).partial_denominators.nth n = some b) : b * (gcf.of v).denominators n ≤ (gcf.of v).denominators (n + 1) := begin rw [denom_eq_conts_b, nth_cont_eq_succ_nth_cont_aux], exact (le_of_succ_succ_nth_continuants_aux_b nth_part_denom_eq) end /-- Shows that the sequence of denominators is monotonically increasing, that is `Bₙ ≤ Bₙ₊₁`. -/ theorem of_denom_mono : (gcf.of v).denominators n ≤ (gcf.of v).denominators (n + 1) := begin let g := gcf.of v, cases (decidable.em $ g.partial_denominators.terminated_at n) with terminated not_terminated, { have : g.partial_denominators.nth n = none, by rwa seq.terminated_at at terminated, have : g.terminated_at n, from terminated_at_iff_part_denom_none.elim_right (by rwa seq.terminated_at at terminated), have : (gcf.of v).denominators (n + 1) = (gcf.of v).denominators n, from denominators_stable_of_terminated n.le_succ this, rw this }, { obtain ⟨b, nth_part_denom_eq⟩ : ∃ b, g.partial_denominators.nth n = some b, from option.ne_none_iff_exists'.mp not_terminated, have : 1 ≤ b, from of_one_le_nth_part_denom nth_part_denom_eq, calc (gcf.of v).denominators n ≤ b * (gcf.of v).denominators n : by simpa using mul_le_mul_of_nonneg_right this zero_le_of_denom ... ≤ (gcf.of v).denominators (n + 1) : le_of_succ_nth_denom nth_part_denom_eq } end end generalized_continued_fraction
85f454d9793f4ed616df01161baa92a378b7f77c
9dc8cecdf3c4634764a18254e94d43da07142918
/src/data/real/cau_seq_completion.lean
d0f1dfc984bfcaa5f171c06406973a6e63592984
[ "Apache-2.0" ]
permissive
jcommelin/mathlib
d8456447c36c176e14d96d9e76f39841f69d2d9b
ee8279351a2e434c2852345c51b728d22af5a156
refs/heads/master
1,664,782,136,488
1,663,638,983,000
1,663,638,983,000
132,563,656
0
0
Apache-2.0
1,663,599,929,000
1,525,760,539,000
Lean
UTF-8
Lean
false
false
11,692
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Robert Y. Lewis -/ import data.real.cau_seq /-! # Cauchy completion This file generalizes the Cauchy completion of `(ℚ, abs)` to the completion of a commutative ring with absolute value. -/ namespace cau_seq.completion open cau_seq section parameters {α : Type*} [linear_ordered_field α] parameters {β : Type*} [comm_ring β] {abv : β → α} [is_absolute_value abv] /-- The Cauchy completion of a commutative ring with absolute value. -/ def Cauchy := @quotient (cau_seq _ abv) cau_seq.equiv /-- The map from Cauchy sequences into the Cauchy completion. -/ def mk : cau_seq _ abv → Cauchy := quotient.mk @[simp] theorem mk_eq_mk (f) : @eq Cauchy ⟦f⟧ (mk f) := rfl theorem mk_eq {f g} : mk f = mk g ↔ f ≈ g := quotient.eq /-- The map from the original ring into the Cauchy completion. -/ def of_rat (x : β) : Cauchy := mk (const abv x) instance : has_zero Cauchy := ⟨of_rat 0⟩ instance : has_one Cauchy := ⟨of_rat 1⟩ instance : inhabited Cauchy := ⟨0⟩ theorem of_rat_zero : of_rat 0 = 0 := rfl theorem of_rat_one : of_rat 1 = 1 := rfl @[simp] theorem mk_eq_zero {f} : mk f = 0 ↔ lim_zero f := by have : mk f = 0 ↔ lim_zero (f - 0) := quotient.eq; rwa sub_zero at this instance : has_add Cauchy := ⟨quotient.map₂ (+) $ λ f₁ g₁ hf f₂ g₂ hg, add_equiv_add hf hg⟩ @[simp] theorem mk_add (f g : cau_seq β abv) : mk f + mk g = mk (f + g) := rfl instance : has_neg Cauchy := ⟨quotient.map has_neg.neg $ λ f₁ f₂ hf, neg_equiv_neg hf⟩ @[simp] theorem mk_neg (f : cau_seq β abv) : -mk f = mk (-f) := rfl instance : has_mul Cauchy := ⟨quotient.map₂ (*) $ λ f₁ g₁ hf f₂ g₂ hg, mul_equiv_mul hf hg⟩ @[simp] theorem mk_mul (f g : cau_seq β abv) : mk f * mk g = mk (f * g) := rfl instance : has_sub Cauchy := ⟨quotient.map₂ has_sub.sub $ λ f₁ g₁ hf f₂ g₂ hg, sub_equiv_sub hf hg⟩ @[simp] theorem mk_sub (f g : cau_seq β abv) : mk f - mk g = mk (f - g) := rfl theorem of_rat_add (x y : β) : of_rat (x + y) = of_rat x + of_rat y := congr_arg mk (const_add _ _) theorem of_rat_neg (x : β) : of_rat (-x) = -of_rat x := congr_arg mk (const_neg _) theorem of_rat_mul (x y : β) : of_rat (x * y) = of_rat x * of_rat y := congr_arg mk (const_mul _ _) private lemma zero_def : 0 = mk 0 := rfl private lemma one_def : 1 = mk 1 := rfl instance : add_group Cauchy := by refine { add := (+), zero := (0 : Cauchy), sub := has_sub.sub, neg := has_neg.neg, sub_eq_add_neg := _, nsmul := nsmul_rec, zsmul := zsmul_rec, .. }; try { intros; refl }; { repeat {refine λ a, quotient.induction_on a (λ _, _)}, simp [zero_def, add_comm, add_left_comm, sub_eq_neg_add] } instance : add_group_with_one Cauchy := { nat_cast := λ n, mk n, nat_cast_zero := congr_arg mk nat.cast_zero, nat_cast_succ := λ n, congr_arg mk (nat.cast_succ n), int_cast := λ n, mk n, int_cast_of_nat := λ n, congr_arg mk (int.cast_of_nat n), int_cast_neg_succ_of_nat := λ n, congr_arg mk (int.cast_neg_succ_of_nat n), one := 1, .. Cauchy.add_group } @[simp] theorem of_rat_nat_cast (n : ℕ) : of_rat n = n := rfl @[simp] theorem of_rat_int_cast (z : ℤ) : of_rat z = z := rfl instance : comm_ring Cauchy := by refine { add := (+), zero := (0 : Cauchy), mul := (*), one := 1, npow := npow_rec, .. Cauchy.add_group_with_one, .. }; try { intros; refl }; { repeat {refine λ a, quotient.induction_on a (λ _, _)}, simp [zero_def, one_def, mul_left_comm, mul_comm, mul_add, add_comm, add_left_comm, sub_eq_add_neg] } -- shortcut instance to ensure computability instance : ring Cauchy := comm_ring.to_ring _ /-- `cau_seq.completion.of_rat` as a `ring_hom` -/ @[simps] def of_rat_ring_hom : β →+* Cauchy := { to_fun := of_rat, map_zero' := of_rat_zero, map_one' := of_rat_one, map_add' := of_rat_add, map_mul' := of_rat_mul, } theorem of_rat_sub (x y : β) : of_rat (x - y) = of_rat x - of_rat y := congr_arg mk (const_sub _ _) end open_locale classical section parameters {α : Type*} [linear_ordered_field α] parameters {β : Type*} [field β] {abv : β → α} [is_absolute_value abv] local notation `Cauchy` := @Cauchy _ _ _ _ abv _ instance : has_rat_cast Cauchy := ⟨λ q, of_rat q⟩ @[simp] theorem of_rat_rat_cast (q : ℚ) : of_rat (↑q : β) = (q : Cauchy) := rfl noncomputable instance : has_inv Cauchy := ⟨λ x, quotient.lift_on x (λ f, mk $ if h : lim_zero f then 0 else inv f h) $ λ f g fg, begin have := lim_zero_congr fg, by_cases hf : lim_zero f, { simp [hf, this.1 hf, setoid.refl] }, { have hg := mt this.2 hf, simp [hf, hg], have If : mk (inv f hf) * mk f = 1 := mk_eq.2 (inv_mul_cancel hf), have Ig : mk (inv g hg) * mk g = 1 := mk_eq.2 (inv_mul_cancel hg), rw [mk_eq.2 fg, ← Ig] at If, rw mul_comm at Ig, rw [← mul_one (mk (inv f hf)), ← Ig, ← mul_assoc, If, mul_assoc, Ig, mul_one] } end⟩ @[simp] theorem inv_zero : (0 : Cauchy)⁻¹ = 0 := congr_arg mk $ by rw dif_pos; [refl, exact zero_lim_zero] @[simp] theorem inv_mk {f} (hf) : (@mk α _ β _ abv _ f)⁻¹ = mk (inv f hf) := congr_arg mk $ by rw dif_neg lemma cau_seq_zero_ne_one : ¬ (0 : cau_seq _ abv) ≈ 1 := λ h, have lim_zero (1 - 0), from setoid.symm h, have lim_zero 1, by simpa, one_ne_zero $ const_lim_zero.1 this lemma zero_ne_one : (0 : Cauchy) ≠ 1 := λ h, cau_seq_zero_ne_one $ mk_eq.1 h protected theorem inv_mul_cancel {x : Cauchy} : x ≠ 0 → x⁻¹ * x = 1 := quotient.induction_on x $ λ f hf, begin simp at hf, simp [hf], exact quotient.sound (cau_seq.inv_mul_cancel hf) end theorem of_rat_inv (x : β) : of_rat (x⁻¹) = ((of_rat x)⁻¹ : Cauchy) := congr_arg mk $ by split_ifs with h; [simp [const_lim_zero.1 h], refl] /-- The Cauchy completion forms a field. -/ noncomputable instance : field Cauchy := { inv := has_inv.inv, mul_inv_cancel := λ x x0, by rw [mul_comm, cau_seq.completion.inv_mul_cancel x0], exists_pair_ne := ⟨0, 1, zero_ne_one⟩, inv_zero := inv_zero, rat_cast := λ q, of_rat q, rat_cast_mk := λ n d hd hnd, by rw [rat.cast_mk', of_rat_mul, of_rat_int_cast, of_rat_inv, of_rat_nat_cast], .. Cauchy.comm_ring } theorem of_rat_div (x y : β) : of_rat (x / y) = (of_rat x / of_rat y : Cauchy) := by simp only [div_eq_inv_mul, of_rat_inv, of_rat_mul] /-- Show the first 10 items of a representative of this equivalence class of cauchy sequences. The representative chosen is the one passed in the VM to `quot.mk`, so two cauchy sequences converging to the same number may be printed differently. -/ meta instance [has_repr β] : has_repr Cauchy := { repr := λ r, let N := 10, seq := r.unquot in "(sorry /- " ++ (", ".intercalate $ (list.range N).map $ repr ∘ seq) ++ ", ... -/)" } end end cau_seq.completion variables {α : Type*} [linear_ordered_field α] namespace cau_seq section variables (β : Type*) [ring β] (abv : β → α) [is_absolute_value abv] /-- A class stating that a ring with an absolute value is complete, i.e. every Cauchy sequence has a limit. -/ class is_complete : Prop := (is_complete : ∀ s : cau_seq β abv, ∃ b : β, s ≈ const abv b) end section variables {β : Type*} [ring β] {abv : β → α} [is_absolute_value abv] variable [is_complete β abv] lemma complete : ∀ s : cau_seq β abv, ∃ b : β, s ≈ const abv b := is_complete.is_complete /-- The limit of a Cauchy sequence in a complete ring. Chosen non-computably. -/ noncomputable def lim (s : cau_seq β abv) : β := classical.some (complete s) lemma equiv_lim (s : cau_seq β abv) : s ≈ const abv (lim s) := classical.some_spec (complete s) lemma eq_lim_of_const_equiv {f : cau_seq β abv} {x : β} (h : cau_seq.const abv x ≈ f) : x = lim f := const_equiv.mp $ setoid.trans h $ equiv_lim f lemma lim_eq_of_equiv_const {f : cau_seq β abv} {x : β} (h : f ≈ cau_seq.const abv x) : lim f = x := (eq_lim_of_const_equiv $ setoid.symm h).symm lemma lim_eq_lim_of_equiv {f g : cau_seq β abv} (h : f ≈ g) : lim f = lim g := lim_eq_of_equiv_const $ setoid.trans h $ equiv_lim g @[simp] lemma lim_const (x : β) : lim (const abv x) = x := lim_eq_of_equiv_const $ setoid.refl _ lemma lim_add (f g : cau_seq β abv) : lim f + lim g = lim (f + g) := eq_lim_of_const_equiv $ show lim_zero (const abv (lim f + lim g) - (f + g)), by rw [const_add, add_sub_add_comm]; exact add_lim_zero (setoid.symm (equiv_lim f)) (setoid.symm (equiv_lim g)) lemma lim_mul_lim (f g : cau_seq β abv) : lim f * lim g = lim (f * g) := eq_lim_of_const_equiv $ show lim_zero (const abv (lim f * lim g) - f * g), from have h : const abv (lim f * lim g) - f * g = (const abv (lim f) - f) * g + const abv (lim f) * (const abv (lim g) - g) := by simp [const_mul (lim f), mul_add, add_mul, sub_eq_add_neg, add_comm, add_left_comm], by rw h; exact add_lim_zero (mul_lim_zero_left _ (setoid.symm (equiv_lim _))) (mul_lim_zero_right _ (setoid.symm (equiv_lim _))) lemma lim_mul (f : cau_seq β abv) (x : β) : lim f * x = lim (f * const abv x) := by rw [← lim_mul_lim, lim_const] lemma lim_neg (f : cau_seq β abv) : lim (-f) = -lim f := lim_eq_of_equiv_const (show lim_zero (-f - const abv (-lim f)), by rw [const_neg, sub_neg_eq_add, add_comm, ← sub_eq_add_neg]; exact setoid.symm (equiv_lim f)) lemma lim_eq_zero_iff (f : cau_seq β abv) : lim f = 0 ↔ lim_zero f := ⟨assume h, by have hf := equiv_lim f; rw h at hf; exact (lim_zero_congr hf).mpr (const_lim_zero.mpr rfl), assume h, have h₁ : f = (f - const abv 0) := ext (λ n, by simp [sub_apply, const_apply]), by rw h₁ at h; exact lim_eq_of_equiv_const h ⟩ end section variables {β : Type*} [field β] {abv : β → α} [is_absolute_value abv] [is_complete β abv] lemma lim_inv {f : cau_seq β abv} (hf : ¬ lim_zero f) : lim (inv f hf) = (lim f)⁻¹ := have hl : lim f ≠ 0 := by rwa ← lim_eq_zero_iff at hf, lim_eq_of_equiv_const $ show lim_zero (inv f hf - const abv (lim f)⁻¹), from have h₁ : ∀ (g f : cau_seq β abv) (hf : ¬ lim_zero f), lim_zero (g - f * inv f hf * g) := λ g f hf, by rw [← one_mul g, ← mul_assoc, ← sub_mul, mul_one, mul_comm, mul_comm f]; exact mul_lim_zero_right _ (setoid.symm (cau_seq.inv_mul_cancel _)), have h₂ : lim_zero ((inv f hf - const abv (lim f)⁻¹) - (const abv (lim f) - f) * (inv f hf * const abv (lim f)⁻¹)) := by rw [sub_mul, ← sub_add, sub_sub, sub_add_eq_sub_sub, sub_right_comm, sub_add]; exact show lim_zero (inv f hf - const abv (lim f) * (inv f hf * const abv (lim f)⁻¹) - (const abv (lim f)⁻¹ - f * (inv f hf * const abv (lim f)⁻¹))), from sub_lim_zero (by rw [← mul_assoc, mul_right_comm, const_inv hl]; exact h₁ _ _ _) (by rw [← mul_assoc]; exact h₁ _ _ _), (lim_zero_congr h₂).mpr $ mul_lim_zero_left _ (setoid.symm (equiv_lim f)) end section variables [is_complete α abs] lemma lim_le {f : cau_seq α abs} {x : α} (h : f ≤ cau_seq.const abs x) : lim f ≤ x := cau_seq.const_le.1 $ cau_seq.le_of_eq_of_le (setoid.symm (equiv_lim f)) h lemma le_lim {f : cau_seq α abs} {x : α} (h : cau_seq.const abs x ≤ f) : x ≤ lim f := cau_seq.const_le.1 $ cau_seq.le_of_le_of_eq h (equiv_lim f) lemma lt_lim {f : cau_seq α abs} {x : α} (h : cau_seq.const abs x < f) : x < lim f := cau_seq.const_lt.1 $ cau_seq.lt_of_lt_of_eq h (equiv_lim f) lemma lim_lt {f : cau_seq α abs} {x : α} (h : f < cau_seq.const abs x) : lim f < x := cau_seq.const_lt.1 $ cau_seq.lt_of_eq_of_lt (setoid.symm (equiv_lim f)) h end end cau_seq
16c547d9add765eb5bdf1bcde4829f8af3ec9086
3618c6e11aa822fd542440674dfb9a7b9921dba0
/scratch/inductive_step.lean
a797c9e23ace5f09f57133847aa68ac9d3eedc8b
[]
no_license
ChrisHughes24/single_relation
99ceedcc02d236ce46d6c65d72caa669857533c5
057e157a59de6d0e43b50fcb537d66792ec20450
refs/heads/master
1,683,652,062,698
1,683,360,089,000
1,683,360,089,000
279,346,432
0
0
null
null
null
null
UTF-8
Lean
false
false
10,111
lean
import for_mathlib.coproduct group_theory.semidirect_product noncomputable theory universe u variables {ι : Type} [decidable_eq ι] (r : free_group ι) (T : set ι) [decidable_pred T] open free_group def phi : closure_var T →* mul_aut (free_group (free_group ι)) := { to_fun := λ g : closure_var T, free_group.equiv (mul_left (g : free_group ι)), map_one' := by simp [equiv.perm.one_def]; refl, map_mul' := λ x y, by simp [equiv.perm.mul_def]; refl } def phi' : free_group ι →* mul_aut (free_group (free_group ι)) := { to_fun := λ w, free_group.equiv (mul_left w), map_one' := by simp [equiv.perm.one_def, mul_aut.one_def], map_mul' := by simp [equiv.perm.mul_def, mul_aut.mul_def] } lemma phi'_of' (n : C∞) (w w' : free_group ι) : phi' w (of' w' n) = of' (w * w') n := by simp [phi'] include r def unnormalize : free_group (free_group ι) ⋊[phi T] closure_var T →* free_group ι := semidirect_product.lift (free_group.lift' (λ g : free_group ι, (mul_aut.conj g : free_group ι ≃* free_group ι).to_monoid_hom.comp (gpowers_hom (free_group ι) r))) (subgroup.subtype (closure_var T)) (λ g, hom_ext (λ i, by simp [_root_.phi, of_eq_of'])) open semidirect_product def unnormalize' : free_group (free_group ι) ⋊[phi'] free_group ι →* free_group ι := semidirect_product.lift (free_group.lift' (λ g : free_group ι, (mul_aut.conj g : free_group ι ≃* free_group ι).to_monoid_hom.comp (gpowers_hom (free_group ι) r))) (monoid_hom.id _) (λ g, hom_ext (λ i, by simp [_root_.phi', of_eq_of'])) @[simp] lemma unnormalize'_inr (w : free_group ι) : unnormalize' r (inr w) = w := semidirect_product.lift_inr _ _ _ _ lemma unnormalize'_inl (w : free_group (free_group ι)) : unnormalize' r (inl w) = free_group.lift' (λ g : free_group ι, (mul_aut.conj g : free_group ι ≃* free_group ι).to_monoid_hom.comp (gpowers_hom (free_group ι) r)) w := semidirect_product.lift_inl _ _ _ _ omit r def remove_subscript (t : ι) : free_group (ι × C∞) →* free_group ι := free_group.lift' (λ g, (mul_aut.conj (of' t g.2)).to_monoid_hom.comp (of' g.1)) def mul_subscript (n : C∞) : free_group (ι × C∞) ≃* free_group (ι × C∞) := free_group.equiv (equiv.prod_congr (equiv.refl _) (mul_left n)) @[simp] lemma remove_subscript_comp_mul_subscript (t : ι) (n : C∞) : (remove_subscript t).comp (mul_subscript n).to_monoid_hom = (mul_aut.conj (of' t n)).to_monoid_hom.comp (remove_subscript t) := free_group.hom_ext (by simp [remove_subscript, mul_subscript, of_eq_of']) @[simp] lemma remove_subscript_mul_subscript (t : ι) (n : C∞) (x) : remove_subscript t (mul_subscript n x) = of' t n * remove_subscript t x * of' t n⁻¹ := by simpa [-remove_subscript_comp_mul_subscript] using monoid_hom.ext_iff.1 (remove_subscript_comp_mul_subscript t n) x @[simp] lemma remove_subscript_of' (t : ι) (l : ι × C∞) (n : C∞) : remove_subscript t (of' l n) = (mul_aut.conj (of' t l.2)).to_monoid_hom.comp (of' l.1) n := free_group.lift'_of' _ _ _ lemma remove_subscript_SD (t : ι) : free_group (free_group (ι × C∞)) ⋊[phi'] free_group (ι × C∞) →* free_group (free_group ι) ⋊[phi'] free_group ι := semidirect_product.lift (inl.comp (free_group.lift' (λ g, of' (remove_subscript t g)))) (inr.comp (remove_subscript t)) begin intro g, apply free_group.hom_ext, assume i, simp only [of_eq_of', lift'_of', monoid_hom.comp_apply, mul_equiv.to_monoid_hom_apply, phi'_of'], apply semidirect_product.ext; simp [phi'] end include r /-- Not the correct definition -/ structure solver (T : set ι): Type := (to_fun : free_group ι → option (free_group (free_group ι) ⋊[phi'] free_group ι)) (inv : ∀ (x : free_group ι), x ∈ (set.univ : set (free_group ι)) → ∃ (y : free_group (free_group ι) ⋊[phi'] free_group ι), y ∈ to_fun x → unnormalize' r y = x) instance : has_coe_to_fun (solver r T) := { F := λ _, free_group ι → option (free_group (free_group ι) ⋊[phi'] free_group ι), coe := solver.to_fun } lemma unnormalize_eq_of_mem {n : solver r T} {x : free_group ι} {y : free_group (free_group ι) ⋊[phi'] free_group ι} (h : y ∈ n x) : unnormalize' r y = x := sorry lemma unnormalize_inl_eq_of_mem {n : solver r T} {x : free_group ι} {y : free_group (free_group ι) ⋊[phi'] free_group ι} (h : y ∈ n x) : unnormalize' r (inl y.left) = x * y.right⁻¹ := by rw [eq_mul_inv_iff_mul_eq, ← unnormalize'_inr r y.right, ← monoid_hom.map_mul, inl_left_mul_inr_right, unnormalize_eq_of_mem r T h] variable {ι} omit r noncomputable def normalize_cons (t : ι) (r' : free_group (ι × C∞)) {A B : set (ι × C∞)} [decidable_pred A] [decidable_pred B] (hA : solver r' A) (hB : solver r' B) : Π (old1 : free_group (ι × C∞)) (old2 : free_group (free_group (ι × C∞)) ⋊[phi'] free_group (ι × C∞)), free_group (free_group (ι × C∞)) ⋊[phi'] free_group (ι × C∞) | old1 ⟨w, ⟨[], _⟩⟩ := ⟨phi' old1 w, old1⟩ | old1 ⟨w, ⟨i :: l, _⟩⟩ := if i.1.1 = t then if i.2 ≤ 1 then option.elim (hA old1) (normalize_cons ⟨old1.1 ++ [i], sorry⟩ ⟨(phi' (of' i.1 i.2))⁻¹ w, ⟨l, sorry⟩⟩) (λ a, inr (of (t, 1))⁻¹ * normalize_cons (mul_subscript ii (right_hom a)) ⟨phi' (of (t, 1)) (phi' a.right⁻¹ a.left * w), of' i.1 (ii * i.2) * ⟨l, sorry⟩⟩) else option.elim (hB old1) (normalize_cons ⟨old1.1 ++ [i], sorry⟩ ⟨(phi' (of' i.1 i.2))⁻¹ w, ⟨l, sorry⟩⟩) (λ a, inr (of (t, 1)) * normalize_cons (mul_subscript (ii⁻¹) (right_hom a)) ⟨phi' (of (t, 1))⁻¹ (phi' a.right⁻¹ a.left * w), of' i.1 (ii⁻¹ * i.2) *⟨l, sorry⟩⟩) else normalize_cons ⟨old1.1 ++ [i], sorry⟩ ⟨(phi' (of' i.1 i.2))⁻¹ w, ⟨l, sorry⟩⟩ using_well_founded { rel_tac := λ _ _, `[exact ⟨λ _ _, true, sorry⟩], dec_tac := `[trivial] } @[simp] lemma remove_subscript_unnormalize_normalize_cons (t : ι) (r' : free_group (ι × C∞)) {A B : set (ι × C∞)} [decidable_pred A] [decidable_pred B] (hA : solver r' A) (hB : solver r' B) : Π (old1 : free_group (ι × C∞)) (old2 : free_group (free_group (ι × C∞)) ⋊[phi'] free_group (ι × C∞)), remove_subscript t (unnormalize' r' (normalize_cons t r' hA hB old1 old2)) = remove_subscript t (old1 * unnormalize' r' old2) | old1 ⟨w, ⟨[], _⟩⟩ := by rw normalize_cons; simp [inl_aut] | old1 ⟨w, ⟨i :: l, _⟩⟩ := begin rw normalize_cons, split_ifs, { cases h1 : hA old1, { simp [remove_subscript_unnormalize_normalize_cons, inl_aut_inv, mul_assoc] }, { have : i.1.2 = ii, from sorry, simp [remove_subscript_unnormalize_normalize_cons, mul_assoc, inl_aut_inv, unnormalize_inl_eq_of_mem _ _ h1, of_eq_of', inl_aut, this, h, unnormalize_eq_of_mem _ _ h1] } }, { cases h2 : hB old1, { simp [remove_subscript_unnormalize_normalize_cons, inl_aut_inv, mul_assoc] }, { have : i.1.2 = ii, from sorry, simp [remove_subscript_unnormalize_normalize_cons, mul_assoc, inl_aut_inv, unnormalize_inl_eq_of_mem _ _ h2, of_eq_of', inl_aut, this, h, unnormalize_eq_of_mem _ _ h2] } }, { simp [remove_subscript_unnormalize_normalize_cons, inl_aut_inv, mul_assoc] } end using_well_founded { rel_tac := λ _ _, `[exact ⟨λ _ _, true, sorry⟩], dec_tac := `[trivial] } noncomputable def normalize_with_subscript_aux (t : ι) (r' : free_group (ι × C∞)) {A B : set (ι × C∞)} [decidable_pred A] [decidable_pred B] (hA : solver r' A) (hB : solver r' B) : Π (w : list (Σ i : ι, C∞)) (hw : reduced w), free_group (free_group (ι × C∞)) ⋊[phi'] free_group (ι × C∞) | [] _ := 1 | (i :: l) _ := normalize_cons t r' hA hB (of' (i.1, 1) i.2) (normalize_with_subscript_aux l sorry) noncomputable def normalize_with_subscript (t : ι) (r' : free_group (ι × C∞)) {A B : set (ι × C∞)} [decidable_pred A] [decidable_pred B] (hA : solver r' A) (hB : solver r' B) (w : free_group ι) : free_group (free_group (ι × C∞)) ⋊[phi'] free_group (ι × C∞) := normalize_with_subscript_aux t r' hA hB w.1 w.2 lemma remove_subscript_unnormalize_normalize_with_subscript_aux (t : ι) (r' : free_group (ι × C∞)) {A B : set (ι × C∞)} [decidable_pred A] [decidable_pred B] (hA : solver r' A) (hB : solver r' B) : Π (w : list (Σ i : ι, C∞)) (hw : reduced w), remove_subscript t (unnormalize' r' (normalize_with_subscript_aux t r' hA hB w hw)) = ⟨w, hw⟩ | [] _ := by simp [normalize_with_subscript_aux] | (i :: l) _ := begin rw [normalize_with_subscript_aux, remove_subscript_unnormalize_normalize_cons, monoid_hom.map_mul, remove_subscript_unnormalize_normalize_with_subscript_aux], simp end @[simp] lemma remove_subscript_unnormalize_normalize_with_subscript (t : ι) (r' : free_group (ι × C∞)) {A B : set (ι × C∞)} [decidable_pred A] [decidable_pred B] (hA : solver r' A) (hB : solver r' B) (w : free_group ι) : remove_subscript t (unnormalize' r' (normalize_with_subscript t r' hA hB w)) = w := by cases w; apply remove_subscript_unnormalize_normalize_with_subscript_aux def Icc_prod (x : ι) (a b : C∞) : set (ι × C∞) := { p | p.1 = x → a ≤ p.2 ∧ p.2 ≤ b } instance (x : ι) (a b : C∞) : decidable_pred (Icc_prod x a b) := by dunfold Icc_prod; apply_instance /- need to cyclically reduce r' -/ def normalize (t x : ι) (r' : free_group (ι × C∞)) (hx : x ∉ T) (ht : exp_sum t r = 1) (a b : C∞) (ha : a ∈ finset.min ((vars r').image prod.snd)) (hb : b ∈ finset.max ((vars r').image prod.snd)) (hr' : r' = ((free_group.to_SD t) r).left) (hr'₁ : solver r' (Icc_prod x a (b * ii⁻¹))) (hr'₂ : solver r' (Icc_prod x (a * ii) b)) (w : free_group ι) : option (free_group (free_group ι) ⋊[phi'] free_group ι) := let w' := remove_subscript_SD t (normalize_with_subscript t r' hr'₁ hr'₂ w) in if w'.right ∈ closure_var T then some w' else none
92481240d519f4d7db54f207488b0b37c5e9b026
4efff1f47634ff19e2f786deadd394270a59ecd2
/src/category_theory/natural_isomorphism.lean
106976a674e48845f6e472419bebb7e6ba1145e5
[ "Apache-2.0" ]
permissive
agjftucker/mathlib
d634cd0d5256b6325e3c55bb7fb2403548371707
87fe50de17b00af533f72a102d0adefe4a2285e8
refs/heads/master
1,625,378,131,941
1,599,166,526,000
1,599,166,526,000
160,748,509
0
0
Apache-2.0
1,544,141,789,000
1,544,141,789,000
null
UTF-8
Lean
false
false
6,330
lean
/- Copyright (c) 2017 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Tim Baumann, Stephen Morgan, Scott Morrison, Floris van Doorn -/ import category_theory.functor_category import category_theory.isomorphism open category_theory -- declare the `v`'s first; see `category_theory.category` for an explanation universes v₁ v₂ v₃ v₄ u₁ u₂ u₃ u₄ namespace category_theory open nat_trans variables {C : Type u₁} [category.{v₁} C] {D : Type u₂} [category.{v₂} D] {E : Type u₃} [category.{v₃} E] namespace iso /-- The application of a natural isomorphism to an object. We put this definition in a different namespace, so that we can use `α.app` -/ @[simp, reducible] def app {F G : C ⥤ D} (α : F ≅ G) (X : C) : F.obj X ≅ G.obj X := { hom := α.hom.app X, inv := α.inv.app X, hom_inv_id' := begin rw [← comp_app, iso.hom_inv_id], refl end, inv_hom_id' := begin rw [← comp_app, iso.inv_hom_id], refl end } @[simp, reassoc] lemma hom_inv_id_app {F G : C ⥤ D} (α : F ≅ G) (X : C) : α.hom.app X ≫ α.inv.app X = 𝟙 (F.obj X) := congr_fun (congr_arg nat_trans.app α.hom_inv_id) X @[simp, reassoc] lemma inv_hom_id_app {F G : C ⥤ D} (α : F ≅ G) (X : C) : α.inv.app X ≫ α.hom.app X = 𝟙 (G.obj X) := congr_fun (congr_arg nat_trans.app α.inv_hom_id) X end iso namespace nat_iso open category_theory.category category_theory.functor @[simp] lemma trans_app {F G H : C ⥤ D} (α : F ≅ G) (β : G ≅ H) (X : C) : (α ≪≫ β).app X = α.app X ≪≫ β.app X := rfl lemma app_hom {F G : C ⥤ D} (α : F ≅ G) (X : C) : (α.app X).hom = α.hom.app X := rfl lemma app_inv {F G : C ⥤ D} (α : F ≅ G) (X : C) : (α.app X).inv = α.inv.app X := rfl variables {F G : C ⥤ D} instance hom_app_is_iso (α : F ≅ G) (X : C) : is_iso (α.hom.app X) := { inv := α.inv.app X, hom_inv_id' := begin rw [←comp_app, iso.hom_inv_id, ←id_app] end, inv_hom_id' := begin rw [←comp_app, iso.inv_hom_id, ←id_app] end } instance inv_app_is_iso (α : F ≅ G) (X : C) : is_iso (α.inv.app X) := { inv := α.hom.app X, hom_inv_id' := begin rw [←comp_app, iso.inv_hom_id, ←id_app] end, inv_hom_id' := begin rw [←comp_app, iso.hom_inv_id, ←id_app] end } section /-! Unfortunately we need a separate set of cancellation lemmas for components of natural isomorphisms, because the `simp` normal form is `α.hom.app X`, rather than `α.app.hom X`. (With the later, the morphism would be visibly part of an isomorphism, so general lemmas about isomorphisms would apply.) In the future, we should consider a redesign that changes this simp norm form, but for now it breaks too many proofs. -/ variables (α : F ≅ G) @[simp] lemma cancel_nat_iso_hom_left {X : C} {Z : D} (g g' : G.obj X ⟶ Z) : α.hom.app X ≫ g = α.hom.app X ≫ g' ↔ g = g' := by simp only [cancel_epi] @[simp] lemma cancel_nat_iso_inv_left {X : C} {Z : D} (g g' : F.obj X ⟶ Z) : α.inv.app X ≫ g = α.inv.app X ≫ g' ↔ g = g' := by simp only [cancel_epi] @[simp] lemma cancel_nat_iso_hom_right {X : D} {Y : C} (f f' : X ⟶ F.obj Y) : f ≫ α.hom.app Y = f' ≫ α.hom.app Y ↔ f = f' := by simp only [cancel_mono] @[simp] lemma cancel_nat_iso_inv_right {X : D} {Y : C} (f f' : X ⟶ G.obj Y) : f ≫ α.inv.app Y = f' ≫ α.inv.app Y ↔ f = f' := by simp only [cancel_mono] @[simp] lemma cancel_nat_iso_hom_right_assoc {W X X' : D} {Y : C} (f : W ⟶ X) (g : X ⟶ F.obj Y) (f' : W ⟶ X') (g' : X' ⟶ F.obj Y) : f ≫ g ≫ α.hom.app Y = f' ≫ g' ≫ α.hom.app Y ↔ f ≫ g = f' ≫ g' := by simp only [←category.assoc, cancel_mono] @[simp] lemma cancel_nat_iso_inv_right_assoc {W X X' : D} {Y : C} (f : W ⟶ X) (g : X ⟶ G.obj Y) (f' : W ⟶ X') (g' : X' ⟶ G.obj Y) : f ≫ g ≫ α.inv.app Y = f' ≫ g' ≫ α.inv.app Y ↔ f ≫ g = f' ≫ g' := by simp only [←category.assoc, cancel_mono] end variables {X Y : C} lemma naturality_1 (α : F ≅ G) (f : X ⟶ Y) : (α.inv.app X) ≫ (F.map f) ≫ (α.hom.app Y) = G.map f := begin erw [naturality, ←category.assoc, is_iso.hom_inv_id, category.id_comp] end lemma naturality_2 (α : F ≅ G) (f : X ⟶ Y) : (α.hom.app X) ≫ (G.map f) ≫ (α.inv.app Y) = F.map f := begin erw [naturality, ←category.assoc, is_iso.hom_inv_id, category.id_comp] end def is_iso_of_is_iso_app (α : F ⟶ G) [∀ X : C, is_iso (α.app X)] : is_iso α := { inv := { app := λ X, inv (α.app X), naturality' := λ X Y f, begin have h := congr_arg (λ f, inv (α.app X) ≫ (f ≫ inv (α.app Y))) (α.naturality f).symm, simp only [is_iso.inv_hom_id_assoc, is_iso.hom_inv_id, assoc, comp_id, cancel_mono] at h, exact h end } } instance is_iso_of_is_iso_app' (α : F ⟶ G) [H : ∀ X : C, is_iso (nat_trans.app α X)] : is_iso α := @nat_iso.is_iso_of_is_iso_app _ _ _ _ _ _ α H -- TODO can we make this an instance? def is_iso_app_of_is_iso (α : F ⟶ G) [is_iso α] (X) : is_iso (α.app X) := { inv := (inv α).app X, hom_inv_id' := congr_fun (congr_arg nat_trans.app (is_iso.hom_inv_id α)) X, inv_hom_id' := congr_fun (congr_arg nat_trans.app (is_iso.inv_hom_id α)) X } def of_components (app : ∀ X : C, F.obj X ≅ G.obj X) (naturality : ∀ {X Y : C} (f : X ⟶ Y), F.map f ≫ (app Y).hom = (app X).hom ≫ G.map f) : F ≅ G := as_iso { app := λ X, (app X).hom } @[simp] lemma of_components.app (app' : ∀ X : C, F.obj X ≅ G.obj X) (naturality) (X) : (of_components app' naturality).app X = app' X := by tidy @[simp] lemma of_components.hom_app (app : ∀ X : C, F.obj X ≅ G.obj X) (naturality) (X) : (of_components app naturality).hom.app X = (app X).hom := rfl @[simp] lemma of_components.inv_app (app : ∀ X : C, F.obj X ≅ G.obj X) (naturality) (X) : (of_components app naturality).inv.app X = (app X).inv := rfl def hcomp {F G : C ⥤ D} {H I : D ⥤ E} (α : F ≅ G) (β : H ≅ I) : F ⋙ H ≅ G ⋙ I := begin refine ⟨α.hom ◫ β.hom, α.inv ◫ β.inv, _, _⟩, { ext, rw [←nat_trans.exchange], simp, refl }, ext, rw [←nat_trans.exchange], simp, refl end -- declare local notation for nat_iso.hcomp localized "infix ` ■ `:80 := category_theory.nat_iso.hcomp" in category end nat_iso end category_theory
7adca1ae29ba92a5904a8e40981806597d5e31f1
2a70b774d16dbdf5a533432ee0ebab6838df0948
/_target/deps/mathlib/src/algebra/module/linear_map.lean
6d3d05eab22a0dd793c7f4174b910e2d7e7e6ef3
[ "Apache-2.0" ]
permissive
hjvromen/lewis
40b035973df7c77ebf927afab7878c76d05ff758
105b675f73630f028ad5d890897a51b3c1146fb0
refs/heads/master
1,677,944,636,343
1,676,555,301,000
1,676,555,301,000
327,553,599
0
0
null
null
null
null
UTF-8
Lean
false
false
17,458
lean
/- Copyright (c) 2020 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Nathaniel Thomas, Jeremy Avigad, Johannes Hölzl, Mario Carneiro, Anne Baanen -/ import algebra.group.hom import algebra.module.basic import algebra.group_action_hom /-! # Linear maps and linear equivalences In this file we define * `linear_map R M M₂`, `M →ₗ[R] M₂` : a linear map between two R-`semimodule`s. * `is_linear_map R f` : predicate saying that `f : M → M₂` is a linear map. * `linear_equiv R M ₂`, `M ≃ₗ[R] M₂`: an invertible linear map ## Tags linear map, linear equiv, linear equivalences, linear isomorphism, linear isomorphic -/ open function open_locale big_operators universes u u' v w x y z variables {R : Type u} {k : Type u'} {S : Type v} {M : Type w} {M₂ : Type x} {M₃ : Type y} {ι : Type z} /-- A map `f` between semimodules over a semiring is linear if it satisfies the two properties `f (x + y) = f x + f y` and `f (c • x) = c • f x`. The predicate `is_linear_map R f` asserts this property. A bundled version is available with `linear_map`, and should be favored over `is_linear_map` most of the time. -/ structure is_linear_map (R : Type u) {M : Type v} {M₂ : Type w} [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [semimodule R M] [semimodule R M₂] (f : M → M₂) : Prop := (map_add : ∀ x y, f (x + y) = f x + f y) (map_smul : ∀ (c : R) x, f (c • x) = c • f x) section set_option old_structure_cmd true /-- A map `f` between semimodules over a semiring is linear if it satisfies the two properties `f (x + y) = f x + f y` and `f (c • x) = c • f x`. Elements of `linear_map R M M₂` (available under the notation `M →ₗ[R] M₂`) are bundled versions of such maps. An unbundled version is available with the predicate `is_linear_map`, but it should be avoided most of the time. -/ structure linear_map (R : Type u) (M : Type v) (M₂ : Type w) [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [semimodule R M] [semimodule R M₂] extends add_hom M M₂, M →[R] M₂ end /-- The `add_hom` underlying a `linear_map`. -/ add_decl_doc linear_map.to_add_hom /-- The `mul_action_hom` underlying a `linear_map`. -/ add_decl_doc linear_map.to_mul_action_hom infixr ` →ₗ `:25 := linear_map _ notation M ` →ₗ[`:25 R:25 `] `:0 M₂:0 := linear_map R M M₂ namespace linear_map section add_comm_monoid variables [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] section variables [semimodule R M] [semimodule R M₂] instance : has_coe_to_fun (M →ₗ[R] M₂) := ⟨_, to_fun⟩ initialize_simps_projections linear_map (to_fun → apply) @[simp] lemma coe_mk (f : M → M₂) (h₁ h₂) : ((linear_map.mk f h₁ h₂ : M →ₗ[R] M₂) : M → M₂) = f := rfl /-- Identity map as a `linear_map` -/ def id : M →ₗ[R] M := ⟨id, λ _ _, rfl, λ _ _, rfl⟩ lemma id_apply (x : M) : @id R M _ _ _ x = x := rfl @[simp, norm_cast] lemma id_coe : ((linear_map.id : M →ₗ[R] M) : M → M) = _root_.id := by { ext x, refl } end section variables [semimodule R M] [semimodule R M₂] variables (f g : M →ₗ[R] M₂) @[simp] lemma to_fun_eq_coe : f.to_fun = ⇑f := rfl theorem is_linear : is_linear_map R f := ⟨f.2, f.3⟩ variables {f g} theorem coe_injective : injective (λ f : M →ₗ[R] M₂, show M → M₂, from f) := by rintro ⟨f, _⟩ ⟨g, _⟩ ⟨h⟩; congr @[ext] theorem ext (H : ∀ x, f x = g x) : f = g := coe_injective $ funext H protected lemma congr_arg : Π {x x' : M}, x = x' → f x = f x' | _ _ rfl := rfl /-- If two linear maps are equal, they are equal at each point. -/ protected lemma congr_fun (h : f = g) (x : M) : f x = g x := h ▸ rfl theorem ext_iff : f = g ↔ ∀ x, f x = g x := ⟨by { rintro rfl x, refl }, ext⟩ variables (f g) @[simp] lemma map_add (x y : M) : f (x + y) = f x + f y := f.map_add' x y @[simp] lemma map_smul (c : R) (x : M) : f (c • x) = c • f x := f.map_smul' c x @[simp] lemma map_zero : f 0 = 0 := by rw [← zero_smul R, map_smul f 0 0, zero_smul] variables (M M₂) /-- A typeclass for `has_scalar` structures which can be moved through a `linear_map`. This typeclass is generated automatically from a `is_scalar_tower` instance, but exists so that we can also add an instance for `add_comm_group.int_module`, allowing `z •` to be moved even if `R` does not support negation. -/ class compatible_smul (R S : Type*) [semiring S] [has_scalar R M] [semimodule S M] [has_scalar R M₂] [semimodule S M₂] := (map_smul : ∀ (f : M →ₗ[S] M₂) (c : R) (x : M), f (c • x) = c • f x) variables {M M₂} @[priority 100] instance compatible_smul.is_scalar_tower {R S : Type*} [semiring S] [has_scalar R S] [has_scalar R M] [semimodule S M] [is_scalar_tower R S M] [has_scalar R M₂] [semimodule S M₂] [is_scalar_tower R S M₂] : compatible_smul M M₂ R S := ⟨λ f c x, by rw [← smul_one_smul S c x, ← smul_one_smul S c (f x), map_smul]⟩ @[simp, priority 900] lemma map_smul_of_tower {R S : Type*} [semiring S] [has_scalar R M] [semimodule S M] [has_scalar R M₂] [semimodule S M₂] [compatible_smul M M₂ R S] (f : M →ₗ[S] M₂) (c : R) (x : M) : f (c • x) = c • f x := compatible_smul.map_smul f c x instance : is_add_monoid_hom f := { map_add := map_add f, map_zero := map_zero f } /-- convert a linear map to an additive map -/ def to_add_monoid_hom : M →+ M₂ := { to_fun := f, map_zero' := f.map_zero, map_add' := f.map_add } @[simp] lemma to_add_monoid_hom_coe : (f.to_add_monoid_hom : M → M₂) = f := rfl variable (R) /-- If `M` and `M₂` are both `R`-semimodules and `S`-semimodules and `R`-semimodule structures are defined by an action of `R` on `S` (formally, we have two scalar towers), then any `S`-linear map from `M` to `M₂` is `R`-linear. See also `linear_map.map_smul_of_tower`. -/ def restrict_scalars {S : Type*} [semiring S] [semimodule S M] [semimodule S M₂] [compatible_smul M M₂ R S] (f : M →ₗ[S] M₂) : M →ₗ[R] M₂ := { to_fun := f, map_add' := f.map_add, map_smul' := f.map_smul_of_tower } variable {R} @[simp] lemma map_sum {ι} {t : finset ι} {g : ι → M} : f (∑ i in t, g i) = (∑ i in t, f (g i)) := f.to_add_monoid_hom.map_sum _ _ theorem to_add_monoid_hom_injective : function.injective (to_add_monoid_hom : (M →ₗ[R] M₂) → (M →+ M₂)) := λ f g h, ext $ add_monoid_hom.congr_fun h /-- If two `R`-linear maps from `R` are equal on `1`, then they are equal. -/ @[ext] theorem ext_ring {f g : R →ₗ[R] M} (h : f 1 = g 1) : f = g := ext $ λ x, by rw [← mul_one x, ← smul_eq_mul, f.map_smul, g.map_smul, h] end section variables {semimodule_M : semimodule R M} {semimodule_M₂ : semimodule R M₂} {semimodule_M₃ : semimodule R M₃} variables (f : M₂ →ₗ[R] M₃) (g : M →ₗ[R] M₂) /-- Composition of two linear maps is a linear map -/ def comp : M →ₗ[R] M₃ := ⟨f ∘ g, by simp, by simp⟩ @[simp] lemma comp_apply (x : M) : f.comp g x = f (g x) := rfl @[norm_cast] lemma comp_coe : (f : M₂ → M₃) ∘ (g : M → M₂) = f.comp g := rfl end /-- If a function `g` is a left and right inverse of a linear map `f`, then `g` is linear itself. -/ def inverse [semimodule R M] [semimodule R M₂] (f : M →ₗ[R] M₂) (g : M₂ → M) (h₁ : left_inverse g f) (h₂ : right_inverse g f) : M₂ →ₗ[R] M := by dsimp [left_inverse, function.right_inverse] at h₁ h₂; exact ⟨g, λ x y, by { rw [← h₁ (g (x + y)), ← h₁ (g x + g y)]; simp [h₂] }, λ a b, by { rw [← h₁ (g (a • b)), ← h₁ (a • g b)]; simp [h₂] }⟩ end add_comm_monoid section add_comm_group variables [semiring R] [add_comm_group M] [add_comm_group M₂] variables {semimodule_M : semimodule R M} {semimodule_M₂ : semimodule R M₂} variables (f : M →ₗ[R] M₂) @[simp] lemma map_neg (x : M) : f (- x) = - f x := f.to_add_monoid_hom.map_neg x @[simp] lemma map_sub (x y : M) : f (x - y) = f x - f y := f.to_add_monoid_hom.map_sub x y instance : is_add_group_hom f := { map_add := map_add f } instance compatible_smul.int_module {S : Type*} [semiring S] [semimodule ℤ M] [semimodule S M] [semimodule ℤ M₂] [semimodule S M₂] : compatible_smul M M₂ ℤ S := ⟨λ f c x, begin induction c using int.induction_on, case hz : { simp }, case hp : n ih { simpa [add_smul] using ih }, case hn : n ih { simpa [sub_smul] using ih } end⟩ end add_comm_group end linear_map namespace is_linear_map section add_comm_monoid variables [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] variables [semimodule R M] [semimodule R M₂] include R /-- Convert an `is_linear_map` predicate to a `linear_map` -/ def mk' (f : M → M₂) (H : is_linear_map R f) : M →ₗ M₂ := ⟨f, H.1, H.2⟩ @[simp] theorem mk'_apply {f : M → M₂} (H : is_linear_map R f) (x : M) : mk' f H x = f x := rfl lemma is_linear_map_smul {R M : Type*} [comm_semiring R] [add_comm_monoid M] [semimodule R M] (c : R) : is_linear_map R (λ (z : M), c • z) := begin refine is_linear_map.mk (smul_add c) _, intros _ _, simp only [smul_smul, mul_comm] end lemma is_linear_map_smul' {R M : Type*} [semiring R] [add_comm_monoid M] [semimodule R M] (a : M) : is_linear_map R (λ (c : R), c • a) := is_linear_map.mk (λ x y, add_smul x y a) (λ x y, mul_smul x y a) variables {f : M → M₂} (lin : is_linear_map R f) include M M₂ lin lemma map_zero : f (0 : M) = (0 : M₂) := (lin.mk' f).map_zero end add_comm_monoid section add_comm_group variables [semiring R] [add_comm_group M] [add_comm_group M₂] variables [semimodule R M] [semimodule R M₂] include R lemma is_linear_map_neg : is_linear_map R (λ (z : M), -z) := is_linear_map.mk neg_add (λ x y, (smul_neg x y).symm) variables {f : M → M₂} (lin : is_linear_map R f) include M M₂ lin lemma map_neg (x : M) : f (- x) = - f x := (lin.mk' f).map_neg x lemma map_sub (x y) : f (x - y) = f x - f y := (lin.mk' f).map_sub x y end add_comm_group end is_linear_map /-- Linear endomorphisms of a module, with associated ring structure `linear_map.endomorphism_semiring` and algebra structure `module.endomorphism_algebra`. -/ abbreviation module.End (R : Type u) (M : Type v) [semiring R] [add_comm_monoid M] [semimodule R M] := M →ₗ[R] M /-- Reinterpret an additive homomorphism as a `ℤ`-linear map. -/ def add_monoid_hom.to_int_linear_map [add_comm_group M] [add_comm_group M₂] (f : M →+ M₂) : M →ₗ[ℤ] M₂ := ⟨f, f.map_add, f.map_int_module_smul⟩ /-- Reinterpret an additive homomorphism as a `ℚ`-linear map. -/ def add_monoid_hom.to_rat_linear_map [add_comm_group M] [vector_space ℚ M] [add_comm_group M₂] [vector_space ℚ M₂] (f : M →+ M₂) : M →ₗ[ℚ] M₂ := { map_smul' := f.map_rat_module_smul, ..f } /-! ### Linear equivalences -/ section set_option old_structure_cmd true /-- A linear equivalence is an invertible linear map. -/ @[nolint has_inhabited_instance] structure linear_equiv (R : Type u) (M : Type v) (M₂ : Type w) [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [semimodule R M] [semimodule R M₂] extends M →ₗ[R] M₂, M ≃+ M₂ end attribute [nolint doc_blame] linear_equiv.to_linear_map attribute [nolint doc_blame] linear_equiv.to_add_equiv infix ` ≃ₗ ` := linear_equiv _ notation M ` ≃ₗ[`:50 R `] ` M₂ := linear_equiv R M M₂ namespace linear_equiv section add_comm_monoid variables {M₄ : Type*} variables [semiring R] variables [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] [add_comm_monoid M₄] section variables [semimodule R M] [semimodule R M₂] [semimodule R M₃] include R instance : has_coe (M ≃ₗ[R] M₂) (M →ₗ[R] M₂) := ⟨to_linear_map⟩ -- see Note [function coercion] instance : has_coe_to_fun (M ≃ₗ[R] M₂) := ⟨_, λ f, f.to_fun⟩ @[simp] lemma mk_apply {to_fun inv_fun map_add map_smul left_inv right_inv a} : (⟨to_fun, map_add, map_smul, inv_fun, left_inv, right_inv⟩ : M ≃ₗ[R] M₂) a = to_fun a := rfl -- This exists for compatibility, previously `≃ₗ[R]` extended `≃` instead of `≃+`. @[nolint doc_blame] def to_equiv : (M ≃ₗ[R] M₂) → M ≃ M₂ := λ f, f.to_add_equiv.to_equiv lemma injective_to_equiv : function.injective (to_equiv : (M ≃ₗ[R] M₂) → M ≃ M₂) := λ ⟨_, _, _, _, _, _⟩ ⟨_, _, _, _, _, _⟩ h, linear_equiv.mk.inj_eq.mpr (equiv.mk.inj h) @[simp] lemma to_equiv_inj {e₁ e₂ : M ≃ₗ[R] M₂} : e₁.to_equiv = e₂.to_equiv ↔ e₁ = e₂ := injective_to_equiv.eq_iff lemma injective_to_linear_map : function.injective (coe : (M ≃ₗ[R] M₂) → (M →ₗ[R] M₂)) := λ e₁ e₂ H, injective_to_equiv $ equiv.ext $ linear_map.congr_fun H @[simp, norm_cast] lemma to_linear_map_inj {e₁ e₂ : M ≃ₗ[R] M₂} : (e₁ : M →ₗ[R] M₂) = e₂ ↔ e₁ = e₂ := injective_to_linear_map.eq_iff end section variables {semimodule_M : semimodule R M} {semimodule_M₂ : semimodule R M₂} variables (e e' : M ≃ₗ[R] M₂) @[simp, norm_cast] theorem coe_coe : ((e : M →ₗ[R] M₂) : M → M₂) = (e : M → M₂) := rfl @[simp] lemma coe_to_equiv : (e.to_equiv : M → M₂) = (e : M → M₂) := rfl @[simp] lemma to_fun_apply {m : M} : e.to_fun m = e m := rfl section variables {e e'} @[ext] lemma ext (h : ∀ x, e x = e' x) : e = e' := injective_to_equiv (equiv.ext h) protected lemma congr_arg : Π {x x' : M}, x = x' → e x = e x' | _ _ rfl := rfl protected lemma congr_fun (h : e = e') (x : M) : e x = e' x := h ▸ rfl lemma ext_iff : e = e' ↔ ∀ x, e x = e' x := ⟨λ h x, h ▸ rfl, ext⟩ end section variables (M R) /-- The identity map is a linear equivalence. -/ @[refl] def refl [semimodule R M] : M ≃ₗ[R] M := { .. linear_map.id, .. equiv.refl M } end @[simp] lemma refl_apply [semimodule R M] (x : M) : refl R M x = x := rfl /-- Linear equivalences are symmetric. -/ @[symm] def symm : M₂ ≃ₗ[R] M := { .. e.to_linear_map.inverse e.inv_fun e.left_inv e.right_inv, .. e.to_equiv.symm } /-- See Note [custom simps projection] -/ def simps.inv_fun [semimodule R M] [semimodule R M₂] (e : M ≃ₗ[R] M₂) : M₂ → M := e.symm initialize_simps_projections linear_equiv (to_fun → apply, inv_fun → symm_apply) @[simp] lemma inv_fun_apply {m : M₂} : e.inv_fun m = e.symm m := rfl variables {semimodule_M₃ : semimodule R M₃} (e₁ : M ≃ₗ[R] M₂) (e₂ : M₂ ≃ₗ[R] M₃) /-- Linear equivalences are transitive. -/ @[trans] def trans : M ≃ₗ[R] M₃ := { .. e₂.to_linear_map.comp e₁.to_linear_map, .. e₁.to_equiv.trans e₂.to_equiv } @[simp] lemma coe_to_add_equiv : ⇑(e.to_add_equiv) = e := rfl @[simp] theorem trans_apply (c : M) : (e₁.trans e₂) c = e₂ (e₁ c) := rfl @[simp] theorem apply_symm_apply (c : M₂) : e (e.symm c) = c := e.6 c @[simp] theorem symm_apply_apply (b : M) : e.symm (e b) = b := e.5 b @[simp] lemma symm_trans_apply (c : M₃) : (e₁.trans e₂).symm c = e₁.symm (e₂.symm c) := rfl @[simp] lemma trans_refl : e.trans (refl R M₂) = e := injective_to_equiv e.to_equiv.trans_refl @[simp] lemma refl_trans : (refl R M).trans e = e := injective_to_equiv e.to_equiv.refl_trans lemma symm_apply_eq {x y} : e.symm x = y ↔ x = e y := e.to_equiv.symm_apply_eq lemma eq_symm_apply {x y} : y = e.symm x ↔ e y = x := e.to_equiv.eq_symm_apply @[simp] lemma trans_symm [semimodule R M] [semimodule R M₂] (f : M ≃ₗ[R] M₂) : f.trans f.symm = linear_equiv.refl R M := by { ext x, simp } @[simp] lemma symm_trans [semimodule R M] [semimodule R M₂] (f : M ≃ₗ[R] M₂) : f.symm.trans f = linear_equiv.refl R M₂ := by { ext x, simp } @[simp, norm_cast] lemma refl_to_linear_map [semimodule R M] : (linear_equiv.refl R M : M →ₗ[R] M) = linear_map.id := rfl @[simp, norm_cast] lemma comp_coe [semimodule R M] [semimodule R M₂] [semimodule R M₃] (f : M ≃ₗ[R] M₂) (f' : M₂ ≃ₗ[R] M₃) : (f' : M₂ →ₗ[R] M₃).comp (f : M →ₗ[R] M₂) = (f.trans f' : M →ₗ[R] M₃) := rfl @[simp] theorem map_add (a b : M) : e (a + b) = e a + e b := e.map_add' a b @[simp] theorem map_zero : e 0 = 0 := e.to_linear_map.map_zero @[simp] theorem map_smul (c : R) (x : M) : e (c • x) = c • e x := e.map_smul' c x @[simp] lemma map_sum {s : finset ι} (u : ι → M) : e (∑ i in s, u i) = ∑ i in s, e (u i) := e.to_linear_map.map_sum @[simp] theorem map_eq_zero_iff {x : M} : e x = 0 ↔ x = 0 := e.to_add_equiv.map_eq_zero_iff theorem map_ne_zero_iff {x : M} : e x ≠ 0 ↔ x ≠ 0 := e.to_add_equiv.map_ne_zero_iff @[simp] theorem symm_symm : e.symm.symm = e := by { cases e, refl } protected lemma bijective : function.bijective e := e.to_equiv.bijective protected lemma injective : function.injective e := e.to_equiv.injective protected lemma surjective : function.surjective e := e.to_equiv.surjective protected lemma image_eq_preimage (s : set M) : e '' s = e.symm ⁻¹' s := e.to_equiv.image_eq_preimage s end /-- An involutive linear map is a linear equivalence. -/ def of_involutive [semimodule R M] (f : M →ₗ[R] M) (hf : involutive f) : M ≃ₗ[R] M := { .. f, .. hf.to_equiv f } @[simp] lemma coe_of_involutive [semimodule R M] (f : M →ₗ[R] M) (hf : involutive f) : ⇑(of_involutive f hf) = f := rfl end add_comm_monoid end linear_equiv
0bb830da47f112b696b603461181a03b8a4a0764
4727251e0cd73359b15b664c3170e5d754078599
/src/category_theory/single_obj.lean
033642514465a991f0711a52a9b9821e6d2cc261
[ "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
6,365
lean
/- Copyright (c) 2019 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import category_theory.endomorphism import category_theory.category.Cat import algebra.category.Mon.basic /-! # Single-object category Single object category with a given monoid of endomorphisms. It is defined to facilitate transfering some definitions and lemmas (e.g., conjugacy etc.) from category theory to monoids and groups. ## Main definitions Given a type `α` with a monoid structure, `single_obj α` is `unit` type with `category` structure such that `End (single_obj α).star` is the monoid `α`. This can be extended to a functor `Mon ⥤ Cat`. If `α` is a group, then `single_obj α` is a groupoid. An element `x : α` can be reinterpreted as an element of `End (single_obj.star α)` using `single_obj.to_End`. ## Implementation notes - `category_struct.comp` on `End (single_obj.star α)` is `flip (*)`, not `(*)`. This way multiplication on `End` agrees with the multiplication on `α`. - By default, Lean puts instances into `category_theory` namespace instead of `category_theory.single_obj`, so we give all names explicitly. -/ universes u v w namespace category_theory /-- Type tag on `unit` used to define single-object categories and groupoids. -/ @[nolint unused_arguments has_inhabited_instance] def single_obj (α : Type u) : Type := unit namespace single_obj variables (α : Type u) /-- One and `flip (*)` become `id` and `comp` for morphisms of the single object category. -/ instance category_struct [has_one α] [has_mul α] : category_struct (single_obj α) := { hom := λ _ _, α, comp := λ _ _ _ x y, y * x, id := λ _, 1 } /-- Monoid laws become category laws for the single object category. -/ instance category [monoid α] : category (single_obj α) := { comp_id' := λ _ _, one_mul, id_comp' := λ _ _, mul_one, assoc' := λ _ _ _ _ x y z, (mul_assoc z y x).symm } lemma id_as_one [monoid α] (x : single_obj α) : 𝟙 x = 1 := rfl lemma comp_as_mul [monoid α] {x y z : single_obj α} (f : x ⟶ y) (g : y ⟶ z) : f ≫ g = g * f := rfl /-- Groupoid structure on `single_obj α`. See <https://stacks.math.columbia.edu/tag/0019>. -/ instance groupoid [group α] : groupoid (single_obj α) := { inv := λ _ _ x, x⁻¹, inv_comp' := λ _ _, mul_right_inv, comp_inv' := λ _ _, mul_left_inv } lemma inv_as_inv [group α] {x y : single_obj α} (f : x ⟶ y) : inv f = f⁻¹ := by { ext, rw [comp_as_mul, inv_mul_self, id_as_one] } /-- The single object in `single_obj α`. -/ protected def star : single_obj α := unit.star /-- The endomorphisms monoid of the only object in `single_obj α` is equivalent to the original monoid α. -/ def to_End [monoid α] : α ≃* End (single_obj.star α) := { map_mul' := λ x y, rfl, .. equiv.refl α } lemma to_End_def [monoid α] (x : α) : to_End α x = x := rfl /-- There is a 1-1 correspondence between monoid homomorphisms `α → β` and functors between the corresponding single-object categories. It means that `single_obj` is a fully faithful functor. See <https://stacks.math.columbia.edu/tag/001F> -- although we do not characterize when the functor is full or faithful. -/ def map_hom (α : Type u) (β : Type v) [monoid α] [monoid β] : (α →* β) ≃ (single_obj α) ⥤ (single_obj β) := { to_fun := λ f, { obj := id, map := λ _ _, ⇑f, map_id' := λ _, f.map_one, map_comp' := λ _ _ _ x y, f.map_mul y x }, inv_fun := λ f, { to_fun := @functor.map _ _ _ _ f (single_obj.star α) (single_obj.star α), map_one' := f.map_id _, map_mul' := λ x y, f.map_comp y x }, left_inv := λ ⟨f, h₁, h₂⟩, rfl, right_inv := λ f, by cases f; obviously } lemma map_hom_id (α : Type u) [monoid α] : map_hom α α (monoid_hom.id α) = 𝟭 _ := rfl lemma map_hom_comp {α : Type u} {β : Type v} [monoid α] [monoid β] (f : α →* β) {γ : Type w} [monoid γ] (g : β →* γ) : map_hom α γ (g.comp f) = map_hom α β f ⋙ map_hom β γ g := rfl /-- Given a function `f : C → G` from a category to a group, we get a functor `C ⥤ G` sending any morphism `x ⟶ y` to `f y * (f x)⁻¹`. -/ @[simps] def difference_functor {C G} [category C] [group G] (f : C → G) : C ⥤ single_obj G := { obj := λ _, (), map := λ x y _, f y * (f x)⁻¹, map_id' := by { intro, rw [single_obj.id_as_one, mul_right_inv] }, map_comp' := by { intros, rw [single_obj.comp_as_mul, ←mul_assoc, mul_left_inj, mul_assoc, inv_mul_self, mul_one] } } end single_obj end category_theory open category_theory namespace monoid_hom /-- Reinterpret a monoid homomorphism `f : α → β` as a functor `(single_obj α) ⥤ (single_obj β)`. See also `category_theory.single_obj.map_hom` for an equivalence between these types. -/ @[reducible] def to_functor {α : Type u} {β : Type v} [monoid α] [monoid β] (f : α →* β) : (single_obj α) ⥤ (single_obj β) := single_obj.map_hom α β f @[simp] lemma id_to_functor (α : Type u) [monoid α] : (id α).to_functor = 𝟭 _ := rfl @[simp] lemma comp_to_functor {α : Type u} {β : Type v} [monoid α] [monoid β] (f : α →* β) {γ : Type w} [monoid γ] (g : β →* γ) : (g.comp f).to_functor = f.to_functor ⋙ g.to_functor := rfl end monoid_hom namespace units variables (α : Type u) [monoid α] /-- The units in a monoid are (multiplicatively) equivalent to the automorphisms of `star` when we think of the monoid as a single-object category. -/ def to_Aut : αˣ ≃* Aut (single_obj.star α) := (units.map_equiv (single_obj.to_End α)).trans $ Aut.units_End_equiv_Aut _ @[simp] lemma to_Aut_hom (x : αˣ) : (to_Aut α x).hom = single_obj.to_End α x := rfl @[simp] lemma to_Aut_inv (x : αˣ) : (to_Aut α x).inv = single_obj.to_End α (x⁻¹ : αˣ) := rfl end units namespace Mon open category_theory /-- The fully faithful functor from `Mon` to `Cat`. -/ def to_Cat : Mon ⥤ Cat := { obj := λ x, Cat.of (single_obj x), map := λ x y f, single_obj.map_hom x y f } instance to_Cat_full : full to_Cat := { preimage := λ x y, (single_obj.map_hom x y).inv_fun, witness' := λ x y, by apply equiv.right_inv } instance to_Cat_faithful : faithful to_Cat := { map_injective' := λ x y, by apply equiv.injective } end Mon
81b956ad89774d50f2a598f846089e5cd85785a1
f10d66a159ce037d07005bd6021cee6bbd6d5ff0
/to_integral_domain.lean
c7ebe7d0ef24b546e61a950c0f8750297656d9d0
[]
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
11,955
lean
import data.finsupp import algebra.ring import .to_finset import .to_multiset import to_comm_semiring noncomputable theory local infix ^ := monoid.pow open classical multiset local attribute [instance] prop_decidable local notation a `~ᵤ` b : 50 := associated a b universe u variable {α : Type u} variable [integral_domain α] --Should be placed elsewhere lemma prod_eq_zero_iff_zero_mem' {s : multiset α} : prod s = 0 ↔ (0 : α) ∈ s := begin split, { apply multiset.induction_on s, { simp * at *, }, { intros a s h1 h2, simp * at *, by_cases ha : a = 0, { simp * at *, }, { have h3 : prod s = 0, { by_contradiction h4, have : a * prod s ≠ 0, from mul_ne_zero ha h4, contradiction, }, simp [h1 h3], } } }, { intro h, rcases (exists_cons_of_mem h) with ⟨t, ht⟩, subst ht, simp * at *, } end lemma associated_of_dvd_dvd {a b : α} (h1 : a ∣ b) (h2 : b ∣ a) : a ~ᵤ b := begin rcases h2 with ⟨c, h3⟩, rcases h1 with ⟨d, h4⟩, by_cases h6 : (a = 0), { have h7 : (b = 0), { simp [h6] at h4, assumption, }, simp * at *, }, { have h3b : a = a * (d * c), { rwa [h4, mul_assoc] at h3}, have h5 : a * 1 = a * (d * c), { simpa}, have h7 : 1 = (d * c), from eq_of_mul_eq_mul_left h6 h5, rw mul_comm _ _ at h7, exact ⟨unit_of_mul_eq_one (h7.symm), by rw [h4, unit_of_mul_eq_one, units.val_coe, ←mul_assoc, mul_comm c, mul_assoc, ←h7, mul_one]⟩, } end lemma dvd_dvd_iff_associated {a b : α} : (a ~ᵤ b) ↔ ( a ∣ b) ∧ ( b ∣ a):= ⟨dvd_dvd_of_associated, assume h1, associated_of_dvd_dvd h1.1 h1.2⟩ --irreducible, prime and coprime def prime (p : α) : Prop := p ≠ 0 ∧ ¬ is_unit p ∧ ∀ a b, p ∣ (a * b) → (p ∣ a ∨ p ∣ b) def irreducible (p : α) : Prop := p ≠ 0 ∧ ¬ is_unit p ∧ ∀d, d∣p → (is_unit d ∨ (d ~ᵤ p)) def irreducible' (p : α) : Prop := p ≠ 0 ∧ ¬ is_unit p ∧ ∀ a b : α, p = a * b → (is_unit a ∨ is_unit b) lemma irreducible'_of_irreducible {p : α} (h1 : irreducible p): irreducible' p := begin have : ∀ (a b : α), p = a * b → is_unit a ∨ is_unit b, { intros a b h5, have h7 : (is_unit a ∨ (a ~ᵤ p)), from h1.2.2 a ⟨b, h5⟩, cases h7, { simp * }, { rcases h7 with ⟨u, h8⟩, have h9 : p * 1 = p * (↑u * b), { subst h8, rw [mul_comm _ p, mul_assoc] at h5, simpa *, }, have h11 : is_unit b, { exact ⟨u⁻¹, eq.symm (calc ↑(u⁻¹) = ↑u⁻¹ * 1 : by simp ... = ↑u⁻¹ * (↑u * b) : by rw [eq_of_mul_eq_mul_left h1.1 h9] ... = _ : by rw [←mul_assoc, units.inv_mul, one_mul])⟩, }, simp [h11] } }, exact ⟨h1.1, h1.2.1, this⟩, end lemma irreducible_of_irreducible' {p : α} (h1 : irreducible' p): irreducible p := begin have : ∀ (d : α), d ∣ p → is_unit d ∨ (d~ᵤ p), { intros a h5, rcases h5 with ⟨b, h6⟩, have h7 : is_unit a ∨ is_unit b, from h1.2.2 _ _ h6, cases h7, { simp *, }, { have h8 : (a ~ᵤ p), { rcases h7 with ⟨u ,hu⟩, apply exists.intro u⁻¹, subst h6, subst hu, rw [mul_comm a, ←mul_assoc, units.inv_mul, one_mul], }, simp [h8] } }, exact ⟨h1.1, h1.2.1, this⟩, end lemma irreducible_iff_irreducible' {p : α} : irreducible p ↔ irreducible' p := iff.intro irreducible'_of_irreducible irreducible_of_irreducible' lemma not_is_unit_of_irreducible {a : α} (h : irreducible a) : ¬ (is_unit a) := h.2.1 lemma dvd_irreducible_of_dvd_mul_unit_irreducible {a b c: α} (h2 : is_unit b)(h3 : irreducible c)(h4 : a ∣ (b * c)) : a ∣ c := let ⟨bᵤ, hb⟩ := h2 in let ⟨d, h5⟩ := h4 in exists.intro ( d*bᵤ.inv) (calc c = 1 * c : by simp ... = (↑bᵤ⁻¹* ↑bᵤ) * c : by rw [←units.inv_mul _] ... = ↑bᵤ⁻¹ * (↑bᵤ * c) : by simp [mul_assoc] ... = ↑bᵤ⁻¹ * (b * c): by rw [hb] ... = ↑bᵤ⁻¹ * (a * d): by rw h5 ... = bᵤ.inv * (a * d): by rw [units.inv_coe] ... = (a * d) * bᵤ.inv : by simp [mul_assoc, mul_comm] ... = a * (d * bᵤ.inv) : by simp [mul_assoc]) --correct simp? @[simp] lemma not_irreducible_one : ¬ irreducible (1 : α) := begin by_contradiction h, have : ¬is_unit (1 : α), from h.2.1, have : is_unit (1 : α), from is_unit_one, contradiction, end @[simp] lemma not_irreducible_zero : ¬ irreducible (0 : α) := begin by_contradiction h1, have : (0 : α) ≠ 0, from h1.1, contradiction, end --Problem with 'a' in the namespace lemma irreducible_of_associated {p b : α}(h1 : irreducible p)(h2 : p ~ᵤ b) : irreducible b := begin rcases h2 with ⟨u, hu⟩, have h7 : (b ≠ 0), { intro h6, simp * at *, }, have h8 : (¬ is_unit b), { intro h8, have h9 : is_unit p, from hu.symm ▸ (is_unit_mul_of_is_unit_of_is_unit (is_unit_unit u) h8), exact h1.2.1 h9 }, have h9 : (∀c, (c∣b → (is_unit c ∨ (c ~ᵤ b)))), { intros c h9, by_cases h10 : is_unit c, { simp [h10]}, { have h15 : (c~ᵤ p), { have h14 : c ∣ p, { rcases h9 with ⟨d, h11⟩, exact ⟨u * d, by {subst h11, subst hu, rw [←mul_assoc, ←mul_assoc, mul_comm c]}⟩ }, have h16: is_unit c ∨ (c~ᵤ p), from h1.2.2 c h14, simp * at *, }, have h16 : (c~ᵤ b), from h15.trans ⟨u, hu⟩, simp *, } }, exact ⟨h7,h8,h9⟩, end lemma unit_mul_irreducible_is_irreducible' {a b : α}: is_unit a → irreducible b → irreducible (a * b) | ⟨aᵤ, ha⟩ h2 := have h3 : (b ~ᵤ (a*b)), from ⟨aᵤ⁻¹, by {rw [ha, ←mul_assoc, units.inv_mul, one_mul]}⟩, irreducible_of_associated h2 h3 lemma irreducible_of_prime {p : α} (h1 : prime p) : irreducible p := begin rw prime at h1, --rw irreducible, have h2 : (p ≠ 0), { from and.elim_left h1, }, have h3 : (¬ is_unit p), from and.elim_left (and.elim_right h1), rw [irreducible_iff_irreducible', irreducible'], have h4 : ∀ (a b : α), p = a * b → is_unit a ∨ is_unit b, { intros b c h4a, by_cases h4b : (b = 0), { simp [h4b] at h4a, contradiction, }, { by_cases h4c : (c = 0), { simp [h4c] at h4a, contradiction, }, --no indent here have h4 : p ∣ (b * c), { simp *, }, have h5 : p ∣ b ∨ p ∣ c, from and.elim_right (and.elim_right h1) b c h4, cases h5, { have h6 : b ∣ b * c, {simp}, have h7 : b ∣ p, { apply dvd.trans h6, simp *, }, have h8 : (p ~ᵤ b), from associated_of_dvd_dvd h5 h7, rw associated at h8, let u := some h8, have h9 : p = ↑u * b, from some_spec h8, rw [h9, mul_comm b c] at h4a, have h10 : ↑u = c, from eq_of_mul_eq_mul_right_of_ne_zero h4b h4a, have h11 : is_unit c, { fapply exists.intro u, exact eq.symm h10, }, simp *, }, { have h6 : c ∣ b * c, {simp}, have h7 : c ∣ p, { apply dvd.trans h6, simp *, }, have h8 : (p ~ᵤ c), from associated_of_dvd_dvd h5 h7, rw associated at h8, let u := some h8, have h9 : p = ↑u * c, from some_spec h8, rw [h9] at h4a, have h10 : ↑u = b, from eq_of_mul_eq_mul_right_of_ne_zero h4c h4a, have h11 : is_unit b, { fapply exists.intro u, exact eq.symm h10, }, simp *, } } }, exact ⟨h2, h3, h4 ⟩ end lemma irreducible_of_mul_is_unit {a b c : α} (h1 : irreducible a) (h2 : is_unit b) (h3 : a * b = c) : irreducible c := begin apply irreducible_of_associated h1, exact associated_of_mul_is_unit h2 h3, end private lemma succ_eq_succ_iff_eq {n m : ℕ} : nat.succ n = nat.succ m ↔ n = m := begin split, exact nat.succ_inj, intro h, simp *, end private lemma eq_zero_or_exists_eq_succ_succ_of_ne_one {n : ℕ} (h : n ≠ 1) : n = 0 ∨ ∃ m, n = nat.succ (nat.succ m) := begin by_cases h2 : n = 0, {simp *}, { rcases (nat.exists_eq_succ_of_ne_zero h2) with ⟨m, hm⟩, subst hm, simp * at *, rw succ_eq_succ_iff_eq at h, rcases (nat.exists_eq_succ_of_ne_zero h) with ⟨s, hs⟩, subst hs, exact ⟨s, rfl⟩, } end lemma irreducible_pow {a : α} {n : ℕ} (h : irreducible a) : irreducible (a^n) ↔ n = 1 := begin split, { intros h1, by_contradiction h2, have h3 : n = 0 ∨ ∃ m, n = nat.succ (nat.succ m), from eq_zero_or_exists_eq_succ_succ_of_ne_one h2, cases h3, { simp * at *, }, { rcases h3 with ⟨m, hm⟩, subst hm, rw pow_succ at *, rw irreducible_iff_irreducible' at h1, unfold irreducible' at h1, have h4: is_unit a ∨ is_unit (a ^ nat.succ m), from h1.2.2 _ _ rfl, cases h4, { have : ¬is_unit a, from h.2.1, contradiction, }, { rw pow_succ at h4, rw is_unit_mul_iff_is_unit_and_is_unit at h4, have : ¬is_unit a, from h.2.1, exact this h4.1, } } }, { intro h, simp * at *, } end lemma not_is_unit_prod_of_ne_zero_of_forall_mem_irreducible {s : multiset α} (h1 : s ≠ 0) (h2 : ∀x : α, x ∈ s → irreducible x) : ¬is_unit s.prod := begin rcases (exists_mem_of_ne_zero h1) with ⟨x, hx⟩, have h2b : x ∣ (s.prod), from dvd_prod_of_mem _ hx, have h3: irreducible x, from h2 x hx, have h4: ¬is_unit x, from not_is_unit_of_irreducible h3, exact not_is_unit_of_not_is_unit_dvd h4 h2b, end --- GCDs section gcd_id variables [has_gcd α] {a b c : α} lemma gcd_zero_associated_left {f : α} : (gcd f (0 : α)) ~ᵤ f := begin apply associated_of_dvd_dvd, exact gcd_left, apply gcd_min, simp, simp end lemma gcd_zero_associated_right {α : Type u} [integral_domain α][has_gcd α] {f : α} : (gcd (0 : α) f) ~ᵤ f := begin apply associated_of_dvd_dvd, exact gcd_right, apply gcd_min, simp, simp end lemma gcd_eq_zero_iff_eq_zero_and_eq_zero {α : Type u} [integral_domain α][has_gcd α] {f g : α} : gcd f g = 0 ↔ f = 0 ∧ g = 0:= begin constructor, { intro h1, by_contradiction h2, have h3 : ¬(g = 0 ∧ f = 0), { rw and.comm at h2, exact h2 }, simp at *, by_cases h4 : (f = 0), { have h5 : g ≠ 0, from h2 h4, rw h4 at h1, have h6 : ((gcd 0 g) ~ᵤ g), from gcd_zero_associated_right, rw [h1] at h6, have h7 : (g ~ᵤ 0), from associated.symm h6, rw [associated_zero_iff_eq_zero] at h7, contradiction, }, { apply h4, apply eq_zero_of_zero_dvd, rw ← h1, exact gcd_left, } }, { intro h1, have h2 : f = 0, from and.elim_left h1, have h3 : g = 0, from and.elim_right h1, rw [h2, h3], exact gcd_zero_zero_eq_zero } end --Isn't it associated? lemma gcd_comm : (gcd a b ~ᵤ gcd b a) := begin apply associated_of_dvd_dvd, { have h1 : gcd a b ∣ a, from gcd_left, have h2 : gcd a b ∣ b, from gcd_right, exact gcd_min h2 h1, }, { have h1 : gcd b a ∣ b, from gcd_left, have h2 : gcd b a ∣ a, from gcd_right, exact gcd_min h2 h1, } end end gcd_id
8aa2751e9e6d934212b773e316ee7f6e9bb0460a
82e44445c70db0f03e30d7be725775f122d72f3e
/src/tactic/transform_decl.lean
698bfd96d2f42f8ceb842d502b58cc4754ab330f
[ "Apache-2.0" ]
permissive
stjordanis/mathlib
51e286d19140e3788ef2c470bc7b953e4991f0c9
2568d41bca08f5d6bf39d915434c8447e21f42ee
refs/heads/master
1,631,748,053,501
1,627,938,886,000
1,627,938,886,000
228,728,358
0
0
Apache-2.0
1,576,630,588,000
1,576,630,587,000
null
UTF-8
Lean
false
false
4,356
lean
/- Copyright (c) 2017 Mario Carneiro All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Floris van Doorn -/ import tactic.core namespace tactic open expr /-- Auxilliary function for `additive_test`. The bool argument *only* matters when applied to exactly a constant. -/ meta def additive_test_aux (f : name → option name) (ignore : name_map $ list ℕ) : bool → expr → bool | b (var n) := tt | b (sort l) := tt | b (const n ls) := b || (f n).is_some | b (mvar n m t) := tt | b (local_const n m bi t) := tt | b (app e f) := additive_test_aux tt e && -- this might be inefficient. -- If it becomes a performance problem: we can give this info for the recursive call to `e`. match ignore.find e.get_app_fn.const_name with | some l := if e.get_app_num_args + 1 ∈ l then tt else additive_test_aux ff f | none := additive_test_aux ff f end | b (lam n bi e t) := additive_test_aux ff t | b (pi n bi e t) := additive_test_aux ff t | b (elet n g e f) := additive_test_aux ff e && additive_test_aux ff f | b (macro d args) := tt /-- `additive_test f replace_all ignore e` tests whether the expression `e` contains no constant `nm` that is not applied to any arguments, and such that `f nm = none`. This is used in `@[to_additive]` for deciding which subexpressions to transform: we only transform constants if `additive_test` applied to their first argument returns `tt`. This means we will replace expression applied to e.g. `α` or `α × β`, but not when applied to e.g. `ℕ` or `ℝ × α`. `f` is the dictionary of declarations that are in the `to_additive` dictionary. We ignore all arguments specified in the `name_map` `ignore`. If `replace_all` is `tt` the test always return `tt`. -/ meta def additive_test (f : name → option name) (replace_all : bool) (ignore : name_map $ list ℕ) (e : expr) : bool := if replace_all then tt else additive_test_aux f ignore ff e private meta def transform_decl_with_prefix_fun_aux (f : name → option name) (replace_all trace : bool) (ignore reorder : name_map $ list ℕ) (pre tgt_pre : name) (attrs : list name) : name → command := λ src, do let tgt := src.map_prefix (λ n, if n = pre then some tgt_pre else none), (get_decl tgt >> skip) <|> do decl ← get_decl src, (decl.type.list_names_with_prefix pre).mfold () (λ n _, transform_decl_with_prefix_fun_aux n), (decl.value.list_names_with_prefix pre).mfold () (λ n _, transform_decl_with_prefix_fun_aux n), is_protected ← is_protected_decl src, env ← get_env, let decl := decl.update_with_fun env (name.map_prefix f) (additive_test f replace_all ignore) reorder tgt, pp_decl ← pp decl, when trace $ trace!"[to_additive] > generating\n{pp_decl}", decorate_error (format!"@[to_additive] failed. Type mismatch in additive declaration. For help, see the docstring of `to_additive.attr`, section `Troubleshooting`. Failed to add declaration\n{pp_decl} Nested error message:\n").to_string $ -- empty line is intentional if is_protected then add_protected_decl decl else add_decl decl, attrs.mmap' (λ n, copy_attribute n src tgt) /-- Make a new copy of a declaration, replacing fragments of the names of identifiers in the type and the body using the function `f`. This is used to implement `@[to_additive]`. -/ meta def transform_decl_with_prefix_fun (f : name → option name) (replace_all trace : bool) (ignore reorder : name_map $ list ℕ) (src tgt : name) (attrs : list name) : command := do transform_decl_with_prefix_fun_aux f replace_all trace ignore reorder src tgt attrs src, ls ← get_eqn_lemmas_for tt src, ls.mmap' $ transform_decl_with_prefix_fun_aux f replace_all trace ignore reorder src tgt attrs /-- Make a new copy of a declaration, replacing fragments of the names of identifiers in the type and the body using the dictionary `dict`. This is used to implement `@[to_additive]`. -/ meta def transform_decl_with_prefix_dict (dict : name_map name) (replace_all trace : bool) (ignore reorder : name_map $ list ℕ) (src tgt : name) (attrs : list name) : command := transform_decl_with_prefix_fun dict.find replace_all trace ignore reorder src tgt attrs end tactic
99d80e9af31110e64cfb2047c2399be7dff844f0
77c5b91fae1b966ddd1db969ba37b6f0e4901e88
/src/analysis/normed_space/multilinear.lean
68160c4b9c4cf2bb1bb538811380bb9df68446b4
[ "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
73,293
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 nnreal open finset metric local attribute [instance, priority 1001] add_comm_group.to_add_comm_monoid normed_group.to_add_comm_group normed_space.to_module -- hack to speed up simp when dealing with complicated types local attribute [-instance] unique.subsingleton pi.subsingleton /-! ### Type variables We use the following type variables in this file: * `𝕜` : a `nondiscrete_normed_field`; * `ι`, `ι'` : finite index types with decidable equality; * `E`, `E₁` : families 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₁ wE' wEi wG wG' variables {𝕜 : Type u} {ι : Type v} {ι' : Type v'} {n : ℕ} {E : ι → Type wE} {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 (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 casesI is_empty_or_nonempty ι, { refine ⟨∥f 0∥ + 1, add_pos_of_nonneg_of_pos (norm_nonneg _) zero_lt_one, λ m, _⟩, obtain rfl : m = 0, from funext (is_empty.elim ‹_›), simp [univ_eq_empty, zero_le_one] }, 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 `le_cInf` 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∥ := le_cInf 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_cInf bounds_nonempty, 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∥ := div_le_of_nonneg_of_le_mul (prod_nonneg $ λ i _, norm_nonneg _) (op_norm_nonneg _) (f.le_op_norm m) /-- 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 := cInf_le bounds_bdd_below ⟨hMp, hM⟩ /-- The operator norm satisfies the triangle inequality. -/ theorem op_norm_add_le : ∥f + g∥ ≤ ∥f∥ + ∥g∥ := cInf_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⟩ theorem le_op_norm_mul_prod_of_le {b : ι → ℝ} (hm : ∀ i, ∥m i∥ ≤ b i) : ∥f m∥ ≤ ∥f∥ * ∏ i, b i := (f.le_op_norm m).trans $ mul_le_mul_of_nonneg_left (prod_le_prod (λ _ _, norm_nonneg _) (λ i _, hm i)) (norm_nonneg f) theorem le_op_norm_mul_pow_card_of_le {b : ℝ} (hm : ∀ i, ∥m i∥ ≤ b) : ∥f m∥ ≤ ∥f∥ * b ^ fintype.card ι := by simpa only [prod_const] using f.le_op_norm_mul_prod_of_le m hm theorem le_op_norm_mul_pow_of_le {Ei : fin n → Type*} [Π i, normed_group (Ei i)] [Π i, normed_space 𝕜 (Ei i)] (f : continuous_multilinear_map 𝕜 Ei G) (m : Π i, Ei i) {b : ℝ} (hm : ∥m∥ ≤ b) : ∥f m∥ ≤ ∥f∥ * b ^ n := by simpa only [fintype.card_fin] using f.le_op_norm_mul_pow_card_of_le m (λ i, (norm_le_pi_norm m i).trans hm) /-- 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∥`, `nnnorm` version. -/ theorem le_op_nnnorm : nnnorm (f m) ≤ nnnorm f * ∏ i, nnnorm (m i) := nnreal.coe_le_coe.1 $ by { push_cast, exact f.le_op_norm m } theorem le_of_op_nnnorm_le {C : ℝ≥0} (h : nnnorm f ≤ C) : nnnorm (f m) ≤ C * ∏ i, nnnorm (m i) := (f.le_op_nnnorm m).trans $ mul_le_mul' h le_rfl lemma op_norm_prod (f : continuous_multilinear_map 𝕜 E G) (g : continuous_multilinear_map 𝕜 E G') : ∥f.prod g∥ = max (∥f∥) (∥g∥) := le_antisymm (op_norm_le_bound _ (norm_nonneg (f, g)) (λ m, have H : 0 ≤ ∏ i, ∥m i∥, from prod_nonneg $ λ _ _, norm_nonneg _, by simpa only [prod_apply, prod.norm_def, max_mul_of_nonneg, H] using max_le_max (f.le_op_norm m) (g.le_op_norm m))) $ max_le (f.op_norm_le_bound (norm_nonneg _) $ λ m, (le_max_left _ _).trans ((f.prod g).le_op_norm _)) (g.op_norm_le_bound (norm_nonneg _) $ λ m, (le_max_right _ _).trans ((f.prod g).le_op_norm _)) lemma norm_pi {ι' : Type v'} [fintype ι'] {E' : ι' → Type wE'} [Π i', normed_group (E' i')] [Π i', normed_space 𝕜 (E' i')] (f : Π i', continuous_multilinear_map 𝕜 E (E' i')) : ∥pi f∥ = ∥f∥ := begin apply le_antisymm, { refine (op_norm_le_bound _ (norm_nonneg f) (λ m, _)), dsimp, rw pi_norm_le_iff, exacts [λ i, (f i).le_of_op_norm_le m (norm_le_pi_norm f i), mul_nonneg (norm_nonneg f) (prod_nonneg $ λ _ _, norm_nonneg _)] }, { refine (pi_norm_le_iff (norm_nonneg _)).2 (λ i, _), refine (op_norm_le_bound _ (norm_nonneg _) (λ m, _)), refine le_trans _ ((pi f).le_op_norm m), convert norm_le_pi_norm (λ j, f j m) i } end section variables (𝕜 E E' G G') /-- `continuous_multilinear_map.prod` as a `linear_isometry_equiv`. -/ def prodL : (continuous_multilinear_map 𝕜 E G) × (continuous_multilinear_map 𝕜 E G') ≃ₗᵢ[𝕜] continuous_multilinear_map 𝕜 E (G × G') := { to_fun := λ f, f.1.prod f.2, inv_fun := λ f, ((continuous_linear_map.fst 𝕜 G G').comp_continuous_multilinear_map f, (continuous_linear_map.snd 𝕜 G G').comp_continuous_multilinear_map f), map_add' := λ f g, rfl, map_smul' := λ c f, rfl, left_inv := λ f, by ext; refl, right_inv := λ f, by ext; refl, norm_map' := λ f, op_norm_prod f.1 f.2 } /-- `continuous_multilinear_map.pi` as a `linear_isometry_equiv`. -/ def piₗᵢ {ι' : Type v'} [fintype ι'] {E' : ι' → Type wE'} [Π i', normed_group (E' i')] [Π i', normed_space 𝕜 (E' i')] : @linear_isometry_equiv 𝕜 (Π i', continuous_multilinear_map 𝕜 E (E' i')) (continuous_multilinear_map 𝕜 E (Π i, E' i)) _ _ _ (@pi.module ι' _ 𝕜 _ _ (λ i', infer_instance)) _ := { to_linear_equiv := -- note: `pi_linear_equiv` does not unify correctly here, presumably due to issues with dependent -- typeclass arguments. { map_add' := λ f g, rfl, map_smul' := λ c f, rfl, .. pi_equiv, }, norm_map' := norm_pi } end 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 lemma tsum_eval {α : Type*} {p : α → continuous_multilinear_map 𝕜 E G} (hp : summable p) (m : Π i, E i) : (∑' a, p a) m = ∑' a, p a m := (has_sum_eval hp.has_sum m).tsum_eq.symm 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 (multilinear_map.mk_pi_algebra 𝕜 ι A) (if nonempty ι then 1 else ∥(1 : A)∥) $ begin intro m, casesI is_empty_or_nonempty ι with hι hι, { simp [eq_empty_of_is_empty univ, not_nonempty_iff.2 hι] }, { simp [norm_prod_le' univ univ_nonempty, 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 [is_empty ι] : ∥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 (not_nonempty_iff.mpr ‹_›), convert ratio_le_op_norm _ (λ _, (1 : A)), simp [eq_empty_of_is_empty (univ : finset ι)], end @[simp] lemma norm_mk_pi_algebra [norm_one_class A] : ∥continuous_multilinear_map.mk_pi_algebra 𝕜 ι A∥ = 1 := begin casesI is_empty_or_nonempty ι, { simp [norm_mk_pi_algebra_of_empty] }, { refine le_antisymm norm_mk_pi_algebra_le _, convert ratio_le_op_norm _ (λ _, 1); [skip, apply_instance], simp }, 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 (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 @[simp] 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 (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 namespace continuous_linear_map lemma 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 /-- `continuous_linear_map.comp_continuous_multilinear_map` as a bundled continuous bilinear map. -/ def comp_continuous_multilinear_mapL : (G →L[𝕜] G') →L[𝕜] continuous_multilinear_map 𝕜 E G →L[𝕜] continuous_multilinear_map 𝕜 E G' := linear_map.mk_continuous₂ (linear_map.mk₂ 𝕜 comp_continuous_multilinear_map (λ f₁ f₂ g, rfl) (λ c f g, rfl) (λ f g₁ g₂, by { ext1, apply f.map_add }) (λ c f g, by { ext1, simp })) 1 $ λ f g, by { rw one_mul, exact f.norm_comp_continuous_multilinear_map_le g } /-- Flip arguments in `f : G →L[𝕜] continuous_multilinear_map 𝕜 E G'` to get `continuous_multilinear_map 𝕜 E (G →L[𝕜] G')` -/ def flip_multilinear (f : G →L[𝕜] continuous_multilinear_map 𝕜 E G') : continuous_multilinear_map 𝕜 E (G →L[𝕜] G') := multilinear_map.mk_continuous { to_fun := λ m, linear_map.mk_continuous { to_fun := λ x, f x m, map_add' := λ x y, by simp only [map_add, continuous_multilinear_map.add_apply], map_smul' := λ c x, by simp only [continuous_multilinear_map.smul_apply, map_smul, ring_hom.id_apply] } (∥f∥ * ∏ i, ∥m i∥) $ λ x, by { rw mul_right_comm, exact (f x).le_of_op_norm_le _ (f.le_op_norm x) }, map_add' := λ m i x y, by { ext1, simp only [add_apply, continuous_multilinear_map.map_add, linear_map.coe_mk, linear_map.mk_continuous_apply]}, map_smul' := λ m i c x, by { ext1, simp only [coe_smul', continuous_multilinear_map.map_smul, linear_map.coe_mk, linear_map.mk_continuous_apply, pi.smul_apply]} } ∥f∥ $ λ m, linear_map.mk_continuous_norm_le _ (mul_nonneg (norm_nonneg f) (prod_nonneg $ λ i hi, norm_nonneg (m i))) _ end continuous_linear_map open continuous_multilinear_map 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 namespace continuous_multilinear_map lemma norm_comp_continuous_linear_le (g : continuous_multilinear_map 𝕜 E₁ G) (f : Π i, E i →L[𝕜] E₁ i) : ∥g.comp_continuous_linear_map f∥ ≤ ∥g∥ * ∏ i, ∥f i∥ := op_norm_le_bound _ (mul_nonneg (norm_nonneg _) $ prod_nonneg $ λ i hi, norm_nonneg _) $ λ m, calc ∥g (λ i, f i (m i))∥ ≤ ∥g∥ * ∏ i, ∥f i (m i)∥ : g.le_op_norm _ ... ≤ ∥g∥ * ∏ i, (∥f i∥ * ∥m i∥) : mul_le_mul_of_nonneg_left (prod_le_prod (λ _ _, norm_nonneg _) (λ i hi, (f i).le_op_norm (m i))) (norm_nonneg g) ... = (∥g∥ * ∏ i, ∥f i∥) * ∏ i, ∥m i∥ : by rw [prod_mul_distrib, mul_assoc] /-- `continuous_multilinear_map.comp_continuous_linear_map` as a bundled continuous linear map. This implementation fixes `f : Π i, E i →L[𝕜] E₁ i`. TODO: Actually, the map is multilinear in `f` but an attempt to formalize this failed because of issues with class instances. -/ def comp_continuous_linear_mapL (f : Π i, E i →L[𝕜] E₁ i) : continuous_multilinear_map 𝕜 E₁ G →L[𝕜] continuous_multilinear_map 𝕜 E G := linear_map.mk_continuous { to_fun := λ g, g.comp_continuous_linear_map f, map_add' := λ g₁ g₂, rfl, map_smul' := λ c g, rfl } (∏ i, ∥f i∥) $ λ g, (norm_comp_continuous_linear_le _ _).trans_eq (mul_comm _ _) @[simp] lemma comp_continuous_linear_mapL_apply (g : continuous_multilinear_map 𝕜 E₁ G) (f : Π i, E i →L[𝕜] E₁ i) : comp_continuous_linear_mapL f g = g.comp_continuous_linear_map f := rfl lemma norm_comp_continuous_linear_mapL_le (f : Π i, E i →L[𝕜] E₁ i) : ∥@comp_continuous_linear_mapL 𝕜 ι E E₁ G _ _ _ _ _ _ _ _ _ f∥ ≤ (∏ i, ∥f i∥) := linear_map.mk_continuous_norm_le _ (prod_nonneg $ λ i _, norm_nonneg _) _ end continuous_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, map_smul' := λ m i c x, by simp } 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. -/ section local attribute [instance] unique.subsingleton 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 end /-! #### 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)} /-- 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)} (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
c0da0c79c826b587c308775fedec161eb866f8ad
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/854.lean
08b8d86eb28fcdf734da25ec311031889d159c59
[ "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
427
lean
example (a : Nat) : (a - 8000) + 1 = Nat.succ (a - 8000) := by rfl theorem mwe (a : Nat) : (a - 100000000) + 1 <= 1 := by apply Nat.succ_le_succ sorry @[irreducible] def someConstant : Nat := 100000000 theorem mwe' (a : Nat) : (a - someConstant) + 1 <= someConstant + 1 := by apply Nat.succ_le_succ sorry theorem mwe'' (a : Nat) : Nat.add (a - 100000000) 1 <= Nat.zero.succ := by apply Nat.succ_le_succ sorry
3b64e75edd87e80cefa345f053ffa47ee509800b
0851884047bb567d19e188e8f1ad959c5ae9c5ce
/src/Topology/Material/Path_Homotopy.lean
dd9bb51e016b08a8cae49149d6b94dcec97abda2
[ "Apache-2.0" ]
permissive
yz5216/xena-UROP-2018
00d3f71a831324966d40d302544ed2cbbec3fd0f
5e9da9dc64dc51897677f8b73ab9f94061a8d977
refs/heads/master
1,584,922,436,989
1,531,487,250,000
1,531,487,250,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
8,930
lean
import analysis.topology.continuity import analysis.topology.topological_space import analysis.topology.infinite_sum import analysis.topology.topological_structures import analysis.topology.uniform_space import analysis.real import data.real.basic tactic.norm_num universe u open set filter lattice classical noncomputable theory section Mario variables {α : Type*} [topological_space α ] ( x y : α ) ---- Mario def I01 := {x : ℝ // 0 ≤ x ∧ x ≤ 1} #check I01 #check topological_space -- noncomputable def h : ℝ := 0.5 -- Has euclidean subspace topology/computability?? instance : topological_space I01 := by unfold I01; apply_instance instance : has_zero I01 := ⟨⟨0, le_refl _, zero_le_one⟩⟩ instance : has_one I01 := ⟨⟨1, zero_le_one, le_refl _⟩⟩ /- instance : ( h : I01 ) := begin end -/ #check has_one structure path {α} [topological_space α] (x y : α) := (to_fun : I01 → α) (at_zero : to_fun 0 = x) (at_one : to_fun 1 = y) (cont : continuous to_fun) #print prefix path def p : path x y := { to_fun := sorry, at_zero := sorry, at_one := sorry, cont := sorry } /- instance {α} [topological_space α] (x y : α) : has_coe_to_fun (path x y) := begin exact ⟨_, path.to_fun⟩, end -/ instance hello {α} [topological_space α] (x y : α) : has_coe_to_fun (path x y) := ⟨_, path.to_fun⟩ #print prefix path #check @has_coe_to_fun end Mario ---------- -- attribute [class] path section Interface_One -- Path interface and Loop variables {α : Type*} [topological_space α ] ( x y : α ) variables ( z w x0 : α ) variables ( g1 : path x y ) ( g2 : path z w) variable l : I01 → α -- PATH Interface -- if equal .to_fun (to distinguish loop / continuously deformed) -- equality of path, starting points and continuity -- for later paths homotopy -- checking ending points def equal_of_pts (f g : I01 → α ) : Prop := f 0 = g 0 ∧ f 1 = g 1 def equal_of_pts_path : Prop := equal_of_pts g1.to_fun g2.to_fun def check_pts ( x y : α ) ( g : I01 → α ) := g 0 = x ∧ g 1 = y def check_pts_of_path ( x y : α ) ( h : path z w ) := check_pts x y h.to_fun def equal_of_path : Prop := g1.to_fun == g2.to_fun -- == ? /- path.mk : Π {α : Type u_2} [_inst_2 : topological_space α] {x y : α} (to_fun : I01 → α), to_fun 0 = x → to_fun 1 = y → continuous to_fun → path x y -/ def is_path ( x y : α ) ( f : I01 → α ) : Prop := f 0 = x ∧ f 1 = y ∧ continuous f -- f is to_fun creator -- #check is_path x y l def to_path { x y : α} ( f : I01 → α ) ( H : is_path x y f) : path x y := { to_fun := f, at_zero := H.left, at_one := H.right.left, cont := H.right.right } lemma cont_of_path ( g : path z w ) : continuous g.to_fun := g.cont -- 'Exists' is not a class #check g1.to_fun def fun_of_path {α} [topological_space α ] { x1 x2 : α } ( g : path x1 x2 ) : I01 → α := g.to_fun #check fun_of_path g1 -- can write equal_of_path in terms of this --- COMPOSITION OF PATHS noncomputable def h : ℝ := 1/2 lemma geq_half : (0 : ℝ) ≤ (1/2 : ℝ) := by norm_num lemma leq_half : (1/2 : ℝ) ≤ (1 : ℝ) := by norm_num #print h #print prefix real.division_ring noncomputable def comp_of_path {α} [topological_space α] { x y z : α } ( f : path x y )( g : path y z ) : path x z := { to_fun := sorry, ---λ t : I01, if t ≤ h then f.to_fun (2*t) else g.to_fun (2*t -1) , at_zero := sorry, at_one := sorry, cont := sorry } --- /- noncomputable def h : I01 := 1 / 2 lemma geq_half : (0 : ℝ) ≤ (1/2 : ℝ) := by norm_num lemma leq_half : (1/2 : ℝ) ≤ (1 : ℝ) := by norm_num lemma geq_half2 : (0 : I01) ≤ (1/2 : I01) := by norm_num lemma leq_half2 : (1/2 : I01) ≤ (1 : I01) := by norm_num instance : ( h : I01 ) := ⟨⟨0, le_refl _, zero_le_one⟩⟩ -/ -- LOOP -- Definition of loop -- (extend path??) !!!! ------------ /- structure loop {α} [topological_space α] (x : α) { y : α } extends path x y := (base_pt : to_fun 0 = x ∧ to_fun 1 = x) -/ /- structure loop {α} [topological_space α] (x : α) := (to_fun : I01 → α) (base_pt : to_fun 0 = x ∧ to_fun 1 = x) (cont : continuous to_fun) -/ def is_loop ( g : path x y) : Prop := g.at_zero == g.at_one -- function to check loop structure loop2 {α} [topological_space α] (x : α) extends path x x := (base_pt : to_fun 0 = x ∧ to_fun 1 = x) --(base_pt : is_loop ) def loop3 {α} [topological_space α] (x0 : α) : Type* := path x0 x0 --#check loop --- not quite #check @loop2 #check @loop3 #check @path -- lemma lemma loop_is_path (l1 : loop2 x0) : path x0 x0 := l1.to_path end Interface_One ---------------------------- section Interface_Two -- Homotopy variables {α : Type*} [topological_space α ] variables {β : Type*} [topological_space β ] ( x y : β ) variables ( z w x0 : β ) variable s : I01 --variables ( f : path x y ) ( g : path z w) -- variable h : α → β def P := topological_space (I01 × α ) -- HOMOTOPY #check @continuous -- General Homotopy structure homotopy {α} {β} [topological_space α] [topological_space β] (f : α → β) ( hcf : continuous f) (g : α → β) ( hcg : continuous g) := (to_fun : I01 × α → β ) -- for product topology (at_zero : (function.curry to_fun) 0 = f ) (at_one : (function.curry to_fun) 1 = g) (cont : continuous to_fun ) -- w.r.t product topology -- Path Homotopy /- structure path_homotopy2 {β} [topological_space β] { x y z w : β } ( f : path x y) ( g : path z w) := (to_fun : I01 × I01 → β ) -- for product topology (at_zero : (function.curry to_fun) 0 = f.to_fun ) (at_one : (function.curry to_fun) 1 = g.to_fun ) (cont : continuous to_fun ) (eq_pts : ∀ s : I01, equal_of_pts f.to_fun ((function.curry to_fun) s) ) --(eq_pts : ∀ s : I01, equal_of_pts_path f ((function.curry to_fun) s) ) -- check that F(s, 0)=x and F(s,1)= y -- Type errors? structure path_homotopy3 {β} [topological_space β] { x y z w : β } ( f : path x y) ( g : path z w) := (to_fun : I01 → I01 → β ) -- for product topology (at_zero : to_fun 0 = f.to_fun ) (at_one : to_fun 1 = g.to_fun ) (cont : continuous to_fun ) (eq_pts : ∀ s : I01, equal_of_pts f.to_fun (to_fun s) ) --(eq_pts : ∀ s : I01, equal_of_pts_path f (to_fun s) ) -/ structure path_homotopy {β} [topological_space β] { x y : β } ( f : path x y) ( g : path x y) := (to_fun : I01 × I01 → β ) (path_s : ∀ s : I01, is_path x y ( λ t, to_fun (s, t) ) ) (at_zero : ∀ y, to_fun (0,y) = f.to_fun y ) (at_one : ∀ y, to_fun (1,y) = g.to_fun y) (cont : continuous to_fun) #check @path_homotopy variables (f : path x y) (g : path x y) variable F : path_homotopy f g #check f.to_fun 0 #check F.at_zero #print prefix path_homotopy def hom_to_path { x y : β } { f g : path x y } ( F : path_homotopy f g ) (s : I01) : path x y := to_path ( λ t, F.to_fun (s, t)) (F.path_s s) -- to_path { x y : α} ( f : I01 → α ) ( H : is_path x y f) #check (F.path_s s ).left -- Ending points of path_homotopy are fixed lemma hom_eq_of_pts { x y : β } { f g : path x y } ( F : path_homotopy f g ) : ∀ s : I01, check_pts x y ( λ t, F.to_fun (s, t)) := -- equal_of_pts f.to_fun ( λ t, F.to_fun (s, t) ) := begin intro s, unfold check_pts, split, have H1: F.to_fun (s, 0) = ( λ t, F.to_fun (s, t)) 0, simp, rw H1, exact (F.path_s s).left, have H1: F.to_fun (s, 1) = ( λ t, F.to_fun (s, t)) 1, simp, rw H1, exact (F.path_s s).right.left end lemma hom_path_is_cont { x y : β } { f g : path x y } ( F : path_homotopy f g ) : ∀ s : I01, continuous ( λ t, F.to_fun (s, t)) := begin intro s, exact (F.path_s s).right.right end definition is_homotopic_to { x y : β } (f : path x y) ( g : path x y) : Prop := nonempty ( path_homotopy f g) /- lemma hom_is_path { f g : path x y } ( F : path_homotopy f g ) : ∀s : I01, is_path ( f.to_fun 0) ( f.to_fun 1) ( λ t , F.to_fun (s, t) ) := begin intro s, unfold is_path, split, --rw (F s).at_zero, sorry ,sorry end #check hom_is_path -/ -- Homotopy as a class ???? #check is_homotopic_to -- Equivalence of Homotopy def path_homotopy_id { x y : β} (f : path x y) : path_homotopy f f := { to_fun := λ pair , f.to_fun pair.2 , path_s := begin intro s, unfold is_path, exact ⟨ f.at_zero, f.at_one, f.cont ⟩ end, at_zero := by simp , at_one := by simp , cont := sorry, --begin unfold continuous, end } theorem homotopy_is_reflexive : @reflexive (path x y) ( is_homotopic_to ) := begin unfold reflexive, intro f, unfold is_homotopic_to, have H : path_homotopy f f, exact path_homotopy_id f , exact ⟨ H ⟩ end #check @is_refl #check @reflexive #check nonempty -- Associativity of homotopy end Interface_Two
8ade42934436c78a164723dbcab5221fdbf8a2d0
aa2345b30d710f7e75f13157a35845ee6d48c017
/tests/tactics.lean
907bd74d021db3ea95dd2fc9b43bb5eccc6f44ca
[ "Apache-2.0" ]
permissive
CohenCyril/mathlib
5241b20a3fd0ac0133e48e618a5fb7761ca7dcbe
a12d5a192f5923016752f638d19fc1a51610f163
refs/heads/master
1,586,031,957,957
1,541,432,824,000
1,541,432,824,000
156,246,337
0
0
Apache-2.0
1,541,434,514,000
1,541,434,513,000
null
UTF-8
Lean
false
false
17,434
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon, Scott Morrison -/ import tactic data.set.lattice data.prod data.vector tactic.rewrite data.stream.basic tactic.tfae tactic.converter.interactive tactic.ring tactic.ring2 section tauto₀ variables p q r : Prop variables h : p ∧ q ∨ p ∧ r include h example : p ∧ p := by tauto end tauto₀ section tauto₁ variables α : Type variables p q r : α → Prop variables h : (∃ x, p x ∧ q x) ∨ (∃ x, p x ∧ r x) include h example : ∃ x, p x := by tauto end tauto₁ section tauto₂ variables α : Type variables x : α variables p q r : α → Prop variables h₀ : (∀ x, p x → q x → r x) ∨ r x variables h₁ : p x variables h₂ : q x include h₀ h₁ h₂ example : ∃ x, r x := by tauto end tauto₂ section tauto₃ example (p : Prop) : p ∧ true ↔ p := by tauto example (p : Prop) : p ∨ false ↔ p := by tauto example (p q r : Prop) [decidable p] [decidable r] : p ∨ (q ∧ r) ↔ (p ∨ q) ∧ (r ∨ p ∨ r) := by tauto example (p q r : Prop) [decidable q] [decidable r] : p ∨ (q ∧ r) ↔ (p ∨ q) ∧ (r ∨ p ∨ r) := by tauto example (p q : Prop) [decidable q] [decidable p] (h : ¬ (p ↔ q)) (h' : ¬ p) : q := by tauto example (p q : Prop) [decidable q] [decidable p] (h : ¬ (p ↔ q)) (h' : p) : ¬ q := by tauto example (p q : Prop) [decidable q] [decidable p] (h : ¬ (p ↔ q)) (h' : q) : ¬ p := by tauto example (p q : Prop) [decidable q] [decidable p] (h : ¬ (p ↔ q)) (h' : ¬ q) : p := by tauto example (p q : Prop) [decidable q] [decidable p] (h : ¬ (p ↔ q)) (h' : ¬ q) (h'' : ¬ p) : false := by tauto example (p q r : Prop) [decidable q] [decidable p] (h : p ↔ q) (h' : r ↔ q) (h'' : ¬ r) : ¬ p := by tauto example (p q r : Prop) (h : p ↔ q) (h' : r ↔ q) : p ↔ r := by tauto! example (p q r : Prop) (h : ¬ p = q) (h' : r = q) : p ↔ ¬ r := by tauto! section modulo_symmetry variables {p q r : Prop} {α : Type} {x y : α} variables (h : x = y) variables (h'' : (p ∧ q ↔ q ∨ r) ↔ (r ∧ p ↔ r ∨ q)) include h include h'' example (h' : ¬ y = x) : p ∧ q := by tauto example (h' : p ∧ ¬ y = x) : p ∧ q := by tauto example : y = x := by tauto example (h' : ¬ x = y) : p ∧ q := by tauto example : x = y := by tauto end modulo_symmetry end tauto₃ section wlog example {x y : ℕ} (a : x = 1) : true := begin suffices : false, trivial, wlog h : x = y, { guard_target x = y ∨ y = x, admit }, { guard_hyp h := x = y, guard_hyp a := x = 1, admit } end example {x y : ℕ} : true := begin suffices : false, trivial, wlog h : x ≤ y, { guard_hyp h := x ≤ y, guard_target false, admit } end example {x y z : ℕ} : true := begin suffices : false, trivial, wlog : x ≤ y + z using x y, { guard_target x ≤ y + z ∨ y ≤ x + z, admit }, { guard_hyp case := x ≤ y + z, guard_target false, admit }, end example {x : ℕ} (S₀ S₁ : set ℕ) (P : ℕ → Prop) (h : x ∈ S₀ ∪ S₁) : true := begin suffices : false, trivial, wlog h' : x ∈ S₀ using S₀ S₁, { guard_target x ∈ S₀ ∨ x ∈ S₁, admit }, { guard_hyp h := x ∈ S₀ ∪ S₁, guard_hyp h' := x ∈ S₀, admit } end example {n m i : ℕ} {p : ℕ → ℕ → ℕ → Prop} : true := begin suffices : false, trivial, wlog : p n m i using [n m i, n i m, i n m], { guard_target p n m i ∨ p n i m ∨ p i n m, admit }, { guard_hyp case := p n m i, admit } end example {n m i : ℕ} {p : ℕ → Prop} : true := begin suffices : false, trivial, wlog : p n using [n m i, m n i, i n m], { guard_target p n ∨ p m ∨ p i, admit }, { guard_hyp case := p n, admit } end example {n m i : ℕ} {p : ℕ → ℕ → Prop} {q : ℕ → ℕ → ℕ → Prop} : true := begin suffices : q n m i, trivial, have h : p n i ∨ p i m ∨ p m i, from sorry, wlog : p n i := h using n m i, { guard_hyp h := p n i, guard_target q n m i, admit }, { guard_hyp h := p i m, guard_hyp this := q i m n, guard_target q n m i, admit }, { guard_hyp h := p m i, guard_hyp this := q m i n, guard_target q n m i, admit }, end example (X : Type) (A B C : set X) : A ∩ (B ∪ C) = (A ∩ B) ∪ (A ∩ C) := begin ext x, split, { intro hyp, cases hyp, wlog x_in : x ∈ B using B C, { assumption }, { exact or.inl ⟨hyp_left, x_in⟩ } }, { intro hyp, wlog x_in : x ∈ A ∩ B using B C, { assumption }, { exact ⟨x_in.left, or.inl x_in.right⟩ } } end example (X : Type) (A B C : set X) : A ∩ (B ∪ C) = (A ∩ B) ∪ (A ∩ C) := begin ext x, split, { intro hyp, wlog x_in : x ∈ B := hyp.2 using B C, { exact or.inl ⟨hyp.1, x_in⟩ } }, { intro hyp, wlog x_in : x ∈ A ∩ B := hyp using B C, { exact ⟨x_in.left, or.inl x_in.right⟩ } } end example (X : Type) (A B C : set X) : A ∩ (B ∪ C) = (A ∩ B) ∪ (A ∩ C) := begin ext x, split, { intro hyp, cases hyp, wlog x_in : x ∈ B := hyp_right using B C, { exact or.inl ⟨hyp_left, x_in⟩ }, }, { intro hyp, wlog x_in : x ∈ A ∩ B := hyp using B C, { exact ⟨x_in.left, or.inl x_in.right⟩ } } end end wlog example (m n p q : nat) (h : m + n = p) : true := begin have : m + n = q, { generalize_hyp h' : m + n = x at h, guard_hyp h' := m + n = x, guard_hyp h := x = p, guard_target m + n = q, admit }, have : m + n = q, { generalize_hyp h' : m + n = x at h ⊢, guard_hyp h' := m + n = x, guard_hyp h := x = p, guard_target x = q, admit }, trivial end example (α : Sort*) (L₁ L₂ L₃ : list α) (H : L₁ ++ L₂ = L₃) : true := begin have : L₁ ++ L₂ = L₂, { generalize_hyp h : L₁ ++ L₂ = L at H, induction L with hd tl ih, case list.nil { tactic.cleanup, change list.nil = L₃ at H, admit }, case list.cons { change list.cons hd tl = L₃ at H, admit } }, trivial end section convert open set variables {α β : Type} local attribute [simp] private lemma singleton_inter_singleton_eq_empty {x y : α} : ({x} ∩ {y} = (∅ : set α)) ↔ x ≠ y := by simp [singleton_inter_eq_empty] example {f : β → α} {x y : α} (h : x ≠ y) : f ⁻¹' {x} ∩ f ⁻¹' {y} = ∅ := begin have : {x} ∩ {y} = (∅ : set α) := by simpa using h, convert preimage_empty, rw [←preimage_inter,this], end end convert section rcases universe u variables {α β γ : Type u} example (x : α × β × γ) : true := begin rcases x with ⟨a, b, c⟩, { guard_hyp a := α, guard_hyp b := β, guard_hyp c := γ, trivial } end example (x : α × β × γ) : true := begin rcases x with ⟨a, ⟨b, c⟩⟩, { guard_hyp a := α, guard_hyp b := β, guard_hyp c := γ, trivial } end example (x : (α × β) × γ) : true := begin rcases x with ⟨⟨a, b⟩, c⟩, { guard_hyp a := α, guard_hyp b := β, guard_hyp c := γ, trivial } end example (x : inhabited α × option β ⊕ γ) : true := begin rcases x with ⟨⟨a⟩, _ | b⟩ | c, { guard_hyp a := α, trivial }, { guard_hyp a := α, guard_hyp b := β, trivial }, { guard_hyp c := γ, trivial } end example (x y : ℕ) (h : x = y) : true := begin rcases x with _|⟨⟩|z, { guard_hyp h := nat.zero = y, trivial }, { guard_hyp h := nat.succ nat.zero = y, trivial }, { guard_hyp z := ℕ, guard_hyp h := z.succ.succ = y, trivial }, end -- from equiv.sum_empty example (s : α ⊕ empty) : true := begin rcases s with _ | ⟨⟨⟩⟩, { guard_hyp s := α, trivial } end end rcases section ext @[extensionality] lemma unit.ext (x y : unit) : x = y := begin cases x, cases y, refl end example : subsingleton unit := begin split, intros, ext end example (x y : ℕ) : true := begin have : x = y, { ext <|> admit }, have : x = y, { ext i <|> admit }, have : x = y, { ext : 1 <|> admit }, trivial end example (X Y : ℕ × ℕ) (h : X.1 = Y.1) (h : X.2 = Y.2) : X = Y := begin ext; assumption end example (X Y : (ℕ → ℕ) × ℕ) (h : ∀ i, X.1 i = Y.1 i) (h : X.2 = Y.2) : X = Y := begin ext x; solve_by_elim, end example (X Y : ℕ → ℕ × ℕ) (h : ∀ i, X i = Y i) : true := begin have : X = Y, { ext i : 1, guard_target X i = Y i, admit }, have : X = Y, { ext i, guard_target (X i).fst = (Y i).fst, admit, guard_target (X i).snd = (Y i).snd, admit, }, have : X = Y, { ext : 1, guard_target X x = Y x, admit }, trivial, end example (s₀ s₁ : set ℕ) (h : s₁ = s₀) : s₀ = s₁ := by { ext1, guard_target x ∈ s₀ ↔ x ∈ s₁, simp * } example (s₀ s₁ : stream ℕ) (h : s₁ = s₀) : s₀ = s₁ := by { ext1, guard_target s₀.nth n = s₁.nth n, simp * } example (s₀ s₁ : ℤ → set (ℕ × ℕ)) (h : ∀ i a b, (a,b) ∈ s₀ i ↔ (a,b) ∈ s₁ i) : s₀ = s₁ := begin ext i ⟨a,b⟩, apply h end def my_foo {α} (x : semigroup α) (y : group α) : true := trivial example {α : Type} : true := begin have : true, { refine_struct (@my_foo α { .. } { .. } ), -- 9 goals guard_tags _field mul semigroup, admit, -- case semigroup, mul -- α : Type -- ⊢ α → α → α guard_tags _field mul_assoc semigroup, admit, -- case semigroup, mul_assoc -- α : Type -- ⊢ ∀ (a b c : α), a * b * c = a * (b * c) guard_tags _field mul group, admit, -- case group, mul -- α : Type -- ⊢ α → α → α guard_tags _field mul_assoc group, admit, -- case group, mul_assoc -- α : Type -- ⊢ ∀ (a b c : α), a * b * c = a * (b * c) guard_tags _field one group, admit, -- case group, one -- α : Type -- ⊢ α guard_tags _field one_mul group, admit, -- case group, one_mul -- α : Type -- ⊢ ∀ (a : α), 1 * a = a guard_tags _field mul_one group, admit, -- case group, mul_one -- α : Type -- ⊢ ∀ (a : α), a * 1 = a guard_tags _field inv group, admit, -- case group, inv -- α : Type -- ⊢ α → α guard_tags _field mul_left_inv group, admit, -- case group, mul_left_inv -- α : Type -- ⊢ ∀ (a : α), a⁻¹ * a = 1 }, trivial end def my_bar {α} (x : semigroup α) (y : group α) (i j : α) : α := i example {α : Type} : true := begin have : monoid α, { refine_struct { mul := my_bar { .. } { .. } }, guard_tags _field mul semigroup, admit, guard_tags _field mul_assoc semigroup, admit, guard_tags _field mul group, admit, guard_tags _field mul_assoc group, admit, guard_tags _field one group, admit, guard_tags _field one_mul group, admit, guard_tags _field mul_one group, admit, guard_tags _field inv group, admit, guard_tags _field mul_left_inv group, admit, guard_tags _field mul_assoc monoid, admit, guard_tags _field one monoid, admit, guard_tags _field one_mul monoid, admit, guard_tags _field mul_one monoid, admit, }, trivial end structure dependent_fields := (a : bool) (v : if a then ℕ else ℤ) @[extensionality] lemma df.ext (s t : dependent_fields) (h : s.a = t.a) (w : (@eq.rec _ s.a (λ b, if b then ℕ else ℤ) s.v t.a h) = t.v): s = t := begin cases s, cases t, dsimp at *, congr, exact h, subst h, simp, simp at w, exact w, end example (s : dependent_fields) : s = s := begin tactic.ext1 [] {tactic.apply_cfg . new_goals := tactic.new_goals.all}, guard_target s.a = s.a, refl, refl, end end ext section apply_rules example {a b c d e : nat} (h1 : a ≤ b) (h2 : c ≤ d) (h3 : 0 ≤ e) : a + c * e + a + c + 0 ≤ b + d * e + b + d + e := add_le_add (add_le_add (add_le_add (add_le_add h1 (mul_le_mul_of_nonneg_right h2 h3)) h1 ) h2) h3 example {a b c d e : nat} (h1 : a ≤ b) (h2 : c ≤ d) (h3 : 0 ≤ e) : a + c * e + a + c + 0 ≤ b + d * e + b + d + e := by apply_rules [add_le_add, mul_le_mul_of_nonneg_right] @[user_attribute] meta def mono_rules : user_attribute := { name := `mono_rules, descr := "lemmas usable to prove monotonicity" } attribute [mono_rules] add_le_add mul_le_mul_of_nonneg_right example {a b c d e : nat} (h1 : a ≤ b) (h2 : c ≤ d) (h3 : 0 ≤ e) : a + c * e + a + c + 0 ≤ b + d * e + b + d + e := by apply_rules [mono_rules] example {a b c d e : nat} (h1 : a ≤ b) (h2 : c ≤ d) (h3 : 0 ≤ e) : a + c * e + a + c + 0 ≤ b + d * e + b + d + e := by apply_rules mono_rules end apply_rules section h_generalize variables {α β γ φ ψ : Type} (f : α → α → α → φ → γ) (x y : α) (a b : β) (z : φ) (h₀ : β = α) (h₁ : β = α) (h₂ : φ = β) (hx : x == a) (hy : y == b) (hz : z == a) include f x y z a b hx hy hz example : f x y x z = f (eq.rec_on h₀ a) (cast h₀ b) (eq.mpr h₁.symm a) (eq.mpr h₂ a) := begin guard_hyp_nums 16, h_generalize hp : a == p with hh, guard_hyp_nums 19, guard_hyp' hh := β = α, guard_target f x y x z = f p (cast h₀ b) p (eq.mpr h₂ a), h_generalize hq : _ == q, guard_hyp_nums 21, guard_target f x y x z = f p q p (eq.mpr h₂ a), h_generalize _ : _ == r, guard_hyp_nums 23, guard_target f x y x z = f p q p r, casesm* [_ == _, _ = _], refl end end h_generalize section h_generalize variables {α β γ φ ψ : Type} (f : list α → list α → γ) (x : list α) (a : list β) (z : φ) (h₀ : β = α) (h₁ : list β = list α) (hx : x == a) include f x z a hx h₀ h₁ example : true := begin have : f x x = f (eq.rec_on h₀ a) (cast h₁ a), { guard_hyp_nums 11, h_generalize : a == p with _, guard_hyp_nums 13, guard_hyp' h := β = α, guard_target f x x = f p (cast h₁ a), h_generalize! : a == q , guard_hyp_nums 13, guard_target ∀ q, f x x = f p q, casesm* [_ == _, _ = _], success_if_fail { refl }, admit }, trivial end end h_generalize section assoc_rw open tactic example : ∀ x y z a b c : ℕ, true := begin intros, have : x + (y + z) = 3 + y, admit, have : a + (b + x) + y + (z + b + c) ≤ 0, (do this ← get_local `this, tgt ← to_expr ```(a + (b + x) + y + (z + b + c)), assoc ← mk_mapp ``add_monoid.add_assoc [`(ℕ),none], (l,p) ← assoc_rewrite_intl assoc this tgt, note `h none p ), erw h, guard_target a + b + 3 + y + b + c ≤ 0, admit, trivial end example : ∀ x y z a b c : ℕ, true := begin intros, have : ∀ y, x + (y + z) = 3 + y, admit, have : a + (b + x) + y + (z + b + c) ≤ 0, (do this ← get_local `this, tgt ← to_expr ```(a + (b + x) + y + (z + b + c)), assoc_rewrite_target this ), guard_target a + b + 3 + y + b + c ≤ 0, admit, trivial end variables x y z a b c : ℕ variables h₀ : ∀ (y : ℕ), x + (y + z) = 3 + y variables h₁ : a + (b + x) + y + (z + b + a) ≤ 0 variables h₂ : y + b + c = y + b + a include h₀ h₁ h₂ example : a + (b + x) + y + (z + b + c) ≤ 0 := by { assoc_rw [h₀,h₂] at *, guard_hyp _inst := is_associative ℕ has_add.add, -- keep a local instance of is_associative to cache -- type class queries exact h₁ } end assoc_rw -- section tfae -- example (p q r s : Prop) -- (h₀ : p ↔ q) -- (h₁ : q ↔ r) -- (h₂ : r ↔ s) : -- p ↔ s := -- begin -- scc, -- end -- example (p' p q r r' s s' : Prop) -- (h₀ : p' → p) -- (h₀ : p → q) -- (h₁ : q → r) -- (h₁ : r' → r) -- (h₂ : r ↔ s) -- (h₂ : s → p) -- (h₂ : s → s') : -- p ↔ s := -- begin -- scc, -- end -- example (p' p q r r' s s' : Prop) -- (h₀ : p' → p) -- (h₀ : p → q) -- (h₁ : q → r) -- (h₁ : r' → r) -- (h₂ : r ↔ s) -- (h₂ : s → p) -- (h₂ : s → s') : -- p ↔ s := -- begin -- scc', -- assumption -- end -- example : tfae [true, ∀ n : ℕ, 0 ≤ n * n, true, true] := begin -- tfae_have : 3 → 1, { intro h, constructor }, -- tfae_have : 2 → 3, { intro h, constructor }, -- tfae_have : 2 ← 1, { intros h n, apply nat.zero_le }, -- tfae_have : 4 ↔ 2, { tauto }, -- tfae_finish, -- end -- example : tfae [] := begin -- tfae_finish, -- end -- end tfae section conv example : 0 + 0 = 0 := begin conv_lhs {erw [add_zero]} end example : 0 + 0 = 0 := begin conv_lhs {simp} end example : 0 = 0 + 0 := begin conv_rhs {simp} end -- Example with ring discharging the goal example : 22 + 7 * 4 + 3 * 8 = 0 + 7 * 4 + 46 := begin conv { ring, }, end -- Example with ring failing to discharge, to normalizing the goal example : (22 + 7 * 4 + 3 * 8 = 0 + 7 * 4 + 47) = (74 = 75) := begin conv { ring, }, end -- Example with ring discharging the goal example (x : ℕ) : 22 + 7 * x + 3 * 8 = 0 + 7 * x + 46 := begin conv { ring, }, end -- Example with ring failing to discharge, to normalizing the goal example (x : ℕ) : (22 + 7 * x + 3 * 8 = 0 + 7 * x + 46 + 1) = (7 * x + 46 = 7 * x + 47) := begin conv { ring, }, end -- norm_num examples: example : 22 + 7 * 4 + 3 * 8 = 74 := begin conv { norm_num, }, end example (x : ℕ) : 22 + 7 * x + 3 * 8 = 7 * x + 46 := begin conv { norm_num, }, end end conv
cac6ae4ee23ff690387c63bcae649c96bafb8526
359199d7253811b032ab92108191da7336eba86e
/src/mywork/mid-term_review/hw-3_practice.lean
0b0f6b716016019a7abd77c8b6223d86e8849f10
[]
no_license
arte-et-marte/my_cs2120f21
0bc6215cb5018a3b7c90d9d399a173233f587064
91609c3609ad81fda895bee8b97cc76813241e17
refs/heads/main
1,693,298,928,348
1,634,931,202,000
1,634,931,202,000
399,946,705
0
0
null
null
null
null
UTF-8
Lean
false
false
2,670
lean
-- 1 example : 0 ≠ 1 := begin assume zero_eq_one, contradiction, -- **Cannot construct a proof of false.** end -- 2 example : 0 ≠ 0 → 2 = 3 := begin assume zero_neq_zero, exact false.elim (zero_neq_zero (eq.refl 0)), -- **zero_neq_zero (0 = 0) does not construct a proof of false because (0 = 0) is a proposition not a proof.** end -- 3 example : ∀ (P : Prop), P → ¬¬P := begin assume P, assume p, assume np, -- **Translate 'not's' to "...implies false".** contradiction, end -- 4 theorem neg_elim : ∀ (P : Prop), ¬¬P → P := begin assume P, assume nnp, have p_or_np : P ∨ ¬P := classical.em P, -- **Introducing a proof of the disjunct P ∨ ¬P to show that the truthness of either will yield a proof of ¬¬P or a proof of false (from which anything follows).** cases p_or_np with p np, exact p, contradiction, end -- 5 theorem demorgan_1 : ∀ (P Q : Prop), ¬(P ∧ Q) ↔ ¬P ∨ ¬Q := begin assume P Q, apply iff.intro _ _, -- forwards implication proof assume n_pandq, have p_or_np : P ∨ ¬P := classical.em P, cases p_or_np with p np, have q_or_nq : Q ∨ ¬Q := classical.em Q, cases q_or_nq with q nq, -- **Why do we get three cases?** have f : false := n_pandq (and.intro p q), exact false.elim f, exact or.intro_right (¬P) nq, exact or.intro_left (¬Q) np, -- backwards implication proof assume np_or_nq, assume p_and_q, cases np_or_nq with np nq, have p : P := and.elim_left p_and_q, contradiction, have q : Q := and.elim_right p_and_q, contradiction, end -- 6 theorem demorgan_2 : ∀ (P Q : Prop), ¬(P ∨ Q) → ¬P ∧ ¬Q := begin assume P Q, assume n_porq, have np_or_nnp : ¬P ∨ ¬¬P := classical.em ¬P, cases np_or_nnp with np nnp, have nq_or_nnq : ¬Q ∨ ¬¬Q := classical.em ¬Q, cases nq_or_nnq with nq nnq, -- case 1 exact and.intro np nq, -- case 2 **TRICKY!!!** apply false.elim (n_porq _), have q_or_nq : Q ∨ ¬Q := classical.em Q, cases q_or_nq with q nq, ---- subcase 1 exact or.intro_right P q, ---- subcase 2 contradiction, -- case 3 **Remember: You are trying to show a contradiction (get a proof by negation) by means the false elimination rule.** apply false.elim (n_porq _), have p_or_np : P ∨ ¬P := classical.em P, cases p_or_np with p np, ---- subcase 1 exact or.intro_left Q p, ---- subcase 2 contradiction, end -- 10 theorem not_all_nats_are_zero : ¬(∀ (n : ℕ), n = 0) := begin assume prop, have f := prop 1, -- **Not 'have f : false := prop 1' because it's not a proof of false that prop 1 should return; it should return a proof of n = 1.** contradiction, end
65b7033ba4bec7e6585339b58c25af5abec609d5
a86a9700120276bf446dd65cec481ed4a39a584c
/demo.lean
8de3c03506b52224b457072bec24031b3b644252
[]
no_license
svanderbleek/lean4tools
21a06e35511a934696f3ab53d70b98fc32cbab0b
a3e7816b44bbd61566d12b7c7f8f3339a3f4ffec
refs/heads/main
1,677,036,069,474
1,612,052,699,000
1,612,052,699,000
334,540,831
0
0
null
null
null
null
UTF-8
Lean
false
false
538
lean
-- Defines a function that takes a name and produces a greeting. def getGreeting (name : String) := s!"Hello, {name}! Isn't Lean great?" -- The `main` function is the entry point of your program. -- Its type is `IO Unit` because it can perform `IO` operations (side effects). def main : IO Unit := -- Define a list of names let names := ["Sebastian", "Leo", "Daniel"] -- Map each name to a greeting let greetings := names.map getGreeting -- Print the list of greetings for greeting in greetings do IO.println greeting
d5ec1b8fbc472dec3a71db13f83da18a6d0b3b49
6772a11d96d69b3f90d6eeaf7f9accddf2a7691d
/examples/naturals.lean
40827eb0e849d1e1dad9fa0351fb4db39ccf62cf
[]
no_license
lbordowitz/lean-category-theory
5397361f0f81037d65762da48de2c16ec85a5e4b
8c59893e44af3804eba4dbc5f7fa5928ed2e0ae6
refs/heads/master
1,611,310,752,156
1,487,070,172,000
1,487,070,172,000
82,003,141
0
0
null
1,487,118,553,000
1,487,118,553,000
null
UTF-8
Lean
false
false
1,464
lean
-- Copyright (c) 2017 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Stephen Morgan, Scott Morrison import ..category import ..functor import ..natural_transformation import ..products import ..monoidal_category namespace tqft.categories.examples.naturals open tqft.categories open tqft.categories.functor open tqft.categories.monoidal_category @[reducible] definition ℕCategory : Category := { Obj := unit, Hom := λ _ _, ℕ, identity := λ _, 0, compose := λ _ _ _, nat.add, left_identity := begin blast, apply nat.zero_add end, right_identity := ♮, associativity := begin blast, apply nat.add_assoc end } definition DoublingAsFunctor : Functor ℕCategory ℕCategory := { onObjects := id, onMorphisms := (λ _ _ n, nat.add n n), identities := ♮, functoriality := begin blast, exact sorry end } definition ℕTensorProduct : Functor (ℕCategory × ℕCategory) ℕCategory := { onObjects := prod.fst, onMorphisms := λ _ _ n, n^.fst + n^.snd, identities := ♮, functoriality := sorry } def ℕLaxMonoidalCategory : LaxMonoidalCategory := { ℕCategory with tensor := ℕTensorProduct, tensor_unit := (), associator := λ _ _ _, Category.identity ℕCategory (), interchange := sorry -- should be trivial, but how? } end tqft.categories.examples.naturals
fe69a4b2490a14fbbd5446ca1c2b3dd15d4de737
bdb33f8b7ea65f7705fc342a178508e2722eb851
/set_theory/cofinality.lean
a4c52a4508a863b78340af3a3155f8462910efb8
[ "Apache-2.0" ]
permissive
rwbarton/mathlib
939ae09bf8d6eb1331fc2f7e067d39567e10e33d
c13c5ea701bb1eec057e0a242d9f480a079105e9
refs/heads/master
1,584,015,335,862
1,524,142,167,000
1,524,142,167,000
130,614,171
0
0
Apache-2.0
1,548,902,667,000
1,524,437,371,000
Lean
UTF-8
Lean
false
false
16,758
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro Cofinality on ordinals, regular cardinals. -/ import set_theory.ordinal noncomputable theory open function cardinal local attribute [instance] classical.prop_decidable universes u v w variables {α : Type*} {r : α → α → Prop} /-- Cofinality of a reflexive order `≼`. This is the smallest cardinality of a subset `S : set α` such that `∀ a, ∃ b ∈ S, a ≼ b`. -/ def order.cof (r : α → α → Prop) [is_refl α r] : cardinal := @cardinal.min {S : set α // ∀ a, ∃ b ∈ S, r a b} ⟨⟨set.univ, λ a, ⟨a, ⟨⟩, refl _⟩⟩⟩ (λ S, mk S) theorem order_iso.cof.aux {α : Type u} {β : Type v} {r s} [is_refl α r] [is_refl β s] (f : r ≃o s) : cardinal.lift.{u (max u v)} (order.cof r) ≤ cardinal.lift.{v (max u v)} (order.cof s) := begin rw [order.cof, order.cof, lift_min, lift_min, cardinal.le_min], intro S, cases S with S H, simp [(∘)], refine le_trans (min_le _ _) _, { exact ⟨f ⁻¹' S, λ a, let ⟨b, bS, h⟩ := H (f a) in ⟨f.symm b, by simp [bS, f.ord', h]⟩⟩ }, { exact lift_mk_le.{u v (max u v)}.2 ⟨⟨λ ⟨x, h⟩, ⟨f x, h⟩, λ ⟨x, h₁⟩ ⟨y, h₂⟩ h₃, by congr; injection h₃ with h'; exact f.to_equiv.bijective.1 h'⟩⟩ } end theorem order_iso.cof {α : Type u} {β : Type v} {r s} [is_refl α r] [is_refl β s] (f : r ≃o s) : cardinal.lift.{u (max u v)} (order.cof r) = cardinal.lift.{v (max u v)} (order.cof s) := le_antisymm (order_iso.cof.aux f) (order_iso.cof.aux f.symm) namespace ordinal /-- Cofinality of an ordinal. This is the smallest cardinal of a subset `S` of the ordinal which is unbounded, in the sense `∀ a, ∃ b ∈ S, a ≤ b`. It is defined for all ordinals, but `cof 0 = 0` and `cof (succ o) = 1`, so it is only really interesting on limit ordinals (when it is an infinite cardinal). -/ def cof (o : ordinal.{u}) : cardinal.{u} := quot.lift_on o (λ ⟨α, r, _⟩, @order.cof α (λ x y, ¬ r y x) ⟨λ a, by resetI; apply irrefl⟩) $ λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨⟨f, hf⟩⟩, begin show @order.cof α (λ x y, ¬ r y x) ⟨_⟩ = @order.cof β (λ x y, ¬ s y x) ⟨_⟩, refine cardinal.lift_inj.1 (@order_iso.cof _ _ _ _ ⟨_⟩ ⟨_⟩ _), exact ⟨f, λ a b, not_congr hf⟩, end theorem le_cof_type [is_well_order α r] {c} : c ≤ cof (type r) ↔ ∀ S : set α, (∀ a, ∃ b ∈ S, ¬ r b a) → c ≤ mk S := by dsimp [cof, order.cof, type, quotient.mk, quot.lift_on]; rw [cardinal.le_min, subtype.forall]; refl theorem cof_type_le [is_well_order α r] (S : set α) (h : ∀ a, ∃ b ∈ S, ¬ r b a) : cof (type r) ≤ mk S := le_cof_type.1 (le_refl _) S h theorem lt_cof_type [is_well_order α r] (S : set α) (hl : mk S < cof (type r)) : ∃ a, ∀ b ∈ S, r b a := not_forall_not.1 $ λ h, not_le_of_lt hl $ cof_type_le S (λ a, not_ball.1 (h a)) theorem cof_eq (r : α → α → Prop) [is_well_order α r] : ∃ S : set α, (∀ a, ∃ b ∈ S, ¬ r b a) ∧ mk S = cof (type r) := begin have : ∃ i, cof (type r) = _, { dsimp [cof, order.cof, type, quotient.mk, quot.lift_on], apply cardinal.min_eq }, exact let ⟨⟨S, hl⟩, e⟩ := this in ⟨S, hl, e.symm⟩, end theorem ord_cof_eq (r : α → α → Prop) [is_well_order α r] : ∃ S : set α, (∀ a, ∃ b ∈ S, ¬ r b a) ∧ type (subrel r S) = (cof (type r)).ord := let ⟨S, hS, e⟩ := cof_eq r, ⟨s, _, e'⟩ := cardinal.ord_eq S, T : set α := {a | ∃ aS : a ∈ S, ∀ b : S, s b ⟨_, aS⟩ → r b a} in begin resetI, suffices, { refine ⟨T, this, le_antisymm _ (cardinal.ord_le.2 $ cof_type_le T this)⟩, rw [← e, e'], refine type_le'.2 ⟨order_embedding.of_monotone (λ a, ⟨a, let ⟨aS, _⟩ := a.2 in aS⟩) (λ a b h, _)⟩, rcases a with ⟨a, aS, ha⟩, rcases b with ⟨b, bS, hb⟩, change s ⟨a, _⟩ ⟨b, _⟩, refine ((trichotomous_of s _ _).resolve_left (λ hn, _)).resolve_left _, { exact asymm h (ha _ hn) }, { intro e, injection e with e, subst b, exact irrefl _ h } }, { intro a, have : {b : S | ¬ r b a} ≠ ∅ := let ⟨b, bS, ba⟩ := hS a in @set.ne_empty_of_mem S {b | ¬ r b a} ⟨b, bS⟩ ba, let b := (is_well_order.wf s).min _ this, have ba : ¬r b a := (is_well_order.wf s).min_mem _ this, refine ⟨b, ⟨b.2, λ c, not_imp_not.1 $ λ h, _⟩, ba⟩, rw [show ∀b:S, (⟨b, b.2⟩:S) = b, by intro b; cases b; refl], exact (is_well_order.wf s).not_lt_min _ this (is_order_connected.neg_trans r h ba) } end theorem lift_cof (o) : (cof o).lift = cof o.lift := induction_on o $ begin introsI α r _, cases lift_type r with _ e, rw e, apply le_antisymm, { refine le_cof_type.2 (λ S H, _), have : (mk (ulift.up ⁻¹' S)).lift ≤ mk S := ⟨⟨λ ⟨⟨x, h⟩⟩, ⟨⟨x⟩, h⟩, λ ⟨⟨x, h₁⟩⟩ ⟨⟨y, h₂⟩⟩ e, by simp at e; congr; injection e⟩⟩, refine le_trans (cardinal.lift_le.2 $ cof_type_le _ _) this, exact λ a, let ⟨⟨b⟩, bs, br⟩ := H ⟨a⟩ in ⟨b, bs, br⟩ }, { rcases cof_eq r with ⟨S, H, e'⟩, have : mk (ulift.down ⁻¹' S) ≤ (mk S).lift := ⟨⟨λ ⟨⟨x⟩, h⟩, ⟨⟨x, h⟩⟩, λ ⟨⟨x⟩, h₁⟩ ⟨⟨y⟩, h₂⟩ e, by simp at e; congr; injections⟩⟩, rw e' at this, refine le_trans (cof_type_le _ _) this, exact λ ⟨a⟩, let ⟨b, bs, br⟩ := H a in ⟨⟨b⟩, bs, br⟩ } end theorem cof_le_card (o) : cof o ≤ card o := induction_on o $ λ α r _, begin resetI, have : mk (@set.univ α) = card (type r) := quotient.sound ⟨equiv.set.univ _⟩, rw ← this, exact cof_type_le set.univ (λ a, ⟨a, ⟨⟩, irrefl a⟩) end theorem cof_ord_le (c : cardinal) : cof c.ord ≤ c := by simpa using cof_le_card c.ord @[simp] theorem cof_zero : cof 0 = 0 := le_antisymm (by simpa using cof_le_card 0) (cardinal.zero_le _) @[simp] theorem cof_eq_zero {o} : cof o = 0 ↔ o = 0 := ⟨induction_on o $ λ α r _ z, by exactI let ⟨S, hl, e⟩ := cof_eq r in type_eq_zero_iff_empty.2 $ λ ⟨a⟩, let ⟨b, h, _⟩ := hl a in ne_zero_iff_nonempty.2 (by exact ⟨⟨_, h⟩⟩) (e.trans z), λ e, by simp [e]⟩ @[simp] theorem cof_succ (o) : cof (succ o) = 1 := begin apply le_antisymm, { refine induction_on o (λ α r _, _), change cof (type _) ≤ _, rw [← (_ : mk _ = 1)], apply cof_type_le, { refine λ a, ⟨sum.inr ⟨()⟩, set.mem_singleton _, _⟩, rcases a with a|⟨⟨⟨⟩⟩⟩; simp [empty_relation] }, { rw [cardinal.fintype_card, set.card_singleton], simp } }, { rw [← cardinal.succ_zero, cardinal.succ_le], simpa [lt_iff_le_and_ne, cardinal.zero_le] using λ h, succ_ne_zero o (cof_eq_zero.1 (eq.symm h)) } end @[simp] theorem cof_eq_one_iff_is_succ {o} : cof.{u} o = 1 ↔ ∃ a, o = succ a := ⟨induction_on o $ λ α r _ z, begin resetI, rcases cof_eq r with ⟨S, hl, e⟩, rw z at e, cases ne_zero_iff_nonempty.1 (by rw e; exact one_ne_zero) with a, refine ⟨typein r a, eq.symm $ quotient.sound ⟨order_iso.of_surjective (order_embedding.of_monotone _ (λ x y, _)) (λ x, _)⟩⟩, { apply sum.rec; [exact subtype.val, exact λ _, a] }, { rcases x with x|⟨⟨⟨⟩⟩⟩; rcases y with y|⟨⟨⟨⟩⟩⟩; simp [subrel, order.preimage, empty_relation], exact x.2 }, { suffices : r x a ∨ ∃ (b : ulift unit), ↑a = x, {simpa}, rcases trichotomous_of r x a with h|h|h, { exact or.inl h }, { exact or.inr ⟨⟨()⟩, h.symm⟩ }, { rcases hl x with ⟨a', aS, hn⟩, rw (_ : ↑a = a') at h, {exact absurd h hn}, refine congr_arg subtype.val (_ : a = ⟨a', aS⟩), haveI := le_one_iff_subsingleton.1 (le_of_eq e), apply subsingleton.elim } } end, λ ⟨a, e⟩, by simp [e]⟩ @[simp] theorem cof_add (a b : ordinal) : b ≠ 0 → cof (a + b) = cof b := induction_on a $ λ α r _, induction_on b $ λ β s _ b0, begin resetI, change cof (type _) = _, refine eq_of_forall_le_iff (λ c, _), rw [le_cof_type, le_cof_type], split; intros H S hS, { refine le_trans (H {a | sum.rec_on a (∅:set α) S} (λ a, _)) ⟨⟨_, _⟩⟩, { cases a with a b, { cases type_ne_zero_iff_nonempty.1 b0 with b, rcases hS b with ⟨b', bs, _⟩, exact ⟨sum.inr b', bs, by simp⟩ }, { rcases hS b with ⟨b', bs, h⟩, exact ⟨sum.inr b', bs, by simp [h]⟩ } }, { exact λ a, match a with ⟨sum.inr b, h⟩ := ⟨b, h⟩ end }, { exact λ a b, match a, b with ⟨sum.inr a, h₁⟩, ⟨sum.inr b, h₂⟩, h := by congr; injection h end } }, { refine le_trans (H (sum.inr ⁻¹' S) (λ a, _)) ⟨⟨_, _⟩⟩, { rcases hS (sum.inr a) with ⟨a'|b', bs, h⟩; simp at h, { cases h }, { exact ⟨b', bs, h⟩ } }, { exact λ ⟨a, h⟩, ⟨_, h⟩ }, { exact λ ⟨a, h₁⟩ ⟨b, h₂⟩ h, by injection h with h; congr; injection h } } end @[simp] theorem cof_cof (o : ordinal) : cof (cof o).ord = cof o := le_antisymm (le_trans (cof_le_card _) (by simp)) $ induction_on o $ λ α r _, by exactI let ⟨S, hS, e₁⟩ := ord_cof_eq r, ⟨T, hT, e₂⟩ := cof_eq (subrel r S) in begin rw e₁ at e₂, rw ← e₂, refine le_trans (cof_type_le {a | ∃ h, (subtype.mk a h : S) ∈ T} (λ a, _)) ⟨⟨_, _⟩⟩, { rcases hS a with ⟨b, bS, br⟩, rcases hT ⟨b, bS⟩ with ⟨c, cT, cs⟩, cases c with c cS, exact ⟨c, ⟨cS, cT⟩, is_order_connected.neg_trans r cs br⟩ }, { exact λ ⟨a, h⟩, ⟨⟨a, h.fst⟩, h.snd⟩ }, { exact λ ⟨a, ha⟩ ⟨b, hb⟩ h, by injection h with h; congr; injection h }, end theorem omega_le_cof {o} : cardinal.omega ≤ cof o ↔ is_limit o := begin rcases zero_or_succ_or_limit o with rfl|⟨o,rfl⟩|l, { simp [not_zero_is_limit, cardinal.omega_pos] }, { simp [not_succ_is_limit, cardinal.one_lt_omega] }, { simp [l], refine le_of_not_lt (λ h, _), cases cardinal.lt_omega.1 h with n e, have := cof_cof o, rw [e, ord_nat] at this, cases n, { simp at e, simpa [e, not_zero_is_limit] using l }, { rw [← nat_cast_succ, cof_succ] at this, rw [← this, cof_eq_one_iff_is_succ] at e, rcases e with ⟨a, rfl⟩, exact not_succ_is_limit _ l } } end @[simp] theorem cof_omega : cof omega = cardinal.omega := le_antisymm (by rw ← card_omega; apply cof_le_card) (omega_le_cof.2 omega_is_limit) theorem cof_eq' (r : α → α → Prop) [is_well_order α r] (h : is_limit (type r)) : ∃ S : set α, (∀ a, ∃ b ∈ S, r a b) ∧ mk S = cof (type r) := let ⟨S, H, e⟩ := cof_eq r in ⟨S, λ a, let a' := enum r _ (h.2 _ (typein_lt_type r a)) in let ⟨b, h, ab⟩ := H a' in ⟨b, h, (is_order_connected.conn a b a' $ (typein_lt_typein r).1 (by rw typein_enum; apply ordinal.lt_succ_self)).resolve_right ab⟩, e⟩ theorem cof_sup_le_lift {ι} (f : ι → ordinal) (H : ∀ i, f i < sup f) : cof (sup f) ≤ (mk ι).lift := begin generalize e : sup f = o, refine ordinal.induction_on o _ e, introsI α r _ e', rw e' at H, refine le_trans (cof_type_le (set.range (λ i, enum r _ (H i))) _) ⟨embedding.of_surjective _⟩, { intro a, by_contra h, apply not_le_of_lt (typein_lt_type r a), rw [← e', sup_le], intro i, simp [set.range] at h, simpa using le_of_lt ((typein_lt_typein r).2 (h _ i rfl)) }, { exact λ i, ⟨_, set.mem_range_self i.1⟩ }, { intro a, rcases a with ⟨_, i, rfl⟩, exact ⟨⟨i⟩, by simp⟩ } end theorem cof_sup_le {ι} (f : ι → ordinal) (H : ∀ i, f i < sup.{u u} f) : cof (sup.{u u} f) ≤ mk ι := by simpa using cof_sup_le_lift.{u u} f H theorem cof_bsup_le_lift {o : ordinal} : ∀ (f : Π a < o, ordinal), (∀ i h, f i h < bsup o f) → cof (bsup o f) ≤ o.card.lift := induction_on o $ λ α r _ f H, by rw bsup_type; refine cof_sup_le_lift _ _; rw ← bsup_type; intro a; apply H theorem cof_bsup_le {o : ordinal} : ∀ (f : Π a < o, ordinal), (∀ i h, f i h < bsup.{u u} o f) → cof (bsup.{u u} o f) ≤ o.card := induction_on o $ λ α r _ f H, by simpa using cof_bsup_le_lift.{u u} f H @[simp] theorem cof_univ : cof univ.{u v} = cardinal.univ := le_antisymm (cof_le_card _) begin refine le_of_forall_lt (λ c h, _), rcases lt_univ'.1 h with ⟨c, rfl⟩, rcases @cof_eq ordinal.{u} (<) _ with ⟨S, H, Se⟩, rw [univ, ← lift_cof, ← cardinal.lift_lift, cardinal.lift_lt, ← Se], refine lt_of_not_ge (λ h, _), cases cardinal.lift_down h with a e, refine quotient.induction_on a (λ α e, _) e, cases quotient.exact e with f, have f := equiv.ulift.symm.trans f, let g := λ a, (f a).1, let o := succ (sup.{u u} g), rcases H o with ⟨b, h, l⟩, refine l (lt_succ.2 _), rw ← show g (f.symm ⟨b, h⟩) = b, by dsimp [g]; simp, apply le_sup end end ordinal namespace cardinal open ordinal local infixr ^ := @pow cardinal.{u} cardinal cardinal.has_pow /-- A cardinal is a limit if it is not zero or a successor cardinal. Note that `ω` is a limit cardinal by this definition. -/ def is_limit (c : cardinal) : Prop := c ≠ 0 ∧ ∀ x < c, succ x < c /-- A cardinal is a strong limit if it is not zero and it is closed under powersets. Note that `ω` is a strong limit by this definition. -/ def is_strong_limit (c : cardinal) : Prop := c ≠ 0 ∧ ∀ x < c, 2 ^ x < c theorem is_strong_limit.is_limit {c} (H : is_strong_limit c) : is_limit c := ⟨H.1, λ x h, lt_of_le_of_lt (succ_le.2 $ cantor _) (H.2 _ h)⟩ /-- A cardinal is regular if it is infinite and it equals its own cofinality. -/ def is_regular (c : cardinal) : Prop := omega ≤ c ∧ c.ord.cof = c theorem cof_is_regular {o : ordinal} (h : o.is_limit) : is_regular o.cof := ⟨omega_le_cof.2 h, cof_cof _⟩ theorem omega_is_regular {o : ordinal} (h : o.is_limit) : is_regular omega := ⟨le_refl _, by simp⟩ theorem succ_is_regular {c : cardinal.{u}} (h : omega ≤ c) : is_regular (succ c) := ⟨le_trans h (le_of_lt $ lt_succ_self _), begin refine le_antisymm (cof_ord_le _) (succ_le.2 _), cases quotient.exists_rep (succ c) with α αe, simp at αe, rcases ord_eq α with ⟨r, wo, re⟩, resetI, have := ord_is_limit (le_trans h $ le_of_lt $ lt_succ_self _), rw [← αe, re] at this ⊢, rcases cof_eq' r this with ⟨S, H, Se⟩, rw [← Se], apply le_imp_le_iff_lt_imp_lt.1 (mul_le_mul_right c), rw [mul_eq_self h, ← succ_le, ← αe, ← sum_const], refine le_trans _ (sum_le_sum (λ x:S, card (typein r x)) _ _), { simp [typein, sum_mk (λ x:S, {a//r a x})], refine ⟨embedding.of_surjective _⟩, { exact λ x, x.2.1 }, { exact λ a, let ⟨b, h, ab⟩ := H a in ⟨⟨⟨_, h⟩, _, ab⟩, rfl⟩ } }, { intro i, rw [← lt_succ, ← lt_ord, ← αe, re], apply typein_lt_type } end⟩ /-- A cardinal is inaccessible if it is an uncountable regular strong limit cardinal. -/ def is_inaccessible (c : cardinal) := omega < c ∧ is_regular c ∧ is_strong_limit c theorem is_inaccessible.mk {c} (h₁ : omega < c) (h₂ : c ≤ c.ord.cof) (h₃ : ∀ x < c, 2 ^ x < c) : is_inaccessible c := ⟨h₁, ⟨le_of_lt h₁, le_antisymm (cof_ord_le _) h₂⟩, ne_of_gt (lt_trans omega_pos h₁), h₃⟩ /- Lean's foundations prove the existence of ω many inaccessible cardinals -/ theorem univ_inaccessible : is_inaccessible (univ.{u v}) := is_inaccessible.mk (by simpa using lift_lt_univ' omega) (by simp) (λ c h, begin rcases lt_univ'.1 h with ⟨c, rfl⟩, rw ← lift_two_power.{u (max (u+1) v)}, apply lift_lt_univ' end) theorem lt_power_cof {c : cardinal.{u}} : omega ≤ c → c < c ^ cof c.ord := quotient.induction_on c $ λ α h, begin rcases ord_eq α with ⟨r, wo, re⟩, resetI, have := ord_is_limit h, rw [mk_def, re] at this ⊢, rcases cof_eq' r this with ⟨S, H, Se⟩, have := sum_lt_prod (λ a:S, mk {x // r x a}) (λ _, mk α) (λ i, _), { simp [Se.symm] at this ⊢, refine lt_of_le_of_lt _ this, refine ⟨embedding.of_surjective _⟩, { exact λ x, x.2.1 }, { exact λ a, let ⟨b, h, ab⟩ := H a in ⟨⟨⟨_, h⟩, _, ab⟩, rfl⟩ } }, { have := typein_lt_type r i, rwa [← re, lt_ord] at this } end theorem lt_cof_power {a b : cardinal} (ha : omega ≤ a) (b1 : 1 < b) : a < cof (b ^ a).ord := begin have b0 : b ≠ 0 := ne_of_gt (lt_trans zero_lt_one b1), apply le_imp_le_iff_lt_imp_lt.1 (power_le_power_left $ power_ne_zero a b0), rw [power_mul, mul_eq_self ha], exact lt_power_cof (le_trans ha $ le_of_lt $ cantor' _ b1), end end cardinal
30a351d7fb224c1ca395218f4623f72221f3ba7a
2eab05920d6eeb06665e1a6df77b3157354316ad
/src/algebra/group/pi.lean
c63306f818a4d09601443164cbc2b77d6741e2b5
[ "Apache-2.0" ]
permissive
ayush1801/mathlib
78949b9f789f488148142221606bf15c02b960d2
ce164e28f262acbb3de6281b3b03660a9f744e3c
refs/heads/master
1,692,886,907,941
1,635,270,866,000
1,635,270,866,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
11,617
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon, Patrick Massot -/ import data.pi import data.set.function import tactic.pi_instances import algebra.group.hom_instances /-! # Pi instances for groups and monoids This file defines instances for group, monoid, semigroup and related structures on Pi types. -/ universes u v w variable {I : Type u} -- The indexing type variable {f : I → Type v} -- The family of types already equipped with instances variables (x y : Π i, f i) (i : I) namespace pi @[to_additive] instance semigroup [∀ i, semigroup $ f i] : semigroup (Π i : I, f i) := by refine_struct { mul := (*), .. }; tactic.pi_instance_derive_field instance semigroup_with_zero [∀ i, semigroup_with_zero $ f i] : semigroup_with_zero (Π i : I, f i) := by refine_struct { zero := (0 : Π i, f i), mul := (*), .. }; tactic.pi_instance_derive_field @[to_additive] instance comm_semigroup [∀ i, comm_semigroup $ f i] : comm_semigroup (Π i : I, f i) := by refine_struct { mul := (*), .. }; tactic.pi_instance_derive_field @[to_additive] instance mul_one_class [∀ i, mul_one_class $ f i] : mul_one_class (Π i : I, f i) := by refine_struct { one := (1 : Π i, f i), mul := (*), .. }; tactic.pi_instance_derive_field @[to_additive] instance monoid [∀ i, monoid $ f i] : monoid (Π i : I, f i) := by refine_struct { one := (1 : Π i, f i), mul := (*), npow := λ n x i, npow n (x i) }; tactic.pi_instance_derive_field @[simp] lemma pow_apply [∀ i, monoid $ f i] (n : ℕ) : (x^n) i = (x i)^n := begin induction n with n ih, { simp, }, { simp [pow_succ, ih], }, end @[to_additive] instance comm_monoid [∀ i, comm_monoid $ f i] : comm_monoid (Π i : I, f i) := by refine_struct { one := (1 : Π i, f i), mul := (*), npow := λ n x i, npow n (x i) }; tactic.pi_instance_derive_field @[to_additive] instance div_inv_monoid [∀ i, div_inv_monoid $ f i] : div_inv_monoid (Π i : I, f i) := by refine_struct { one := (1 : Π i, f i), mul := (*), inv := has_inv.inv, div := has_div.div, npow := npow, gpow := λ z x i, gpow z (x i) }; tactic.pi_instance_derive_field @[to_additive] instance group [∀ i, group $ f i] : group (Π i : I, f i) := by refine_struct { one := (1 : Π i, f i), mul := (*), inv := has_inv.inv, div := has_div.div, npow := npow, gpow := gpow }; tactic.pi_instance_derive_field @[to_additive] instance comm_group [∀ i, comm_group $ f i] : comm_group (Π i : I, f i) := by refine_struct { one := (1 : Π i, f i), mul := (*), inv := has_inv.inv, div := has_div.div, npow := npow, gpow := gpow }; tactic.pi_instance_derive_field @[to_additive add_left_cancel_semigroup] instance left_cancel_semigroup [∀ i, left_cancel_semigroup $ f i] : left_cancel_semigroup (Π i : I, f i) := by refine_struct { mul := (*) }; tactic.pi_instance_derive_field @[to_additive add_right_cancel_semigroup] instance right_cancel_semigroup [∀ i, right_cancel_semigroup $ f i] : right_cancel_semigroup (Π i : I, f i) := by refine_struct { mul := (*) }; tactic.pi_instance_derive_field @[to_additive add_left_cancel_monoid] instance left_cancel_monoid [∀ i, left_cancel_monoid $ f i] : left_cancel_monoid (Π i : I, f i) := by refine_struct { one := (1 : Π i, f i), mul := (*), npow := npow }; tactic.pi_instance_derive_field @[to_additive add_right_cancel_monoid] instance right_cancel_monoid [∀ i, right_cancel_monoid $ f i] : right_cancel_monoid (Π i : I, f i) := by refine_struct { one := (1 : Π i, f i), mul := (*), npow := npow, .. }; tactic.pi_instance_derive_field @[to_additive add_cancel_monoid] instance cancel_monoid [∀ i, cancel_monoid $ f i] : cancel_monoid (Π i : I, f i) := by refine_struct { one := (1 : Π i, f i), mul := (*), npow := npow }; tactic.pi_instance_derive_field @[to_additive add_cancel_comm_monoid] instance cancel_comm_monoid [∀ i, cancel_comm_monoid $ f i] : cancel_comm_monoid (Π i : I, f i) := by refine_struct { one := (1 : Π i, f i), mul := (*), npow := npow }; tactic.pi_instance_derive_field instance mul_zero_class [∀ i, mul_zero_class $ f i] : mul_zero_class (Π i : I, f i) := by refine_struct { zero := (0 : Π i, f i), mul := (*), .. }; tactic.pi_instance_derive_field instance mul_zero_one_class [∀ i, mul_zero_one_class $ f i] : mul_zero_one_class (Π i : I, f i) := by refine_struct { zero := (0 : Π i, f i), one := (1 : Π i, f i), mul := (*), .. }; tactic.pi_instance_derive_field instance monoid_with_zero [∀ i, monoid_with_zero $ f i] : monoid_with_zero (Π i : I, f i) := by refine_struct { zero := (0 : Π i, f i), one := (1 : Π i, f i), mul := (*), npow := npow }; tactic.pi_instance_derive_field instance comm_monoid_with_zero [∀ i, comm_monoid_with_zero $ f i] : comm_monoid_with_zero (Π i : I, f i) := by refine_struct { zero := (0 : Π i, f i), one := (1 : Π i, f i), mul := (*), npow := npow }; tactic.pi_instance_derive_field section instance_lemmas open function variables {α β γ : Type*} @[simp, to_additive] lemma const_one [has_one β] : const α (1 : β) = 1 := rfl @[simp, to_additive] lemma comp_one [has_one β] {f : β → γ} : f ∘ 1 = const α (f 1) := rfl @[simp, to_additive] lemma one_comp [has_one γ] {f : α → β} : (1 : β → γ) ∘ f = 1 := rfl end instance_lemmas end pi section monoid_hom variables (f) [Π i, mul_one_class (f i)] /-- Evaluation of functions into an indexed collection of monoids at a point is a monoid homomorphism. This is `function.eval i` as a `monoid_hom`. -/ @[to_additive "Evaluation of functions into an indexed collection of additive monoids at a point is an additive monoid homomorphism. This is `function.eval i` as an `add_monoid_hom`.", simps] def pi.eval_monoid_hom (i : I) : (Π i, f i) →* f i := { to_fun := λ g, g i, map_one' := pi.one_apply i, map_mul' := λ x y, pi.mul_apply _ _ i, } /-- `function.const` as a `monoid_hom`. -/ @[to_additive "`function.const` as an `add_monoid_hom`.", simps] def pi.const_monoid_hom (α β : Type*) [mul_one_class β] : β →* (α → β) := { to_fun := function.const α, map_one' := rfl, map_mul' := λ _ _, rfl } /-- Coercion of a `monoid_hom` into a function is itself a `monoid_hom`. See also `monoid_hom.eval`. -/ @[to_additive "Coercion of an `add_monoid_hom` into a function is itself a `add_monoid_hom`. See also `add_monoid_hom.eval`. ", simps] def monoid_hom.coe_fn (α β : Type*) [mul_one_class α] [comm_monoid β] : (α →* β) →* (α → β) := { to_fun := λ g, g, map_one' := rfl, map_mul' := λ x y, rfl, } /-- Monoid homomorphism between the function spaces `I → α` and `I → β`, induced by a monoid homomorphism `f` between `α` and `β`. -/ @[to_additive "Additive monoid homomorphism between the function spaces `I → α` and `I → β`, induced by an additive monoid homomorphism `f` between `α` and `β`", simps] protected def monoid_hom.comp_left {α β : Type*} [mul_one_class α] [mul_one_class β] (f : α →* β) (I : Type*) : (I → α) →* (I → β) := { to_fun := λ h, f ∘ h, map_one' := by ext; simp, map_mul' := λ _ _, by ext; simp } end monoid_hom section single variables [decidable_eq I] open pi variables (f) /-- The zero-preserving homomorphism including a single value into a dependent family of values, as functions supported at a point. This is the `zero_hom` version of `pi.single`. -/ @[simps] def zero_hom.single [Π i, has_zero $ f i] (i : I) : zero_hom (f i) (Π i, f i) := { to_fun := single i, map_zero' := single_zero i } /-- The additive monoid homomorphism including a single additive monoid into a dependent family of additive monoids, as functions supported at a point. This is the `add_monoid_hom` version of `pi.single`. -/ @[simps] def add_monoid_hom.single [Π i, add_zero_class $ f i] (i : I) : f i →+ Π i, f i := { to_fun := single i, map_add' := single_op₂ (λ _, (+)) (λ _, zero_add _) _, .. (zero_hom.single f i) } /-- The multiplicative homomorphism including a single `mul_zero_class` into a dependent family of `mul_zero_class`es, as functions supported at a point. This is the `mul_hom` version of `pi.single`. -/ @[simps] def mul_hom.single [Π i, mul_zero_class $ f i] (i : I) : mul_hom (f i) (Π i, f i) := { to_fun := single i, map_mul' := single_op₂ (λ _, (*)) (λ _, zero_mul _) _, } variables {f} lemma pi.single_add [Π i, add_zero_class $ f i] (i : I) (x y : f i) : single i (x + y) = single i x + single i y := (add_monoid_hom.single f i).map_add x y lemma pi.single_neg [Π i, add_group $ f i] (i : I) (x : f i) : single i (-x) = -single i x := (add_monoid_hom.single f i).map_neg x lemma pi.single_sub [Π i, add_group $ f i] (i : I) (x y : f i) : single i (x - y) = single i x - single i y := (add_monoid_hom.single f i).map_sub x y lemma pi.single_mul [Π i, mul_zero_class $ f i] (i : I) (x y : f i) : single i (x * y) = single i x * single i y := (mul_hom.single f i).map_mul x y lemma pi.update_eq_sub_add_single [Π i, add_group $ f i] (g : Π (i : I), f i) (x : f i) : function.update g i x = g - single i (g i) + single i x := begin ext j, rcases eq_or_ne i j with rfl|h, { simp }, { simp [function.update_noteq h.symm, h] } end end single namespace function @[simp, to_additive] lemma update_one [Π i, has_one (f i)] [decidable_eq I] (i : I) : update (1 : Π i, f i) i 1 = 1 := update_eq_self i 1 @[to_additive] lemma update_mul [Π i, has_mul (f i)] [decidable_eq I] (f₁ f₂ : Π i, f i) (i : I) (x₁ : f i) (x₂ : f i) : update (f₁ * f₂) i (x₁ * x₂) = update f₁ i x₁ * update f₂ i x₂ := funext $ λ j, (apply_update₂ (λ i, (*)) f₁ f₂ i x₁ x₂ j).symm @[to_additive] lemma update_inv [Π i, has_inv (f i)] [decidable_eq I] (f₁ : Π i, f i) (i : I) (x₁ : f i) : update (f₁⁻¹) i (x₁⁻¹) = (update f₁ i x₁)⁻¹ := funext $ λ j, (apply_update (λ i, has_inv.inv) f₁ i x₁ j).symm @[to_additive] lemma update_div [Π i, has_div (f i)] [decidable_eq I] (f₁ f₂ : Π i, f i) (i : I) (x₁ : f i) (x₂ : f i) : update (f₁ / f₂) i (x₁ / x₂) = update f₁ i x₁ / update f₂ i x₂ := funext $ λ j, (apply_update₂ (λ i, (/)) f₁ f₂ i x₁ x₂ j).symm end function section piecewise @[to_additive] lemma set.piecewise_mul [Π i, has_mul (f i)] (s : set I) [Π i, decidable (i ∈ s)] (f₁ f₂ g₁ g₂ : Π i, f i) : s.piecewise (f₁ * f₂) (g₁ * g₂) = s.piecewise f₁ g₁ * s.piecewise f₂ g₂ := s.piecewise_op₂ _ _ _ _ (λ _, (*)) @[to_additive] lemma set.piecewise_inv [Π i, has_inv (f i)] (s : set I) [Π i, decidable (i ∈ s)] (f₁ g₁ : Π i, f i) : s.piecewise (f₁⁻¹) (g₁⁻¹) = (s.piecewise f₁ g₁)⁻¹ := s.piecewise_op f₁ g₁ (λ _ x, x⁻¹) @[to_additive] lemma set.piecewise_div [Π i, has_div (f i)] (s : set I) [Π i, decidable (i ∈ s)] (f₁ f₂ g₁ g₂ : Π i, f i) : s.piecewise (f₁ / f₂) (g₁ / g₂) = s.piecewise f₁ g₁ / s.piecewise f₂ g₂ := s.piecewise_op₂ _ _ _ _ (λ _, (/)) end piecewise section extend variables {ι : Type u} {η : Type v} (R : Type w) (s : ι → η) /-- `function.extend s f 1` as a bundled hom. -/ @[to_additive function.extend_by_zero.hom "`function.extend s f 0` as a bundled hom.", simps] noncomputable def function.extend_by_one.hom [mul_one_class R] : (ι → R) →* (η → R) := { to_fun := λ f, function.extend s f 1, map_one' := function.extend_one s, map_mul' := λ f g, by { simpa using function.extend_mul s f g 1 1 } } end extend
1448524326982fd4b78ee8f917395a4dda614e48
7cdf3413c097e5d36492d12cdd07030eb991d394
/src/game/world6/level1.lean
d9b70103b9da947f9cd522c145b9cd84e03b5153
[]
no_license
alreadydone/natural_number_game
3135b9385a9f43e74cfbf79513fc37e69b99e0b3
1a39e693df4f4e871eb449890d3c7715a25c2ec9
refs/heads/master
1,599,387,390,105
1,573,200,587,000
1,573,200,691,000
220,397,084
0
0
null
1,573,192,734,000
1,573,192,733,000
null
UTF-8
Lean
false
false
3,095
lean
-- World name : Proposition world /- # Proposition world. A Proposition is a true/false statement, like `2 + 2 = 4` or `2 + 2 = 5`. Just like we can have concrete sets in Lean like `mynat`, and abstract sets called things like `X`, we can also have concrete propositions like `2 + 2 = 5` and abstract propositions called things like `P`. Mathematicians are very good at conflating a theorem with its proof. They might say "now use theorem 12 and we're done". What they really mean is "now use the proof of theorem 12..." (i.e. the fact that we proved it already). Particularly problematic is the fact that mathematicians use the word Proposition to mean "a relatively straightforward statement which is true" and computer scientists use it to mean "a statement of arbitrary complexity, which might be true or false". Computer scientists are far more careful about distinguishing between a proposition and a proof. (for example: `x + 0 = x`) is a proposition, and `add_zero x` is its proof. The convention we'll use is capital letters for propositions and small letters for proofs. In this world you will see the local context in the following kind of state: ``` P : Prop p : P ``` Here `P` is the true/false statement (the statement of proposition), and `p` is its proof. It's like `P` being the set and `p` being the element. In fact computer scientists sometimes think about the following analogy: propositions are like sets, and proofs are like their elements. ## What's going on in this world? We're going to learn about manipulating propositions and proofs. Fortunately, we don't need to learn a bunch of new tactics -- the ones we just learnt (`exact`, `intro`, `have`, `apply`) will be perfect. The levels in proposition world are "back to normal", we're proving theorems, not constructing elements of sets. Or are we? If you delete the sorry below then your local context will look like this: ``` P Q : Prop, p : P, h : P → Q ⊢ Q ``` In this situation, we have true/false statements $P$ and $Q$, a proof $p$ of $P$, and $h$ is the hypothesis that $P\implies Q$. Our goal is to construct a proof of $Q$. It's clear what to do *mathematically* to solve this goal -- we can deduce $Q$ by applying the hypothesis $h:P\implies Q$ to the proof $p$ of $P$. But how to do it in Lean? Adopting a point of view wholly unfamiliar to mathematicians, Lean interprets the hypothesis $h$ as a function from proofs of $P$ to proofs of $Q$, so the rather surprising approach `exact h(p),` works to close the goal. Note that `exact h(P),` (with a capital P) won't work; this is a common error I see from beginners. "We're trying to solve P so it's exactly P". The goal states the *theorem*, your job is to construct the *proof*. $P$ is not proof of $P$, it's $p$ that is a proof of $P$. In Lean, Propositions are types, like sets, and proofs are terms, like elements of sets. ## Level 1 -- `exact` -/ /- Lemma : no-side-bar If $P$ is true, and $P\implies Q$ is also true, then $Q$ is true. -/ lemma level1 (P Q : Prop) (p : P) (h : P → Q) : Q := begin exact h(p), end
16a808c6dd4319744066046aa77d2af09ecc08e6
7cef822f3b952965621309e88eadf618da0c8ae9
/src/category_theory/concrete_category/bundled.lean
e29df77fc1aa5f305abe2c1e568b1ccb66e9f6bc
[ "Apache-2.0" ]
permissive
rmitta/mathlib
8d90aee30b4db2b013e01f62c33f297d7e64a43d
883d974b608845bad30ae19e27e33c285200bf84
refs/heads/master
1,585,776,832,544
1,576,874,096,000
1,576,874,096,000
153,663,165
0
2
Apache-2.0
1,544,806,490,000
1,539,884,365,000
Lean
UTF-8
Lean
false
false
1,774
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Johannes Hölzl, Reid Barton, Sean Leather Bundled types. -/ /-! `bundled c` provides a uniform structure for bundling a type equipped with a type class. We provide `category` instances for these in `unbundled_hom.lean` (for categories with unbundled homs, e.g. topological spaces) and in `bundled_hom.lean` (for categories with bundled homs, e.g. monoids). -/ universes u v namespace category_theory variables {c d : Type u → Type v} {α : Type u} /-- `bundled` is a type bundled with a type class instance for that type. Only the type class is exposed as a parameter. -/ structure bundled (c : Type u → Type v) : Type (max (u+1) v) := (α : Type u) (str : c α . tactic.apply_instance) namespace bundled /-- A generic function for lifting a type equipped with an instance to a bundled object. -/ -- Usually explicit instances will provide their own version of this, e.g. `Mon.of` and `Top.of`. def of {c : Type u → Type v} (α : Type u) [str : c α] : bundled c := ⟨α, str⟩ instance : has_coe_to_sort (bundled c) := { S := Type u, coe := bundled.α } /- `bundled.map` is reducible so that, if we define a category def Ring : Type (u+1) := induced_category SemiRing (bundled.map @ring.to_semiring) instance search is able to "see" that a morphism R ⟶ S in Ring is really a (semi)ring homomorphism from R.α to S.α, and not merely from `(bundled.map @ring.to_semiring R).α` to `(bundled.map @ring.to_semiring S).α`. -/ /-- Map over the bundled structure -/ @[reducible] def map (f : Π {α}, c α → d α) (b : bundled c) : bundled d := ⟨b.α, f b.str⟩ end bundled end category_theory
c2c0fc257983542d6f1ce23a477f7d48994aba40
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/ordmap/ordset_auto.lean
5d87007773349d7eaaae564a448a1d65630eaaba
[]
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
51,391
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 Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.ordmap.ordnode import Mathlib.algebra.ordered_ring import Mathlib.data.nat.dist import Mathlib.tactic.linarith.default import Mathlib.PostPort universes u_1 l namespace Mathlib /-! # Verification of the `ordnode α` datatype This file proves the correctness of the operations in `data.ordmap.ordnode`. The public facing version is the type `ordset α`, which is a wrapper around `ordnode α` which includes the correctness invariant of the type, and it exposes parallel operations like `insert` as functions on `ordset` that do the same thing but bundle the correctness proofs. The advantage is that it is possible to, for example, prove that the result of `find` on `insert` will actually find the element, while `ordnode` cannot guarantee this if the input tree did not satisfy the type invariants. ## Main definitions * `ordset α`: A well formed set of values of type `α` ## Implementation notes The majority of this file is actually in the `ordnode` namespace, because we first have to prove the correctness of all the operations (and defining what correctness means here is actually somewhat subtle). So all the actual `ordset` operations are at the very end, once we have all the theorems. An `ordnode α` is an inductive type which describes a tree which stores the `size` at internal nodes. The correctness invariant of an `ordnode α` is: * `ordnode.sized t`: All internal `size` fields must match the actual measured size of the tree. (This is not hard to satisfy.) * `ordnode.balanced t`: Unless the tree has the form `()` or `((a) b)` or `(a (b))` (that is, nil or a single singleton subtree), the two subtrees must satisfy `size l ≤ δ * size r` and `size r ≤ δ * size l`, where `δ := 3` is a global parameter of the data structure (and this property must hold recursively at subtrees). This is why we say this is a "size balanced tree" data structure. * `ordnode.bounded lo hi t`: The members of the tree must be in strictly increasing order, meaning that if `a` is in the left subtree and `b` is the root, then `a ≤ b` and `¬ (b ≤ a)`. We enforce this using `ordnode.bounded` which includes also a global upper and lower bound. Because the `ordnode` file was ported from Haskell, the correctness invariants of some of the functions have not been spelled out, and some theorems like `ordnode.valid'.balance_l_aux` show very intricate assumptions on the sizes, which may need to be revised if it turns out some operations violate these assumptions, because there is a decent amount of slop in the actual data structure invariants, so the theorem will go through with multiple choices of assumption. **Note:** This file is incomplete, in the sense that the intent is to have verified versions and lemmas about all the definitions in `ordnode.lean`, but at the moment only a few operations are verified (the hard part should be out of the way, but still). Contributors are encouraged to pick this up and finish the job, if it appeals to you. ## Tags ordered map, ordered set, data structure, verified programming -/ namespace ordnode /-! ### delta and ratio -/ theorem not_le_delta {s : ℕ} (H : 1 ≤ s) : ¬s ≤ delta * 0 := fun (h : s ≤ delta * 0) => not_lt_of_le (eq.mp (Eq._oldrec (Eq.refl (s ≤ delta * 0)) (mul_zero delta)) h) H theorem delta_lt_false {a : ℕ} {b : ℕ} (h₁ : delta * a < b) (h₂ : delta * b < a) : False := sorry /-! ### `singleton` -/ /-! ### `size` and `empty` -/ /-- O(n). Computes the actual number of elements in the set, ignoring the cached `size` field. -/ def real_size {α : Type u_1} : ordnode α → ℕ := sorry /-! ### `sized` -/ /-- The `sized` property asserts that all the `size` fields in nodes match the actual size of the respective subtrees. -/ def sized {α : Type u_1} : ordnode α → Prop := sorry theorem sized.node' {α : Type u_1} {l : ordnode α} {x : α} {r : ordnode α} (hl : sized l) (hr : sized r) : sized (node' l x r) := { left := rfl, right := { left := hl, right := hr } } theorem sized.eq_node' {α : Type u_1} {s : ℕ} {l : ordnode α} {x : α} {r : ordnode α} (h : sized (node s l x r)) : node s l x r = node' l x r := eq.mpr (id (Eq._oldrec (Eq.refl (node s l x r = node' l x r)) (and.left h))) (Eq.refl (node (size l + size r + 1) l x r)) theorem sized.size_eq {α : Type u_1} {s : ℕ} {l : ordnode α} {x : α} {r : ordnode α} (H : sized (node s l x r)) : size (node s l x r) = size l + size r + 1 := and.left H theorem sized.induction {α : Type u_1} {t : ordnode α} (hl : sized t) {C : ordnode α → Prop} (H0 : C nil) (H1 : ∀ (l : ordnode α) (x : α) (r : ordnode α), C l → C r → C (node' l x r)) : C t := sorry theorem size_eq_real_size {α : Type u_1} {t : ordnode α} : sized t → size t = real_size t := sorry @[simp] theorem sized.size_eq_zero {α : Type u_1} {t : ordnode α} (ht : sized t) : size t = 0 ↔ t = nil := sorry theorem sized.pos {α : Type u_1} {s : ℕ} {l : ordnode α} {x : α} {r : ordnode α} (h : sized (node s l x r)) : 0 < s := eq.mpr (id (Eq._oldrec (Eq.refl (0 < s)) (and.left h))) (nat.le_add_left (Nat.succ 0) (size l + size r)) /-! `dual` -/ theorem dual_dual {α : Type u_1} (t : ordnode α) : dual (dual t) = t := sorry @[simp] theorem size_dual {α : Type u_1} (t : ordnode α) : size (dual t) = size t := ordnode.cases_on t (Eq.refl (size (dual nil))) fun (t_size : ℕ) (t_l : ordnode α) (t_x : α) (t_r : ordnode α) => Eq.refl (size (dual (node t_size t_l t_x t_r))) /-! `balanced` -/ /-- The `balanced_sz l r` asserts that a hypothetical tree with children of sizes `l` and `r` is balanced: either `l ≤ δ * r` and `r ≤ δ * r`, or the tree is trivial with a singleton on one side and nothing on the other. -/ def balanced_sz (l : ℕ) (r : ℕ) := l + r ≤ 1 ∨ l ≤ delta * r ∧ r ≤ delta * l protected instance balanced_sz.dec : DecidableRel balanced_sz := fun (l r : ℕ) => or.decidable /-- The `balanced t` asserts that the tree `t` satisfies the balance invariants (at every level). -/ def balanced {α : Type u_1} : ordnode α → Prop := sorry protected instance balanced.dec {α : Type u_1} : decidable_pred balanced := sorry theorem balanced_sz.symm {l : ℕ} {r : ℕ} : balanced_sz l r → balanced_sz r l := or.imp (eq.mpr (id (Eq._oldrec (Eq.refl (l + r ≤ 1 → r + l ≤ 1)) (add_comm l r))) id) and.symm theorem balanced_sz_zero {l : ℕ} : balanced_sz l 0 ↔ l ≤ 1 := sorry theorem balanced_sz_up {l : ℕ} {r₁ : ℕ} {r₂ : ℕ} (h₁ : r₁ ≤ r₂) (h₂ : l + r₂ ≤ 1 ∨ r₂ ≤ delta * l) (H : balanced_sz l r₁) : balanced_sz l r₂ := sorry theorem balanced_sz_down {l : ℕ} {r₁ : ℕ} {r₂ : ℕ} (h₁ : r₁ ≤ r₂) (h₂ : l + r₂ ≤ 1 ∨ l ≤ delta * r₁) (H : balanced_sz l r₂) : balanced_sz l r₁ := sorry theorem balanced.dual {α : Type u_1} {t : ordnode α} : balanced t → balanced (dual t) := sorry /-! ### `rotate` and `balance` -/ /-- Build a tree from three nodes, left associated (ignores the invariants). -/ def node3_l {α : Type u_1} (l : ordnode α) (x : α) (m : ordnode α) (y : α) (r : ordnode α) : ordnode α := node' (node' l x m) y r /-- Build a tree from three nodes, right associated (ignores the invariants). -/ def node3_r {α : Type u_1} (l : ordnode α) (x : α) (m : ordnode α) (y : α) (r : ordnode α) : ordnode α := node' l x (node' m y r) /-- Build a tree from three nodes, with `a () b -> (a ()) b` and `a (b c) d -> ((a b) (c d))`. -/ def node4_l {α : Type u_1} : ordnode α → α → ordnode α → α → ordnode α → ordnode α := sorry /-- Build a tree from three nodes, with `a () b -> a (() b)` and `a (b c) d -> ((a b) (c d))`. -/ def node4_r {α : Type u_1} : ordnode α → α → ordnode α → α → ordnode α → ordnode α := sorry /-- Concatenate two nodes, performing a left rotation `x (y z) -> ((x y) z)` if balance is upset. -/ def rotate_l {α : Type u_1} : ordnode α → α → ordnode α → ordnode α := sorry /-- Concatenate two nodes, performing a right rotation `(x y) z -> (x (y z))` if balance is upset. -/ def rotate_r {α : Type u_1} : ordnode α → α → ordnode α → ordnode α := sorry /-- A left balance operation. This will rebalance a concatenation, assuming the original nodes are not too far from balanced. -/ def balance_l' {α : Type u_1} (l : ordnode α) (x : α) (r : ordnode α) : ordnode α := ite (size l + size r ≤ 1) (node' l x r) (ite (size l > delta * size r) (rotate_r l x r) (node' l x r)) /-- A right balance operation. This will rebalance a concatenation, assuming the original nodes are not too far from balanced. -/ def balance_r' {α : Type u_1} (l : ordnode α) (x : α) (r : ordnode α) : ordnode α := ite (size l + size r ≤ 1) (node' l x r) (ite (size r > delta * size l) (rotate_l l x r) (node' l x r)) /-- The full balance operation. This is the same as `balance`, but with less manual inlining. It is somewhat easier to work with this version in proofs. -/ def balance' {α : Type u_1} (l : ordnode α) (x : α) (r : ordnode α) : ordnode α := ite (size l + size r ≤ 1) (node' l x r) (ite (size r > delta * size l) (rotate_l l x r) (ite (size l > delta * size r) (rotate_r l x r) (node' l x r))) theorem dual_node' {α : Type u_1} (l : ordnode α) (x : α) (r : ordnode α) : dual (node' l x r) = node' (dual r) x (dual l) := sorry theorem dual_node3_l {α : Type u_1} (l : ordnode α) (x : α) (m : ordnode α) (y : α) (r : ordnode α) : dual (node3_l l x m y r) = node3_r (dual r) y (dual m) x (dual l) := sorry theorem dual_node3_r {α : Type u_1} (l : ordnode α) (x : α) (m : ordnode α) (y : α) (r : ordnode α) : dual (node3_r l x m y r) = node3_l (dual r) y (dual m) x (dual l) := sorry theorem dual_node4_l {α : Type u_1} (l : ordnode α) (x : α) (m : ordnode α) (y : α) (r : ordnode α) : dual (node4_l l x m y r) = node4_r (dual r) y (dual m) x (dual l) := sorry theorem dual_node4_r {α : Type u_1} (l : ordnode α) (x : α) (m : ordnode α) (y : α) (r : ordnode α) : dual (node4_r l x m y r) = node4_l (dual r) y (dual m) x (dual l) := sorry theorem dual_rotate_l {α : Type u_1} (l : ordnode α) (x : α) (r : ordnode α) : dual (rotate_l l x r) = rotate_r (dual r) x (dual l) := sorry theorem dual_rotate_r {α : Type u_1} (l : ordnode α) (x : α) (r : ordnode α) : dual (rotate_r l x r) = rotate_l (dual r) x (dual l) := sorry theorem dual_balance' {α : Type u_1} (l : ordnode α) (x : α) (r : ordnode α) : dual (balance' l x r) = balance' (dual r) x (dual l) := sorry theorem dual_balance_l {α : Type u_1} (l : ordnode α) (x : α) (r : ordnode α) : dual (balance_l l x r) = balance_r (dual r) x (dual l) := sorry theorem dual_balance_r {α : Type u_1} (l : ordnode α) (x : α) (r : ordnode α) : dual (balance_r l x r) = balance_l (dual r) x (dual l) := sorry theorem sized.node3_l {α : Type u_1} {l : ordnode α} {x : α} {m : ordnode α} {y : α} {r : ordnode α} (hl : sized l) (hm : sized m) (hr : sized r) : sized (node3_l l x m y r) := sized.node' (sized.node' hl hm) hr theorem sized.node3_r {α : Type u_1} {l : ordnode α} {x : α} {m : ordnode α} {y : α} {r : ordnode α} (hl : sized l) (hm : sized m) (hr : sized r) : sized (node3_r l x m y r) := sized.node' hl (sized.node' hm hr) theorem sized.node4_l {α : Type u_1} {l : ordnode α} {x : α} {m : ordnode α} {y : α} {r : ordnode α} (hl : sized l) (hm : sized m) (hr : sized r) : sized (node4_l l x m y r) := sorry theorem node3_l_size {α : Type u_1} {l : ordnode α} {x : α} {m : ordnode α} {y : α} {r : ordnode α} : size (node3_l l x m y r) = size l + size m + size r + bit0 1 := sorry theorem node3_r_size {α : Type u_1} {l : ordnode α} {x : α} {m : ordnode α} {y : α} {r : ordnode α} : size (node3_r l x m y r) = size l + size m + size r + bit0 1 := sorry theorem node4_l_size {α : Type u_1} {l : ordnode α} {x : α} {m : ordnode α} {y : α} {r : ordnode α} (hm : sized m) : size (node4_l l x m y r) = size l + size m + size r + bit0 1 := sorry theorem sized.dual {α : Type u_1} {t : ordnode α} (h : sized t) : sized (dual t) := sorry theorem sized.dual_iff {α : Type u_1} {t : ordnode α} : sized (dual t) ↔ sized t := { mp := fun (h : sized (dual t)) => eq.mpr (id (Eq._oldrec (Eq.refl (sized t)) (Eq.symm (dual_dual t)))) (sized.dual h), mpr := sized.dual } theorem sized.rotate_l {α : Type u_1} {l : ordnode α} {x : α} {r : ordnode α} (hl : sized l) (hr : sized r) : sized (rotate_l l x r) := sorry theorem sized.rotate_r {α : Type u_1} {l : ordnode α} {x : α} {r : ordnode α} (hl : sized l) (hr : sized r) : sized (rotate_r l x r) := iff.mp sized.dual_iff (eq.mpr (id (Eq._oldrec (Eq.refl (sized (dual (rotate_r l x r)))) (dual_rotate_r l x r))) (sized.rotate_l (sized.dual hr) (sized.dual hl))) theorem sized.rotate_l_size {α : Type u_1} {l : ordnode α} {x : α} {r : ordnode α} (hm : sized r) : size (rotate_l l x r) = size l + size r + 1 := sorry theorem sized.rotate_r_size {α : Type u_1} {l : ordnode α} {x : α} {r : ordnode α} (hl : sized l) : size (rotate_r l x r) = size l + size r + 1 := sorry theorem sized.balance' {α : Type u_1} {l : ordnode α} {x : α} {r : ordnode α} (hl : sized l) (hr : sized r) : sized (balance' l x r) := sorry theorem size_balance' {α : Type u_1} {l : ordnode α} {x : α} {r : ordnode α} (hl : sized l) (hr : sized r) : size (balance' l x r) = size l + size r + 1 := sorry /-! ## `all`, `any`, `emem`, `amem` -/ theorem all.imp {α : Type u_1} {P : α → Prop} {Q : α → Prop} (H : ∀ (a : α), P a → Q a) {t : ordnode α} : all P t → all Q t := sorry theorem any.imp {α : Type u_1} {P : α → Prop} {Q : α → Prop} (H : ∀ (a : α), P a → Q a) {t : ordnode α} : any P t → any Q t := sorry theorem all_singleton {α : Type u_1} {P : α → Prop} {x : α} : all P (singleton x) ↔ P x := { mp := fun (h : all P (singleton x)) => and.left (and.right h), mpr := fun (h : P x) => { left := True.intro, right := { left := h, right := True.intro } } } theorem any_singleton {α : Type u_1} {P : α → Prop} {x : α} : any P (singleton x) ↔ P x := sorry theorem all_dual {α : Type u_1} {P : α → Prop} {t : ordnode α} : all P (dual t) ↔ all P t := sorry theorem all_iff_forall {α : Type u_1} {P : α → Prop} {t : ordnode α} : all P t ↔ ∀ (x : α), emem x t → P x := sorry theorem any_iff_exists {α : Type u_1} {P : α → Prop} {t : ordnode α} : any P t ↔ ∃ (x : α), emem x t ∧ P x := sorry theorem emem_iff_all {α : Type u_1} {x : α} {t : ordnode α} : emem x t ↔ ∀ (P : α → Prop), all P t → P x := sorry theorem all_node' {α : Type u_1} {P : α → Prop} {l : ordnode α} {x : α} {r : ordnode α} : all P (node' l x r) ↔ all P l ∧ P x ∧ all P r := iff.rfl theorem all_node3_l {α : Type u_1} {P : α → Prop} {l : ordnode α} {x : α} {m : ordnode α} {y : α} {r : ordnode α} : all P (node3_l l x m y r) ↔ all P l ∧ P x ∧ all P m ∧ P y ∧ all P r := sorry theorem all_node3_r {α : Type u_1} {P : α → Prop} {l : ordnode α} {x : α} {m : ordnode α} {y : α} {r : ordnode α} : all P (node3_r l x m y r) ↔ all P l ∧ P x ∧ all P m ∧ P y ∧ all P r := iff.rfl theorem all_node4_l {α : Type u_1} {P : α → Prop} {l : ordnode α} {x : α} {m : ordnode α} {y : α} {r : ordnode α} : all P (node4_l l x m y r) ↔ all P l ∧ P x ∧ all P m ∧ P y ∧ all P r := sorry theorem all_node4_r {α : Type u_1} {P : α → Prop} {l : ordnode α} {x : α} {m : ordnode α} {y : α} {r : ordnode α} : all P (node4_r l x m y r) ↔ all P l ∧ P x ∧ all P m ∧ P y ∧ all P r := sorry theorem all_rotate_l {α : Type u_1} {P : α → Prop} {l : ordnode α} {x : α} {r : ordnode α} : all P (rotate_l l x r) ↔ all P l ∧ P x ∧ all P r := sorry theorem all_rotate_r {α : Type u_1} {P : α → Prop} {l : ordnode α} {x : α} {r : ordnode α} : all P (rotate_r l x r) ↔ all P l ∧ P x ∧ all P r := sorry theorem all_balance' {α : Type u_1} {P : α → Prop} {l : ordnode α} {x : α} {r : ordnode α} : all P (balance' l x r) ↔ all P l ∧ P x ∧ all P r := sorry /-! ### `to_list` -/ theorem foldr_cons_eq_to_list {α : Type u_1} (t : ordnode α) (r : List α) : foldr List.cons t r = to_list t ++ r := sorry @[simp] theorem to_list_nil {α : Type u_1} : to_list nil = [] := rfl @[simp] theorem to_list_node {α : Type u_1} (s : ℕ) (l : ordnode α) (x : α) (r : ordnode α) : to_list (node s l x r) = to_list l ++ x :: to_list r := sorry theorem emem_iff_mem_to_list {α : Type u_1} {x : α} {t : ordnode α} : emem x t ↔ x ∈ to_list t := sorry theorem length_to_list' {α : Type u_1} (t : ordnode α) : list.length (to_list t) = real_size t := sorry theorem length_to_list {α : Type u_1} {t : ordnode α} (h : sized t) : list.length (to_list t) = size t := eq.mpr (id (Eq._oldrec (Eq.refl (list.length (to_list t) = size t)) (length_to_list' t))) (eq.mpr (id (Eq._oldrec (Eq.refl (real_size t = size t)) (size_eq_real_size h))) (Eq.refl (real_size t))) theorem equiv_iff {α : Type u_1} {t₁ : ordnode α} {t₂ : ordnode α} (h₁ : sized t₁) (h₂ : sized t₂) : equiv t₁ t₂ ↔ to_list t₁ = to_list t₂ := sorry /-! ### `(find/erase/split)_(min/max)` -/ theorem find_min'_dual {α : Type u_1} (t : ordnode α) (x : α) : find_min' (dual t) x = find_max' x t := sorry theorem find_max'_dual {α : Type u_1} (t : ordnode α) (x : α) : find_max' x (dual t) = find_min' t x := eq.mpr (id (Eq._oldrec (Eq.refl (find_max' x (dual t) = find_min' t x)) (Eq.symm (find_min'_dual (dual t) x)))) (eq.mpr (id (Eq._oldrec (Eq.refl (find_min' (dual (dual t)) x = find_min' t x)) (dual_dual t))) (Eq.refl (find_min' t x))) theorem find_min_dual {α : Type u_1} (t : ordnode α) : find_min (dual t) = find_max t := ordnode.cases_on t (idRhs (find_min (dual nil) = find_min (dual nil)) rfl) fun (t_size : ℕ) (t_l : ordnode α) (t_x : α) (t_r : ordnode α) => idRhs (some (find_min' (dual t_r) t_x) = some (find_max' t_x t_r)) (congr_arg some (find_min'_dual t_r t_x)) theorem find_max_dual {α : Type u_1} (t : ordnode α) : find_max (dual t) = find_min t := eq.mpr (id (Eq._oldrec (Eq.refl (find_max (dual t) = find_min t)) (Eq.symm (find_min_dual (dual t))))) (eq.mpr (id (Eq._oldrec (Eq.refl (find_min (dual (dual t)) = find_min t)) (dual_dual t))) (Eq.refl (find_min t))) theorem dual_erase_min {α : Type u_1} (t : ordnode α) : dual (erase_min t) = erase_max (dual t) := sorry theorem dual_erase_max {α : Type u_1} (t : ordnode α) : dual (erase_max t) = erase_min (dual t) := sorry theorem split_min_eq {α : Type u_1} (s : ℕ) (l : ordnode α) (x : α) (r : ordnode α) : split_min' l x r = (find_min' l x, erase_min (node s l x r)) := sorry theorem split_max_eq {α : Type u_1} (s : ℕ) (l : ordnode α) (x : α) (r : ordnode α) : split_max' l x r = (erase_max (node s l x r), find_max' x r) := sorry theorem find_min'_all {α : Type u_1} {P : α → Prop} (t : ordnode α) (x : α) : all P t → P x → P (find_min' t x) := sorry theorem find_max'_all {α : Type u_1} {P : α → Prop} (x : α) (t : ordnode α) : P x → all P t → P (find_max' x t) := sorry /-! ### `glue` -/ /-! ### `merge` -/ @[simp] theorem merge_nil_left {α : Type u_1} (t : ordnode α) : merge t nil = t := ordnode.cases_on t (Eq.refl (merge nil nil)) fun (t_size : ℕ) (t_l : ordnode α) (t_x : α) (t_r : ordnode α) => Eq.refl (merge (node t_size t_l t_x t_r) nil) @[simp] theorem merge_nil_right {α : Type u_1} (t : ordnode α) : merge nil t = t := rfl @[simp] theorem merge_node {α : Type u_1} {ls : ℕ} {ll : ordnode α} {lx : α} {lr : ordnode α} {rs : ℕ} {rl : ordnode α} {rx : α} {rr : ordnode α} : merge (node ls ll lx lr) (node rs rl rx rr) = ite (delta * ls < rs) (balance_l (merge (node ls ll lx lr) rl) rx rr) (ite (delta * rs < ls) (balance_r ll lx (merge lr (node rs rl rx rr))) (glue (node ls ll lx lr) (node rs rl rx rr))) := rfl /-! ### `insert` -/ theorem dual_insert {α : Type u_1} [preorder α] [is_total α LessEq] [DecidableRel LessEq] (x : α) (t : ordnode α) : dual (ordnode.insert x t) = ordnode.insert x (dual t) := sorry /-! ### `balance` properties -/ theorem balance_eq_balance' {α : Type u_1} {l : ordnode α} {x : α} {r : ordnode α} (hl : balanced l) (hr : balanced r) (sl : sized l) (sr : sized r) : balance l x r = balance' l x r := sorry theorem balance_l_eq_balance {α : Type u_1} {l : ordnode α} {x : α} {r : ordnode α} (sl : sized l) (sr : sized r) (H1 : size l = 0 → size r ≤ 1) (H2 : 1 ≤ size l → 1 ≤ size r → size r ≤ delta * size l) : balance_l l x r = balance l x r := sorry /-- `raised n m` means `m` is either equal or one up from `n`. -/ def raised (n : ℕ) (m : ℕ) := m = n ∨ m = n + 1 theorem raised_iff {n : ℕ} {m : ℕ} : raised n m ↔ n ≤ m ∧ m ≤ n + 1 := sorry theorem raised.dist_le {n : ℕ} {m : ℕ} (H : raised n m) : nat.dist n m ≤ 1 := sorry theorem raised.dist_le' {n : ℕ} {m : ℕ} (H : raised n m) : nat.dist m n ≤ 1 := eq.mpr (id (Eq._oldrec (Eq.refl (nat.dist m n ≤ 1)) (nat.dist_comm m n))) (raised.dist_le H) theorem raised.add_left (k : ℕ) {n : ℕ} {m : ℕ} (H : raised n m) : raised (k + n) (k + m) := or.dcases_on H (fun (H : m = n) => Eq._oldrec (Or.inl rfl) H) fun (H : m = n + 1) => Eq._oldrec (Or.inr rfl) (Eq.symm H) theorem raised.add_right (k : ℕ) {n : ℕ} {m : ℕ} (H : raised n m) : raised (n + k) (m + k) := eq.mpr (id (Eq._oldrec (Eq.refl (raised (n + k) (m + k))) (add_comm n k))) (eq.mpr (id (Eq._oldrec (Eq.refl (raised (k + n) (m + k))) (add_comm m k))) (raised.add_left k H)) theorem raised.right {α : Type u_1} {l : ordnode α} {x₁ : α} {x₂ : α} {r₁ : ordnode α} {r₂ : ordnode α} (H : raised (size r₁) (size r₂)) : raised (size (node' l x₁ r₁)) (size (node' l x₂ r₂)) := sorry theorem balance_l_eq_balance' {α : Type u_1} {l : ordnode α} {x : α} {r : ordnode α} (hl : balanced l) (hr : balanced r) (sl : sized l) (sr : sized r) (H : (∃ (l' : ℕ), raised l' (size l) ∧ balanced_sz l' (size r)) ∨ ∃ (r' : ℕ), raised (size r) r' ∧ balanced_sz (size l) r') : balance_l l x r = balance' l x r := sorry theorem balance_sz_dual {α : Type u_1} {l : ordnode α} {r : ordnode α} (H : (∃ (l' : ℕ), raised (size l) l' ∧ balanced_sz l' (size r)) ∨ ∃ (r' : ℕ), raised r' (size r) ∧ balanced_sz (size l) r') : (∃ (l' : ℕ), raised l' (size (dual r)) ∧ balanced_sz l' (size (dual l))) ∨ ∃ (r' : ℕ), raised (size (dual l)) r' ∧ balanced_sz (size (dual r)) r' := sorry theorem size_balance_l {α : Type u_1} {l : ordnode α} {x : α} {r : ordnode α} (hl : balanced l) (hr : balanced r) (sl : sized l) (sr : sized r) (H : (∃ (l' : ℕ), raised l' (size l) ∧ balanced_sz l' (size r)) ∨ ∃ (r' : ℕ), raised (size r) r' ∧ balanced_sz (size l) r') : size (balance_l l x r) = size l + size r + 1 := eq.mpr (id (Eq._oldrec (Eq.refl (size (balance_l l x r) = size l + size r + 1)) (balance_l_eq_balance' hl hr sl sr H))) (eq.mpr (id (Eq._oldrec (Eq.refl (size (balance' l x r) = size l + size r + 1)) (size_balance' sl sr))) (Eq.refl (size l + size r + 1))) theorem all_balance_l {α : Type u_1} {P : α → Prop} {l : ordnode α} {x : α} {r : ordnode α} (hl : balanced l) (hr : balanced r) (sl : sized l) (sr : sized r) (H : (∃ (l' : ℕ), raised l' (size l) ∧ balanced_sz l' (size r)) ∨ ∃ (r' : ℕ), raised (size r) r' ∧ balanced_sz (size l) r') : all P (balance_l l x r) ↔ all P l ∧ P x ∧ all P r := sorry theorem balance_r_eq_balance' {α : Type u_1} {l : ordnode α} {x : α} {r : ordnode α} (hl : balanced l) (hr : balanced r) (sl : sized l) (sr : sized r) (H : (∃ (l' : ℕ), raised (size l) l' ∧ balanced_sz l' (size r)) ∨ ∃ (r' : ℕ), raised r' (size r) ∧ balanced_sz (size l) r') : balance_r l x r = balance' l x r := sorry theorem size_balance_r {α : Type u_1} {l : ordnode α} {x : α} {r : ordnode α} (hl : balanced l) (hr : balanced r) (sl : sized l) (sr : sized r) (H : (∃ (l' : ℕ), raised (size l) l' ∧ balanced_sz l' (size r)) ∨ ∃ (r' : ℕ), raised r' (size r) ∧ balanced_sz (size l) r') : size (balance_r l x r) = size l + size r + 1 := eq.mpr (id (Eq._oldrec (Eq.refl (size (balance_r l x r) = size l + size r + 1)) (balance_r_eq_balance' hl hr sl sr H))) (eq.mpr (id (Eq._oldrec (Eq.refl (size (balance' l x r) = size l + size r + 1)) (size_balance' sl sr))) (Eq.refl (size l + size r + 1))) theorem all_balance_r {α : Type u_1} {P : α → Prop} {l : ordnode α} {x : α} {r : ordnode α} (hl : balanced l) (hr : balanced r) (sl : sized l) (sr : sized r) (H : (∃ (l' : ℕ), raised (size l) l' ∧ balanced_sz l' (size r)) ∨ ∃ (r' : ℕ), raised r' (size r) ∧ balanced_sz (size l) r') : all P (balance_r l x r) ↔ all P l ∧ P x ∧ all P r := sorry /-! ### `bounded` -/ /-- `bounded t lo hi` says that every element `x ∈ t` is in the range `lo < x < hi`, and also this property holds recursively in subtrees, making the full tree a BST. The bounds can be set to `lo = ⊥` and `hi = ⊤` if we care only about the internal ordering constraints. -/ def bounded {α : Type u_1} [preorder α] : ordnode α → with_bot α → with_top α → Prop := sorry theorem bounded.dual {α : Type u_1} [preorder α] {t : ordnode α} {o₁ : with_bot α} {o₂ : with_top α} (h : bounded t o₁ o₂) : bounded (dual t) o₂ o₁ := sorry theorem bounded.dual_iff {α : Type u_1} [preorder α] {t : ordnode α} {o₁ : with_bot α} {o₂ : with_top α} : bounded t o₁ o₂ ↔ bounded (dual t) o₂ o₁ := sorry theorem bounded.weak_left {α : Type u_1} [preorder α] {t : ordnode α} {o₁ : with_bot α} {o₂ : with_top α} : bounded t o₁ o₂ → bounded t ⊥ o₂ := sorry theorem bounded.weak_right {α : Type u_1} [preorder α] {t : ordnode α} {o₁ : with_bot α} {o₂ : with_top α} : bounded t o₁ o₂ → bounded t o₁ ⊤ := sorry theorem bounded.weak {α : Type u_1} [preorder α] {t : ordnode α} {o₁ : with_bot α} {o₂ : with_top α} (h : bounded t o₁ o₂) : bounded t ⊥ ⊤ := bounded.weak_right (bounded.weak_left h) theorem bounded.mono_left {α : Type u_1} [preorder α] {x : α} {y : α} (xy : x ≤ y) {t : ordnode α} {o : with_top α} : bounded t (↑y) o → bounded t (↑x) o := sorry theorem bounded.mono_right {α : Type u_1} [preorder α] {x : α} {y : α} (xy : x ≤ y) {t : ordnode α} {o : with_bot α} : bounded t o ↑x → bounded t o ↑y := sorry theorem bounded.to_lt {α : Type u_1} [preorder α] {t : ordnode α} {x : α} {y : α} : bounded t ↑x ↑y → x < y := sorry theorem bounded.to_nil {α : Type u_1} [preorder α] {t : ordnode α} {o₁ : with_bot α} {o₂ : with_top α} : bounded t o₁ o₂ → bounded nil o₁ o₂ := sorry theorem bounded.trans_left {α : Type u_1} [preorder α] {t₁ : ordnode α} {t₂ : ordnode α} {x : α} {o₁ : with_bot α} {o₂ : with_top α} : bounded t₁ o₁ ↑x → bounded t₂ (↑x) o₂ → bounded t₂ o₁ o₂ := sorry theorem bounded.trans_right {α : Type u_1} [preorder α] {t₁ : ordnode α} {t₂ : ordnode α} {x : α} {o₁ : with_bot α} {o₂ : with_top α} : bounded t₁ o₁ ↑x → bounded t₂ (↑x) o₂ → bounded t₁ o₁ o₂ := sorry theorem bounded.mem_lt {α : Type u_1} [preorder α] {t : ordnode α} {o : with_bot α} {x : α} : bounded t o ↑x → all (fun (_x : α) => _x < x) t := sorry theorem bounded.mem_gt {α : Type u_1} [preorder α] {t : ordnode α} {o : with_top α} {x : α} : bounded t (↑x) o → all (fun (_x : α) => _x > x) t := sorry theorem bounded.of_lt {α : Type u_1} [preorder α] {t : ordnode α} {o₁ : with_bot α} {o₂ : with_top α} {x : α} : bounded t o₁ o₂ → bounded nil o₁ ↑x → all (fun (_x : α) => _x < x) t → bounded t o₁ ↑x := sorry theorem bounded.of_gt {α : Type u_1} [preorder α] {t : ordnode α} {o₁ : with_bot α} {o₂ : with_top α} {x : α} : bounded t o₁ o₂ → bounded nil (↑x) o₂ → all (fun (_x : α) => _x > x) t → bounded t (↑x) o₂ := sorry theorem bounded.to_sep {α : Type u_1} [preorder α] {t₁ : ordnode α} {t₂ : ordnode α} {o₁ : with_bot α} {o₂ : with_top α} {x : α} (h₁ : bounded t₁ o₁ ↑x) (h₂ : bounded t₂ (↑x) o₂) : all (fun (y : α) => all (fun (z : α) => y < z) t₂) t₁ := all.imp (fun (y : α) (yx : y < x) => all.imp (fun (z : α) (xz : z > x) => lt_trans yx xz) (bounded.mem_gt h₂)) (bounded.mem_lt h₁) /-! ### `valid` -/ /-- The validity predicate for an `ordnode` subtree. This asserts that the `size` fields are correct, the tree is balanced, and the elements of the tree are organized according to the ordering. This version of `valid` also puts all elements in the tree in the interval `(lo, hi)`. -/ structure valid' {α : Type u_1} [preorder α] (lo : with_bot α) (t : ordnode α) (hi : with_top α) where ord : bounded t lo hi sz : sized t bal : balanced t /-- The validity predicate for an `ordnode` subtree. This asserts that the `size` fields are correct, the tree is balanced, and the elements of the tree are organized according to the ordering. -/ def valid {α : Type u_1} [preorder α] (t : ordnode α) := valid' ⊥ t ⊤ theorem valid'.mono_left {α : Type u_1} [preorder α] {x : α} {y : α} (xy : x ≤ y) {t : ordnode α} {o : with_top α} (h : valid' (↑y) t o) : valid' (↑x) t o := valid'.mk (bounded.mono_left xy (valid'.ord h)) (valid'.sz h) (valid'.bal h) theorem valid'.mono_right {α : Type u_1} [preorder α] {x : α} {y : α} (xy : x ≤ y) {t : ordnode α} {o : with_bot α} (h : valid' o t ↑x) : valid' o t ↑y := valid'.mk (bounded.mono_right xy (valid'.ord h)) (valid'.sz h) (valid'.bal h) theorem valid'.trans_left {α : Type u_1} [preorder α] {t₁ : ordnode α} {t₂ : ordnode α} {x : α} {o₁ : with_bot α} {o₂ : with_top α} (h : bounded t₁ o₁ ↑x) (H : valid' (↑x) t₂ o₂) : valid' o₁ t₂ o₂ := valid'.mk (bounded.trans_left h (valid'.ord H)) (valid'.sz H) (valid'.bal H) theorem valid'.trans_right {α : Type u_1} [preorder α] {t₁ : ordnode α} {t₂ : ordnode α} {x : α} {o₁ : with_bot α} {o₂ : with_top α} (H : valid' o₁ t₁ ↑x) (h : bounded t₂ (↑x) o₂) : valid' o₁ t₁ o₂ := valid'.mk (bounded.trans_right (valid'.ord H) h) (valid'.sz H) (valid'.bal H) theorem valid'.of_lt {α : Type u_1} [preorder α] {t : ordnode α} {x : α} {o₁ : with_bot α} {o₂ : with_top α} (H : valid' o₁ t o₂) (h₁ : bounded nil o₁ ↑x) (h₂ : all (fun (_x : α) => _x < x) t) : valid' o₁ t ↑x := valid'.mk (bounded.of_lt (valid'.ord H) h₁ h₂) (valid'.sz H) (valid'.bal H) theorem valid'.of_gt {α : Type u_1} [preorder α] {t : ordnode α} {x : α} {o₁ : with_bot α} {o₂ : with_top α} (H : valid' o₁ t o₂) (h₁ : bounded nil (↑x) o₂) (h₂ : all (fun (_x : α) => _x > x) t) : valid' (↑x) t o₂ := valid'.mk (bounded.of_gt (valid'.ord H) h₁ h₂) (valid'.sz H) (valid'.bal H) theorem valid'.valid {α : Type u_1} [preorder α] {t : ordnode α} {o₁ : with_bot α} {o₂ : with_top α} (h : valid' o₁ t o₂) : valid t := valid'.mk (bounded.weak (valid'.ord h)) (valid'.sz h) (valid'.bal h) theorem valid'_nil {α : Type u_1} [preorder α] {o₁ : with_bot α} {o₂ : with_top α} (h : bounded nil o₁ o₂) : valid' o₁ nil o₂ := valid'.mk h True.intro True.intro theorem valid_nil {α : Type u_1} [preorder α] : valid nil := valid'_nil True.intro theorem valid'.node {α : Type u_1} [preorder α] {s : ℕ} {l : ordnode α} {x : α} {r : ordnode α} {o₁ : with_bot α} {o₂ : with_top α} (hl : valid' o₁ l ↑x) (hr : valid' (↑x) r o₂) (H : balanced_sz (size l) (size r)) (hs : s = size l + size r + 1) : valid' o₁ (node s l x r) o₂ := valid'.mk { left := valid'.ord hl, right := valid'.ord hr } { left := hs, right := { left := valid'.sz hl, right := valid'.sz hr } } { left := H, right := { left := valid'.bal hl, right := valid'.bal hr } } theorem valid'.dual {α : Type u_1} [preorder α] {t : ordnode α} {o₁ : with_bot α} {o₂ : with_top α} (h : valid' o₁ t o₂) : valid' o₂ (dual t) o₁ := sorry theorem valid'.dual_iff {α : Type u_1} [preorder α] {t : ordnode α} {o₁ : with_bot α} {o₂ : with_top α} : valid' o₁ t o₂ ↔ valid' o₂ (dual t) o₁ := sorry theorem valid.dual {α : Type u_1} [preorder α] {t : ordnode α} : valid t → valid (dual t) := valid'.dual theorem valid.dual_iff {α : Type u_1} [preorder α] {t : ordnode α} : valid t ↔ valid (dual t) := valid'.dual_iff theorem valid'.left {α : Type u_1} [preorder α] {s : ℕ} {l : ordnode α} {x : α} {r : ordnode α} {o₁ : with_bot α} {o₂ : with_top α} (H : valid' o₁ (node s l x r) o₂) : valid' o₁ l ↑x := valid'.mk (and.left (valid'.ord H)) (and.left (and.right (valid'.sz H))) (and.left (and.right (valid'.bal H))) theorem valid'.right {α : Type u_1} [preorder α] {s : ℕ} {l : ordnode α} {x : α} {r : ordnode α} {o₁ : with_bot α} {o₂ : with_top α} (H : valid' o₁ (node s l x r) o₂) : valid' (↑x) r o₂ := valid'.mk (and.right (valid'.ord H)) (and.right (and.right (valid'.sz H))) (and.right (and.right (valid'.bal H))) theorem valid.left {α : Type u_1} [preorder α] {s : ℕ} {l : ordnode α} {x : α} {r : ordnode α} (H : valid (node s l x r)) : valid l := valid'.valid (valid'.left H) theorem valid.right {α : Type u_1} [preorder α] {s : ℕ} {l : ordnode α} {x : α} {r : ordnode α} (H : valid (node s l x r)) : valid r := valid'.valid (valid'.right H) theorem valid.size_eq {α : Type u_1} [preorder α] {s : ℕ} {l : ordnode α} {x : α} {r : ordnode α} (H : valid (node s l x r)) : size (node s l x r) = size l + size r + 1 := and.left (valid'.sz H) theorem valid'.node' {α : Type u_1} [preorder α] {l : ordnode α} {x : α} {r : ordnode α} {o₁ : with_bot α} {o₂ : with_top α} (hl : valid' o₁ l ↑x) (hr : valid' (↑x) r o₂) (H : balanced_sz (size l) (size r)) : valid' o₁ (node' l x r) o₂ := valid'.node hl hr H rfl theorem valid'_singleton {α : Type u_1} [preorder α] {x : α} {o₁ : with_bot α} {o₂ : with_top α} (h₁ : bounded nil o₁ ↑x) (h₂ : bounded nil (↑x) o₂) : valid' o₁ (singleton x) o₂ := valid'.node (valid'_nil h₁) (valid'_nil h₂) (Or.inl zero_le_one) rfl theorem valid_singleton {α : Type u_1} [preorder α] {x : α} : valid (singleton x) := valid'_singleton True.intro True.intro theorem valid'.node3_l {α : Type u_1} [preorder α] {l : ordnode α} {x : α} {m : ordnode α} {y : α} {r : ordnode α} {o₁ : with_bot α} {o₂ : with_top α} (hl : valid' o₁ l ↑x) (hm : valid' (↑x) m ↑y) (hr : valid' (↑y) r o₂) (H1 : balanced_sz (size l) (size m)) (H2 : balanced_sz (size l + size m + 1) (size r)) : valid' o₁ (node3_l l x m y r) o₂ := valid'.node' (valid'.node' hl hm H1) hr H2 theorem valid'.node3_r {α : Type u_1} [preorder α] {l : ordnode α} {x : α} {m : ordnode α} {y : α} {r : ordnode α} {o₁ : with_bot α} {o₂ : with_top α} (hl : valid' o₁ l ↑x) (hm : valid' (↑x) m ↑y) (hr : valid' (↑y) r o₂) (H1 : balanced_sz (size l) (size m + size r + 1)) (H2 : balanced_sz (size m) (size r)) : valid' o₁ (node3_r l x m y r) o₂ := valid'.node' hl (valid'.node' hm hr H2) H1 theorem valid'.node4_l_lemma₁ {a : ℕ} {b : ℕ} {c : ℕ} {d : ℕ} (lr₂ : bit1 1 * (b + c + 1 + d) ≤ bit0 (bit0 (bit0 (bit0 1))) * a + bit1 (bit0 (bit0 1))) (mr₂ : b + c + 1 ≤ bit1 1 * d) (mm₁ : b ≤ bit1 1 * c) : b < bit1 1 * a + 1 := sorry theorem valid'.node4_l_lemma₂ {b : ℕ} {c : ℕ} {d : ℕ} (mr₂ : b + c + 1 ≤ bit1 1 * d) : c ≤ bit1 1 * d := sorry theorem valid'.node4_l_lemma₃ {b : ℕ} {c : ℕ} {d : ℕ} (mr₁ : bit0 1 * d ≤ b + c + 1) (mm₁ : b ≤ bit1 1 * c) : d ≤ bit1 1 * c := sorry theorem valid'.node4_l_lemma₄ {a : ℕ} {b : ℕ} {c : ℕ} {d : ℕ} (lr₁ : bit1 1 * a ≤ b + c + 1 + d) (mr₂ : b + c + 1 ≤ bit1 1 * d) (mm₁ : b ≤ bit1 1 * c) : a + b + 1 ≤ bit1 1 * (c + d + 1) := sorry theorem valid'.node4_l_lemma₅ {a : ℕ} {b : ℕ} {c : ℕ} {d : ℕ} (lr₂ : bit1 1 * (b + c + 1 + d) ≤ bit0 (bit0 (bit0 (bit0 1))) * a + bit1 (bit0 (bit0 1))) (mr₁ : bit0 1 * d ≤ b + c + 1) (mm₂ : c ≤ bit1 1 * b) : c + d + 1 ≤ bit1 1 * (a + b + 1) := sorry theorem valid'.node4_l {α : Type u_1} [preorder α] {l : ordnode α} {x : α} {m : ordnode α} {y : α} {r : ordnode α} {o₁ : with_bot α} {o₂ : with_top α} (hl : valid' o₁ l ↑x) (hm : valid' (↑x) m ↑y) (hr : valid' (↑y) r o₂) (Hm : 0 < size m) (H : size l = 0 ∧ size m = 1 ∧ size r ≤ 1 ∨ 0 < size l ∧ ratio * size r ≤ size m ∧ delta * size l ≤ size m + size r ∧ bit1 1 * (size m + size r) ≤ bit0 (bit0 (bit0 (bit0 1))) * size l + bit1 (bit0 (bit0 1)) ∧ size m ≤ delta * size r) : valid' o₁ (node4_l l x m y r) o₂ := sorry theorem valid'.rotate_l_lemma₁ {a : ℕ} {b : ℕ} {c : ℕ} (H2 : bit1 1 * a ≤ b + c) (hb₂ : c ≤ bit1 1 * b) : a ≤ bit1 1 * b := sorry theorem valid'.rotate_l_lemma₂ {a : ℕ} {b : ℕ} {c : ℕ} (H3 : bit0 1 * (b + c) ≤ bit1 (bit0 (bit0 1)) * a + bit1 1) (h : b < bit0 1 * c) : b < bit1 1 * a + 1 := sorry theorem valid'.rotate_l_lemma₃ {a : ℕ} {b : ℕ} {c : ℕ} (H2 : bit1 1 * a ≤ b + c) (h : b < bit0 1 * c) : a + b < bit1 1 * c := sorry theorem valid'.rotate_l_lemma₄ {a : ℕ} {b : ℕ} (H3 : bit0 1 * b ≤ bit1 (bit0 (bit0 1)) * a + bit1 1) : bit1 1 * b ≤ bit0 (bit0 (bit0 (bit0 1))) * a + bit1 (bit0 (bit0 1)) := sorry theorem valid'.rotate_l {α : Type u_1} [preorder α] {l : ordnode α} {x : α} {r : ordnode α} {o₁ : with_bot α} {o₂ : with_top α} (hl : valid' o₁ l ↑x) (hr : valid' (↑x) r o₂) (H1 : ¬size l + size r ≤ 1) (H2 : delta * size l < size r) (H3 : bit0 1 * size r ≤ bit1 (bit0 (bit0 1)) * size l + bit1 (bit0 1) ∨ size r ≤ bit1 1) : valid' o₁ (rotate_l l x r) o₂ := sorry theorem valid'.rotate_r {α : Type u_1} [preorder α] {l : ordnode α} {x : α} {r : ordnode α} {o₁ : with_bot α} {o₂ : with_top α} (hl : valid' o₁ l ↑x) (hr : valid' (↑x) r o₂) (H1 : ¬size l + size r ≤ 1) (H2 : delta * size r < size l) (H3 : bit0 1 * size l ≤ bit1 (bit0 (bit0 1)) * size r + bit1 (bit0 1) ∨ size l ≤ bit1 1) : valid' o₁ (rotate_r l x r) o₂ := sorry theorem valid'.balance'_aux {α : Type u_1} [preorder α] {l : ordnode α} {x : α} {r : ordnode α} {o₁ : with_bot α} {o₂ : with_top α} (hl : valid' o₁ l ↑x) (hr : valid' (↑x) r o₂) (H₁ : bit0 1 * size r ≤ bit1 (bit0 (bit0 1)) * size l + bit1 (bit0 1) ∨ size r ≤ bit1 1) (H₂ : bit0 1 * size l ≤ bit1 (bit0 (bit0 1)) * size r + bit1 (bit0 1) ∨ size l ≤ bit1 1) : valid' o₁ (balance' l x r) o₂ := sorry theorem valid'.balance'_lemma {α : Type u_1} {l : ordnode α} {l' : ℕ} {r : ordnode α} {r' : ℕ} (H1 : balanced_sz l' r') (H2 : nat.dist (size l) l' ≤ 1 ∧ size r = r' ∨ nat.dist (size r) r' ≤ 1 ∧ size l = l') : bit0 1 * size r ≤ bit1 (bit0 (bit0 1)) * size l + bit1 (bit0 1) ∨ size r ≤ bit1 1 := sorry theorem valid'.balance' {α : Type u_1} [preorder α] {l : ordnode α} {x : α} {r : ordnode α} {o₁ : with_bot α} {o₂ : with_top α} (hl : valid' o₁ l ↑x) (hr : valid' (↑x) r o₂) (H : ∃ (l' : ℕ), ∃ (r' : ℕ), balanced_sz l' r' ∧ (nat.dist (size l) l' ≤ 1 ∧ size r = r' ∨ nat.dist (size r) r' ≤ 1 ∧ size l = l')) : valid' o₁ (balance' l x r) o₂ := sorry theorem valid'.balance {α : Type u_1} [preorder α] {l : ordnode α} {x : α} {r : ordnode α} {o₁ : with_bot α} {o₂ : with_top α} (hl : valid' o₁ l ↑x) (hr : valid' (↑x) r o₂) (H : ∃ (l' : ℕ), ∃ (r' : ℕ), balanced_sz l' r' ∧ (nat.dist (size l) l' ≤ 1 ∧ size r = r' ∨ nat.dist (size r) r' ≤ 1 ∧ size l = l')) : valid' o₁ (balance l x r) o₂ := sorry theorem valid'.balance_l_aux {α : Type u_1} [preorder α] {l : ordnode α} {x : α} {r : ordnode α} {o₁ : with_bot α} {o₂ : with_top α} (hl : valid' o₁ l ↑x) (hr : valid' (↑x) r o₂) (H₁ : size l = 0 → size r ≤ 1) (H₂ : 1 ≤ size l → 1 ≤ size r → size r ≤ delta * size l) (H₃ : bit0 1 * size l ≤ bit1 (bit0 (bit0 1)) * size r + bit1 (bit0 1) ∨ size l ≤ bit1 1) : valid' o₁ (balance_l l x r) o₂ := sorry theorem valid'.balance_l {α : Type u_1} [preorder α] {l : ordnode α} {x : α} {r : ordnode α} {o₁ : with_bot α} {o₂ : with_top α} (hl : valid' o₁ l ↑x) (hr : valid' (↑x) r o₂) (H : (∃ (l' : ℕ), raised l' (size l) ∧ balanced_sz l' (size r)) ∨ ∃ (r' : ℕ), raised (size r) r' ∧ balanced_sz (size l) r') : valid' o₁ (balance_l l x r) o₂ := sorry theorem valid'.balance_r_aux {α : Type u_1} [preorder α] {l : ordnode α} {x : α} {r : ordnode α} {o₁ : with_bot α} {o₂ : with_top α} (hl : valid' o₁ l ↑x) (hr : valid' (↑x) r o₂) (H₁ : size r = 0 → size l ≤ 1) (H₂ : 1 ≤ size r → 1 ≤ size l → size l ≤ delta * size r) (H₃ : bit0 1 * size r ≤ bit1 (bit0 (bit0 1)) * size l + bit1 (bit0 1) ∨ size r ≤ bit1 1) : valid' o₁ (balance_r l x r) o₂ := sorry theorem valid'.balance_r {α : Type u_1} [preorder α] {l : ordnode α} {x : α} {r : ordnode α} {o₁ : with_bot α} {o₂ : with_top α} (hl : valid' o₁ l ↑x) (hr : valid' (↑x) r o₂) (H : (∃ (l' : ℕ), raised (size l) l' ∧ balanced_sz l' (size r)) ∨ ∃ (r' : ℕ), raised r' (size r) ∧ balanced_sz (size l) r') : valid' o₁ (balance_r l x r) o₂ := eq.mpr (id (Eq._oldrec (Eq.refl (valid' o₁ (balance_r l x r) o₂)) (propext valid'.dual_iff))) (eq.mpr (id (Eq._oldrec (Eq.refl (valid' o₂ (dual (balance_r l x r)) o₁)) (dual_balance_r l x r))) (valid'.balance_l (valid'.dual hr) (valid'.dual hl) (balance_sz_dual H))) theorem valid'.erase_max_aux {α : Type u_1} [preorder α] {s : ℕ} {l : ordnode α} {x : α} {r : ordnode α} {o₁ : with_bot α} {o₂ : with_top α} (H : valid' o₁ (node s l x r) o₂) : valid' o₁ (erase_max (node' l x r)) ↑(find_max' x r) ∧ size (node' l x r) = size (erase_max (node' l x r)) + 1 := sorry theorem valid'.erase_min_aux {α : Type u_1} [preorder α] {s : ℕ} {l : ordnode α} {x : α} {r : ordnode α} {o₁ : with_bot α} {o₂ : with_top α} (H : valid' o₁ (node s l x r) o₂) : valid' (↑(find_min' l x)) (erase_min (node' l x r)) o₂ ∧ size (node' l x r) = size (erase_min (node' l x r)) + 1 := sorry theorem erase_min.valid {α : Type u_1} [preorder α] {t : ordnode α} (h : valid t) : valid (erase_min t) := sorry theorem erase_max.valid {α : Type u_1} [preorder α] {t : ordnode α} (h : valid t) : valid (erase_max t) := eq.mpr (id (Eq._oldrec (Eq.refl (valid (erase_max t))) (propext valid.dual_iff))) (eq.mpr (id (Eq._oldrec (Eq.refl (valid (dual (erase_max t)))) (dual_erase_max t))) (erase_min.valid (valid.dual h))) theorem valid'.glue_aux {α : Type u_1} [preorder α] {l : ordnode α} {r : ordnode α} {o₁ : with_bot α} {o₂ : with_top α} (hl : valid' o₁ l o₂) (hr : valid' o₁ r o₂) (sep : all (fun (x : α) => all (fun (y : α) => x < y) r) l) (bal : balanced_sz (size l) (size r)) : valid' o₁ (glue l r) o₂ ∧ size (glue l r) = size l + size r := sorry theorem valid'.glue {α : Type u_1} [preorder α] {l : ordnode α} {x : α} {r : ordnode α} {o₁ : with_bot α} {o₂ : with_top α} (hl : valid' o₁ l ↑x) (hr : valid' (↑x) r o₂) : balanced_sz (size l) (size r) → valid' o₁ (glue l r) o₂ ∧ size (glue l r) = size l + size r := valid'.glue_aux (valid'.trans_right hl (valid'.ord hr)) (valid'.trans_left (valid'.ord hl) hr) (bounded.to_sep (valid'.ord hl) (valid'.ord hr)) theorem valid'.merge_lemma {a : ℕ} {b : ℕ} {c : ℕ} (h₁ : bit1 1 * a < b + c + 1) (h₂ : b ≤ bit1 1 * c) : bit0 1 * (a + b) ≤ bit1 (bit0 (bit0 1)) * c + bit1 (bit0 1) := sorry theorem valid'.merge_aux₁ {α : Type u_1} [preorder α] {o₁ : with_bot α} {o₂ : with_top α} {ls : ℕ} {ll : ordnode α} {lx : α} {lr : ordnode α} {rs : ℕ} {rl : ordnode α} {rx : α} {rr : ordnode α} {t : ordnode α} (hl : valid' o₁ (node ls ll lx lr) o₂) (hr : valid' o₁ (node rs rl rx rr) o₂) (h : delta * ls < rs) (v : valid' o₁ t ↑rx) (e : size t = ls + size rl) : valid' o₁ (balance_l t rx rr) o₂ ∧ size (balance_l t rx rr) = ls + rs := sorry theorem valid'.merge_aux {α : Type u_1} [preorder α] {l : ordnode α} {r : ordnode α} {o₁ : with_bot α} {o₂ : with_top α} (hl : valid' o₁ l o₂) (hr : valid' o₁ r o₂) (sep : all (fun (x : α) => all (fun (y : α) => x < y) r) l) : valid' o₁ (merge l r) o₂ ∧ size (merge l r) = size l + size r := sorry theorem valid.merge {α : Type u_1} [preorder α] {l : ordnode α} {r : ordnode α} (hl : valid l) (hr : valid r) (sep : all (fun (x : α) => all (fun (y : α) => x < y) r) l) : valid (merge l r) := and.left (valid'.merge_aux hl hr sep) theorem insert_with.valid_aux {α : Type u_1} [preorder α] [is_total α LessEq] [DecidableRel LessEq] (f : α → α) (x : α) (hf : ∀ (y : α), x ≤ y ∧ y ≤ x → x ≤ f y ∧ f y ≤ x) {t : ordnode α} {o₁ : with_bot α} {o₂ : with_top α} : valid' o₁ t o₂ → bounded nil o₁ ↑x → bounded nil (↑x) o₂ → valid' o₁ (insert_with f x t) o₂ ∧ raised (size t) (size (insert_with f x t)) := sorry theorem insert_with.valid {α : Type u_1} [preorder α] [is_total α LessEq] [DecidableRel LessEq] (f : α → α) (x : α) (hf : ∀ (y : α), x ≤ y ∧ y ≤ x → x ≤ f y ∧ f y ≤ x) {t : ordnode α} (h : valid t) : valid (insert_with f x t) := and.left (insert_with.valid_aux (fun (y : α) => f y) x hf h True.intro True.intro) theorem insert_eq_insert_with {α : Type u_1} [preorder α] [DecidableRel LessEq] (x : α) (t : ordnode α) : ordnode.insert x t = insert_with (fun (_x : α) => x) x t := sorry theorem insert.valid {α : Type u_1} [preorder α] [is_total α LessEq] [DecidableRel LessEq] (x : α) {t : ordnode α} (h : valid t) : valid (ordnode.insert x t) := eq.mpr (id (Eq._oldrec (Eq.refl (valid (ordnode.insert x t))) (insert_eq_insert_with x t))) (insert_with.valid (fun (_x : α) => x) x (fun (_x : α) (_x : x ≤ _x ∧ _x ≤ x) => { left := le_refl x, right := le_refl x }) h) theorem insert'_eq_insert_with {α : Type u_1} [preorder α] [DecidableRel LessEq] (x : α) (t : ordnode α) : insert' x t = insert_with id x t := sorry theorem insert'.valid {α : Type u_1} [preorder α] [is_total α LessEq] [DecidableRel LessEq] (x : α) {t : ordnode α} (h : valid t) : valid (insert' x t) := eq.mpr (id (Eq._oldrec (Eq.refl (valid (insert' x t))) (insert'_eq_insert_with x t))) (insert_with.valid id x (fun (_x : α) => id) h) end ordnode /-- An `ordset α` is a finite set of values, represented as a tree. The operations on this type maintain that the tree is balanced and correctly stores subtree sizes at each level. The correctness property of the tree is baked into the type, so all operations on this type are correct by construction. -/ def ordset (α : Type u_1) [preorder α] := Subtype fun (t : ordnode α) => ordnode.valid t namespace ordset /-- O(1). The empty set. -/ def nil {α : Type u_1} [preorder α] : ordset α := { val := ordnode.nil, property := sorry } /-- O(1). Get the size of the set. -/ def size {α : Type u_1} [preorder α] (s : ordset α) : ℕ := ordnode.size (subtype.val s) /-- O(1). Construct a singleton set containing value `a`. -/ protected def singleton {α : Type u_1} [preorder α] (a : α) : ordset α := { val := singleton a, property := ordnode.valid_singleton } protected instance has_emptyc {α : Type u_1} [preorder α] : has_emptyc (ordset α) := has_emptyc.mk nil protected instance inhabited {α : Type u_1} [preorder α] : Inhabited (ordset α) := { default := nil } protected instance has_singleton {α : Type u_1} [preorder α] : has_singleton α (ordset α) := has_singleton.mk ordset.singleton /-- O(1). Is the set empty? -/ def empty {α : Type u_1} [preorder α] (s : ordset α) := s = ∅ theorem empty_iff {α : Type u_1} [preorder α] {s : ordset α} : s = ∅ ↔ ↥(ordnode.empty (subtype.val s)) := sorry protected instance empty.decidable_pred {α : Type u_1} [preorder α] : decidable_pred empty := fun (s : ordset α) => decidable_of_iff' (↥(ordnode.empty (subtype.val s))) empty_iff /-- O(log n). Insert an element into the set, preserving balance and the BST property. If an equivalent element is already in the set, this replaces it. -/ protected def insert {α : Type u_1} [preorder α] [is_total α LessEq] [DecidableRel LessEq] (x : α) (s : ordset α) : ordset α := { val := ordnode.insert x (subtype.val s), property := sorry } protected instance has_insert {α : Type u_1} [preorder α] [is_total α LessEq] [DecidableRel LessEq] : has_insert α (ordset α) := has_insert.mk ordset.insert /-- O(log n). Insert an element into the set, preserving balance and the BST property. If an equivalent element is already in the set, the set is returned as is. -/ def insert' {α : Type u_1} [preorder α] [is_total α LessEq] [DecidableRel LessEq] (x : α) (s : ordset α) : ordset α := { val := ordnode.insert' x (subtype.val s), property := sorry } end Mathlib
0f682b76de171312ac67a2e7353361cac092b621
e39f04f6ff425fe3b3f5e26a8998b817d1dba80f
/category_theory/limits/limits.lean
d0e637dacb2c48d679451b256e497639534e6916
[ "Apache-2.0" ]
permissive
kristychoi/mathlib
c504b5e8f84e272ea1d8966693c42de7523bf0ec
257fd84fe98927ff4a5ffe044f68c4e9d235cc75
refs/heads/master
1,586,520,722,896
1,544,030,145,000
1,544,031,933,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
22,773
lean
-- Copyright (c) 2018 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Scott Morrison, Reid Barton, Mario Carneiro import category_theory.whiskering import category_theory.yoneda import category_theory.limits.cones open category_theory category_theory.category category_theory.functor namespace category_theory.limits universes u u' u'' v w variables {J : Type v} [small_category J] variables {C : Type u} [𝒞 : category.{u v} C] include 𝒞 variables {F : J ⥤ C} /-- A cone `t` on `F` is a limit cone if each cone on `F` admits a unique cone morphism to `t`. -/ structure is_limit (t : cone F) := (lift : Π (s : cone F), s.X ⟶ t.X) (fac' : ∀ (s : cone F) (j : J), lift s ≫ t.π.app j = s.π.app j . obviously) (uniq' : ∀ (s : cone F) (m : s.X ⟶ t.X) (w : ∀ j : J, m ≫ t.π.app j = s.π.app j), m = lift s . obviously) restate_axiom is_limit.fac' attribute [simp] is_limit.fac restate_axiom is_limit.uniq' namespace is_limit instance subsingleton {t : cone F} : subsingleton (is_limit t) := ⟨by intros P Q; cases P; cases Q; congr; ext; solve_by_elim⟩ /- Repackaging the definition in terms of cone morphisms. -/ def lift_cone_morphism {t : cone F} (h : is_limit t) (s : cone F) : s ⟶ t := { hom := h.lift s } lemma uniq_cone_morphism {s t : cone F} (h : is_limit t) {f f' : s ⟶ t} : f = f' := have ∀ {g : s ⟶ t}, g = h.lift_cone_morphism s, by intro g; ext; exact h.uniq _ _ g.w, this.trans this.symm def mk_cone_morphism {t : cone F} (lift : Π (s : cone F), s ⟶ t) (uniq' : ∀ (s : cone F) (m : s ⟶ t), m = lift s) : is_limit t := { lift := λ s, (lift s).hom, uniq' := λ s m w, have cone_morphism.mk m w = lift s, by apply uniq', congr_arg cone_morphism.hom this } /-- Limit cones on `F` are unique up to isomorphism. -/ def unique {s t : cone F} (P : is_limit s) (Q : is_limit t) : s ≅ t := { hom := Q.lift_cone_morphism s, inv := P.lift_cone_morphism t, hom_inv_id' := P.uniq_cone_morphism, inv_hom_id' := Q.uniq_cone_morphism } def of_iso_limit {r t : cone F} (P : is_limit r) (i : r ≅ t) : is_limit t := is_limit.mk_cone_morphism (λ s, P.lift_cone_morphism s ≫ i.hom) (λ s m, by rw ←i.comp_inv_eq; apply P.uniq_cone_morphism) variables {t : cone F} lemma hom_lift (h : is_limit t) {W : C} (m : W ⟶ t.X) : m = h.lift { X := W, π := { app := λ b, m ≫ t.π.app b } } := h.uniq { X := W, π := { app := λ b, m ≫ t.π.app b } } m (λ b, rfl) /-- Two morphisms into a limit are equal if their compositions with each cone morphism are equal. -/ lemma hom_ext (h : is_limit t) {W : C} {f f' : W ⟶ t.X} (w : ∀ j, f ≫ t.π.app j = f' ≫ t.π.app j) : f = f' := by rw [h.hom_lift f, h.hom_lift f']; congr; exact funext w /-- The universal property of a limit cone: a map `W ⟶ X` is the same as a cone on `F` with vertex `W`. -/ def hom_iso (h : is_limit t) (W : C) : (W ⟶ t.X) ≅ ((const J).obj W ⟹ F) := { hom := λ f, (t.extend f).π, inv := λ π, h.lift { X := W, π := π }, hom_inv_id' := by ext f; apply h.hom_ext; intro j; simp; dsimp; refl } @[simp] lemma hom_iso_hom (h : is_limit t) {W : C} (f : W ⟶ t.X) : (is_limit.hom_iso h W).hom f = (t.extend f).π := rfl /-- The limit of `F` represents the functor taking `W` to the set of cones on `F` with vertex `W`. -/ def nat_iso (h : is_limit t) : yoneda.obj t.X ≅ F.cones := nat_iso.of_components (is_limit.hom_iso h) (by tidy) def hom_iso' (h : is_limit t) (W : C) : (W ⟶ t.X) ≅ { p : Π j, W ⟶ F.obj j // ∀ {j j'} (f : j ⟶ j'), p j ≫ F.map f = p j' } := h.hom_iso W ≪≫ { hom := λ π, ⟨λ j, π.app j, λ j j' f, by convert ←(π.naturality f).symm; apply id_comp⟩, inv := λ p, { app := λ j, p.1 j, naturality' := λ j j' f, begin dsimp, erw [id_comp], exact (p.2 f).symm end } } end is_limit /-- A cocone `t` on `F` is a colimit cocone if each cocone on `F` admits a unique cocone morphism from `t`. -/ structure is_colimit (t : cocone F) := (desc : Π (s : cocone F), t.X ⟶ s.X) (fac' : ∀ (s : cocone F) (j : J), t.ι.app j ≫ desc s = s.ι.app j . obviously) (uniq' : ∀ (s : cocone F) (m : t.X ⟶ s.X) (w : ∀ j : J, t.ι.app j ≫ m = s.ι.app j), m = desc s . obviously) restate_axiom is_colimit.fac' attribute [simp] is_colimit.fac restate_axiom is_colimit.uniq' namespace is_colimit instance subsingleton {t : cocone F} : subsingleton (is_colimit t) := ⟨by intros P Q; cases P; cases Q; congr; ext; solve_by_elim⟩ /- Repackaging the definition in terms of cone morphisms. -/ def desc_cocone_morphism {t : cocone F} (h : is_colimit t) (s : cocone F) : t ⟶ s := { hom := h.desc s } lemma uniq_cocone_morphism {s t : cocone F} (h : is_colimit t) {f f' : t ⟶ s} : f = f' := have ∀ {g : t ⟶ s}, g = h.desc_cocone_morphism s, by intro g; ext; exact h.uniq _ _ g.w, this.trans this.symm def mk_cocone_morphism {t : cocone F} (desc : Π (s : cocone F), t ⟶ s) (uniq' : ∀ (s : cocone F) (m : t ⟶ s), m = desc s) : is_colimit t := { desc := λ s, (desc s).hom, uniq' := λ s m w, have cocone_morphism.mk m w = desc s, by apply uniq', congr_arg cocone_morphism.hom this } /-- Limit cones on `F` are unique up to isomorphism. -/ def unique {s t : cocone F} (P : is_colimit s) (Q : is_colimit t) : s ≅ t := { hom := P.desc_cocone_morphism t, inv := Q.desc_cocone_morphism s, hom_inv_id' := P.uniq_cocone_morphism, inv_hom_id' := Q.uniq_cocone_morphism } def of_iso_colimit {r t : cocone F} (P : is_colimit r) (i : r ≅ t) : is_colimit t := is_colimit.mk_cocone_morphism (λ s, i.inv ≫ P.desc_cocone_morphism s) (λ s m, by rw i.eq_inv_comp; apply P.uniq_cocone_morphism) variables {t : cocone F} lemma hom_desc (h : is_colimit t) {W : C} (m : t.X ⟶ W) : m = h.desc { X := W, ι := { app := λ b, t.ι.app b ≫ m, naturality' := by intros; erw [←assoc, t.ι.naturality, comp_id, comp_id] } } := h.uniq { X := W, ι := { app := λ b, t.ι.app b ≫ m, naturality' := _ } } m (λ b, rfl) /-- Two morphisms out of a colimit are equal if their compositions with each cocone morphism are equal. -/ lemma hom_ext (h : is_colimit t) {W : C} {f f' : t.X ⟶ W} (w : ∀ j, t.ι.app j ≫ f = t.ι.app j ≫ f') : f = f' := by rw [h.hom_desc f, h.hom_desc f']; congr; exact funext w /-- The universal property of a colimit cocone: a map `X ⟶ W` is the same as a cocone on `F` with vertex `W`. -/ def hom_iso (h : is_colimit t) (W : C) : (t.X ⟶ W) ≅ (F ⟹ (const J).obj W) := { hom := λ f, (t.extend f).ι, inv := λ ι, h.desc { X := W, ι := ι }, hom_inv_id' := by ext f; apply h.hom_ext; intro j; simp; dsimp; refl } @[simp] lemma hom_iso_hom (h : is_colimit t) {W : C} (f : t.X ⟶ W) : (is_colimit.hom_iso h W).hom f = (t.extend f).ι := rfl /-- The colimit of `F` represents the functor taking `W` to the set of cocones on `F` with vertex `W`. -/ def nat_iso (h : is_colimit t) : coyoneda.obj t.X ≅ F.cocones := nat_iso.of_components (is_colimit.hom_iso h) (by intros; ext; dsimp; rw ←assoc; refl) def hom_iso' (h : is_colimit t) (W : C) : (t.X ⟶ W) ≅ { p : Π j, F.obj j ⟶ W // ∀ {j j' : J} (f : j ⟶ j'), F.map f ≫ p j' = p j } := h.hom_iso W ≪≫ { hom := λ ι, ⟨λ j, ι.app j, λ j j' f, by convert ←(ι.naturality f); apply comp_id⟩, inv := λ p, { app := λ j, p.1 j, naturality' := λ j j' f, begin dsimp, erw [comp_id], exact (p.2 f) end } } end is_colimit section limit /-- `has_limit F` represents a particular chosen limit of the diagram `F`. -/ class has_limit (F : J ⥤ C) := (cone : cone F) (is_limit : is_limit cone) variables (J C) /-- `C` has limits of shape `J` if we have chosen a particular limit of every functor `F : J ⥤ C`. -/ @[class] def has_limits_of_shape := Π F : J ⥤ C, has_limit F /-- `C` has all (small) limits if it has limits of every shape. -/ @[class] def has_limits := Π {J : Type v} {𝒥 : small_category J}, by exactI has_limits_of_shape J C variables {J C} instance has_limit_of_has_limits_of_shape {J : Type v} [small_category J] [H : has_limits_of_shape J C] (F : J ⥤ C) : has_limit F := H F instance has_limits_of_shape_of_has_limits {J : Type v} [small_category J] [H : has_limits.{u v} C] : has_limits_of_shape J C := H /- Interface to the `has_limit` class. -/ def limit.cone (F : J ⥤ C) [has_limit F] : cone F := has_limit.cone F def limit (F : J ⥤ C) [has_limit F] := (limit.cone F).X def limit.π (F : J ⥤ C) [has_limit F] (j : J) : limit F ⟶ F.obj j := (limit.cone F).π.app j @[simp] lemma limit.cone_π {F : J ⥤ C} [has_limit F] (j : J) : (limit.cone F).π.app j = limit.π _ j := rfl @[simp] lemma limit.w (F : J ⥤ C) [has_limit F] {j j' : J} (f : j ⟶ j') : limit.π F j ≫ F.map f = limit.π F j' := (limit.cone F).w f def limit.is_limit (F : J ⥤ C) [has_limit F] : is_limit (limit.cone F) := has_limit.is_limit.{u v} F def limit.lift (F : J ⥤ C) [has_limit F] (c : cone F) : c.X ⟶ limit F := (limit.is_limit F).lift c @[simp] lemma limit.is_limit_lift {F : J ⥤ C} [has_limit F] (c : cone F) : (limit.is_limit F).lift c = limit.lift F c := rfl @[simp] lemma limit.lift_π {F : J ⥤ C} [has_limit F] (c : cone F) (j : J) : limit.lift F c ≫ limit.π F j = c.π.app j := is_limit.fac _ c j def limit.cone_morphism {F : J ⥤ C} [has_limit F] (c : cone F) : cone_morphism c (limit.cone F) := (limit.is_limit F).lift_cone_morphism c @[simp] lemma limit.cone_morphism_hom {F : J ⥤ C} [has_limit F] (c : cone F) : (limit.cone_morphism c).hom = limit.lift F c := rfl @[simp] lemma limit.cone_morphism_π {F : J ⥤ C} [has_limit F] (c : cone F) (j : J) : (limit.cone_morphism c).hom ≫ limit.π F j = c.π.app j := by erw is_limit.fac @[extensionality] lemma limit.hom_ext {F : J ⥤ C} [has_limit F] {X : C} {f f' : X ⟶ limit F} (w : ∀ j, f ≫ limit.π F j = f' ≫ limit.π F j) : f = f' := (limit.is_limit F).hom_ext w def limit.hom_iso (F : J ⥤ C) [has_limit F] (W : C) : (W ⟶ limit F) ≅ (F.cones.obj W) := (limit.is_limit F).hom_iso W @[simp] lemma limit.hom_iso_hom (F : J ⥤ C) [has_limit F] {W : C} (f : W ⟶ limit F): (limit.hom_iso F W).hom f = (const J).map f ≫ (limit.cone F).π := (limit.is_limit F).hom_iso_hom f def limit.hom_iso' (F : J ⥤ C) [has_limit F] (W : C) : (W ⟶ limit F) ≅ { p : Π j, W ⟶ F.obj j // ∀ {j j' : J} (f : j ⟶ j'), p j ≫ F.map f = p j' } := (limit.is_limit F).hom_iso' W section pre variables {K : Type v} [small_category K] variables (F) [has_limit F] (E : K ⥤ J) [has_limit (E ⋙ F)] def limit.pre : limit F ⟶ limit (E ⋙ F) := limit.lift (E ⋙ F) { X := limit F, π := { app := λ k, limit.π F (E.obj k) } } @[simp] lemma limit.pre_π (k : K) : limit.pre F E ≫ limit.π (E ⋙ F) k = limit.π F (E.obj k) := by erw is_limit.fac @[simp] lemma limit.lift_pre (c : cone F) : limit.lift F c ≫ limit.pre F E = limit.lift (E ⋙ F) (c.whisker E) := by ext; simp variables {L : Type v} [small_category L] variables (D : L ⥤ K) [has_limit (D ⋙ E ⋙ F)] @[simp] lemma limit.pre_pre : limit.pre F E ≫ limit.pre (E ⋙ F) D = limit.pre F (D ⋙ E) := by ext j; erw [assoc, limit.pre_π, limit.pre_π, limit.pre_π]; refl end pre section post variables {D : Type u'} [𝒟 : category.{u' v} D] include 𝒟 variables (F) [has_limit F] (G : C ⥤ D) [has_limit (F ⋙ G)] def limit.post : G.obj (limit F) ⟶ limit (F ⋙ G) := limit.lift (F ⋙ G) { X := G.obj (limit F), π := { app := λ j, G.map (limit.π F j), naturality' := by intros j j' f; erw [←G.map_comp, limits.cone.w, id_comp]; refl } } @[simp] lemma limit.post_π (j : J) : limit.post F G ≫ limit.π (F ⋙ G) j = G.map (limit.π F j) := by erw is_limit.fac @[simp] lemma limit.lift_post (c : cone F) : G.map (limit.lift F c) ≫ limit.post F G = limit.lift (F ⋙ G) (G.map_cone c) := by ext; rw [assoc, limit.post_π, ←G.map_comp, limit.lift_π, limit.lift_π]; refl @[simp] lemma limit.post_post {E : Type u''} [category.{u'' v} E] (H : D ⥤ E) [has_limit ((F ⋙ G) ⋙ H)] : /- H G (limit F) ⟶ H (limit (F ⋙ G)) ⟶ limit ((F ⋙ G) ⋙ H) equals -/ /- H G (limit F) ⟶ limit (F ⋙ (G ⋙ H)) -/ H.map (limit.post F G) ≫ limit.post (F ⋙ G) H = limit.post F (G ⋙ H) := by ext; erw [assoc, limit.post_π, ←H.map_comp, limit.post_π, limit.post_π]; refl end post lemma limit.pre_post {K : Type v} [small_category K] {D : Type u'} [category.{u' v} D] (E : K ⥤ J) (F : J ⥤ C) (G : C ⥤ D) [has_limit F] [has_limit (E ⋙ F)] [has_limit (F ⋙ G)] [has_limit ((E ⋙ F) ⋙ G)] : /- G (limit F) ⟶ G (limit (E ⋙ F)) ⟶ limit ((E ⋙ F) ⋙ G) vs -/ /- G (limit F) ⟶ limit F ⋙ G ⟶ limit (E ⋙ (F ⋙ G)) or -/ G.map (limit.pre F E) ≫ limit.post (E ⋙ F) G = limit.post F G ≫ limit.pre (F ⋙ G) E := by ext; erw [assoc, limit.post_π, ←G.map_comp, limit.pre_π, assoc, limit.pre_π, limit.post_π]; refl section lim_functor variables [has_limits_of_shape J C] /-- `limit F` is functorial in `F`, when `C` has all limits of shape `J`. -/ def lim : (J ⥤ C) ⥤ C := { obj := λ F, limit F, map := λ F G α, limit.lift G { X := limit F, π := { app := λ j, limit.π F j ≫ α.app j, naturality' := λ j j' f, by erw [id_comp, assoc, ←α.naturality, ←assoc, limit.w] } }, map_comp' := λ F G H α β, by ext; erw [assoc, is_limit.fac, is_limit.fac, ←assoc, is_limit.fac, assoc]; refl } variables {F} {G : J ⥤ C} (α : F ⟹ G) @[simp] lemma lim.map_π (j : J) : lim.map α ≫ limit.π G j = limit.π F j ≫ α.app j := by apply is_limit.fac @[simp] lemma limit.lift_map (c : cone F) : limit.lift F c ≫ lim.map α = limit.lift G (c.postcompose α) := by ext; rw [assoc, lim.map_π, ←assoc, limit.lift_π, limit.lift_π]; refl lemma limit.map_pre {K : Type v} [small_category K] [has_limits_of_shape K C] (E : K ⥤ J) : lim.map α ≫ limit.pre G E = limit.pre F E ≫ lim.map (whisker_left E α) := by ext; rw [assoc, limit.pre_π, lim.map_π, assoc, lim.map_π, ←assoc, limit.pre_π]; refl lemma limit.map_post {D : Type u'} [category.{u' v} D] [has_limits_of_shape J D] (H : C ⥤ D) : /- H (limit F) ⟶ H (limit G) ⟶ limit (G ⋙ H) vs H (limit F) ⟶ limit (F ⋙ H) ⟶ limit (G ⋙ H) -/ H.map (lim.map α) ≫ limit.post G H = limit.post F H ≫ lim.map (whisker_right α H) := begin ext, rw [assoc, limit.post_π, ←H.map_comp, lim.map_π, H.map_comp], rw [assoc, lim.map_π, ←assoc, limit.post_π], refl end end lim_functor end limit section colimit /-- `has_colimit F` represents a particular chosen colimit of the diagram `F`. -/ class has_colimit (F : J ⥤ C) := (cocone : cocone F) (is_colimit : is_colimit cocone) variables (J C) /-- `C` has colimits of shape `J` if we have chosen a particular colimit of every functor `F : J ⥤ C`. -/ @[class] def has_colimits_of_shape := Π F : J ⥤ C, has_colimit F /-- `C` has all (small) colimits if it has limits of every shape. -/ @[class] def has_colimits := Π {J : Type v} {𝒥 : small_category J}, by exactI has_colimits_of_shape J C variables {J C} instance has_colimit_of_has_colimits_of_shape {J : Type v} [small_category J] [H : has_colimits_of_shape J C] (F : J ⥤ C) : has_colimit F := H F instance has_colimits_of_shape_of_has_colimits {J : Type v} [small_category J] [H : has_colimits.{u v} C] : has_colimits_of_shape J C := H /- Interface to the `has_colimit` class. -/ def colimit.cocone (F : J ⥤ C) [has_colimit F] : cocone F := has_colimit.cocone F def colimit (F : J ⥤ C) [has_colimit F] := (colimit.cocone F).X def colimit.ι (F : J ⥤ C) [has_colimit F] (j : J) : F.obj j ⟶ colimit F := (colimit.cocone F).ι.app j @[simp] lemma colimit.cocone_ι {F : J ⥤ C} [has_colimit F] (j : J) : (colimit.cocone F).ι.app j = colimit.ι _ j := rfl @[simp] lemma colimit.w (F : J ⥤ C) [has_colimit F] {j j' : J} (f : j ⟶ j') : F.map f ≫ colimit.ι F j' = colimit.ι F j := (colimit.cocone F).w f def colimit.is_colimit (F : J ⥤ C) [has_colimit F] : is_colimit (colimit.cocone F) := has_colimit.is_colimit.{u v} F def colimit.desc (F : J ⥤ C) [has_colimit F] (c : cocone F) : colimit F ⟶ c.X := (colimit.is_colimit F).desc c @[simp] lemma colimit.is_colimit_desc {F : J ⥤ C} [has_colimit F] (c : cocone F) : (colimit.is_colimit F).desc c = colimit.desc F c := rfl @[simp] lemma colimit.ι_desc {F : J ⥤ C} [has_colimit F] (c : cocone F) (j : J) : colimit.ι F j ≫ colimit.desc F c = c.ι.app j := is_colimit.fac _ c j def colimit.cocone_morphism {F : J ⥤ C} [has_colimit F] (c : cocone F) : cocone_morphism (colimit.cocone F) c := (colimit.is_colimit F).desc_cocone_morphism c @[simp] lemma colimit.cocone_morphism_hom {F : J ⥤ C} [has_colimit F] (c : cocone F) : (colimit.cocone_morphism c).hom = colimit.desc F c := rfl @[simp] lemma colimit.ι_cocone_morphism {F : J ⥤ C} [has_colimit F] (c : cocone F) (j : J) : colimit.ι F j ≫ (colimit.cocone_morphism c).hom = c.ι.app j := by erw is_colimit.fac @[extensionality] lemma colimit.hom_ext {F : J ⥤ C} [has_colimit F] {X : C} {f f' : colimit F ⟶ X} (w : ∀ j, colimit.ι F j ≫ f = colimit.ι F j ≫ f') : f = f' := (colimit.is_colimit F).hom_ext w def colimit.hom_iso (F : J ⥤ C) [has_colimit F] (W : C) : (colimit F ⟶ W) ≅ (F.cocones.obj W) := (colimit.is_colimit F).hom_iso W @[simp] lemma colimit.hom_iso_hom (F : J ⥤ C) [has_colimit F] {W : C} (f : colimit F ⟶ W): (colimit.hom_iso F W).hom f = (colimit.cocone F).ι ≫ (const J).map f := (colimit.is_colimit F).hom_iso_hom f def colimit.hom_iso' (F : J ⥤ C) [has_colimit F] (W : C) : (colimit F ⟶ W) ≅ { p : Π j, F.obj j ⟶ W // ∀ {j j'} (f : j ⟶ j'), F.map f ≫ p j' = p j } := (colimit.is_colimit F).hom_iso' W section pre variables {K : Type v} [small_category K] variables (F) [has_colimit F] (E : K ⥤ J) [has_colimit (E ⋙ F)] def colimit.pre : colimit (E ⋙ F) ⟶ colimit F := colimit.desc (E ⋙ F) { X := colimit F, ι := { app := λ k, colimit.ι F (E.obj k) } } @[simp] lemma colimit.ι_pre (k : K) : colimit.ι (E ⋙ F) k ≫ colimit.pre F E = colimit.ι F (E.obj k) := by erw is_colimit.fac @[simp] lemma colimit.pre_desc (c : cocone F) : colimit.pre F E ≫ colimit.desc F c = colimit.desc (E ⋙ F) (c.whisker E) := by ext; rw [←assoc, colimit.ι_pre]; simp variables {L : Type v} [small_category L] variables (D : L ⥤ K) [has_colimit (D ⋙ E ⋙ F)] @[simp] lemma colimit.pre_pre : colimit.pre (E ⋙ F) D ≫ colimit.pre F E = colimit.pre F (D ⋙ E) := begin ext j, erw [←assoc, colimit.ι_pre, colimit.ι_pre], -- Why doesn't another erw [colimit.ι_pre] work here, like it did in limit.pre_pre? letI : has_colimit ((D ⋙ E) ⋙ F) := show has_colimit (D ⋙ E ⋙ F), by apply_instance, exact (colimit.ι_pre F (D ⋙ E) j).symm end end pre section post variables {D : Type u'} [𝒟 : category.{u' v} D] include 𝒟 variables (F) [has_colimit F] (G : C ⥤ D) [has_colimit (F ⋙ G)] def colimit.post : colimit (F ⋙ G) ⟶ G.obj (colimit F) := colimit.desc (F ⋙ G) { X := G.obj (colimit F), ι := { app := λ j, G.map (colimit.ι F j), naturality' := by intros j j' f; erw [←G.map_comp, limits.cocone.w, comp_id]; refl } } @[simp] lemma colimit.ι_post (j : J) : colimit.ι (F ⋙ G) j ≫ colimit.post F G = G.map (colimit.ι F j) := by erw is_colimit.fac @[simp] lemma colimit.post_desc (c : cocone F) : colimit.post F G ≫ G.map (colimit.desc F c) = colimit.desc (F ⋙ G) (G.map_cocone c) := by ext; rw [←assoc, colimit.ι_post, ←G.map_comp, colimit.ι_desc, colimit.ι_desc]; refl @[simp] lemma colimit.post_post {E : Type u''} [category.{u'' v} E] (H : D ⥤ E) [has_colimit ((F ⋙ G) ⋙ H)] : /- H G (colimit F) ⟶ H (colimit (F ⋙ G)) ⟶ colimit ((F ⋙ G) ⋙ H) equals -/ /- H G (colimit F) ⟶ colimit (F ⋙ (G ⋙ H)) -/ colimit.post (F ⋙ G) H ≫ H.map (colimit.post F G) = colimit.post F (G ⋙ H) := begin ext, erw [←assoc, colimit.ι_post, ←H.map_comp, colimit.ι_post], exact (colimit.ι_post F (G ⋙ H) j).symm end end post lemma colimit.pre_post {K : Type v} [small_category K] {D : Type u'} [category.{u' v} D] (E : K ⥤ J) (F : J ⥤ C) (G : C ⥤ D) [has_colimit F] [has_colimit (E ⋙ F)] [has_colimit (F ⋙ G)] [has_colimit ((E ⋙ F) ⋙ G)] : /- G (colimit F) ⟶ G (colimit (E ⋙ F)) ⟶ colimit ((E ⋙ F) ⋙ G) vs -/ /- G (colimit F) ⟶ colimit F ⋙ G ⟶ colimit (E ⋙ (F ⋙ G)) or -/ colimit.post (E ⋙ F) G ≫ G.map (colimit.pre F E) = colimit.pre (F ⋙ G) E ≫ colimit.post F G := begin ext, erw [←assoc, colimit.ι_post, ←G.map_comp, colimit.ι_pre, ←assoc], letI : has_colimit (E ⋙ F ⋙ G) := show has_colimit ((E ⋙ F) ⋙ G), by apply_instance, erw [colimit.ι_pre (F ⋙ G) E j, colimit.ι_post] end section colim_functor variables [has_colimits_of_shape J C] /-- `colimit F` is functorial in `F`, when `C` has all colimits of shape `J`. -/ def colim : (J ⥤ C) ⥤ C := { obj := λ F, colimit F, map := λ F G α, colimit.desc F { X := colimit G, ι := { app := λ j, α.app j ≫ colimit.ι G j, naturality' := λ j j' f, by erw [comp_id, ←assoc, α.naturality, assoc, colimit.w] } }, map_comp' := λ F G H α β, by ext; erw [←assoc, is_colimit.fac, is_colimit.fac, assoc, is_colimit.fac, ←assoc]; refl } variables {F} {G : J ⥤ C} (α : F ⟹ G) @[simp] lemma colim.ι_map (j : J) : colimit.ι F j ≫ colim.map α = α.app j ≫ colimit.ι G j := by apply is_colimit.fac @[simp] lemma colimit.map_desc (c : cocone G) : colim.map α ≫ colimit.desc G c = colimit.desc F (c.precompose α) := by ext; rw [←assoc, colim.ι_map, assoc, colimit.ι_desc, colimit.ι_desc]; refl lemma colimit.pre_map {K : Type v} [small_category K] [has_colimits_of_shape K C] (E : K ⥤ J) : colimit.pre F E ≫ colim.map α = colim.map (whisker_left E α) ≫ colimit.pre G E := by ext; rw [←assoc, colimit.ι_pre, colim.ι_map, ←assoc, colim.ι_map, assoc, colimit.ι_pre]; refl lemma colimit.map_post {D : Type u'} [category.{u' v} D] [has_colimits_of_shape J D] (H : C ⥤ D) : /- H (colimit F) ⟶ H (colimit G) ⟶ colimit (G ⋙ H) vs H (colimit F) ⟶ colimit (F ⋙ H) ⟶ colimit (G ⋙ H) -/ colimit.post F H ≫ H.map (colim.map α) = colim.map (whisker_right α H) ≫ colimit.post G H:= begin ext, rw [←assoc, colimit.ι_post, ←H.map_comp, colim.ι_map, H.map_comp], rw [←assoc, colim.ι_map, assoc, colimit.ι_post], refl end end colim_functor end colimit end category_theory.limits
615425c549053613961edb8a1d763625db99bd8e
9060db28f6353f040da7481ea5ebcdac426589ff
/meta_data.lean
8d8e54faf02e3bfc3602141d99cb4c0e48dd1adb
[]
no_license
picrin/formalabstracts
9ccd859fb34a9194fa5ded77ab1bc734ababe194
8ebd529598cfc8b6bd02530dd21b7bf3156de174
refs/heads/master
1,609,476,202,073
1,500,070,922,000
1,500,070,922,000
97,234,461
0
0
null
1,500,037,389,000
1,500,037,389,000
null
UTF-8
Lean
false
false
656
lean
-- The type of results inductive {u} result : Type (u+1) | Proof : Π {P : Prop}, P → result | Construction : Π {A : Type u}, A → result | Conjecture : Prop → result /- TODO: This definition forces all the results in a particular fabstract to lie in the same universe. -/ -- Each formal abstract contains an instance of the meta_data structure, -- describing the contents. structure {u} meta_data : Type (u+1) := (description : string) -- short description of the contents (authors : list string) -- list of authors (doi : list string) -- references to the original article (results : list (result.{u})) -- the list of main results
edd6b43f5dc46565a0bb52835fbb5362a1e77a5a
07c76fbd96ea1786cc6392fa834be62643cea420
/tests/lean/hott/614.hlean
0e5d8451bb94f021b222ebe811fbb97502637a50
[ "Apache-2.0" ]
permissive
fpvandoorn/lean2
5a430a153b570bf70dc8526d06f18fc000a60ad9
0889cf65b7b3cebfb8831b8731d89c2453dd1e9f
refs/heads/master
1,592,036,508,364
1,545,093,958,000
1,545,093,958,000
75,436,854
0
0
null
1,480,718,780,000
1,480,718,780,000
null
UTF-8
Lean
false
false
593
hlean
import homotopy.circle open circle eq int pi attribute circle.rec [recursor] protected definition my_decode {x : circle} (c : circle.code x) : base = x := begin induction x, { revert c, exact power loop }, { apply arrow_pathover_left, intro b, apply concato_eq, apply eq_pathover_r, rewrite [power_con,transport_code_loop]}, end protected definition my_decode' {x : circle} : circle.code x → base = x := begin induction x, { exact power loop}, { apply arrow_pathover_left, intro b, apply concato_eq, apply eq_pathover_r, rewrite [power_con,transport_code_loop]}, end
10e1a67122ceb2c0ad28839b1f95c01e1727cbd5
77c5b91fae1b966ddd1db969ba37b6f0e4901e88
/src/algebra/algebra/basic.lean
bcbf30428a8b059a64b6c7421770bf9aa4c7789a
[ "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
53,083
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Yury Kudryashov -/ import algebra.iterate_hom import data.equiv.ring_aut import algebra.module.basic import linear_algebra.basic /-! # Algebras over commutative semirings In this file we define `algebra`s over commutative (semi)rings, algebra homomorphisms `alg_hom`, and algebra equivalences `alg_equiv`. We also define the usual operations on `alg_hom`s (`id`, `comp`). `subalgebra`s are defined in `algebra.algebra.subalgebra`. If `S` is an `R`-algebra and `A` is an `S`-algebra then `algebra.comap.algebra R S A` can be used to provide `A` with a structure of an `R`-algebra. Other than that, `algebra.comap` is now deprecated and replaced with `is_scalar_tower`. For the category of `R`-algebras, denoted `Algebra R`, see the file `algebra/category/Algebra/basic.lean`. ## Notations * `A →ₐ[R] B` : `R`-algebra homomorphism from `A` to `B`. * `A ≃ₐ[R] B` : `R`-algebra equivalence from `A` to `B`. -/ universes u v w u₁ v₁ open_locale big_operators section prio -- We set this priority to 0 later in this file set_option extends_priority 200 /- control priority of `instance [algebra R A] : has_scalar R A` -/ /-- Given a commutative (semi)ring `R`, an `R`-algebra is a (possibly noncommutative) (semi)ring `A` endowed with a morphism of rings `R →+* A` which lands in the center of `A`. For convenience, this typeclass extends `has_scalar R A` where the scalar action must agree with left multiplication by the image of the structure morphism. Given an `algebra R A` instance, the structure morphism `R →+* A` is denoted `algebra_map R A`. -/ @[nolint has_inhabited_instance] class algebra (R : Type u) (A : Type v) [comm_semiring R] [semiring A] extends has_scalar R A, R →+* A := (commutes' : ∀ r x, to_fun r * x = x * to_fun r) (smul_def' : ∀ r x, r • x = to_fun r * x) end prio /-- Embedding `R →+* A` given by `algebra` structure. -/ def algebra_map (R : Type u) (A : Type v) [comm_semiring R] [semiring A] [algebra R A] : R →+* A := algebra.to_ring_hom /-- Creating an algebra from a morphism to the center of a semiring. -/ def ring_hom.to_algebra' {R S} [comm_semiring R] [semiring S] (i : R →+* S) (h : ∀ c x, i c * x = x * i c) : algebra R S := { smul := λ c x, i c * x, commutes' := h, smul_def' := λ c x, rfl, to_ring_hom := i} /-- Creating an algebra from a morphism to a commutative semiring. -/ def ring_hom.to_algebra {R S} [comm_semiring R] [comm_semiring S] (i : R →+* S) : algebra R S := i.to_algebra' $ λ _, mul_comm _ lemma ring_hom.algebra_map_to_algebra {R S} [comm_semiring R] [comm_semiring S] (i : R →+* S) : @algebra_map R S _ _ i.to_algebra = i := rfl namespace algebra variables {R : Type u} {S : Type v} {A : Type w} {B : Type*} /-- Let `R` be a commutative semiring, let `A` be a semiring with a `module R` structure. If `(r • 1) * x = x * (r • 1) = r • x` for all `r : R` and `x : A`, then `A` is an `algebra` over `R`. See note [reducible non-instances]. -/ @[reducible] def of_module' [comm_semiring R] [semiring A] [module R A] (h₁ : ∀ (r : R) (x : A), (r • 1) * x = r • x) (h₂ : ∀ (r : R) (x : A), x * (r • 1) = r • x) : algebra R A := { to_fun := λ r, r • 1, map_one' := one_smul _ _, map_mul' := λ r₁ r₂, by rw [h₁, mul_smul], map_zero' := zero_smul _ _, map_add' := λ r₁ r₂, add_smul r₁ r₂ 1, commutes' := λ r x, by simp only [h₁, h₂], smul_def' := λ r x, by simp only [h₁] } /-- Let `R` be a commutative semiring, let `A` be a semiring with a `module R` structure. If `(r • x) * y = x * (r • y) = r • (x * y)` for all `r : R` and `x y : A`, then `A` is an `algebra` over `R`. See note [reducible non-instances]. -/ @[reducible] def of_module [comm_semiring R] [semiring A] [module R A] (h₁ : ∀ (r : R) (x y : A), (r • x) * y = r • (x * y)) (h₂ : ∀ (r : R) (x y : A), x * (r • y) = r • (x * y)) : algebra R A := of_module' (λ r x, by rw [h₁, one_mul]) (λ r x, by rw [h₂, mul_one]) section semiring variables [comm_semiring R] [comm_semiring S] variables [semiring A] [algebra R A] [semiring B] [algebra R B] lemma smul_def'' (r : R) (x : A) : r • x = algebra_map R A r * x := algebra.smul_def' r x /-- To prove two algebra structures on a fixed `[comm_semiring R] [semiring A]` agree, it suffices to check the `algebra_map`s agree. -/ -- We'll later use this to show `algebra ℤ M` is a subsingleton. @[ext] lemma algebra_ext {R : Type*} [comm_semiring R] {A : Type*} [semiring A] (P Q : algebra R A) (w : ∀ (r : R), by { haveI := P, exact algebra_map R A r } = by { haveI := Q, exact algebra_map R A r }) : P = Q := begin unfreezingI { rcases P with ⟨⟨P⟩⟩, rcases Q with ⟨⟨Q⟩⟩ }, congr, { funext r a, replace w := congr_arg (λ s, s * a) (w r), simp only [←algebra.smul_def''] at w, apply w, }, { ext r, exact w r, }, { apply proof_irrel_heq, }, { apply proof_irrel_heq, }, end @[priority 200] -- see Note [lower instance priority] instance to_module : module R A := { one_smul := by simp [smul_def''], mul_smul := by simp [smul_def'', mul_assoc], smul_add := by simp [smul_def'', mul_add], smul_zero := by simp [smul_def''], add_smul := by simp [smul_def'', add_mul], zero_smul := by simp [smul_def''] } -- from now on, we don't want to use the following instance anymore attribute [instance, priority 0] algebra.to_has_scalar lemma smul_def (r : R) (x : A) : r • x = algebra_map R A r * x := algebra.smul_def' r x lemma algebra_map_eq_smul_one (r : R) : algebra_map R A r = r • 1 := calc algebra_map R A r = algebra_map R A r * 1 : (mul_one _).symm ... = r • 1 : (algebra.smul_def r 1).symm lemma algebra_map_eq_smul_one' : ⇑(algebra_map R A) = λ r, r • (1 : A) := funext algebra_map_eq_smul_one /-- `mul_comm` for `algebra`s when one element is from the base ring. -/ theorem commutes (r : R) (x : A) : algebra_map R A r * x = x * algebra_map R A r := algebra.commutes' r x /-- `mul_left_comm` for `algebra`s when one element is from the base ring. -/ theorem left_comm (x : A) (r : R) (y : A) : x * (algebra_map R A r * y) = algebra_map R A r * (x * y) := by rw [← mul_assoc, ← commutes, mul_assoc] /-- `mul_right_comm` for `algebra`s when one element is from the base ring. -/ theorem right_comm (x : A) (r : R) (y : A) : (x * algebra_map R A r) * y = (x * y) * algebra_map R A r := by rw [mul_assoc, commutes, ←mul_assoc] instance _root_.is_scalar_tower.right : is_scalar_tower R A A := ⟨λ x y z, by rw [smul_eq_mul, smul_eq_mul, smul_def, smul_def, mul_assoc]⟩ /-- This is just a special case of the global `mul_smul_comm` lemma that requires less typeclass search (and was here first). -/ @[simp] protected lemma mul_smul_comm (s : R) (x y : A) : x * (s • y) = s • (x * y) := -- TODO: set up `is_scalar_tower.smul_comm_class` earlier so that we can actually prove this using -- `mul_smul_comm s x y`. by rw [smul_def, smul_def, left_comm] /-- This is just a special case of the global `smul_mul_assoc` lemma that requires less typeclass search (and was here first). -/ @[simp] protected lemma smul_mul_assoc (r : R) (x y : A) : (r • x) * y = r • (x * y) := smul_mul_assoc r x y instance _root_.is_scalar_tower.opposite_right : is_scalar_tower R Aᵒᵖ A := ⟨λ x y z, algebra.mul_smul_comm _ _ _⟩ section variables {r : R} {a : A} @[simp] lemma bit0_smul_one : bit0 r • (1 : A) = bit0 (r • (1 : A)) := by simp [bit0, add_smul] lemma bit0_smul_one' : bit0 r • (1 : A) = r • 2 := by simp [bit0, add_smul, smul_add] @[simp] lemma bit0_smul_bit0 : bit0 r • bit0 a = r • (bit0 (bit0 a)) := by simp [bit0, add_smul, smul_add] @[simp] lemma bit0_smul_bit1 : bit0 r • bit1 a = r • (bit0 (bit1 a)) := by simp [bit0, add_smul, smul_add] @[simp] lemma bit1_smul_one : bit1 r • (1 : A) = bit1 (r • (1 : A)) := by simp [bit1, add_smul] lemma bit1_smul_one' : bit1 r • (1 : A) = r • 2 + 1 := by simp [bit1, bit0, add_smul, smul_add] @[simp] lemma bit1_smul_bit0 : bit1 r • bit0 a = r • (bit0 (bit0 a)) + bit0 a := by simp [bit1, add_smul, smul_add] @[simp] lemma bit1_smul_bit1 : bit1 r • bit1 a = r • (bit0 (bit1 a)) + bit1 a := by { simp only [bit0, bit1, add_smul, smul_add, one_smul], abel } end variables (R A) /-- The canonical ring homomorphism `algebra_map R A : R →* A` for any `R`-algebra `A`, packaged as an `R`-linear map. -/ protected def linear_map : R →ₗ[R] A := { map_smul' := λ x y, by simp [algebra.smul_def], ..algebra_map R A } @[simp] lemma linear_map_apply (r : R) : algebra.linear_map R A r = algebra_map R A r := rfl instance id : algebra R R := (ring_hom.id R).to_algebra variables {R A} namespace id @[simp] lemma map_eq_id : algebra_map R R = ring_hom.id _ := rfl lemma map_eq_self (x : R) : algebra_map R R x = x := rfl @[simp] lemma smul_eq_mul (x y : R) : x • y = x * y := rfl end id section prod variables (R A B) instance : algebra R (A × B) := { commutes' := by { rintro r ⟨a, b⟩, dsimp, rw [commutes r a, commutes r b] }, smul_def' := by { rintro r ⟨a, b⟩, dsimp, rw [smul_def r a, smul_def r b] }, .. prod.module, .. ring_hom.prod (algebra_map R A) (algebra_map R B) } variables {R A B} @[simp] lemma algebra_map_prod_apply (r : R) : algebra_map R (A × B) r = (algebra_map R A r, algebra_map R B r) := rfl end prod /-- Algebra over a subsemiring. This builds upon `subsemiring.module`. -/ instance of_subsemiring (S : subsemiring R) : algebra S A := { smul := (•), commutes' := λ r x, algebra.commutes r x, smul_def' := λ r x, algebra.smul_def r x, .. (algebra_map R A).comp S.subtype } /-- Algebra over a subring. This builds upon `subring.module`. -/ instance of_subring {R A : Type*} [comm_ring R] [ring A] [algebra R A] (S : subring R) : algebra S A := { smul := (•), .. algebra.of_subsemiring S.to_subsemiring, .. (algebra_map R A).comp S.subtype } lemma algebra_map_of_subring {R : Type*} [comm_ring R] (S : subring R) : (algebra_map S R : S →+* R) = subring.subtype S := rfl lemma coe_algebra_map_of_subring {R : Type*} [comm_ring R] (S : subring R) : (algebra_map S R : S → R) = subtype.val := rfl lemma algebra_map_of_subring_apply {R : Type*} [comm_ring R] (S : subring R) (x : S) : algebra_map S R x = x := rfl /-- Explicit characterization of the submonoid map in the case of an algebra. `S` is made explicit to help with type inference -/ def algebra_map_submonoid (S : Type*) [semiring S] [algebra R S] (M : submonoid R) : (submonoid S) := submonoid.map (algebra_map R S : R →* S) M lemma mem_algebra_map_submonoid_of_mem [algebra R S] {M : submonoid R} (x : M) : (algebra_map R S x) ∈ algebra_map_submonoid S M := set.mem_image_of_mem (algebra_map R S) x.2 end semiring section ring variables [comm_ring R] variables (R) /-- A `semiring` that is an `algebra` over a commutative ring carries a natural `ring` structure. See note [reducible non-instances]. -/ @[reducible] def semiring_to_ring [semiring A] [algebra R A] : ring A := { ..module.add_comm_monoid_to_add_comm_group R, ..(infer_instance : semiring A) } variables {R} lemma mul_sub_algebra_map_commutes [ring A] [algebra R A] (x : A) (r : R) : x * (x - algebra_map R A r) = (x - algebra_map R A r) * x := by rw [mul_sub, ←commutes, sub_mul] lemma mul_sub_algebra_map_pow_commutes [ring A] [algebra R A] (x : A) (r : R) (n : ℕ) : x * (x - algebra_map R A r) ^ n = (x - algebra_map R A r) ^ n * x := begin induction n with n ih, { simp }, { rw [pow_succ, ←mul_assoc, mul_sub_algebra_map_commutes, mul_assoc, ih, ←mul_assoc], } end end ring end algebra namespace no_zero_smul_divisors variables {R A : Type*} open algebra section ring variables [comm_ring R] /-- If `algebra_map R A` is injective and `A` has no zero divisors, `R`-multiples in `A` are zero only if one of the factors is zero. Cannot be an instance because there is no `injective (algebra_map R A)` typeclass. -/ lemma of_algebra_map_injective [semiring A] [algebra R A] [no_zero_divisors A] (h : function.injective (algebra_map R A)) : no_zero_smul_divisors R A := ⟨λ c x hcx, (mul_eq_zero.mp ((smul_def c x).symm.trans hcx)).imp_left ((algebra_map R A).injective_iff.mp h _)⟩ variables (R A) lemma algebra_map_injective [ring A] [nontrivial A] [algebra R A] [no_zero_smul_divisors R A] : function.injective (algebra_map R A) := suffices function.injective (λ (c : R), c • (1 : A)), by { convert this, ext, rw [algebra.smul_def, mul_one] }, smul_left_injective R one_ne_zero variables {R A} lemma iff_algebra_map_injective [domain A] [algebra R A] : no_zero_smul_divisors R A ↔ function.injective (algebra_map R A) := ⟨@@no_zero_smul_divisors.algebra_map_injective R A _ _ _ _, no_zero_smul_divisors.of_algebra_map_injective⟩ end ring section field variables [field R] [semiring A] [algebra R A] @[priority 100] -- see note [lower instance priority] instance algebra.no_zero_smul_divisors [nontrivial A] [no_zero_divisors A] : no_zero_smul_divisors R A := no_zero_smul_divisors.of_algebra_map_injective (algebra_map R A).injective end field end no_zero_smul_divisors namespace opposite variables {R A : Type*} [comm_semiring R] [semiring A] [algebra R A] instance : algebra R Aᵒᵖ := { to_ring_hom := (algebra_map R A).to_opposite $ λ x y, algebra.commutes _ _, smul_def' := λ c x, unop_injective $ by { dsimp, simp only [op_mul, algebra.smul_def, algebra.commutes, op_unop] }, commutes' := λ r, op_induction $ λ x, by dsimp; simp only [← op_mul, algebra.commutes], ..opposite.has_scalar A R } @[simp] lemma algebra_map_apply (c : R) : algebra_map R Aᵒᵖ c = op (algebra_map R A c) := rfl end opposite namespace module variables (R : Type u) (M : Type v) [comm_semiring R] [add_comm_monoid M] [module R M] instance : algebra R (module.End R M) := algebra.of_module smul_mul_assoc (λ r f g, (smul_comm r f g).symm) lemma algebra_map_End_eq_smul_id (a : R) : (algebra_map R (End R M)) a = a • linear_map.id := rfl @[simp] lemma algebra_map_End_apply (a : R) (m : M) : (algebra_map R (End R M)) a m = a • m := rfl @[simp] lemma ker_algebra_map_End (K : Type u) (V : Type v) [field K] [add_comm_group V] [module K V] (a : K) (ha : a ≠ 0) : ((algebra_map K (End K V)) a).ker = ⊥ := linear_map.ker_smul _ _ ha end module set_option old_structure_cmd true /-- Defining the homomorphism in the category R-Alg. -/ @[nolint has_inhabited_instance] structure alg_hom (R : Type u) (A : Type v) (B : Type w) [comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B] extends ring_hom A B := (commutes' : ∀ r : R, to_fun (algebra_map R A r) = algebra_map R B r) run_cmd tactic.add_doc_string `alg_hom.to_ring_hom "Reinterpret an `alg_hom` as a `ring_hom`" infixr ` →ₐ `:25 := alg_hom _ notation A ` →ₐ[`:25 R `] ` B := alg_hom R A B namespace alg_hom variables {R : Type u} {A : Type v} {B : Type w} {C : Type u₁} {D : Type v₁} section semiring variables [comm_semiring R] [semiring A] [semiring B] [semiring C] [semiring D] variables [algebra R A] [algebra R B] [algebra R C] [algebra R D] instance : has_coe_to_fun (A →ₐ[R] B) := ⟨_, λ f, f.to_fun⟩ initialize_simps_projections alg_hom (to_fun → apply) @[simp] lemma to_fun_eq_coe (f : A →ₐ[R] B) : f.to_fun = f := rfl instance coe_ring_hom : has_coe (A →ₐ[R] B) (A →+* B) := ⟨alg_hom.to_ring_hom⟩ instance coe_monoid_hom : has_coe (A →ₐ[R] B) (A →* B) := ⟨λ f, ↑(f : A →+* B)⟩ instance coe_add_monoid_hom : has_coe (A →ₐ[R] B) (A →+ B) := ⟨λ f, ↑(f : A →+* B)⟩ @[simp, norm_cast] lemma coe_mk {f : A → B} (h₁ h₂ h₃ h₄ h₅) : ⇑(⟨f, h₁, h₂, h₃, h₄, h₅⟩ : A →ₐ[R] B) = f := rfl -- make the coercion the simp-normal form @[simp] lemma to_ring_hom_eq_coe (f : A →ₐ[R] B) : f.to_ring_hom = f := rfl @[simp, norm_cast] lemma coe_to_ring_hom (f : A →ₐ[R] B) : ⇑(f : A →+* B) = f := rfl -- as `simp` can already prove this lemma, it is not tagged with the `simp` attribute. @[norm_cast] lemma coe_to_monoid_hom (f : A →ₐ[R] B) : ⇑(f : A →* B) = f := rfl -- as `simp` can already prove this lemma, it is not tagged with the `simp` attribute. @[norm_cast] lemma coe_to_add_monoid_hom (f : A →ₐ[R] B) : ⇑(f : A →+ B) = f := rfl variables (φ : A →ₐ[R] B) theorem coe_fn_injective : @function.injective (A →ₐ[R] B) (A → B) coe_fn := by { intros φ₁ φ₂ H, cases φ₁, cases φ₂, congr, exact H } theorem coe_ring_hom_injective : function.injective (coe : (A →ₐ[R] B) → (A →+* B)) := λ φ₁ φ₂ H, coe_fn_injective $ show ((φ₁ : (A →+* B)) : A → B) = ((φ₂ : (A →+* B)) : A → B), from congr_arg _ H theorem coe_monoid_hom_injective : function.injective (coe : (A →ₐ[R] B) → (A →* B)) := ring_hom.coe_monoid_hom_injective.comp coe_ring_hom_injective theorem coe_add_monoid_hom_injective : function.injective (coe : (A →ₐ[R] B) → (A →+ B)) := ring_hom.coe_add_monoid_hom_injective.comp coe_ring_hom_injective protected lemma congr_fun {φ₁ φ₂ : A →ₐ[R] B} (H : φ₁ = φ₂) (x : A) : φ₁ x = φ₂ x := H ▸ rfl protected lemma congr_arg (φ : A →ₐ[R] B) {x y : A} (h : x = y) : φ x = φ y := h ▸ rfl @[ext] theorem ext {φ₁ φ₂ : A →ₐ[R] B} (H : ∀ x, φ₁ x = φ₂ x) : φ₁ = φ₂ := coe_fn_injective $ funext H theorem ext_iff {φ₁ φ₂ : A →ₐ[R] B} : φ₁ = φ₂ ↔ ∀ x, φ₁ x = φ₂ x := ⟨alg_hom.congr_fun, ext⟩ @[simp] theorem mk_coe {f : A →ₐ[R] B} (h₁ h₂ h₃ h₄ h₅) : (⟨f, h₁, h₂, h₃, h₄, h₅⟩ : A →ₐ[R] B) = f := ext $ λ _, rfl @[simp] theorem commutes (r : R) : φ (algebra_map R A r) = algebra_map R B r := φ.commutes' r theorem comp_algebra_map : (φ : A →+* B).comp (algebra_map R A) = algebra_map R B := ring_hom.ext $ φ.commutes @[simp] lemma map_add (r s : A) : φ (r + s) = φ r + φ s := φ.to_ring_hom.map_add r s @[simp] lemma map_zero : φ 0 = 0 := φ.to_ring_hom.map_zero @[simp] lemma map_mul (x y) : φ (x * y) = φ x * φ y := φ.to_ring_hom.map_mul x y @[simp] lemma map_one : φ 1 = 1 := φ.to_ring_hom.map_one @[simp] lemma map_smul (r : R) (x : A) : φ (r • x) = r • φ x := by simp only [algebra.smul_def, map_mul, commutes] @[simp] lemma map_pow (x : A) (n : ℕ) : φ (x ^ n) = (φ x) ^ n := φ.to_ring_hom.map_pow x n lemma map_sum {ι : Type*} (f : ι → A) (s : finset ι) : φ (∑ x in s, f x) = ∑ x in s, φ (f x) := φ.to_ring_hom.map_sum f s lemma map_finsupp_sum {α : Type*} [has_zero α] {ι : Type*} (f : ι →₀ α) (g : ι → α → A) : φ (f.sum g) = f.sum (λ i a, φ (g i a)) := φ.map_sum _ _ @[simp] lemma map_nat_cast (n : ℕ) : φ n = n := φ.to_ring_hom.map_nat_cast n @[simp] lemma map_bit0 (x) : φ (bit0 x) = bit0 (φ x) := φ.to_ring_hom.map_bit0 x @[simp] lemma map_bit1 (x) : φ (bit1 x) = bit1 (φ x) := φ.to_ring_hom.map_bit1 x /-- If a `ring_hom` is `R`-linear, then it is an `alg_hom`. -/ def mk' (f : A →+* B) (h : ∀ (c : R) x, f (c • x) = c • f x) : A →ₐ[R] B := { to_fun := f, commutes' := λ c, by simp only [algebra.algebra_map_eq_smul_one, h, f.map_one], .. f } @[simp] lemma coe_mk' (f : A →+* B) (h : ∀ (c : R) x, f (c • x) = c • f x) : ⇑(mk' f h) = f := rfl section variables (R A) /-- Identity map as an `alg_hom`. -/ protected def id : A →ₐ[R] A := { commutes' := λ _, rfl, ..ring_hom.id A } @[simp] lemma coe_id : ⇑(alg_hom.id R A) = id := rfl @[simp] lemma id_to_ring_hom : (alg_hom.id R A : A →+* A) = ring_hom.id _ := rfl end lemma id_apply (p : A) : alg_hom.id R A p = p := rfl /-- Composition of algebra homeomorphisms. -/ def comp (φ₁ : B →ₐ[R] C) (φ₂ : A →ₐ[R] B) : A →ₐ[R] C := { commutes' := λ r : R, by rw [← φ₁.commutes, ← φ₂.commutes]; refl, .. φ₁.to_ring_hom.comp ↑φ₂ } @[simp] lemma coe_comp (φ₁ : B →ₐ[R] C) (φ₂ : A →ₐ[R] B) : ⇑(φ₁.comp φ₂) = φ₁ ∘ φ₂ := rfl lemma comp_apply (φ₁ : B →ₐ[R] C) (φ₂ : A →ₐ[R] B) (p : A) : φ₁.comp φ₂ p = φ₁ (φ₂ p) := rfl lemma comp_to_ring_hom (φ₁ : B →ₐ[R] C) (φ₂ : A →ₐ[R] B) : ⇑(φ₁.comp φ₂ : A →+* C) = (φ₁ : B →+* C).comp ↑φ₂ := rfl @[simp] theorem comp_id : φ.comp (alg_hom.id R A) = φ := ext $ λ x, rfl @[simp] theorem id_comp : (alg_hom.id R B).comp φ = φ := ext $ λ x, rfl theorem comp_assoc (φ₁ : C →ₐ[R] D) (φ₂ : B →ₐ[R] C) (φ₃ : A →ₐ[R] B) : (φ₁.comp φ₂).comp φ₃ = φ₁.comp (φ₂.comp φ₃) := ext $ λ x, rfl /-- R-Alg ⥤ R-Mod -/ def to_linear_map : A →ₗ[R] B := { to_fun := φ, map_add' := φ.map_add, map_smul' := φ.map_smul } @[simp] lemma to_linear_map_apply (p : A) : φ.to_linear_map p = φ p := rfl theorem to_linear_map_injective : function.injective (to_linear_map : _ → (A →ₗ[R] B)) := λ φ₁ φ₂ h, ext $ linear_map.congr_fun h @[simp] lemma comp_to_linear_map (f : A →ₐ[R] B) (g : B →ₐ[R] C) : (g.comp f).to_linear_map = g.to_linear_map.comp f.to_linear_map := rfl @[simp] lemma to_linear_map_id : to_linear_map (alg_hom.id R A) = linear_map.id := linear_map.ext $ λ _, rfl /-- Promote a `linear_map` to an `alg_hom` by supplying proofs about the behavior on `1` and `*`. -/ @[simps] def of_linear_map (f : A →ₗ[R] B) (map_one : f 1 = 1) (map_mul : ∀ x y, f (x * y) = f x * f y) : A →ₐ[R] B := { to_fun := f, map_one' := map_one, map_mul' := map_mul, commutes' := λ c, by simp only [algebra.algebra_map_eq_smul_one, f.map_smul, map_one], .. f.to_add_monoid_hom } @[simp] lemma of_linear_map_to_linear_map (map_one) (map_mul) : of_linear_map φ.to_linear_map map_one map_mul = φ := by { ext, refl } @[simp] lemma to_linear_map_of_linear_map (f : A →ₗ[R] B) (map_one) (map_mul) : to_linear_map (of_linear_map f map_one map_mul) = f := by { ext, refl } @[simp] lemma of_linear_map_id (map_one) (map_mul) : of_linear_map linear_map.id map_one map_mul = alg_hom.id R A := ext $ λ _, rfl lemma map_list_prod (s : list A) : φ s.prod = (s.map φ).prod := φ.to_ring_hom.map_list_prod s section prod /-- First projection as `alg_hom`. -/ def fst : A × B →ₐ[R] A := { commutes' := λ r, rfl, .. ring_hom.fst A B} /-- Second projection as `alg_hom`. -/ def snd : A × B →ₐ[R] B := { commutes' := λ r, rfl, .. ring_hom.snd A B} end prod lemma algebra_map_eq_apply (f : A →ₐ[R] B) {y : R} {x : A} (h : algebra_map R A y = x) : algebra_map R B y = f x := h ▸ (f.commutes _).symm end semiring section comm_semiring variables [comm_semiring R] [comm_semiring A] [comm_semiring B] variables [algebra R A] [algebra R B] (φ : A →ₐ[R] B) lemma map_multiset_prod (s : multiset A) : φ s.prod = (s.map φ).prod := φ.to_ring_hom.map_multiset_prod s lemma map_prod {ι : Type*} (f : ι → A) (s : finset ι) : φ (∏ x in s, f x) = ∏ x in s, φ (f x) := φ.to_ring_hom.map_prod f s lemma map_finsupp_prod {α : Type*} [has_zero α] {ι : Type*} (f : ι →₀ α) (g : ι → α → A) : φ (f.prod g) = f.prod (λ i a, φ (g i a)) := φ.map_prod _ _ end comm_semiring section ring variables [comm_semiring R] [ring A] [ring B] variables [algebra R A] [algebra R B] (φ : A →ₐ[R] B) @[simp] lemma map_neg (x) : φ (-x) = -φ x := φ.to_ring_hom.map_neg x @[simp] lemma map_sub (x y) : φ (x - y) = φ x - φ y := φ.to_ring_hom.map_sub x y @[simp] lemma map_int_cast (n : ℤ) : φ n = n := φ.to_ring_hom.map_int_cast n end ring section division_ring variables [comm_ring R] [division_ring A] [division_ring B] variables [algebra R A] [algebra R B] (φ : A →ₐ[R] B) @[simp] lemma map_inv (x) : φ (x⁻¹) = (φ x)⁻¹ := φ.to_ring_hom.map_inv x @[simp] lemma map_div (x y) : φ (x / y) = φ x / φ y := φ.to_ring_hom.map_div x y end division_ring theorem injective_iff {R A B : Type*} [comm_semiring R] [ring A] [semiring B] [algebra R A] [algebra R B] (f : A →ₐ[R] B) : function.injective f ↔ (∀ x, f x = 0 → x = 0) := ring_hom.injective_iff (f : A →+* B) end alg_hom @[simp] lemma rat.smul_one_eq_coe {A : Type*} [division_ring A] [algebra ℚ A] (m : ℚ) : m • (1 : A) = ↑m := by rw [algebra.smul_def, mul_one, ring_hom.eq_rat_cast] set_option old_structure_cmd true /-- An equivalence of algebras is an equivalence of rings commuting with the actions of scalars. -/ structure alg_equiv (R : Type u) (A : Type v) (B : Type w) [comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B] extends A ≃ B, A ≃* B, A ≃+ B, A ≃+* B := (commutes' : ∀ r : R, to_fun (algebra_map R A r) = algebra_map R B r) attribute [nolint doc_blame] alg_equiv.to_ring_equiv attribute [nolint doc_blame] alg_equiv.to_equiv attribute [nolint doc_blame] alg_equiv.to_add_equiv attribute [nolint doc_blame] alg_equiv.to_mul_equiv notation A ` ≃ₐ[`:50 R `] ` A' := alg_equiv R A A' namespace alg_equiv variables {R : Type u} {A₁ : Type v} {A₂ : Type w} {A₃ : Type u₁} section semiring variables [comm_semiring R] [semiring A₁] [semiring A₂] [semiring A₃] variables [algebra R A₁] [algebra R A₂] [algebra R A₃] variables (e : A₁ ≃ₐ[R] A₂) instance : has_coe_to_fun (A₁ ≃ₐ[R] A₂) := ⟨_, alg_equiv.to_fun⟩ @[ext] lemma ext {f g : A₁ ≃ₐ[R] A₂} (h : ∀ a, f a = g a) : f = g := begin have h₁ : f.to_equiv = g.to_equiv := equiv.ext h, cases f, cases g, congr, { exact (funext h) }, { exact congr_arg equiv.inv_fun h₁ } end protected lemma congr_arg {f : A₁ ≃ₐ[R] A₂} : Π {x x' : A₁}, x = x' → f x = f x' | _ _ rfl := rfl protected lemma congr_fun {f g : A₁ ≃ₐ[R] A₂} (h : f = g) (x : A₁) : f x = g x := h ▸ rfl lemma ext_iff {f g : A₁ ≃ₐ[R] A₂} : f = g ↔ ∀ x, f x = g x := ⟨λ h x, h ▸ rfl, ext⟩ lemma coe_fun_injective : @function.injective (A₁ ≃ₐ[R] A₂) (A₁ → A₂) (λ e, (e : A₁ → A₂)) := begin intros f g w, ext, exact congr_fun w a, end instance has_coe_to_ring_equiv : has_coe (A₁ ≃ₐ[R] A₂) (A₁ ≃+* A₂) := ⟨alg_equiv.to_ring_equiv⟩ @[simp] lemma coe_mk {to_fun inv_fun left_inv right_inv map_mul map_add commutes} : ⇑(⟨to_fun, inv_fun, left_inv, right_inv, map_mul, map_add, commutes⟩ : A₁ ≃ₐ[R] A₂) = to_fun := rfl @[simp] theorem mk_coe (e : A₁ ≃ₐ[R] A₂) (e' h₁ h₂ h₃ h₄ h₅) : (⟨e, e', h₁, h₂, h₃, h₄, h₅⟩ : A₁ ≃ₐ[R] A₂) = e := ext $ λ _, rfl @[simp] lemma to_fun_eq_coe (e : A₁ ≃ₐ[R] A₂) : e.to_fun = e := rfl -- TODO: decide on a simp-normal form so that only one of these two lemmas is needed @[simp, norm_cast] lemma coe_ring_equiv : ((e : A₁ ≃+* A₂) : A₁ → A₂) = e := rfl @[simp] lemma coe_ring_equiv' : (e.to_ring_equiv : A₁ → A₂) = e := rfl lemma coe_ring_equiv_injective : function.injective (coe : (A₁ ≃ₐ[R] A₂) → (A₁ ≃+* A₂)) := λ e₁ e₂ h, ext $ ring_equiv.congr_fun h @[simp] lemma map_add : ∀ x y, e (x + y) = e x + e y := e.to_add_equiv.map_add @[simp] lemma map_zero : e 0 = 0 := e.to_add_equiv.map_zero @[simp] lemma map_mul : ∀ x y, e (x * y) = (e x) * (e y) := e.to_mul_equiv.map_mul @[simp] lemma map_one : e 1 = 1 := e.to_mul_equiv.map_one @[simp] lemma commutes : ∀ (r : R), e (algebra_map R A₁ r) = algebra_map R A₂ r := e.commutes' lemma map_sum {ι : Type*} (f : ι → A₁) (s : finset ι) : e (∑ x in s, f x) = ∑ x in s, e (f x) := e.to_add_equiv.map_sum f s lemma map_finsupp_sum {α : Type*} [has_zero α] {ι : Type*} (f : ι →₀ α) (g : ι → α → A₁) : e (f.sum g) = f.sum (λ i b, e (g i b)) := e.map_sum _ _ /-- Interpret an algebra equivalence as an algebra homomorphism. This definition is included for symmetry with the other `to_*_hom` projections. The `simp` normal form is to use the coercion of the `has_coe_to_alg_hom` instance. -/ def to_alg_hom : A₁ →ₐ[R] A₂ := { map_one' := e.map_one, map_zero' := e.map_zero, ..e } instance has_coe_to_alg_hom : has_coe (A₁ ≃ₐ[R] A₂) (A₁ →ₐ[R] A₂) := ⟨to_alg_hom⟩ @[simp] lemma to_alg_hom_eq_coe : e.to_alg_hom = e := rfl @[simp, norm_cast] lemma coe_alg_hom : ((e : A₁ →ₐ[R] A₂) : A₁ → A₂) = e := rfl lemma coe_alg_hom_injective : function.injective (coe : (A₁ ≃ₐ[R] A₂) → (A₁ →ₐ[R] A₂)) := λ e₁ e₂ h, ext $ alg_hom.congr_fun h /-- The two paths coercion can take to a `ring_hom` are equivalent -/ lemma coe_ring_hom_commutes : ((e : A₁ →ₐ[R] A₂) : A₁ →+* A₂) = ((e : A₁ ≃+* A₂) : A₁ →+* A₂) := rfl @[simp] lemma map_pow : ∀ (x : A₁) (n : ℕ), e (x ^ n) = (e x) ^ n := e.to_alg_hom.map_pow lemma injective : function.injective e := e.to_equiv.injective lemma surjective : function.surjective e := e.to_equiv.surjective lemma bijective : function.bijective e := e.to_equiv.bijective instance : has_one (A₁ ≃ₐ[R] A₁) := ⟨{commutes' := λ r, rfl, ..(1 : A₁ ≃+* A₁)}⟩ instance : inhabited (A₁ ≃ₐ[R] A₁) := ⟨1⟩ /-- Algebra equivalences are reflexive. -/ @[refl] def refl : A₁ ≃ₐ[R] A₁ := 1 @[simp] lemma refl_to_alg_hom : ↑(refl : A₁ ≃ₐ[R] A₁) = alg_hom.id R A₁ := rfl @[simp] lemma coe_refl : ⇑(refl : A₁ ≃ₐ[R] A₁) = id := rfl /-- Algebra equivalences are symmetric. -/ @[symm] def symm (e : A₁ ≃ₐ[R] A₂) : A₂ ≃ₐ[R] A₁ := { commutes' := λ r, by { rw ←e.to_ring_equiv.symm_apply_apply (algebra_map R A₁ r), congr, change _ = e _, rw e.commutes, }, ..e.to_ring_equiv.symm, } /-- See Note [custom simps projection] -/ def simps.symm_apply (e : A₁ ≃ₐ[R] A₂) : A₂ → A₁ := e.symm initialize_simps_projections alg_equiv (to_fun → apply, inv_fun → symm_apply) @[simp] lemma inv_fun_eq_symm {e : A₁ ≃ₐ[R] A₂} : e.inv_fun = e.symm := rfl @[simp] lemma symm_symm (e : A₁ ≃ₐ[R] A₂) : e.symm.symm = e := by { ext, refl, } lemma symm_bijective : function.bijective (symm : (A₁ ≃ₐ[R] A₂) → (A₂ ≃ₐ[R] A₁)) := equiv.bijective ⟨symm, symm, symm_symm, symm_symm⟩ @[simp] lemma mk_coe' (e : A₁ ≃ₐ[R] A₂) (f h₁ h₂ h₃ h₄ h₅) : (⟨f, e, h₁, h₂, h₃, h₄, h₅⟩ : A₂ ≃ₐ[R] A₁) = e.symm := symm_bijective.injective $ ext $ λ x, rfl @[simp] theorem symm_mk (f f') (h₁ h₂ h₃ h₄ h₅) : (⟨f, f', h₁, h₂, h₃, h₄, h₅⟩ : A₁ ≃ₐ[R] A₂).symm = { to_fun := f', inv_fun := f, ..(⟨f, f', h₁, h₂, h₃, h₄, h₅⟩ : A₁ ≃ₐ[R] A₂).symm } := rfl /-- Algebra equivalences are transitive. -/ @[trans] def trans (e₁ : A₁ ≃ₐ[R] A₂) (e₂ : A₂ ≃ₐ[R] A₃) : A₁ ≃ₐ[R] A₃ := { commutes' := λ r, show e₂.to_fun (e₁.to_fun _) = _, by rw [e₁.commutes', e₂.commutes'], ..(e₁.to_ring_equiv.trans e₂.to_ring_equiv), } @[simp] lemma apply_symm_apply (e : A₁ ≃ₐ[R] A₂) : ∀ x, e (e.symm x) = x := e.to_equiv.apply_symm_apply @[simp] lemma symm_apply_apply (e : A₁ ≃ₐ[R] A₂) : ∀ x, e.symm (e x) = x := e.to_equiv.symm_apply_apply @[simp] lemma symm_trans_apply (e₁ : A₁ ≃ₐ[R] A₂) (e₂ : A₂ ≃ₐ[R] A₃) (x : A₃) : (e₁.trans e₂).symm x = e₁.symm (e₂.symm x) := rfl @[simp] lemma coe_trans (e₁ : A₁ ≃ₐ[R] A₂) (e₂ : A₂ ≃ₐ[R] A₃) : ⇑(e₁.trans e₂) = e₂ ∘ e₁ := rfl lemma trans_apply (e₁ : A₁ ≃ₐ[R] A₂) (e₂ : A₂ ≃ₐ[R] A₃) (x : A₁) : (e₁.trans e₂) x = e₂ (e₁ x) := rfl @[simp] lemma comp_symm (e : A₁ ≃ₐ[R] A₂) : alg_hom.comp (e : A₁ →ₐ[R] A₂) ↑e.symm = alg_hom.id R A₂ := by { ext, simp } @[simp] lemma symm_comp (e : A₁ ≃ₐ[R] A₂) : alg_hom.comp ↑e.symm (e : A₁ →ₐ[R] A₂) = alg_hom.id R A₁ := by { ext, simp } theorem left_inverse_symm (e : A₁ ≃ₐ[R] A₂) : function.left_inverse e.symm e := e.left_inv theorem right_inverse_symm (e : A₁ ≃ₐ[R] A₂) : function.right_inverse e.symm e := e.right_inv /-- If `A₁` is equivalent to `A₁'` and `A₂` is equivalent to `A₂'`, then the type of maps `A₁ →ₐ[R] A₂` is equivalent to the type of maps `A₁' →ₐ[R] A₂'`. -/ def arrow_congr {A₁' A₂' : Type*} [semiring A₁'] [semiring A₂'] [algebra R A₁'] [algebra R A₂'] (e₁ : A₁ ≃ₐ[R] A₁') (e₂ : A₂ ≃ₐ[R] A₂') : (A₁ →ₐ[R] A₂) ≃ (A₁' →ₐ[R] A₂') := { to_fun := λ f, (e₂.to_alg_hom.comp f).comp e₁.symm.to_alg_hom, inv_fun := λ f, (e₂.symm.to_alg_hom.comp f).comp e₁.to_alg_hom, left_inv := λ f, by { simp only [alg_hom.comp_assoc, to_alg_hom_eq_coe, symm_comp], simp only [←alg_hom.comp_assoc, symm_comp, alg_hom.id_comp, alg_hom.comp_id] }, right_inv := λ f, by { simp only [alg_hom.comp_assoc, to_alg_hom_eq_coe, comp_symm], simp only [←alg_hom.comp_assoc, comp_symm, alg_hom.id_comp, alg_hom.comp_id] } } lemma arrow_congr_comp {A₁' A₂' A₃' : Type*} [semiring A₁'] [semiring A₂'] [semiring A₃'] [algebra R A₁'] [algebra R A₂'] [algebra R A₃'] (e₁ : A₁ ≃ₐ[R] A₁') (e₂ : A₂ ≃ₐ[R] A₂') (e₃ : A₃ ≃ₐ[R] A₃') (f : A₁ →ₐ[R] A₂) (g : A₂ →ₐ[R] A₃) : arrow_congr e₁ e₃ (g.comp f) = (arrow_congr e₂ e₃ g).comp (arrow_congr e₁ e₂ f) := by { ext, simp only [arrow_congr, equiv.coe_fn_mk, alg_hom.comp_apply], congr, exact (e₂.symm_apply_apply _).symm } @[simp] lemma arrow_congr_refl : arrow_congr alg_equiv.refl alg_equiv.refl = equiv.refl (A₁ →ₐ[R] A₂) := by { ext, refl } @[simp] lemma arrow_congr_trans {A₁' A₂' A₃' : Type*} [semiring A₁'] [semiring A₂'] [semiring A₃'] [algebra R A₁'] [algebra R A₂'] [algebra R A₃'] (e₁ : A₁ ≃ₐ[R] A₂) (e₁' : A₁' ≃ₐ[R] A₂') (e₂ : A₂ ≃ₐ[R] A₃) (e₂' : A₂' ≃ₐ[R] A₃') : arrow_congr (e₁.trans e₂) (e₁'.trans e₂') = (arrow_congr e₁ e₁').trans (arrow_congr e₂ e₂') := by { ext, refl } @[simp] lemma arrow_congr_symm {A₁' A₂' : Type*} [semiring A₁'] [semiring A₂'] [algebra R A₁'] [algebra R A₂'] (e₁ : A₁ ≃ₐ[R] A₁') (e₂ : A₂ ≃ₐ[R] A₂') : (arrow_congr e₁ e₂).symm = arrow_congr e₁.symm e₂.symm := by { ext, refl } /-- If an algebra morphism has an inverse, it is a algebra isomorphism. -/ def of_alg_hom (f : A₁ →ₐ[R] A₂) (g : A₂ →ₐ[R] A₁) (h₁ : f.comp g = alg_hom.id R A₂) (h₂ : g.comp f = alg_hom.id R A₁) : A₁ ≃ₐ[R] A₂ := { to_fun := f, inv_fun := g, left_inv := alg_hom.ext_iff.1 h₂, right_inv := alg_hom.ext_iff.1 h₁, ..f } lemma coe_alg_hom_of_alg_hom (f : A₁ →ₐ[R] A₂) (g : A₂ →ₐ[R] A₁) (h₁ h₂) : ↑(of_alg_hom f g h₁ h₂) = f := alg_hom.ext $ λ _, rfl @[simp] lemma of_alg_hom_coe_alg_hom (f : A₁ ≃ₐ[R] A₂) (g : A₂ →ₐ[R] A₁) (h₁ h₂) : of_alg_hom ↑f g h₁ h₂ = f := ext $ λ _, rfl lemma of_alg_hom_symm (f : A₁ →ₐ[R] A₂) (g : A₂ →ₐ[R] A₁) (h₁ h₂) : (of_alg_hom f g h₁ h₂).symm = of_alg_hom g f h₂ h₁ := rfl /-- Promotes a bijective algebra homomorphism to an algebra equivalence. -/ noncomputable def of_bijective (f : A₁ →ₐ[R] A₂) (hf : function.bijective f) : A₁ ≃ₐ[R] A₂ := { .. ring_equiv.of_bijective (f : A₁ →+* A₂) hf, .. f } /-- Forgetting the multiplicative structures, an equivalence of algebras is a linear equivalence. -/ @[simps apply] def to_linear_equiv (e : A₁ ≃ₐ[R] A₂) : A₁ ≃ₗ[R] A₂ := { to_fun := e, map_smul' := λ r x, by simp [algebra.smul_def''], inv_fun := e.symm, .. e } @[simp] lemma to_linear_equiv_refl : (alg_equiv.refl : A₁ ≃ₐ[R] A₁).to_linear_equiv = linear_equiv.refl R A₁ := rfl @[simp] lemma to_linear_equiv_symm (e : A₁ ≃ₐ[R] A₂) : e.to_linear_equiv.symm = e.symm.to_linear_equiv := rfl @[simp] lemma to_linear_equiv_trans (e₁ : A₁ ≃ₐ[R] A₂) (e₂ : A₂ ≃ₐ[R] A₃) : (e₁.trans e₂).to_linear_equiv = e₁.to_linear_equiv.trans e₂.to_linear_equiv := rfl theorem to_linear_equiv_injective : function.injective (to_linear_equiv : _ → (A₁ ≃ₗ[R] A₂)) := λ e₁ e₂ h, ext $ linear_equiv.congr_fun h /-- Interpret an algebra equivalence as a linear map. -/ def to_linear_map : A₁ →ₗ[R] A₂ := e.to_alg_hom.to_linear_map @[simp] lemma to_alg_hom_to_linear_map : (e : A₁ →ₐ[R] A₂).to_linear_map = e.to_linear_map := rfl @[simp] lemma to_linear_equiv_to_linear_map : e.to_linear_equiv.to_linear_map = e.to_linear_map := rfl @[simp] lemma to_linear_map_apply (x : A₁) : e.to_linear_map x = e x := rfl theorem to_linear_map_injective : function.injective (to_linear_map : _ → (A₁ →ₗ[R] A₂)) := λ e₁ e₂ h, ext $ linear_map.congr_fun h @[simp] lemma trans_to_linear_map (f : A₁ ≃ₐ[R] A₂) (g : A₂ ≃ₐ[R] A₃) : (f.trans g).to_linear_map = g.to_linear_map.comp f.to_linear_map := rfl section of_linear_equiv variables (l : A₁ ≃ₗ[R] A₂) (map_mul : ∀ x y : A₁, l (x * y) = l x * l y) (commutes : ∀ r : R, l (algebra_map R A₁ r) = algebra_map R A₂ r) /-- Upgrade a linear equivalence to an algebra equivalence, given that it distributes over multiplication and action of scalars. -/ @[simps apply] def of_linear_equiv : A₁ ≃ₐ[R] A₂ := { to_fun := l, inv_fun := l.symm, map_mul' := map_mul, commutes' := commutes, ..l } @[simp] lemma of_linear_equiv_symm : (of_linear_equiv l map_mul commutes).symm = of_linear_equiv l.symm ((of_linear_equiv l map_mul commutes).symm.map_mul) ((of_linear_equiv l map_mul commutes).symm.commutes) := rfl @[simp] lemma of_linear_equiv_to_linear_equiv (map_mul) (commutes) : of_linear_equiv e.to_linear_equiv map_mul commutes = e := by { ext, refl } @[simp] lemma to_linear_equiv_of_linear_equiv : to_linear_equiv (of_linear_equiv l map_mul commutes) = l := by { ext, refl } end of_linear_equiv instance aut : group (A₁ ≃ₐ[R] A₁) := { mul := λ ϕ ψ, ψ.trans ϕ, mul_assoc := λ ϕ ψ χ, rfl, one := 1, one_mul := λ ϕ, by { ext, refl }, mul_one := λ ϕ, by { ext, refl }, inv := symm, mul_left_inv := λ ϕ, by { ext, exact symm_apply_apply ϕ a } } @[simp] lemma mul_apply (e₁ e₂ : A₁ ≃ₐ[R] A₁) (x : A₁) : (e₁ * e₂) x = e₁ (e₂ x) := rfl /-- An algebra isomorphism induces a group isomorphism between automorphism groups -/ @[simps apply] def aut_congr (ϕ : A₁ ≃ₐ[R] A₂) : (A₁ ≃ₐ[R] A₁) ≃* (A₂ ≃ₐ[R] A₂) := { to_fun := λ ψ, ϕ.symm.trans (ψ.trans ϕ), inv_fun := λ ψ, ϕ.trans (ψ.trans ϕ.symm), left_inv := λ ψ, by { ext, simp_rw [trans_apply, symm_apply_apply] }, right_inv := λ ψ, by { ext, simp_rw [trans_apply, apply_symm_apply] }, map_mul' := λ ψ χ, by { ext, simp only [mul_apply, trans_apply, symm_apply_apply] } } @[simp] lemma aut_congr_refl : aut_congr (alg_equiv.refl) = mul_equiv.refl (A₁ ≃ₐ[R] A₁) := by { ext, refl } @[simp] lemma aut_congr_symm (ϕ : A₁ ≃ₐ[R] A₂) : (aut_congr ϕ).symm = aut_congr ϕ.symm := rfl @[simp] lemma aut_congr_trans (ϕ : A₁ ≃ₐ[R] A₂) (ψ : A₂ ≃ₐ[R] A₃) : (aut_congr ϕ).trans (aut_congr ψ) = aut_congr (ϕ.trans ψ) := rfl /-- The tautological action by `A₁ ≃ₐ[R] A₁` on `A₁`. This generalizes `function.End.apply_mul_action`. -/ instance apply_mul_semiring_action : mul_semiring_action (A₁ ≃ₐ[R] A₁) A₁ := { smul := ($), smul_zero := alg_equiv.map_zero, smul_add := alg_equiv.map_add, smul_one := alg_equiv.map_one, smul_mul := alg_equiv.map_mul, one_smul := λ _, rfl, mul_smul := λ _ _ _, rfl } @[simp] protected lemma smul_def (f : A₁ ≃ₐ[R] A₁) (a : A₁) : f • a = f a := rfl instance apply_has_faithful_scalar : has_faithful_scalar (A₁ ≃ₐ[R] A₁) A₁ := ⟨λ _ _, alg_equiv.ext⟩ instance apply_smul_comm_class : smul_comm_class R (A₁ ≃ₐ[R] A₁) A₁ := { smul_comm := λ r e a, (e.to_linear_equiv.map_smul r a).symm } instance apply_smul_comm_class' : smul_comm_class (A₁ ≃ₐ[R] A₁) R A₁ := { smul_comm := λ e r a, (e.to_linear_equiv.map_smul r a) } @[simp] lemma algebra_map_eq_apply (e : A₁ ≃ₐ[R] A₂) {y : R} {x : A₁} : (algebra_map R A₂ y = e x) ↔ (algebra_map R A₁ y = x) := ⟨λ h, by simpa using e.symm.to_alg_hom.algebra_map_eq_apply h, λ h, e.to_alg_hom.algebra_map_eq_apply h⟩ end semiring section comm_semiring variables [comm_semiring R] [comm_semiring A₁] [comm_semiring A₂] variables [algebra R A₁] [algebra R A₂] (e : A₁ ≃ₐ[R] A₂) lemma map_prod {ι : Type*} (f : ι → A₁) (s : finset ι) : e (∏ x in s, f x) = ∏ x in s, e (f x) := e.to_alg_hom.map_prod f s lemma map_finsupp_prod {α : Type*} [has_zero α] {ι : Type*} (f : ι →₀ α) (g : ι → α → A₁) : e (f.prod g) = f.prod (λ i a, e (g i a)) := e.to_alg_hom.map_finsupp_prod f g end comm_semiring section ring variables [comm_ring R] [ring A₁] [ring A₂] variables [algebra R A₁] [algebra R A₂] (e : A₁ ≃ₐ[R] A₂) @[simp] lemma map_neg (x) : e (-x) = -e x := e.to_alg_hom.map_neg x @[simp] lemma map_sub (x y) : e (x - y) = e x - e y := e.to_alg_hom.map_sub x y end ring section division_ring variables [comm_ring R] [division_ring A₁] [division_ring A₂] variables [algebra R A₁] [algebra R A₂] (e : A₁ ≃ₐ[R] A₂) @[simp] lemma map_inv (x) : e (x⁻¹) = (e x)⁻¹ := e.to_alg_hom.map_inv x @[simp] lemma map_div (x y) : e (x / y) = e x / e y := e.to_alg_hom.map_div x y end division_ring end alg_equiv namespace mul_semiring_action variables {M G : Type*} (R A : Type*) [comm_semiring R] [semiring A] [algebra R A] section variables [monoid M] [mul_semiring_action M A] [smul_comm_class M R A] /-- Each element of the monoid defines a algebra homomorphism. This is a stronger version of `mul_semiring_action.to_ring_hom` and `distrib_mul_action.to_linear_map`. -/ @[simps] def to_alg_hom (m : M) : A →ₐ[R] A := alg_hom.mk' (mul_semiring_action.to_ring_hom _ _ m) (smul_comm _) theorem to_alg_hom_injective [has_faithful_scalar M A] : function.injective (mul_semiring_action.to_alg_hom R A : M → A →ₐ[R] A) := λ m₁ m₂ h, eq_of_smul_eq_smul $ λ r, alg_hom.ext_iff.1 h r end section variables [group G] [mul_semiring_action G A] [smul_comm_class G R A] /-- Each element of the group defines a algebra equivalence. This is a stronger version of `mul_semiring_action.to_ring_equiv` and `distrib_mul_action.to_linear_equiv`. -/ @[simps] def to_alg_equiv (g : G) : A ≃ₐ[R] A := { .. mul_semiring_action.to_ring_equiv _ _ g, .. mul_semiring_action.to_alg_hom R A g } theorem to_alg_equiv_injective [has_faithful_scalar G A] : function.injective (mul_semiring_action.to_alg_equiv R A : G → A ≃ₐ[R] A) := λ m₁ m₂ h, eq_of_smul_eq_smul $ λ r, alg_equiv.ext_iff.1 h r end end mul_semiring_action section nat variables {R : Type*} [semiring R] -- Lower the priority so that `algebra.id` is picked most of the time when working with -- `ℕ`-algebras. This is only an issue since `algebra.id` and `algebra_nat` are not yet defeq. -- TODO: fix this by adding an `of_nat` field to semirings. /-- Semiring ⥤ ℕ-Alg -/ @[priority 99] instance algebra_nat : algebra ℕ R := { commutes' := nat.cast_commute, smul_def' := λ _ _, nsmul_eq_mul _ _, to_ring_hom := nat.cast_ring_hom R } instance nat_algebra_subsingleton : subsingleton (algebra ℕ R) := ⟨λ P Q, by { ext, simp, }⟩ end nat namespace ring_hom variables {R S : Type*} /-- Reinterpret a `ring_hom` as an `ℕ`-algebra homomorphism. -/ def to_nat_alg_hom [semiring R] [semiring S] (f : R →+* S) : R →ₐ[ℕ] S := { to_fun := f, commutes' := λ n, by simp, .. f } /-- Reinterpret a `ring_hom` as a `ℤ`-algebra homomorphism. -/ def to_int_alg_hom [ring R] [ring S] [algebra ℤ R] [algebra ℤ S] (f : R →+* S) : R →ₐ[ℤ] S := { commutes' := λ n, by simp, .. f } @[simp] lemma map_rat_algebra_map [ring R] [ring S] [algebra ℚ R] [algebra ℚ S] (f : R →+* S) (r : ℚ) : f (algebra_map ℚ R r) = algebra_map ℚ S r := ring_hom.ext_iff.1 (subsingleton.elim (f.comp (algebra_map ℚ R)) (algebra_map ℚ S)) r /-- Reinterpret a `ring_hom` as a `ℚ`-algebra homomorphism. -/ def to_rat_alg_hom [ring R] [ring S] [algebra ℚ R] [algebra ℚ S] (f : R →+* S) : R →ₐ[ℚ] S := { commutes' := f.map_rat_algebra_map, .. f } end ring_hom namespace rat instance algebra_rat {α} [division_ring α] [char_zero α] : algebra ℚ α := (rat.cast_hom α).to_algebra' $ λ r x, r.cast_commute x @[simp] theorem algebra_map_rat_rat : algebra_map ℚ ℚ = ring_hom.id ℚ := subsingleton.elim _ _ -- TODO[gh-6025]: make this an instance once safe to do so lemma algebra_rat_subsingleton {α} [semiring α] : subsingleton (algebra ℚ α) := ⟨λ x y, algebra.algebra_ext x y $ ring_hom.congr_fun $ subsingleton.elim _ _⟩ end rat namespace char_zero variables {R : Type*} (S : Type*) [comm_semiring R] [semiring S] [algebra R S] lemma of_algebra [char_zero S] : char_zero R := ⟨begin suffices : function.injective (algebra_map R S ∘ coe), { exact this.of_comp }, convert char_zero.cast_injective, ext n, rw [function.comp_app, ← (algebra_map ℕ _).eq_nat_cast, ← ring_hom.comp_apply, ring_hom.eq_nat_cast], all_goals { apply_instance } end⟩ end char_zero namespace algebra open module variables (R : Type u) (A : Type v) variables [comm_semiring R] [semiring A] [algebra R A] /-- `algebra_map` as an `alg_hom`. -/ def of_id : R →ₐ[R] A := { commutes' := λ _, rfl, .. algebra_map R A } variables {R} theorem of_id_apply (r) : of_id R A r = algebra_map R A r := rfl end algebra section int variables (R : Type*) [ring R] -- Lower the priority so that `algebra.id` is picked most of the time when working with -- `ℤ`-algebras. This is only an issue since `algebra.id ℤ` and `algebra_int ℤ` are not yet defeq. -- TODO: fix this by adding an `of_int` field to rings. /-- Ring ⥤ ℤ-Alg -/ @[priority 99] instance algebra_int : algebra ℤ R := { commutes' := int.cast_commute, smul_def' := λ _ _, gsmul_eq_mul _ _, to_ring_hom := int.cast_ring_hom R } variables {R} instance int_algebra_subsingleton : subsingleton (algebra ℤ R) := ⟨λ P Q, by { ext, simp, }⟩ end int /-! The R-algebra structure on `Π i : I, A i` when each `A i` is an R-algebra. We couldn't set this up back in `algebra.pi_instances` because this file imports it. -/ namespace pi variable {I : Type u} -- The indexing type variable {R : Type*} -- The scalar type variable {f : I → Type v} -- The family of types already equipped with instances variables (x y : Π i, f i) (i : I) variables (I f) instance algebra {r : comm_semiring R} [s : ∀ i, semiring (f i)] [∀ i, algebra R (f i)] : algebra R (Π i : I, f i) := { commutes' := λ a f, begin ext, simp [algebra.commutes], end, smul_def' := λ a f, begin ext, simp [algebra.smul_def''], end, ..(pi.ring_hom (λ i, algebra_map R (f i)) : R →+* Π i : I, f i) } @[simp] lemma algebra_map_apply {r : comm_semiring R} [s : ∀ i, semiring (f i)] [∀ i, algebra R (f i)] (a : R) (i : I) : algebra_map R (Π i, f i) a i = algebra_map R (f i) a := rfl -- One could also build a `Π i, R i`-algebra structure on `Π i, A i`, -- when each `A i` is an `R i`-algebra, although I'm not sure that it's useful. variables {I} (R) (f) /-- `function.eval` as an `alg_hom`. The name matches `pi.eval_ring_hom`, `pi.eval_monoid_hom`, etc. -/ @[simps] def eval_alg_hom {r : comm_semiring R} [Π i, semiring (f i)] [Π i, algebra R (f i)] (i : I) : (Π i, f i) →ₐ[R] f i := { to_fun := λ f, f i, commutes' := λ r, rfl, .. pi.eval_ring_hom f i} variables (A B : Type*) [comm_semiring R] [semiring B] [algebra R B] /-- `function.const` as an `alg_hom`. The name matches `pi.const_ring_hom`, `pi.const_monoid_hom`, etc. -/ @[simps] def const_alg_hom : B →ₐ[R] (A → B) := { to_fun := function.const _, commutes' := λ r, rfl, .. pi.const_ring_hom A B} /-- When `R` is commutative and permits an `algebra_map`, `pi.const_ring_hom` is equal to that map. -/ @[simp] lemma const_ring_hom_eq_algebra_map : const_ring_hom A R = algebra_map R (A → R) := rfl @[simp] lemma const_alg_hom_eq_algebra_of_id : const_alg_hom R A R = algebra.of_id R (A → R) := rfl end pi section is_scalar_tower variables {R : Type*} [comm_semiring R] variables (A : Type*) [semiring A] [algebra R A] variables {M : Type*} [add_comm_monoid M] [module A M] [module R M] [is_scalar_tower R A M] variables {N : Type*} [add_comm_monoid N] [module A N] [module R N] [is_scalar_tower R A N] lemma algebra_compatible_smul (r : R) (m : M) : r • m = ((algebra_map R A) r) • m := by rw [←(one_smul A m), ←smul_assoc, algebra.smul_def, mul_one, one_smul] @[simp] lemma algebra_map_smul (r : R) (m : M) : ((algebra_map R A) r) • m = r • m := (algebra_compatible_smul A r m).symm variable {A} @[priority 100] -- see Note [lower instance priority] instance is_scalar_tower.to_smul_comm_class : smul_comm_class R A M := ⟨λ r a m, by rw [algebra_compatible_smul A r (a • m), smul_smul, algebra.commutes, mul_smul, ←algebra_compatible_smul]⟩ @[priority 100] -- see Note [lower instance priority] instance is_scalar_tower.to_smul_comm_class' : smul_comm_class A R M := smul_comm_class.symm _ _ _ lemma smul_algebra_smul_comm (r : R) (a : A) (m : M) : a • r • m = r • a • m := smul_comm _ _ _ namespace linear_map instance coe_is_scalar_tower : has_coe (M →ₗ[A] N) (M →ₗ[R] N) := ⟨restrict_scalars R⟩ variables (R) {A M N} @[simp, norm_cast squash] lemma coe_restrict_scalars_eq_coe (f : M →ₗ[A] N) : (f.restrict_scalars R : M → N) = f := rfl @[simp, norm_cast squash] lemma coe_coe_is_scalar_tower (f : M →ₗ[A] N) : ((f : M →ₗ[R] N) : M → N) = f := rfl /-- `A`-linearly coerce a `R`-linear map from `M` to `A` to a function, given an algebra `A` over a commutative semiring `R` and `M` a module over `R`. -/ def lto_fun (R : Type u) (M : Type v) (A : Type w) [comm_semiring R] [add_comm_monoid M] [module R M] [comm_ring A] [algebra R A] : (M →ₗ[R] A) →ₗ[A] (M → A) := { to_fun := linear_map.to_fun, map_add' := λ f g, rfl, map_smul' := λ c f, rfl } end linear_map end is_scalar_tower /-! TODO: The following lemmas no longer involve `algebra` at all, and could be moved closer to `algebra/module/submodule.lean`. Currently this is tricky because `ker`, `range`, `⊤`, and `⊥` are all defined in `linear_algebra/basic.lean`. -/ section module open module variables (R S M N : Type*) [semiring R] [semiring S] [has_scalar R S] variables [add_comm_monoid M] [module R M] [module S M] [is_scalar_tower R S M] variables [add_comm_monoid N] [module R N] [module S N] [is_scalar_tower R S N] variables {S M N} namespace submodule variables (R S M) /-- If `S` is an `R`-algebra, then the `R`-module generated by a set `X` is included in the `S`-module generated by `X`. -/ lemma span_le_restrict_scalars (X : set M) : span R (X : set M) ≤ restrict_scalars R (span S X) := submodule.span_le.mpr submodule.subset_span end submodule @[simp] lemma linear_map.ker_restrict_scalars (f : M →ₗ[S] N) : (f.restrict_scalars R).ker = f.ker.restrict_scalars R := rfl end module namespace submodule variables (R A M : Type*) variables [comm_semiring R] [semiring A] [algebra R A] [add_comm_monoid M] variables [module R M] [module A M] [is_scalar_tower R A M] /-- If `A` is an `R`-algebra such that the induced morhpsim `R →+* A` is surjective, then the `R`-module generated by a set `X` equals the `A`-module generated by `X`. -/ lemma span_eq_restrict_scalars (X : set M) (hsur : function.surjective (algebra_map R A)) : span R X = restrict_scalars R (span A X) := begin apply (span_le_restrict_scalars R A M X).antisymm (λ m hm, _), refine span_induction hm subset_span (zero_mem _) (λ _ _, add_mem _) (λ a m hm, _), obtain ⟨r, rfl⟩ := hsur a, simpa [algebra_map_smul] using smul_mem _ r hm end end submodule namespace alg_hom variables {R : Type u} {A : Type v} {B : Type w} {I : Type*} variables [comm_semiring R] [semiring A] [semiring B] variables [algebra R A] [algebra R B] /-- `R`-algebra homomorphism between the function spaces `I → A` and `I → B`, induced by an `R`-algebra homomorphism `f` between `A` and `B`. -/ @[simps] protected def comp_left (f : A →ₐ[R] B) (I : Type*) : (I → A) →ₐ[R] (I → B) := { to_fun := λ h, f ∘ h, commutes' := λ c, by { ext, exact f.commutes' c }, .. f.to_ring_hom.comp_left I } end alg_hom
26968ce83f2a7a335ac2ab67e7b627c3ccbb390b
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/analysis/normed_space/linear_isometry_auto.lean
10bc5fb39ac81bdb4235b6d4856b0e0cbfe5a88c
[]
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
26,024
lean
/- Copyright (c) 2021 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Yury Kudryashov -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.topology.metric_space.isometry import Mathlib.PostPort universes u_6 u_7 u_8 l u_1 u_2 u_3 u_4 u_5 namespace Mathlib /-! # Linear isometries In this file we define `linear_isometry R E F` (notation: `E →ₗᵢ[R] F`) to be a linear isometric embedding of `E` into `F` and `linear_isometry_equiv` (notation: `E ≃ₗᵢ[R] F`) to be a linear isometric equivalence between `E` and `F`. We also prove some trivial lemmas and provide convenience constructors. -/ /-- An `R`-linear isometric embedding of one normed `R`-module into another. -/ structure linear_isometry (R : Type u_6) (E : Type u_7) (F : Type u_8) [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] extends linear_map R E F where norm_map' : ∀ (x : E), norm (coe_fn _to_linear_map x) = norm x namespace linear_isometry protected instance has_coe_to_fun {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] : has_coe_to_fun (linear_isometry R E F) := has_coe_to_fun.mk (fun (f : linear_isometry R E F) => E → F) fun (f : linear_isometry R E F) => linear_map.to_fun (to_linear_map f) @[simp] theorem coe_to_linear_map {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (f : linear_isometry R E F) : ⇑(to_linear_map f) = ⇑f := rfl theorem to_linear_map_injective {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] : function.injective to_linear_map := sorry theorem coe_fn_injective {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] : function.injective fun (f : linear_isometry R E F) (x : E) => coe_fn f x := function.injective.comp linear_map.coe_injective to_linear_map_injective theorem ext {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] {f : linear_isometry R E F} {g : linear_isometry R E F} (h : ∀ (x : E), coe_fn f x = coe_fn g x) : f = g := coe_fn_injective (funext h) @[simp] theorem map_zero {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (f : linear_isometry R E F) : coe_fn f 0 = 0 := linear_map.map_zero (to_linear_map f) @[simp] theorem map_add {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (f : linear_isometry R E F) (x : E) (y : E) : coe_fn f (x + y) = coe_fn f x + coe_fn f y := linear_map.map_add (to_linear_map f) x y @[simp] theorem map_sub {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (f : linear_isometry R E F) (x : E) (y : E) : coe_fn f (x - y) = coe_fn f x - coe_fn f y := linear_map.map_sub (to_linear_map f) x y @[simp] theorem map_smul {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (f : linear_isometry R E F) (c : R) (x : E) : coe_fn f (c • x) = c • coe_fn f x := linear_map.map_smul (to_linear_map f) c x @[simp] theorem norm_map {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (f : linear_isometry R E F) (x : E) : norm (coe_fn f x) = norm x := norm_map' f x @[simp] theorem nnnorm_map {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (f : linear_isometry R E F) (x : E) : nnnorm (coe_fn f x) = nnnorm x := nnreal.eq (norm_map f x) protected theorem isometry {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (f : linear_isometry R E F) : isometry ⇑f := add_monoid_hom.isometry_of_norm (linear_map.to_add_monoid_hom (to_linear_map f)) (norm_map f) @[simp] theorem dist_map {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (f : linear_isometry R E F) (x : E) (y : E) : dist (coe_fn f x) (coe_fn f y) = dist x y := isometry.dist_eq (linear_isometry.isometry f) x y @[simp] theorem edist_map {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (f : linear_isometry R E F) (x : E) (y : E) : edist (coe_fn f x) (coe_fn f y) = edist x y := isometry.edist_eq (linear_isometry.isometry f) x y protected theorem injective {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (f : linear_isometry R E F) : function.injective ⇑f := isometry.injective (linear_isometry.isometry f) theorem map_eq_iff {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (f : linear_isometry R E F) {x : E} {y : E} : coe_fn f x = coe_fn f y ↔ x = y := function.injective.eq_iff (linear_isometry.injective f) theorem map_ne {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (f : linear_isometry R E F) {x : E} {y : E} (h : x ≠ y) : coe_fn f x ≠ coe_fn f y := function.injective.ne (linear_isometry.injective f) h protected theorem lipschitz {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (f : linear_isometry R E F) : lipschitz_with 1 ⇑f := isometry.lipschitz (linear_isometry.isometry f) protected theorem antilipschitz {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (f : linear_isometry R E F) : antilipschitz_with 1 ⇑f := isometry.antilipschitz (linear_isometry.isometry f) protected theorem continuous {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (f : linear_isometry R E F) : continuous ⇑f := isometry.continuous (linear_isometry.isometry f) theorem ediam_image {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (f : linear_isometry R E F) (s : set E) : emetric.diam (⇑f '' s) = emetric.diam s := isometry.ediam_image (linear_isometry.isometry f) s theorem ediam_range {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (f : linear_isometry R E F) : emetric.diam (set.range ⇑f) = emetric.diam set.univ := isometry.ediam_range (linear_isometry.isometry f) theorem diam_image {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (f : linear_isometry R E F) (s : set E) : metric.diam (⇑f '' s) = metric.diam s := isometry.diam_image (linear_isometry.isometry f) s theorem diam_range {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (f : linear_isometry R E F) : metric.diam (set.range ⇑f) = metric.diam set.univ := isometry.diam_range (linear_isometry.isometry f) /-- Interpret a linear isometry as a continuous linear map. -/ def to_continuous_linear_map {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (f : linear_isometry R E F) : continuous_linear_map R E F := continuous_linear_map.mk (to_linear_map f) @[simp] theorem coe_to_continuous_linear_map {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (f : linear_isometry R E F) : ⇑(to_continuous_linear_map f) = ⇑f := rfl @[simp] theorem comp_continuous_iff {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (f : linear_isometry R E F) {α : Type u_4} [topological_space α] {g : α → E} : continuous (⇑f ∘ g) ↔ continuous g := sorry /-- The identity linear isometry. -/ def id {R : Type u_1} {E : Type u_2} [semiring R] [normed_group E] [semimodule R E] : linear_isometry R E E := mk linear_map.id sorry @[simp] theorem coe_id {R : Type u_1} {E : Type u_2} [semiring R] [normed_group E] [semimodule R E] : ⇑id = ⇑id := rfl protected instance inhabited {R : Type u_1} {E : Type u_2} [semiring R] [normed_group E] [semimodule R E] : Inhabited (linear_isometry R E E) := { default := id } /-- Composition of linear isometries. -/ def comp {R : Type u_1} {E : Type u_2} {F : Type u_3} {G : Type u_4} [semiring R] [normed_group E] [normed_group F] [normed_group G] [semimodule R E] [semimodule R F] [semimodule R G] (g : linear_isometry R F G) (f : linear_isometry R E F) : linear_isometry R E G := mk (linear_map.comp (to_linear_map g) (to_linear_map f)) sorry @[simp] theorem coe_comp {R : Type u_1} {E : Type u_2} {F : Type u_3} {G : Type u_4} [semiring R] [normed_group E] [normed_group F] [normed_group G] [semimodule R E] [semimodule R F] [semimodule R G] (g : linear_isometry R F G) (f : linear_isometry R E F) : ⇑(comp g f) = ⇑g ∘ ⇑f := rfl @[simp] theorem id_comp {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (f : linear_isometry R E F) : comp id f = f := ext fun (x : E) => rfl @[simp] theorem comp_id {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (f : linear_isometry R E F) : comp f id = f := ext fun (x : E) => rfl theorem comp_assoc {R : Type u_1} {E : Type u_2} {F : Type u_3} {G : Type u_4} {G' : Type u_5} [semiring R] [normed_group E] [normed_group F] [normed_group G] [normed_group G'] [semimodule R E] [semimodule R F] [semimodule R G] [semimodule R G'] (f : linear_isometry R G G') (g : linear_isometry R F G) (h : linear_isometry R E F) : comp (comp f g) h = comp f (comp g h) := rfl protected instance monoid {R : Type u_1} {E : Type u_2} [semiring R] [normed_group E] [semimodule R E] : monoid (linear_isometry R E E) := monoid.mk comp comp_assoc id id_comp comp_id @[simp] theorem coe_one {R : Type u_1} {E : Type u_2} [semiring R] [normed_group E] [semimodule R E] : ⇑1 = ⇑id := rfl @[simp] theorem coe_mul {R : Type u_1} {E : Type u_2} [semiring R] [normed_group E] [semimodule R E] (f : linear_isometry R E E) (g : linear_isometry R E E) : ⇑(f * g) = ⇑f ∘ ⇑g := rfl end linear_isometry /-- A linear isometric equivalence between two normed vector spaces. -/ structure linear_isometry_equiv (R : Type u_6) (E : Type u_7) (F : Type u_8) [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] extends linear_equiv R E F where norm_map' : ∀ (x : E), norm (coe_fn _to_linear_equiv x) = norm x namespace linear_isometry_equiv protected instance has_coe_to_fun {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] : has_coe_to_fun (linear_isometry_equiv R E F) := has_coe_to_fun.mk (fun (f : linear_isometry_equiv R E F) => E → F) fun (f : linear_isometry_equiv R E F) => linear_equiv.to_fun (to_linear_equiv f) @[simp] theorem coe_mk {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (e : linear_equiv R E F) (he : ∀ (x : E), norm (coe_fn e x) = norm x) : ⇑(mk e he) = ⇑e := rfl @[simp] theorem coe_to_linear_equiv {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (e : linear_isometry_equiv R E F) : ⇑(to_linear_equiv e) = ⇑e := rfl theorem to_linear_equiv_injective {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] : function.injective to_linear_equiv := sorry theorem ext {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] {e : linear_isometry_equiv R E F} {e' : linear_isometry_equiv R E F} (h : ∀ (x : E), coe_fn e x = coe_fn e' x) : e = e' := to_linear_equiv_injective (linear_equiv.ext h) /-- Construct a `linear_isometry_equiv` from a `linear_equiv` and two inequalities: `∀ x, ∥e x∥ ≤ ∥x∥` and `∀ y, ∥e.symm y∥ ≤ ∥y∥`. -/ def of_bounds {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (e : linear_equiv R E F) (h₁ : ∀ (x : E), norm (coe_fn e x) ≤ norm x) (h₂ : ∀ (y : F), norm (coe_fn (linear_equiv.symm e) y) ≤ norm y) : linear_isometry_equiv R E F := mk e sorry @[simp] theorem norm_map {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (e : linear_isometry_equiv R E F) (x : E) : norm (coe_fn e x) = norm x := norm_map' e x /-- Reinterpret a `linear_isometry_equiv` as a `linear_isometry`. -/ def to_linear_isometry {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (e : linear_isometry_equiv R E F) : linear_isometry R E F := linear_isometry.mk (↑(to_linear_equiv e)) (norm_map' e) protected theorem isometry {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (e : linear_isometry_equiv R E F) : isometry ⇑e := linear_isometry.isometry (to_linear_isometry e) /-- Reinterpret a `linear_isometry_equiv` as an `isometric`. -/ def to_isometric {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (e : linear_isometry_equiv R E F) : E ≃ᵢ F := isometric.mk (linear_equiv.to_equiv (to_linear_equiv e)) (linear_isometry_equiv.isometry e) protected theorem continuous {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (e : linear_isometry_equiv R E F) : continuous ⇑e := isometry.continuous (linear_isometry_equiv.isometry e) /-- Identity map as a `linear_isometry_equiv`. -/ def refl (R : Type u_1) (E : Type u_2) [semiring R] [normed_group E] [semimodule R E] : linear_isometry_equiv R E E := mk (linear_equiv.refl R E) sorry protected instance inhabited {R : Type u_1} {E : Type u_2} [semiring R] [normed_group E] [semimodule R E] : Inhabited (linear_isometry_equiv R E E) := { default := refl R E } @[simp] theorem coe_refl {R : Type u_1} {E : Type u_2} [semiring R] [normed_group E] [semimodule R E] : ⇑(refl R E) = id := rfl /-- The inverse `linear_isometry_equiv`. -/ def symm {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (e : linear_isometry_equiv R E F) : linear_isometry_equiv R F E := mk (linear_equiv.symm (to_linear_equiv e)) sorry @[simp] theorem apply_symm_apply {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (e : linear_isometry_equiv R E F) (x : F) : coe_fn e (coe_fn (symm e) x) = x := linear_equiv.apply_symm_apply (to_linear_equiv e) x @[simp] theorem symm_apply_apply {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (e : linear_isometry_equiv R E F) (x : E) : coe_fn (symm e) (coe_fn e x) = x := linear_equiv.symm_apply_apply (to_linear_equiv e) x @[simp] theorem map_eq_zero_iff {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (e : linear_isometry_equiv R E F) {x : E} : coe_fn e x = 0 ↔ x = 0 := linear_equiv.map_eq_zero_iff (to_linear_equiv e) @[simp] theorem symm_symm {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (e : linear_isometry_equiv R E F) : symm (symm e) = e := ext fun (x : E) => rfl @[simp] theorem coe_symm_to_linear_equiv {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (e : linear_isometry_equiv R E F) : ⇑(linear_equiv.symm (to_linear_equiv e)) = ⇑(symm e) := rfl /-- Composition of `linear_isometry_equiv`s as a `linear_isometry_equiv`. -/ def trans {R : Type u_1} {E : Type u_2} {F : Type u_3} {G : Type u_4} [semiring R] [normed_group E] [normed_group F] [normed_group G] [semimodule R E] [semimodule R F] [semimodule R G] (e : linear_isometry_equiv R E F) (e' : linear_isometry_equiv R F G) : linear_isometry_equiv R E G := mk (linear_equiv.trans (to_linear_equiv e) (to_linear_equiv e')) sorry @[simp] theorem coe_trans {R : Type u_1} {E : Type u_2} {F : Type u_3} {G : Type u_4} [semiring R] [normed_group E] [normed_group F] [normed_group G] [semimodule R E] [semimodule R F] [semimodule R G] (e₁ : linear_isometry_equiv R E F) (e₂ : linear_isometry_equiv R F G) : ⇑(trans e₁ e₂) = ⇑e₂ ∘ ⇑e₁ := rfl @[simp] theorem trans_refl {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (e : linear_isometry_equiv R E F) : trans e (refl R F) = e := ext fun (x : E) => rfl @[simp] theorem refl_trans {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (e : linear_isometry_equiv R E F) : trans (refl R E) e = e := ext fun (x : E) => rfl @[simp] theorem trans_symm {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (e : linear_isometry_equiv R E F) : trans e (symm e) = refl R E := ext (symm_apply_apply e) @[simp] theorem symm_trans {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (e : linear_isometry_equiv R E F) : trans (symm e) e = refl R F := ext (apply_symm_apply e) @[simp] theorem coe_symm_trans {R : Type u_1} {E : Type u_2} {F : Type u_3} {G : Type u_4} [semiring R] [normed_group E] [normed_group F] [normed_group G] [semimodule R E] [semimodule R F] [semimodule R G] (e₁ : linear_isometry_equiv R E F) (e₂ : linear_isometry_equiv R F G) : ⇑(symm (trans e₁ e₂)) = ⇑(symm e₁) ∘ ⇑(symm e₂) := rfl theorem trans_assoc {R : Type u_1} {E : Type u_2} {F : Type u_3} {G : Type u_4} {G' : Type u_5} [semiring R] [normed_group E] [normed_group F] [normed_group G] [normed_group G'] [semimodule R E] [semimodule R F] [semimodule R G] [semimodule R G'] (eEF : linear_isometry_equiv R E F) (eFG : linear_isometry_equiv R F G) (eGG' : linear_isometry_equiv R G G') : trans eEF (trans eFG eGG') = trans (trans eEF eFG) eGG' := rfl protected instance group {R : Type u_1} {E : Type u_2} [semiring R] [normed_group E] [semimodule R E] : group (linear_isometry_equiv R E E) := group.mk (fun (e₁ e₂ : linear_isometry_equiv R E E) => trans e₂ e₁) sorry (refl R E) trans_refl refl_trans symm (div_inv_monoid.div._default (fun (e₁ e₂ : linear_isometry_equiv R E E) => trans e₂ e₁) sorry (refl R E) trans_refl refl_trans symm) trans_symm @[simp] theorem coe_one {R : Type u_1} {E : Type u_2} [semiring R] [normed_group E] [semimodule R E] : ⇑1 = id := rfl @[simp] theorem coe_mul {R : Type u_1} {E : Type u_2} [semiring R] [normed_group E] [semimodule R E] (e : linear_isometry_equiv R E E) (e' : linear_isometry_equiv R E E) : ⇑(e * e') = ⇑e ∘ ⇑e' := rfl @[simp] theorem coe_inv {R : Type u_1} {E : Type u_2} [semiring R] [normed_group E] [semimodule R E] (e : linear_isometry_equiv R E E) : ⇑(e⁻¹) = ⇑(symm e) := rfl /-- Reinterpret a `linear_isometry_equiv` as a `continuous_linear_equiv`. -/ def to_continuous_linear_equiv {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (e : linear_isometry_equiv R E F) : continuous_linear_equiv R E F := continuous_linear_equiv.mk (to_linear_equiv e) @[simp] theorem map_zero {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (e : linear_isometry_equiv R E F) : coe_fn e 0 = 0 := linear_equiv.map_zero (to_linear_equiv e) @[simp] theorem map_add {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (e : linear_isometry_equiv R E F) (x : E) (y : E) : coe_fn e (x + y) = coe_fn e x + coe_fn e y := linear_equiv.map_add (to_linear_equiv e) x y @[simp] theorem map_sub {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (e : linear_isometry_equiv R E F) (x : E) (y : E) : coe_fn e (x - y) = coe_fn e x - coe_fn e y := linear_equiv.map_sub (to_linear_equiv e) x y @[simp] theorem map_smul {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (e : linear_isometry_equiv R E F) (c : R) (x : E) : coe_fn e (c • x) = c • coe_fn e x := linear_equiv.map_smul (to_linear_equiv e) c x @[simp] theorem nnnorm_map {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (e : linear_isometry_equiv R E F) (x : E) : nnnorm (coe_fn e x) = nnnorm x := linear_isometry.nnnorm_map (to_linear_isometry e) x @[simp] theorem dist_map {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (e : linear_isometry_equiv R E F) (x : E) (y : E) : dist (coe_fn e x) (coe_fn e y) = dist x y := linear_isometry.dist_map (to_linear_isometry e) x y @[simp] theorem edist_map {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (e : linear_isometry_equiv R E F) (x : E) (y : E) : edist (coe_fn e x) (coe_fn e y) = edist x y := linear_isometry.edist_map (to_linear_isometry e) x y protected theorem bijective {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (e : linear_isometry_equiv R E F) : function.bijective ⇑e := linear_equiv.bijective (to_linear_equiv e) protected theorem injective {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (e : linear_isometry_equiv R E F) : function.injective ⇑e := linear_equiv.injective (to_linear_equiv e) protected theorem surjective {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (e : linear_isometry_equiv R E F) : function.surjective ⇑e := linear_equiv.surjective (to_linear_equiv e) theorem map_eq_iff {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (e : linear_isometry_equiv R E F) {x : E} {y : E} : coe_fn e x = coe_fn e y ↔ x = y := function.injective.eq_iff (linear_isometry_equiv.injective e) theorem map_ne {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (e : linear_isometry_equiv R E F) {x : E} {y : E} (h : x ≠ y) : coe_fn e x ≠ coe_fn e y := function.injective.ne (linear_isometry_equiv.injective e) h protected theorem lipschitz {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (e : linear_isometry_equiv R E F) : lipschitz_with 1 ⇑e := isometry.lipschitz (linear_isometry_equiv.isometry e) protected theorem antilipschitz {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (e : linear_isometry_equiv R E F) : antilipschitz_with 1 ⇑e := isometry.antilipschitz (linear_isometry_equiv.isometry e) theorem ediam_image {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (e : linear_isometry_equiv R E F) (s : set E) : emetric.diam (⇑e '' s) = emetric.diam s := isometry.ediam_image (linear_isometry_equiv.isometry e) s theorem diam_image {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (e : linear_isometry_equiv R E F) (s : set E) : metric.diam (⇑e '' s) = metric.diam s := isometry.diam_image (linear_isometry_equiv.isometry e) s end Mathlib
615d62bd2a14b7a93c448497813bd75a42224534
7b4371534ac437ca8cfb325dd5c6638ff111d31a
/logic_util.lean
91993cac05192eafa4d1878cdd2fafbabb4380a9
[]
no_license
Shamrock-Frost/boolean_rings
6d78294568b6b9ad7b9c67b5de5e9545227826da
5da11beeaa37ec186c1deff946f2dbf7594fceb4
refs/heads/master
1,588,394,857,485
1,553,973,949,000
1,553,973,949,000
177,757,941
0
0
null
null
null
null
UTF-8
Lean
false
false
17,009
lean
instance {T} {S : set T} [h : decidable_pred S] : decidable_pred (set.compl S) := λ x, decidable.cases_on (h x) (λ h, is_true h) (λ h, is_false (λ h', h' h)) lemma and.distrib_left (P Q R : Prop) : P ∧ (Q ∨ R) ↔ (P ∧ Q) ∨ (P ∧ R) := iff.intro (assume h : P ∧ (Q ∨ R), have hp : P := and.left h, show (P ∧ Q) ∨ (P ∧ R), from h.right.cases_on (λ hq, or.inl (and.intro hp hq)) (λ hr, or.inr (and.intro hp hr))) (assume h : (P ∧ Q) ∨ (P ∧ R), show P ∧ (Q ∨ R), from or.cases_on h (λ hpq : P ∧ Q, and.intro hpq.left (or.inl hpq.right)) (λ hpr : P ∧ R, and.intro hpr.left (or.inr hpr.right))) lemma and.distrib_right (P Q R : Prop) : (Q ∨ R) ∧ P ↔ (Q ∧ P) ∨ (R ∧ P) := by { rw and_comm, rw and.distrib_left, rw and_comm P Q, rw and_comm P R, } lemma or.distrib_left (P Q R : Prop) : P ∨ (Q ∧ R) ↔ (P ∨ Q) ∧ (P ∨ R) := iff.intro (assume h : P ∨ (Q ∧ R), show (P ∨ Q) ∧ (P ∨ R), from h.cases_on (λ hp, and.intro (or.inl hp) (or.inl hp)) (λ hqr, and.intro (or.inr hqr.left) (or.inr hqr.right))) (by { intro h, cases h, cases h_left, { exact or.inl h_left }, { cases h_right, { exact or.inl h_right }, { apply or.inr, constructor; assumption } } }) lemma or.distrib_right (P Q R : Prop) : (Q ∧ R) ∨ P ↔ (Q ∨ P) ∧ (R ∨ P) := by { rw or_comm, rw or.distrib_left, rw or_comm P Q, rw or_comm P R } lemma not_or_iff_and_not (p q : Prop) : ¬(p ∨ q) ↔ ¬p ∧ ¬q := begin constructor; intro h, { constructor; intro h'; apply h, { apply or.inl, assumption }, { apply or.inr, assumption } }, { intro h', cases h, cases h', { exact h_left h' }, { exact h_right h' } } end lemma and_not_and (p q : Prop) : p ∧ ¬(p ∧ q) ↔ p ∧ ¬q := begin constructor; intro h; cases h, { constructor, assumption, intro hp, apply h_right, constructor; assumption }, { constructor, assumption, intro hpq, apply h_right, cases hpq, assumption } end lemma classical.exists_of_not_forall {T} {P : T → Prop} : (¬ ∀ x : T, P x) → ∃ x : T, ¬ P x := begin intro, apply classical.by_contradiction, intro h, apply a, intro x, cases classical.em (P x), { assumption }, { exfalso, apply h, existsi x, assumption } end lemma classical.implies_iff_or {P Q : Prop} : (P → Q) ↔ (¬ P ∨ Q) := begin constructor, { intro h, cases classical.em P, exact or.inr (h h_1), exact or.inl h_1 }, { intro h, cases h, exact false.elim ∘ h, exact λ _, h } end lemma classical.dne (P) : P ↔ ¬ ¬ P := iff.intro (λ h h', h' h) $ by { intro h, cases classical.em P, assumption, trivial } lemma subset_of_empty_iff_empty {T} {A : set T} : A ⊆ ∅ ↔ A = ∅ := by { simp [(⊆), set.subset], constructor, { intro h, funext, apply propext, constructor, { apply h }, { intro h, cases h } }, { intro h, rw h, intro, exact id } } lemma inter_subset_l {T} (A B : set T) : A ∩ B ⊆ A := λ _, and.left lemma inter_subset_r {T} (A B : set T) : A ∩ B ⊆ B := λ _, and.right lemma subset_union_l {T} (A B : set T) : A ⊆ A ∪ B := λ _, or.inl lemma subset_union_r {T} (A B : set T) : B ⊆ A ∪ B := λ _, or.inr def fun.im {A B : Type _} (f : A → B) := { b : B | ∃ a : A, f a = b } @[reducible] def disjoint {T} (A B : set T) := A ∩ B = ∅ lemma mk_disjoint {T} (A B : set T) : (∀ x : T, ¬ (A x ∧ B x)) → disjoint A B := by { intro h, dunfold disjoint, rw ← subset_of_empty_iff_empty, exact h } lemma elim_disjoint {T} {A B : set T} : disjoint A B → ∀ x : T, A x → B x → false := by { dunfold disjoint, intros h x ha hb, refine (_ : (∅ : set T) x), rw ← h, constructor; assumption } lemma disjoint_compl {T} (A : set T) : disjoint A (-A) := by { apply mk_disjoint, intros x h, exact h.right h.left } lemma disjoint_implies_disjoint_subset {T} {A B A' : set T} : A' ⊆ A → disjoint A B → disjoint A' B := by { intros, apply mk_disjoint, intros x h, apply elim_disjoint a_1 x (a h.left) h.right } lemma inter_comm {T} (A B : set T) : A ∩ B = B ∩ A := begin funext, apply propext, rw (_ : (A ∩ B) a ↔ A a ∧ B a), rw (_ : (B ∩ A) a ↔ B a ∧ A a), rw and_comm, all_goals {refl} end lemma disjoint_symm {T} (A B : set T) : disjoint A B ↔ disjoint B A := by { dunfold disjoint, rw inter_comm } lemma union_comm {T} (A B : set T) : A ∪ B = B ∪ A := begin funext, apply propext, rw (_ : (A ∪ B) a ↔ A a ∨ B a), rw (_ : (B ∪ A) a ↔ B a ∨ A a), rw or_comm, all_goals {refl} end lemma inter_assoc {T} (A B C : set T) : (A ∩ B) ∩ C = A ∩ (B ∩ C) := begin funext, apply propext, rw (_ : ((A ∩ B) ∩ C) a ↔ (A a ∧ B a) ∧ C a), rw (_ : (A ∩ (B ∩ C)) a ↔ A a ∧ (B a ∧ C a)), rw and_assoc, all_goals {refl} end lemma union_assoc {T} (A B C : set T) : (A ∪ B) ∪ C = A ∪ (B ∪ C) := begin funext, apply propext, rw (_ : ((A ∪ B) ∪ C) a ↔ (A a ∨ B a) ∨ C a), rw (_ : (A ∪ (B ∪ C)) a ↔ A a ∨ (B a ∨ C a)), rw or_assoc, all_goals {refl} end lemma compl_union {T} (A B : set T) : -(A ∪ B) = -A ∩ -B := begin funext, apply propext, rw (_ : (-(A ∪ B)) a ↔ ¬ (A a ∨ B a)), rw (_ : (- A ∩ - B) a ↔ ¬ (A a) ∧ ¬ (B a)), rw not_or_iff_and_not, all_goals {refl} end lemma compl_inter {T} (A B : set T) [decidable_pred A] [decidable_pred B] : -(A ∩ B) = -A ∪ -B := begin funext, apply propext, rw (_ : (-(A ∩ B)) a ↔ ¬ (A a ∧ B a)), rw (_ : (- A ∪ - B) a ↔ ¬ (A a) ∨ ¬ (B a)), rw decidable.not_and_iff_or_not, all_goals {refl} end lemma union_empty {T} (A : set T) : A ∪ ∅ = A := begin funext, apply propext, rw (_ : (A ∪ ∅) a ↔ A a ∨ false), rw or_false, refl end lemma inter_univ {T} (A : set T) : A ∩ set.univ = A := begin funext, apply propext, rw (_ : (A ∩ set.univ) a ↔ A a ∧ true), rw and_true, refl end lemma inter_empty {T} (A : set T) : A ∩ ∅ = ∅ := begin funext, apply propext, rw (_ : (A ∩ ∅) a ↔ A a ∧ false), rw and_false, refl, refl, end lemma union_self {T} (A : set T) : A ∪ A = A := begin funext, apply propext, rw (_ : (A ∪ A) a ↔ A a ∨ A a), rw or_self, refl end lemma inter_self {T} (A : set T) : A ∩ A = A := begin funext, apply propext, rw (_ : (A ∩ A) a ↔ A a ∧ A a), rw and_self, refl end lemma elem_singleton {T} (x : T) : {x} = { y : T | y = x } := by { rw (_ : {x} = {y : T | y = x} ∪ ∅), apply union_empty, refl } lemma compl_compl {T} (A : set T) [decidable_pred A] : - (- A) = A := begin funext, apply propext, rw (_ : (- (- A)) a = ¬ (¬ (A a))), rw decidable.not_not_iff, refl end lemma inter.distrib_left {T} (A B C : set T) : A ∩ (B ∪ C) = (A ∩ B) ∪ (A ∩ C) := begin funext, apply propext, rw (_ : (A ∩ (B ∪ C)) a ↔ A a ∧ (B a ∨ C a)), rw (_ : ((A ∩ B) ∪ (A ∩ C)) a ↔ (A a ∧ B a) ∨ (A a ∧ C a)), { rw and.distrib_left }, all_goals {refl} end lemma inter.distrib_right {T} (A B C : set T) : (B ∪ C) ∩ A = (B ∩ A) ∪ (C ∩ A) := by { rw inter_comm, rw inter.distrib_left, rw inter_comm A B, rw inter_comm A C } lemma union.distrib_left {T} (A B C : set T) : A ∪ (B ∩ C) = (A ∪ B) ∩ (A ∪ C) := begin funext, apply propext, rw (_ : (A ∪ (B ∩ C)) a ↔ A a ∨ (B a ∧ C a)), rw (_ : ((A ∪ B) ∩ (A ∪ C)) a ↔ (A a ∨ B a) ∧ (A a ∨ C a)), { rw or.distrib_left }, all_goals {refl} end lemma union.distrib_right {T} (A B C : set T) : (B ∩ C) ∪ A = (B ∪ A) ∩ (C ∪ A) := by { rw union_comm, rw union.distrib_left, rw union_comm A B, rw union_comm A C } lemma set.FOIL1 {T} (A B C D : set T) : (A ∪ B) ∩ (C ∪ D) = (A ∩ C) ∪ (B ∩ C) ∪ (A ∩ D) ∪ (B ∩ D) := begin rw inter.distrib_left, rw inter.distrib_right, rw inter.distrib_right, repeat { rw union_assoc }, end lemma set.FOIL2 {T} (A B C D : set T) : (A ∩ B) ∪ (C ∩ D) = (A ∪ C) ∩ (B ∪ C) ∩ (A ∪ D) ∩ (B ∪ D) := begin rw union.distrib_left, rw union.distrib_right, rw union.distrib_right, repeat { rw inter_assoc }, end def set_minus {T} (A B : set T) : set T := { x ∈ A | x ∉ B } infix `∖`:80 := set_minus lemma minus_is_subset {T} (A B : set T) : A ∖ B ⊆ A := λ _ h, h.left lemma minus_eq_inter_compl {T} (A B : set T) : A ∖ B = A ∩ (-B) := begin funext, apply propext, rw (_ : (A ∖ B) a ↔ A a ∧ ¬ (B a)), rw (_ : (A ∩ -B) a ↔ A a ∧ ¬ (B a)), refl, refl, end lemma minus_disj {T} (A B : set T) : disjoint (A ∖ B) B := begin rw [minus_eq_inter_compl], apply disjoint_implies_disjoint_subset, apply inter_subset_r, rw disjoint_symm, apply disjoint_compl end lemma union_minus {T} (A B C : set T) : (A ∪ B) ∖ C = (A ∖ C) ∪ (B ∖ C) := begin funext, apply propext, rw (_ : (((A ∪ B)∖C) a ↔ (A a ∨ B a) ∧ ¬ (C a))), rw (_ : ((A∖C) ∪ (B∖C)) a ↔ (A a ∧ ¬(C a)) ∨ (B a ∧ ¬(C a))), apply and.distrib_right, all_goals {refl} end lemma minus_subset_union_subset {T} {A A' : set T} [decidable_pred A] : A ⊆ A' → (A' ∖ A) ∪ A = A' := begin intros hsub, funext, apply propext, constructor, { intro h, cases h, { exact h.left }, { apply hsub, assumption } }, { intro h, by_cases h' : A a, { exact or.inr h' }, { exact or.inl ⟨h, h'⟩ } } end lemma minus_inter {T} (A B C : set T) [decidable_pred B] [decidable_pred C] : A ∖ (B ∩ C) = (A ∖ B) ∪ (A ∖ C) := begin funext, apply propext, rw (_ : (A∖(B ∩ C)) a ↔ A a ∧ ¬ (B a ∧ C a)), rw (_ : ((A∖B) ∪ (A∖C)) a ↔ (A a ∧ ¬ (B a)) ∨ (A a ∧ ¬ (C a))), { rw decidable.not_and_iff_or_not, apply and.distrib_left }, all_goals {refl} end lemma minus_union {T} (A B C : set T) : A ∖ (B ∪ C) = (A ∖ B) ∩ (A ∖ C) := begin funext, apply propext, rw (_ : (A∖(B ∪ C)) a ↔ A a ∧ ¬ (B a ∨ C a)), rw (_ : ((A∖B) ∩ (A∖C)) a ↔ (A a ∧ ¬ (B a)) ∧ (A a ∧ ¬ (C a))), rw [not_or_iff_and_not , and_assoc , ← and_assoc (¬ (B a)) (A a) , and_comm (¬ (B a)) (A a) , and_assoc , ← and_assoc (A a) (A a) , and_self ], all_goals {refl} end lemma minus_eq_minus_inter {T} (A B : set T) : A ∖ B = A ∖ (A ∩ B) := begin funext, apply propext, rw (_ : (A∖B) a ↔ A a ∧ ¬ B a), rw (_ : (A∖(A ∩ B)) a ↔ A a ∧ ¬ (A a ∧ B a)), { constructor; intro h; cases h; apply and.intro h_left; intro h'; apply h_right, { exact h'.right }, { exact and.intro h_left h' } }, all_goals {refl} end lemma minus_self {T} (A : set T) : A ∖ A = ∅ := begin funext, apply propext, constructor; intro h; exfalso, { have : A a ∧ ¬ (A a) := h, exact this.right this.left }, { exact h } end lemma minus_empty {T} (A : set T) : A∖∅ = A := begin funext, apply propext, rw (_ : (A ∖ ∅) a ↔ A a ∧ ¬ false), { rw [not_false_iff, and_true] }, refl end lemma minus_minus_eq_minus_union {T} (A B C : set T) : (A ∖ B) ∖ C = A ∖ (B ∪ C) := begin funext, apply propext, rw (_ : (A∖B∖C) a ↔ (A a ∧ ¬ (B a)) ∧ ¬ (C a)), rw (_ : (A ∖ (B ∪ C)) a ↔ A a ∧ ¬ (B a ∨ C a)), { rw and_assoc, rw not_or_iff_and_not }, all_goals {refl} end lemma minus_of_minus {T} (A B C : set T) [decidable_pred B] [decidable_pred C] : A ∖ (B ∖ C) = (A ∖ B) ∪ (A ∩ C) := begin rw minus_eq_inter_compl A B, rw ← inter.distrib_left, rw minus_eq_inter_compl A, rw minus_eq_inter_compl B, rw compl_inter B (-C), rw compl_compl end def symm_diff {T} (A B : set T) : set T := (A ∪ B) ∖ (A ∩ B) infix `Δ`:60 := symm_diff lemma symm_diff_def2 {T} (A B : set T) : A Δ B = (A ∖ B) ∪ (B ∖ A) := by { dsimp [(Δ)], rw union_minus, apply congr, { apply congr_arg, rw ← minus_eq_minus_inter }, { rw inter_comm, rw ← minus_eq_minus_inter } } lemma symm_diff_comm {T} (A B : set T) : A Δ B = B Δ A := by dsimp [(Δ)]; rw [inter_comm, union_comm] lemma minus_inter_inter_eq_empty {T} (A B : set T) : A∖B ∩ (A ∩ B) = ∅ := begin rw minus_eq_inter_compl, rw inter_assoc, rw ← inter_assoc (- B), rw inter_comm (-B), rw inter_assoc A (-B), rw inter_comm (-B), rw ← minus_eq_inter_compl, rw minus_self, rw inter_empty, rw inter_empty end lemma minus_of_symm_diff {T} (A B C : set T) [decidable_pred A] [decidable_pred B] [decidable_pred C] : C ∖ (A Δ B) = ((C ∖ A) ∩ (C ∖ B)) ∪ (C ∩ A ∩ B) := begin rw symm_diff_def2, rw ← minus_union, rw minus_union, rw [minus_of_minus, minus_of_minus], rw set.FOIL1, rw (_ : C ∩ B ∩ C∖B = ∅), rw (_ : C∖A ∩ (C ∩ A) = ∅), rw union_empty, rw union_empty, rw minus_union, have : C ∩ B ∩ (C ∩ A) = C ∩ A ∩ B, { rw ← inter_assoc, rw inter_comm C B, rw inter_assoc B C C, rw inter_self, rw inter_assoc, rw inter_comm }, rw this, { apply minus_inter_inter_eq_empty }, { rw inter_comm, apply minus_inter_inter_eq_empty } end lemma symm_diff_assoc {T} (A B C : set T) [decidable_pred A] [decidable_pred B] [decidable_pred C] : (A Δ B) Δ C = A Δ (B Δ C) := begin rw symm_diff_def2, rw minus_of_symm_diff, rw symm_diff_def2, rw symm_diff_def2, rw minus_of_symm_diff, rw symm_diff_def2, rw union_minus, rw minus_minus_eq_minus_union, rw minus_union, rw minus_minus_eq_minus_union, rw minus_union, rw union_minus, rw minus_minus_eq_minus_union, rw minus_union, rw minus_minus_eq_minus_union, rw minus_union, suffices : B∖A ∩ B∖C ∪ (C∖A ∩ C∖B ∪ C ∩ A ∩ B) = A ∩ B ∩ C ∪ (B∖C ∩ B∖A ∪ C∖B ∩ C∖A), { rw union_assoc, rw this, rw ← union_assoc }, rw ← union_assoc, rw ← union_assoc, rw union_comm, rw ← union_assoc, rw (_ : C ∩ A ∩ B = A ∩ B ∩ C), rw (_ : B∖A ∩ B∖C = B∖C ∩ B∖A), rw (_ : C∖A ∩ C∖B = C∖B ∩ C∖A), rw inter_comm, rw inter_comm, rw inter_assoc, rw inter_comm end lemma empty_symm_diff {T} (A : set T) : ∅ Δ A = A := by { intros, simp [(Δ)], rw [union_comm, inter_comm], rw [union_empty, inter_empty, minus_empty] } lemma symm_diff_self {T} (A : set T) : A Δ A = ∅ := by { dsimp [(Δ)], rw union_self, rw inter_self, apply minus_self } lemma left_distrib_inter_symm_diff {T} (A B C : set T) : A ∩ (B Δ C) = (A ∩ B) Δ (A ∩ C) := begin rw symm_diff_def2, rw symm_diff_def2, rw inter.distrib_left, have : ∀ A' B' C' : set T, A' ∩ B'∖C' = (A' ∩ B')∖(A' ∩ C'), { intros, rw minus_eq_inter_compl, rw minus_eq_inter_compl, suffices : A' ∩ -C' = A' ∩ -(A' ∩ C'), { rw ← inter_assoc, rw inter_comm, rw ← inter_assoc, rw inter_comm (-C'), rw this, rw inter_assoc, rw inter_assoc, rw inter_comm B' }, { funext, apply propext, rw (_ : (A' ∩ -C') a ↔ A' a ∧ ¬ (C' a)), rw (_ : (A' ∩ -(A' ∩ C')) a ↔ A' a ∧ ¬ (A' a ∧ C' a)), { rw and_not_and }, all_goals {refl} } }, rw ← this, rw ← this end lemma union_decomp_symm {T} (A B : set T) [decidable_pred A] [decidable_pred B] : A ∪ B = (A Δ B) ∪ (A ∩ B) := begin dsimp [(Δ)], symmetry, apply @minus_subset_union_subset _ _ _ _, exact λ _, or.inl ∘ and.left, intro x, by_cases h : A x; by_cases h' : B x, { apply decidable.is_true, constructor; assumption }, { apply decidable.is_false, intro h'', cases h'', apply h', assumption }, all_goals { apply decidable.is_false, intro h'', cases h'', apply h, assumption } end lemma union_decomp_l {T} (A B : set T) [decidable_pred A] : A ∪ B = A ∪ (B ∖ A) := begin funext x, apply propext, constructor; intro h, { by_cases h' : A x, { exact or.inl h' }, { cases h, { exfalso, apply h', assumption }, apply or.inr, constructor; assumption } }, { cases h, exact or.inl h, exact or.inr (minus_is_subset _ _ h) } end lemma union_decomp_r {T} (A B : set T) [decidable_pred B] : A ∪ B = (A ∖ B) ∪ B := begin transitivity B ∪ A, apply union_comm, transitivity B ∪ (A ∖ B), apply union_decomp_l, apply union_comm end lemma symm_diff_disj_inter {T} (A B : set T) : disjoint (A Δ B) (A ∩ B) := minus_disj (A ∪ B) (A ∩ B) lemma decomp {T} (A B : set T) [decidable_pred B] : A = (A ∖ B) ∪ (A ∩ B) := begin funext, apply propext, constructor, { intro h, by_cases h' : B x, { apply or.inr, constructor; assumption }, { apply or.inl, constructor; assumption } }, { intro h, cases h; cases h; assumption } end def subset_of_subtype_to_subset {A : Type _} {P : A → Prop} : set (subtype P) → set A := λ S, { a : A | ∃ h : P a, S ⟨a, h⟩ }
1787387a26f20c36d3cde3cb31603fba60929775
9ad8d18fbe5f120c22b5e035bc240f711d2cbd7e
/src/combinatorics/erase.lean
dcc9e403b9310625da54bed48e894a42dd64bfc3
[]
no_license
agusakov/lean_lib
c0e9cc29fc7d2518004e224376adeb5e69b5cc1a
f88d162da2f990b87c4d34f5f46bbca2bbc5948e
refs/heads/master
1,642,141,461,087
1,557,395,798,000
1,557,395,798,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,815
lean
/- Copyright (c) 2019 Neil Strickland. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Neil Strickland This is about the obvious bijection (X \ {x}) ∐ 1 ≃ X, or (option (erase a)) ≃ α in Lean notation. -/ import data.fintype namespace combinatorics variables {α : Type*} [fintype α] [decidable_eq α] def erase (a : α) := {b : α // b ≠ a} namespace erase instance (a : α) : decidable_eq (erase a) := by { apply_instance } instance (a : α) : fintype (erase a) := by { dsimp[erase], apply_instance } def option_equiv (a : α) : option (erase a) ≃ α := begin let to_fun : option (erase a) → α := λ x, @option.cases_on (erase a) (λ _, α) x a (λ b,b.val), have to_fun_none : to_fun none = a := rfl, have to_fun_some : ∀ b, to_fun (some b) = b.val := λ b,rfl, let inv_fun : ∀ b : α, option (erase a) := λ b, (if h : b = a then none else (some ⟨b,h⟩)), have inv_fun_a : inv_fun a = none := dif_pos rfl, have inv_fun_not_a : ∀ (b : α) (h : b ≠ a), inv_fun b = some ⟨b,h⟩ := λ b h,dif_neg h, have left_inv : function.left_inverse inv_fun to_fun := begin rintro (_ | ⟨b,b_ne_a⟩), {rw[to_fun_none,inv_fun_a],}, {rw[to_fun_some,inv_fun_not_a],} end, have right_inv : function.right_inverse inv_fun to_fun := begin intro b, by_cases h : b = a, {rw[h,inv_fun_a]}, {rw[inv_fun_not_a b h]} end, exact ⟨to_fun,inv_fun,left_inv,right_inv⟩, end lemma card (a : α) : fintype.card (erase a) + 1 = fintype.card α := (@fintype.card_option (erase a) _).symm.trans (fintype.card_congr (option_equiv a)) def inc {a : α} (b : erase a) : α := b.val def inc_inj (a : α) : function.injective (@inc α _ _ a) := λ b₁ b₂ e, subtype.eq e end erase end combinatorics
911545310fe059dd37981cfa44919b36ffce724a
38bf3fd2bb651ab70511408fcf70e2029e2ba310
/src/category_theory/concrete_category/bundled_hom.lean
3afa1db2e89508bcdd5495060066f89b67530286
[ "Apache-2.0" ]
permissive
JaredCorduan/mathlib
130392594844f15dad65a9308c242551bae6cd2e
d5de80376088954d592a59326c14404f538050a1
refs/heads/master
1,595,862,206,333
1,570,816,457,000
1,570,816,457,000
209,134,499
0
0
Apache-2.0
1,568,746,811,000
1,568,746,811,000
null
UTF-8
Lean
false
false
5,061
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Yury Kudryashov -/ import category_theory.concrete_category.basic import category_theory.concrete_category.bundled /-! # Category instances for algebraic structures that use bundled homs. Many algebraic structures in Lean initially used unbundled homs (e.g. a bare function between types, along with an `is_monoid_hom` typeclass), but the general trend is towards using bundled homs. This file provides a basic infrastructure to define concrete categories using bundled homs, and define forgetful functors between them. -/ universes u namespace category_theory variables {c : Type u → Type u} (hom : Π ⦃α β : Type u⦄ (Iα : c α) (Iβ : c β), Type u) /-- Class for bundled homs. Note that the arguments order follows that of lemmas for `monoid_hom`. This way we can use `⟨@monoid_hom.to_fun, @monoid_hom.id ...⟩` in an instance. -/ structure bundled_hom := (to_fun : Π {α β : Type u} (Iα : c α) (Iβ : c β), hom Iα Iβ → α → β) (id : Π {α : Type u} (I : c α), hom I I) (comp : Π {α β γ : Type u} (Iα : c α) (Iβ : c β) (Iγ : c γ), hom Iβ Iγ → hom Iα Iβ → hom Iα Iγ) (hom_ext : ∀ {α β : Type u} (Iα : c α) (Iβ : c β), function.injective (to_fun Iα Iβ) . obviously) (id_to_fun : ∀ {α : Type u} (I : c α), to_fun I I (id I) = _root_.id . obviously) (comp_to_fun : ∀ {α β γ : Type u} (Iα : c α) (Iβ : c β) (Iγ : c γ) (f : hom Iα Iβ) (g : hom Iβ Iγ), to_fun Iα Iγ (comp Iα Iβ Iγ g f) = (to_fun Iβ Iγ g) ∘ (to_fun Iα Iβ f) . obviously) attribute [class] bundled_hom attribute [simp] bundled_hom.id_to_fun bundled_hom.comp_to_fun namespace bundled_hom variable [𝒞 : bundled_hom hom] include 𝒞 /-- Every `@bundled_hom c _` defines a category with objects in `bundled c`. -/ instance : category (bundled c) := by refine { hom := λ X Y, @hom X.1 Y.1 X.str Y.str, id := λ X, @bundled_hom.id c hom 𝒞 X X.str, comp := λ X Y Z f g, @bundled_hom.comp c hom 𝒞 X Y Z X.str Y.str Z.str g f, comp_id' := _, id_comp' := _, assoc' := _}; intros; apply 𝒞.hom_ext; simp only [𝒞.id_to_fun, 𝒞.comp_to_fun, function.left_id, function.right_id] /-- A category given by `bundled_hom` is a concrete category. -/ instance concrete_category : concrete_category (bundled c) := { forget := { obj := λ X, X, map := λ X Y f, 𝒞.to_fun X.str Y.str f, map_id' := λ X, 𝒞.id_to_fun X.str, map_comp' := by intros; erw 𝒞.comp_to_fun; refl }, forget_faithful := { injectivity' := by intros; apply 𝒞.hom_ext } } /-- Usually a bundled hom structure already has a coercion to function that works with different universes. So we don't use this as an instance. -/ def has_coe_to_fun {X Y : bundled c} : has_coe_to_fun (X ⟶ Y) := { F := λ f, X → Y, coe := λ f, (forget _).map f } local attribute [instance] has_coe_to_fun @[simp] lemma coe_id {X : bundled c} : ((𝟙 X) : X → X) = _root_.id := (forget _).map_id X @[simp] lemma coe_comp {X Y Z : bundled c} (f : X ⟶ Y) (g : Y ⟶ Z) (x : X) : (f ≫ g) x = g (f x) := congr_fun ((forget _).map_comp _ _) x section full_subcategory variables {hom} (𝒞) {d : Type u → Type u} (obj : Π ⦃α⦄, d α → c α) include obj /-- Construct a `bundled_hom` representing a full subcategory of a given `bundled_hom` category. The corresponding `category` and `concrete_category` instances agree with `induced_category (bundled.map @obj)`. -/ protected def full_subcategory : bundled_hom (λ α β (Iα : d α) (Iβ : d β), hom (obj Iα) (obj Iβ)) := { to_fun := by intros; apply 𝒞.to_fun; assumption, id := by intros; apply 𝒞.id, comp := by intros; apply 𝒞.comp; assumption, hom_ext := by intros; apply 𝒞.hom_ext, id_to_fun := by intros; apply 𝒞.id_to_fun, comp_to_fun := by intros; apply 𝒞.comp_to_fun } /-- A full subcategory of a concrete category with bundled homs has a forgetful functor to the entire category. This is used to construct instances of `has_forget` in many concrete examples. -/ def full_subcategory_has_forget₂ : @has_forget₂ (bundled d) (bundled c) (by haveI := 𝒞.full_subcategory obj; apply_instance) (by apply_instance) := induced_category.has_forget₂ (bundled.map @obj) end full_subcategory variables {hom} /-- A version of `has_forget₂.mk'` for categories defined using `@bundled_hom`. -/ def mk_has_forget₂ {d : Type u → Type u} {hom_d : Π ⦃α β : Type u⦄ (Iα : d α) (Iβ : d β), Type u} [bundled_hom hom_d] (obj : Π ⦃α⦄, c α → d α) (map : Π {X Y : bundled c}, (X ⟶ Y) → ((bundled.map obj X) ⟶ (bundled.map obj Y))) (h_map : ∀ {X Y : bundled c} (f : X ⟶ Y), (map f : X → Y) = f) : has_forget₂ (bundled c) (bundled d) := has_forget₂.mk' (bundled.map @obj) (λ _, rfl) @map (by intros; apply heq_of_eq; apply h_map) end bundled_hom end category_theory
0fc732251f6c8dc221073a1a082dc8a2e20becb3
32025d5c2d6e33ad3b6dd8a3c91e1e838066a7f7
/tests/lean/run/core.lean
78e2b9b218a7922e1e39585b16dd0c34862e5fca
[ "Apache-2.0" ]
permissive
walterhu1015/lean4
b2c71b688975177402758924eaa513475ed6ce72
2214d81e84646a905d0b20b032c89caf89c737ad
refs/heads/master
1,671,342,096,906
1,599,695,985,000
1,599,695,985,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
294
lean
import Lean.CoreM open Lean open Lean.Core def f : CoreM Nat := do { env ← getEnv; cinfo ← getConstInfo `Nat.add; trace! `Elab "trace message"; liftIO $ IO.println $ toString cinfo.type; liftIO $ IO.println "testing..."; pure 10 } #eval f set_option trace.Elab true #eval f
ecda0bc37251d487aaac619135ef3f2a6c01dda6
976d2334b51721ddc405deb2e1754016d454286e
/lean_at_mc2020_source/source/solutions/exercise_induction.lean
61deb4733f6f7900a29828b4fc472762adf1887b
[]
no_license
kbuzzard/lean-at-MC2020
11bb6ac9ec38a6caace9d5d9a1705d6794d9f477
1f7ca65a7ba5cc17eb49f525c02dc6b0e65d6543
refs/heads/master
1,668,496,422,317
1,594,131,838,000
1,594,131,838,000
277,877,735
0
0
null
1,594,142,006,000
1,594,142,005,000
null
UTF-8
Lean
false
false
2,666
lean
import tactic import data.int.basic -- a rw puzzle? example (p : ℕ → Prop) (n : ℕ) (hn : p n) (h8 : ∀ n, p n ↔ p (n + 8)) (h3 : ∀ n, p (n + 3) ↔ p n) : p (n + 1) := begin rw ← h3 at hn, rw ← h3 at hn, rw ← h3 at hn, rw h8, exact hn, end -- example : fin 0 ≠ fin 1 := begin have : ∃ b : fin 1, true, use 0, intro h, rw ← h at this, cases this with k hk, cases k, linarith, end -- when i started i thought this would be a rw puzzle, but it's not theorem reflexive_of_symmetric_and_transitive (r : ℕ → ℕ → Prop) (h_symm : symmetric r) (h_trans : transitive r) (h_connected : ∀ x, ∃ y, r x y) : reflexive r := begin intro x, have hxy := h_connected x, cases hxy with y hy, apply h_trans hy, apply h_symm hy, end lemma even_or_odd (n : ℕ) : (∃ k, n = 2 * k) ∨ ∃ k, n = 2 * k + 1 := begin induction n with d hd, { use 0, simp }, -- you should ~always do this rw after opening the successor case of induction on the naturals rw nat.succ_eq_add_one, cases hd with h_even h_odd, { cases h_even with k hk, right, use k, rw hk }, cases h_odd with k hk, left, use k+1, rw hk, ring, end -- I don't think I can do this without coercions example (p : ℤ → Prop) (p_succ : ∀ n, p n → p (n + 1)) (p_pred : ∀ n, p n → p (n - 1)) : (∀ n, p n) ↔ p 0 := begin have key1 : ∀ n, p n ↔ p (n+1), { intro, split; intro h, { apply p_succ, assumption }, have := p_pred (n+1), ring at this, apply this, assumption }, split; intro h, { apply h }, intro n, cases n, -- rintro ⟨n⟩ also works { induction n with d hd, {simpa}, rw nat.succ_eq_add_one, simp only [int.coe_nat_succ, int.of_nat_eq_coe], rwa ← key1 }, induction n with d hd, { rw key1, simpa }, rw nat.succ_eq_add_one, rw key1, simpa, end open_locale big_operators open finset -- by landing in ℤ, we avoid the perils of nat subtraction def f : ℕ → ℕ | 0 := 0 | (n + 1) := n + 1 + f n example : f 1 = 1 := begin unfold f, end example (n : ℕ) : 2 * f n = n * (n + 1) := begin induction n with d hd, -- base case { unfold f, simp }, rw nat.succ_eq_add_one, unfold f, ring, rw hd, ring, end variables {R : Type*} [comm_ring R] example (n : ℕ) (a : R) : (1 - a) * ∑ k in range n, a ^ k = 1 - a ^ n := begin rw mul_sum, apply sum_range_induction, { simp }, intro, ring, end -- doing your induction "by hand" example (n : ℕ) (a : R) : (1 - a) * ∑ k in range n, a^k = 1 - a ^n := begin induction n with d hd, { simp }, rw [sum_range_succ, mul_add, hd, nat.succ_eq_add_one], ring_exp, end
04f5af4dad6b5e7ed2ff5bbc7f0800360b40f3c7
5d76f062116fa5bd22eda20d6fd74da58dba65bb
/src/snarks/babysnark/vars.lean
43ab0475f5df790fa600305ab94ce45839771e22
[]
no_license
brando90/formal_baby_snark
59e4732dfb43f97776a3643f2731262f58d2bb81
4732da237784bd461ff949729cc011db83917907
refs/heads/master
1,682,650,246,414
1,621,103,975,000
1,621,103,975,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
201
lean
section /-- An inductive type from which to index the variables of the 3-variable polynomials the proof manages -/ @[derive decidable_eq] inductive vars : Type | X : vars | Y : vars | Z : vars end
00b95fd49a6e957237a8e4b471f612506fd73eae
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/data/int/cast.lean
516d76b8882162e5255286428e99d89f4629e846
[ "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
11,658
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.int.basic import data.nat.cast /-! # Cast of integers This file defines the *canonical* homomorphism from the integers into a type `α` with `0`, `1`, `+` and `-` (typically a `ring`). ## Main declarations * `cast`: Canonical homomorphism `ℤ → α` where `α` has a `0`, `1`, `+` and `-`. * `cast_add_hom`: `cast` bundled as an `add_monoid_hom`. * `cast_ring_hom`: `cast` bundled as a `ring_hom`. ## Implementation note Setting up the coercions priorities is tricky. See Note [coercion into rings]. -/ open nat namespace int @[simp, push_cast] theorem nat_cast_eq_coe_nat : ∀ n, @coe ℕ ℤ (@coe_to_lift _ _ nat.cast_coe) n = @coe ℕ ℤ (@coe_to_lift _ _ (@coe_base _ _ int.has_coe)) n | 0 := rfl | (n+1) := congr_arg (+(1:ℤ)) (nat_cast_eq_coe_nat n) /-- Coercion `ℕ → ℤ` as a `ring_hom`. -/ def of_nat_hom : ℕ →+* ℤ := ⟨coe, rfl, int.of_nat_mul, rfl, int.of_nat_add⟩ section cast variables {α : Type*} section variables [has_zero α] [has_one α] [has_add α] [has_neg α] /-- Canonical homomorphism from the integers to any ring(-like) structure `α` -/ protected def cast : ℤ → α | (n : ℕ) := n | -[1+ n] := -(n+1) -- see Note [coercion into rings] @[priority 900] instance cast_coe : has_coe_t ℤ α := ⟨int.cast⟩ @[simp, norm_cast] theorem cast_zero : ((0 : ℤ) : α) = 0 := rfl theorem cast_of_nat (n : ℕ) : (of_nat n : α) = n := rfl @[simp, norm_cast] theorem cast_coe_nat (n : ℕ) : ((n : ℤ) : α) = n := rfl theorem cast_coe_nat' (n : ℕ) : (@coe ℕ ℤ (@coe_to_lift _ _ nat.cast_coe) n : α) = n := by simp @[simp, norm_cast] theorem cast_neg_succ_of_nat (n : ℕ) : (-[1+ n] : α) = -(n + 1) := rfl end @[simp, norm_cast] theorem cast_one [add_monoid α] [has_one α] [has_neg α] : ((1 : ℤ) : α) = 1 := nat.cast_one @[simp] theorem cast_sub_nat_nat [add_group α] [has_one α] (m n) : ((int.sub_nat_nat m n : ℤ) : α) = m - n := begin unfold sub_nat_nat, cases e : n - m, { simp [sub_nat_nat, e, nat.le_of_sub_eq_zero e] }, { rw [sub_nat_nat, cast_neg_succ_of_nat, ← nat.cast_succ, ← e, nat.cast_sub $ _root_.le_of_lt $ nat.lt_of_sub_eq_succ e, neg_sub] }, end @[simp, norm_cast] theorem cast_neg_of_nat [add_group α] [has_one α] : ∀ n, ((neg_of_nat n : ℤ) : α) = -n | 0 := neg_zero.symm | (n+1) := rfl @[simp, norm_cast] theorem cast_add [add_group α] [has_one α] : ∀ m n, ((m + n : ℤ) : α) = m + n | (m : ℕ) (n : ℕ) := nat.cast_add _ _ | (m : ℕ) -[1+ n] := by simpa only [sub_eq_add_neg] using cast_sub_nat_nat _ _ | -[1+ m] (n : ℕ) := (cast_sub_nat_nat _ _).trans $ sub_eq_of_eq_add $ show (n:α) = -(m+1) + n + (m+1), by rw [add_assoc, ← cast_succ, ← nat.cast_add, add_comm, nat.cast_add, cast_succ, neg_add_cancel_left] | -[1+ m] -[1+ n] := show -((m + n + 1 + 1 : ℕ) : α) = -(m + 1) + -(n + 1), begin rw [← neg_add_rev, ← nat.cast_add_one, ← nat.cast_add_one, ← nat.cast_add], apply congr_arg (λ x:ℕ, -(x:α)), ac_refl end @[simp, norm_cast] theorem cast_neg [add_group α] [has_one α] : ∀ n, ((-n : ℤ) : α) = -n | (n : ℕ) := cast_neg_of_nat _ | -[1+ n] := (neg_neg _).symm @[simp, norm_cast] theorem cast_sub [add_group α] [has_one α] (m n) : ((m - n : ℤ) : α) = m - n := by simp [sub_eq_add_neg] @[simp, norm_cast] theorem cast_mul [ring α] : ∀ m n, ((m * n : ℤ) : α) = m * n | (m : ℕ) (n : ℕ) := nat.cast_mul _ _ | (m : ℕ) -[1+ n] := (cast_neg_of_nat _).trans $ show (-(m * (n + 1) : ℕ) : α) = m * -(n + 1), by rw [nat.cast_mul, nat.cast_add_one, neg_mul_eq_mul_neg] | -[1+ m] (n : ℕ) := (cast_neg_of_nat _).trans $ show (-((m + 1) * n : ℕ) : α) = -(m + 1) * n, by rw [nat.cast_mul, nat.cast_add_one, neg_mul_eq_neg_mul] | -[1+ m] -[1+ n] := show (((m + 1) * (n + 1) : ℕ) : α) = -(m + 1) * -(n + 1), by rw [nat.cast_mul, nat.cast_add_one, nat.cast_add_one, neg_mul_neg] /-- `coe : ℤ → α` as an `add_monoid_hom`. -/ def cast_add_hom (α : Type*) [add_group α] [has_one α] : ℤ →+ α := ⟨coe, cast_zero, cast_add⟩ @[simp] lemma coe_cast_add_hom [add_group α] [has_one α] : ⇑(cast_add_hom α) = coe := rfl /-- `coe : ℤ → α` as a `ring_hom`. -/ def cast_ring_hom (α : Type*) [ring α] : ℤ →+* α := ⟨coe, cast_one, cast_mul, cast_zero, cast_add⟩ @[simp] lemma coe_cast_ring_hom [ring α] : ⇑(cast_ring_hom α) = coe := rfl lemma cast_commute [ring α] (m : ℤ) (x : α) : commute ↑m x := int.cases_on m (λ n, n.cast_commute x) (λ n, ((n+1).cast_commute x).neg_left) lemma cast_comm [ring α] (m : ℤ) (x : α) : (m : α) * x = x * m := (cast_commute m x).eq lemma commute_cast [ring α] (x : α) (m : ℤ) : commute x m := (m.cast_commute x).symm @[simp, norm_cast] theorem coe_nat_bit0 (n : ℕ) : (↑(bit0 n) : ℤ) = bit0 ↑n := by {unfold bit0, simp} @[simp, norm_cast] theorem coe_nat_bit1 (n : ℕ) : (↑(bit1 n) : ℤ) = bit1 ↑n := by {unfold bit1, unfold bit0, simp} @[simp, norm_cast] theorem cast_bit0 [ring α] (n : ℤ) : ((bit0 n : ℤ) : α) = bit0 n := cast_add _ _ @[simp, norm_cast] theorem cast_bit1 [ring α] (n : ℤ) : ((bit1 n : ℤ) : α) = bit1 n := by rw [bit1, cast_add, cast_one, cast_bit0]; refl lemma cast_two [ring α] : ((2 : ℤ) : α) = 2 := by simp theorem cast_mono [ordered_ring α] : monotone (coe : ℤ → α) := begin intros m n h, rw ← sub_nonneg at h, lift n - m to ℕ using h with k, rw [← sub_nonneg, ← cast_sub, ← h_1, cast_coe_nat], exact k.cast_nonneg end @[simp] theorem cast_nonneg [ordered_ring α] [nontrivial α] : ∀ {n : ℤ}, (0 : α) ≤ n ↔ 0 ≤ n | (n : ℕ) := by simp | -[1+ n] := have -(n:α) < 1, from lt_of_le_of_lt (by simp) zero_lt_one, by simpa [(neg_succ_lt_zero n).not_le, ← sub_eq_add_neg, le_neg] using this.not_le @[simp, norm_cast] theorem cast_le [ordered_ring α] [nontrivial α] {m n : ℤ} : (m : α) ≤ n ↔ m ≤ n := by rw [← sub_nonneg, ← cast_sub, cast_nonneg, sub_nonneg] theorem cast_strict_mono [ordered_ring α] [nontrivial α] : strict_mono (coe : ℤ → α) := strict_mono_of_le_iff_le $ λ m n, cast_le.symm @[simp, norm_cast] theorem cast_lt [ordered_ring α] [nontrivial α] {m n : ℤ} : (m : α) < n ↔ m < n := cast_strict_mono.lt_iff_lt @[simp] theorem cast_nonpos [ordered_ring α] [nontrivial α] {n : ℤ} : (n : α) ≤ 0 ↔ n ≤ 0 := by rw [← cast_zero, cast_le] @[simp] theorem cast_pos [ordered_ring α] [nontrivial α] {n : ℤ} : (0 : α) < n ↔ 0 < n := by rw [← cast_zero, cast_lt] @[simp] theorem cast_lt_zero [ordered_ring α] [nontrivial α] {n : ℤ} : (n : α) < 0 ↔ n < 0 := by rw [← cast_zero, cast_lt] @[simp, norm_cast] theorem cast_min [linear_ordered_ring α] {a b : ℤ} : (↑(min a b) : α) = min a b := monotone.map_min cast_mono @[simp, norm_cast] theorem cast_max [linear_ordered_ring α] {a b : ℤ} : (↑(max a b) : α) = max a b := monotone.map_max cast_mono @[simp, norm_cast] theorem cast_abs [linear_ordered_ring α] {q : ℤ} : ((|q| : ℤ) : α) = |q| := by simp [abs_eq_max_neg] lemma cast_nat_abs {R : Type*} [linear_ordered_ring R] : ∀ (n : ℤ), (n.nat_abs : R) = |n| | (n : ℕ) := by simp only [int.nat_abs_of_nat, int.cast_coe_nat, nat.abs_cast] | -[1+n] := by simp only [int.nat_abs, int.cast_neg_succ_of_nat, abs_neg, ← nat.cast_succ, nat.abs_cast] lemma coe_int_dvd [comm_ring α] (m n : ℤ) (h : m ∣ n) : (m : α) ∣ (n : α) := ring_hom.map_dvd (int.cast_ring_hom α) h end cast end int namespace prod variables {α : Type*} {β : Type*} [has_zero α] [has_one α] [has_add α] [has_neg α] [has_zero β] [has_one β] [has_add β] [has_neg β] @[simp] lemma fst_int_cast (n : ℤ) : (n : α × β).fst = n := by induction n; simp * @[simp] lemma snd_int_cast (n : ℤ) : (n : α × β).snd = n := by induction n; simp * end prod open int namespace add_monoid_hom variables {A : Type*} /-- Two additive monoid homomorphisms `f`, `g` from `ℤ` to an additive monoid are equal if `f 1 = g 1`. -/ @[ext] theorem ext_int [add_monoid A] {f g : ℤ →+ A} (h1 : f 1 = g 1) : f = g := have f.comp (int.of_nat_hom : ℕ →+ ℤ) = g.comp (int.of_nat_hom : ℕ →+ ℤ) := ext_nat h1, have ∀ n : ℕ, f n = g n := ext_iff.1 this, ext $ λ n, int.cases_on n this $ λ n, eq_on_neg (this $ n + 1) variables [add_group A] [has_one A] theorem eq_int_cast_hom (f : ℤ →+ A) (h1 : f 1 = 1) : f = int.cast_add_hom A := ext_int $ by simp [h1] theorem eq_int_cast (f : ℤ →+ A) (h1 : f 1 = 1) : ∀ n : ℤ, f n = n := ext_iff.1 (f.eq_int_cast_hom h1) end add_monoid_hom namespace monoid_hom variables {M : Type*} [monoid M] open multiplicative @[ext] theorem ext_mint {f g : multiplicative ℤ →* M} (h1 : f (of_add 1) = g (of_add 1)) : f = g := monoid_hom.ext $ add_monoid_hom.ext_iff.mp $ @add_monoid_hom.ext_int _ _ f.to_additive g.to_additive h1 /-- If two `monoid_hom`s agree on `-1` and the naturals then they are equal. -/ @[ext] theorem ext_int {f g : ℤ →* M} (h_neg_one : f (-1) = g (-1)) (h_nat : f.comp int.of_nat_hom.to_monoid_hom = g.comp int.of_nat_hom.to_monoid_hom) : f = g := begin ext (x | x), { exact (monoid_hom.congr_fun h_nat x : _), }, { rw [int.neg_succ_of_nat_eq, ← neg_one_mul, f.map_mul, g.map_mul], congr' 1, exact_mod_cast (monoid_hom.congr_fun h_nat (x + 1) : _), } end end monoid_hom namespace monoid_with_zero_hom variables {M : Type*} [monoid_with_zero M] /-- If two `monoid_with_zero_hom`s agree on `-1` and the naturals then they are equal. -/ @[ext] theorem ext_int {f g : monoid_with_zero_hom ℤ M} (h_neg_one : f (-1) = g (-1)) (h_nat : f.comp int.of_nat_hom.to_monoid_with_zero_hom = g.comp int.of_nat_hom.to_monoid_with_zero_hom) : f = g := to_monoid_hom_injective $ monoid_hom.ext_int h_neg_one $ monoid_hom.ext (congr_fun h_nat : _) /-- If two `monoid_with_zero_hom`s agree on `-1` and the _positive_ naturals then they are equal. -/ theorem ext_int' {φ₁ φ₂ : monoid_with_zero_hom ℤ M} (h_neg_one : φ₁ (-1) = φ₂ (-1)) (h_pos : ∀ n : ℕ, 0 < n → φ₁ n = φ₂ n) : φ₁ = φ₂ := ext_int h_neg_one $ ext_nat h_pos end monoid_with_zero_hom namespace ring_hom variables {α : Type*} {β : Type*} [ring α] [ring β] @[simp] lemma eq_int_cast (f : ℤ →+* α) (n : ℤ) : f n = n := f.to_add_monoid_hom.eq_int_cast f.map_one n lemma eq_int_cast' (f : ℤ →+* α) : f = int.cast_ring_hom α := ring_hom.ext f.eq_int_cast @[simp] lemma map_int_cast (f : α →+* β) (n : ℤ) : f n = n := (f.comp (int.cast_ring_hom α)).eq_int_cast n lemma ext_int {R : Type*} [semiring R] (f g : ℤ →+* R) : f = g := coe_add_monoid_hom_injective $ add_monoid_hom.ext_int $ f.map_one.trans g.map_one.symm instance int.subsingleton_ring_hom {R : Type*} [semiring R] : subsingleton (ℤ →+* R) := ⟨ring_hom.ext_int⟩ end ring_hom @[simp, norm_cast] theorem int.cast_id (n : ℤ) : ↑n = n := ((ring_hom.id ℤ).eq_int_cast n).symm namespace pi variables {α β : Type*} lemma int_apply [has_zero β] [has_one β] [has_add β] [has_neg β] : ∀ (n : ℤ) (a : α), (n : α → β) a = n | (n:ℕ) a := pi.nat_apply n a | -[1+n] a := by rw [cast_neg_succ_of_nat, cast_neg_succ_of_nat, neg_apply, add_apply, one_apply, nat_apply] @[simp] lemma coe_int [has_zero β] [has_one β] [has_add β] [has_neg β] (n : ℤ) : (n : α → β) = λ _, n := by { ext, rw pi.int_apply } end pi
2cf1f9f56346ac8273a910346d7d723fb1514c5d
ee8cdbabf07f77e7be63a449b8483ce308d37218
/lean/src/test/amc12b-2002-p4.lean
ee573dd160afe630ecf92c92bf1fb9b7c7c0c9d7
[ "MIT", "Apache-2.0" ]
permissive
zeta1999/miniF2F
6d66c75d1c18152e224d07d5eed57624f731d4b7
c1ba9629559c5273c92ec226894baa0c1ce27861
refs/heads/main
1,681,897,460,642
1,620,646,361,000
1,620,646,361,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
316
lean
/- Copyright (c) 2021 OpenAI. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kunhao Zheng -/ import data.real.basic import data.rat.basic open_locale rat example (n : ℕ+) (h₀ : ( 1 /. 2 + 1 /. 3 + 1 /. 7 + 1 /. ↑n ).denom = 1 ) : n = 42 := begin sorry end
f5c29881fd033a13190d71917450040e6369ea60
5ee26964f602030578ef0159d46145dd2e357ba5
/src/for_mathlib/topology.lean
3fcc015fa708af1de3573e7d8f7c799cc5e98945
[ "Apache-2.0" ]
permissive
fpvandoorn/lean-perfectoid-spaces
569b4006fdfe491ca8b58dd817bb56138ada761f
06cec51438b168837fc6e9268945735037fd1db6
refs/heads/master
1,590,154,571,918
1,557,685,392,000
1,557,685,392,000
186,363,547
0
0
Apache-2.0
1,557,730,933,000
1,557,730,933,000
null
UTF-8
Lean
false
false
8,457
lean
import topology.opens import topology.uniform_space.cauchy import topology.algebra.group import for_mathlib.function import for_mathlib.filter open topological_space -- predicates we need for topological rings -- We need to think whether we could directly use the class t2_space (which is not using opens though) definition is_hausdorff (α : Type*) [topological_space α] : Prop := ∀ x y, x ≠ y → ∃ u v : opens α, x ∈ u ∧ y ∈ v ∧ u ∩ v = ∅ lemma continuous_of_const {α : Type*} {β : Type*} [topological_space α] [topological_space β] {f : α → β} (h : ∀a b, f a = f b) : continuous f := λ s _, by convert @is_open_const _ _ (∃ a, f a ∈ s); exact set.ext (λ a, ⟨λ fa, ⟨_, fa⟩, λ ⟨b, fb⟩, show f a ∈ s, from h b a ▸ fb⟩) section variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} variables [topological_space α] [topological_space β] [topological_space γ] [topological_space δ] def continuous₂ (f : α → β → γ) := continuous (function.uncurry f) lemma continuous₂_def (f : α → β → γ) : continuous₂ f ↔ continuous (function.uncurry f) := iff.rfl lemma continuous₂_curry (f : α × β → γ) : continuous₂ (function.curry f) ↔ continuous f := by rw [←function.uncurry_curry f] {occs := occurrences.pos [2]} ; refl lemma continuous₂.comp {f : α → β → γ} {g : γ → δ} (hf : continuous₂ f)(hg : continuous g) : continuous₂ (g ∘₂ f) := begin unfold continuous₂, rw function.uncurry_comp₂, exact hf.comp hg end section open filter /- f α → β g ↓ ↓ h γ → δ i -/ variables {g : α → γ} (eg : embedding g) include eg lemma embedding.nhds_eq_comap (a : α) : nhds a = comap g (nhds $ g a) := by rw [eg.2, nhds_induced_eq_comap] variables {f : α → β} {i : γ → δ} {h : β → δ} (eh : embedding h) (H : h ∘ f = i ∘ g) include eh H lemma embedding.tendsto_iff (a : α) : continuous_at i (g a) → continuous_at f a:= begin let N := nhds a, let Nf := nhds (f a), let Nhf := nhds (h $ f a), let Ng := nhds (g a), have Neq1 : Nf = comap h Nhf, from eh.nhds_eq_comap (f a), have Neq2 : N = comap g Ng, from eg.nhds_eq_comap a, intro hyp, replace hyp : Ng ≤ comap i Nhf, { unfold continuous_at at hyp, rw ← show h (f a) = i (g a), from congr_fun H a at hyp, rwa tendsto_iff_comap at hyp }, rw calc continuous_at f a ↔ tendsto f N Nf : iff.rfl ... ↔ N ≤ comap f Nf : tendsto_iff_comap ... ↔ comap g Ng ≤ comap f (comap h Nhf) : by rw [Neq1, Neq2] ... ↔ comap g Ng ≤ comap g (comap i Nhf) : by rw comap_comm H, exact comap_mono hyp end end end namespace dense_embedding open set function filter variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} variables [topological_space α] [topological_space β] [topological_space γ] [topological_space δ] variables {f : α → β} {g : α → γ} {h : β → δ} {i : γ → δ} /- f α → β g ↓ ↓ h γ → δ i -/ -- The following lemma correct a typo in mathlib topology/maps.lean protected lemma continuous' (df : dense_embedding f) : continuous f := continuous_iff_continuous_at.mpr $ λ a, df.continuous_at -- TODO: The first item in the next proof should be extracted as a lemma about functions with dense image lemma comp (df : dense_embedding f) (dh : dense_embedding h) : dense_embedding (h ∘ f) := { dense := begin intro, rw range_comp, have Hf : closure (range f) = univ, from eq_univ_of_forall df.dense, have Hh : closure (range h) = univ, from eq_univ_of_forall dh.dense, rw [← image_univ, ← Hf] at Hh, have : h '' (closure $ range f) ⊆ closure (h '' range f), from image_closure_subset_closure_image dh.continuous', have := closure_mono this, rw closure_closure at this, apply this, simp [Hh] end, inj := function.injective_comp dh.inj df.inj, induced := λ a, by rw [← comap_comap_comp, dh.induced, df.induced] } -- density proof should be easier lemma of_comm_square (dg : dense_embedding g) (di : dense_embedding i) (dh : dense_embedding h) (H : h ∘ f = i ∘ g) : dense_embedding f := have dhf : dense_embedding (h ∘ f), by {rw H, exact comp dg di}, { dense := begin intro x, have H := dhf.dense (h x), rw mem_closure_iff_nhds at H ⊢, intros t ht, rw [←dh.induced x, mem_comap_sets] at ht, rcases ht with ⟨u, hu, hinc⟩, replace H := H u hu, rw ne_empty_iff_exists_mem at H ⊢, rcases H with ⟨v, hv1, a, rfl⟩, use f a, split, swap, apply mem_range_self, apply mem_of_mem_of_subset _ hinc, rwa mem_preimage_eq, end , inj := λ a b H, dhf.inj (by {show h (f a) = _, rw H}), induced := λ a, by rw [←dhf.induced a, ←@comap_comap_comp _ _ _ _ _ h, dh.induced] } lemma of_homeo (h : α ≃ₜ β) : dense_embedding h := { dense := begin intro x, erw range_iff_surjective.mpr (h.to_equiv.surjective), simp end, inj := h.to_equiv.injective, induced := begin intro a, symmetry, apply embedding.nhds_eq_comap, refine ⟨h.to_equiv.injective, _⟩, symmetry, apply homeomorph.induced_eq end } end dense_embedding section open filter variables {α : Type*} [topological_space α] {β : Type*} [topological_space β] [discrete_topology β] lemma continuous_into_discrete_iff (f : α → β) : continuous f ↔ ∀ b : β, is_open (f ⁻¹' {b}) := begin split, { intros hf b, exact hf _ (is_open_discrete _) }, { intro h, rw continuous_iff_continuous_at, intro x, have key : f ⁻¹' {f x} ∈ nhds x, from mem_nhds_sets (h $ f x) (set.mem_insert (f x) ∅), calc map f (nhds x) ≤ pure (f x) : (tendsto_pure f (nhds x) (f x)).2 key ... ≤ nhds (f x) : pure_le_nhds _ } end end -- tools for proving that a product of top rings is a top ring def continuous_pi₁ {I : Type*} {R : I → Type*} {S : I → Type*} [∀ i, topological_space (R i)] [∀ i, topological_space (S i)] {f : Π (i : I), (R i) → (S i)} (Hfi : ∀ i, continuous (f i)) : continuous (λ rs i, f i (rs i) : (Π (i : I), R i) → Π (i : I), S i) := continuous_pi (λ i, continuous.comp (continuous_apply i) (Hfi i)) def continuous_pi₂ {I : Type*} {R : I → Type*} {S : I → Type*} {T : I → Type*} [∀ i, topological_space (R i)] [∀ i, topological_space (S i)] [∀ i, topological_space (T i)] {f : Π (i : I), (R i) × (S i) → (T i)} (Hfi : ∀ i, continuous (f i)) : continuous (λ rs i, f i ⟨rs.1 i, rs.2 i⟩ : (Π (i : I), R i) × (Π (i : I), S i) → Π (i : I), T i) := continuous_pi (λ i, continuous.comp (continuous.prod_mk (continuous.comp (continuous_fst) (continuous_apply i)) (continuous.comp (continuous_snd) (continuous_apply i))) (Hfi i)) section bases open filter set variables {α : Type*} {ι : Type*} {s : ι → set α} [inhabited ι] lemma generate_eq_of_base (H : ∀ i j, ∃ k, s k ⊆ s i ∩ s j) (U : set α) : U ∈ generate (range s) ↔ ∃ i, s i ⊆ U := begin split ; intro h, { induction h with U U_in U V U_gen UV U_union U V U_gen V_gen U_union V_union, { rcases U_in with ⟨i, rfl⟩, use i }, { use default ι, exact (univ_mem_sets : univ ∈ principal (s $ default ι))}, { cases U_union with i Ui, use i, exact subset.trans Ui UV }, { cases U_union with i Ui, cases V_union with j Vj, cases H i j with k k_sub, use k, cases subset_inter_iff.1 k_sub with ki kj, exact subset_inter_iff.2 ⟨subset.trans ki Ui, subset.trans kj Vj⟩ }}, { cases h with i Ui, exact generate_sets.superset (generate_sets.basic $ mem_range_self i) Ui }, end lemma mem_infi_range_of_base (H : ∀ i j, ∃ k, s k ⊆ s i ∩ s j) (U : set α) : U ∈ (⨅ i, principal (s i)) ↔ ∃ i, s i ⊆ U := begin rw mem_infi, { split, { exact λ ⟨_, ⟨i, rfl⟩, Ui⟩, ⟨i, Ui⟩ }, { rintro ⟨i, Ui⟩, rw mem_Union, use [i, Ui] } }, { rintros i j, cases H i j with k k_sub, use k, split ; apply principal_mono.2 ; simp [set.subset_inter_iff.1 k_sub] }, { apply_instance } end lemma generate_eq_infi (H : ∀ i j, ∃ k, s k ⊆ s i ∩ s j) : generate (range s) = ⨅ i, principal (s i) := by ext t ; rw [generate_eq_of_base H, mem_infi_range_of_base H] end bases
ddfb2da2457a3288e62b011aecc43c0ed7c1eb71
60bf3fa4185ec5075eaea4384181bfbc7e1dc319
/src/game/sup_inf/lub_prodSets.lean
011b33f44e6e2410d46d7571621358dbe8d68443
[ "Apache-2.0" ]
permissive
anrddh/real-number-game
660f1127d03a78fd35986c771d65c3132c5f4025
c708c4e02ec306c657e1ea67862177490db041b0
refs/heads/master
1,668,214,277,092
1,593,105,075,000
1,593,105,075,000
264,269,218
0
0
null
1,589,567,264,000
1,589,567,264,000
null
UTF-8
Lean
false
false
1,180
lean
import data.real.basic import ..sets.sets_level09 namespace xena -- hide /- # Chapter 3 : Sup and Inf ## Level 9 An intermediary result to be used in the next level. -/ -- main result in lemma sup_mem_prod_of_sets -- begin hide --def mem_prod_sets (A : set ℝ) (B : set ℝ) := { x : ℝ | ∃ y ∈ A, ∃ z ∈ B, x = y * z} -- end hide /- Prove that a given real number is the supremum of a particular set. -/ /- Lemma Given two sets of reals $A$ and $B$, show that given real number is the LUB of their elementwise product `mem_prod_sets`. -/ lemma mem_prod_sets_lub_proof : is_lub (mem_prod_sets (set.Icc (-2:ℝ) (-1:ℝ)) (set.Icc (0:ℝ) (3:ℝ)) ) 0 := begin split, intros x h1, cases h1 with a hh, cases hh with ha h2, cases h2 with b h3, cases h3 with hb hx, have H : a ≤ 0, cases ha with hg hl, linarith, have G : b ≥ 0, cases hb with hg hl, exact hg, rw hx, exact mul_nonpos_of_nonpos_of_nonneg H G, intros x hx, by_contradiction hnx, push_neg at hnx, --TODO: kmb doesn't know what zero_in_prod is, and it's not compiling have E := zero_in_prod, have D := hx E, linarith, done --sorry end end xena -- hide
1ba9909155ee8444a16ee3e42fd1f6f41c71c653
8d65764a9e5f0923a67fc435eb1a5a1d02fd80e3
/src/analysis/normed_space/multilinear.lean
80da874210ccdb837442abd1b0f5add67217199c
[ "Apache-2.0" ]
permissive
troyjlee/mathlib
e18d4b8026e32062ab9e89bc3b003a5d1cfec3f5
45e7eb8447555247246e3fe91c87066506c14875
refs/heads/master
1,689,248,035,046
1,629,470,528,000
1,629,470,528,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
73,231
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 nnreal open finset metric local attribute [instance, priority 1001] add_comm_group.to_add_comm_monoid normed_group.to_add_comm_group normed_space.to_module -- hack to speed up simp when dealing with complicated types local attribute [-instance] unique.subsingleton pi.subsingleton /-! ### Type variables We use the following type variables in this file: * `𝕜` : a `nondiscrete_normed_field`; * `ι`, `ι'` : finite index types with decidable equality; * `E`, `E₁` : families 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₁ wE' wEi wG wG' variables {𝕜 : Type u} {ι : Type v} {ι' : Type v'} {n : ℕ} {E : ι → Type wE} {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 (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 `le_cInf` 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∥ := le_cInf 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_cInf bounds_nonempty, 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∥ := div_le_of_nonneg_of_le_mul (prod_nonneg $ λ i _, norm_nonneg _) (op_norm_nonneg _) (f.le_op_norm m) /-- 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 := cInf_le bounds_bdd_below ⟨hMp, hM⟩ /-- The operator norm satisfies the triangle inequality. -/ theorem op_norm_add_le : ∥f + g∥ ≤ ∥f∥ + ∥g∥ := cInf_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⟩ theorem le_op_norm_mul_prod_of_le {b : ι → ℝ} (hm : ∀ i, ∥m i∥ ≤ b i) : ∥f m∥ ≤ ∥f∥ * ∏ i, b i := (f.le_op_norm m).trans $ mul_le_mul_of_nonneg_left (prod_le_prod (λ _ _, norm_nonneg _) (λ i _, hm i)) (norm_nonneg f) theorem le_op_norm_mul_pow_card_of_le {b : ℝ} (hm : ∀ i, ∥m i∥ ≤ b) : ∥f m∥ ≤ ∥f∥ * b ^ fintype.card ι := by simpa only [prod_const] using f.le_op_norm_mul_prod_of_le m hm theorem le_op_norm_mul_pow_of_le {Ei : fin n → Type*} [Π i, normed_group (Ei i)] [Π i, normed_space 𝕜 (Ei i)] (f : continuous_multilinear_map 𝕜 Ei G) (m : Π i, Ei i) {b : ℝ} (hm : ∥m∥ ≤ b) : ∥f m∥ ≤ ∥f∥ * b ^ n := by simpa only [fintype.card_fin] using f.le_op_norm_mul_pow_card_of_le m (λ i, (norm_le_pi_norm m i).trans hm) /-- 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∥`, `nnnorm` version. -/ theorem le_op_nnnorm : nnnorm (f m) ≤ nnnorm f * ∏ i, nnnorm (m i) := nnreal.coe_le_coe.1 $ by { push_cast, exact f.le_op_norm m } theorem le_of_op_nnnorm_le {C : ℝ≥0} (h : nnnorm f ≤ C) : nnnorm (f m) ≤ C * ∏ i, nnnorm (m i) := (f.le_op_nnnorm m).trans $ mul_le_mul' h le_rfl lemma op_norm_prod (f : continuous_multilinear_map 𝕜 E G) (g : continuous_multilinear_map 𝕜 E G') : ∥f.prod g∥ = max (∥f∥) (∥g∥) := le_antisymm (op_norm_le_bound _ (norm_nonneg (f, g)) (λ m, have H : 0 ≤ ∏ i, ∥m i∥, from prod_nonneg $ λ _ _, norm_nonneg _, by simpa only [prod_apply, prod.norm_def, max_mul_of_nonneg, H] using max_le_max (f.le_op_norm m) (g.le_op_norm m))) $ max_le (f.op_norm_le_bound (norm_nonneg _) $ λ m, (le_max_left _ _).trans ((f.prod g).le_op_norm _)) (g.op_norm_le_bound (norm_nonneg _) $ λ m, (le_max_right _ _).trans ((f.prod g).le_op_norm _)) lemma norm_pi {ι' : Type v'} [fintype ι'] {E' : ι' → Type wE'} [Π i', normed_group (E' i')] [Π i', normed_space 𝕜 (E' i')] (f : Π i', continuous_multilinear_map 𝕜 E (E' i')) : ∥pi f∥ = ∥f∥ := begin apply le_antisymm, { refine (op_norm_le_bound _ (norm_nonneg f) (λ m, _)), dsimp, rw pi_norm_le_iff, exacts [λ i, (f i).le_of_op_norm_le m (norm_le_pi_norm f i), mul_nonneg (norm_nonneg f) (prod_nonneg $ λ _ _, norm_nonneg _)] }, { refine (pi_norm_le_iff (norm_nonneg _)).2 (λ i, _), refine (op_norm_le_bound _ (norm_nonneg _) (λ m, _)), refine le_trans _ ((pi f).le_op_norm m), convert norm_le_pi_norm (λ j, f j m) i } end section variables (𝕜 E E' G G') /-- `continuous_multilinear_map.prod` as a `linear_isometry_equiv`. -/ def prodL : (continuous_multilinear_map 𝕜 E G) × (continuous_multilinear_map 𝕜 E G') ≃ₗᵢ[𝕜] continuous_multilinear_map 𝕜 E (G × G') := { to_fun := λ f, f.1.prod f.2, inv_fun := λ f, ((continuous_linear_map.fst 𝕜 G G').comp_continuous_multilinear_map f, (continuous_linear_map.snd 𝕜 G G').comp_continuous_multilinear_map f), map_add' := λ f g, rfl, map_smul' := λ c f, rfl, left_inv := λ f, by ext; refl, right_inv := λ f, by ext; refl, norm_map' := λ f, op_norm_prod f.1 f.2 } /-- `continuous_multilinear_map.pi` as a `linear_isometry_equiv`. -/ def piₗᵢ {ι' : Type v'} [fintype ι'] {E' : ι' → Type wE'} [Π i', normed_group (E' i')] [Π i', normed_space 𝕜 (E' i')] : @linear_isometry_equiv 𝕜 (Π i', continuous_multilinear_map 𝕜 E (E' i')) (continuous_multilinear_map 𝕜 E (Π i, E' i)) _ _ _ (@pi.module ι' _ 𝕜 _ _ (λ i', infer_instance)) _ := { to_linear_equiv := -- note: `pi_linear_equiv` does not unify correctly here, presumably due to issues with dependent -- typeclass arguments. { map_add' := λ f g, rfl, map_smul' := λ c f, rfl, .. pi_equiv, }, norm_map' := norm_pi } end 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 lemma tsum_eval {α : Type*} {p : α → continuous_multilinear_map 𝕜 E G} (hp : summable p) (m : Π i, E i) : (∑' a, p a) m = ∑' a, p a m := (has_sum_eval hp.has_sum m).tsum_eq.symm 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 (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 [is_empty ι] : ∥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 (not_nonempty_iff.mpr ‹_›), convert ratio_le_op_norm _ (λ _, (1 : A)), simp [eq_empty_of_is_empty (univ : finset ι)], end @[simp] lemma norm_mk_pi_algebra [norm_one_class A] : ∥continuous_multilinear_map.mk_pi_algebra 𝕜 ι A∥ = 1 := begin casesI is_empty_or_nonempty ι, { simp [norm_mk_pi_algebra_of_empty] }, { refine le_antisymm norm_mk_pi_algebra_le _, convert ratio_le_op_norm _ (λ _, 1); [skip, apply_instance], simp }, 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 (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 @[simp] 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 (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 namespace continuous_linear_map lemma 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 /-- `continuous_linear_map.comp_continuous_multilinear_map` as a bundled continuous bilinear map. -/ def comp_continuous_multilinear_mapL : (G →L[𝕜] G') →L[𝕜] continuous_multilinear_map 𝕜 E G →L[𝕜] continuous_multilinear_map 𝕜 E G' := linear_map.mk_continuous₂ (linear_map.mk₂ 𝕜 comp_continuous_multilinear_map (λ f₁ f₂ g, rfl) (λ c f g, rfl) (λ f g₁ g₂, by { ext1, apply f.map_add }) (λ c f g, by { ext1, simp })) 1 $ λ f g, by { rw one_mul, exact f.norm_comp_continuous_multilinear_map_le g } /-- Flip arguments in `f : G →L[𝕜] continuous_multilinear_map 𝕜 E G'` to get `continuous_multilinear_map 𝕜 E (G →L[𝕜] G')` -/ def flip_multilinear (f : G →L[𝕜] continuous_multilinear_map 𝕜 E G') : continuous_multilinear_map 𝕜 E (G →L[𝕜] G') := multilinear_map.mk_continuous { to_fun := λ m, linear_map.mk_continuous { to_fun := λ x, f x m, map_add' := λ x y, by simp only [map_add, continuous_multilinear_map.add_apply], map_smul' := λ c x, by simp only [continuous_multilinear_map.smul_apply, map_smul]} (∥f∥ * ∏ i, ∥m i∥) $ λ x, by { rw mul_right_comm, exact (f x).le_of_op_norm_le _ (f.le_op_norm x) }, map_add' := λ m i x y, by { ext1, simp only [add_apply, continuous_multilinear_map.map_add, linear_map.coe_mk, linear_map.mk_continuous_apply]}, map_smul' := λ m i c x, by { ext1, simp only [coe_smul', continuous_multilinear_map.map_smul, linear_map.coe_mk, linear_map.mk_continuous_apply, pi.smul_apply]} } ∥f∥ $ λ m, linear_map.mk_continuous_norm_le _ (mul_nonneg (norm_nonneg f) (prod_nonneg $ λ i hi, norm_nonneg (m i))) _ end continuous_linear_map open continuous_multilinear_map 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 namespace continuous_multilinear_map lemma norm_comp_continuous_linear_le (g : continuous_multilinear_map 𝕜 E₁ G) (f : Π i, E i →L[𝕜] E₁ i) : ∥g.comp_continuous_linear_map f∥ ≤ ∥g∥ * ∏ i, ∥f i∥ := op_norm_le_bound _ (mul_nonneg (norm_nonneg _) $ prod_nonneg $ λ i hi, norm_nonneg _) $ λ m, calc ∥g (λ i, f i (m i))∥ ≤ ∥g∥ * ∏ i, ∥f i (m i)∥ : g.le_op_norm _ ... ≤ ∥g∥ * ∏ i, (∥f i∥ * ∥m i∥) : mul_le_mul_of_nonneg_left (prod_le_prod (λ _ _, norm_nonneg _) (λ i hi, (f i).le_op_norm (m i))) (norm_nonneg g) ... = (∥g∥ * ∏ i, ∥f i∥) * ∏ i, ∥m i∥ : by rw [prod_mul_distrib, mul_assoc] /-- `continuous_multilinear_map.comp_continuous_linear_map` as a bundled continuous linear map. This implementation fixes `f : Π i, E i →L[𝕜] E₁ i`. TODO: Actually, the map is multilinear in `f` but an attempt to formalize this failed because of issues with class instances. -/ def comp_continuous_linear_mapL (f : Π i, E i →L[𝕜] E₁ i) : continuous_multilinear_map 𝕜 E₁ G →L[𝕜] continuous_multilinear_map 𝕜 E G := linear_map.mk_continuous { to_fun := λ g, g.comp_continuous_linear_map f, map_add' := λ g₁ g₂, rfl, map_smul' := λ c g, rfl } (∏ i, ∥f i∥) $ λ g, (norm_comp_continuous_linear_le _ _).trans_eq (mul_comm _ _) @[simp] lemma comp_continuous_linear_mapL_apply (g : continuous_multilinear_map 𝕜 E₁ G) (f : Π i, E i →L[𝕜] E₁ i) : comp_continuous_linear_mapL f g = g.comp_continuous_linear_map f := rfl lemma norm_comp_continuous_linear_mapL_le (f : Π i, E i →L[𝕜] E₁ i) : ∥@comp_continuous_linear_mapL 𝕜 ι E E₁ G _ _ _ _ _ _ _ _ _ f∥ ≤ (∏ i, ∥f i∥) := linear_map.mk_continuous_norm_le _ (prod_nonneg $ λ i _, norm_nonneg _) _ end continuous_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, map_smul' := λ m i c x, by simp } 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. -/ section local attribute [instance] unique.subsingleton 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 end /-! #### 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)} /-- 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)} (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
80ea9667b139cc2adce6053fdc5defe003e8fe79
fe84e287c662151bb313504482b218a503b972f3
/src/poset/upper.lean
aee72717ec80a008b65e1e549fc9663f9ac59a98
[]
no_license
NeilStrickland/lean_lib
91e163f514b829c42fe75636407138b5c75cba83
6a9563de93748ace509d9db4302db6cd77d8f92c
refs/heads/master
1,653,408,198,261
1,652,996,419,000
1,652,996,419,000
181,006,067
4
1
null
null
null
null
UTF-8
Lean
false
false
5,465
lean
/- Copyright (c) 2019 Neil Strickland. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Neil Strickland Given a finite poset `P`, we define `upper P` to be the set of subsets `U ⊆ P` that are closed upwards. We order this by *reverse* inclusion, to ensure that the map `u : p ↦ {x : p ≤ x}` is a morphism of posets. We prove that `upper P` is a bounded distributive lattice with this order. -/ import poset.basic order.bounded order.lattice universes uP uQ uR uS variables (P : Type uP) [decidable_eq P] [fintype P] variables [partial_order P] [decidable_rel (has_le.le : P → P → Prop)] namespace poset variable {P} def is_upper : finset P → Prop := λ (U : finset P), ∀ (p₀ p₁ : P), (p₀ ≤ p₁) → (p₀ ∈ U) → (p₁ ∈ U) variable (P) instance is_upper_decidable (U : finset P) : decidable (is_upper U) := by { dsimp[is_upper], apply_instance } lemma is_upper_empty : is_upper (@finset.empty P) := λ p₀ p₁ hp hU, (finset.not_mem_empty p₀ hU).elim lemma is_upper_univ : is_upper (@finset.univ P _) := λ p₀ p₁ hp hU, (finset.mem_univ p₁) variable {P} lemma is_upper_union (U V : finset P) (hU : is_upper U) (hV : is_upper V) : is_upper (U ∪ V) := λ p₀ p₁ hp hpUV, begin rcases (finset.mem_union.mp hpUV) with hpU | hpV, {exact finset.mem_union_left V (hU p₀ p₁ hp hpU)}, {exact finset.mem_union_right U (hV p₀ p₁ hp hpV)}, end lemma is_upper_inter (U V : finset P) (hU : is_upper U) (hV : is_upper V) : is_upper (U ∩ V) := λ p₀ p₁ hp hpUV, begin replace hpUV := finset.mem_inter.mp hpUV, apply finset.mem_inter.mpr, split, {exact (hU p₀ p₁ hp hpUV.left)}, {exact (hV p₀ p₁ hp hpUV.right)}, end def distrib (U V W : finset P) : U ∩ (V ∪ W) ⊆ (U ∩ V) ∪ (U ∩ W) := begin intros A h, rw[finset.mem_inter,finset.mem_union] at h, rw[finset.mem_union,finset.mem_inter,finset.mem_inter], rcases h with ⟨hU,hV | hW⟩, exact or.inl ⟨hU,hV⟩, exact or.inr ⟨hU,hW⟩ end variable (P) def upper := { U : finset P // is_upper U } namespace upper instance : fintype (upper P) := by {dsimp [upper], apply_instance} /-- To print an upper set, ignore the upperness property and just print the underlying set. -/ instance [has_repr P] : has_repr (upper P) := ⟨λ U, repr U.val⟩ variable {P} def els (U : upper P) : Type* := {p // p ∈ U.val} variable (P) instance els_order (U : upper P) : partial_order U.els := by { unfold els, apply_instance } instance : has_mem P (upper P) := ⟨λ p U, p ∈ U.val⟩ /-- Two upper sets are equal iff they have the same elements. -/ @[ext] lemma ext (U₀ U₁ : upper P) : (∀ (p : P), p ∈ U₀ ↔ p ∈ U₁) → U₀ = U₁ := begin intro h, apply subtype.eq, ext p, exact h p end /-- upper P has a natural structure as a bounded distributive lattice. -/ instance dl : distrib_lattice (upper P) := { le := λ U V, V.val ⊆ U.val, le_refl := λ U, le_refl U.val, le_antisymm := λ U V (h0 : V.val ⊆ U.val) (h1 : U.val ⊆ V.val), begin apply subtype.eq, exact le_antisymm h1 h0, end, le_trans := λ U V W (h0 : V.val ⊆ U.val) (h1 : W.val ⊆ V.val), @le_trans (finset P) _ W.val V.val U.val h1 h0, inf := λ U V, ⟨U.val ∪ V.val, is_upper_union U.val V.val U.property V.property⟩, sup := λ U V, ⟨U.val ∩ V.val, is_upper_inter U.val V.val U.property V.property⟩, le_sup_left := λ U V,finset.inter_subset_left U.val V.val, le_sup_right := λ U V,finset.inter_subset_right U.val V.val, sup_le := λ U V W (U_le_W : W.val ⊆ U.val) (V_le_W : W.val ⊆ V.val), finset.subset_inter U_le_W V_le_W, inf_le_left := λ U V,finset.subset_union_left U.val V.val, inf_le_right := λ U V,finset.subset_union_right U.val V.val, le_inf := λ U V W (U_le_V : V.val ⊆ U.val) (U_le_W : W.val ⊆ U.val), finset.union_subset U_le_V U_le_W, le_sup_inf := λ U V W A h, distrib U.val V.val W.val h, } instance bo : bounded_order (upper P) := { bot := ⟨finset.univ,is_upper_univ P⟩, top := ⟨finset.empty,is_upper_empty P⟩, bot_le := λ U,finset.subset_univ U.val, le_top := λ U,finset.empty_subset U.val } variable {P} lemma mem_bot (p : P) : p ∈ (⊥ : upper P) := finset.mem_univ p lemma not_mem_top (p : P) : p ∉ (⊤ : upper P) := finset.not_mem_empty p lemma mem_inf {U V : upper P} (p : P) : p ∈ U ⊓ V ↔ (p ∈ U ∨ p ∈ V) := finset.mem_union lemma mem_sup {U V : upper P} (p : P) : p ∈ U ⊔ V ↔ (p ∈ U ∧ p ∈ V) := finset.mem_inter /- We embed `P` in `upper P` using the map `u : A ↦ { B : A ⊆ B }` -/ def u : poset.hom P (upper P) := ⟨λ p, ⟨finset.univ.filter (λ q, p ≤ q), begin intros q r hqr hpq, replace hpq := (finset.mem_filter.mp hpq).right, exact finset.mem_filter.mpr ⟨finset.mem_univ r,le_trans hpq hqr⟩, end ⟩, λ p₀ p₁ h q q_in_up₀, begin have : p₀ ≤ q := le_trans h (finset.mem_filter.mp q_in_up₀).right, exact finset.mem_filter.mpr ⟨finset.mem_univ q, this⟩ end⟩ lemma mem_u (p q : P) : p ∈ (@u P _ _ _ _ q) ↔ q ≤ p := begin change p ∈ finset.filter _ _ ↔ q ≤ p, simp [finset.mem_filter, finset.mem_univ] end end upper end poset
ad3469899d35270167de35197cc24e19a0d7166e
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/tests/lean/Reformat/Input.lean
43649bfc6375a0a4ccabb4e595e4f6e6d890b5a8
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
EdAyers/lean4
57ac632d6b0789cb91fab2170e8c9e40441221bd
37ba0df5841bde51dbc2329da81ac23d4f6a4de4
refs/heads/master
1,676,463,245,298
1,660,619,433,000
1,660,619,433,000
183,433,437
1
0
Apache-2.0
1,657,612,672,000
1,556,196,574,000
Lean
UTF-8
Lean
false
false
9,611
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude universe u v w @[inline] def id {α : Sort u} (a : α) : α := a /- The kernel definitional equality test (t =?= s) has special support for idDelta applications. It implements the following rules 1) (idDelta t) =?= t 2) t =?= (idDelta t) 3) (idDelta t) =?= s IF (unfoldOf t) =?= s 4) t =?= idDelta s IF t =?= (unfoldOf s) This is mechanism for controlling the delta reduction (aka unfolding) used in the kernel. We use idDelta applications to address performance problems when Type checking theorems generated by the equation Compiler. -/ @[inline] def idDelta {α : Sort u} (a : α) : α := a /- `idRhs` is an auxiliary declaration used to implement "smart unfolding". It is used as a marker. -/ @[macroInline, reducible] def idRhs (α : Sort u) (a : α) : α := a abbrev Function.comp {α : Sort u} {β : Sort v} {δ : Sort w} (f : β → δ) (g : α → β) : α → δ := fun x => f (g x) abbrev Function.const {α : Sort u} (β : Sort v) (a : α) : β → α := fun x => a @[reducible] def inferInstance {α : Type u} [i : α] : α := i @[reducible] def inferInstanceAs (α : Type u) [i : α] : α := i set_option bootstrap.inductiveCheckResultingUniverse false in inductive PUnit : Sort u | unit : PUnit /-- An abbreviation for `PUnit.{0}`, its most common instantiation. This Type should be preferred over `PUnit` where possible to avoid unnecessary universe parameters. -/ abbrev Unit : Type := PUnit @[matchPattern] abbrev Unit.unit : Unit := PUnit.unit /-- Auxiliary unsafe constant used by the Compiler when erasing proofs from code. -/ unsafe axiom lcProof {α : Prop} : α /-- Auxiliary unsafe constant used by the Compiler to mark unreachable code. -/ unsafe axiom lcUnreachable {α : Sort u} : α inductive True : Prop | intro : True inductive False : Prop inductive Empty : Type def Not (a : Prop) : Prop := a → False @[macroInline] def False.elim {C : Sort u} (h : False) : C := False.rec (fun _ => C) h @[macroInline] def absurd {a : Prop} {b : Sort v} (h₁ : a) (h₂ : Not a) : b := False.elim (h₂ h₁) inductive Eq : α → α → Prop | refl (a : α) : Eq a a abbrev Eq.ndrec.{u1, u2} {α : Sort u2} {a : α} {motive : α → Sort u1} (m : motive a) {b : α} (h : Eq a b) : motive b := Eq.rec (motive := fun α _ => motive α) m h @[matchPattern] def rfl {α : Sort u} {a : α} : Eq a a := Eq.refl a theorem Eq.subst {α : Sort u} {motive : α → Prop} {a b : α} (h₁ : Eq a b) (h₂ : motive a) : motive b := Eq.ndrec h₂ h₁ theorem Eq.symm {α : Sort u} {a b : α} (h : Eq a b) : Eq b a := h ▸ rfl @[macroInline] def cast {α β : Sort u} (h : Eq α β) (a : α) : β := Eq.rec (motive := fun α _ => α) a h theorem congrArg {α : Sort u} {β : Sort v} {a₁ a₂ : α} (f : α → β) (h : Eq a₁ a₂) : Eq (f a₁) (f a₂) := h ▸ rfl /- Initialize the Quotient Module, which effectively adds the following definitions: opaque Quot {α : Sort u} (r : α → α → Prop) : Sort u opaque Quot.mk {α : Sort u} (r : α → α → Prop) (a : α) : Quot r opaque Quot.lift {α : Sort u} {r : α → α → Prop} {β : Sort v} (f : α → β) : (∀ a b : α, r a b → Eq (f a) (f b)) → Quot r → β opaque Quot.ind {α : Sort u} {r : α → α → Prop} {β : Quot r → Prop} : (∀ a : α, β (Quot.mk r a)) → ∀ q : Quot r, β q -/ init_quot inductive HEq : {α : Sort u} → α → {β : Sort u} → β → Prop | refl (a : α) : HEq a a @[matchPattern] def HEq.rfl {α : Sort u} {a : α} : HEq a a := HEq.refl a theorem eqOfHEq {α : Sort u} {a a' : α} (h : HEq a a') : Eq a a' := have : (α β : Sort u) → (a : α) → (b : β) → HEq a b → (h : Eq α β) → Eq (cast h a) b := fun α β a b h₁ => HEq.rec (motive := fun {β} (b : β) (h : HEq a b) => (h₂ : Eq α β) → Eq (cast h₂ a) b) (fun (h₂ : Eq α α) => rfl) h₁ this α α a a' h rfl structure Prod (α : Type u) (β : Type v) := (fst : α) (snd : β) attribute [unbox] Prod /-- Similar to `Prod`, but `α` and `β` can be propositions. We use this Type internally to automatically generate the brecOn recursor. -/ structure PProd (α : Sort u) (β : Sort v) := (fst : α) (snd : β) /-- Similar to `Prod`, but `α` and `β` are in the same universe. -/ structure MProd (α β : Type u) := (fst : α) (snd : β) structure And (a b : Prop) : Prop := intro :: (left : a) (right : b) inductive Or (a b : Prop) : Prop | inl (h : a) : Or a b | inr (h : b) : Or a b inductive Bool : Type | false : Bool | true : Bool export Bool (false true) /- Remark: Subtype must take a Sort instead of Type because of the axiom strongIndefiniteDescription. -/ structure Subtype {α : Sort u} (p : α → Prop) := (val : α) (property : p val) /-- Gadget for optional parameter support. -/ @[reducible] def optParam (α : Sort u) (default : α) : Sort u := α /-- Gadget for marking output parameters in type classes. -/ @[reducible] def outParam (α : Sort u) : Sort u := α /-- Auxiliary Declaration used to implement the notation (a : α) -/ @[reducible] def typedExpr (α : Sort u) (a : α) : α := a /-- Auxiliary Declaration used to implement the named patterns `x@p` -/ @[reducible] def namedPattern {α : Sort u} (x a : α) : α := a /- Auxiliary axiom used to implement `sorry`. -/ axiom sorryAx (α : Sort u) (synthetic := true) : α theorem eqFalseOfNeTrue : {b : Bool} → Not (Eq b true) → Eq b false | true, h => False.elim (h rfl) | false, h => rfl theorem eqTrueOfNeFalse : {b : Bool} → Not (Eq b false) → Eq b true | true, h => rfl | false, h => False.elim (h rfl) theorem neFalseOfEqTrue : {b : Bool} → Eq b true → Not (Eq b false) | true, _ => fun h => Bool.noConfusion h | false, h => Bool.noConfusion h theorem neTrueOfEqFalse : {b : Bool} → Eq b false → Not (Eq b true) | true, h => Bool.noConfusion h | false, _ => fun h => Bool.noConfusion h class Inhabited (α : Sort u) := (default : α) opaque arbitrary (α : Sort u) [s : Inhabited α] : α := @Inhabited.default α s instance (α : Sort u) {β : Sort v} [Inhabited β] : Inhabited (α → β) := {default := fun _ => arbitrary β} instance (α : Sort u) {β : α → Sort v} [(a : α) → Inhabited (β a)] : Inhabited ((a : α) → β a) := {default := fun a => arbitrary (β a)} /-- Universe lifting operation from Sort to Type -/ structure PLift (α : Sort u) : Type u := up :: (down : α) /- Bijection between α and PLift α -/ theorem PLift.upDown {α : Sort u} : ∀ (b : PLift α), Eq (up (down b)) b | up a => rfl theorem PLift.downUp {α : Sort u} (a : α) : Eq (down (up a)) a := rfl /- Pointed types -/ structure PointedType := (type : Type u) (val : type) instance : Inhabited PointedType.{u} := {default := { type := PUnit.{u+1}, val := ⟨⟩ }} /-- Universe lifting operation -/ structure ULift.{r, s} (α : Type s) : Type (max s r) := up :: (down : α) /- Bijection between α and ULift.{v} α -/ theorem ULift.upDown {α : Type u} : ∀ (b : ULift.{v} α), Eq (up (down b)) b | up a => rfl theorem ULift.downUp {α : Type u} (a : α) : Eq (down (up.{v} a)) a := rfl class inductive Decidable (p : Prop) | isFalse (h : Not p) : Decidable p | isTrue (h : p) : Decidable p @[inlineIfReduce, nospecialize] def Decidable.decide (p : Prop) [h : Decidable p] : Bool := Decidable.casesOn (motive := fun _ => Bool) h (fun _ => false) (fun _ => true) export Decidable (isTrue isFalse decide) abbrev DecidablePred {α : Sort u} (r : α → Prop) := (a : α) → Decidable (r a) abbrev DecidableRel {α : Sort u} (r : α → α → Prop) := (a b : α) → Decidable (r a b) abbrev DecidableEq (α : Sort u) := (a b : α) → Decidable (Eq a b) def decEq {α : Sort u} [s : DecidableEq α] (a b : α) : Decidable (Eq a b) := s a b theorem decideEqTrue : {p : Prop} → [s : Decidable p] → p → Eq (decide p) true | _, isTrue _, _ => rfl | _, isFalse h₁, h₂ => absurd h₂ h₁ theorem decideEqTrue' : [s : Decidable p] → p → Eq (decide p) true | isTrue _, _ => rfl | isFalse h₁, h₂ => absurd h₂ h₁ theorem decideEqFalse : {p : Prop} → [s : Decidable p] → Not p → Eq (decide p) false | _, isTrue h₁, h₂ => absurd h₁ h₂ | _, isFalse h, _ => rfl theorem ofDecideEqTrue {p : Prop} [s : Decidable p] : Eq (decide p) true → p := fun h => match s with | isTrue h₁ => h₁ | isFalse h₁ => absurd h (neTrueOfEqFalse (decideEqFalse h₁)) theorem ofDecideEqFalse {p : Prop} [s : Decidable p] : Eq (decide p) false → Not p := fun h => match s with | isTrue h₁ => absurd h (neFalseOfEqTrue (decideEqTrue h₁)) | isFalse h₁ => h₁ @[inline] instance : DecidableEq Bool := fun a b => match a, b with | false, false => isTrue rfl | false, true => isFalse (fun h => Bool.noConfusion h) | true, false => isFalse (fun h => Bool.noConfusion h) | true, true => isTrue rfl class BEq (α : Type u) := (beq : α → α → Bool) open BEq (beq) instance {α : Type u} [DecidableEq α] : BEq α := ⟨fun a b => decide (Eq a b)⟩ -- We use "dependent" if-then-else to be able to communicate the if-then-else condition -- to the branches @[macroInline] def dite {α : Sort u} (c : Prop) [h : Decidable c] (t : c → α) (e : Not c → α) : α := Decidable.casesOn (motive := fun _ => α) h e t
a99cadfeb5920d34921a4ec205b87106a17aadf3
b3c7090f393c11bd47c82d2f8bb4edf8213173f5
/src/bundled_quotients.lean
305e58794b18dc0df66acc4bb4456ae1b9c83f6d
[]
no_license
ImperialCollegeLondon/lean-groups
964b197478f0313d826073576a3e0ae8b166a584
9a82d2a66ef7f549107fcb4e1504d734c43ebb33
refs/heads/master
1,592,371,184,330
1,567,197,270,000
1,567,197,270,000
195,810,480
4
0
null
null
null
null
UTF-8
Lean
false
false
792
lean
import group_theory.quotient_group bundled_subgroup namespace quotient_group variables {G : Type*} [group G] {N : subgroup G} (h : is_normal_subgroup N) open function def quotient' {G : Type*} [group G] {N : subgroup G} (h : is_normal_subgroup N) := quotient N.carrier instance quotient'_is_group {G : Type*} [group G] {N : subgroup G} (h : is_normal_subgroup N) : group (quotient' h) := by unfold quotient'; letI : normal_subgroup (N.carrier) := h; apply_instance def mk' {G : Type*} [group G] {N : subgroup G} (h : is_normal_subgroup N) : G →* quotient' h := by letI : normal_subgroup (N.carrier) := h; exact group_hom.mk (quotient_group.mk) theorem mk'.surjective : surjective (mk' h) := begin intro q, use quotient.out' q, apply quotient.out_eq' end end quotient_group
d0e1bf524203d93212f176682ee3bc118f5a0923
82e44445c70db0f03e30d7be725775f122d72f3e
/archive/100-theorems-list/9_area_of_a_circle.lean
c6c2ced3620d6027db960999881ef3a9a1c0acc6
[ "Apache-2.0" ]
permissive
stjordanis/mathlib
51e286d19140e3788ef2c470bc7b953e4991f0c9
2568d41bca08f5d6bf39d915434c8447e21f42ee
refs/heads/master
1,631,748,053,501
1,627,938,886,000
1,627,938,886,000
228,728,358
0
0
Apache-2.0
1,576,630,588,000
1,576,630,587,000
null
UTF-8
Lean
false
false
6,442
lean
/- Copyright (c) 2021 James Arthur, Benjamin Davidson, Andrew Souther. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: James Arthur, Benjamin Davidson, Andrew Souther -/ import measure_theory.interval_integral import analysis.special_functions.sqrt /-! # Freek № 9: The Area of a Circle In this file we show that the area of a disc with nonnegative radius `r` is `π * r^2`. The main tools our proof uses are `volume_region_between_eq_integral`, which allows us to represent the area of the disc as an integral, and `interval_integral.integral_eq_sub_of_has_deriv_at'_of_le`, the second fundamental theorem of calculus. We begin by defining `disc` in `ℝ × ℝ`, then show that `disc` can be represented as the `region_between` two functions. Though not necessary for the main proof, we nonetheless choose to include a proof of the measurability of the disc in order to convince the reader that the set whose volume we will be calculating is indeed measurable and our result is therefore meaningful. In the main proof, `area_disc`, we use `volume_region_between_eq_integral` followed by `interval_integral.integral_of_le` to reduce our goal to a single `interval_integral`: `∫ (x : ℝ) in -r..r, 2 * sqrt (r ^ 2 - x ^ 2) = π * r ^ 2`. After disposing of the trivial case `r = 0`, we show that `λ x, 2 * sqrt (r ^ 2 - x ^ 2)` is equal to the derivative of `λ x, r ^ 2 * arcsin (x / r) + x * sqrt (r ^ 2 - x ^ 2)` everywhere on `Ioo (-r) r` and that those two functions are continuous, then apply the second fundamental theorem of calculus with those facts. Some simple algebra then completes the proof. Note that we choose to define `disc` as a set of points in `ℝ ⨯ ℝ`. This is admittedly not ideal; it would be more natural to define `disc` as a `metric.ball` in `euclidean_space ℝ (fin 2)` (as well as to provide a more general proof in higher dimensions). However, our proof indirectly relies on a number of theorems (particularly `measure_theory.measure.prod_apply`) which do not yet exist for Euclidean space, thus forcing us to use this less-preferable definition. As `measure_theory.pi` continues to develop, it should eventually become possible to redefine `disc` and extend our proof to the n-ball. -/ open set real measure_theory interval_integral open_locale real nnreal /-- A disc of radius `r` is defined as the collection of points `(p.1, p.2)` in `ℝ × ℝ` such that `p.1 ^ 2 + p.2 ^ 2 < r ^ 2`. Note that this definition is not equivalent to `metric.ball (0 : ℝ × ℝ) r`. This was done intentionally because `dist` in `ℝ × ℝ` is defined as the uniform norm, making the `metric.ball` in `ℝ × ℝ` a square, not a disc. See the module docstring for an explanation of why we don't define the disc in Euclidean space. -/ def disc (r : ℝ) := {p : ℝ × ℝ | p.1 ^ 2 + p.2 ^ 2 < r ^ 2} variable (r : ℝ≥0) /-- A disc of radius `r` can be represented as the region between the two curves `λ x, - sqrt (r ^ 2 - x ^ 2)` and `λ x, sqrt (r ^ 2 - x ^ 2)`. -/ lemma disc_eq_region_between : disc r = region_between (λ x, -sqrt (r^2 - x^2)) (λ x, sqrt (r^2 - x^2)) (Ioc (-r) r) := begin ext p, simp only [disc, region_between, mem_set_of_eq, mem_Ioo, mem_Ioc, pi.neg_apply], split; intro h, { cases abs_lt_of_sq_lt_sq' (lt_of_add_lt_of_nonneg_left h (sq_nonneg p.2)) r.2, rw [add_comm, ← lt_sub_iff_add_lt] at h, exact ⟨⟨left, right.le⟩, sq_lt.mp h⟩ }, { rw [add_comm, ← lt_sub_iff_add_lt], exact sq_lt.mpr h.2 }, end /-- The disc is a `measurable_set`. -/ theorem measurable_set_disc : measurable_set (disc r) := by apply measurable_set_lt; apply continuous.measurable; continuity /-- **Area of a Circle**: The area of a disc with radius `r` is `π * r ^ 2`. -/ theorem area_disc : volume (disc r) = nnreal.pi * r ^ 2 := begin let f := λ x, sqrt (r ^ 2 - x ^ 2), let F := λ x, (r:ℝ) ^ 2 * arcsin (r⁻¹ * x) + x * sqrt (r ^ 2 - x ^ 2), have hf : continuous f := by continuity, suffices : ∫ x in -r..r, 2 * f x = nnreal.pi * r ^ 2, { have h : integrable_on f (Ioc (-r) r) := (hf.integrable_on_compact is_compact_Icc).mono_set Ioc_subset_Icc_self, calc volume (disc r) = volume (region_between (λ x, -f x) f (Ioc (-r) r)) : by rw disc_eq_region_between ... = ennreal.of_real (∫ x in Ioc (-r:ℝ) r, (f - has_neg.neg ∘ f) x) : volume_region_between_eq_integral h.neg h measurable_set_Ioc (λ x hx, neg_le_self (sqrt_nonneg _)) ... = ennreal.of_real (∫ x in (-r:ℝ)..r, 2 * f x) : by simp [two_mul, integral_of_le] ... = nnreal.pi * r ^ 2 : by rw_mod_cast [this, ← ennreal.coe_nnreal_eq], }, obtain ⟨hle, (heq | hlt)⟩ := ⟨nnreal.coe_nonneg r, hle.eq_or_lt⟩, { simp [← heq] }, have hderiv : ∀ x ∈ Ioo (-r:ℝ) r, has_deriv_at F (2 * f x) x, { rintros x ⟨hx1, hx2⟩, convert ((has_deriv_at_const x ((r:ℝ)^2)).mul ((has_deriv_at_arcsin _ _).comp x ((has_deriv_at_const x (r:ℝ)⁻¹).mul (has_deriv_at_id' x)))).add ((has_deriv_at_id' x).mul (((has_deriv_at_id' x).pow.const_sub ((r:ℝ)^2)).sqrt _)), { have h : sqrt (1 - x ^ 2 / r ^ 2) * r = sqrt (r ^ 2 - x ^ 2), { rw [← sqrt_sq hle, ← sqrt_mul, sub_mul, sqrt_sq hle, div_mul_eq_mul_div_comm, div_self (pow_ne_zero 2 hlt.ne'), one_mul, mul_one], simpa [sqrt_sq hle, div_le_one (pow_pos hlt 2)] using sq_le_sq' hx1.le hx2.le }, field_simp, rw [h, mul_left_comm, ← sq, neg_mul_eq_mul_neg, mul_div_mul_left (-x^2) _ two_ne_zero, add_left_comm, div_add_div_same, tactic.ring.add_neg_eq_sub, div_sqrt, two_mul] }, { suffices : -(1:ℝ) < r⁻¹ * x, by exact this.ne', calc -(1:ℝ) = r⁻¹ * -r : by simp [hlt.ne'] ... < r⁻¹ * x : by nlinarith [inv_pos.mpr hlt] }, { suffices : (r:ℝ)⁻¹ * x < 1, by exact this.ne, calc (r:ℝ)⁻¹ * x < r⁻¹ * r : by nlinarith [inv_pos.mpr hlt] ... = 1 : inv_mul_cancel hlt.ne' }, { nlinarith } }, have hcont := (by continuity : continuous F).continuous_on, have hcont' := (continuous_const.mul hf).continuous_on, calc ∫ x in -r..r, 2 * f x = F r - F (-r) : integral_eq_sub_of_has_deriv_at'_of_le (neg_le_self r.2) hcont hderiv hcont' ... = nnreal.pi * r ^ 2 : by norm_num [F, inv_mul_cancel hlt.ne', ← mul_div_assoc, mul_comm π], end
4817f17aec14acbb5a4ef6175792311f3570c0a1
82e44445c70db0f03e30d7be725775f122d72f3e
/src/category_theory/monad/algebra.lean
e31a4eef2f99611f74ae32afd4d645bdd4acbbfb
[ "Apache-2.0" ]
permissive
stjordanis/mathlib
51e286d19140e3788ef2c470bc7b953e4991f0c9
2568d41bca08f5d6bf39d915434c8447e21f42ee
refs/heads/master
1,631,748,053,501
1,627,938,886,000
1,627,938,886,000
228,728,358
0
0
Apache-2.0
1,576,630,588,000
1,576,630,587,000
null
UTF-8
Lean
false
false
12,109
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Bhavik Mehta -/ import category_theory.monad.basic import category_theory.adjunction.basic import category_theory.reflects_isomorphisms /-! # Eilenberg-Moore (co)algebras for a (co)monad This file defines Eilenberg-Moore (co)algebras for a (co)monad, and provides the category instance for them. Further it defines the adjoint pair of free and forgetful functors, respectively from and to the original category, as well as the adjoint pair of forgetful and cofree functors, respectively from and to the original category. ## References * [Riehl, *Category theory in context*, Section 5.2.4][riehl2017] -/ namespace category_theory open category universes v₁ u₁ -- morphism levels before object levels. See note [category_theory universes]. variables {C : Type u₁} [category.{v₁} C] namespace monad /-- An Eilenberg-Moore algebra for a monad `T`. cf Definition 5.2.3 in [Riehl][riehl2017]. -/ structure algebra (T : monad C) : Type (max u₁ v₁) := (A : C) (a : (T : C ⥤ C).obj A ⟶ A) (unit' : T.η.app A ≫ a = 𝟙 A . obviously) (assoc' : T.μ.app A ≫ a = (T : C ⥤ C).map a ≫ a . obviously) restate_axiom algebra.unit' restate_axiom algebra.assoc' attribute [reassoc] algebra.unit algebra.assoc namespace algebra variables {T : monad C} /-- A morphism of Eilenberg–Moore algebras for the monad `T`. -/ @[ext] structure hom (A B : algebra T) := (f : A.A ⟶ B.A) (h' : (T : C ⥤ C).map f ≫ B.a = A.a ≫ f . obviously) restate_axiom hom.h' attribute [simp, reassoc] hom.h namespace hom /-- The identity homomorphism for an Eilenberg–Moore algebra. -/ def id (A : algebra T) : hom A A := { f := 𝟙 A.A } instance (A : algebra T) : inhabited (hom A A) := ⟨{ f := 𝟙 _ }⟩ /-- Composition of Eilenberg–Moore algebra homomorphisms. -/ def comp {P Q R : algebra T} (f : hom P Q) (g : hom Q R) : hom P R := { f := f.f ≫ g.f } end hom instance : category_struct (algebra T) := { hom := hom, id := hom.id, comp := @hom.comp _ _ _ } @[simp] lemma comp_eq_comp {A A' A'' : algebra T} (f : A ⟶ A') (g : A' ⟶ A'') : algebra.hom.comp f g = f ≫ g := rfl @[simp] lemma id_eq_id (A : algebra T) : algebra.hom.id A = 𝟙 A := rfl @[simp] lemma id_f (A : algebra T) : (𝟙 A : A ⟶ A).f = 𝟙 A.A := rfl @[simp] lemma comp_f {A A' A'' : algebra T} (f : A ⟶ A') (g : A' ⟶ A'') : (f ≫ g).f = f.f ≫ g.f := rfl /-- The category of Eilenberg-Moore algebras for a monad. cf Definition 5.2.4 in [Riehl][riehl2017]. -/ instance EilenbergMoore : category (algebra T) := {}. /-- To construct an isomorphism of algebras, it suffices to give an isomorphism of the carriers which commutes with the structure morphisms. -/ @[simps] def iso_mk {A B : algebra T} (h : A.A ≅ B.A) (w : (T : C ⥤ C).map h.hom ≫ B.a = A.a ≫ h.hom) : A ≅ B := { hom := { f := h.hom }, inv := { f := h.inv, h' := by { rw [h.eq_comp_inv, category.assoc, ←w, ←functor.map_comp_assoc], simp } } } end algebra variables (T : monad C) /-- The forgetful functor from the Eilenberg-Moore category, forgetting the algebraic structure. -/ @[simps] def forget : algebra T ⥤ C := { obj := λ A, A.A, map := λ A B f, f.f } /-- The free functor from the Eilenberg-Moore category, constructing an algebra for any object. -/ @[simps] def free : C ⥤ algebra T := { obj := λ X, { A := T.obj X, a := T.μ.app X, assoc' := (T.assoc _).symm }, map := λ X Y f, { f := T.map f, h' := T.μ.naturality _ } } instance [inhabited C] : inhabited (algebra T) := ⟨(free T).obj (default C)⟩ /-- The adjunction between the free and forgetful constructions for Eilenberg-Moore algebras for a monad. cf Lemma 5.2.8 of [Riehl][riehl2017]. -/ -- The other two `simps` projection lemmas can be derived from these two, so `simp_nf` complains if -- those are added too @[simps unit counit] def adj : T.free ⊣ T.forget := adjunction.mk_of_hom_equiv { hom_equiv := λ X Y, { to_fun := λ f, T.η.app X ≫ f.f, inv_fun := λ f, { f := T.map f ≫ Y.a, h' := by { dsimp, simp [←Y.assoc, ←T.μ.naturality_assoc] } }, left_inv := λ f, by { ext, dsimp, simp }, right_inv := λ f, begin dsimp only [forget_obj, monad_to_functor_eq_coe], rw [←T.η.naturality_assoc, Y.unit], apply category.comp_id, end }} /-- Given an algebra morphism whose carrier part is an isomorphism, we get an algebra isomorphism. -/ lemma algebra_iso_of_iso {A B : algebra T} (f : A ⟶ B) [is_iso f.f] : is_iso f := ⟨⟨{ f := inv f.f, h' := by { rw [is_iso.eq_comp_inv f.f, category.assoc, ← f.h], simp } }, by tidy⟩⟩ instance forget_reflects_iso : reflects_isomorphisms T.forget := { reflects := λ A B, algebra_iso_of_iso T } instance forget_faithful : faithful T.forget := {} instance : is_right_adjoint T.forget := ⟨T.free, T.adj⟩ @[simp] lemma left_adjoint_forget : left_adjoint T.forget = T.free := rfl @[simp] lemma of_right_adjoint_forget : adjunction.of_right_adjoint T.forget = T.adj := rfl /-- Given a monad morphism from `T₂` to `T₁`, we get a functor from the algebras of `T₁` to algebras of `T₂`. -/ @[simps] def algebra_functor_of_monad_hom {T₁ T₂ : monad C} (h : T₂ ⟶ T₁) : algebra T₁ ⥤ algebra T₂ := { obj := λ A, { A := A.A, a := h.app A.A ≫ A.a, unit' := by { dsimp, simp [A.unit] }, assoc' := by { dsimp, simp [A.assoc] } }, map := λ A₁ A₂ f, { f := f.f } } /-- The identity monad morphism induces the identity functor from the category of algebras to itself. -/ @[simps {rhs_md := semireducible}] def algebra_functor_of_monad_hom_id {T₁ : monad C} : algebra_functor_of_monad_hom (𝟙 T₁) ≅ 𝟭 _ := nat_iso.of_components (λ X, algebra.iso_mk (iso.refl _) (by { dsimp, simp, })) (λ X Y f, by { ext, dsimp, simp }) /-- A composition of monad morphisms gives the composition of corresponding functors. -/ @[simps {rhs_md := semireducible}] def algebra_functor_of_monad_hom_comp {T₁ T₂ T₃ : monad C} (f : T₁ ⟶ T₂) (g : T₂ ⟶ T₃) : algebra_functor_of_monad_hom (f ≫ g) ≅ algebra_functor_of_monad_hom g ⋙ algebra_functor_of_monad_hom f := nat_iso.of_components (λ X, algebra.iso_mk (iso.refl _) (by { dsimp, simp })) (λ X Y f, by { ext, dsimp, simp }) /-- If `f` and `g` are two equal morphisms of monads, then the functors of algebras induced by them are isomorphic. We define it like this as opposed to using `eq_to_iso` so that the components are nicer to prove lemmas about. -/ @[simps {rhs_md := semireducible}] def algebra_functor_of_monad_hom_eq {T₁ T₂ : monad C} {f g : T₁ ⟶ T₂} (h : f = g) : algebra_functor_of_monad_hom f ≅ algebra_functor_of_monad_hom g := nat_iso.of_components (λ X, algebra.iso_mk (iso.refl _) (by { dsimp, simp [h] })) (λ X Y f, by { ext, dsimp, simp }) /-- Isomorphic monads give equivalent categories of algebras. Furthermore, they are equivalent as categories over `C`, that is, we have `algebra_equiv_of_iso_monads h ⋙ forget = forget`. -/ @[simps] def algebra_equiv_of_iso_monads {T₁ T₂ : monad C} (h : T₁ ≅ T₂) : algebra T₁ ≌ algebra T₂ := { functor := algebra_functor_of_monad_hom h.inv, inverse := algebra_functor_of_monad_hom h.hom, unit_iso := algebra_functor_of_monad_hom_id.symm ≪≫ algebra_functor_of_monad_hom_eq (by simp) ≪≫ algebra_functor_of_monad_hom_comp _ _, counit_iso := (algebra_functor_of_monad_hom_comp _ _).symm ≪≫ algebra_functor_of_monad_hom_eq (by simp) ≪≫ algebra_functor_of_monad_hom_id } @[simp] lemma algebra_equiv_of_iso_monads_comp_forget {T₁ T₂ : monad C} (h : T₁ ⟶ T₂) : algebra_functor_of_monad_hom h ⋙ forget _ = forget _ := rfl end monad namespace comonad /-- An Eilenberg-Moore coalgebra for a comonad `T`. -/ @[nolint has_inhabited_instance] structure coalgebra (G : comonad C) : Type (max u₁ v₁) := (A : C) (a : A ⟶ (G : C ⥤ C).obj A) (counit' : a ≫ G.ε.app A = 𝟙 A . obviously) (coassoc' : a ≫ G.δ.app A = a ≫ G.map a . obviously) restate_axiom coalgebra.counit' restate_axiom coalgebra.coassoc' attribute [reassoc] coalgebra.counit coalgebra.coassoc namespace coalgebra variables {G : comonad C} /-- A morphism of Eilenberg-Moore coalgebras for the comonad `G`. -/ @[ext, nolint has_inhabited_instance] structure hom (A B : coalgebra G) := (f : A.A ⟶ B.A) (h' : A.a ≫ (G : C ⥤ C).map f = f ≫ B.a . obviously) restate_axiom hom.h' attribute [simp, reassoc] hom.h namespace hom /-- The identity homomorphism for an Eilenberg–Moore coalgebra. -/ def id (A : coalgebra G) : hom A A := { f := 𝟙 A.A } /-- Composition of Eilenberg–Moore coalgebra homomorphisms. -/ def comp {P Q R : coalgebra G} (f : hom P Q) (g : hom Q R) : hom P R := { f := f.f ≫ g.f } end hom /-- The category of Eilenberg-Moore coalgebras for a comonad. -/ instance : category_struct (coalgebra G) := { hom := hom, id := hom.id, comp := @hom.comp _ _ _ } @[simp] lemma comp_eq_comp {A A' A'' : coalgebra G} (f : A ⟶ A') (g : A' ⟶ A'') : coalgebra.hom.comp f g = f ≫ g := rfl @[simp] lemma id_eq_id (A : coalgebra G) : coalgebra.hom.id A = 𝟙 A := rfl @[simp] lemma id_f (A : coalgebra G) : (𝟙 A : A ⟶ A).f = 𝟙 A.A := rfl @[simp] lemma comp_f {A A' A'' : coalgebra G} (f : A ⟶ A') (g : A' ⟶ A'') : (f ≫ g).f = f.f ≫ g.f := rfl /-- The category of Eilenberg-Moore coalgebras for a comonad. -/ instance EilenbergMoore : category (coalgebra G) := {}. /-- To construct an isomorphism of coalgebras, it suffices to give an isomorphism of the carriers which commutes with the structure morphisms. -/ @[simps] def iso_mk {A B : coalgebra G} (h : A.A ≅ B.A) (w : A.a ≫ (G : C ⥤ C).map h.hom = h.hom ≫ B.a) : A ≅ B := { hom := { f := h.hom }, inv := { f := h.inv, h' := by { rw [h.eq_inv_comp, ←reassoc_of w, ←functor.map_comp], simp } } } end coalgebra variables (G : comonad C) /-- The forgetful functor from the Eilenberg-Moore category, forgetting the coalgebraic structure. -/ @[simps] def forget : coalgebra G ⥤ C := { obj := λ A, A.A, map := λ A B f, f.f } /-- The cofree functor from the Eilenberg-Moore category, constructing a coalgebra for any object. -/ @[simps] def cofree : C ⥤ coalgebra G := { obj := λ X, { A := G.obj X, a := G.δ.app X, coassoc' := (G.coassoc _).symm }, map := λ X Y f, { f := G.map f, h' := (G.δ.naturality _).symm } } /-- The adjunction between the cofree and forgetful constructions for Eilenberg-Moore coalgebras for a comonad. -/ -- The other two `simps` projection lemmas can be derived from these two, so `simp_nf` complains if -- those are added too @[simps unit counit] def adj : G.forget ⊣ G.cofree := adjunction.mk_of_hom_equiv { hom_equiv := λ X Y, { to_fun := λ f, { f := X.a ≫ G.map f, h' := by { dsimp, simp [←coalgebra.coassoc_assoc] } }, inv_fun := λ g, g.f ≫ G.ε.app Y, left_inv := λ f, by { dsimp, rw [category.assoc, G.ε.naturality, functor.id_map, X.counit_assoc] }, right_inv := λ g, begin ext1, dsimp, rw [functor.map_comp, g.h_assoc, cofree_obj_a, comonad.right_counit], apply comp_id, end }} /-- Given a coalgebra morphism whose carrier part is an isomorphism, we get a coalgebra isomorphism. -/ lemma coalgebra_iso_of_iso {A B : coalgebra G} (f : A ⟶ B) [is_iso f.f] : is_iso f := ⟨⟨{ f := inv f.f, h' := by { rw [is_iso.eq_inv_comp f.f, ←f.h_assoc], simp } }, by tidy⟩⟩ instance forget_reflects_iso : reflects_isomorphisms G.forget := { reflects := λ A B, coalgebra_iso_of_iso G } instance forget_faithful : faithful (forget G) := {} instance : is_left_adjoint G.forget := ⟨_, G.adj⟩ @[simp] lemma right_adjoint_forget : right_adjoint G.forget = G.cofree := rfl @[simp] lemma of_left_adjoint_forget : adjunction.of_left_adjoint G.forget = G.adj := rfl end comonad end category_theory
96f4b0571aae0cb766ebd1a26e747ed80083da58
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/category_theory/limits/small_complete.lean
5eed263d4d6083c570768c28f3f79799f7058351
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
2,058
lean
/- Copyright (c) 2020 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta -/ import category_theory.limits.shapes.products import set_theory.cardinal.basic /-! # Any small complete category is a preorder We show that any small category which has all (small) limits is a preorder: In particular, we show that if a small category `C` in universe `u` has products of size `u`, then for any `X Y : C` there is at most one morphism `X ⟶ Y`. Note that in Lean, a preorder category is strictly one where the morphisms are in `Prop`, so we instead show that the homsets are subsingleton. ## References * https://ncatlab.org/nlab/show/complete+small+category#in_classical_logic ## Tags small complete, preorder, Freyd -/ namespace category_theory open category limits open_locale cardinal universe u variables {C : Type u} [small_category C] [has_products.{u} C] /-- A small category with products is a thin category. in Lean, a preorder category is one where the morphisms are in Prop, which is weaker than the usual notion of a preorder/thin category which says that each homset is subsingleton; we show the latter rather than providing a `preorder C` instance. -/ @[priority 100] instance : quiver.is_thin C := λ X Y, ⟨λ r s, begin classical, by_contra r_ne_s, have z : (2 : cardinal) ≤ #(X ⟶ Y), { rw cardinal.two_le_iff, exact ⟨_, _, r_ne_s⟩ }, let md := Σ (Z W : C), Z ⟶ W, let α := #md, apply not_le_of_lt (cardinal.cantor α), let yp : C := ∏ (λ (f : md), Y), transitivity (#(X ⟶ yp)), { apply le_trans (cardinal.power_le_power_right z), rw cardinal.power_def, apply le_of_eq, rw cardinal.eq, refine ⟨⟨pi.lift, λ f k, f ≫ pi.π _ k, _, _⟩⟩, { intros f, ext k, simp }, { intros f, ext ⟨j⟩, simp } }, { apply cardinal.mk_le_of_injective _, { intro f, exact ⟨_, _, f⟩ }, { rintro f g k, cases k, refl } }, end⟩ end category_theory
85fb9bba8e59cbae8e5afcbb2728ae5cec5c5d8a
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/linear_algebra/clifford_algebra/grading.lean
6e9f3a429a8185777fd26f791e50d2464a61d0b8
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
9,361
lean
/- Copyright (c) 2021 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser -/ import linear_algebra.clifford_algebra.basic import data.zmod.basic import ring_theory.graded_algebra.basic /-! # Results about the grading structure of the clifford algebra > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. The main result is `clifford_algebra.graded_algebra`, which says that the clifford algebra is a ℤ₂-graded algebra (or "superalgebra"). -/ namespace clifford_algebra variables {R M : Type*} [comm_ring R] [add_comm_group M] [module R M] variables {Q : quadratic_form R M} open_locale direct_sum variables (Q) /-- The even or odd submodule, defined as the supremum of the even or odd powers of `(ι Q).range`. `even_odd 0` is the even submodule, and `even_odd 1` is the odd submodule. -/ def even_odd (i : zmod 2) : submodule R (clifford_algebra Q) := ⨆ (j : {n : ℕ // ↑n = i}), (ι Q).range ^ (j : ℕ) lemma one_le_even_odd_zero : 1 ≤ even_odd Q 0 := begin refine le_trans _ (le_supr _ ⟨0, nat.cast_zero⟩), exact (pow_zero _).ge, end lemma range_ι_le_even_odd_one : (ι Q).range ≤ even_odd Q 1 := begin refine le_trans _ (le_supr _ ⟨1, nat.cast_one⟩), exact (pow_one _).ge, end lemma ι_mem_even_odd_one (m : M) : ι Q m ∈ even_odd Q 1 := range_ι_le_even_odd_one Q $ linear_map.mem_range_self _ m lemma ι_mul_ι_mem_even_odd_zero (m₁ m₂ : M) : ι Q m₁ * ι Q m₂ ∈ even_odd Q 0 := submodule.mem_supr_of_mem ⟨2, rfl⟩ begin rw [subtype.coe_mk, pow_two], exact submodule.mul_mem_mul (linear_map.mem_range_self (ι Q) m₁) (linear_map.mem_range_self (ι Q) m₂) end lemma even_odd_mul_le (i j : zmod 2) : even_odd Q i * even_odd Q j ≤ even_odd Q (i + j) := begin simp_rw [even_odd, submodule.supr_eq_span, submodule.span_mul_span], apply submodule.span_mono, intros z hz, obtain ⟨x, y, hx, hy, rfl⟩ := hz, obtain ⟨xi, hx'⟩ := set.mem_Union.mp hx, obtain ⟨yi, hy'⟩ := set.mem_Union.mp hy, refine set.mem_Union.mpr ⟨⟨xi + yi, by simp only [nat.cast_add, xi.prop, yi.prop]⟩, _⟩, simp only [subtype.coe_mk, nat.cast_add, pow_add], exact submodule.mul_mem_mul hx' hy', end instance even_odd.graded_monoid : set_like.graded_monoid (even_odd Q) := { one_mem := submodule.one_le.mp (one_le_even_odd_zero Q), mul_mem := λ i j p q hp hq, submodule.mul_le.mp (even_odd_mul_le Q _ _) _ hp _ hq } /-- A version of `clifford_algebra.ι` that maps directly into the graded structure. This is primarily an auxiliary construction used to provide `clifford_algebra.graded_algebra`. -/ def graded_algebra.ι : M →ₗ[R] ⨁ i : zmod 2, even_odd Q i := direct_sum.lof R (zmod 2) (λ i, ↥(even_odd Q i)) 1 ∘ₗ (ι Q).cod_restrict _ (ι_mem_even_odd_one Q) lemma graded_algebra.ι_apply (m : M) : graded_algebra.ι Q m = direct_sum.of (λ i, ↥(even_odd Q i)) 1 (⟨ι Q m, ι_mem_even_odd_one Q m⟩) := rfl lemma graded_algebra.ι_sq_scalar (m : M) : graded_algebra.ι Q m * graded_algebra.ι Q m = algebra_map R _ (Q m) := begin rw [graded_algebra.ι_apply Q, direct_sum.of_mul_of, direct_sum.algebra_map_apply], refine direct_sum.of_eq_of_graded_monoid_eq (sigma.subtype_ext rfl $ ι_sq_scalar _ _), end lemma graded_algebra.lift_ι_eq (i' : zmod 2) (x' : even_odd Q i') : lift Q ⟨by apply graded_algebra.ι Q, graded_algebra.ι_sq_scalar Q⟩ x' = direct_sum.of (λ i, even_odd Q i) i' x' := begin cases x' with x' hx', dsimp only [subtype.coe_mk, direct_sum.lof_eq_of], refine submodule.supr_induction' _ (λ i x hx, _) _ (λ x y hx hy ihx ihy, _) hx', { obtain ⟨i, rfl⟩ := i, dsimp only [subtype.coe_mk] at hx, refine submodule.pow_induction_on_left' _ (λ r, _) (λ x y i hx hy ihx ihy, _) (λ m hm i x hx ih, _) hx, { rw [alg_hom.commutes, direct_sum.algebra_map_apply], refl }, { rw [alg_hom.map_add, ihx, ihy, ←map_add], refl }, { obtain ⟨_, rfl⟩ := hm, rw [alg_hom.map_mul, ih, lift_ι_apply, graded_algebra.ι_apply Q, direct_sum.of_mul_of], refine direct_sum.of_eq_of_graded_monoid_eq (sigma.subtype_ext _ _); dsimp only [graded_monoid.mk, subtype.coe_mk], { rw [nat.succ_eq_add_one, add_comm, nat.cast_add, nat.cast_one] }, refl } }, { rw alg_hom.map_zero, apply eq.symm, apply dfinsupp.single_eq_zero.mpr, refl, }, { rw [alg_hom.map_add, ihx, ihy, ←map_add], refl }, end /-- The clifford algebra is graded by the even and odd parts. -/ instance graded_algebra : graded_algebra (even_odd Q) := graded_algebra.of_alg_hom (even_odd Q) -- while not necessary, the `by apply` makes this elaborate faster (lift Q ⟨by apply graded_algebra.ι Q, graded_algebra.ι_sq_scalar Q⟩) -- the proof from here onward is mostly similar to the `tensor_algebra` case, with some extra -- handling for the `supr` in `even_odd`. (begin ext m, dsimp only [linear_map.comp_apply, alg_hom.to_linear_map_apply, alg_hom.comp_apply, alg_hom.id_apply], rw [lift_ι_apply, graded_algebra.ι_apply Q, direct_sum.coe_alg_hom_of, subtype.coe_mk], end) (by apply graded_algebra.lift_ι_eq Q) lemma supr_ι_range_eq_top : (⨆ i : ℕ, (ι Q).range ^ i) = ⊤ := begin rw [← (direct_sum.decomposition.is_internal (even_odd Q)).submodule_supr_eq_top, eq_comm], calc (⨆ (i : zmod 2) (j : {n // ↑n = i}), (ι Q).range ^ ↑j) = (⨆ (i : Σ i : zmod 2, {n : ℕ // ↑n = i}), (ι Q).range ^ (i.2 : ℕ)) : by rw supr_sigma ... = (⨆ (i : ℕ), (ι Q).range ^ i) : function.surjective.supr_congr (λ i, i.2) (λ i, ⟨⟨_, i, rfl⟩, rfl⟩) (λ _, rfl), end lemma even_odd_is_compl : is_compl (even_odd Q 0) (even_odd Q 1) := (direct_sum.decomposition.is_internal (even_odd Q)).is_compl zero_ne_one $ begin have : (finset.univ : finset (zmod 2)) = {0, 1} := rfl, simpa using congr_arg (coe : finset (zmod 2) → set (zmod 2)) this, end /-- To show a property is true on the even or odd part, it suffices to show it is true on the scalars or vectors (respectively), closed under addition, and under left-multiplication by a pair of vectors. -/ @[elab_as_eliminator] lemma even_odd_induction (n : zmod 2) {P : Π x, x ∈ even_odd Q n → Prop} (hr : ∀ v (h : v ∈ (ι Q).range ^ n.val), P v (submodule.mem_supr_of_mem ⟨n.val, n.nat_cast_zmod_val⟩ h)) (hadd : ∀ {x y hx hy}, P x hx → P y hy → P (x + y) (submodule.add_mem _ hx hy)) (hιι_mul : ∀ m₁ m₂ {x hx}, P x hx → P (ι Q m₁ * ι Q m₂ * x) (zero_add n ▸ set_like.mul_mem_graded (ι_mul_ι_mem_even_odd_zero Q m₁ m₂) hx)) (x : clifford_algebra Q) (hx : x ∈ even_odd Q n) : P x hx := begin apply submodule.supr_induction' _ _ (hr 0 (submodule.zero_mem _)) @hadd, refine subtype.rec _, simp_rw [subtype.coe_mk, zmod.nat_coe_zmod_eq_iff, add_comm n.val], rintros n' ⟨k, rfl⟩ xv, simp_rw [pow_add, pow_mul], refine submodule.mul_induction_on' _ _, { intros a ha b hb, refine submodule.pow_induction_on_left' ((ι Q).range ^ 2) _ _ _ ha, { intro r, simp_rw ←algebra.smul_def, exact hr _ (submodule.smul_mem _ _ hb), }, { intros x y n hx hy, simp_rw add_mul, apply hadd, }, { intros x hx n y hy ihy, revert hx, simp_rw pow_two, refine submodule.mul_induction_on' _ _, { simp_rw linear_map.mem_range, rintros _ ⟨m₁, rfl⟩ _ ⟨m₂, rfl⟩, simp_rw mul_assoc _ y b, refine hιι_mul _ _ ihy, }, { intros x hx y hy ihx ihy, simp_rw add_mul, apply hadd ihx ihy } } }, { intros x y hx hy, apply hadd } end /-- To show a property is true on the even parts, it suffices to show it is true on the scalars, closed under addition, and under left-multiplication by a pair of vectors. -/ @[elab_as_eliminator] lemma even_induction {P : Π x, x ∈ even_odd Q 0 → Prop} (hr : ∀ r : R, P (algebra_map _ _ r) (set_like.algebra_map_mem_graded _ _)) (hadd : ∀ {x y hx hy}, P x hx → P y hy → P (x + y) (submodule.add_mem _ hx hy)) (hιι_mul : ∀ m₁ m₂ {x hx}, P x hx → P (ι Q m₁ * ι Q m₂ * x) (zero_add 0 ▸ set_like.mul_mem_graded (ι_mul_ι_mem_even_odd_zero Q m₁ m₂) hx)) (x : clifford_algebra Q) (hx : x ∈ even_odd Q 0) : P x hx := begin refine even_odd_induction Q 0 (λ rx, _) @hadd hιι_mul x hx, simp_rw [zmod.val_zero, pow_zero], rintro ⟨r, rfl⟩, exact hr r, end /-- To show a property is true on the odd parts, it suffices to show it is true on the vectors, closed under addition, and under left-multiplication by a pair of vectors. -/ @[elab_as_eliminator] lemma odd_induction {P : Π x, x ∈ even_odd Q 1 → Prop} (hι : ∀ v, P (ι Q v) (ι_mem_even_odd_one _ _)) (hadd : ∀ {x y hx hy}, P x hx → P y hy → P (x + y) (submodule.add_mem _ hx hy)) (hιι_mul : ∀ m₁ m₂ {x hx}, P x hx → P (ι Q m₁ * ι Q m₂ * x) (zero_add (1 : zmod 2) ▸ set_like.mul_mem_graded (ι_mul_ι_mem_even_odd_zero Q m₁ m₂) hx)) (x : clifford_algebra Q) (hx : x ∈ even_odd Q 1) : P x hx := begin refine even_odd_induction Q 1 (λ ιv, _) @hadd hιι_mul x hx, simp_rw [zmod.val_one, pow_one], rintro ⟨v, rfl⟩, exact hι v, end end clifford_algebra
d465de1810f4c282c14140a3ab01791fab366a16
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/ring_theory/class_group.lean
59466077dfe9ac295fdf18ad44ca8bf1670fd876
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
15,428
lean
/- Copyright (c) 2021 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen -/ import group_theory.quotient_group import ring_theory.dedekind_domain.ideal /-! # The ideal class group This file defines the ideal class group `class_group R` of fractional ideals of `R` inside its field of fractions. ## Main definitions - `to_principal_ideal` sends an invertible `x : K` to an invertible fractional ideal - `class_group` is the quotient of invertible fractional ideals modulo `to_principal_ideal.range` - `class_group.mk0` sends a nonzero integral ideal in a Dedekind domain to its class ## Main results - `class_group.mk0_eq_mk0_iff` shows the equivalence with the "classical" definition, where `I ~ J` iff `x I = y J` for `x y ≠ (0 : R)` ## Implementation details The definition of `class_group R` involves `fraction_ring R`. However, the API should be completely identical no matter the choice of field of fractions for `R`. -/ variables {R K L : Type*} [comm_ring R] variables [field K] [field L] [decidable_eq L] variables [algebra R K] [is_fraction_ring R K] variables [algebra K L] [finite_dimensional K L] variables [algebra R L] [is_scalar_tower R K L] open_locale non_zero_divisors open is_localization is_fraction_ring fractional_ideal units section variables (R K) /-- `to_principal_ideal R K x` sends `x ≠ 0 : K` to the fractional `R`-ideal generated by `x` -/ @[irreducible] def to_principal_ideal : Kˣ →* (fractional_ideal R⁰ K)ˣ := { to_fun := λ x, ⟨span_singleton _ x, span_singleton _ x⁻¹, by simp only [span_singleton_one, units.mul_inv', span_singleton_mul_span_singleton], by simp only [span_singleton_one, units.inv_mul', span_singleton_mul_span_singleton]⟩, map_mul' := λ x y, ext (by simp only [units.coe_mk, units.coe_mul, span_singleton_mul_span_singleton]), map_one' := ext (by simp only [span_singleton_one, units.coe_mk, units.coe_one]) } local attribute [semireducible] to_principal_ideal variables {R K} @[simp] lemma coe_to_principal_ideal (x : Kˣ) : (to_principal_ideal R K x : fractional_ideal R⁰ K) = span_singleton _ x := rfl @[simp] lemma to_principal_ideal_eq_iff {I : (fractional_ideal R⁰ K)ˣ} {x : Kˣ} : to_principal_ideal R K x = I ↔ span_singleton R⁰ (x : K) = I := units.ext_iff lemma mem_principal_ideals_iff {I : (fractional_ideal R⁰ K)ˣ} : I ∈ (to_principal_ideal R K).range ↔ ∃ x : K, span_singleton R⁰ x = I := begin simp only [monoid_hom.mem_range, to_principal_ideal_eq_iff], split; rintros ⟨x, hx⟩, { exact ⟨x, hx⟩ }, { refine ⟨units.mk0 x _, hx⟩, rintro rfl, simpa [I.ne_zero.symm] using hx }, end instance principal_ideals.normal : (to_principal_ideal R K).range.normal := subgroup.normal_of_comm _ end variables (R) [is_domain R] /-- The ideal class group of `R` is the group of invertible fractional ideals modulo the principal ideals. -/ @[derive(comm_group)] def class_group := (fractional_ideal R⁰ (fraction_ring R))ˣ ⧸ (to_principal_ideal R (fraction_ring R)).range noncomputable instance : inhabited (class_group R) := ⟨1⟩ variables {R K} /-- Send a nonzero fractional ideal to the corresponding class in the class group. -/ noncomputable def class_group.mk : (fractional_ideal R⁰ K)ˣ →* class_group R := (quotient_group.mk' (to_principal_ideal R (fraction_ring R)).range).comp (units.map (fractional_ideal.canonical_equiv R⁰ K (fraction_ring R))) variables (K) /-- Induction principle for the class group: to show something holds for all `x : class_group R`, we can choose a fraction field `K` and show it holds for the equivalence class of each `I : fractional_ideal R⁰ K`. -/ @[elab_as_eliminator] lemma class_group.induction {P : class_group R → Prop} (h : ∀ (I : (fractional_ideal R⁰ K)ˣ), P (class_group.mk I)) (x : class_group R) : P x := quotient_group.induction_on x (λ I, begin convert h (units.map_equiv ↑(canonical_equiv R⁰ (fraction_ring R) K) I), ext : 1, rw [units.coe_map, units.coe_map_equiv], exact (canonical_equiv_flip R⁰ K (fraction_ring R) I).symm end) /-- The definition of the class group does not depend on the choice of field of fractions. -/ noncomputable def class_group.equiv : class_group R ≃* (fractional_ideal R⁰ K)ˣ ⧸ (to_principal_ideal R K).range := quotient_group.congr _ _ (units.map_equiv (fractional_ideal.canonical_equiv R⁰ (fraction_ring R) K : fractional_ideal R⁰ (fraction_ring R) ≃* fractional_ideal R⁰ K)) $ begin ext I, simp only [subgroup.mem_map, mem_principal_ideals_iff, monoid_hom.coe_coe], split, { rintro ⟨I, ⟨x, hx⟩, rfl⟩, refine ⟨fraction_ring.alg_equiv R K x, _⟩, rw [units.coe_map_equiv, ← hx, ring_equiv.coe_to_mul_equiv, canonical_equiv_span_singleton], refl }, { rintro ⟨x, hx⟩, refine ⟨units.map_equiv ↑(canonical_equiv R⁰ K (fraction_ring R)) I, ⟨(fraction_ring.alg_equiv R K).symm x, _⟩, units.ext _⟩, { rw [units.coe_map_equiv, ← hx, ring_equiv.coe_to_mul_equiv, canonical_equiv_span_singleton], refl }, simp only [ring_equiv.coe_to_mul_equiv, canonical_equiv_flip, units.coe_map_equiv] }, end @[simp] lemma class_group.equiv_mk (K' : Type*) [field K'] [algebra R K'] [is_fraction_ring R K'] (I : (fractional_ideal R⁰ K)ˣ) : class_group.equiv K' (class_group.mk I) = quotient_group.mk' _ (units.map_equiv ↑(fractional_ideal.canonical_equiv R⁰ K K') I) := begin rw [class_group.equiv, class_group.mk, monoid_hom.comp_apply, quotient_group.congr_mk'], congr, ext : 1, rw [units.coe_map_equiv, units.coe_map_equiv, units.coe_map], exact fractional_ideal.canonical_equiv_canonical_equiv _ _ _ _ _ end @[simp] lemma class_group.mk_canonical_equiv (K' : Type*) [field K'] [algebra R K'] [is_fraction_ring R K'] (I : (fractional_ideal R⁰ K)ˣ) : class_group.mk (units.map ↑(canonical_equiv R⁰ K K') I : (fractional_ideal R⁰ K')ˣ) = class_group.mk I := by rw [class_group.mk, monoid_hom.comp_apply, ← monoid_hom.comp_apply (units.map _), ← units.map_comp, ← ring_equiv.coe_monoid_hom_trans, fractional_ideal.canonical_equiv_trans_canonical_equiv]; refl /-- Send a nonzero integral ideal to an invertible fractional ideal. -/ noncomputable def fractional_ideal.mk0 [is_dedekind_domain R] : (ideal R)⁰ →* (fractional_ideal R⁰ K)ˣ := { to_fun := λ I, units.mk0 I ((fractional_ideal.coe_to_fractional_ideal_ne_zero (le_refl R⁰)).mpr (mem_non_zero_divisors_iff_ne_zero.mp I.2)), map_one' := by simp, map_mul' := λ x y, by simp } @[simp] lemma fractional_ideal.coe_mk0 [is_dedekind_domain R] (I : (ideal R)⁰) : (fractional_ideal.mk0 K I : fractional_ideal R⁰ K) = I := rfl lemma fractional_ideal.canonical_equiv_mk0 [is_dedekind_domain R] (K' : Type*) [field K'] [algebra R K'] [is_fraction_ring R K'] (I : (ideal R)⁰) : fractional_ideal.canonical_equiv R⁰ K K' (fractional_ideal.mk0 K I) = fractional_ideal.mk0 K' I := by simp only [fractional_ideal.coe_mk0, coe_coe, fractional_ideal.canonical_equiv_coe_ideal] @[simp] lemma fractional_ideal.map_canonical_equiv_mk0 [is_dedekind_domain R] (K' : Type*) [field K'] [algebra R K'] [is_fraction_ring R K'] (I : (ideal R)⁰) : units.map ↑(fractional_ideal.canonical_equiv R⁰ K K') (fractional_ideal.mk0 K I) = fractional_ideal.mk0 K' I := units.ext (fractional_ideal.canonical_equiv_mk0 K K' I) /-- Send a nonzero ideal to the corresponding class in the class group. -/ noncomputable def class_group.mk0 [is_dedekind_domain R] : (ideal R)⁰ →* class_group R := class_group.mk.comp (fractional_ideal.mk0 (fraction_ring R)) @[simp] lemma class_group.mk_mk0 [is_dedekind_domain R] (I : (ideal R)⁰): class_group.mk (fractional_ideal.mk0 K I) = class_group.mk0 I := by rw [class_group.mk0, monoid_hom.comp_apply, ← class_group.mk_canonical_equiv K (fraction_ring R), fractional_ideal.map_canonical_equiv_mk0] @[simp] lemma class_group.equiv_mk0 [is_dedekind_domain R] (I : (ideal R)⁰): class_group.equiv K (class_group.mk0 I) = quotient_group.mk' (to_principal_ideal R K).range (fractional_ideal.mk0 K I) := begin rw [class_group.mk0, monoid_hom.comp_apply, class_group.equiv_mk], congr, ext, simp end lemma class_group.mk0_eq_mk0_iff_exists_fraction_ring [is_dedekind_domain R] {I J : (ideal R)⁰} : class_group.mk0 I = class_group.mk0 J ↔ ∃ (x ≠ (0 : K)), span_singleton R⁰ x * I = J := begin refine (class_group.equiv K).injective.eq_iff.symm.trans _, simp only [class_group.equiv_mk0, quotient_group.mk'_eq_mk', mem_principal_ideals_iff, coe_coe, units.ext_iff, units.coe_mul, fractional_ideal.coe_mk0, exists_prop], split, { rintros ⟨X, ⟨x, hX⟩, hx⟩, refine ⟨x, _, _⟩, { rintro rfl, simpa [X.ne_zero.symm] using hX }, simpa only [hX, mul_comm] using hx }, { rintros ⟨x, hx, eq_J⟩, refine ⟨units.mk0 _ (span_singleton_ne_zero_iff.mpr hx), ⟨x, rfl⟩, _⟩, simpa only [mul_comm] using eq_J } end variables {K} lemma class_group.mk0_eq_mk0_iff [is_dedekind_domain R] {I J : (ideal R)⁰} : class_group.mk0 I = class_group.mk0 J ↔ ∃ (x y : R) (hx : x ≠ 0) (hy : y ≠ 0), ideal.span {x} * (I : ideal R) = ideal.span {y} * J := begin refine (class_group.mk0_eq_mk0_iff_exists_fraction_ring (fraction_ring R)).trans ⟨_, _⟩, { rintros ⟨z, hz, h⟩, obtain ⟨x, ⟨y, hy⟩, rfl⟩ := is_localization.mk'_surjective R⁰ z, refine ⟨x, y, _, mem_non_zero_divisors_iff_ne_zero.mp hy, _⟩, { rintro hx, apply hz, rw [hx, is_fraction_ring.mk'_eq_div, _root_.map_zero, zero_div] }, { exact (fractional_ideal.mk'_mul_coe_ideal_eq_coe_ideal _ hy).mp h } }, { rintros ⟨x, y, hx, hy, h⟩, have hy' : y ∈ R⁰ := mem_non_zero_divisors_iff_ne_zero.mpr hy, refine ⟨is_localization.mk' _ x ⟨y, hy'⟩, _, _⟩, { contrapose! hx, rwa [mk'_eq_iff_eq_mul, zero_mul, ← (algebra_map R (fraction_ring R)).map_zero, (is_fraction_ring.injective R (fraction_ring R)).eq_iff] at hx }, { exact (fractional_ideal.mk'_mul_coe_ideal_eq_coe_ideal _ hy').mpr h } }, end lemma class_group.mk0_surjective [is_dedekind_domain R] : function.surjective (class_group.mk0 : (ideal R)⁰ → class_group R) := begin rintros ⟨I⟩, obtain ⟨a, a_ne_zero', ha⟩ := I.1.2, have a_ne_zero := mem_non_zero_divisors_iff_ne_zero.mp a_ne_zero', have fa_ne_zero : (algebra_map R (fraction_ring R)) a ≠ 0 := is_fraction_ring.to_map_ne_zero_of_mem_non_zero_divisors a_ne_zero', refine ⟨⟨{ carrier := { x | (algebra_map R _ a)⁻¹ * algebra_map R _ x ∈ I.1 }, .. }, _⟩, _⟩, { simp only [ring_hom.map_add, set.mem_set_of_eq, mul_zero, ring_hom.map_mul, mul_add], exact λ _ _ ha hb, submodule.add_mem I ha hb }, { simp only [ring_hom.map_zero, set.mem_set_of_eq, mul_zero, ring_hom.map_mul], exact submodule.zero_mem I }, { intros c _ hb, simp only [smul_eq_mul, set.mem_set_of_eq, mul_zero, ring_hom.map_mul, mul_add, mul_left_comm ((algebra_map R (fraction_ring R)) a)⁻¹], rw ← algebra.smul_def c, exact submodule.smul_mem I c hb }, { rw [mem_non_zero_divisors_iff_ne_zero, submodule.zero_eq_bot, submodule.ne_bot_iff], obtain ⟨x, x_ne, x_mem⟩ := exists_ne_zero_mem_is_integer I.ne_zero, refine ⟨a * x, _, mul_ne_zero a_ne_zero x_ne⟩, change ((algebra_map R _) a)⁻¹ * (algebra_map R _) (a * x) ∈ I.1, rwa [ring_hom.map_mul, ← mul_assoc, inv_mul_cancel fa_ne_zero, one_mul] }, { symmetry, apply quotient.sound, change setoid.r _ _, rw quotient_group.left_rel_apply, refine ⟨units.mk0 (algebra_map R _ a) fa_ne_zero, _⟩, apply @mul_left_cancel _ _ I, rw [← mul_assoc, mul_right_inv, one_mul, eq_comm, mul_comm I], apply units.ext, simp only [fractional_ideal.coe_mk0, fractional_ideal.map_canonical_equiv_mk0, set_like.coe_mk, units.coe_mk0, coe_to_principal_ideal, coe_coe, units.coe_mul, fractional_ideal.eq_span_singleton_mul], split, { intros zJ' hzJ', obtain ⟨zJ, hzJ : (algebra_map R _ a)⁻¹ * algebra_map R _ zJ ∈ ↑I, rfl⟩ := (mem_coe_ideal R⁰).mp hzJ', refine ⟨_, hzJ, _⟩, rw [← mul_assoc, mul_inv_cancel fa_ne_zero, one_mul] }, { intros zI' hzI', obtain ⟨y, hy⟩ := ha zI' hzI', rw [← algebra.smul_def, mem_coe_ideal], refine ⟨y, _, hy⟩, show (algebra_map R _ a)⁻¹ * algebra_map R _ y ∈ (I : fractional_ideal R⁰ (fraction_ring R)), rwa [hy, algebra.smul_def, ← mul_assoc, inv_mul_cancel fa_ne_zero, one_mul] } } end lemma class_group.mk_eq_one_iff {I : (fractional_ideal R⁰ K)ˣ} : class_group.mk I = 1 ↔ (I : submodule R K).is_principal := begin simp only [← (class_group.equiv K).injective.eq_iff, _root_.map_one, class_group.equiv_mk, quotient_group.mk'_apply, quotient_group.eq_one_iff, monoid_hom.mem_range, units.ext_iff, coe_to_principal_ideal, units.coe_map_equiv, fractional_ideal.canonical_equiv_self, coe_coe, ring_equiv.coe_mul_equiv_refl, mul_equiv.refl_apply], refine ⟨λ ⟨x, hx⟩, ⟨⟨x, by rw [← hx, coe_span_singleton]⟩⟩, _⟩, unfreezingI { intros hI }, obtain ⟨x, hx⟩ := @submodule.is_principal.principal _ _ _ _ _ _ hI, have hx' : (I : fractional_ideal R⁰ K) = span_singleton R⁰ x, { apply subtype.coe_injective, rw [hx, coe_span_singleton] }, refine ⟨units.mk0 x _, _⟩, { intro x_eq, apply units.ne_zero I, simp [hx', x_eq] }, simp [hx'] end lemma class_group.mk0_eq_one_iff [is_dedekind_domain R] {I : ideal R} (hI : I ∈ (ideal R)⁰) : class_group.mk0 ⟨I, hI⟩ = 1 ↔ I.is_principal := class_group.mk_eq_one_iff.trans (coe_submodule_is_principal R _) /-- The class group of principal ideal domain is finite (in fact a singleton). See `class_group.fintype_of_admissible` for a finiteness proof that works for rings of integers of global fields. -/ noncomputable instance [is_principal_ideal_ring R] : fintype (class_group R) := { elems := {1}, complete := begin refine class_group.induction (fraction_ring R) (λ I, _), rw finset.mem_singleton, exact class_group.mk_eq_one_iff.mpr (I : fractional_ideal R⁰ (fraction_ring R)).is_principal end } /-- The class number of a principal ideal domain is `1`. -/ lemma card_class_group_eq_one [is_principal_ideal_ring R] : fintype.card (class_group R) = 1 := begin rw fintype.card_eq_one_iff, use 1, refine class_group.induction (fraction_ring R) (λ I, _), exact class_group.mk_eq_one_iff.mpr (I : fractional_ideal R⁰ (fraction_ring R)).is_principal end /-- The class number is `1` iff the ring of integers is a principal ideal domain. -/ lemma card_class_group_eq_one_iff [is_dedekind_domain R] [fintype (class_group R)] : fintype.card (class_group R) = 1 ↔ is_principal_ideal_ring R := begin split, swap, { introsI, convert card_class_group_eq_one, assumption, }, rw fintype.card_eq_one_iff, rintros ⟨I, hI⟩, have eq_one : ∀ J : class_group R, J = 1 := λ J, trans (hI J) (hI 1).symm, refine ⟨λ I, _⟩, by_cases hI : I = ⊥, { rw hI, exact bot_is_principal }, exact (class_group.mk0_eq_one_iff (mem_non_zero_divisors_iff_ne_zero.mpr hI)).mp (eq_one _), end
fb2942191502c34694ca6de1e379fa11fee00a85
6b02ce66658141f3e0aa3dfa88cd30bbbb24d17b
/stage0/src/Lean/Elab/Do.lean
a62cd4143b904d352fecbd8aaa8e2de1669371fb
[ "Apache-2.0" ]
permissive
pbrinkmeier/lean4
d31991fd64095e64490cb7157bcc6803f9c48af4
32fd82efc2eaf1232299e930ec16624b370eac39
refs/heads/master
1,681,364,001,662
1,618,425,427,000
1,618,425,427,000
358,314,562
0
0
Apache-2.0
1,618,504,558,000
1,618,501,999,000
null
UTF-8
Lean
false
false
66,221
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.Elab.Term import Lean.Elab.Binders import Lean.Elab.Match import Lean.Elab.Quotation.Util import Lean.Parser.Do namespace Lean.Elab.Term open Lean.Parser.Term open Meta private def getDoSeqElems (doSeq : Syntax) : List Syntax := if doSeq.getKind == `Lean.Parser.Term.doSeqBracketed then doSeq[1].getArgs.toList.map fun arg => arg[0] else if doSeq.getKind == `Lean.Parser.Term.doSeqIndent then doSeq[0].getArgs.toList.map fun arg => arg[0] else [] private def getDoSeq (doStx : Syntax) : Syntax := doStx[1] @[builtinTermElab liftMethod] def elabLiftMethod : TermElab := fun stx _ => throwErrorAt stx "invalid use of `(<- ...)`, must be nested inside a 'do' expression" /-- Return true if we should not lift `(<- ...)` actions nested in the syntax nodes with the given kind. -/ private def liftMethodDelimiter (k : SyntaxNodeKind) : Bool := k == `Lean.Parser.Term.do || k == `Lean.Parser.Term.doSeqIndent || k == `Lean.Parser.Term.doSeqBracketed || k == `Lean.Parser.Term.termReturn || k == `Lean.Parser.Term.termUnless || k == `Lean.Parser.Term.termTry || k == `Lean.Parser.Term.termFor private partial def hasLiftMethod : Syntax → Bool | Syntax.node k args => if liftMethodDelimiter k then false -- NOTE: We don't check for lifts in quotations here, which doesn't break anything but merely makes this rare case a -- bit slower else if k == `Lean.Parser.Term.liftMethod then true else args.any hasLiftMethod | _ => false structure ExtractMonadResult where m : Expr α : Expr hasBindInst : Expr expectedType : Expr private def mkIdBindFor (type : Expr) : TermElabM ExtractMonadResult := do let u ← getDecLevel type let id := Lean.mkConst `Id [u] let idBindVal := Lean.mkConst `Id.hasBind [u] pure { m := id, hasBindInst := idBindVal, α := type, expectedType := mkApp id type } private def extractBind (expectedType? : Option Expr) : TermElabM ExtractMonadResult := do match expectedType? with | none => throwError "invalid 'do' notation, expected type is not available" | some expectedType => let type ← withReducible $ whnf expectedType if type.getAppFn.isMVar then throwError "invalid 'do' notation, expected type is not available" match type with | Expr.app m α _ => try let bindInstType ← mkAppM `Bind #[m] let bindInstVal ← synthesizeInst bindInstType pure { m := m, hasBindInst := bindInstVal, α := α, expectedType := expectedType } catch _ => mkIdBindFor type | _ => mkIdBindFor type namespace Do /- A `doMatch` alternative. `vars` is the array of variables declared by `patterns`. -/ structure Alt (σ : Type) where ref : Syntax vars : Array Name patterns : Syntax rhs : σ deriving Inhabited /- Auxiliary datastructure for representing a `do` code block, and compiling "reassignments" (e.g., `x := x + 1`). We convert `Code` into a `Syntax` term representing the: - `do`-block, or - the visitor argument for the `forIn` combinator. We say the following constructors are terminals: - `break`: for interrupting a `for x in s` - `continue`: for interrupting the current iteration of a `for x in s` - `return e`: for returning `e` as the result for the whole `do` computation block - `action a`: for executing action `a` as a terminal - `ite`: if-then-else - `match`: pattern matching - `jmp` a goto to a join-point We say the terminals `break`, `continue`, `action`, and `return` are "exit points" Note that, `return e` is not equivalent to `action (pure e)`. Here is an example: ``` def f (x : Nat) : IO Unit := do if x == 0 then return () IO.println "hello" ``` Executing `#eval f 0` will not print "hello". Now, consider ``` def g (x : Nat) : IO Unit := do if x == 0 then pure () IO.println "hello" ``` The `if` statement is essentially a noop, and "hello" is printed when we execute `g 0`. - `decl` represents all declaration-like `doElem`s (e.g., `let`, `have`, `let rec`). The field `stx` is the actual `doElem`, `vars` is the array of variables declared by it, and `cont` is the next instruction in the `do` code block. `vars` is an array since we have declarations such as `let (a, b) := s`. - `reassign` is an reassignment-like `doElem` (e.g., `x := x + 1`). - `joinpoint` is a join point declaration: an auxiliary `let`-declaration used to represent the control-flow. - `seq a k` executes action `a`, ignores its result, and then executes `k`. We also store the do-elements `dbg_trace` and `assert!` as actions in a `seq`. A code block `C` is well-formed if - For every `jmp ref j as` in `C`, there is a `joinpoint j ps b k` and `jmp ref j as` is in `k`, and `ps.size == as.size` -/ inductive Code where | decl (xs : Array Name) (doElem : Syntax) (k : Code) | reassign (xs : Array Name) (doElem : Syntax) (k : Code) /- The Boolean value in `params` indicates whether we should use `(x : typeof! x)` when generating term Syntax or not -/ | joinpoint (name : Name) (params : Array (Name × Bool)) (body : Code) (k : Code) | seq (action : Syntax) (k : Code) | action (action : Syntax) | «break» (ref : Syntax) | «continue» (ref : Syntax) | «return» (ref : Syntax) (val : Syntax) /- Recall that an if-then-else may declare a variable using `optIdent` for the branches `thenBranch` and `elseBranch`. We store the variable name at `var?`. -/ | ite (ref : Syntax) (h? : Option Name) (optIdent : Syntax) (cond : Syntax) (thenBranch : Code) (elseBranch : Code) | «match» (ref : Syntax) (discrs : Syntax) (optType : Syntax) (alts : Array (Alt Code)) | jmp (ref : Syntax) (jpName : Name) (args : Array Syntax) deriving Inhabited /- A code block, and the collection of variables updated by it. -/ structure CodeBlock where code : Code uvars : NameSet := {} -- set of variables updated by `code` private def nameSetToArray (s : NameSet) : Array Name := s.fold (fun (xs : Array Name) x => xs.push x) #[] private def varsToMessageData (vars : Array Name) : MessageData := MessageData.joinSep (vars.toList.map fun n => MessageData.ofName (n.simpMacroScopes)) " " partial def CodeBlocl.toMessageData (codeBlock : CodeBlock) : MessageData := let us := MessageData.ofList $ (nameSetToArray codeBlock.uvars).toList.map MessageData.ofName let rec loop : Code → MessageData | Code.decl xs _ k => m!"let {varsToMessageData xs} := ...\n{loop k}" | Code.reassign xs _ k => m!"{varsToMessageData xs} := ...\n{loop k}" | Code.joinpoint n ps body k => m!"let {n.simpMacroScopes} {varsToMessageData (ps.map Prod.fst)} := {indentD (loop body)}\n{loop k}" | Code.seq e k => m!"{e}\n{loop k}" | Code.action e => e | Code.ite _ _ _ c t e => m!"if {c} then {indentD (loop t)}\nelse{loop e}" | Code.jmp _ j xs => m!"jmp {j.simpMacroScopes} {xs.toList}" | Code.«break» _ => m!"break {us}" | Code.«continue» _ => m!"continue {us}" | Code.«return» _ v => m!"return {v} {us}" | Code.«match» _ ds t alts => m!"match {ds} with" ++ alts.foldl (init := m!"") fun acc alt => acc ++ m!"\n| {alt.patterns} => {loop alt.rhs}" loop codeBlock.code /- Return true if the give code contains an exit point that satisfies `p` -/ @[inline] partial def hasExitPointPred (c : Code) (p : Code → Bool) : Bool := let rec @[specialize] loop : Code → Bool | Code.decl _ _ k => loop k | Code.reassign _ _ k => loop k | Code.joinpoint _ _ b k => loop b || loop k | Code.seq _ k => loop k | Code.ite _ _ _ _ t e => loop t || loop e | Code.«match» _ _ _ alts => alts.any (loop ·.rhs) | Code.jmp _ _ _ => false | c => p c loop c def hasExitPoint (c : Code) : Bool := hasExitPointPred c fun c => true def hasReturn (c : Code) : Bool := hasExitPointPred c fun | Code.«return» _ _ => true | _ => false def hasTerminalAction (c : Code) : Bool := hasExitPointPred c fun | Code.«action» _ => true | _ => false def hasBreakContinue (c : Code) : Bool := hasExitPointPred c fun | Code.«break» _ => true | Code.«continue» _ => true | _ => false def hasBreakContinueReturn (c : Code) : Bool := hasExitPointPred c fun | Code.«break» _ => true | Code.«continue» _ => true | Code.«return» _ _ => true | _ => false def mkAuxDeclFor {m} [Monad m] [MonadQuotation m] (e : Syntax) (mkCont : Syntax → m Code) : m Code := withRef e <| withFreshMacroScope do let y ← `(y) let yName := y.getId let doElem ← `(doElem| let y ← $e:term) -- Add elaboration hint for producing sane error message let y ← `(ensureExpectedType% "type mismatch, result value" $y) let k ← mkCont y pure $ Code.decl #[yName] doElem k /- Convert `action _ e` instructions in `c` into `let y ← e; jmp _ jp (xs y)`. -/ partial def convertTerminalActionIntoJmp (code : Code) (jp : Name) (xs : Array Name) : MacroM Code := let rec loop : Code → MacroM Code | Code.decl xs stx k => do Code.decl xs stx (← loop k) | Code.reassign xs stx k => do Code.reassign xs stx (← loop k) | Code.joinpoint n ps b k => do Code.joinpoint n ps (← loop b) (← loop k) | Code.seq e k => do Code.seq e (← loop k) | Code.ite ref x? h c t e => do Code.ite ref x? h c (← loop t) (← loop e) | Code.«match» ref ds t alts => do Code.«match» ref ds t (← alts.mapM fun alt => do pure { alt with rhs := (← loop alt.rhs) }) | Code.action e => mkAuxDeclFor e fun y => let ref := e -- We jump to `jp` with xs **and** y let jmpArgs := xs.map $ mkIdentFrom ref let jmpArgs := jmpArgs.push y pure $ Code.jmp ref jp jmpArgs | c => pure c loop code structure JPDecl where name : Name params : Array (Name × Bool) body : Code def attachJP (jpDecl : JPDecl) (k : Code) : Code := Code.joinpoint jpDecl.name jpDecl.params jpDecl.body k def attachJPs (jpDecls : Array JPDecl) (k : Code) : Code := jpDecls.foldr attachJP k def mkFreshJP (ps : Array (Name × Bool)) (body : Code) : TermElabM JPDecl := do let ps ← if ps.isEmpty then let y ← mkFreshUserName `y pure #[(y, false)] else pure ps -- Remark: the compiler frontend implemented in C++ currently detects jointpoints created by -- the "do" notation by testing the name. See hack at method `visit_let` at `lcnf.cpp` -- We will remove this hack when we re-implement the compiler frontend in Lean. let name ← mkFreshUserName `_do_jp pure { name := name, params := ps, body := body } def mkFreshJP' (xs : Array Name) (body : Code) : TermElabM JPDecl := mkFreshJP (xs.map fun x => (x, true)) body def addFreshJP (ps : Array (Name × Bool)) (body : Code) : StateRefT (Array JPDecl) TermElabM Name := do let jp ← mkFreshJP ps body modify fun (jps : Array JPDecl) => jps.push jp pure jp.name def insertVars (rs : NameSet) (xs : Array Name) : NameSet := xs.foldl (·.insert ·) rs def eraseVars (rs : NameSet) (xs : Array Name) : NameSet := xs.foldl (·.erase ·) rs def eraseOptVar (rs : NameSet) (x? : Option Name) : NameSet := match x? with | none => rs | some x => rs.insert x /- Create a new jointpoint for `c`, and jump to it with the variables `rs` -/ def mkSimpleJmp (ref : Syntax) (rs : NameSet) (c : Code) : StateRefT (Array JPDecl) TermElabM Code := do let xs := nameSetToArray rs let jp ← addFreshJP (xs.map fun x => (x, true)) c if xs.isEmpty then let unit ← `(Unit.unit) return Code.jmp ref jp #[unit] else return Code.jmp ref jp (xs.map $ mkIdentFrom ref) /- Create a new joinpoint that takes `rs` and `val` as arguments. `val` must be syntax representing a pure value. The body of the joinpoint is created using `mkJPBody yFresh`, where `yFresh` is a fresh variable created by this method. -/ def mkJmp (ref : Syntax) (rs : NameSet) (val : Syntax) (mkJPBody : Syntax → MacroM Code) : StateRefT (Array JPDecl) TermElabM Code := do let xs := nameSetToArray rs let args := xs.map $ mkIdentFrom ref let args := args.push val let yFresh ← mkFreshUserName `y let ps := xs.map fun x => (x, true) let ps := ps.push (yFresh, false) let jpBody ← liftMacroM $ mkJPBody (mkIdentFrom ref yFresh) let jp ← addFreshJP ps jpBody pure $ Code.jmp ref jp args /- `pullExitPointsAux rs c` auxiliary method for `pullExitPoints`, `rs` is the set of update variable in the current path. -/ partial def pullExitPointsAux : NameSet → Code → StateRefT (Array JPDecl) TermElabM Code | rs, Code.decl xs stx k => do Code.decl xs stx (← pullExitPointsAux (eraseVars rs xs) k) | rs, Code.reassign xs stx k => do Code.reassign xs stx (← pullExitPointsAux (insertVars rs xs) k) | rs, Code.joinpoint j ps b k => do Code.joinpoint j ps (← pullExitPointsAux rs b) (← pullExitPointsAux rs k) | rs, Code.seq e k => do Code.seq e (← pullExitPointsAux rs k) | rs, Code.ite ref x? o c t e => do Code.ite ref x? o c (← pullExitPointsAux (eraseOptVar rs x?) t) (← pullExitPointsAux (eraseOptVar rs x?) e) | rs, Code.«match» ref ds t alts => do Code.«match» ref ds t (← alts.mapM fun alt => do pure { alt with rhs := (← pullExitPointsAux (eraseVars rs alt.vars) alt.rhs) }) | rs, c@(Code.jmp _ _ _) => pure c | rs, Code.«break» ref => mkSimpleJmp ref rs (Code.«break» ref) | rs, Code.«continue» ref => mkSimpleJmp ref rs (Code.«continue» ref) | rs, Code.«return» ref val => mkJmp ref rs val (fun y => pure $ Code.«return» ref y) | rs, Code.action e => -- We use `mkAuxDeclFor` because `e` is not pure. mkAuxDeclFor e fun y => let ref := e mkJmp ref rs y (fun yFresh => do pure $ Code.action (← `(Pure.pure $yFresh))) /- Auxiliary operation for adding new variables to the collection of updated variables in a CodeBlock. When a new variable is not already in the collection, but is shadowed by some declaration in `c`, we create auxiliary join points to make sure we preserve the semantics of the code block. Example: suppose we have the code block `print x; let x := 10; return x`. And we want to extend it with the reassignment `x := x + 1`. We first use `pullExitPoints` to create ``` let jp (x!1) := return x!1; print x; let x := 10; jmp jp x ``` and then we add the reassignment ``` x := x + 1 let jp (x!1) := return x!1; print x; let x := 10; jmp jp x ``` Note that we created a fresh variable `x!1` to avoid accidental name capture. As another example, consider ``` print x; let x := 10 y := y + 1; return x; ``` We transform it into ``` let jp (y x!1) := return x!1; print x; let x := 10 y := y + 1; jmp jp y x ``` and then we add the reassignment as in the previous example. We need to include `y` in the jump, because each exit point is implicitly returning the set of update variables. We implement the method as follows. Let `us` be `c.uvars`, then 1- for each `return _ y` in `c`, we create a join point `let j (us y!1) := return y!1` and replace the `return _ y` with `jmp us y` 2- for each `break`, we create a join point `let j (us) := break` and replace the `break` with `jmp us`. 3- Same as 2 for `continue`. -/ def pullExitPoints (c : Code) : TermElabM Code := do if hasExitPoint c then let (c, jpDecls) ← (pullExitPointsAux {} c).run #[] pure $ attachJPs jpDecls c else pure c partial def extendUpdatedVarsAux (c : Code) (ws : NameSet) : TermElabM Code := let rec update : Code → TermElabM Code | Code.joinpoint j ps b k => do Code.joinpoint j ps (← update b) (← update k) | Code.seq e k => do Code.seq e (← update k) | c@(Code.«match» ref ds t alts) => do if alts.any fun alt => alt.vars.any fun x => ws.contains x then -- If a pattern variable is shadowing a variable in ws, we `pullExitPoints` pullExitPoints c else Code.«match» ref ds t (← alts.mapM fun alt => do pure { alt with rhs := (← update alt.rhs) }) | Code.ite ref none o c t e => do Code.ite ref none o c (← update t) (← update e) | c@(Code.ite ref (some h) o cond t e) => do if ws.contains h then -- if the `h` at `if h:c then t else e` shadows a variable in `ws`, we `pullExitPoints` pullExitPoints c else Code.ite ref (some h) o cond (← update t) (← update e) | Code.reassign xs stx k => do Code.reassign xs stx (← update k) | c@(Code.decl xs stx k) => do if xs.any fun x => ws.contains x then -- One the declared variables is shadowing a variable in `ws` pullExitPoints c else Code.decl xs stx (← update k) | c => pure c update c /- Extend the set of updated variables. It assumes `ws` is a super set of `c.uvars`. We **cannot** simply update the field `c.uvars`, because `c` may have shadowed some variable in `ws`. See discussion at `pullExitPoints`. -/ partial def extendUpdatedVars (c : CodeBlock) (ws : NameSet) : TermElabM CodeBlock := do if ws.any fun x => !c.uvars.contains x then -- `ws` contains a variable that is not in `c.uvars`, but in `c.dvars` (i.e., it has been shadowed) pure { code := (← extendUpdatedVarsAux c.code ws), uvars := ws } else pure { c with uvars := ws } private def union (s₁ s₂ : NameSet) : NameSet := s₁.fold (·.insert ·) s₂ /- Given two code blocks `c₁` and `c₂`, make sure they have the same set of updated variables. Let `ws` the union of the updated variables in `c₁‵ and ‵c₂`. We use `extendUpdatedVars c₁ ws` and `extendUpdatedVars c₂ ws` -/ def homogenize (c₁ c₂ : CodeBlock) : TermElabM (CodeBlock × CodeBlock) := do let ws := union c₁.uvars c₂.uvars let c₁ ← extendUpdatedVars c₁ ws let c₂ ← extendUpdatedVars c₂ ws pure (c₁, c₂) /- Extending code blocks with variable declarations: `let x : t := v` and `let x : t ← v`. We remove `x` from the collection of updated varibles. Remark: `stx` is the syntax for the declaration (e.g., `letDecl`), and `xs` are the variables declared by it. It is an array because we have let-declarations that declare multiple variables. Example: `let (x, y) := t` -/ def mkVarDeclCore (xs : Array Name) (stx : Syntax) (c : CodeBlock) : CodeBlock := { code := Code.decl xs stx c.code, uvars := eraseVars c.uvars xs } /- Extending code blocks with reassignments: `x : t := v` and `x : t ← v`. Remark: `stx` is the syntax for the declaration (e.g., `letDecl`), and `xs` are the variables declared by it. It is an array because we have let-declarations that declare multiple variables. Example: `(x, y) ← t` -/ def mkReassignCore (xs : Array Name) (stx : Syntax) (c : CodeBlock) : TermElabM CodeBlock := do let us := c.uvars let ws := insertVars us xs -- If `xs` contains a new updated variable, then we must use `extendUpdatedVars`. -- See discussion at `pullExitPoints` let code ← if xs.any fun x => !us.contains x then extendUpdatedVarsAux c.code ws else pure c.code pure { code := Code.reassign xs stx code, uvars := ws } def mkSeq (action : Syntax) (c : CodeBlock) : CodeBlock := { c with code := Code.seq action c.code } def mkTerminalAction (action : Syntax) : CodeBlock := { code := Code.action action } def mkReturn (ref : Syntax) (val : Syntax) : CodeBlock := { code := Code.«return» ref val } def mkBreak (ref : Syntax) : CodeBlock := { code := Code.«break» ref } def mkContinue (ref : Syntax) : CodeBlock := { code := Code.«continue» ref } def mkIte (ref : Syntax) (optIdent : Syntax) (cond : Syntax) (thenBranch : CodeBlock) (elseBranch : CodeBlock) : TermElabM CodeBlock := do let x? := if optIdent.isNone then none else some optIdent[0].getId let (thenBranch, elseBranch) ← homogenize thenBranch elseBranch pure { code := Code.ite ref x? optIdent cond thenBranch.code elseBranch.code, uvars := thenBranch.uvars, } private def mkUnit : MacroM Syntax := `((⟨⟩ : PUnit)) private def mkPureUnit : MacroM Syntax := `(pure PUnit.unit) def mkPureUnitAction : MacroM CodeBlock := do mkTerminalAction (← mkPureUnit) def mkUnless (cond : Syntax) (c : CodeBlock) : MacroM CodeBlock := do let thenBranch ← mkPureUnitAction pure { c with code := Code.ite (← getRef) none mkNullNode cond thenBranch.code c.code } def mkMatch (ref : Syntax) (discrs : Syntax) (optType : Syntax) (alts : Array (Alt CodeBlock)) : TermElabM CodeBlock := do -- nary version of homogenize let ws := alts.foldl (union · ·.rhs.uvars) {} let alts ← alts.mapM fun alt => do let rhs ← extendUpdatedVars alt.rhs ws pure { ref := alt.ref, vars := alt.vars, patterns := alt.patterns, rhs := rhs.code : Alt Code } pure { code := Code.«match» ref discrs optType alts, uvars := ws } /- Return a code block that executes `terminal` and then `k` with the value produced by `terminal`. This method assumes `terminal` is a terminal -/ def concat (terminal : CodeBlock) (kRef : Syntax) (y? : Option Name) (k : CodeBlock) : TermElabM CodeBlock := do unless hasTerminalAction terminal.code do throwErrorAt kRef "'do' element is unreachable" let (terminal, k) ← homogenize terminal k let xs := nameSetToArray k.uvars let y ← match y? with | some y => pure y | none => mkFreshUserName `y let ps := xs.map fun x => (x, true) let ps := ps.push (y, false) let jpDecl ← mkFreshJP ps k.code let jp := jpDecl.name let terminal ← liftMacroM $ convertTerminalActionIntoJmp terminal.code jp xs pure { code := attachJP jpDecl terminal, uvars := k.uvars } def getLetIdDeclVar (letIdDecl : Syntax) : Name := letIdDecl[0].getId def getPatternVarNames (pvars : Array PatternVar) : Array Name := pvars.filterMap fun | PatternVar.localVar x => some x | _ => none -- support both regular and syntax match def getPatternVarsEx (pattern : Syntax) : TermElabM (Array Name) := getPatternVarNames <$> getPatternVars pattern <|> Array.map Syntax.getId <$> Quotation.getPatternVars pattern def getPatternsVarsEx (patterns : Array Syntax) : TermElabM (Array Name) := getPatternVarNames <$> getPatternsVars patterns <|> Array.map Syntax.getId <$> Quotation.getPatternsVars patterns def getLetPatDeclVars (letPatDecl : Syntax) : TermElabM (Array Name) := do let pattern := letPatDecl[0] getPatternVarsEx pattern def getLetEqnsDeclVar (letEqnsDecl : Syntax) : Name := letEqnsDecl[0].getId def getLetDeclVars (letDecl : Syntax) : TermElabM (Array Name) := do let arg := letDecl[0] if arg.getKind == `Lean.Parser.Term.letIdDecl then pure #[getLetIdDeclVar arg] else if arg.getKind == `Lean.Parser.Term.letPatDecl then getLetPatDeclVars arg else if arg.getKind == `Lean.Parser.Term.letEqnsDecl then pure #[getLetEqnsDeclVar arg] else throwError "unexpected kind of let declaration" def getDoLetVars (doLet : Syntax) : TermElabM (Array Name) := -- leading_parser "let " >> optional "mut " >> letDecl getLetDeclVars doLet[2] def getDoHaveVar (doHave : Syntax) : Name := /- `leading_parser "have " >> Term.haveDecl` where ``` haveDecl := leading_parser optIdent >> termParser >> (haveAssign <|> fromTerm <|> byTactic) optIdent := optional (try (ident >> " : ")) ``` -/ let optIdent := doHave[1][0] if optIdent.isNone then `this else optIdent[0].getId def getDoLetRecVars (doLetRec : Syntax) : TermElabM (Array Name) := do -- letRecDecls is an array of `(group (optional attributes >> letDecl))` let letRecDecls := doLetRec[1][0].getSepArgs let letDecls := letRecDecls.map fun p => p[2] let mut allVars := #[] for letDecl in letDecls do let vars ← getLetDeclVars letDecl allVars := allVars ++ vars pure allVars -- ident >> optType >> leftArrow >> termParser def getDoIdDeclVar (doIdDecl : Syntax) : Name := doIdDecl[0].getId -- termParser >> leftArrow >> termParser >> optional (" | " >> termParser) def getDoPatDeclVars (doPatDecl : Syntax) : TermElabM (Array Name) := do let pattern := doPatDecl[0] getPatternVarsEx pattern -- leading_parser "let " >> optional "mut " >> (doIdDecl <|> doPatDecl) def getDoLetArrowVars (doLetArrow : Syntax) : TermElabM (Array Name) := do let decl := doLetArrow[2] if decl.getKind == `Lean.Parser.Term.doIdDecl then pure #[getDoIdDeclVar decl] else if decl.getKind == `Lean.Parser.Term.doPatDecl then getDoPatDeclVars decl else throwError "unexpected kind of 'do' declaration" def getDoReassignVars (doReassign : Syntax) : TermElabM (Array Name) := do let arg := doReassign[0] if arg.getKind == `Lean.Parser.Term.letIdDecl then pure #[getLetIdDeclVar arg] else if arg.getKind == `Lean.Parser.Term.letPatDecl then getLetPatDeclVars arg else throwError "unexpected kind of reassignment" def mkDoSeq (doElems : Array Syntax) : Syntax := mkNode `Lean.Parser.Term.doSeqIndent #[mkNullNode $ doElems.map fun doElem => mkNullNode #[doElem, mkNullNode]] def mkSingletonDoSeq (doElem : Syntax) : Syntax := mkDoSeq #[doElem] /- If the given syntax is a `doIf`, return an equivalente `doIf` that has an `else` but no `else if`s or `if let`s. -/ private def expandDoIf? (stx : Syntax) : MacroM (Option Syntax) := match stx with | `(doElem|if $p:doIfProp then $t else $e) => pure none | `(doElem|if%$i $cond:doIfCond then $t $[else if%$is $conds:doIfCond then $ts]* $[else $e?]?) => withRef stx do let mut e := e?.getD (← `(doSeq|pure PUnit.unit)) let mut eIsSeq := true for (i, cond, t) in Array.zip (is.reverse.push i) (Array.zip (conds.reverse.push cond) (ts.reverse.push t)) do e ← if eIsSeq then e else `(doSeq|$e:doElem) e ← withRef cond <| match cond with | `(doIfCond|let $pat := $d) => `(doElem| match%$i $d:term with | $pat:term => $t | _ => $e) | `(doIfCond|let $pat ← $d) => `(doElem| match%$i ← $d with | $pat:term => $t | _ => $e) | _ => `(doElem| if%$i $cond:doIfCond then $t else $e) eIsSeq := false return some e | _ => pure none structure DoIfView where ref : Syntax optIdent : Syntax cond : Syntax thenBranch : Syntax elseBranch : Syntax /- This method assumes `expandDoIf?` is not applicable. -/ private def mkDoIfView (doIf : Syntax) : MacroM DoIfView := do pure { ref := doIf, optIdent := doIf[1][0], cond := doIf[1][1], thenBranch := doIf[3], elseBranch := doIf[5][1] } /- We use `MProd` instead of `Prod` to group values when expanding the `do` notation. `MProd` is a universe monomorphic product. The motivation is to generate simpler universe constraints in code that was not written by the user. Note that we are not restricting the macro power since the `Bind.bind` combinator already forces values computed by monadic actions to be in the same universe. -/ private def mkTuple (elems : Array Syntax) : MacroM Syntax := do if elems.size == 0 then mkUnit else if elems.size == 1 then pure elems[0] else (elems.extract 0 (elems.size - 1)).foldrM (fun elem tuple => `(MProd.mk $elem $tuple)) (elems.back) /- Return `some action` if `doElem` is a `doExpr <action>`-/ def isDoExpr? (doElem : Syntax) : Option Syntax := if doElem.getKind == `Lean.Parser.Term.doExpr then some doElem[0] else none /-- Given `uvars := #[a_1, ..., a_n, a_{n+1}]` construct term ``` let a_1 := x.1 let x := x.2 let a_2 := x.1 let x := x.2 ... let a_n := x.1 let a_{n+1} := x.2 body ``` Special cases - `uvars := #[]` => `body` - `uvars := #[a]` => `let a := x; body` We use this method when expanding the `for-in` notation. -/ private def destructTuple (uvars : Array Name) (x : Syntax) (body : Syntax) : MacroM Syntax := do if uvars.size == 0 then return body else if uvars.size == 1 then `(let $(← mkIdentFromRef uvars[0]):ident := $x; $body) else destruct uvars.toList x body where destruct (as : List Name) (x : Syntax) (body : Syntax) : MacroM Syntax := do match as with | [a, b] => `(let $(← mkIdentFromRef a):ident := $x.1; let $(← mkIdentFromRef b):ident := $x.2; $body) | a :: as => withFreshMacroScope do let rest ← destruct as (← `(x)) body `(let $(← mkIdentFromRef a):ident := $x.1; let x := $x.2; $rest) | _ => unreachable! /- The procedure `ToTerm.run` converts a `CodeBlock` into a `Syntax` term. We use this method to convert 1- The `CodeBlock` for a root `do ...` term into a `Syntax` term. This kind of `CodeBlock` never contains `break` nor `continue`. Moreover, the collection of updated variables is not packed into the result. Thus, we have two kinds of exit points - `Code.action e` which is converted into `e` - `Code.return _ e` which is converted into `pure e` We use `Kind.regular` for this case. 2- The `CodeBlock` for `b` at `for x in xs do b`. In this case, we need to generate a `Syntax` term representing a function for the `xs.forIn` combinator. a) If `b` contain a `Code.return _ a` exit point. The generated `Syntax` term has type `m (ForInStep (Option α × σ))`, where `a : α`, and the `σ` is the type of the tuple of variables reassigned by `b`. We use `Kind.forInWithReturn` for this case b) If `b` does not contain a `Code.return _ a` exit point. Then, the generated `Syntax` term has type `m (ForInStep σ)`. We use `Kind.forIn` for this case. 3- The `CodeBlock` `c` for a `do` sequence nested in a monadic combinator (e.g., `MonadExcept.tryCatch`). The generated `Syntax` term for `c` must inform whether `c` "exited" using `Code.action`, `Code.return`, `Code.break` or `Code.continue`. We use the auxiliary types `DoResult`s for storing this information. For example, the auxiliary type `DoResultPBC α σ` is used for a code block that exits with `Code.action`, **and** `Code.break`/`Code.continue`, `α` is the type of values produced by the exit `action`, and `σ` is the type of the tuple of reassigned variables. The type `DoResult α β σ` is usedf for code blocks that exit with `Code.action`, `Code.return`, **and** `Code.break`/`Code.continue`, `β` is the type of the returned values. We don't use `DoResult α β σ` for all cases because: a) The elaborator would not be able to infer all type parameters without extra annotations. For example, if the code block does not contain `Code.return _ _`, the elaborator will not be able to infer `β`. b) We need to pattern match on the result produced by the combinator (e.g., `MonadExcept.tryCatch`), but we don't want to consider "unreachable" cases. We do not distinguish between cases that contain `break`, but not `continue`, and vice versa. When listing all cases, we use `a` to indicate the code block contains `Code.action _`, `r` for `Code.return _ _`, and `b/c` for a code block that contains `Code.break _` or `Code.continue _`. - `a`: `Kind.regular`, type `m (α × σ)` - `r`: `Kind.regular`, type `m (α × σ)` Note that the code that pattern matches on the result will behave differently in this case. It produces `return a` for this case, and `pure a` for the previous one. - `b/c`: `Kind.nestedBC`, type `m (DoResultBC σ)` - `a` and `r`: `Kind.nestedPR`, type `m (DoResultPR α β σ)` - `a` and `bc`: `Kind.nestedSBC`, type `m (DoResultSBC α σ)` - `r` and `bc`: `Kind.nestedSBC`, type `m (DoResultSBC α σ)` Again the code that pattern matches on the result will behave differently in this case and the previous one. It produces `return a` for the constructor `DoResultSPR.pureReturn a u` for this case, and `pure a` for the previous case. - `a`, `r`, `b/c`: `Kind.nestedPRBC`, type type `m (DoResultPRBC α β σ)` Here is the recipe for adding new combinators with nested `do`s. Example: suppose we want to support `repeat doSeq`. Assuming we have `repeat : m α → m α` 1- Convert `doSeq` into `codeBlock : CodeBlock` 2- Create term `term` using `mkNestedTerm code m uvars a r bc` where `code` is `codeBlock.code`, `uvars` is an array containing `codeBlock.uvars`, `m` is a `Syntax` representing the Monad, and `a` is true if `code` contains `Code.action _`, `r` is true if `code` contains `Code.return _ _`, `bc` is true if `code` contains `Code.break _` or `Code.continue _`. Remark: for combinators such as `repeat` that take a single `doSeq`, all arguments, but `m`, are extracted from `codeBlock`. 3- Create the term `repeat $term` 4- and then, convert it into a `doSeq` using `matchNestedTermResult ref (repeat $term) uvsar a r bc` -/ namespace ToTerm inductive Kind where | regular | forIn | forInWithReturn | nestedBC | nestedPR | nestedSBC | nestedPRBC instance : Inhabited Kind := ⟨Kind.regular⟩ def Kind.isRegular : Kind → Bool | Kind.regular => true | _ => false structure Context where m : Syntax -- Syntax to reference the monad associated with the do notation. uvars : Array Name kind : Kind abbrev M := ReaderT Context MacroM def mkUVarTuple : M Syntax := do let ctx ← read let uvarIdents ← ctx.uvars.mapM mkIdentFromRef mkTuple uvarIdents def returnToTerm (val : Syntax) : M Syntax := do let ctx ← read let u ← mkUVarTuple match ctx.kind with | Kind.regular => if ctx.uvars.isEmpty then `(Pure.pure $val) else `(Pure.pure (MProd.mk $val $u)) | Kind.forIn => `(Pure.pure (ForInStep.done $u)) | Kind.forInWithReturn => `(Pure.pure (ForInStep.done (MProd.mk (some $val) $u))) | Kind.nestedBC => unreachable! | Kind.nestedPR => `(Pure.pure (DoResultPR.«return» $val $u)) | Kind.nestedSBC => `(Pure.pure (DoResultSBC.«pureReturn» $val $u)) | Kind.nestedPRBC => `(Pure.pure (DoResultPRBC.«return» $val $u)) def continueToTerm : M Syntax := do let ctx ← read let u ← mkUVarTuple match ctx.kind with | Kind.regular => unreachable! | Kind.forIn => `(Pure.pure (ForInStep.yield $u)) | Kind.forInWithReturn => `(Pure.pure (ForInStep.yield (MProd.mk none $u))) | Kind.nestedBC => `(Pure.pure (DoResultBC.«continue» $u)) | Kind.nestedPR => unreachable! | Kind.nestedSBC => `(Pure.pure (DoResultSBC.«continue» $u)) | Kind.nestedPRBC => `(Pure.pure (DoResultPRBC.«continue» $u)) def breakToTerm : M Syntax := do let ctx ← read let u ← mkUVarTuple match ctx.kind with | Kind.regular => unreachable! | Kind.forIn => `(Pure.pure (ForInStep.done $u)) | Kind.forInWithReturn => `(Pure.pure (ForInStep.done (MProd.mk none $u))) | Kind.nestedBC => `(Pure.pure (DoResultBC.«break» $u)) | Kind.nestedPR => unreachable! | Kind.nestedSBC => `(Pure.pure (DoResultSBC.«break» $u)) | Kind.nestedPRBC => `(Pure.pure (DoResultPRBC.«break» $u)) def actionTerminalToTerm (action : Syntax) : M Syntax := withRef action <| withFreshMacroScope do let ctx ← read let u ← mkUVarTuple match ctx.kind with | Kind.regular => if ctx.uvars.isEmpty then pure action else `(Bind.bind $action fun y => Pure.pure (MProd.mk y $u)) | Kind.forIn => `(Bind.bind $action fun (_ : PUnit) => Pure.pure (ForInStep.yield $u)) | Kind.forInWithReturn => `(Bind.bind $action fun (_ : PUnit) => Pure.pure (ForInStep.yield (MProd.mk none $u))) | Kind.nestedBC => unreachable! | Kind.nestedPR => `(Bind.bind $action fun y => (Pure.pure (DoResultPR.«pure» y $u))) | Kind.nestedSBC => `(Bind.bind $action fun y => (Pure.pure (DoResultSBC.«pureReturn» y $u))) | Kind.nestedPRBC => `(Bind.bind $action fun y => (Pure.pure (DoResultPRBC.«pure» y $u))) def seqToTerm (action : Syntax) (k : Syntax) : M Syntax := withRef action <| withFreshMacroScope do if action.getKind == `Lean.Parser.Term.doDbgTrace then let msg := action[1] `(dbg_trace $msg; $k) else if action.getKind == `Lean.Parser.Term.doAssert then let cond := action[1] `(assert! $cond; $k) else let action ← withRef action `(($action : $((←read).m) PUnit)) `(Bind.bind $action (fun (_ : PUnit) => $k)) def declToTerm (decl : Syntax) (k : Syntax) : M Syntax := withRef decl <| withFreshMacroScope do let kind := decl.getKind if kind == `Lean.Parser.Term.doLet then let letDecl := decl[2] `(let $letDecl:letDecl; $k) else if kind == `Lean.Parser.Term.doLetRec then let letRecToken := decl[0] let letRecDecls := decl[1] pure $ mkNode `Lean.Parser.Term.letrec #[letRecToken, letRecDecls, mkNullNode, k] else if kind == `Lean.Parser.Term.doLetArrow then let arg := decl[2] let ref := arg if arg.getKind == `Lean.Parser.Term.doIdDecl then let id := arg[0] let type := expandOptType ref arg[1] let doElem := arg[3] -- `doElem` must be a `doExpr action`. See `doLetArrowToCode` match isDoExpr? doElem with | some action => let action ← withRef action `(($action : $((← read).m) $type)) `(Bind.bind $action (fun ($id:ident : $type) => $k)) | none => Macro.throwErrorAt decl "unexpected kind of 'do' declaration" else Macro.throwErrorAt decl "unexpected kind of 'do' declaration" else if kind == `Lean.Parser.Term.doHave then -- The `have` term is of the form `"have " >> haveDecl >> optSemicolon termParser` let args := decl.getArgs let args := args ++ #[mkNullNode /- optional ';' -/, k] pure $ mkNode `Lean.Parser.Term.«have» args else Macro.throwErrorAt decl "unexpected kind of 'do' declaration" def reassignToTerm (reassign : Syntax) (k : Syntax) : MacroM Syntax := withRef reassign <| withFreshMacroScope do let kind := reassign.getKind if kind == `Lean.Parser.Term.doReassign then -- doReassign := leading_parser (letIdDecl <|> letPatDecl) let arg := reassign[0] if arg.getKind == `Lean.Parser.Term.letIdDecl then -- letIdDecl := leading_parser ident >> many (ppSpace >> bracketedBinder) >> optType >> " := " >> termParser let x := arg[0] let val := arg[4] let newVal ← `(ensureTypeOf% $x $(quote "invalid reassignment, value") $val) let arg := arg.setArg 4 newVal let letDecl := mkNode `Lean.Parser.Term.letDecl #[arg] `(let $letDecl:letDecl; $k) else -- TODO: ensure the types did not change let letDecl := mkNode `Lean.Parser.Term.letDecl #[arg] `(let $letDecl:letDecl; $k) else -- Note that `doReassignArrow` is expanded by `doReassignArrowToCode Macro.throwErrorAt reassign "unexpected kind of 'do' reassignment" def mkIte (optIdent : Syntax) (cond : Syntax) (thenBranch : Syntax) (elseBranch : Syntax) : MacroM Syntax := do if optIdent.isNone then `(ite $cond $thenBranch $elseBranch) else let h := optIdent[0] `(dite $cond (fun $h => $thenBranch) (fun $h => $elseBranch)) def mkJoinPoint (j : Name) (ps : Array (Name × Bool)) (body : Syntax) (k : Syntax) : M Syntax := withRef body <| withFreshMacroScope do let pTypes ← ps.mapM fun ⟨id, useTypeOf⟩ => do if useTypeOf then `(typeOf% $(← mkIdentFromRef id)) else `(_) let ps ← ps.mapM fun ⟨id, useTypeOf⟩ => mkIdentFromRef id /- We use `let_delayed` instead of `let` for joinpoints to make sure `$k` is elaborated before `$body`. By elaborating `$k` first, we "learn" more about `$body`'s type. For example, consider the following example `do` expression ``` def f (x : Nat) : IO Unit := do if x > 0 then IO.println "x is not zero" -- Error is here IO.mkRef true ``` it is expanded into ``` def f (x : Nat) : IO Unit := do let jp (u : Unit) : IO _ := IO.mkRef true; if x > 0 then IO.println "not zero" jp () else jp () ``` If we use the regular `let` instead of `let_delayed`, the joinpoint `jp` will be elaborated and its type will be inferred to be `Unit → IO (IO.Ref Bool)`. Then, we get a typing error at `jp ()`. By using `let_delayed`, we first elaborate `if x > 0 ...` and learn that `jp` has type `Unit → IO Unit`. Then, we get the expected type mismatch error at `IO.mkRef true`. -/ `(let_delayed $(← mkIdentFromRef j):ident $[($ps : $pTypes)]* : $((← read).m) _ := $body; $k) def mkJmp (ref : Syntax) (j : Name) (args : Array Syntax) : Syntax := Syntax.mkApp (mkIdentFrom ref j) args partial def toTerm : Code → M Syntax | Code.«return» ref val => withRef ref <| returnToTerm val | Code.«continue» ref => withRef ref continueToTerm | Code.«break» ref => withRef ref breakToTerm | Code.action e => actionTerminalToTerm e | Code.joinpoint j ps b k => do mkJoinPoint j ps (← toTerm b) (← toTerm k) | Code.jmp ref j args => pure $ mkJmp ref j args | Code.decl _ stx k => do declToTerm stx (← toTerm k) | Code.reassign _ stx k => do reassignToTerm stx (← toTerm k) | Code.seq stx k => do seqToTerm stx (← toTerm k) | Code.ite ref _ o c t e => withRef ref <| do mkIte o c (← toTerm t) (← toTerm e) | Code.«match» ref discrs optType alts => do let mut termAlts := #[] for alt in alts do let rhs ← toTerm alt.rhs let termAlt := mkNode `Lean.Parser.Term.matchAlt #[mkAtomFrom alt.ref "|", alt.patterns, mkAtomFrom alt.ref "=>", rhs] termAlts := termAlts.push termAlt let termMatchAlts := mkNode `Lean.Parser.Term.matchAlts #[mkNullNode termAlts] pure $ mkNode `Lean.Parser.Term.«match» #[mkAtomFrom ref "match", discrs, optType, mkAtomFrom ref "with", termMatchAlts] def run (code : Code) (m : Syntax) (uvars : Array Name := #[]) (kind := Kind.regular) : MacroM Syntax := do let term ← toTerm code { m := m, kind := kind, uvars := uvars } pure term /- Given - `a` is true if the code block has a `Code.action _` exit point - `r` is true if the code block has a `Code.return _ _` exit point - `bc` is true if the code block has a `Code.break _` or `Code.continue _` exit point generate Kind. See comment at the beginning of the `ToTerm` namespace. -/ def mkNestedKind (a r bc : Bool) : Kind := match a, r, bc with | true, false, false => Kind.regular | false, true, false => Kind.regular | false, false, true => Kind.nestedBC | true, true, false => Kind.nestedPR | true, false, true => Kind.nestedSBC | false, true, true => Kind.nestedSBC | true, true, true => Kind.nestedPRBC | false, false, false => unreachable! def mkNestedTerm (code : Code) (m : Syntax) (uvars : Array Name) (a r bc : Bool) : MacroM Syntax := do ToTerm.run code m uvars (mkNestedKind a r bc) /- Given a term `term` produced by `ToTerm.run`, pattern match on its result. See comment at the beginning of the `ToTerm` namespace. - `a` is true if the code block has a `Code.action _` exit point - `r` is true if the code block has a `Code.return _ _` exit point - `bc` is true if the code block has a `Code.break _` or `Code.continue _` exit point The result is a sequence of `doElem` -/ def matchNestedTermResult (term : Syntax) (uvars : Array Name) (a r bc : Bool) : MacroM (List Syntax) := do let toDoElems (auxDo : Syntax) : List Syntax := getDoSeqElems (getDoSeq auxDo) let u ← mkTuple (← uvars.mapM mkIdentFromRef) match a, r, bc with | true, false, false => if uvars.isEmpty then toDoElems (← `(do $term:term)) else toDoElems (← `(do let r ← $term:term; $u:term := r.2; pure r.1)) | false, true, false => if uvars.isEmpty then toDoElems (← `(do let r ← $term:term; return r)) else toDoElems (← `(do let r ← $term:term; $u:term := r.2; return r.1)) | false, false, true => toDoElems <$> `(do let r ← $term:term; match r with | DoResultBC.«break» u => $u:term := u; break | DoResultBC.«continue» u => $u:term := u; continue) | true, true, false => toDoElems <$> `(do let r ← $term:term; match r with | DoResultPR.«pure» a u => $u:term := u; pure a | DoResultPR.«return» b u => $u:term := u; return b) | true, false, true => toDoElems <$> `(do let r ← $term:term; match r with | DoResultSBC.«pureReturn» a u => $u:term := u; pure a | DoResultSBC.«break» u => $u:term := u; break | DoResultSBC.«continue» u => $u:term := u; continue) | false, true, true => toDoElems <$> `(do let r ← $term:term; match r with | DoResultSBC.«pureReturn» a u => $u:term := u; return a | DoResultSBC.«break» u => $u:term := u; break | DoResultSBC.«continue» u => $u:term := u; continue) | true, true, true => toDoElems <$> `(do let r ← $term:term; match r with | DoResultPRBC.«pure» a u => $u:term := u; pure a | DoResultPRBC.«return» a u => $u:term := u; return a | DoResultPRBC.«break» u => $u:term := u; break | DoResultPRBC.«continue» u => $u:term := u; continue) | false, false, false => unreachable! end ToTerm def isMutableLet (doElem : Syntax) : Bool := let kind := doElem.getKind (kind == `Lean.Parser.Term.doLetArrow || kind == `Lean.Parser.Term.doLet) && !doElem[1].isNone namespace ToCodeBlock structure Context where ref : Syntax m : Syntax -- Syntax representing the monad associated with the do notation. mutableVars : NameSet := {} insideFor : Bool := false abbrev M := ReaderT Context TermElabM @[inline] def withNewMutableVars {α} (newVars : Array Name) (mutable : Bool) (x : M α) : M α := withReader (fun ctx => if mutable then { ctx with mutableVars := insertVars ctx.mutableVars newVars } else ctx) x def checkReassignable (xs : Array Name) : M Unit := do let throwInvalidReassignment (x : Name) : M Unit := throwError "'{x.simpMacroScopes}' cannot be reassigned" let ctx ← read for x in xs do unless ctx.mutableVars.contains x do throwInvalidReassignment x @[inline] def withFor {α} (x : M α) : M α := withReader (fun ctx => { ctx with insideFor := true }) x structure ToForInTermResult where uvars : Array Name term : Syntax def mkForInBody (x : Syntax) (forInBody : CodeBlock) : M ToForInTermResult := do let ctx ← read let uvars := forInBody.uvars let uvars := nameSetToArray uvars let term ← liftMacroM $ ToTerm.run forInBody.code ctx.m uvars (if hasReturn forInBody.code then ToTerm.Kind.forInWithReturn else ToTerm.Kind.forIn) pure ⟨uvars, term⟩ def ensureInsideFor : M Unit := unless (← read).insideFor do throwError "invalid 'do' element, it must be inside 'for'" def ensureEOS (doElems : List Syntax) : M Unit := unless doElems.isEmpty do throwError "must be last element in a 'do' sequence" private partial def expandLiftMethodAux (inQuot : Bool) : Syntax → StateT (List Syntax) MacroM Syntax | stx@(Syntax.node k args) => if liftMethodDelimiter k then pure stx else if k == `Lean.Parser.Term.liftMethod && !inQuot then withFreshMacroScope do let term := args[1] let term ← expandLiftMethodAux inQuot term let auxDoElem ← `(doElem| let a ← $term:term) modify fun s => s ++ [auxDoElem] `(a) else do let inAntiquot := stx.isAntiquot && !stx.isEscapedAntiquot let args ← args.mapM (expandLiftMethodAux (inQuot && !inAntiquot || stx.isQuot)) pure $ Syntax.node k args | stx => pure stx def expandLiftMethod (doElem : Syntax) : MacroM (List Syntax × Syntax) := do if !hasLiftMethod doElem then pure ([], doElem) else let (doElem, doElemsNew) ← (expandLiftMethodAux false doElem).run [] pure (doElemsNew, doElem) def checkLetArrowRHS (doElem : Syntax) : M Unit := do let kind := doElem.getKind if kind == `Lean.Parser.Term.doLetArrow || kind == `Lean.Parser.Term.doLet || kind == `Lean.Parser.Term.doLetRec || kind == `Lean.Parser.Term.doHave || kind == `Lean.Parser.Term.doReassign || kind == `Lean.Parser.Term.doReassignArrow then throwErrorAt doElem "invalid kind of value '{kind}' in an assignment" /- Generate `CodeBlock` for `doReturn` which is of the form ``` "return " >> optional termParser ``` `doElems` is only used for sanity checking. -/ def doReturnToCode (doReturn : Syntax) (doElems: List Syntax) : M CodeBlock := withRef doReturn do ensureEOS doElems let argOpt := doReturn[1] let arg ← if argOpt.isNone then liftMacroM mkUnit else pure argOpt[0] return mkReturn (← getRef) arg structure Catch where x : Syntax optType : Syntax codeBlock : CodeBlock def getTryCatchUpdatedVars (tryCode : CodeBlock) (catches : Array Catch) (finallyCode? : Option CodeBlock) : NameSet := let ws := tryCode.uvars let ws := catches.foldl (fun ws alt => union alt.codeBlock.uvars ws) ws let ws := match finallyCode? with | none => ws | some c => union c.uvars ws ws def tryCatchPred (tryCode : CodeBlock) (catches : Array Catch) (finallyCode? : Option CodeBlock) (p : Code → Bool) : Bool := p tryCode.code || catches.any (fun «catch» => p «catch».codeBlock.code) || match finallyCode? with | none => false | some finallyCode => p finallyCode.code mutual /- "Concatenate" `c` with `doSeqToCode doElems` -/ partial def concatWith (c : CodeBlock) (doElems : List Syntax) : M CodeBlock := match doElems with | [] => pure c | nextDoElem :: _ => do let k ← doSeqToCode doElems let ref := nextDoElem concat c ref none k /- Generate `CodeBlock` for `doLetArrow; doElems` `doLetArrow` is of the form ``` "let " >> optional "mut " >> (doIdDecl <|> doPatDecl) ``` where ``` def doIdDecl := leading_parser ident >> optType >> leftArrow >> doElemParser def doPatDecl := leading_parser termParser >> leftArrow >> doElemParser >> optional (" | " >> doElemParser) ``` -/ partial def doLetArrowToCode (doLetArrow : Syntax) (doElems : List Syntax) : M CodeBlock := do let ref := doLetArrow let decl := doLetArrow[2] if decl.getKind == `Lean.Parser.Term.doIdDecl then let y := decl[0].getId let doElem := decl[3] let k ← withNewMutableVars #[y] (isMutableLet doLetArrow) (doSeqToCode doElems) match isDoExpr? doElem with | some action => pure $ mkVarDeclCore #[y] doLetArrow k | none => checkLetArrowRHS doElem let c ← doSeqToCode [doElem] match doElems with | [] => pure c | kRef::_ => concat c kRef y k else if decl.getKind == `Lean.Parser.Term.doPatDecl then let pattern := decl[0] let doElem := decl[2] let optElse := decl[3] if optElse.isNone then withFreshMacroScope do let auxDo ← if isMutableLet doLetArrow then `(do let discr ← $doElem; let mut $pattern:term := discr) else `(do let discr ← $doElem; let $pattern:term := discr) doSeqToCode <| getDoSeqElems (getDoSeq auxDo) ++ doElems else if isMutableLet doLetArrow then throwError "'mut' is currently not supported in let-decls with 'else' case" let contSeq := mkDoSeq doElems.toArray let elseSeq := mkSingletonDoSeq optElse[1] let auxDo ← `(do let discr ← $doElem; match discr with | $pattern:term => $contSeq | _ => $elseSeq) doSeqToCode <| getDoSeqElems (getDoSeq auxDo) else throwError "unexpected kind of 'do' declaration" /- Generate `CodeBlock` for `doReassignArrow; doElems` `doReassignArrow` is of the form ``` (doIdDecl <|> doPatDecl) ``` -/ partial def doReassignArrowToCode (doReassignArrow : Syntax) (doElems : List Syntax) : M CodeBlock := do let ref := doReassignArrow let decl := doReassignArrow[0] if decl.getKind == `Lean.Parser.Term.doIdDecl then let doElem := decl[3] let y := decl[0] let auxDo ← `(do let r ← $doElem; $y:ident := r) doSeqToCode <| getDoSeqElems (getDoSeq auxDo) ++ doElems else if decl.getKind == `Lean.Parser.Term.doPatDecl then let pattern := decl[0] let doElem := decl[2] let optElse := decl[3] if optElse.isNone then withFreshMacroScope do let auxDo ← `(do let discr ← $doElem; $pattern:term := discr) doSeqToCode <| getDoSeqElems (getDoSeq auxDo) ++ doElems else throwError "reassignment with `|` (i.e., \"else clause\") is not currently supported" else throwError "unexpected kind of 'do' reassignment" /- Generate `CodeBlock` for `doIf; doElems` `doIf` is of the form ``` "if " >> optIdent >> termParser >> " then " >> doSeq >> many (group (try (group (" else " >> " if ")) >> optIdent >> termParser >> " then " >> doSeq)) >> optional (" else " >> doSeq) ``` -/ partial def doIfToCode (doIf : Syntax) (doElems : List Syntax) : M CodeBlock := do let view ← liftMacroM $ mkDoIfView doIf let thenBranch ← doSeqToCode (getDoSeqElems view.thenBranch) let elseBranch ← doSeqToCode (getDoSeqElems view.elseBranch) let ite ← mkIte view.ref view.optIdent view.cond thenBranch elseBranch concatWith ite doElems /- Generate `CodeBlock` for `doUnless; doElems` `doUnless` is of the form ``` "unless " >> termParser >> "do " >> doSeq ``` -/ partial def doUnlessToCode (doUnless : Syntax) (doElems : List Syntax) : M CodeBlock := withRef doUnless do let ref := doUnless let cond := doUnless[1] let doSeq := doUnless[3] let body ← doSeqToCode (getDoSeqElems doSeq) let unlessCode ← liftMacroM <| mkUnless cond body concatWith unlessCode doElems /- Generate `CodeBlock` for `doFor; doElems` `doFor` is of the form ``` def doForDecl := leading_parser termParser >> " in " >> withForbidden "do" termParser def doFor := leading_parser "for " >> sepBy1 doForDecl ", " >> "do " >> doSeq ``` -/ partial def doForToCode (doFor : Syntax) (doElems : List Syntax) : M CodeBlock := do let doForDecls := doFor[1].getSepArgs if doForDecls.size > 1 then /- Expand ``` for x in xs, y in ys do body ``` into ``` let s := toStream ys for x in xs do match Stream.next? s with | none => break | some (y, s') => s := s' body ``` -/ -- Extract second element let doForDecl := doForDecls[1] let y := doForDecl[0] let ys := doForDecl[2] let doForDecls := doForDecls.eraseIdx 1 let body := doFor[3] withFreshMacroScope do let toStreamFn ← withRef ys `(toStream) let auxDo ← `(do let mut s := $toStreamFn:ident $ys for $doForDecls:doForDecl,* do match Stream.next? s with | none => break | some ($y, s') => s := s' do $body) doSeqToCode (getDoSeqElems (getDoSeq auxDo) ++ doElems) else withRef doFor do let x := doForDecls[0][0] let xs := doForDecls[0][2] let forElems := getDoSeqElems doFor[3] let forInBodyCodeBlock ← withFor (doSeqToCode forElems) let ⟨uvars, forInBody⟩ ← mkForInBody x forInBodyCodeBlock let uvarsTuple ← liftMacroM do mkTuple (← uvars.mapM mkIdentFromRef) if hasReturn forInBodyCodeBlock.code then let forInBody ← liftMacroM <| destructTuple uvars (← `(r)) forInBody let forInTerm ← `(forIn% $(xs) (MProd.mk none $uvarsTuple) fun $x r => let r := r.2; $forInBody) let auxDo ← `(do let r ← $forInTerm:term; $uvarsTuple:term := r.2; match r.1 with | none => Pure.pure (ensureExpectedType% "type mismatch, 'for'" PUnit.unit) | some a => return ensureExpectedType% "type mismatch, 'for'" a) doSeqToCode (getDoSeqElems (getDoSeq auxDo) ++ doElems) else let forInBody ← liftMacroM <| destructTuple uvars (← `(r)) forInBody let forInTerm ← `(forIn% $(xs) $uvarsTuple fun $x r => $forInBody) if doElems.isEmpty then let auxDo ← `(do let r ← $forInTerm:term; $uvarsTuple:term := r; Pure.pure (ensureExpectedType% "type mismatch, 'for'" PUnit.unit)) doSeqToCode <| getDoSeqElems (getDoSeq auxDo) else let auxDo ← `(do let r ← $forInTerm:term; $uvarsTuple:term := r) doSeqToCode <| getDoSeqElems (getDoSeq auxDo) ++ doElems /-- Generate `CodeBlock` for `doMatch; doElems` -/ partial def doMatchToCode (doMatch : Syntax) (doElems: List Syntax) : M CodeBlock := do let ref := doMatch let discrs := doMatch[1] let optType := doMatch[2] let matchAlts := doMatch[4][0].getArgs -- Array of `doMatchAlt` let alts ← matchAlts.mapM fun matchAlt => do let patterns := matchAlt[1] let vars ← getPatternsVarsEx patterns.getSepArgs let rhs := matchAlt[3] let rhs ← doSeqToCode (getDoSeqElems rhs) pure { ref := matchAlt, vars := vars, patterns := patterns, rhs := rhs : Alt CodeBlock } let matchCode ← mkMatch ref discrs optType alts concatWith matchCode doElems /-- Generate `CodeBlock` for `doTry; doElems` ``` def doTry := leading_parser "try " >> doSeq >> many (doCatch <|> doCatchMatch) >> optional doFinally def doCatch := leading_parser "catch " >> binderIdent >> optional (":" >> termParser) >> darrow >> doSeq def doCatchMatch := leading_parser "catch " >> doMatchAlts def doFinally := leading_parser "finally " >> doSeq ``` -/ partial def doTryToCode (doTry : Syntax) (doElems: List Syntax) : M CodeBlock := do let ref := doTry let tryCode ← doSeqToCode (getDoSeqElems doTry[1]) let optFinally := doTry[3] let catches ← doTry[2].getArgs.mapM fun catchStx => do if catchStx.getKind == `Lean.Parser.Term.doCatch then let x := catchStx[1] let optType := catchStx[2] let c ← doSeqToCode (getDoSeqElems catchStx[4]) pure { x := x, optType := optType, codeBlock := c : Catch } else if catchStx.getKind == `Lean.Parser.Term.doCatchMatch then let matchAlts := catchStx[1] let x ← `(ex) let auxDo ← `(do match ex with $matchAlts) let c ← doSeqToCode (getDoSeqElems (getDoSeq auxDo)) pure { x := x, codeBlock := c, optType := mkNullNode : Catch } else throwError "unexpected kind of 'catch'" let finallyCode? ← if optFinally.isNone then pure none else some <$> doSeqToCode (getDoSeqElems optFinally[0][1]) if catches.isEmpty && finallyCode?.isNone then throwError "invalid 'try', it must have a 'catch' or 'finally'" let ctx ← read let ws := getTryCatchUpdatedVars tryCode catches finallyCode? let uvars := nameSetToArray ws let a := tryCatchPred tryCode catches finallyCode? hasTerminalAction let r := tryCatchPred tryCode catches finallyCode? hasReturn let bc := tryCatchPred tryCode catches finallyCode? hasBreakContinue let toTerm (codeBlock : CodeBlock) : M Syntax := do let codeBlock ← liftM $ extendUpdatedVars codeBlock ws liftMacroM $ ToTerm.mkNestedTerm codeBlock.code ctx.m uvars a r bc let term ← toTerm tryCode let term ← catches.foldlM (fun term «catch» => do let catchTerm ← toTerm «catch».codeBlock if catch.optType.isNone then `(MonadExcept.tryCatch $term (fun $(«catch».x):ident => $catchTerm)) else let type := «catch».optType[1] `(tryCatchThe $type $term (fun $(«catch».x):ident => $catchTerm))) term let term ← match finallyCode? with | none => pure term | some finallyCode => withRef optFinally do unless finallyCode.uvars.isEmpty do throwError "'finally' currently does not support reassignments" if hasBreakContinueReturn finallyCode.code then throwError "'finally' currently does 'return', 'break', nor 'continue'" let finallyTerm ← liftMacroM <| ToTerm.run finallyCode.code ctx.m {} ToTerm.Kind.regular `(tryFinally $term $finallyTerm) let doElemsNew ← liftMacroM <| ToTerm.matchNestedTermResult term uvars a r bc doSeqToCode (doElemsNew ++ doElems) partial def doSeqToCode : List Syntax → M CodeBlock | [] => do liftMacroM mkPureUnitAction | doElem::doElems => withRef doElem do match (← liftMacroM <| expandMacro? doElem) with | some doElem => doSeqToCode (doElem::doElems) | none => match (← liftMacroM <| expandDoIf? doElem) with | some doElem => doSeqToCode (doElem::doElems) | none => let (liftedDoElems, doElem) ← liftM (liftMacroM <| expandLiftMethod doElem : TermElabM _) if !liftedDoElems.isEmpty then doSeqToCode (liftedDoElems ++ [doElem] ++ doElems) else let ref := doElem let concatWithRest (c : CodeBlock) : M CodeBlock := concatWith c doElems let k := doElem.getKind if k == `Lean.Parser.Term.doLet then let vars ← getDoLetVars doElem mkVarDeclCore vars doElem <$> withNewMutableVars vars (isMutableLet doElem) (doSeqToCode doElems) else if k == `Lean.Parser.Term.doHave then let var := getDoHaveVar doElem mkVarDeclCore #[var] doElem <$> (doSeqToCode doElems) else if k == `Lean.Parser.Term.doLetRec then let vars ← getDoLetRecVars doElem mkVarDeclCore vars doElem <$> (doSeqToCode doElems) else if k == `Lean.Parser.Term.doReassign then let vars ← getDoReassignVars doElem checkReassignable vars let k ← doSeqToCode doElems mkReassignCore vars doElem k else if k == `Lean.Parser.Term.doLetArrow then doLetArrowToCode doElem doElems else if k == `Lean.Parser.Term.doReassignArrow then doReassignArrowToCode doElem doElems else if k == `Lean.Parser.Term.doIf then doIfToCode doElem doElems else if k == `Lean.Parser.Term.doUnless then doUnlessToCode doElem doElems else if k == `Lean.Parser.Term.doFor then withFreshMacroScope do doForToCode doElem doElems else if k == `Lean.Parser.Term.doMatch then doMatchToCode doElem doElems else if k == `Lean.Parser.Term.doTry then doTryToCode doElem doElems else if k == `Lean.Parser.Term.doBreak then ensureInsideFor ensureEOS doElems return mkBreak ref else if k == `Lean.Parser.Term.doContinue then ensureInsideFor ensureEOS doElems return mkContinue ref else if k == `Lean.Parser.Term.doReturn then doReturnToCode doElem doElems else if k == `Lean.Parser.Term.doDbgTrace then return mkSeq doElem (← doSeqToCode doElems) else if k == `Lean.Parser.Term.doAssert then return mkSeq doElem (← doSeqToCode doElems) else if k == `Lean.Parser.Term.doNested then let nestedDoSeq := doElem[1] doSeqToCode (getDoSeqElems nestedDoSeq ++ doElems) else if k == `Lean.Parser.Term.doExpr then let term := doElem[0] if doElems.isEmpty then return mkTerminalAction term else return mkSeq term (← doSeqToCode doElems) else throwError "unexpected do-element\n{doElem}" end def run (doStx : Syntax) (m : Syntax) : TermElabM CodeBlock := (doSeqToCode <| getDoSeqElems <| getDoSeq doStx).run { ref := doStx, m := m } end ToCodeBlock /- Create a synthetic metavariable `?m` and assign `m` to it. We use `?m` to refer to `m` when expanding the `do` notation. -/ private def mkMonadAlias (m : Expr) : TermElabM Syntax := do let result ← `(?m) let mType ← inferType m let mvar ← elabTerm result mType assignExprMVar mvar.mvarId! m pure result @[builtinTermElab «do»] def elabDo : TermElab := fun stx expectedType? => do tryPostponeIfNoneOrMVar expectedType? let bindInfo ← extractBind expectedType? let m ← mkMonadAlias bindInfo.m let codeBlock ← ToCodeBlock.run stx m let stxNew ← liftMacroM $ ToTerm.run codeBlock.code m trace[Elab.do] stxNew withMacroExpansion stx stxNew $ elabTermEnsuringType stxNew bindInfo.expectedType end Do builtin_initialize registerTraceClass `Elab.do private def toDoElem (newKind : SyntaxNodeKind) : Macro := fun stx => do let stx := stx.setKind newKind withRef stx `(do $stx:doElem) @[builtinMacro Lean.Parser.Term.termFor] def expandTermFor : Macro := toDoElem `Lean.Parser.Term.doFor @[builtinMacro Lean.Parser.Term.termTry] def expandTermTry : Macro := toDoElem `Lean.Parser.Term.doTry @[builtinMacro Lean.Parser.Term.termUnless] def expandTermUnless : Macro := toDoElem `Lean.Parser.Term.doUnless @[builtinMacro Lean.Parser.Term.termReturn] def expandTermReturn : Macro := toDoElem `Lean.Parser.Term.doReturn end Term end Elab end Lean
a93979cb36cb2a5801b35eb48d10d86e8342125c
969dbdfed67fda40a6f5a2b4f8c4a3c7dc01e0fb
/src/category_theory/limits/shapes/strong_epi.lean
ba3ba7c3e67d7f287bd7a6d328de173b807923e2
[ "Apache-2.0" ]
permissive
SAAluthwela/mathlib
62044349d72dd63983a8500214736aa7779634d3
83a4b8b990907291421de54a78988c024dc8a552
refs/heads/master
1,679,433,873,417
1,615,998,031,000
1,615,998,031,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,031
lean
/- Copyright (c) 2020 Markus Himmel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Markus Himmel -/ import category_theory.arrow /-! # Strong epimorphisms In this file, we define strong epimorphisms. A strong epimorphism is an epimorphism `f`, such that for every commutative square with `f` at the top and a monomorphism at the bottom, there is a diagonal morphism making the two triangles commute. This lift is necessarily unique (as shown in `comma.lean`). ## Main results Besides the definition, we show that * the composition of two strong epimorphisms is a strong epimorphism, * if `f ≫ g` is a strong epimorphism, then so is `g`, * if `f` is both a strong epimorphism and a monomorphism, then it is an isomorphism ## Future work There is also the dual notion of strong monomorphism. ## References * [F. Borceux, *Handbook of Categorical Algebra 1*][borceux-vol1] -/ universes v u namespace category_theory variables {C : Type u} [category.{v} C] variables {P Q : C} /-- A strong epimorphism `f` is an epimorphism such that every commutative square with `f` at the top and a monomorphism at the bottom has a lift. -/ class strong_epi (f : P ⟶ Q) : Prop := (epi : epi f) (has_lift : Π {X Y : C} {u : P ⟶ X} {v : Q ⟶ Y} {z : X ⟶ Y} [mono z] (h : u ≫ z = f ≫ v), arrow.has_lift $ arrow.hom_mk' h) attribute [instance] strong_epi.has_lift @[priority 100] instance epi_of_strong_epi (f : P ⟶ Q) [strong_epi f] : epi f := strong_epi.epi section variables {R : C} (f : P ⟶ Q) (g : Q ⟶ R) /-- The composition of two strong epimorphisms is a strong epimorphism. -/ lemma strong_epi_comp [strong_epi f] [strong_epi g] : strong_epi (f ≫ g) := { epi := epi_comp _ _, has_lift := begin introsI, have h₀ : u ≫ z = f ≫ g ≫ v, by simpa [category.assoc] using h, let w : Q ⟶ X := arrow.lift (arrow.hom_mk' h₀), have h₁ : w ≫ z = g ≫ v, by rw arrow.lift_mk'_right, exact arrow.has_lift.mk ⟨(arrow.lift (arrow.hom_mk' h₁) : R ⟶ X), by simp, by simp⟩ end } /-- If `f ≫ g` is a strong epimorphism, then so is g. -/ lemma strong_epi_of_strong_epi [strong_epi (f ≫ g)] : strong_epi g := { epi := epi_of_epi f g, has_lift := begin introsI, have h₀ : (f ≫ u) ≫ z = (f ≫ g) ≫ v, by simp only [category.assoc, h], exact arrow.has_lift.mk ⟨(arrow.lift (arrow.hom_mk' h₀) : R ⟶ X), (cancel_mono z).1 (by simp [h]), by simp⟩, end } /-- An isomorphism is in particular a strong epimorphism. -/ @[priority 100] instance strong_epi_of_is_iso [is_iso f] : strong_epi f := { epi := by apply_instance, has_lift := λ X Y u v z _ h, arrow.has_lift.mk ⟨inv f ≫ u, by simp, by simp [h]⟩ } end /-- A strong epimorphism that is a monomorphism is an isomorphism. -/ lemma is_iso_of_mono_of_strong_epi (f : P ⟶ Q) [mono f] [strong_epi f] : is_iso f := ⟨arrow.lift $ arrow.hom_mk' $ show 𝟙 P ≫ f = f ≫ 𝟙 Q, by simp, by tidy⟩ end category_theory
66a4f32364a92b92af6ee99aa6a5d5239ed217d2
a339bc2ac96174381fb610f4b2e1ba42df2be819
/hott/homotopy/sphere.hlean
c6066e0f5824d11df8310c82ee54d4d011b9c3d9
[ "Apache-2.0" ]
permissive
kalfsvag/lean2
25b2dccc07a98e5aa20f9a11229831f9d3edf2e7
4d4a0c7c53a9922c5f630f6f8ebdccf7ddef2cc7
refs/heads/master
1,610,513,122,164
1,483,135,198,000
1,483,135,198,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
13,724
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn Declaration of the n-spheres -/ import .susp types.trunc open eq nat susp bool is_trunc unit pointed algebra /- We can define spheres with the following possible indices: - trunc_index (defining S^-2 = S^-1 = empty) - nat (forgetting that S^-1 = empty) - nat, but counting wrong (S^0 = empty, S^1 = bool, ...) - some new type "integers >= -1" We choose the last option here. -/ /- Sphere levels -/ inductive sphere_index : Type₀ := | minus_one : sphere_index | succ : sphere_index → sphere_index notation `ℕ₋₁` := sphere_index namespace trunc_index definition sub_one [reducible] (n : ℕ₋₁) : ℕ₋₂ := sphere_index.rec_on n -2 (λ n k, k.+1) postfix `..-1`:(max+1) := sub_one definition of_sphere_index [reducible] (n : ℕ₋₁) : ℕ₋₂ := n..-1.+1 -- we use a double dot to distinguish with the notation .-1 in trunc_index (of type ℕ → ℕ₋₂) end trunc_index namespace sphere_index /- notation for sphere_index is -1, 0, 1, ... from 0 and up this comes from a coercion from num to sphere_index (via nat) -/ postfix `.+1`:(max+1) := sphere_index.succ postfix `.+2`:(max+1) := λ(n : sphere_index), (n .+1 .+1) notation `-1` := minus_one definition has_zero_sphere_index [instance] : has_zero ℕ₋₁ := has_zero.mk (succ minus_one) definition has_one_sphere_index [instance] : has_one ℕ₋₁ := has_one.mk (succ (succ minus_one)) definition add_plus_one (n m : ℕ₋₁) : ℕ₋₁ := sphere_index.rec_on m n (λ k l, l .+1) -- addition of sphere_indices, where (-1 + -1) is defined to be -1. protected definition add (n m : ℕ₋₁) : ℕ₋₁ := sphere_index.cases_on m (sphere_index.cases_on n -1 id) (sphere_index.rec n (λn' r, succ r)) inductive le (a : ℕ₋₁) : ℕ₋₁ → Type := | sp_refl : le a a | step : Π {b}, le a b → le a (b.+1) infix ` +1+ `:65 := sphere_index.add_plus_one definition has_add_sphere_index [instance] [priority 2000] [reducible] : has_add ℕ₋₁ := has_add.mk sphere_index.add definition has_le_sphere_index [instance] : has_le ℕ₋₁ := has_le.mk sphere_index.le definition sub_one [reducible] (n : ℕ) : ℕ₋₁ := nat.rec_on n -1 (λ n k, k.+1) postfix `..-1`:(max+1) := sub_one definition of_nat [coercion] [reducible] (n : ℕ) : ℕ₋₁ := n..-1.+1 -- we use a double dot to distinguish with the notation .-1 in trunc_index (of type ℕ → ℕ₋₂) definition add_one [reducible] (n : ℕ₋₁) : ℕ := sphere_index.rec_on n 0 (λ n k, nat.succ k) definition add_plus_one_of_nat (n m : ℕ) : (n +1+ m) = sphere_index.of_nat (n + m + 1) := begin induction m with m IH, { reflexivity }, { exact ap succ IH} end definition succ_sub_one (n : ℕ) : (nat.succ n)..-1 = n :> ℕ₋₁ := idp definition add_sub_one (n m : ℕ) : (n + m)..-1 = n..-1 +1+ m..-1 :> ℕ₋₁ := begin induction m with m IH, { reflexivity }, { exact ap succ IH } end definition succ_le_succ {n m : ℕ₋₁} (H : n ≤ m) : n.+1 ≤[ℕ₋₁] m.+1 := by induction H with m H IH; apply le.sp_refl; exact le.step IH definition minus_one_le (n : ℕ₋₁) : -1 ≤[ℕ₋₁] n := by induction n with n IH; apply le.sp_refl; exact le.step IH open decidable protected definition has_decidable_eq [instance] : Π(n m : ℕ₋₁), decidable (n = m) | has_decidable_eq -1 -1 := inl rfl | has_decidable_eq (n.+1) -1 := inr (by contradiction) | has_decidable_eq -1 (m.+1) := inr (by contradiction) | has_decidable_eq (n.+1) (m.+1) := match has_decidable_eq n m with | inl xeqy := inl (by rewrite xeqy) | inr xney := inr (λ h : succ n = succ m, by injection h with xeqy; exact absurd xeqy xney) end definition not_succ_le_minus_two {n : sphere_index} (H : n .+1 ≤[ℕ₋₁] -1) : empty := by cases H protected definition le_trans {n m k : ℕ₋₁} (H1 : n ≤[ℕ₋₁] m) (H2 : m ≤[ℕ₋₁] k) : n ≤[ℕ₋₁] k := begin induction H2 with k H2 IH, { exact H1}, { exact le.step IH} end definition le_of_succ_le_succ {n m : ℕ₋₁} (H : n.+1 ≤[ℕ₋₁] m.+1) : n ≤[ℕ₋₁] m := begin cases H with m H', { apply le.sp_refl}, { exact sphere_index.le_trans (le.step !le.sp_refl) H'} end theorem not_succ_le_self {n : ℕ₋₁} : ¬n.+1 ≤[ℕ₋₁] n := begin induction n with n IH: intro H, { exact not_succ_le_minus_two H}, { exact IH (le_of_succ_le_succ H)} end protected definition le_antisymm {n m : ℕ₋₁} (H1 : n ≤[ℕ₋₁] m) (H2 : m ≤[ℕ₋₁] n) : n = m := begin induction H2 with n H2 IH, { reflexivity}, { exfalso, apply @not_succ_le_self n, exact sphere_index.le_trans H1 H2} end protected definition le_succ {n m : ℕ₋₁} (H1 : n ≤[ℕ₋₁] m): n ≤[ℕ₋₁] m.+1 := le.step H1 definition add_plus_one_minus_one (n : ℕ₋₁) : n +1+ -1 = n := idp definition add_plus_one_succ (n m : ℕ₋₁) : n +1+ (m.+1) = (n +1+ m).+1 := idp definition minus_one_add_plus_one (n : ℕ₋₁) : -1 +1+ n = n := begin induction n with n IH, reflexivity, exact ap succ IH end definition succ_add_plus_one (n m : ℕ₋₁) : (n.+1) +1+ m = (n +1+ m).+1 := begin induction m with m IH, reflexivity, exact ap succ IH end definition sphere_index_of_nat_add_one (n : ℕ₋₁) : sphere_index.of_nat (add_one n) = n.+1 := begin induction n with n IH, reflexivity, exact ap succ IH end definition add_one_succ (n : ℕ₋₁) : add_one (n.+1) = succ (add_one n) := by reflexivity definition add_one_sub_one (n : ℕ) : add_one (n..-1) = n := begin induction n with n IH, reflexivity, exact ap nat.succ IH end definition add_one_of_nat (n : ℕ) : add_one n = nat.succ n := ap nat.succ (add_one_sub_one n) definition sphere_index.of_nat_succ (n : ℕ) : sphere_index.of_nat (nat.succ n) = (sphere_index.of_nat n).+1 := begin induction n with n IH, reflexivity, exact ap succ IH end /- warning: if this coercion is available, the coercion ℕ → ℕ₋₂ is the composition of the coercions ℕ → ℕ₋₁ → ℕ₋₂. We don't want this composition as coercion, because it has worse computational properties. You can rewrite it with trans_to_of_sphere_index_eq defined below. -/ attribute trunc_index.of_sphere_index [coercion] end sphere_index open sphere_index definition weak_order_sphere_index [trans_instance] [reducible] : weak_order sphere_index := weak_order.mk le sphere_index.le.sp_refl @sphere_index.le_trans @sphere_index.le_antisymm namespace trunc_index definition sub_two_eq_sub_one_sub_one (n : ℕ) : n.-2 = n..-1..-1 := begin induction n with n IH, { reflexivity}, { exact ap trunc_index.succ IH} end definition of_nat_sub_one (n : ℕ) : (sphere_index.of_nat n)..-1 = (trunc_index.sub_two n).+1 := begin induction n with n IH, { reflexivity}, { exact ap trunc_index.succ IH} end definition sub_one_of_sphere_index (n : ℕ) : of_sphere_index n..-1 = (trunc_index.sub_two n).+1 := begin induction n with n IH, { reflexivity}, { exact ap trunc_index.succ IH} end definition succ_sub_one (n : ℕ₋₁) : n.+1..-1 = n :> ℕ₋₂ := idp definition of_sphere_index_of_nat (n : ℕ) : of_sphere_index (sphere_index.of_nat n) = of_nat n :> ℕ₋₂ := begin induction n with n IH, { reflexivity}, { exact ap trunc_index.succ IH} end definition trans_to_of_sphere_index_eq (n : ℕ) : trunc_index._trans_to_of_sphere_index n = of_nat n :> ℕ₋₂ := of_sphere_index_of_nat n definition trunc_index_of_nat_add_one (n : ℕ₋₁) : trunc_index.of_nat (add_one n) = (of_sphere_index n).+1 := begin induction n with n IH, reflexivity, exact ap succ IH end definition of_sphere_index_succ (n : ℕ₋₁) : of_sphere_index (n.+1) = (of_sphere_index n).+1 := begin induction n with n IH, reflexivity, exact ap succ IH end end trunc_index open sphere_index equiv definition sphere (n : ℕ₋₁) : Type₀ := iterate_susp (add_one n) empty namespace sphere export [notation] sphere_index definition base {n : ℕ} : sphere n := north definition pointed_sphere [instance] [constructor] (n : ℕ) : pointed (sphere n) := pointed.mk base definition psphere [constructor] (n : ℕ) : Type* := pointed.mk' (sphere n) namespace ops abbreviation S := sphere notation `S*` := psphere end ops open sphere.ops definition sphere_minus_one : S -1 = empty := idp definition sphere_succ [unfold_full] (n : ℕ₋₁) : S n.+1 = susp (S n) := idp definition psphere_succ [unfold_full] (n : ℕ) : S* (n + 1) = psusp (S* n) := idp definition psphere_eq_iterate_susp (n : ℕ) : S* n = pointed.MK (iterate_susp (succ n) empty) !north := begin esimp, apply ap (λx, pointed.MK (susp x) (@north x)); apply ap (λx, iterate_susp x empty), apply add_one_sub_one end definition equator [constructor] (n : ℕ) : S* n →* Ω (S* (succ n)) := loop_psusp_unit (S* n) definition surf {n : ℕ} : Ω[n] (S* n) := begin induction n with n s, { exact south }, { exact (loopn_succ_in (S* (succ n)) n)⁻¹ᵉ* (apn n (equator n) s), } end definition bool_of_sphere [unfold 1] : S 0 → bool := proof susp.rec ff tt (λx, empty.elim x) qed definition sphere_of_bool [unfold 1] : bool → S 0 | ff := proof north qed | tt := proof south qed definition sphere_equiv_bool [constructor] : S 0 ≃ bool := equiv.MK bool_of_sphere sphere_of_bool (λb, match b with | tt := idp | ff := idp end) (λx, proof susp.rec_on x idp idp (empty.rec _) qed) definition psphere_pequiv_pbool [constructor] : S* 0 ≃* pbool := pequiv_of_equiv sphere_equiv_bool idp definition sphere_eq_bool : S 0 = bool := ua sphere_equiv_bool definition sphere_eq_pbool : S* 0 = pbool := pType_eq sphere_equiv_bool idp definition psphere_pmap_pequiv' (A : Type*) (n : ℕ) : ppmap (S* n) A ≃* Ω[n] A := begin revert A, induction n with n IH: intro A, { refine _ ⬝e* !pmap_pbool_pequiv, exact pequiv_ppcompose_right psphere_pequiv_pbool⁻¹ᵉ* }, { refine psusp_adjoint_loop (S* n) A ⬝e* IH (Ω A) ⬝e* !loopn_succ_in⁻¹ᵉ* } end definition psphere_pmap_pequiv (A : Type*) (n : ℕ) : ppmap (S* n) A ≃* Ω[n] A := begin fapply pequiv_change_fun, { exact psphere_pmap_pequiv' A n }, { exact papn_fun A surf }, { revert A, induction n with n IH: intro A, { reflexivity }, { intro f, refine ap !loopn_succ_in⁻¹ᵉ* (IH (Ω A) _ ⬝ !apn_pcompose _) ⬝ _, exact !loopn_succ_in_inv_natural⁻¹* _ }} end protected definition elim {n : ℕ} {P : Type*} (p : Ω[n] P) : S* n →* P := !psphere_pmap_pequiv⁻¹ᵉ* p -- definition elim_surf {n : ℕ} {P : Type*} (p : Ω[n] P) : apn n (sphere.elim p) surf = p := -- begin -- induction n with n IH, -- { esimp [apn,surf,sphere.elim,psphere_pmap_equiv], apply sorry}, -- { apply sorry} -- end end sphere namespace sphere open is_conn trunc_index sphere_index sphere.ops -- Corollary 8.2.2 theorem is_conn_sphere [instance] (n : ℕ₋₁) : is_conn (n..-1) (S n) := begin induction n with n IH, { apply is_conn_minus_two }, { rewrite [trunc_index.succ_sub_one n, sphere.sphere_succ], apply is_conn_susp } end theorem is_conn_psphere [instance] (n : ℕ) : is_conn (n.-1) (S* n) := transport (λx, is_conn x (sphere n)) (of_nat_sub_one n) (is_conn_sphere n) end sphere open sphere sphere.ops namespace is_trunc open trunc_index variables {n : ℕ} {A : Type} definition is_trunc_of_psphere_pmap_equiv_constant (H : Π(a : A) (f : S* n →* pointed.Mk a) (x : S n), f x = f base) : is_trunc (n.-2.+1) A := begin apply iff.elim_right !is_trunc_iff_is_contr_loop, intro a, apply is_trunc_equiv_closed, exact !psphere_pmap_pequiv, fapply is_contr.mk, { exact pmap.mk (λx, a) idp}, { intro f, fapply pmap_eq, { intro x, esimp, refine !respect_pt⁻¹ ⬝ (!H ⬝ !H⁻¹)}, { rewrite [▸*,con.right_inv,▸*,con.left_inv]}} end definition is_trunc_iff_map_sphere_constant (H : Π(f : S n → A) (x : S n), f x = f base) : is_trunc (n.-2.+1) A := begin apply is_trunc_of_psphere_pmap_equiv_constant, intros, cases f with f p, esimp at *, apply H end definition psphere_pmap_equiv_constant_of_is_trunc' [H : is_trunc (n.-2.+1) A] (a : A) (f : S* n →* pointed.Mk a) (x : S n) : f x = f base := begin let H' := iff.elim_left (is_trunc_iff_is_contr_loop n A) H a, note H'' := @is_trunc_equiv_closed_rev _ _ _ !psphere_pmap_pequiv H', esimp at H'', have p : f = pmap.mk (λx, f base) (respect_pt f), by apply is_prop.elim, exact ap10 (ap pmap.to_fun p) x end definition psphere_pmap_equiv_constant_of_is_trunc [H : is_trunc (n.-2.+1) A] (a : A) (f : S* n →* pointed.Mk a) (x y : S n) : f x = f y := let H := psphere_pmap_equiv_constant_of_is_trunc' a f in !H ⬝ !H⁻¹ definition map_sphere_constant_of_is_trunc [H : is_trunc (n.-2.+1) A] (f : S n → A) (x y : S n) : f x = f y := psphere_pmap_equiv_constant_of_is_trunc (f base) (pmap.mk f idp) x y definition map_sphere_constant_of_is_trunc_self [H : is_trunc (n.-2.+1) A] (f : S n → A) (x : S n) : map_sphere_constant_of_is_trunc f x x = idp := !con.right_inv end is_trunc
17fd780228ec3bc1fa465a4345378732cafa3090
491068d2ad28831e7dade8d6dff871c3e49d9431
/tests/lean/run/reducible.lean
5a719cb03176c3fdfb37d801a6fc14ffa8de8e69
[ "Apache-2.0" ]
permissive
davidmueller13/lean
65a3ed141b4088cd0a268e4de80eb6778b21a0e9
c626e2e3c6f3771e07c32e82ee5b9e030de5b050
refs/heads/master
1,611,278,313,401
1,444,021,177,000
1,444,021,177,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,220
lean
definition x [reducible] := 10 definition y := 20 definition z [irreducible] := 30 definition w := 40 (* local env = get_env() local x = Const("x") local y = Const("y") local z = Const("z") local w = Const("w") local val_x = env:find("x"):value() local val_y = env:find("y"):value() local val_z = env:find("z"):value() local val_w = env:find("w"):value() -- All definitions are not unfolded local tc = opaque_type_checker(env) assert(tc:whnf(x) == x) assert(tc:whnf(y) == y) assert(tc:whnf(z) == z) assert(tc:whnf(w) == w) -- Opaque and definitions marked as irreducibled are not unfolded local tc = non_irreducible_type_checker(env) assert(tc:whnf(x) == val_x) assert(tc:whnf(y) == val_y) assert(tc:whnf(z) == z) -- Only definitions marked as reducible are unfolded local tc = reducible_type_checker(env) assert(tc:whnf(x) == val_x) assert(tc:whnf(y) == y) assert(tc:whnf(z) == z) assert(tc:whnf(w) == w) -- Default: only opaque definitions are not unfolded. -- Opaqueness is a feature of the kernel. local tc = type_checker(env) assert(tc:whnf(x) == val_x) assert(tc:whnf(y) == val_y) assert(tc:whnf(z) == val_z) *) eval [whnf] x
032854e62e107fee1d436272407184fe00dec0ea
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/category_theory/abelian/exact.lean
67d1b304d6fdd271bf07adb13924f48efef6842f
[ "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
18,120
lean
/- Copyright (c) 2020 Markus Himmel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Markus Himmel, Adam Topaz, Johan Commelin, Jakob von Raumer -/ import category_theory.abelian.opposite import category_theory.limits.preserves.shapes.zero import category_theory.limits.preserves.shapes.kernels import category_theory.preadditive.left_exact import category_theory.adjunction.limits import algebra.homology.exact import tactic.tfae /-! # Exact sequences in abelian categories In an abelian category, we get several interesting results related to exactness which are not true in more general settings. ## Main results * `(f, g)` is exact if and only if `f ≫ g = 0` and `kernel.ι g ≫ cokernel.π f = 0`. This characterisation tends to be less cumbersome to work with than the original definition involving the comparison map `image f ⟶ kernel g`. * If `(f, g)` is exact, then `image.ι f` has the universal property of the kernel of `g`. * `f` is a monomorphism iff `kernel.ι f = 0` iff `exact 0 f`, and `f` is an epimorphism iff `cokernel.π = 0` iff `exact f 0`. * A faithful functor between abelian categories that preserves zero morphisms reflects exact sequences. * `X ⟶ Y ⟶ Z ⟶ 0` is exact if and only if the second map is a cokernel of the first, and `0 ⟶ X ⟶ Y ⟶ Z` is exact if and only if the first map is a kernel of the second. * An exact functor preserves exactness, more specifically, `F` preserves finite colimits and finite limits, if and only if `exact f g` implies `exact (F.map f) (F.map g)`. -/ universes v₁ v₂ u₁ u₂ noncomputable theory open category_theory open category_theory.limits open category_theory.preadditive variables {C : Type u₁} [category.{v₁} C] [abelian C] namespace category_theory namespace abelian variables {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) local attribute [instance] has_equalizers_of_has_kernels /-- In an abelian category, a pair of morphisms `f : X ⟶ Y`, `g : Y ⟶ Z` is exact iff `image_subobject f = kernel_subobject g`. -/ theorem exact_iff_image_eq_kernel : exact f g ↔ image_subobject f = kernel_subobject g := begin split, { intro h, fapply subobject.eq_of_comm, { suffices : is_iso (image_to_kernel _ _ h.w), { exactI as_iso (image_to_kernel _ _ h.w), }, exact is_iso_of_mono_of_epi _, }, { simp, }, }, { apply exact_of_image_eq_kernel, }, end theorem exact_iff : exact f g ↔ f ≫ g = 0 ∧ kernel.ι g ≫ cokernel.π f = 0 := begin split, { intro h, exact ⟨h.1, kernel_comp_cokernel f g h⟩ }, { refine λ h, ⟨h.1, _⟩, suffices hl : is_limit (kernel_fork.of_ι (image_subobject f).arrow (image_subobject_arrow_comp_eq_zero h.1)), { have : image_to_kernel f g h.1 = (is_limit.cone_point_unique_up_to_iso hl (limit.is_limit _)).hom ≫ (kernel_subobject_iso _).inv, { ext, simp }, rw this, apply_instance, }, refine kernel_fork.is_limit.of_ι _ _ _ _ _, { refine λ W u hu, kernel.lift (cokernel.π f) u _ ≫ (image_iso_image f).hom ≫ (image_subobject_iso _).inv, rw [←kernel.lift_ι g u hu, category.assoc, h.2, has_zero_morphisms.comp_zero] }, { tidy }, { intros, rw [←cancel_mono (image_subobject f).arrow, w], simp, } } end theorem exact_iff' {cg : kernel_fork g} (hg : is_limit cg) {cf : cokernel_cofork f} (hf : is_colimit cf) : exact f g ↔ f ≫ g = 0 ∧ cg.ι ≫ cf.π = 0 := begin split, { intro h, exact ⟨h.1, fork_ι_comp_cofork_π f g h cg cf⟩ }, { rw exact_iff, refine λ h, ⟨h.1, _⟩, apply zero_of_epi_comp (is_limit.cone_point_unique_up_to_iso hg (limit.is_limit _)).hom, apply zero_of_comp_mono (is_colimit.cocone_point_unique_up_to_iso (colimit.is_colimit _) hf).hom, simp [h.2] } end theorem exact_tfae : tfae [exact f g, f ≫ g = 0 ∧ kernel.ι g ≫ cokernel.π f = 0, image_subobject f = kernel_subobject g] := begin tfae_have : 1 ↔ 2, { apply exact_iff }, tfae_have : 1 ↔ 3, { apply exact_iff_image_eq_kernel }, tfae_finish end lemma is_equivalence.exact_iff {D : Type u₁} [category.{v₁} D] [abelian D] (F : C ⥤ D) [is_equivalence F] : exact (F.map f) (F.map g) ↔ exact f g := begin simp only [exact_iff, ← F.map_eq_zero_iff, F.map_comp, category.assoc, ← kernel_comparison_comp_ι g F, ← π_comp_cokernel_comparison f F], rw [is_iso.comp_left_eq_zero (kernel_comparison g F), ← category.assoc, is_iso.comp_right_eq_zero _ (cokernel_comparison f F)], end /-- The dual result is true even in non-abelian categories, see `category_theory.exact_comp_mono_iff`. -/ lemma exact_epi_comp_iff {W : C} (h : W ⟶ X) [epi h] : exact (h ≫ f) g ↔ exact f g := begin refine ⟨λ hfg, _, λ h, exact_epi_comp h⟩, let hc := is_cokernel_of_comp _ _ (colimit.is_colimit (parallel_pair (h ≫ f) 0)) (by rw [← cancel_epi h, ← category.assoc, cokernel_cofork.condition, comp_zero]) rfl, refine (exact_iff' _ _ (limit.is_limit _) hc).2 ⟨_, ((exact_iff _ _).1 hfg).2⟩, exact zero_of_epi_comp h (by rw [← hfg.1, category.assoc]) end /-- If `(f, g)` is exact, then `abelian.image.ι f` is a kernel of `g`. -/ def is_limit_image (h : exact f g) : is_limit (kernel_fork.of_ι (abelian.image.ι f) (image_ι_comp_eq_zero h.1) : kernel_fork g) := begin rw exact_iff at h, refine kernel_fork.is_limit.of_ι _ _ _ _ _, { refine λ W u hu, kernel.lift (cokernel.π f) u _, rw [←kernel.lift_ι g u hu, category.assoc, h.2, has_zero_morphisms.comp_zero] }, tidy end /-- If `(f, g)` is exact, then `image.ι f` is a kernel of `g`. -/ def is_limit_image' (h : exact f g) : is_limit (kernel_fork.of_ι (limits.image.ι f) (limits.image_ι_comp_eq_zero h.1)) := is_kernel.iso_kernel _ _ (is_limit_image f g h) (image_iso_image f).symm $ is_image.lift_fac _ _ /-- If `(f, g)` is exact, then `coimages.coimage.π g` is a cokernel of `f`. -/ def is_colimit_coimage (h : exact f g) : is_colimit (cokernel_cofork.of_π (abelian.coimage.π g) (abelian.comp_coimage_π_eq_zero h.1) : cokernel_cofork f) := begin rw exact_iff at h, refine cokernel_cofork.is_colimit.of_π _ _ _ _ _, { refine λ W u hu, cokernel.desc (kernel.ι g) u _, rw [←cokernel.π_desc f u hu, ←category.assoc, h.2, has_zero_morphisms.zero_comp] }, tidy end /-- If `(f, g)` is exact, then `factor_thru_image g` is a cokernel of `f`. -/ def is_colimit_image (h : exact f g) : is_colimit (cokernel_cofork.of_π (limits.factor_thru_image g) (comp_factor_thru_image_eq_zero h.1)) := is_cokernel.cokernel_iso _ _ (is_colimit_coimage f g h) (coimage_iso_image' g) $ (cancel_mono (limits.image.ι g)).1 $ by simp lemma exact_cokernel : exact f (cokernel.π f) := by { rw exact_iff, tidy } instance (h : exact f g) : mono (cokernel.desc f g h.w) := suffices h : cokernel.desc f g h.w = (is_colimit.cocone_point_unique_up_to_iso (colimit.is_colimit _) (is_colimit_image f g h)).hom ≫ limits.image.ι g, by { rw h, apply mono_comp }, (cancel_epi (cokernel.π f)).1 $ by simp /-- If `ex : exact f g` and `epi g`, then `cokernel.desc _ _ ex.w` is an isomorphism. -/ instance (ex : exact f g) [epi g] : is_iso (cokernel.desc f g ex.w) := is_iso_of_mono_of_epi (limits.cokernel.desc f g ex.w) @[simp, reassoc] lemma cokernel.desc.inv [epi g] (ex : exact f g) : g ≫ inv (cokernel.desc _ _ ex.w) = cokernel.π _ := by simp instance (ex : exact f g) [mono f] : is_iso (kernel.lift g f ex.w) := is_iso_of_mono_of_epi (limits.kernel.lift g f ex.w) @[simp, reassoc] lemma kernel.lift.inv [mono f] (ex : exact f g) : inv (kernel.lift _ _ ex.w) ≫ f = kernel.ι g := by simp /-- If `X ⟶ Y ⟶ Z ⟶ 0` is exact, then the second map is a cokernel of the first. -/ def is_colimit_of_exact_of_epi [epi g] (h : exact f g) : is_colimit (cokernel_cofork.of_π _ h.w) := is_colimit.of_iso_colimit (colimit.is_colimit _) $ cocones.ext ⟨cokernel.desc _ _ h.w, epi_desc g (cokernel.π f) ((exact_iff _ _).1 h).2, (cancel_epi (cokernel.π f)).1 (by tidy), (cancel_epi g).1 (by tidy)⟩ (λ j, by cases j; simp) /-- If `0 ⟶ X ⟶ Y ⟶ Z` is exact, then the first map is a kernel of the second. -/ def is_limit_of_exact_of_mono [mono f] (h : exact f g) : is_limit (kernel_fork.of_ι _ h.w) := is_limit.of_iso_limit (limit.is_limit _) $ cones.ext ⟨mono_lift f (kernel.ι g) ((exact_iff _ _).1 h).2, kernel.lift _ _ h.w, (cancel_mono (kernel.ι g)).1 (by tidy), (cancel_mono f).1 (by tidy)⟩ (λ j, by cases j; simp) lemma exact_of_is_cokernel (w : f ≫ g = 0) (h : is_colimit (cokernel_cofork.of_π _ w)) : exact f g := begin refine (exact_iff _ _).2 ⟨w, _⟩, have := h.fac (cokernel_cofork.of_π _ (cokernel.condition f)) walking_parallel_pair.one, simp only [cofork.of_π_ι_app] at this, rw [← this, ← category.assoc, kernel.condition, zero_comp] end lemma exact_of_is_kernel (w : f ≫ g = 0) (h : is_limit (kernel_fork.of_ι _ w)) : exact f g := begin refine (exact_iff _ _).2 ⟨w, _⟩, have := h.fac (kernel_fork.of_ι _ (kernel.condition g)) walking_parallel_pair.zero, simp only [fork.of_ι_π_app] at this, rw [← this, category.assoc, cokernel.condition, comp_zero] end lemma exact_iff_exact_image_ι : exact f g ↔ exact (abelian.image.ι f) g := by conv_lhs { rw ← abelian.image.fac f }; apply exact_epi_comp_iff lemma exact_iff_exact_coimage_π : exact f g ↔ exact f (coimage.π g) := by conv_lhs { rw ← abelian.coimage.fac g}; apply exact_comp_mono_iff section variables (Z) lemma tfae_mono : tfae [mono f, kernel.ι f = 0, exact (0 : Z ⟶ X) f] := begin tfae_have : 3 → 2, { exact kernel_ι_eq_zero_of_exact_zero_left Z }, tfae_have : 1 → 3, { introsI, exact exact_zero_left_of_mono Z }, tfae_have : 2 → 1, { exact mono_of_kernel_ι_eq_zero _ }, tfae_finish end -- Note we've already proved `mono_iff_exact_zero_left : mono f ↔ exact (0 : Z ⟶ X) f` -- in any preadditive category with kernels and images. lemma mono_iff_kernel_ι_eq_zero : mono f ↔ kernel.ι f = 0 := (tfae_mono X f).out 0 1 lemma tfae_epi : tfae [epi f, cokernel.π f = 0, exact f (0 : Y ⟶ Z)] := begin tfae_have : 3 → 2, { rw exact_iff, rintro ⟨-, h⟩, exact zero_of_epi_comp _ h }, tfae_have : 1 → 3, { rw exact_iff, introI, exact ⟨by simp, by simp [cokernel.π_of_epi]⟩ }, tfae_have : 2 → 1, { exact epi_of_cokernel_π_eq_zero _ }, tfae_finish end -- Note we've already proved `epi_iff_exact_zero_right : epi f ↔ exact f (0 : Y ⟶ Z)` -- in any preadditive category with equalizers and images. lemma epi_iff_cokernel_π_eq_zero : epi f ↔ cokernel.π f = 0 := (tfae_epi X f).out 0 1 end section opposite lemma exact.op (h : exact f g) : exact g.op f.op := begin rw exact_iff, refine ⟨by simp [← op_comp, h.w], quiver.hom.unop_inj _⟩, simp only [unop_comp, cokernel.π_op, eq_to_hom_refl, kernel.ι_op, category.id_comp, category.assoc, kernel_comp_cokernel_assoc _ _ h, zero_comp, comp_zero, unop_zero], end lemma exact.op_iff : exact g.op f.op ↔ exact f g := ⟨λ e, begin rw ← is_equivalence.exact_iff _ _ (op_op_equivalence C).inverse, exact exact.op _ _ e end, exact.op _ _⟩ lemma exact.unop {X Y Z : Cᵒᵖ} (g : X ⟶ Y) (f : Y ⟶ Z) (h : exact g f) : exact f.unop g.unop := begin rw [← f.op_unop, ← g.op_unop] at h, rwa ← exact.op_iff, end lemma exact.unop_iff {X Y Z : Cᵒᵖ} (g : X ⟶ Y) (f : Y ⟶ Z) : exact f.unop g.unop ↔ exact g f := ⟨λ e, by rwa [← f.op_unop, ← g.op_unop, ← exact.op_iff] at e, λ e, @@exact.unop _ _ g f e⟩ end opposite end abelian namespace functor section variables {D : Type u₂} [category.{v₂} D] [abelian D] variables (F : C ⥤ D) [preserves_zero_morphisms F] @[priority 100] instance reflects_exact_sequences_of_preserves_zero_morphisms_of_faithful [faithful F] : reflects_exact_sequences F := { reflects := λ X Y Z f g hfg, begin rw [abelian.exact_iff, ← F.map_comp, F.map_eq_zero_iff] at hfg, refine (abelian.exact_iff _ _).2 ⟨hfg.1, F.zero_of_map_zero _ _⟩, obtain ⟨k, hk⟩ := kernel.lift' (F.map g) (F.map (kernel.ι g)) (by simp only [← F.map_comp, kernel.condition, category_theory.functor.map_zero]), obtain ⟨l, hl⟩ := cokernel.desc' (F.map f) (F.map (cokernel.π f)) (by simp only [← F.map_comp, cokernel.condition, category_theory.functor.map_zero]), rw [F.map_comp, ← hk, ← hl, category.assoc, reassoc_of hfg.2, zero_comp, comp_zero] end } end end functor namespace functor open limits abelian variables {A : Type u₁} {B : Type u₂} [category.{v₁} A] [category.{v₂} B] variables [abelian A] [abelian B] variables (L : A ⥤ B) section variables [preserves_finite_limits L] [preserves_finite_colimits L] /-- A functor preserving finite limits and finite colimits preserves exactness. The converse result is also true, see `functor.preserves_finite_limits_of_map_exact` and `functor.preserves_finite_colimits_of_map_exact`. -/ lemma map_exact {X Y Z : A} (f : X ⟶ Y) (g : Y ⟶ Z) (e1 : exact f g) : exact (L.map f) (L.map g) := begin let hcoker := is_colimit_of_has_cokernel_of_preserves_colimit L f, let hker := is_limit_of_has_kernel_of_preserves_limit L g, refine (exact_iff' _ _ hker hcoker).2 ⟨by simp [← L.map_comp, e1.1], _⟩, rw [fork.ι_of_ι, cofork.π_of_π, ← L.map_comp, kernel_comp_cokernel _ _ e1, L.map_zero] end end section variables (h : ∀ ⦃X Y Z : A⦄ {f : X ⟶ Y} {g : Y ⟶ Z}, exact f g → exact (L.map f) (L.map g)) include h open_locale zero_object /-- A functor which preserves exactness preserves zero morphisms. -/ lemma preserves_zero_morphisms_of_map_exact : L.preserves_zero_morphisms := begin replace h := (h (exact_of_zero (𝟙 0) (𝟙 0))).w, rw [L.map_id, category.comp_id] at h, exact preserves_zero_morphisms_of_map_zero_object (id_zero_equiv_iso_zero _ h), end /-- A functor which preserves exactness preserves monomorphisms. -/ lemma preserves_monomorphisms_of_map_exact : L.preserves_monomorphisms := { preserves := λ X Y f hf, begin letI := preserves_zero_morphisms_of_map_exact L h, apply ((tfae_mono (L.obj 0) (L.map f)).out 2 0).mp, rw ←L.map_zero, exact h (((tfae_mono 0 f).out 0 2).mp hf) end } /-- A functor which preserves exactness preserves epimorphisms. -/ lemma preserves_epimorphisms_of_map_exact : L.preserves_epimorphisms := { preserves := λ X Y f hf, begin letI := preserves_zero_morphisms_of_map_exact L h, apply ((tfae_epi (L.obj 0) (L.map f)).out 2 0).mp, rw ←L.map_zero, exact h (((tfae_epi 0 f).out 0 2).mp hf) end } /-- A functor which preserves exactness preserves kernels. -/ def preserves_kernels_of_map_exact (X Y : A) (f : X ⟶ Y) : preserves_limit (parallel_pair f 0) L := { preserves := λ c ic, begin letI := preserves_zero_morphisms_of_map_exact L h, letI := preserves_monomorphisms_of_map_exact L h, letI := mono_of_is_limit_fork ic, have hf := (is_limit_map_cone_fork_equiv' L (kernel_fork.condition c)).symm (is_limit_of_exact_of_mono (L.map (fork.ι c)) (L.map f) (h (exact_of_is_kernel (fork.ι c) f (kernel_fork.condition c) (ic.of_iso_limit (iso_of_ι _))))), exact hf.of_iso_limit ((cones.functoriality _ L).map_iso (iso_of_ι _).symm), end } /-- A functor which preserves exactness preserves zero cokernels. -/ def preserves_cokernels_of_map_exact (X Y : A) (f : X ⟶ Y) : preserves_colimit (parallel_pair f 0) L := { preserves := λ c ic, begin letI := preserves_zero_morphisms_of_map_exact L h, letI := preserves_epimorphisms_of_map_exact L h, letI := epi_of_is_colimit_cofork ic, have hf := (is_colimit_map_cocone_cofork_equiv' L (cokernel_cofork.condition c)).symm (is_colimit_of_exact_of_epi (L.map f) (L.map (cofork.π c)) (h (exact_of_is_cokernel f (cofork.π c) (cokernel_cofork.condition c) (ic.of_iso_colimit (iso_of_π _))))), exact hf.of_iso_colimit ((cocones.functoriality _ L).map_iso (iso_of_π _).symm), end } /-- A functor which preserves exactness is left exact, i.e. preserves finite limits. This is part of the inverse implication to `functor.map_exact`. -/ def preserves_finite_limits_of_map_exact : preserves_finite_limits L := begin letI := preserves_zero_morphisms_of_map_exact L h, letI := preserves_kernels_of_map_exact L h, apply preserves_finite_limits_of_preserves_kernels, end /-- A functor which preserves exactness is right exact, i.e. preserves finite colimits. This is part of the inverse implication to `functor.map_exact`. -/ def preserves_finite_colimits_of_map_exact : preserves_finite_colimits L := begin letI := preserves_zero_morphisms_of_map_exact L h, letI := preserves_cokernels_of_map_exact L h, apply preserves_finite_colimits_of_preserves_cokernels, end end section /-- A functor preserving zero morphisms, monos, and cokernels preserves finite limits. -/ def preserves_finite_limits_of_preserves_monos_and_cokernels [preserves_zero_morphisms L] [preserves_monomorphisms L] [∀ {X Y} (f : X ⟶ Y), preserves_colimit (parallel_pair f 0) L] : preserves_finite_limits L := begin apply preserves_finite_limits_of_map_exact, intros X Y Z f g h, rw [← abelian.coimage.fac g, L.map_comp, exact_comp_mono_iff], exact exact_of_is_cokernel _ _ _ (is_colimit_cofork_map_of_is_colimit' L _ (is_colimit_coimage f g h)) end /-- A functor preserving zero morphisms, epis, and kernels preserves finite colimits. -/ def preserves_finite_colimits_of_preserves_epis_and_kernels [preserves_zero_morphisms L] [preserves_epimorphisms L] [∀ {X Y} (f : X ⟶ Y), preserves_limit (parallel_pair f 0) L] : preserves_finite_colimits L := begin apply preserves_finite_colimits_of_map_exact, intros X Y Z f g h, rw [← abelian.image.fac f, L.map_comp, exact_epi_comp_iff], exact exact_of_is_kernel _ _ _ (is_limit_fork_map_of_is_limit' L _ (is_limit_image f g h)) end end end functor end category_theory
fec5a190980e8b3d397b9321c8f28b225505bd21
9028d228ac200bbefe3a711342514dd4e4458bff
/archive/100-theorems-list/70_perfect_numbers.lean
ce08c52150aedc484ed9dc10d9c546d185d36323
[ "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
2,138
lean
/- Copyright (c) 2020 Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Aaron Anderson. -/ import number_theory.arithmetic_function import number_theory.lucas_lehmer import algebra.geom_sum /-! # Perfect Numbers This file proves (currently one direction of) Theorem 70 from the [100 Theorems List](https://www.cs.ru.nl/~freek/100/). The theorem characterizes even perfect numbers. Euclid proved that if `2 ^ (k + 1) - 1` is prime (these primes are known as Mersenne primes), then `2 ^ k * 2 ^ (k + 1) - 1` is perfect. Euler proved the converse, that if `n` is even and perfect, then there exists `k` such that `n = 2 ^ k * 2 ^ (k + 1) - 1` and `2 ^ (k + 1) - 1` is prime. ## References https://en.wikipedia.org/wiki/Euclid%E2%80%93Euler_theorem -/ lemma odd_mersenne_succ (k : ℕ) : ¬ 2 ∣ mersenne (k + 1) := by simp [← even_iff_two_dvd, ← nat.even_succ, nat.succ_eq_add_one] with parity_simps namespace nat open arithmetic_function finset open_locale arithmetic_function lemma sigma_two_pow_eq_mersenne_succ (k : ℕ) : σ 1 (2 ^ k) = mersenne (k + 1) := by simpa [mersenne, prime_two, ← geom_sum_mul_add 1 (k+1)] /-- Euclid's theorem that Mersenne primes induce perfect numbers -/ theorem perfect_two_pow_mul_mersenne_of_prime (k : ℕ) (pr : (mersenne (k + 1)).prime) : perfect ((2 ^ k) * mersenne (k + 1)) := begin rw [perfect_iff_sum_divisors_eq_two_mul, ← mul_assoc, ← pow_succ, ← sigma_one_apply, mul_comm, is_multiplicative_sigma.map_mul_of_coprime (nat.prime_two.coprime_pow_of_not_dvd (odd_mersenne_succ _)), sigma_two_pow_eq_mersenne_succ], { simp [pr, nat.prime_two] }, { apply mul_pos (pow_pos _ k) (mersenne_pos (nat.succ_pos k)), norm_num } end lemma ne_zero_of_prime_mersenne (k : ℕ) (pr : (mersenne (k + 1)).prime) : k ≠ 0 := begin rintro rfl, simpa [mersenne, not_prime_one] using pr, end theorem even_two_pow_mul_mersenne_of_prime (k : ℕ) (pr : (mersenne (k + 1)).prime) : even ((2 ^ k) * mersenne (k + 1)) := by simp [ne_zero_of_prime_mersenne k pr] with parity_simps end nat
270504573c182f30047bc6b96a8d86575b84592b
95dcf8dea2baf2b4b0a60d438f27c35ae3dd3990
/src/group_theory/group_action.lean
fc9c41108223de2fb130e8b266c2e048955f40b6
[ "Apache-2.0" ]
permissive
uniformity1/mathlib
829341bad9dfa6d6be9adaacb8086a8a492e85a4
dd0e9bd8f2e5ec267f68e72336f6973311909105
refs/heads/master
1,588,592,015,670
1,554,219,842,000
1,554,219,842,000
179,110,702
0
0
Apache-2.0
1,554,220,076,000
1,554,220,076,000
null
UTF-8
Lean
false
false
6,544
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import data.set.finite group_theory.coset universes u v w variables {α : Type u} {β : Type v} {γ : Type w} /-- Typeclass for types with a scalar multiplication operation, denoted `•` (`\bu`) -/ class has_scalar (α : Type u) (γ : Type v) := (smul : α → γ → γ) infixr ` • `:73 := has_scalar.smul /-- Typeclass for multiplictive actions by monoids. This generalizes group actions. -/ class mul_action (α : Type u) (β : Type v) [monoid α] extends has_scalar α β := (one_smul : ∀ b : β, (1 : α) • b = b) (mul_smul : ∀ (x y : α) (b : β), (x * y) • b = x • y • b) section variables [monoid α] [mul_action α β] theorem mul_smul (a₁ a₂ : α) (b : β) : (a₁ * a₂) • b = a₁ • a₂ • b := mul_action.mul_smul _ _ _ variable (α) @[simp] theorem one_smul (b : β) : (1 : α) • b = b := mul_action.one_smul α _ end namespace mul_action variables (α) [monoid α] [mul_action α β] def orbit (b : β) := set.range (λ x : α, x • b) variable {α} @[simp] lemma mem_orbit_iff {b₁ b₂ : β} : b₂ ∈ orbit α b₁ ↔ ∃ x : α, x • b₁ = b₂ := iff.rfl @[simp] lemma mem_orbit (b : β) (x : α) : x • b ∈ orbit α b := ⟨x, rfl⟩ @[simp] lemma mem_orbit_self (b : β) : b ∈ orbit α b := ⟨1, by simp [mul_action.one_smul]⟩ instance orbit_fintype (b : β) [fintype α] [decidable_eq β] : fintype (orbit α b) := set.fintype_range _ variable (α) def stabilizer (b : β) : set α := {x : α | x • b = b} variable {α} @[simp] lemma mem_stabilizer_iff {b : β} {x : α} : x ∈ stabilizer α b ↔ x • b = b := iff.rfl variables (α) (β) def fixed_points : set β := {b : β | ∀ x, x ∈ stabilizer α b} variables {α} (β) @[simp] lemma mem_fixed_points {b : β} : b ∈ fixed_points α β ↔ ∀ x : α, x • b = b := iff.rfl lemma mem_fixed_points' {b : β} : b ∈ fixed_points α β ↔ (∀ b', b' ∈ orbit α b → b' = b) := ⟨λ h b h₁, let ⟨x, hx⟩ := mem_orbit_iff.1 h₁ in hx ▸ h x, λ h b, mem_stabilizer_iff.2 (h _ (mem_orbit _ _))⟩ def comp_hom [monoid γ] (g : γ → α) [is_monoid_hom g] : mul_action γ β := { smul := λ x b, (g x) • b, one_smul := by simp [is_monoid_hom.map_one g, mul_action.one_smul], mul_smul := by simp [is_monoid_hom.map_mul g, mul_action.mul_smul] } end mul_action namespace mul_action variables [group α] [mul_action α β] section open mul_action quotient_group variables (α) (β) def to_perm (g : α) : equiv.perm β := { to_fun := (•) g, inv_fun := (•) g⁻¹, left_inv := λ a, by rw [← mul_action.mul_smul, inv_mul_self, mul_action.one_smul], right_inv := λ a, by rw [← mul_action.mul_smul, mul_inv_self, mul_action.one_smul] } variables {α} {β} instance : is_group_hom (to_perm α β) := { mul := λ x y, equiv.ext _ _ (λ a, mul_action.mul_smul x y a) } lemma bijective (g : α) : function.bijective (λ b : β, g • b) := (to_perm α β g).bijective lemma orbit_eq_iff {a b : β} : orbit α a = orbit α b ↔ a ∈ orbit α b:= ⟨λ h, h ▸ mem_orbit_self _, λ ⟨x, (hx : x • b = a)⟩, set.ext (λ c, ⟨λ ⟨y, (hy : y • a = c)⟩, ⟨y * x, show (y * x) • b = c, by rwa [mul_action.mul_smul, hx]⟩, λ ⟨y, (hy : y • b = c)⟩, ⟨y * x⁻¹, show (y * x⁻¹) • a = c, by conv {to_rhs, rw [← hy, ← mul_one y, ← inv_mul_self x, ← mul_assoc, mul_action.mul_smul, hx]}⟩⟩)⟩ instance (b : β) : is_subgroup (stabilizer α b) := { one_mem := mul_action.one_smul _ _, mul_mem := λ x y (hx : x • b = b) (hy : y • b = b), show (x * y) • b = b, by rw mul_action.mul_smul; simp *, inv_mem := λ x (hx : x • b = b), show x⁻¹ • b = b, by rw [← hx, ← mul_action.mul_smul, inv_mul_self, mul_action.one_smul, hx] } variables (α) (β) def orbit_rel : setoid β := { r := λ a b, a ∈ orbit α b, iseqv := ⟨mem_orbit_self, λ a b, by simp [orbit_eq_iff.symm, eq_comm], λ a b, by simp [orbit_eq_iff.symm, eq_comm] {contextual := tt}⟩ } variables {β} open quotient_group noncomputable def orbit_equiv_quotient_stabilizer (b : β) : orbit α b ≃ quotient (stabilizer α b) := equiv.symm (@equiv.of_bijective _ _ (λ x : quotient (stabilizer α b), quotient.lift_on' x (λ x, (⟨x • b, mem_orbit _ _⟩ : orbit α b)) (λ g h (H : _ = _), subtype.eq $ (mul_action.bijective (g⁻¹)).1 $ show g⁻¹ • (g • b) = g⁻¹ • (h • b), by rw [← mul_action.mul_smul, ← mul_action.mul_smul, H, inv_mul_self, mul_action.one_smul])) ⟨λ g h, quotient.induction_on₂' g h (λ g h H, quotient.sound' $ have H : g • b = h • b := subtype.mk.inj H, show (g⁻¹ * h) • b = b, by rw [mul_action.mul_smul, ← H, ← mul_action.mul_smul, inv_mul_self, mul_action.one_smul]), λ ⟨b, ⟨g, hgb⟩⟩, ⟨g, subtype.eq hgb⟩⟩) end open quotient_group mul_action is_subgroup def mul_left_cosets (H : set α) [is_subgroup H] (x : α) (y : quotient H) : quotient H := quotient.lift_on' y (λ y, quotient_group.mk ((x : α) * y)) (λ a b (hab : _ ∈ H), quotient_group.eq.2 (by rwa [mul_inv_rev, ← mul_assoc, mul_assoc (a⁻¹), inv_mul_self, mul_one])) instance (H : set α) [is_subgroup H] : mul_action α (quotient H) := { smul := mul_left_cosets H, one_smul := λ a, quotient.induction_on' a (λ a, quotient_group.eq.2 (by simp [is_submonoid.one_mem])), mul_smul := λ x y a, quotient.induction_on' a (λ a, quotient_group.eq.2 (by simp [mul_inv_rev, is_submonoid.one_mem, mul_assoc])) } instance mul_left_cosets_comp_subtype_val (H I : set α) [is_subgroup H] [is_subgroup I] : mul_action I (quotient H) := mul_action.comp_hom (quotient H) (subtype.val : I → α) end mul_action /-- Typeclass for multiplicative actions on additive structures. This generalizes group modules. -/ class distrib_mul_action (α : Type u) (β : Type v) [monoid α] [add_monoid β] extends mul_action α β := (smul_add : ∀(r : α) (x y : β), r • (x + y) = r • x + r • y) (smul_zero {} : ∀(r : α), r • (0 : β) = 0) section variables [monoid α] [add_monoid β] [distrib_mul_action α β] theorem smul_add (a : α) (b₁ b₂ : β) : a • (b₁ + b₂) = a • b₁ + a • b₂ := distrib_mul_action.smul_add _ _ _ @[simp] theorem smul_zero (a : α) : a • (0 : β) = 0 := distrib_mul_action.smul_zero _ end
db7ed8bdb8862dd1e46dd21bd5590f184ce082cb
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/probability/martingale/borel_cantelli.lean
4a97b49a346b9e3bfe1766207125af990bcec4c9
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
18,825
lean
/- Copyright (c) 2022 Kexing Ying. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kexing Ying -/ import probability.martingale.convergence import probability.martingale.optional_stopping import probability.martingale.centering /-! # Generalized Borel-Cantelli lemma > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file proves Lévy's generalized Borel-Cantelli lemma which is a generalization of the Borel-Cantelli lemmas. With this generalization, one can easily deduce the Borel-Cantelli lemmas by choosing appropriate filtrations. This file also contains the one sided martingale bound which is required to prove the generalized Borel-Cantelli. ## Main results - `measure_theory.submartingale.bdd_above_iff_exists_tendsto`: the one sided martingale bound: given a submartingale `f` with uniformly bounded differences, the set for which `f` converges is almost everywhere equal to the set for which it is bounded. - `measure_theory.ae_mem_limsup_at_top_iff`: Lévy's generalized Borel-Cantelli: given a filtration `ℱ` and a sequence of sets `s` such that `s n ∈ ℱ n` for all `n`, `limsup at_top s` is almost everywhere equal to the set for which `∑ ℙ[s (n + 1)∣ℱ n] = ∞`. -/ open filter open_locale nnreal ennreal measure_theory probability_theory big_operators topology namespace measure_theory variables {Ω : Type*} {m0 : measurable_space Ω} {μ : measure Ω} {ℱ : filtration ℕ m0} {f : ℕ → Ω → ℝ} {ω : Ω} /-! ### One sided martingale bound -/ -- TODO: `least_ge` should be defined taking values in `with_top ℕ` once the `stopped_process` -- refactor is complete /-- `least_ge f r n` is the stopping time corresponding to the first time `f ≥ r`. -/ noncomputable def least_ge (f : ℕ → Ω → ℝ) (r : ℝ) (n : ℕ) := hitting f (set.Ici r) 0 n lemma adapted.is_stopping_time_least_ge (r : ℝ) (n : ℕ) (hf : adapted ℱ f) : is_stopping_time ℱ (least_ge f r n) := hitting_is_stopping_time hf measurable_set_Ici lemma least_ge_le {i : ℕ} {r : ℝ} (ω : Ω) : least_ge f r i ω ≤ i := hitting_le ω -- The following four lemmas shows `least_ge` behaves like a stopped process. Ideally we should -- define `least_ge` as a stopping time and take its stopped process. However, we can't do that -- with our current definition since a stopping time takes only finite indicies. An upcomming -- refactor should hopefully make it possible to have stopping times taking infinity as a value lemma least_ge_mono {n m : ℕ} (hnm : n ≤ m) (r : ℝ) (ω : Ω) : least_ge f r n ω ≤ least_ge f r m ω := hitting_mono hnm lemma least_ge_eq_min (π : Ω → ℕ) (r : ℝ) (ω : Ω) {n : ℕ} (hπn : ∀ ω, π ω ≤ n) : least_ge f r (π ω) ω = min (π ω) (least_ge f r n ω) := begin classical, refine le_antisymm (le_min (least_ge_le _) (least_ge_mono (hπn ω) r ω)) _, by_cases hle : π ω ≤ least_ge f r n ω, { rw [min_eq_left hle, least_ge], by_cases h : ∃ j ∈ set.Icc 0 (π ω), f j ω ∈ set.Ici r, { refine hle.trans (eq.le _), rw [least_ge, ← hitting_eq_hitting_of_exists (hπn ω) h] }, { simp only [hitting, if_neg h] } }, { rw [min_eq_right (not_le.1 hle).le, least_ge, least_ge, ← hitting_eq_hitting_of_exists (hπn ω) _], rw [not_le, least_ge, hitting_lt_iff _ (hπn ω)] at hle, exact let ⟨j, hj₁, hj₂⟩ := hle in ⟨j, ⟨hj₁.1, hj₁.2.le⟩, hj₂⟩ } end lemma stopped_value_stopped_value_least_ge (f : ℕ → Ω → ℝ) (π : Ω → ℕ) (r : ℝ) {n : ℕ} (hπn : ∀ ω, π ω ≤ n) : stopped_value (λ i, stopped_value f (least_ge f r i)) π = stopped_value (stopped_process f (least_ge f r n)) π := by { ext1 ω, simp_rw [stopped_process, stopped_value], rw least_ge_eq_min _ _ _ hπn, } lemma submartingale.stopped_value_least_ge [is_finite_measure μ] (hf : submartingale f ℱ μ) (r : ℝ) : submartingale (λ i, stopped_value f (least_ge f r i)) ℱ μ := begin rw submartingale_iff_expected_stopped_value_mono, { intros σ π hσ hπ hσ_le_π hπ_bdd, obtain ⟨n, hπ_le_n⟩ := hπ_bdd, simp_rw stopped_value_stopped_value_least_ge f σ r (λ i, (hσ_le_π i).trans (hπ_le_n i)), simp_rw stopped_value_stopped_value_least_ge f π r hπ_le_n, refine hf.expected_stopped_value_mono _ _ _ (λ ω, (min_le_left _ _).trans (hπ_le_n ω)), { exact hσ.min (hf.adapted.is_stopping_time_least_ge _ _), }, { exact hπ.min (hf.adapted.is_stopping_time_least_ge _ _), }, { exact λ ω, min_le_min (hσ_le_π ω) le_rfl, }, }, { exact λ i, strongly_measurable_stopped_value_of_le hf.adapted.prog_measurable_of_discrete (hf.adapted.is_stopping_time_least_ge _ _) least_ge_le, }, { exact λ i, integrable_stopped_value _ ((hf.adapted.is_stopping_time_least_ge _ _)) (hf.integrable) least_ge_le, }, end variables {r : ℝ} {R : ℝ≥0} lemma norm_stopped_value_least_ge_le (hr : 0 ≤ r) (hf0 : f 0 = 0) (hbdd : ∀ᵐ ω ∂μ, ∀ i, |f (i + 1) ω - f i ω| ≤ R) (i : ℕ) : ∀ᵐ ω ∂μ, stopped_value f (least_ge f r i) ω ≤ r + R := begin filter_upwards [hbdd] with ω hbddω, change f (least_ge f r i ω) ω ≤ r + R, by_cases heq : least_ge f r i ω = 0, { rw [heq, hf0, pi.zero_apply], exact add_nonneg hr R.coe_nonneg }, { obtain ⟨k, hk⟩ := nat.exists_eq_succ_of_ne_zero heq, rw [hk, add_comm, ← sub_le_iff_le_add], have := not_mem_of_lt_hitting (hk.symm ▸ k.lt_succ_self : k < least_ge f r i ω) (zero_le _), simp only [set.mem_union, set.mem_Iic, set.mem_Ici, not_or_distrib, not_le] at this, exact (sub_lt_sub_left this _).le.trans ((le_abs_self _).trans (hbddω _)) } end lemma submartingale.stopped_value_least_ge_snorm_le [is_finite_measure μ] (hf : submartingale f ℱ μ) (hr : 0 ≤ r) (hf0 : f 0 = 0) (hbdd : ∀ᵐ ω ∂μ, ∀ i, |f (i + 1) ω - f i ω| ≤ R) (i : ℕ) : snorm (stopped_value f (least_ge f r i)) 1 μ ≤ 2 * μ set.univ * ennreal.of_real (r + R) := begin refine snorm_one_le_of_le' ((hf.stopped_value_least_ge r).integrable _) _ (norm_stopped_value_least_ge_le hr hf0 hbdd i), rw ← integral_univ, refine le_trans _ ((hf.stopped_value_least_ge r).set_integral_le (zero_le _) measurable_set.univ), simp_rw [stopped_value, least_ge, hitting_of_le le_rfl, hf0, integral_zero'] end lemma submartingale.stopped_value_least_ge_snorm_le' [is_finite_measure μ] (hf : submartingale f ℱ μ) (hr : 0 ≤ r) (hf0 : f 0 = 0) (hbdd : ∀ᵐ ω ∂μ, ∀ i, |f (i + 1) ω - f i ω| ≤ R) (i : ℕ) : snorm (stopped_value f (least_ge f r i)) 1 μ ≤ ennreal.to_nnreal (2 * μ set.univ * ennreal.of_real (r + R)) := begin refine (hf.stopped_value_least_ge_snorm_le hr hf0 hbdd i).trans _, simp [ennreal.coe_to_nnreal (measure_ne_top μ _), ennreal.coe_to_nnreal], end /-- This lemma is superceded by `submartingale.bdd_above_iff_exists_tendsto`. -/ lemma submartingale.exists_tendsto_of_abs_bdd_above_aux [is_finite_measure μ] (hf : submartingale f ℱ μ) (hf0 : f 0 = 0) (hbdd : ∀ᵐ ω ∂μ, ∀ i, |f (i + 1) ω - f i ω| ≤ R) : ∀ᵐ ω ∂μ, bdd_above (set.range $ λ n, f n ω) → ∃ c, tendsto (λ n, f n ω) at_top (𝓝 c) := begin have ht : ∀ᵐ ω ∂μ, ∀ i : ℕ, ∃ c, tendsto (λ n, stopped_value f (least_ge f i n) ω) at_top (𝓝 c), { rw ae_all_iff, exact λ i, submartingale.exists_ae_tendsto_of_bdd (hf.stopped_value_least_ge i) (hf.stopped_value_least_ge_snorm_le' i.cast_nonneg hf0 hbdd) }, filter_upwards [ht] with ω hω hωb, rw bdd_above at hωb, obtain ⟨i, hi⟩ := exists_nat_gt hωb.some, have hib : ∀ n, f n ω < i, { intro n, exact lt_of_le_of_lt ((mem_upper_bounds.1 hωb.some_mem) _ ⟨n, rfl⟩) hi }, have heq : ∀ n, stopped_value f (least_ge f i n) ω = f n ω, { intro n, rw [least_ge, hitting, stopped_value], simp only, rw if_neg, simp only [set.mem_Icc, set.mem_union, set.mem_Ici], push_neg, exact λ j _, hib j }, simp only [← heq, hω i], end lemma submartingale.bdd_above_iff_exists_tendsto_aux [is_finite_measure μ] (hf : submartingale f ℱ μ) (hf0 : f 0 = 0) (hbdd : ∀ᵐ ω ∂μ, ∀ i, |f (i + 1) ω - f i ω| ≤ R) : ∀ᵐ ω ∂μ, bdd_above (set.range $ λ n, f n ω) ↔ ∃ c, tendsto (λ n, f n ω) at_top (𝓝 c) := by filter_upwards [hf.exists_tendsto_of_abs_bdd_above_aux hf0 hbdd] with ω hω using ⟨hω, λ ⟨c, hc⟩, hc.bdd_above_range⟩ /-- One sided martingale bound: If `f` is a submartingale which has uniformly bounded differences, then for almost every `ω`, `f n ω` is bounded above (in `n`) if and only if it converges. -/ lemma submartingale.bdd_above_iff_exists_tendsto [is_finite_measure μ] (hf : submartingale f ℱ μ) (hbdd : ∀ᵐ ω ∂μ, ∀ i, |f (i + 1) ω - f i ω| ≤ R) : ∀ᵐ ω ∂μ, bdd_above (set.range $ λ n, f n ω) ↔ ∃ c, tendsto (λ n, f n ω) at_top (𝓝 c) := begin set g : ℕ → Ω → ℝ := λ n ω, f n ω - f 0 ω with hgdef, have hg : submartingale g ℱ μ := hf.sub_martingale (martingale_const_fun _ _ (hf.adapted 0) (hf.integrable 0)), have hg0 : g 0 = 0, { ext ω, simp only [hgdef, sub_self, pi.zero_apply] }, have hgbdd : ∀ᵐ ω ∂μ, ∀ (i : ℕ), |g (i + 1) ω - g i ω| ≤ ↑R, { simpa only [sub_sub_sub_cancel_right] }, filter_upwards [hg.bdd_above_iff_exists_tendsto_aux hg0 hgbdd] with ω hω, convert hω using 1; rw eq_iff_iff, { simp only [hgdef], refine ⟨λ h, _, λ h, _⟩; obtain ⟨b, hb⟩ := h; refine ⟨b + |f 0 ω|, λ y hy, _⟩; obtain ⟨n, rfl⟩ := hy, { simp_rw [sub_eq_add_neg], exact add_le_add (hb ⟨n, rfl⟩) (neg_le_abs_self _) }, { exact sub_le_iff_le_add.1 (le_trans (sub_le_sub_left (le_abs_self _) _) (hb ⟨n, rfl⟩)) } }, { simp only [hgdef], refine ⟨λ h, _, λ h, _⟩; obtain ⟨c, hc⟩ := h, { exact ⟨c - f 0 ω, hc.sub_const _⟩ }, { refine ⟨c + f 0 ω, _⟩, have := hc.add_const (f 0 ω), simpa only [sub_add_cancel] } } end /-! ### Lévy's generalization of the Borel-Cantelli lemma Lévy's generalization of the Borel-Cantelli lemma states that: given a natural number indexed filtration $(\mathcal{F}_n)$, and a sequence of sets $(s_n)$ such that for all $n$, $s_n \in \mathcal{F}_n$, $limsup_n s_n$ is almost everywhere equal to the set for which $\sum_n \mathbb{P}[s_n \mid \mathcal{F}_n] = \infty$. The proof strategy follows by constructing a martingale satisfying the one sided martingale bound. In particular, we define $$ f_n := \sum_{k < n} \mathbf{1}_{s_{n + 1}} - \mathbb{P}[s_{n + 1} \mid \mathcal{F}_n]. $$ Then, as a martingale is both a sub and a super-martingale, the set for which it is unbounded from above must agree with the set for which it is unbounded from below almost everywhere. Thus, it can only converge to $\pm \infty$ with probability 0. Thus, by considering $$ \limsup_n s_n = \{\sum_n \mathbf{1}_{s_n} = \infty\} $$ almost everywhere, the result follows. -/ lemma martingale.bdd_above_range_iff_bdd_below_range [is_finite_measure μ] (hf : martingale f ℱ μ) (hbdd : ∀ᵐ ω ∂μ, ∀ i, |f (i + 1) ω - f i ω| ≤ R) : ∀ᵐ ω ∂μ, bdd_above (set.range (λ n, f n ω)) ↔ bdd_below (set.range (λ n, f n ω)) := begin have hbdd' : ∀ᵐ ω ∂μ, ∀ i, |(-f) (i + 1) ω - (-f) i ω| ≤ R, { filter_upwards [hbdd] with ω hω i, erw [← abs_neg, neg_sub, sub_neg_eq_add, neg_add_eq_sub], exact hω i }, have hup := hf.submartingale.bdd_above_iff_exists_tendsto hbdd, have hdown := hf.neg.submartingale.bdd_above_iff_exists_tendsto hbdd', filter_upwards [hup, hdown] with ω hω₁ hω₂, have : (∃ c, tendsto (λ n, f n ω) at_top (𝓝 c)) ↔ ∃ c, tendsto (λ n, (-f) n ω) at_top (𝓝 c), { split; rintro ⟨c, hc⟩, { exact ⟨-c, hc.neg⟩ }, { refine ⟨-c, _⟩, convert hc.neg, simp only [neg_neg, pi.neg_apply] } }, rw [hω₁, this, ← hω₂], split; rintro ⟨c, hc⟩; refine ⟨-c, λ ω hω, _⟩, { rw mem_upper_bounds at hc, refine neg_le.2 (hc _ _), simpa only [pi.neg_apply, set.mem_range, neg_inj] }, { rw mem_lower_bounds at hc, simp_rw [set.mem_range, pi.neg_apply, neg_eq_iff_eq_neg] at hω, refine le_neg.1 (hc _ _), simpa only [set.mem_range] } end lemma martingale.ae_not_tendsto_at_top_at_top [is_finite_measure μ] (hf : martingale f ℱ μ) (hbdd : ∀ᵐ ω ∂μ, ∀ i, |f (i + 1) ω - f i ω| ≤ R) : ∀ᵐ ω ∂μ, ¬ tendsto (λ n, f n ω) at_top at_top := by filter_upwards [hf.bdd_above_range_iff_bdd_below_range hbdd] with ω hω htop using unbounded_of_tendsto_at_top htop (hω.2 $ bdd_below_range_of_tendsto_at_top_at_top htop) lemma martingale.ae_not_tendsto_at_top_at_bot [is_finite_measure μ] (hf : martingale f ℱ μ) (hbdd : ∀ᵐ ω ∂μ, ∀ i, |f (i + 1) ω - f i ω| ≤ R) : ∀ᵐ ω ∂μ, ¬ tendsto (λ n, f n ω) at_top at_bot := by filter_upwards [hf.bdd_above_range_iff_bdd_below_range hbdd] with ω hω htop using unbounded_of_tendsto_at_bot htop (hω.1 $ bdd_above_range_of_tendsto_at_top_at_bot htop) namespace borel_cantelli /-- Auxiliary definition required to prove Lévy's generalization of the Borel-Cantelli lemmas for which we will take the martingale part. -/ noncomputable def process (s : ℕ → set Ω) (n : ℕ) : Ω → ℝ := ∑ k in finset.range n, (s (k + 1)).indicator 1 variables {s : ℕ → set Ω} lemma process_zero : process s 0 = 0 := by rw [process, finset.range_zero, finset.sum_empty] lemma adapted_process (hs : ∀ n, measurable_set[ℱ n] (s n)) : adapted ℱ (process s) := λ n, finset.strongly_measurable_sum' _ $ λ k hk, strongly_measurable_one.indicator $ ℱ.mono (finset.mem_range.1 hk) _ $ hs _ lemma martingale_part_process_ae_eq (ℱ : filtration ℕ m0) (μ : measure Ω) (s : ℕ → set Ω) (n : ℕ) : martingale_part (process s) ℱ μ n = ∑ k in finset.range n, ((s (k + 1)).indicator 1 - μ[(s (k + 1)).indicator 1 | ℱ k]) := begin simp only [martingale_part_eq_sum, process_zero, zero_add], refine finset.sum_congr rfl (λ k hk, _), simp only [process, finset.sum_range_succ_sub_sum], end lemma predictable_part_process_ae_eq (ℱ : filtration ℕ m0) (μ : measure Ω) (s : ℕ → set Ω) (n : ℕ) : predictable_part (process s) ℱ μ n = ∑ k in finset.range n, μ[(s (k + 1)).indicator (1 : Ω → ℝ) | ℱ k] := begin have := martingale_part_process_ae_eq ℱ μ s n, simp_rw [martingale_part, process, finset.sum_sub_distrib] at this, exact sub_right_injective this, end lemma process_difference_le (s : ℕ → set Ω) (ω : Ω) (n : ℕ) : |process s (n + 1) ω - process s n ω| ≤ (1 : ℝ≥0) := begin rw [nonneg.coe_one, process, process, finset.sum_apply, finset.sum_apply, finset.sum_range_succ_sub_sum, ← real.norm_eq_abs, norm_indicator_eq_indicator_norm], refine set.indicator_le' (λ _ _, _) (λ _ _, zero_le_one) _, rw [pi.one_apply, norm_one] end lemma integrable_process (μ : measure Ω) [is_finite_measure μ] (hs : ∀ n, measurable_set[ℱ n] (s n)) (n : ℕ) : integrable (process s n) μ := integrable_finset_sum' _ $ λ k hk, integrable_on.integrable_indicator (integrable_const 1) $ ℱ.le _ _ $ hs _ end borel_cantelli open borel_cantelli /-- An a.e. monotone adapted process `f` with uniformly bounded differences converges to `+∞` if and only if its predictable part also converges to `+∞`. -/ lemma tendsto_sum_indicator_at_top_iff [is_finite_measure μ] (hfmono : ∀ᵐ ω ∂μ, ∀ n, f n ω ≤ f (n + 1) ω) (hf : adapted ℱ f) (hint : ∀ n, integrable (f n) μ) (hbdd : ∀ᵐ ω ∂μ, ∀ n, |f (n + 1) ω - f n ω| ≤ R) : ∀ᵐ ω ∂μ, tendsto (λ n, f n ω) at_top at_top ↔ tendsto (λ n, predictable_part f ℱ μ n ω) at_top at_top := begin have h₁ := (martingale_martingale_part hf hint).ae_not_tendsto_at_top_at_top (martingale_part_bdd_difference ℱ hbdd), have h₂ := (martingale_martingale_part hf hint).ae_not_tendsto_at_top_at_bot (martingale_part_bdd_difference ℱ hbdd), have h₃ : ∀ᵐ ω ∂μ, ∀ n, 0 ≤ μ[f (n + 1) - f n | ℱ n] ω, { refine ae_all_iff.2 (λ n, condexp_nonneg _), filter_upwards [ae_all_iff.1 hfmono n] with ω hω using sub_nonneg.2 hω }, filter_upwards [h₁, h₂, h₃, hfmono] with ω hω₁ hω₂ hω₃ hω₄, split; intro ht, { refine tendsto_at_top_at_top_of_monotone' _ _, { intros n m hnm, simp only [predictable_part, finset.sum_apply], refine finset.sum_mono_set_of_nonneg hω₃ (finset.range_mono hnm) }, rintro ⟨b, hbdd⟩, rw ← tendsto_neg_at_bot_iff at ht, simp only [martingale_part, sub_eq_add_neg] at hω₁, exact hω₁ (tendsto_at_top_add_right_of_le _ (-b) (tendsto_neg_at_bot_iff.1 ht) $ λ n, neg_le_neg (hbdd ⟨n, rfl⟩)) }, { refine tendsto_at_top_at_top_of_monotone' (monotone_nat_of_le_succ hω₄) _, rintro ⟨b, hbdd⟩, exact hω₂ (tendsto_at_bot_add_left_of_ge _ b (λ n, hbdd ⟨n, rfl⟩) $ tendsto_neg_at_bot_iff.2 ht) }, end open borel_cantelli lemma tendsto_sum_indicator_at_top_iff' [is_finite_measure μ] {s : ℕ → set Ω} (hs : ∀ n, measurable_set[ℱ n] (s n)) : ∀ᵐ ω ∂μ, tendsto (λ n, ∑ k in finset.range n, (s (k + 1)).indicator (1 : Ω → ℝ) ω) at_top at_top ↔ tendsto (λ n, ∑ k in finset.range n, μ[(s (k + 1)).indicator (1 : Ω → ℝ) | ℱ k] ω) at_top at_top := begin have := tendsto_sum_indicator_at_top_iff (eventually_of_forall $ λ ω n, _) (adapted_process hs) (integrable_process μ hs) (eventually_of_forall $ process_difference_le s), swap, { rw [process, process, ← sub_nonneg, finset.sum_apply, finset.sum_apply, finset.sum_range_succ_sub_sum], exact set.indicator_nonneg (λ _ _, zero_le_one) _ }, simp_rw [process, predictable_part_process_ae_eq] at this, simpa using this, end /-- **Lévy's generalization of the Borel-Cantelli lemma**: given a sequence of sets `s` and a filtration `ℱ` such that for all `n`, `s n` is `ℱ n`-measurable, `at_top.limsup s` is almost everywhere equal to the set for which `∑ k, ℙ(s (k + 1) | ℱ k) = ∞`. -/ theorem ae_mem_limsup_at_top_iff (μ : measure Ω) [is_finite_measure μ] {s : ℕ → set Ω} (hs : ∀ n, measurable_set[ℱ n] (s n)) : ∀ᵐ ω ∂μ, ω ∈ limsup s at_top ↔ tendsto (λ n, ∑ k in finset.range n, μ[(s (k + 1)).indicator (1 : Ω → ℝ) | ℱ k] ω) at_top at_top := (limsup_eq_tendsto_sum_indicator_at_top ℝ s).symm ▸ tendsto_sum_indicator_at_top_iff' hs end measure_theory
ef0278c77875a03e3220665b085895fcd3d6f273
63abd62053d479eae5abf4951554e1064a4c45b4
/src/data/mv_polynomial/invertible.lean
b3e3d4740e211539bc578c799a20ad5d2ed0b97a
[ "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
1,034
lean
/- Copyright (c) 2020 Johan Commelin and Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin and Robert Y. Lewis -/ import data.mv_polynomial.basic import ring_theory.algebra_tower /-! # Invertible polynomials This file is a stub containing some basic facts about invertible elements in the ring of polynomials. -/ open mv_polynomial noncomputable instance mv_polynomial.invertible_C (σ : Type*) {R : Type*} [comm_semiring R] (r : R) [invertible r] : invertible (C r : mv_polynomial σ R) := invertible.map C.to_monoid_hom _ /-- A natural number that is invertible when coerced to a commutative semiring `R` is also invertible when coerced to any polynomial ring with rational coefficients. Short-cut for typeclass resolution. -/ noncomputable instance mv_polynomial.invertible_coe_nat (σ R : Type*) (p : ℕ) [comm_semiring R] [invertible (p : R)] : invertible (p : mv_polynomial σ R) := is_scalar_tower.invertible_algebra_coe_nat R _ _
2ac7e8e3cb67cce4e4f55fd4f768676e9fa8a1f2
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/topology/local_homeomorph.lean
937372ce4f183912246b2b033fdad507f7c2b837
[ "Apache-2.0" ]
permissive
dupuisf/mathlib
62de4ec6544bf3b79086afd27b6529acfaf2c1bb
8582b06b0a5d06c33ee07d0bdf7c646cae22cf36
refs/heads/master
1,669,494,854,016
1,595,692,409,000
1,595,692,409,000
272,046,630
0
0
Apache-2.0
1,592,066,143,000
1,592,066,142,000
null
UTF-8
Lean
false
false
37,421
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 data.equiv.local_equiv import topology.homeomorph import topology.opens /-! # Local homeomorphisms This file defines homeomorphisms between open subsets of topological spaces. An element `e` of `local_homeomorph α β` is an extension of `local_equiv α β`, i.e., it is a pair of functions `e.to_fun` and `e.inv_fun`, inverse of each other on the sets `e.source` and `e.target`. Additionally, we require that these sets are open, and that the functions are continuous on them. Equivalently, they are homeomorphisms there. As in equivs, we register a coercion to functions, and we use `e x` and `e.symm x` throughout instead of `e.to_fun x` and `e.inv_fun x`. ## Main definitions `homeomorph.to_local_homeomorph`: associating a local homeomorphism to a homeomorphism, with source = target = univ `local_homeomorph.symm` : the inverse of a local homeomorphism `local_homeomorph.trans` : the composition of two local homeomorphisms `local_homeomorph.refl` : the identity local homeomorphism `local_homeomorph.of_set`: the identity on a set `s` `eq_on_source` : equivalence relation describing the "right" notion of equality for local homeomorphisms ## Implementation notes Most statements are copied from their local_equiv versions, although some care is required especially when restricting to subsets, as these should be open subsets. For design notes, see `local_equiv.lean`. -/ open function set open_locale topological_space variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} [topological_space α] [topological_space β] [topological_space γ] [topological_space δ] /-- local homeomorphisms, defined on open subsets of the space -/ @[nolint has_inhabited_instance] structure local_homeomorph (α : Type*) (β : Type*) [topological_space α] [topological_space β] extends local_equiv α β := (open_source : is_open source) (open_target : is_open target) (continuous_to_fun : continuous_on to_fun source) (continuous_inv_fun : continuous_on inv_fun target) /-- A homeomorphism induces a local homeomorphism on the whole space -/ def homeomorph.to_local_homeomorph (e : homeomorph α β) : local_homeomorph α β := { open_source := is_open_univ, open_target := is_open_univ, continuous_to_fun := by { erw ← continuous_iff_continuous_on_univ, exact e.continuous_to_fun }, continuous_inv_fun := by { erw ← continuous_iff_continuous_on_univ, exact e.continuous_inv_fun }, ..e.to_equiv.to_local_equiv } namespace local_homeomorph variables (e : local_homeomorph α β) (e' : local_homeomorph β γ) instance : has_coe_to_fun (local_homeomorph α β) := ⟨_, λ e, e.to_local_equiv.to_fun⟩ /-- The inverse of a local homeomorphism -/ protected def symm : local_homeomorph β α := { open_source := e.open_target, open_target := e.open_source, continuous_to_fun := e.continuous_inv_fun, continuous_inv_fun := e.continuous_to_fun, ..e.to_local_equiv.symm } protected lemma continuous_on : continuous_on e e.source := e.continuous_to_fun lemma continuous_on_symm : continuous_on e.symm e.target := e.continuous_inv_fun @[simp, mfld_simps] lemma mk_coe (e : local_equiv α β) (a b c d) : (local_homeomorph.mk e a b c d : α → β) = e := rfl @[simp, mfld_simps] lemma mk_coe_symm (e : local_equiv α β) (a b c d) : ((local_homeomorph.mk e a b c d).symm : β → α) = e.symm := rfl /- Register a few simp lemmas to make sure that `simp` puts the application of a local homeomorphism in its normal form, i.e., in terms of its coercion to a function. -/ @[simp, mfld_simps] lemma to_fun_eq_coe (e : local_homeomorph α β) : e.to_fun = e := rfl @[simp, mfld_simps] lemma inv_fun_eq_coe (e : local_homeomorph α β) : e.inv_fun = e.symm := rfl @[simp, mfld_simps] lemma coe_coe : (e.to_local_equiv : α → β) = e := rfl @[simp, mfld_simps] lemma coe_coe_symm : (e.to_local_equiv.symm : β → α) = e.symm := rfl @[simp, mfld_simps] lemma map_source {x : α} (h : x ∈ e.source) : e x ∈ e.target := e.map_source' h @[simp, mfld_simps] lemma map_target {x : β} (h : x ∈ e.target) : e.symm x ∈ e.source := e.map_target' h @[simp, mfld_simps] lemma left_inv {x : α} (h : x ∈ e.source) : e.symm (e x) = x := e.left_inv' h @[simp, mfld_simps] lemma right_inv {x : β} (h : x ∈ e.target) : e (e.symm x) = x := e.right_inv' h lemma source_preimage_target : e.source ⊆ e ⁻¹' e.target := λ _ h, map_source e h lemma eq_of_local_equiv_eq {e e' : local_homeomorph α β} (h : e.to_local_equiv = e'.to_local_equiv) : e = e' := begin cases e, cases e', dsimp at *, induction h, refl end lemma eventually_left_inverse (e : local_homeomorph α β) {x} (hx : x ∈ e.source) : ∀ᶠ y in 𝓝 x, e.symm (e y) = y := filter.eventually.mono (mem_nhds_sets e.open_source hx) e.left_inv' lemma eventually_left_inverse' (e : local_homeomorph α β) {x} (hx : x ∈ e.target) : ∀ᶠ y in 𝓝 (e.symm x), e.symm (e y) = y := e.eventually_left_inverse (e.map_target hx) lemma eventually_right_inverse (e : local_homeomorph α β) {x} (hx : x ∈ e.target) : ∀ᶠ y in 𝓝 x, e (e.symm y) = y := filter.eventually.mono (mem_nhds_sets e.open_target hx) e.right_inv' lemma eventually_right_inverse' (e : local_homeomorph α β) {x} (hx : x ∈ e.source) : ∀ᶠ y in 𝓝 (e x), e (e.symm y) = y := e.eventually_right_inverse (e.map_source hx) lemma image_eq_target_inter_inv_preimage {s : set α} (h : s ⊆ e.source) : e '' s = e.target ∩ e.symm ⁻¹' s := e.to_local_equiv.image_eq_target_inter_inv_preimage h lemma image_inter_source_eq (s : set α) : e '' (s ∩ e.source) = e.target ∩ e.symm ⁻¹' (s ∩ e.source) := e.image_eq_target_inter_inv_preimage (inter_subset_right _ _) lemma symm_image_eq_source_inter_preimage {s : set β} (h : s ⊆ e.target) : e.symm '' s = e.source ∩ e ⁻¹' s := e.symm.image_eq_target_inter_inv_preimage h lemma symm_image_inter_target_eq (s : set β) : e.symm '' (s ∩ e.target) = e.source ∩ e ⁻¹' (s ∩ e.target) := e.symm.image_inter_source_eq _ /-- Two local homeomorphisms are equal when they have equal `to_fun`, `inv_fun` and `source`. It is not sufficient to have equal `to_fun` and `source`, as this only determines `inv_fun` on the target. This would only be true for a weaker notion of equality, arguably the right one, called `eq_on_source`. -/ @[ext] protected lemma ext (e' : local_homeomorph α β) (h : ∀x, e x = e' x) (hinv : ∀x, e.symm x = e'.symm x) (hs : e.source = e'.source) : e = e' := eq_of_local_equiv_eq (local_equiv.ext h hinv hs) @[simp, mfld_simps] lemma symm_to_local_equiv : e.symm.to_local_equiv = e.to_local_equiv.symm := rfl -- The following lemmas are already simp via local_equiv lemma symm_source : e.symm.source = e.target := rfl lemma symm_target : e.symm.target = e.source := rfl @[simp, mfld_simps] lemma symm_symm : e.symm.symm = e := eq_of_local_equiv_eq $ by simp /-- A local homeomorphism is continuous at any point of its source -/ protected lemma continuous_at {x : α} (h : x ∈ e.source) : continuous_at e x := (e.continuous_on x h).continuous_at (mem_nhds_sets e.open_source h) /-- A local homeomorphism inverse is continuous at any point of its target -/ lemma continuous_at_symm {x : β} (h : x ∈ e.target) : continuous_at e.symm x := e.symm.continuous_at h lemma tendsto_symm (e : local_homeomorph α β) {x} (hx : x ∈ e.source) : filter.tendsto e.symm (𝓝 (e x)) (𝓝 x) := by simpa only [continuous_at, e.left_inv hx] using e.continuous_at_symm (e.map_source hx) /-- Preimage of interior or interior of preimage coincide for local homeomorphisms, when restricted to the source. -/ lemma preimage_interior (s : set β) : e.source ∩ e ⁻¹' (interior s) = e.source ∩ interior (e ⁻¹' s) := begin apply subset.antisymm, { exact e.continuous_on.preimage_interior_subset_interior_preimage e.open_source }, { calc e.source ∩ interior (e ⁻¹' s) = (e.source ∩ interior (e ⁻¹' s)) ∩ (e ⁻¹' e.target) : by mfld_set_tac ... = (e.source ∩ e ⁻¹' (e.symm ⁻¹' (interior (e ⁻¹' s)))) ∩ (e ⁻¹' e.target) : begin have := e.to_local_equiv.source_inter_preimage_inv_preimage _, simp only [coe_coe_symm, coe_coe] at this, rw this end ... = e.source ∩ e ⁻¹' (e.target ∩ e.symm ⁻¹' (interior (e ⁻¹' s))) : by rw [inter_comm e.target, preimage_inter, inter_assoc] ... ⊆ e.source ∩ e ⁻¹' (e.target ∩ interior (e.symm ⁻¹' (e ⁻¹' s))) : begin apply inter_subset_inter (subset.refl _) (preimage_mono _), exact e.continuous_on_symm.preimage_interior_subset_interior_preimage e.open_target end ... = e.source ∩ e ⁻¹' (interior (e.target ∩ e.symm ⁻¹' (e ⁻¹' s))) : by rw [interior_inter, interior_eq_of_open e.open_target] ... = e.source ∩ e ⁻¹' (interior (e.target ∩ s)) : begin have := e.to_local_equiv.target_inter_inv_preimage_preimage, simp only [coe_coe_symm, coe_coe] at this, rw this end ... = e.source ∩ e ⁻¹' e.target ∩ e ⁻¹' (interior s) : by rw [interior_inter, preimage_inter, interior_eq_of_open e.open_target, inter_assoc] ... = e.source ∩ e ⁻¹' (interior s) : by mfld_set_tac } end lemma preimage_open_of_open {s : set β} (hs : is_open s) : is_open (e.source ∩ e ⁻¹' s) := e.continuous_on.preimage_open_of_open e.open_source hs lemma preimage_open_of_open_symm {s : set α} (hs : is_open s) : is_open (e.target ∩ e.symm ⁻¹' s) := e.symm.continuous_on.preimage_open_of_open e.open_target hs /-- The image of an open set in the source is open. -/ lemma image_open_of_open {s : set α} (hs : is_open s) (h : s ⊆ e.source) : is_open (e '' s) := begin have : e '' s = e.target ∩ e.symm ⁻¹' s := e.to_local_equiv.image_eq_target_inter_inv_preimage h, rw this, exact e.continuous_on_symm.preimage_open_of_open e.open_target hs end /-- The image of the restriction of an open set to the source is open. -/ lemma image_open_of_open' {s : set α} (hs : is_open s) : is_open (e '' (s ∩ e.source)) := begin refine image_open_of_open _ (is_open_inter hs e.open_source) _, simp, end /-- Restricting a local homeomorphism `e` to `e.source ∩ s` when `s` is open. This is sometimes hard to use because of the openness assumption, but it has the advantage that when it can be used then its local_equiv is defeq to local_equiv.restr -/ protected def restr_open (s : set α) (hs : is_open s) : local_homeomorph α β := { open_source := is_open_inter e.open_source hs, open_target := (continuous_on_open_iff e.open_target).1 e.continuous_inv_fun s hs, continuous_to_fun := e.continuous_to_fun.mono (inter_subset_left _ _), continuous_inv_fun := e.continuous_inv_fun.mono (inter_subset_left _ _), ..e.to_local_equiv.restr s} @[simp, mfld_simps] lemma restr_open_to_local_equiv (s : set α) (hs : is_open s) : (e.restr_open s hs).to_local_equiv = e.to_local_equiv.restr s := rfl -- Already simp via local_equiv lemma restr_open_source (s : set α) (hs : is_open s) : (e.restr_open s hs).source = e.source ∩ s := rfl /-- Restricting a local homeomorphism `e` to `e.source ∩ interior s`. We use the interior to make sure that the restriction is well defined whatever the set s, since local homeomorphisms are by definition defined on open sets. In applications where `s` is open, this coincides with the restriction of local equivalences -/ protected def restr (s : set α) : local_homeomorph α β := e.restr_open (interior s) is_open_interior @[simp, mfld_simps] lemma restr_to_local_equiv (s : set α) : (e.restr s).to_local_equiv = (e.to_local_equiv).restr (interior s) := rfl @[simp, mfld_simps] lemma restr_coe (s : set α) : (e.restr s : α → β) = e := rfl @[simp, mfld_simps] lemma restr_coe_symm (s : set α) : ((e.restr s).symm : β → α) = e.symm := rfl lemma restr_source (s : set α) : (e.restr s).source = e.source ∩ interior s := rfl lemma restr_target (s : set α) : (e.restr s).target = e.target ∩ e.symm ⁻¹' (interior s) := rfl lemma restr_source' (s : set α) (hs : is_open s) : (e.restr s).source = e.source ∩ s := by rw [e.restr_source, interior_eq_of_open hs] lemma restr_to_local_equiv' (s : set α) (hs : is_open s): (e.restr s).to_local_equiv = e.to_local_equiv.restr s := by rw [e.restr_to_local_equiv, interior_eq_of_open hs] lemma restr_eq_of_source_subset {e : local_homeomorph α β} {s : set α} (h : e.source ⊆ s) : e.restr s = e := begin apply eq_of_local_equiv_eq, rw restr_to_local_equiv, apply local_equiv.restr_eq_of_source_subset, have := interior_mono h, rwa interior_eq_of_open (e.open_source) at this end @[simp, mfld_simps] lemma restr_univ {e : local_homeomorph α β} : e.restr univ = e := restr_eq_of_source_subset (subset_univ _) lemma restr_source_inter (s : set α) : e.restr (e.source ∩ s) = e.restr s := begin refine local_homeomorph.ext _ _ (λx, rfl) (λx, rfl) _, simp [interior_eq_of_open e.open_source], rw [← inter_assoc, inter_self] end /-- The identity on the whole space as a local homeomorphism. -/ protected def refl (α : Type*) [topological_space α] : local_homeomorph α α := (homeomorph.refl α).to_local_homeomorph @[simp, mfld_simps] lemma refl_local_equiv : (local_homeomorph.refl α).to_local_equiv = local_equiv.refl α := rfl lemma refl_source : (local_homeomorph.refl α).source = univ := rfl lemma refl_target : (local_homeomorph.refl α).target = univ := rfl @[simp, mfld_simps] lemma refl_symm : (local_homeomorph.refl α).symm = local_homeomorph.refl α := rfl @[simp, mfld_simps] lemma refl_coe : (local_homeomorph.refl α : α → α) = id := rfl section variables {s : set α} (hs : is_open s) /-- The identity local equiv on a set `s` -/ def of_set (s : set α) (hs : is_open s) : local_homeomorph α α := { open_source := hs, open_target := hs, continuous_to_fun := continuous_id.continuous_on, continuous_inv_fun := continuous_id.continuous_on, ..local_equiv.of_set s } @[simp, mfld_simps] lemma of_set_to_local_equiv : (of_set s hs).to_local_equiv = local_equiv.of_set s := rfl lemma of_set_source : (of_set s hs).source = s := rfl lemma of_set_target : (of_set s hs).target = s := rfl @[simp, mfld_simps] lemma of_set_coe : (of_set s hs : α → α) = id := rfl @[simp, mfld_simps] lemma of_set_symm : (of_set s hs).symm = of_set s hs := rfl @[simp, mfld_simps] lemma of_set_univ_eq_refl : of_set univ is_open_univ = local_homeomorph.refl α := by ext; simp end /-- Composition of two local homeomorphisms when the target of the first and the source of the second coincide. -/ protected def trans' (h : e.target = e'.source) : local_homeomorph α γ := { open_source := e.open_source, open_target := e'.open_target, continuous_to_fun := begin apply continuous_on.comp e'.continuous_to_fun e.continuous_to_fun, rw ← h, exact e.to_local_equiv.source_subset_preimage_target end, continuous_inv_fun := begin apply continuous_on.comp e.continuous_inv_fun e'.continuous_inv_fun, rw h, exact e'.to_local_equiv.target_subset_preimage_source end, ..local_equiv.trans' e.to_local_equiv e'.to_local_equiv h } /-- Composing two local homeomorphisms, by restricting to the maximal domain where their composition is well defined. -/ protected def trans : local_homeomorph α γ := local_homeomorph.trans' (e.symm.restr_open e'.source e'.open_source).symm (e'.restr_open e.target e.open_target) (by simp [inter_comm]) @[simp, mfld_simps] lemma trans_to_local_equiv : (e.trans e').to_local_equiv = e.to_local_equiv.trans e'.to_local_equiv := rfl @[simp, mfld_simps] lemma coe_trans : (e.trans e' : α → γ) = e' ∘ e := rfl @[simp, mfld_simps] lemma coe_trans_symm : ((e.trans e').symm : γ → α) = e.symm ∘ e'.symm := rfl lemma trans_symm_eq_symm_trans_symm : (e.trans e').symm = e'.symm.trans e.symm := by cases e; cases e'; refl /- This could be considered as a simp lemma, but there are many situations where it makes something simple into something more complicated. -/ lemma trans_source : (e.trans e').source = e.source ∩ e ⁻¹' e'.source := local_equiv.trans_source e.to_local_equiv e'.to_local_equiv lemma trans_source' : (e.trans e').source = e.source ∩ e ⁻¹' (e.target ∩ e'.source) := local_equiv.trans_source' e.to_local_equiv e'.to_local_equiv lemma trans_source'' : (e.trans e').source = e.symm '' (e.target ∩ e'.source) := local_equiv.trans_source'' e.to_local_equiv e'.to_local_equiv lemma image_trans_source : e '' (e.trans e').source = e.target ∩ e'.source := local_equiv.image_trans_source e.to_local_equiv e'.to_local_equiv lemma trans_target : (e.trans e').target = e'.target ∩ e'.symm ⁻¹' e.target := rfl lemma trans_target' : (e.trans e').target = e'.target ∩ e'.symm ⁻¹' (e'.source ∩ e.target) := trans_source' e'.symm e.symm lemma trans_target'' : (e.trans e').target = e' '' (e'.source ∩ e.target) := trans_source'' e'.symm e.symm lemma inv_image_trans_target : e'.symm '' (e.trans e').target = e'.source ∩ e.target := image_trans_source e'.symm e.symm lemma trans_assoc (e'' : local_homeomorph γ δ) : (e.trans e').trans e'' = e.trans (e'.trans e'') := eq_of_local_equiv_eq $ local_equiv.trans_assoc e.to_local_equiv e'.to_local_equiv e''.to_local_equiv @[simp, mfld_simps] lemma trans_refl : e.trans (local_homeomorph.refl β) = e := eq_of_local_equiv_eq $ local_equiv.trans_refl e.to_local_equiv @[simp, mfld_simps] lemma refl_trans : (local_homeomorph.refl α).trans e = e := eq_of_local_equiv_eq $ local_equiv.refl_trans e.to_local_equiv lemma trans_of_set {s : set β} (hs : is_open s) : e.trans (of_set s hs) = e.restr (e ⁻¹' s) := local_homeomorph.ext _ _ (λx, rfl) (λx, rfl) $ by simp [local_equiv.trans_source, (e.preimage_interior _).symm, interior_eq_of_open hs] lemma trans_of_set' {s : set β} (hs : is_open s) : e.trans (of_set s hs) = e.restr (e.source ∩ e ⁻¹' s) := by rw [trans_of_set, restr_source_inter] lemma of_set_trans {s : set α} (hs : is_open s) : (of_set s hs).trans e = e.restr s := local_homeomorph.ext _ _ (λx, rfl) (λx, rfl) $ by simp [local_equiv.trans_source, interior_eq_of_open hs, inter_comm] lemma of_set_trans' {s : set α} (hs : is_open s) : (of_set s hs).trans e = e.restr (e.source ∩ s) := by rw [of_set_trans, restr_source_inter] @[simp, mfld_simps] lemma of_set_trans_of_set {s : set α} (hs : is_open s) {s' : set α} (hs' : is_open s') : (of_set s hs).trans (of_set s' hs') = of_set (s ∩ s') (is_open_inter hs hs') := begin rw (of_set s hs).trans_of_set hs', ext; simp [interior_eq_of_open hs'] end lemma restr_trans (s : set α) : (e.restr s).trans e' = (e.trans e').restr s := eq_of_local_equiv_eq $ local_equiv.restr_trans e.to_local_equiv e'.to_local_equiv (interior s) /-- `eq_on_source e e'` means that `e` and `e'` have the same source, and coincide there. They should really be considered the same local equiv. -/ def eq_on_source (e e' : local_homeomorph α β) : Prop := e.source = e'.source ∧ (eq_on e e' e.source) lemma eq_on_source_iff (e e' : local_homeomorph α β) : eq_on_source e e' ↔ local_equiv.eq_on_source e.to_local_equiv e'.to_local_equiv := iff.rfl /-- `eq_on_source` is an equivalence relation -/ instance : setoid (local_homeomorph α β) := { r := eq_on_source, iseqv := ⟨ λe, (@local_equiv.eq_on_source_setoid α β).iseqv.1 e.to_local_equiv, λe e' h, (@local_equiv.eq_on_source_setoid α β).iseqv.2.1 ((eq_on_source_iff e e').1 h), λe e' e'' h h', (@local_equiv.eq_on_source_setoid α β).iseqv.2.2 ((eq_on_source_iff e e').1 h) ((eq_on_source_iff e' e'').1 h')⟩ } lemma eq_on_source_refl : e ≈ e := setoid.refl _ /-- If two local homeomorphisms are equivalent, so are their inverses -/ lemma eq_on_source.symm' {e e' : local_homeomorph α β} (h : e ≈ e') : e.symm ≈ e'.symm := local_equiv.eq_on_source.symm' h /-- Two equivalent local homeomorphisms have the same source -/ lemma eq_on_source.source_eq {e e' : local_homeomorph α β} (h : e ≈ e') : e.source = e'.source := h.1 /-- Two equivalent local homeomorphisms have the same target -/ lemma eq_on_source.target_eq {e e' : local_homeomorph α β} (h : e ≈ e') : e.target = e'.target := h.symm'.1 /-- Two equivalent local homeomorphisms have coinciding `to_fun` on the source -/ lemma eq_on_source.eq_on {e e' : local_homeomorph α β} (h : e ≈ e') : eq_on e e' e.source := h.2 /-- Two equivalent local homeomorphisms have coinciding `inv_fun` on the target -/ lemma eq_on_source.symm_eq_on_target {e e' : local_homeomorph α β} (h : e ≈ e') : eq_on e.symm e'.symm e.target := h.symm'.2 /-- Composition of local homeomorphisms respects equivalence -/ lemma eq_on_source.trans' {e e' : local_homeomorph α β} {f f' : local_homeomorph β γ} (he : e ≈ e') (hf : f ≈ f') : e.trans f ≈ e'.trans f' := local_equiv.eq_on_source.trans' he hf /-- Restriction of local homeomorphisms respects equivalence -/ lemma eq_on_source.restr {e e' : local_homeomorph α β} (he : e ≈ e') (s : set α) : e.restr s ≈ e'.restr s := local_equiv.eq_on_source.restr he _ /-- Composition of a local homeomorphism and its inverse is equivalent to the restriction of the identity to the source -/ lemma trans_self_symm : e.trans e.symm ≈ local_homeomorph.of_set e.source e.open_source := local_equiv.trans_self_symm _ lemma trans_symm_self : e.symm.trans e ≈ local_homeomorph.of_set e.target e.open_target := e.symm.trans_self_symm lemma eq_of_eq_on_source_univ {e e' : local_homeomorph α β} (h : e ≈ e') (s : e.source = univ) (t : e.target = univ) : e = e' := eq_of_local_equiv_eq $ local_equiv.eq_of_eq_on_source_univ _ _ h s t section prod /-- The product of two local homeomorphisms, as a local homeomorphism on the product space. -/ def prod (e : local_homeomorph α β) (e' : local_homeomorph γ δ) : local_homeomorph (α × γ) (β × δ) := { open_source := is_open_prod e.open_source e'.open_source, open_target := is_open_prod e.open_target e'.open_target, continuous_to_fun := continuous_on.prod (e.continuous_to_fun.comp continuous_fst.continuous_on (prod_subset_preimage_fst _ _)) (e'.continuous_to_fun.comp continuous_snd.continuous_on (prod_subset_preimage_snd _ _)), continuous_inv_fun := continuous_on.prod (e.continuous_inv_fun.comp continuous_fst.continuous_on (prod_subset_preimage_fst _ _)) (e'.continuous_inv_fun.comp continuous_snd.continuous_on (prod_subset_preimage_snd _ _)), ..e.to_local_equiv.prod e'.to_local_equiv } @[simp, mfld_simps] lemma prod_to_local_equiv (e : local_homeomorph α β) (e' : local_homeomorph γ δ) : (e.prod e').to_local_equiv = e.to_local_equiv.prod e'.to_local_equiv := rfl lemma prod_source (e : local_homeomorph α β) (e' : local_homeomorph γ δ) : (e.prod e').source = set.prod e.source e'.source := rfl lemma prod_target (e : local_homeomorph α β) (e' : local_homeomorph γ δ) : (e.prod e').target = set.prod e.target e'.target := rfl @[simp, mfld_simps] lemma prod_coe (e : local_homeomorph α β) (e' : local_homeomorph γ δ) : (e.prod e' : α × γ → β × δ) = λp, (e p.1, e' p.2) := rfl lemma prod_coe_symm (e : local_homeomorph α β) (e' : local_homeomorph γ δ) : ((e.prod e').symm : β × δ → α × γ) = λp, (e.symm p.1, e'.symm p.2) := rfl @[simp, mfld_simps] lemma prod_symm (e : local_homeomorph α β) (e' : local_homeomorph γ δ) : (e.prod e').symm = (e.symm.prod e'.symm) := by ext x; simp [prod_coe_symm] @[simp, mfld_simps] lemma prod_trans {η : Type*} {ε : Type*} [topological_space η] [topological_space ε] (e : local_homeomorph α β) (f : local_homeomorph β γ) (e' : local_homeomorph δ η) (f' : local_homeomorph η ε) : (e.prod e').trans (f.prod f') = (e.trans f).prod (e'.trans f') := by ext x; simp [ext_iff]; tauto end prod section continuity /-- Continuity within a set at a point can be read under right composition with a local homeomorphism, if the point is in its target -/ lemma continuous_within_at_iff_continuous_within_at_comp_right {f : β → γ} {s : set β} {x : β} (h : x ∈ e.target) : continuous_within_at f s x ↔ continuous_within_at (f ∘ e) (e ⁻¹' s) (e.symm x) := begin split, { assume f_cont, have : e (e.symm x) = x := e.right_inv h, rw ← this at f_cont, have : e.source ∈ 𝓝 (e.symm x) := mem_nhds_sets e.open_source (e.map_target h), rw [← continuous_within_at_inter this, inter_comm], exact continuous_within_at.comp f_cont ((e.continuous_at (e.map_target h)).continuous_within_at) (inter_subset_right _ _) }, { assume fe_cont, have : continuous_within_at ((f ∘ e) ∘ e.symm) (s ∩ e.target) x, { apply continuous_within_at.comp fe_cont, apply (e.continuous_at_symm h).continuous_within_at, assume x hx, simp [hx.1, hx.2, e.map_target] }, have : continuous_within_at f (s ∩ e.target) x := continuous_within_at.congr this (λy hy, by simp [hy.2]) (by simp [h]), rwa continuous_within_at_inter at this, exact mem_nhds_sets e.open_target h } end /-- Continuity at a point can be read under right composition with a local homeomorphism, if the point is in its target -/ lemma continuous_at_iff_continuous_at_comp_right {f : β → γ} {x : β} (h : x ∈ e.target) : continuous_at f x ↔ continuous_at (f ∘ e) (e.symm x) := by rw [← continuous_within_at_univ, e.continuous_within_at_iff_continuous_within_at_comp_right h, preimage_univ, continuous_within_at_univ] /-- A function is continuous on a set if and only if its composition with a local homeomorphism on the right is continuous on the corresponding set. -/ lemma continuous_on_iff_continuous_on_comp_right {f : β → γ} {s : set β} (h : s ⊆ e.target) : continuous_on f s ↔ continuous_on (f ∘ e) (e.source ∩ e ⁻¹' s) := begin split, { assume f_cont x hx, have := e.continuous_within_at_iff_continuous_within_at_comp_right (e.map_source hx.1), rw e.left_inv hx.1 at this, have A := f_cont _ hx.2, rw this at A, exact A.mono (inter_subset_right _ _), }, { assume fe_cont x hx, have := e.continuous_within_at_iff_continuous_within_at_comp_right (h hx), rw this, have : e.source ∈ 𝓝 (e.symm x) := mem_nhds_sets e.open_source (e.map_target (h hx)), rw [← continuous_within_at_inter this, inter_comm], exact fe_cont _ (by simp [hx, h hx, e.map_target (h hx)]) } end /-- Continuity within a set at a point can be read under left composition with a local homeomorphism if a neighborhood of the initial point is sent to the source of the local homeomorphism-/ lemma continuous_within_at_iff_continuous_within_at_comp_left {f : γ → α} {s : set γ} {x : γ} (hx : f x ∈ e.source) (h : f ⁻¹' e.source ∈ nhds_within x s) : continuous_within_at f s x ↔ continuous_within_at (e ∘ f) s x := begin rw [← continuous_within_at_inter' h, ← continuous_within_at_inter' h], split, { assume f_cont, have : e.source ∈ 𝓝 (f x) := mem_nhds_sets e.open_source hx, apply continuous_within_at.comp (e.continuous_on (f x) hx) f_cont (inter_subset_right _ _) }, { assume fe_cont, have : continuous_within_at (e.symm ∘ (e ∘ f)) (s ∩ f ⁻¹' e.source) x, { have : continuous_within_at e.symm univ (e (f x)) := (e.continuous_at_symm (e.map_source hx)).continuous_within_at, exact continuous_within_at.comp this fe_cont (subset_univ _) }, exact this.congr (λy hy, by simp [e.left_inv hy.2]) (by simp [e.left_inv hx]) } end /-- Continuity at a point can be read under left composition with a local homeomorphism if a neighborhood of the initial point is sent to the source of the local homeomorphism-/ lemma continuous_at_iff_continuous_at_comp_left {f : γ → α} {x : γ} (h : f ⁻¹' e.source ∈ 𝓝 x) : continuous_at f x ↔ continuous_at (e ∘ f) x := begin have hx : f x ∈ e.source := (mem_of_nhds h : _), have h' : f ⁻¹' e.source ∈ nhds_within x univ, by rwa nhds_within_univ, rw [← continuous_within_at_univ, ← continuous_within_at_univ, e.continuous_within_at_iff_continuous_within_at_comp_left hx h'] end /-- A function is continuous on a set if and only if its composition with a local homeomorphism on the left is continuous on the corresponding set. -/ lemma continuous_on_iff_continuous_on_comp_left {f : γ → α} {s : set γ} (h : s ⊆ f ⁻¹' e.source) : continuous_on f s ↔ continuous_on (e ∘ f) s := begin split, { assume f_cont, exact e.continuous_on.comp f_cont h }, { assume fe_cont, have : continuous_on (e.symm ∘ e ∘ f) s, { apply continuous_on.comp e.continuous_on_symm fe_cont, assume x hx, have : f x ∈ e.source := h hx, simp [this] }, refine continuous_on.congr_mono this (λx hx, _) (subset.refl _), have : f x ∈ e.source := h hx, simp [this] } end end continuity /-- If a local homeomorphism has source and target equal to univ, then it induces a homeomorphism between the whole spaces, expressed in this definition. -/ def to_homeomorph_of_source_eq_univ_target_eq_univ (h : e.source = (univ : set α)) (h' : e.target = univ) : homeomorph α β := { to_fun := e, inv_fun := e.symm, left_inv := λx, e.left_inv $ by { rw h, exact mem_univ _ }, right_inv := λx, e.right_inv $ by { rw h', exact mem_univ _ }, continuous_to_fun := begin rw [continuous_iff_continuous_on_univ], convert e.continuous_to_fun, rw h end, continuous_inv_fun := begin rw [continuous_iff_continuous_on_univ], convert e.continuous_inv_fun, rw h' end } @[simp, mfld_simps] lemma to_homeomorph_coe (h : e.source = (univ : set α)) (h' : e.target = univ) : (e.to_homeomorph_of_source_eq_univ_target_eq_univ h h' : α → β) = e := rfl @[simp, mfld_simps] lemma to_homeomorph_symm_coe (h : e.source = (univ : set α)) (h' : e.target = univ) : ((e.to_homeomorph_of_source_eq_univ_target_eq_univ h h').symm : β → α) = e.symm := rfl /-- A local homeomorphism whose source is all of `α` defines an open embedding of `α` into `β`. The converse is also true; see `open_embedding.to_local_homeomorph`. -/ lemma to_open_embedding (h : e.source = set.univ) : open_embedding e.to_fun := begin apply open_embedding_of_continuous_injective_open, { apply continuous_iff_continuous_on_univ.mpr, rw ← h, exact e.continuous_to_fun }, { apply set.injective_iff_inj_on_univ.mpr, rw ← h, exact e.to_local_equiv.bij_on_source.inj_on }, { intros U hU, simpa only [h, subset_univ] with mfld_simps using e.image_open_of_open hU} end end local_homeomorph namespace homeomorph variables (e : homeomorph α β) (e' : homeomorph β γ) /- Register as simp lemmas that the fields of a local homeomorphism built from a homeomorphism correspond to the fields of the original homeomorphism. -/ @[simp, mfld_simps] lemma to_local_homeomorph_source : e.to_local_homeomorph.source = univ := rfl @[simp, mfld_simps] lemma to_local_homeomorph_target : e.to_local_homeomorph.target = univ := rfl @[simp, mfld_simps] lemma to_local_homeomorph_coe : (e.to_local_homeomorph : α → β) = e := rfl @[simp, mfld_simps] lemma to_local_homeomorph_coe_symm : (e.to_local_homeomorph.symm : β → α) = e.symm := rfl @[simp, mfld_simps] lemma refl_to_local_homeomorph : (homeomorph.refl α).to_local_homeomorph = local_homeomorph.refl α := rfl @[simp, mfld_simps] lemma symm_to_local_homeomorph : e.symm.to_local_homeomorph = e.to_local_homeomorph.symm := rfl @[simp, mfld_simps] lemma trans_to_local_homeomorph : (e.trans e').to_local_homeomorph = e.to_local_homeomorph.trans e'.to_local_homeomorph := local_homeomorph.eq_of_local_equiv_eq $ equiv.trans_to_local_equiv _ _ end homeomorph namespace open_embedding variables [nonempty α] variables {f : α → β} (h : open_embedding f) include f h /-- An open embedding of `α` into `β`, with `α` nonempty, defines a local equivalence whose source is all of `α`. This is mainly an auxiliary lemma for the stronger result `to_local_homeomorph`. -/ noncomputable def to_local_equiv : local_equiv α β := set.inj_on.to_local_equiv f set.univ (set.injective_iff_inj_on_univ.mp h.to_embedding.inj) @[simp, mfld_simps] lemma to_local_equiv_coe : (h.to_local_equiv : α → β) = f := rfl @[simp, mfld_simps] lemma to_local_equiv_source : h.to_local_equiv.source = set.univ := rfl @[simp, mfld_simps] lemma to_local_equiv_target : h.to_local_equiv.target = set.range f := begin rw ←local_equiv.image_source_eq_target, ext, split, { exact λ ⟨a, _, h'⟩, ⟨a, h'⟩ }, { exact λ ⟨a, h'⟩, ⟨a, by trivial, h'⟩ } end lemma open_target : is_open h.to_local_equiv.target := by simpa only with mfld_simps using h.open_range lemma continuous_inv_fun : continuous_on h.to_local_equiv.inv_fun h.to_local_equiv.target := begin apply (continuous_on_open_iff h.open_target).mpr, intros t ht, simp only with mfld_simps, convert h.open_iff_image_open.mp ht, ext y, have hinv : ∀ x : α, (f x = y) → h.to_local_equiv.symm y = x := λ x hxy, by { simpa only [hxy.symm] with mfld_simps using h.to_local_equiv.left_inv }, simp only [mem_image, mem_range] with mfld_simps, split, { rintros ⟨⟨x, hxy⟩, hy⟩, refine ⟨x, _, hxy⟩, rwa (hinv x hxy) at hy }, { rintros ⟨x, hx, hxy⟩, refine ⟨⟨x, hxy⟩, _⟩, rwa ← (hinv x hxy) at hx } end /-- An open embedding of `α` into `β`, with `α` nonempty, defines a local homeomorphism whose source is all of `α`. The converse is also true; see `local_homeomorph.to_open_embedding`. -/ noncomputable def to_local_homeomorph : local_homeomorph α β := { to_local_equiv := h.to_local_equiv, open_source := is_open_univ, open_target := h.open_target, continuous_to_fun := by simpa only with mfld_simps using h.continuous.continuous_on, continuous_inv_fun := h.continuous_inv_fun } @[simp, mfld_simps] lemma to_local_homeomorph_coe : (h.to_local_homeomorph : α → β) = f := rfl @[simp, mfld_simps] lemma source : h.to_local_homeomorph.source = set.univ := rfl @[simp, mfld_simps] lemma target : h.to_local_homeomorph.target = set.range f := h.to_local_equiv_target end open_embedding namespace topological_space.opens open topological_space variables (s : opens α) [nonempty s] /-- The inclusion of an open subset `s` of a space `α` into `α` is a local homeomorphism from the subtype `s` to `α`. -/ noncomputable def local_homeomorph_subtype_coe : local_homeomorph s α := open_embedding.to_local_homeomorph (s.2.open_embedding_subtype_coe) @[simp, mfld_simps] lemma local_homeomorph_subtype_coe_coe : (s.local_homeomorph_subtype_coe : s → α) = coe := rfl @[simp, mfld_simps] lemma local_homeomorph_subtype_coe_source : s.local_homeomorph_subtype_coe.source = set.univ := rfl @[simp, mfld_simps] lemma local_homeomorph_subtype_coe_target : s.local_homeomorph_subtype_coe.target = s := by { simp only [local_homeomorph_subtype_coe, subtype.range_coe_subtype] with mfld_simps, refl } end topological_space.opens namespace local_homeomorph open topological_space variables (e : local_homeomorph α β) variables (s : opens α) [nonempty s] /-- The restriction of a local homeomorphism `e` to an open subset `s` of the domain type produces a local homeomorphism whose domain is the subtype `s`.-/ noncomputable def subtype_restr : local_homeomorph s β := s.local_homeomorph_subtype_coe.trans e lemma subtype_restr_def : e.subtype_restr s = s.local_homeomorph_subtype_coe.trans e := rfl @[simp, mfld_simps] lemma subtype_restr_coe : ((e.subtype_restr s : local_homeomorph s β) : s → β) = set.restrict (e : α → β) s := rfl @[simp, mfld_simps] lemma subtype_restr_source : (e.subtype_restr s).source = coe ⁻¹' e.source := by simp only [subtype_restr_def] with mfld_simps /- This lemma characterizes the transition functions of an open subset in terms of the transition functions of the original space. -/ lemma subtype_restr_symm_trans_subtype_restr (f f' : local_homeomorph α β) : (f.subtype_restr s).symm.trans (f'.subtype_restr s) ≈ (f.symm.trans f').restr (f.target ∩ (f.symm) ⁻¹' s) := begin simp only [subtype_restr_def, trans_symm_eq_symm_trans_symm], have openness₁ : is_open (f.target ∩ f.symm ⁻¹' s) := f.preimage_open_of_open_symm s.2, rw [← of_set_trans _ openness₁, ← trans_assoc, ← trans_assoc], refine eq_on_source.trans' _ (eq_on_source_refl _), -- f' has been eliminated !!! have sets_identity : f.symm.source ∩ (f.target ∩ (f.symm) ⁻¹' s) = f.symm.source ∩ f.symm ⁻¹' s, { mfld_set_tac }, have openness₂ : is_open (s : set α) := s.2, rw [of_set_trans', sets_identity, ← trans_of_set' _ openness₂, trans_assoc], refine eq_on_source.trans' (eq_on_source_refl _) _, -- f has been eliminated !!! refine setoid.trans (trans_symm_self s.local_homeomorph_subtype_coe) _, simp only with mfld_simps, end end local_homeomorph
7d4a21e8676b8afeed31cb9e65bc7e3f4b53f141
4727251e0cd73359b15b664c3170e5d754078599
/src/topology/discrete_quotient.lean
f7b952645ee47fe02802b7f2b0c6829b1bd466b1
[ "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
14,300
lean
/- Copyright (c) 2021 Adam Topaz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Calle Sönne, Adam Topaz -/ import topology.separation import topology.subset_properties import topology.locally_constant.basic /-! # Discrete quotients of a topological space. This file defines the type of discrete quotients of a topological space, denoted `discrete_quotient X`. To avoid quantifying over types, we model such quotients as setoids whose equivalence classes are clopen. ## Definitions 1. `discrete_quotient X` is the type of discrete quotients of `X`. It is endowed with a coercion to `Type`, which is defined as the quotient associated to the setoid in question, and each such quotient is endowed with the discrete topology. 2. Given `S : discrete_quotient X`, the projection `X → S` is denoted `S.proj`. 3. When `X` is compact and `S : discrete_quotient X`, the space `S` is endowed with a `fintype` instance. ## Order structure The type `discrete_quotient X` is endowed with an instance of a `semilattice_inf` with `order_top`. The partial ordering `A ≤ B` mathematically means that `B.proj` factors through `A.proj`. The top element `⊤` is the trivial quotient, meaning that every element of `X` is collapsed to a point. Given `h : A ≤ B`, the map `A → B` is `discrete_quotient.of_le h`. Whenever `X` is discrete, the type `discrete_quotient X` is also endowed with an instance of a `semilattice_inf` with `order_bot`, where the bot element `⊥` is `X` itself. Given `f : X → Y` and `h : continuous f`, we define a predicate `le_comap h A B` for `A : discrete_quotient X` and `B : discrete_quotient Y`, asserting that `f` descends to `A → B`. If `cond : le_comap h A B`, the function `A → B` is obtained by `discrete_quotient.map cond`. ## Theorems The two main results proved in this file are: 1. `discrete_quotient.eq_of_proj_eq` which states that when `X` is compact, t2 and totally disconnected, any two elements of `X` agree if their projections in `Q` agree for all `Q : discrete_quotient X`. 2. `discrete_quotient.exists_of_compat` which states that when `X` is compact, then any system of elements of `Q` as `Q : discrete_quotient X` varies, which is compatible with respect to `discrete_quotient.of_le`, must arise from some element of `X`. ## Remarks The constructions in this file will be used to show that any profinite space is a limit of finite discrete spaces. -/ variables (X : Type*) [topological_space X] /-- The type of discrete quotients of a topological space. -/ @[ext] structure discrete_quotient := (rel : X → X → Prop) (equiv : equivalence rel) (clopen : ∀ x, is_clopen (set_of (rel x))) namespace discrete_quotient variables {X} (S : discrete_quotient X) /-- Construct a discrete quotient from a clopen set. -/ def of_clopen {A : set X} (h : is_clopen A) : discrete_quotient X := { rel := λ x y, x ∈ A ∧ y ∈ A ∨ x ∉ A ∧ y ∉ A, equiv := ⟨by tauto!, by tauto!, by tauto!⟩, clopen := begin intros x, by_cases hx : x ∈ A, { apply is_clopen.union, { convert h, ext, exact ⟨λ i, i.2, λ i, ⟨hx,i⟩⟩ }, { convert is_clopen_empty, tidy } }, { apply is_clopen.union, { convert is_clopen_empty, tidy }, { convert is_clopen.compl h, ext, exact ⟨λ i, i.2, λ i, ⟨hx, i⟩⟩ } }, end } lemma refl : ∀ x : X, S.rel x x := S.equiv.1 lemma symm : ∀ x y : X, S.rel x y → S.rel y x := S.equiv.2.1 lemma trans : ∀ x y z : X, S.rel x y → S.rel y z → S.rel x z := S.equiv.2.2 /-- The setoid whose quotient yields the discrete quotient. -/ def setoid : setoid X := ⟨S.rel, S.equiv⟩ instance : has_coe_to_sort (discrete_quotient X) Type* := ⟨λ S, quotient S.setoid⟩ instance : topological_space S := ⊥ /-- The projection from `X` to the given discrete quotient. -/ def proj : X → S := quotient.mk' lemma proj_surjective : function.surjective S.proj := quotient.surjective_quotient_mk' lemma fiber_eq (x : X) : S.proj ⁻¹' {S.proj x} = set_of (S.rel x) := begin ext1 y, simp only [set.mem_preimage, set.mem_singleton_iff, quotient.eq', discrete_quotient.proj.equations._eqn_1, set.mem_set_of_eq], exact ⟨λ h, S.symm _ _ h, λ h, S.symm _ _ h⟩, end lemma proj_is_locally_constant : is_locally_constant S.proj := begin rw (is_locally_constant.tfae S.proj).out 0 3, intros x, rcases S.proj_surjective x with ⟨x,rfl⟩, simp [fiber_eq, (S.clopen x).1], end lemma proj_continuous : continuous S.proj := is_locally_constant.continuous $ proj_is_locally_constant _ lemma fiber_closed (A : set S) : is_closed (S.proj ⁻¹' A) := is_closed.preimage S.proj_continuous ⟨trivial⟩ lemma fiber_open (A : set S) : is_open (S.proj ⁻¹' A) := is_open.preimage S.proj_continuous trivial lemma fiber_clopen (A : set S) : is_clopen (S.proj ⁻¹' A) := ⟨fiber_open _ _, fiber_closed _ _⟩ instance : partial_order (discrete_quotient X) := { le := λ A B, ∀ x y : X, A.rel x y → B.rel x y, le_refl := λ a, by tauto, le_trans := λ a b c h1 h2, by tauto, le_antisymm := λ a b h1 h2, by { ext, tauto } } instance : order_top (discrete_quotient X) := { top := ⟨λ a b, true, ⟨by tauto, by tauto, by tauto⟩, λ _, is_clopen_univ⟩, le_top := λ a, by tauto } instance : semilattice_inf (discrete_quotient X) := { inf := λ A B, { rel := λ x y, A.rel x y ∧ B.rel x y, equiv := ⟨λ a, ⟨A.refl _,B.refl _⟩, λ a b h, ⟨A.symm _ _ h.1, B.symm _ _ h.2⟩, λ a b c h1 h2, ⟨A.trans _ _ _ h1.1 h2.1, B.trans _ _ _ h1.2 h2.2⟩⟩, clopen := λ x, is_clopen.inter (A.clopen _) (B.clopen _) }, inf_le_left := λ a b, by tauto, inf_le_right := λ a b, by tauto, le_inf := λ a b c h1 h2, by tauto, ..discrete_quotient.partial_order } instance : inhabited (discrete_quotient X) := ⟨⊤⟩ section comap variables {Y : Type*} [topological_space Y] {f : Y → X} (cont : continuous f) /-- Comap a discrete quotient along a continuous map. -/ def comap : discrete_quotient Y := { rel := λ a b, S.rel (f a) (f b), equiv := ⟨λ a, S.refl _, λ a b h, S.symm _ _ h, λ a b c h1 h2, S.trans _ _ _ h1 h2⟩, clopen := λ y, ⟨is_open.preimage cont (S.clopen _).1, is_closed.preimage cont (S.clopen _).2⟩ } @[simp] lemma comap_id : S.comap (continuous_id : continuous (id : X → X)) = S := by { ext, refl } @[simp] lemma comap_comp {Z : Type*} [topological_space Z] {g : Z → Y} (cont' : continuous g) : S.comap (continuous.comp cont cont') = (S.comap cont).comap cont' := by { ext, refl } lemma comap_mono {A B : discrete_quotient X} (h : A ≤ B) : A.comap cont ≤ B.comap cont := by tauto end comap section of_le /-- The map induced by a refinement of a discrete quotient. -/ def of_le {A B : discrete_quotient X} (h : A ≤ B) : A → B := λ a, quotient.lift_on' a (λ x, B.proj x) (λ a b i, quotient.sound' (h _ _ i)) @[simp] lemma of_le_refl {A : discrete_quotient X} : of_le (le_refl A) = id := by { ext ⟨⟩, refl } lemma of_le_refl_apply {A : discrete_quotient X} (a : A) : of_le (le_refl A) a = a := by simp @[simp] lemma of_le_comp {A B C : discrete_quotient X} (h1 : A ≤ B) (h2 : B ≤ C) : of_le (le_trans h1 h2) = of_le h2 ∘ of_le h1 := by { ext ⟨⟩, refl } lemma of_le_comp_apply {A B C : discrete_quotient X} (h1 : A ≤ B) (h2 : B ≤ C) (a : A) : of_le (le_trans h1 h2) a = of_le h2 (of_le h1 a) := by simp lemma of_le_continuous {A B : discrete_quotient X} (h : A ≤ B) : continuous (of_le h) := continuous_of_discrete_topology @[simp] lemma of_le_proj {A B : discrete_quotient X} (h : A ≤ B) : of_le h ∘ A.proj = B.proj := by { ext, exact quotient.sound' (B.refl _) } @[simp] lemma of_le_proj_apply {A B : discrete_quotient X} (h : A ≤ B) (x : X) : of_le h (A.proj x) = B.proj x := by { change (of_le h ∘ A.proj) x = _, simp } end of_le /-- When X is discrete, there is a `order_bot` instance on `discrete_quotient X` -/ instance [discrete_topology X] : order_bot (discrete_quotient X) := { bot := { rel := (=), equiv := eq_equivalence, clopen := λ x, is_clopen_discrete _ }, bot_le := by { rintro S a b (h : a = b), rw h, exact S.refl _ } } lemma proj_bot_injective [discrete_topology X] : function.injective (⊥ : discrete_quotient X).proj := λ a b h, quotient.exact' h lemma proj_bot_bijective [discrete_topology X] : function.bijective (⊥ : discrete_quotient X).proj := ⟨proj_bot_injective, proj_surjective _⟩ section map variables {Y : Type*} [topological_space Y] {f : Y → X} (cont : continuous f) (A : discrete_quotient Y) (B : discrete_quotient X) /-- Given `cont : continuous f`, `le_comap cont A B` is defined as `A ≤ B.comap f`. Mathematically this means that `f` descends to a morphism `A → B`. -/ def le_comap : Prop := A ≤ B.comap cont variables {cont A B} lemma le_comap_id (A : discrete_quotient X) : le_comap continuous_id A A := by tauto lemma le_comap_comp {Z : Type*} [topological_space Z] {g : Z → Y} {cont' : continuous g} {C : discrete_quotient Z} : le_comap cont' C A → le_comap cont A B → le_comap (continuous.comp cont cont') C B := by tauto lemma le_comap_trans {C : discrete_quotient X} : le_comap cont A B → B ≤ C → le_comap cont A C := λ h1 h2, le_trans h1 $ comap_mono _ h2 /-- Map a discrete quotient along a continuous map. -/ def map (cond : le_comap cont A B) : A → B := quotient.map' f cond lemma map_continuous (cond : le_comap cont A B) : continuous (map cond) := continuous_of_discrete_topology @[simp] lemma map_proj (cond : le_comap cont A B) : map cond ∘ A.proj = B.proj ∘ f := rfl @[simp] lemma map_proj_apply (cond : le_comap cont A B) (y : Y) : map cond (A.proj y) = B.proj (f y) := rfl @[simp] lemma map_id : map (le_comap_id A) = id := by { ext ⟨⟩, refl } @[simp] lemma map_comp {Z : Type*} [topological_space Z] {g : Z → Y} {cont' : continuous g} {C : discrete_quotient Z} (h1 : le_comap cont' C A) (h2 : le_comap cont A B) : map (le_comap_comp h1 h2) = map h2 ∘ map h1 := by { ext ⟨⟩, refl } @[simp] lemma of_le_map {C : discrete_quotient X} (cond : le_comap cont A B) (h : B ≤ C) : map (le_comap_trans cond h) = of_le h ∘ map cond := by { ext ⟨⟩, refl } @[simp] lemma of_le_map_apply {C : discrete_quotient X} (cond : le_comap cont A B) (h : B ≤ C) (a : A) : map (le_comap_trans cond h) a = of_le h (map cond a) := by { rcases a, refl } @[simp] lemma map_of_le {C : discrete_quotient Y} (cond : le_comap cont A B) (h : C ≤ A) : map (le_trans h cond) = map cond ∘ of_le h := by { ext ⟨⟩, refl } @[simp] lemma map_of_le_apply {C : discrete_quotient Y} (cond : le_comap cont A B) (h : C ≤ A) (c : C) : map (le_trans h cond) c = map cond (of_le h c) := by { rcases c, refl } end map lemma eq_of_proj_eq [t2_space X] [compact_space X] [disc : totally_disconnected_space X] {x y : X} : (∀ Q : discrete_quotient X, Q.proj x = Q.proj y) → x = y := begin intro h, change x ∈ ({y} : set X), rw totally_disconnected_space_iff_connected_component_singleton at disc, rw [← disc y, connected_component_eq_Inter_clopen], rintros U ⟨⟨U, hU1, hU2⟩, rfl⟩, replace h : _ ∨ _ := quotient.exact' (h (of_clopen hU1)), tauto, end lemma fiber_le_of_le {A B : discrete_quotient X} (h : A ≤ B) (a : A) : A.proj ⁻¹' {a} ≤ B.proj ⁻¹' {of_le h a} := begin induction a, erw [fiber_eq, fiber_eq], tidy, end lemma exists_of_compat [compact_space X] (Qs : Π (Q : discrete_quotient X), Q) (compat : ∀ (A B : discrete_quotient X) (h : A ≤ B), of_le h (Qs _) = Qs _) : ∃ x : X, ∀ Q : discrete_quotient X, Q.proj x = Qs _ := begin obtain ⟨x,hx⟩ := is_compact.nonempty_Inter_of_directed_nonempty_compact_closed (λ (Q : discrete_quotient X), Q.proj ⁻¹' {Qs _}) (λ A B, _) (λ i, _) (λ i, (fiber_closed _ _).is_compact) (λ i, fiber_closed _ _), { refine ⟨x, λ Q, _⟩, specialize hx _ ⟨Q,rfl⟩, dsimp at hx, rcases proj_surjective _ (Qs Q) with ⟨y,hy⟩, rw ← hy at *, rw fiber_eq at hx, exact quotient.sound' (Q.symm y x hx) }, { refine ⟨A ⊓ B, λ a ha, _, λ a ha, _⟩, { dsimp only, erw ← compat (A ⊓ B) A inf_le_left, exact fiber_le_of_le _ _ ha }, { dsimp only, erw ← compat (A ⊓ B) B inf_le_right, exact fiber_le_of_le _ _ ha } }, { obtain ⟨x,hx⟩ := i.proj_surjective (Qs i), refine ⟨x,_⟩, dsimp only, rw [← hx, fiber_eq], apply i.refl }, end noncomputable instance [compact_space X] : fintype S := begin have cond : is_compact (⊤ : set X) := compact_univ, rw is_compact_iff_finite_subcover at cond, have h := @cond S (λ s, S.proj ⁻¹' {s}) (λ s, fiber_open _ _) (λ x hx, ⟨S.proj ⁻¹' {S.proj x}, ⟨S.proj x, rfl⟩, rfl⟩), let T := classical.some h, have hT := classical.some_spec h, refine ⟨T,λ s, _⟩, rcases S.proj_surjective s with ⟨x,rfl⟩, rcases hT (by tauto : x ∈ ⊤) with ⟨j, ⟨j,rfl⟩, h1, ⟨hj, rfl⟩, h2⟩, dsimp only at h2, suffices : S.proj x = j, by rwa this, rcases j with ⟨j⟩, apply quotient.sound', erw fiber_eq at h2, exact S.symm _ _ h2 end end discrete_quotient namespace locally_constant variables {X} {α : Type*} (f : locally_constant X α) /-- Any locally constant function induces a discrete quotient. -/ def discrete_quotient : discrete_quotient X := { rel := λ a b, f b = f a, equiv := ⟨by tauto, by tauto, λ a b c h1 h2, by rw [h2, h1]⟩, clopen := λ x, f.is_locally_constant.is_clopen_fiber _ } /-- The function from the discrete quotient associated to a locally constant function. -/ def lift : f.discrete_quotient → α := λ a, quotient.lift_on' a f (λ a b h, h.symm) lemma lift_is_locally_constant : _root_.is_locally_constant f.lift := λ A, trivial /-- A locally constant version of `locally_constant.lift`. -/ def locally_constant_lift : locally_constant f.discrete_quotient α := ⟨f.lift, f.lift_is_locally_constant⟩ @[simp] lemma lift_eq_coe : f.lift = f.locally_constant_lift := rfl @[simp] lemma factors : f.locally_constant_lift ∘ f.discrete_quotient.proj = f := by { ext, refl } end locally_constant
8c155b4ccc59da3d425861a2c644423a97b6c88d
206422fb9edabf63def0ed2aa3f489150fb09ccb
/src/data/dfinsupp.lean
f4c16ed67d2cb13bebba1c0e9973a056e65788eb
[ "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
40,666
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Kenny Lau -/ import algebra.module.pi import algebra.big_operators.basic import data.set.finite import group_theory.submonoid.basic /-! # Dependent functions with finite support For a non-dependent version see `data/finsupp.lean`. -/ universes u u₁ u₂ v v₁ v₂ v₃ w x y l open_locale big_operators variables (ι : Type u) (β : ι → Type v) namespace dfinsupp variable [Π i, has_zero (β i)] structure pre : Type (max u v) := (to_fun : Π i, β i) (pre_support : multiset ι) (zero : ∀ i, i ∈ pre_support ∨ to_fun i = 0) instance inhabited_pre : inhabited (pre ι β) := ⟨⟨λ i, 0, ∅, λ i, or.inr rfl⟩⟩ instance : setoid (pre ι β) := { r := λ x y, ∀ i, x.to_fun i = y.to_fun i, iseqv := ⟨λ f i, rfl, λ f g H i, (H i).symm, λ f g h H1 H2 i, (H1 i).trans (H2 i)⟩ } end dfinsupp variable {ι} /-- A dependent function `Π i, β i` with finite support. -/ @[reducible] def dfinsupp [Π i, has_zero (β i)] : Type* := quotient (dfinsupp.pre.setoid ι β) variable {β} notation `Π₀` binders `, ` r:(scoped f, dfinsupp f) := r infix ` →ₚ `:25 := dfinsupp namespace dfinsupp section basic variables [Π i, has_zero (β i)] variables {β₁ : ι → Type v₁} {β₂ : ι → Type v₂} variables [Π i, has_zero (β₁ i)] [Π i, has_zero (β₂ i)] instance : has_coe_to_fun (Π₀ i, β i) := ⟨λ _, Π i, β i, λ f, quotient.lift_on f pre.to_fun $ λ _ _, funext⟩ instance : has_zero (Π₀ i, β i) := ⟨⟦⟨λ i, 0, ∅, λ i, or.inr rfl⟩⟧⟩ instance : inhabited (Π₀ i, β i) := ⟨0⟩ @[simp] lemma zero_apply (i : ι) : (0 : Π₀ i, β i) i = 0 := rfl @[ext] lemma ext {f g : Π₀ i, β i} (H : ∀ i, f i = g i) : f = g := quotient.induction_on₂ f g (λ _ _ H, quotient.sound H) H /-- The composition of `f : β₁ → β₂` and `g : Π₀ i, β₁ i` is `map_range f hf g : Π₀ i, β₂ i`, well defined when `f 0 = 0`. -/ def map_range (f : Π i, β₁ i → β₂ i) (hf : ∀ i, f i 0 = 0) (g : Π₀ i, β₁ i) : Π₀ i, β₂ i := quotient.lift_on g (λ x, ⟦(⟨λ i, f i (x.1 i), x.2, λ i, or.cases_on (x.3 i) or.inl $ λ H, or.inr $ by rw [H, hf]⟩ : pre ι β₂)⟧) $ λ x y H, quotient.sound $ λ i, by simp only [H i] @[simp] lemma map_range_apply (f : Π i, β₁ i → β₂ i) (hf : ∀ i, f i 0 = 0) (g : Π₀ i, β₁ i) (i : ι) : map_range f hf g i = f i (g i) := quotient.induction_on g $ λ x, rfl /-- Let `f i` be a binary operation `β₁ i → β₂ i → β i` such that `f i 0 0 = 0`. Then `zip_with f hf` is a binary operation `Π₀ i, β₁ i → Π₀ i, β₂ i → Π₀ i, β i`. -/ def zip_with (f : Π i, β₁ i → β₂ i → β i) (hf : ∀ i, f i 0 0 = 0) (g₁ : Π₀ i, β₁ i) (g₂ : Π₀ i, β₂ i) : (Π₀ i, β i) := begin refine quotient.lift_on₂ g₁ g₂ (λ x y, ⟦(⟨λ i, f i (x.1 i) (y.1 i), x.2 + y.2, λ i, _⟩ : pre ι β)⟧) _, { cases x.3 i with h1 h1, { left, rw multiset.mem_add, left, exact h1 }, cases y.3 i with h2 h2, { left, rw multiset.mem_add, right, exact h2 }, right, rw [h1, h2, hf] }, exact λ x₁ x₂ y₁ y₂ H1 H2, quotient.sound $ λ i, by simp only [H1 i, H2 i] end @[simp] lemma zip_with_apply (f : Π i, β₁ i → β₂ i → β i) (hf : ∀ i, f i 0 0 = 0) (g₁ : Π₀ i, β₁ i) (g₂ : Π₀ i, β₂ i) (i : ι) : zip_with f hf g₁ g₂ i = f i (g₁ i) (g₂ i) := quotient.induction_on₂ g₁ g₂ $ λ _ _, rfl end basic section algebra instance [Π i, add_monoid (β i)] : has_add (Π₀ i, β i) := ⟨zip_with (λ _, (+)) (λ _, add_zero 0)⟩ @[simp] lemma add_apply [Π i, add_monoid (β i)] (g₁ g₂ : Π₀ i, β i) (i : ι) : (g₁ + g₂) i = g₁ i + g₂ i := zip_with_apply _ _ g₁ g₂ i instance [Π i, add_monoid (β i)] : add_monoid (Π₀ i, β i) := { add_monoid . zero := 0, add := (+), add_assoc := λ f g h, ext $ λ i, by simp only [add_apply, add_assoc], zero_add := λ f, ext $ λ i, by simp only [add_apply, zero_apply, zero_add], add_zero := λ f, ext $ λ i, by simp only [add_apply, zero_apply, add_zero] } instance is_add_monoid_hom [Π i, add_monoid (β i)] {i : ι} : is_add_monoid_hom (λ g : Π₀ i : ι, β i, g i) := { map_add := λ f g, add_apply f g i, map_zero := zero_apply i } instance [Π i, add_group (β i)] : has_neg (Π₀ i, β i) := ⟨λ f, f.map_range (λ _, has_neg.neg) (λ _, neg_zero)⟩ instance [Π i, add_comm_monoid (β i)] : add_comm_monoid (Π₀ i, β i) := { add_comm := λ f g, ext $ λ i, by simp only [add_apply, add_comm], .. dfinsupp.add_monoid } @[simp] lemma neg_apply [Π i, add_group (β i)] (g : Π₀ i, β i) (i : ι) : (- g) i = - g i := map_range_apply _ _ g i instance [Π i, add_group (β i)] : add_group (Π₀ i, β i) := { add_left_neg := λ f, ext $ λ i, by simp only [add_apply, neg_apply, zero_apply, add_left_neg], .. dfinsupp.add_monoid, .. (infer_instance : has_neg (Π₀ i, β i)) } @[simp] lemma sub_apply [Π i, add_group (β i)] (g₁ g₂ : Π₀ i, β i) (i : ι) : (g₁ - g₂) i = g₁ i - g₂ i := by rw [sub_eq_add_neg]; simp [sub_eq_add_neg] instance [Π i, add_comm_group (β i)] : add_comm_group (Π₀ i, β i) := { add_comm := λ f g, ext $ λ i, by simp only [add_apply, add_comm], ..dfinsupp.add_group } /-- Dependent functions with finite support inherit a semiring action from an action on each coordinate. -/ instance {γ : Type w} [semiring γ] [Π i, add_comm_monoid (β i)] [Π i, semimodule γ (β i)] : has_scalar γ (Π₀ i, β i) := ⟨λc v, v.map_range (λ _, (•) c) (λ _, smul_zero _)⟩ @[simp] lemma smul_apply {γ : Type w} [semiring γ] [Π i, add_comm_monoid (β i)] [Π i, semimodule γ (β i)] (b : γ) (v : Π₀ i, β i) (i : ι) : (b • v) i = b • (v i) := map_range_apply _ _ v i /-- Dependent functions with finite support inherit a semimodule structure from such a structure on each coordinate. -/ instance {γ : Type w} [semiring γ] [Π i, add_comm_monoid (β i)] [Π i, semimodule γ (β i)] : semimodule γ (Π₀ i, β i) := { smul_zero := λ c, ext $ λ i, by simp only [smul_apply, smul_zero, zero_apply], zero_smul := λ c, ext $ λ i, by simp only [smul_apply, zero_smul, zero_apply], smul_add := λ c x y, ext $ λ i, by simp only [add_apply, smul_apply, smul_add], add_smul := λ c x y, ext $ λ i, by simp only [add_apply, smul_apply, add_smul], one_smul := λ x, ext $ λ i, by simp only [smul_apply, one_smul], mul_smul := λ r s x, ext $ λ i, by simp only [smul_apply, smul_smul], .. (infer_instance : has_scalar γ (Π₀ i, β i)) } end algebra section filter_and_subtype_domain /-- `filter p f` is the function which is `f i` if `p i` is true and 0 otherwise. -/ def filter [Π i, has_zero (β i)] (p : ι → Prop) [decidable_pred p] (f : Π₀ i, β i) : Π₀ i, β i := quotient.lift_on f (λ x, ⟦(⟨λ i, if p i then x.1 i else 0, x.2, λ i, or.cases_on (x.3 i) or.inl $ λ H, or.inr $ by rw [H, if_t_t]⟩ : pre ι β)⟧) $ λ x y H, quotient.sound $ λ i, by simp only [H i] @[simp] lemma filter_apply [Π i, has_zero (β i)] (p : ι → Prop) [decidable_pred p] (i : ι) (f : Π₀ i, β i) : f.filter p i = if p i then f i else 0 := quotient.induction_on f $ λ x, rfl lemma filter_apply_pos [Π i, has_zero (β i)] {p : ι → Prop} [decidable_pred p] (f : Π₀ i, β i) {i : ι} (h : p i) : f.filter p i = f i := by simp only [filter_apply, if_pos h] lemma filter_apply_neg [Π i, has_zero (β i)] {p : ι → Prop} [decidable_pred p] (f : Π₀ i, β i) {i : ι} (h : ¬ p i) : f.filter p i = 0 := by simp only [filter_apply, if_neg h] lemma filter_pos_add_filter_neg [Π i, add_monoid (β i)] (f : Π₀ i, β i) (p : ι → Prop) [decidable_pred p] : f.filter p + f.filter (λi, ¬ p i) = f := ext $ λ i, by simp only [add_apply, filter_apply]; split_ifs; simp only [add_zero, zero_add] /-- `subtype_domain p f` is the restriction of the finitely supported function `f` to the subtype `p`. -/ def subtype_domain [Π i, has_zero (β i)] (p : ι → Prop) [decidable_pred p] (f : Π₀ i, β i) : Π₀ i : subtype p, β i := begin fapply quotient.lift_on f, { intro x, refine ⟦⟨λ i, x.1 (i : ι), (x.2.filter p).attach.map $ λ j, ⟨j, (multiset.mem_filter.1 j.2).2⟩, _⟩⟧, refine λ i, or.cases_on (x.3 i) (λ H, _) or.inr, left, rw multiset.mem_map, refine ⟨⟨i, multiset.mem_filter.2 ⟨H, i.2⟩⟩, _, subtype.eta _ _⟩, apply multiset.mem_attach }, intros x y H, exact quotient.sound (λ i, H i) end @[simp] lemma subtype_domain_zero [Π i, has_zero (β i)] {p : ι → Prop} [decidable_pred p] : subtype_domain p (0 : Π₀ i, β i) = 0 := rfl @[simp] lemma subtype_domain_apply [Π i, has_zero (β i)] {p : ι → Prop} [decidable_pred p] {i : subtype p} {v : Π₀ i, β i} : (subtype_domain p v) i = v i := quotient.induction_on v $ λ x, rfl @[simp] lemma subtype_domain_add [Π i, add_monoid (β i)] {p : ι → Prop} [decidable_pred p] {v v' : Π₀ i, β i} : (v + v').subtype_domain p = v.subtype_domain p + v'.subtype_domain p := ext $ λ i, by simp only [add_apply, subtype_domain_apply] instance subtype_domain.is_add_monoid_hom [Π i, add_monoid (β i)] {p : ι → Prop} [decidable_pred p] : is_add_monoid_hom (subtype_domain p : (Π₀ i : ι, β i) → Π₀ i : subtype p, β i) := { map_add := λ _ _, subtype_domain_add, map_zero := subtype_domain_zero } @[simp] lemma subtype_domain_neg [Π i, add_group (β i)] {p : ι → Prop} [decidable_pred p] {v : Π₀ i, β i} : (- v).subtype_domain p = - v.subtype_domain p := ext $ λ i, by simp only [neg_apply, subtype_domain_apply] @[simp] lemma subtype_domain_sub [Π i, add_group (β i)] {p : ι → Prop} [decidable_pred p] {v v' : Π₀ i, β i} : (v - v').subtype_domain p = v.subtype_domain p - v'.subtype_domain p := ext $ λ i, by simp only [sub_apply, subtype_domain_apply] end filter_and_subtype_domain variable [dec : decidable_eq ι] include dec section basic variable [Π i, has_zero (β i)] omit dec lemma finite_supp (f : Π₀ i, β i) : set.finite {i | f i ≠ 0} := begin classical, exact quotient.induction_on f (λ x, x.2.to_finset.finite_to_set.subset (λ i H, multiset.mem_to_finset.2 ((x.3 i).resolve_right H))) end include dec /-- Create an element of `Π₀ i, β i` from a finset `s` and a function `x` defined on this `finset`. -/ def mk (s : finset ι) (x : Π i : (↑s : set ι), β (i : ι)) : Π₀ i, β i := ⟦⟨λ i, if H : i ∈ s then x ⟨i, H⟩ else 0, s.1, λ i, if H : i ∈ s then or.inl H else or.inr $ dif_neg H⟩⟧ @[simp] lemma mk_apply {s : finset ι} {x : Π i : (↑s : set ι), β i} {i : ι} : (mk s x : Π i, β i) i = if H : i ∈ s then x ⟨i, H⟩ else 0 := rfl theorem mk_injective (s : finset ι) : function.injective (@mk ι β _ _ s) := begin intros x y H, ext i, have h1 : (mk s x : Π i, β i) i = (mk s y : Π i, β i) i, {rw H}, cases i with i hi, change i ∈ s at hi, dsimp only [mk_apply, subtype.coe_mk] at h1, simpa only [dif_pos hi] using h1 end /-- The function `single i b : Π₀ i, β i` sends `i` to `b` and all other points to `0`. -/ def single (i : ι) (b : β i) : Π₀ i, β i := mk {i} $ λ j, eq.rec_on (finset.mem_singleton.1 j.prop).symm b @[simp] lemma single_apply {i i' b} : (single i b : Π₀ i, β i) i' = (if h : i = i' then eq.rec_on h b else 0) := begin dsimp only [single], by_cases h : i = i', { have h1 : i' ∈ ({i} : finset ι) := finset.mem_singleton.2 h.symm, simp only [mk_apply, dif_pos h, dif_pos h1], refl }, { have h1 : i' ∉ ({i} : finset ι) := finset.not_mem_singleton.2 (ne.symm h), simp only [mk_apply, dif_neg h, dif_neg h1] } end @[simp] lemma single_zero {i} : (single i 0 : Π₀ i, β i) = 0 := quotient.sound $ λ j, if H : j ∈ ({i} : finset _) then by dsimp only; rw [dif_pos H]; cases finset.mem_singleton.1 H; refl else dif_neg H @[simp] lemma single_eq_same {i b} : (single i b : Π₀ i, β i) i = b := by simp only [single_apply, dif_pos rfl] lemma single_eq_of_ne {i i' b} (h : i ≠ i') : (single i b : Π₀ i, β i) i' = 0 := by simp only [single_apply, dif_neg h] lemma single_injective {i} : function.injective (single i : β i → Π₀ i, β i) := λ x y H, congr_fun (mk_injective _ H) ⟨i, by simp⟩ /-- Like `finsupp.single_eq_single_iff`, but with a `heq` due to dependent types -/ lemma single_eq_single_iff (i j : ι) (xi : β i) (xj : β j) : dfinsupp.single i xi = dfinsupp.single j xj ↔ i = j ∧ xi == xj ∨ xi = 0 ∧ xj = 0 := begin split, { intro h, by_cases hij : i = j, { subst hij, exact or.inl ⟨rfl, heq_of_eq (dfinsupp.single_injective h)⟩, }, { have h_coe : ⇑(dfinsupp.single i xi) = dfinsupp.single j xj := congr_arg coe_fn h, have hci := congr_fun h_coe i, have hcj := congr_fun h_coe j, rw dfinsupp.single_eq_same at hci hcj, rw dfinsupp.single_eq_of_ne (ne.symm hij) at hci, rw dfinsupp.single_eq_of_ne (hij) at hcj, exact or.inr ⟨hci, hcj.symm⟩, }, }, { rintros (⟨hi, hxi⟩ | ⟨hi, hj⟩), { subst hi, rw eq_of_heq hxi, }, { rw [hi, hj, dfinsupp.single_zero, dfinsupp.single_zero], }, }, end /-- Redefine `f i` to be `0`. -/ def erase (i : ι) (f : Π₀ i, β i) : Π₀ i, β i := quotient.lift_on f (λ x, ⟦(⟨λ j, if j = i then 0 else x.1 j, x.2, λ j, or.cases_on (x.3 j) or.inl $ λ H, or.inr $ by simp only [H, if_t_t]⟩ : pre ι β)⟧) $ λ x y H, quotient.sound $ λ j, if h : j = i then by simp only [if_pos h] else by simp only [if_neg h, H j] @[simp] lemma erase_apply {i j : ι} {f : Π₀ i, β i} : (f.erase i) j = if j = i then 0 else f j := quotient.induction_on f $ λ x, rfl @[simp] lemma erase_same {i : ι} {f : Π₀ i, β i} : (f.erase i) i = 0 := by simp lemma erase_ne {i i' : ι} {f : Π₀ i, β i} (h : i' ≠ i) : (f.erase i) i' = f i' := by simp [h] end basic section add_monoid variable [Π i, add_monoid (β i)] @[simp] lemma single_add {i : ι} {b₁ b₂ : β i} : single i (b₁ + b₂) = single i b₁ + single i b₂ := ext $ assume i', begin by_cases h : i = i', { subst h, simp only [add_apply, single_eq_same] }, { simp only [add_apply, single_eq_of_ne h, zero_add] } end variables (β) /-- `dfinsupp.single` as an `add_monoid_hom`. -/ @[simps] def single_add_hom (i : ι) : β i →+ Π₀ i, β i := { to_fun := single i, map_zero' := single_zero, map_add' := λ _ _, single_add } variables {β} lemma single_add_erase {i : ι} {f : Π₀ i, β i} : single i (f i) + f.erase i = f := ext $ λ i', if h : i = i' then by subst h; simp only [add_apply, single_apply, erase_apply, dif_pos rfl, if_pos, add_zero] else by simp only [add_apply, single_apply, erase_apply, dif_neg h, if_neg (ne.symm h), zero_add] lemma erase_add_single {i : ι} {f : Π₀ i, β i} : f.erase i + single i (f i) = f := ext $ λ i', if h : i = i' then by subst h; simp only [add_apply, single_apply, erase_apply, dif_pos rfl, if_pos, zero_add] else by simp only [add_apply, single_apply, erase_apply, dif_neg h, if_neg (ne.symm h), add_zero] protected theorem induction {p : (Π₀ i, β i) → Prop} (f : Π₀ i, β i) (h0 : p 0) (ha : ∀i b (f : Π₀ i, β i), f i = 0 → b ≠ 0 → p f → p (single i b + f)) : p f := begin refine quotient.induction_on f (λ x, _), cases x with f s H, revert f H, apply multiset.induction_on s, { intros f H, convert h0, ext i, exact (H i).resolve_left id }, intros i s ih f H, by_cases H1 : i ∈ s, { have H2 : ∀ j, j ∈ s ∨ f j = 0, { intro j, cases H j with H2 H2, { cases multiset.mem_cons.1 H2 with H3 H3, { left, rw H3, exact H1 }, { left, exact H3 } }, right, exact H2 }, have H3 : (⟦{to_fun := f, pre_support := i ::ₘ s, zero := H}⟧ : Π₀ i, β i) = ⟦{to_fun := f, pre_support := s, zero := H2}⟧, { exact quotient.sound (λ i, rfl) }, rw H3, apply ih }, have H2 : p (erase i ⟦{to_fun := f, pre_support := i ::ₘ s, zero := H}⟧), { dsimp only [erase, quotient.lift_on_beta], have H2 : ∀ j, j ∈ s ∨ ite (j = i) 0 (f j) = 0, { intro j, cases H j with H2 H2, { cases multiset.mem_cons.1 H2 with H3 H3, { right, exact if_pos H3 }, { left, exact H3 } }, right, split_ifs; [refl, exact H2] }, have H3 : (⟦{to_fun := λ (j : ι), ite (j = i) 0 (f j), pre_support := i ::ₘ s, zero := _}⟧ : Π₀ i, β i) = ⟦{to_fun := λ (j : ι), ite (j = i) 0 (f j), pre_support := s, zero := H2}⟧ := quotient.sound (λ i, rfl), rw H3, apply ih }, have H3 : single i _ + _ = (⟦{to_fun := f, pre_support := i ::ₘ s, zero := H}⟧ : Π₀ i, β i) := single_add_erase, rw ← H3, change p (single i (f i) + _), cases classical.em (f i = 0) with h h, { rw [h, single_zero, zero_add], exact H2 }, refine ha _ _ _ _ h H2, rw erase_same end lemma induction₂ {p : (Π₀ i, β i) → Prop} (f : Π₀ i, β i) (h0 : p 0) (ha : ∀i b (f : Π₀ i, β i), f i = 0 → b ≠ 0 → p f → p (f + single i b)) : p f := dfinsupp.induction f h0 $ λ i b f h1 h2 h3, have h4 : f + single i b = single i b + f, { ext j, by_cases H : i = j, { subst H, simp [h1] }, { simp [H] } }, eq.rec_on h4 $ ha i b f h1 h2 h3 @[simp] lemma add_closure_Union_range_single : add_submonoid.closure (⋃ i : ι, set.range (single i : β i → (Π₀ i, β i))) = ⊤ := top_unique $ λ x hx, (begin apply dfinsupp.induction x, exact add_submonoid.zero_mem _, exact λ a b f ha hb hf, add_submonoid.add_mem _ (add_submonoid.subset_closure $ set.mem_Union.2 ⟨a, set.mem_range_self _⟩) hf end) /-- If two additive homomorphisms from `Π₀ i, β i` are equal on each `single a b`, then they are equal. -/ lemma add_hom_ext {γ : Type w} [add_monoid γ] ⦃f g : (Π₀ i, β i) →+ γ⦄ (H : ∀ (i : ι) (y : β i), f (single i y) = g (single i y)) : f = g := begin refine add_monoid_hom.eq_of_eq_on_mdense add_closure_Union_range_single (λ f hf, _), simp only [set.mem_Union, set.mem_range] at hf, rcases hf with ⟨x, y, rfl⟩, apply H end /-- If two additive homomorphisms from `Π₀ i, β i` are equal on each `single a b`, then they are equal. See note [partially-applied ext lemmas]. -/ @[ext] lemma add_hom_ext' {γ : Type w} [add_monoid γ] ⦃f g : (Π₀ i, β i) →+ γ⦄ (H : ∀ x, f.comp (single_add_hom β x) = g.comp (single_add_hom β x)) : f = g := add_hom_ext $ λ x, add_monoid_hom.congr_fun (H x) end add_monoid @[simp] lemma mk_add [Π i, add_monoid (β i)] {s : finset ι} {x y : Π i : (↑s : set ι), β i} : mk s (x + y) = mk s x + mk s y := ext $ λ i, by simp only [add_apply, mk_apply]; split_ifs; [refl, rw zero_add] @[simp] lemma mk_zero [Π i, has_zero (β i)] {s : finset ι} : mk s (0 : Π i : (↑s : set ι), β i.1) = 0 := ext $ λ i, by simp only [mk_apply]; split_ifs; refl @[simp] lemma mk_neg [Π i, add_group (β i)] {s : finset ι} {x : Π i : (↑s : set ι), β i.1} : mk s (-x) = -mk s x := ext $ λ i, by simp only [neg_apply, mk_apply]; split_ifs; [refl, rw neg_zero] @[simp] lemma mk_sub [Π i, add_group (β i)] {s : finset ι} {x y : Π i : (↑s : set ι), β i.1} : mk s (x - y) = mk s x - mk s y := ext $ λ i, by simp only [sub_apply, mk_apply]; split_ifs; [refl, rw sub_zero] instance [Π i, add_group (β i)] {s : finset ι} : is_add_group_hom (@mk ι β _ _ s) := { map_add := λ _ _, mk_add } section variables (γ : Type w) [semiring γ] [Π i, add_comm_monoid (β i)] [Π i, semimodule γ (β i)] include γ @[simp] lemma mk_smul {s : finset ι} {c : γ} (x : Π i : (↑s : set ι), β i.1) : mk s (c • x) = c • mk s x := ext $ λ i, by simp only [smul_apply, mk_apply]; split_ifs; [refl, rw smul_zero] @[simp] lemma single_smul {i : ι} {c : γ} {x : β i} : single i (c • x) = c • single i x := ext $ λ i, by simp only [smul_apply, single_apply]; split_ifs; [cases h, rw smul_zero]; refl end section support_basic variables [Π i, has_zero (β i)] [Π i (x : β i), decidable (x ≠ 0)] /-- Set `{i | f x ≠ 0}` as a `finset`. -/ def support (f : Π₀ i, β i) : finset ι := quotient.lift_on f (λ x, x.2.to_finset.filter $ λ i, x.1 i ≠ 0) $ begin intros x y Hxy, ext i, split, { intro H, rcases finset.mem_filter.1 H with ⟨h1, h2⟩, rw Hxy i at h2, exact finset.mem_filter.2 ⟨multiset.mem_to_finset.2 $ (y.3 i).resolve_right h2, h2⟩ }, { intro H, rcases finset.mem_filter.1 H with ⟨h1, h2⟩, rw ← Hxy i at h2, exact finset.mem_filter.2 ⟨multiset.mem_to_finset.2 $ (x.3 i).resolve_right h2, h2⟩ }, end @[simp] theorem support_mk_subset {s : finset ι} {x : Π i : (↑s : set ι), β i.1} : (mk s x).support ⊆ s := λ i H, multiset.mem_to_finset.1 (finset.mem_filter.1 H).1 @[simp] theorem mem_support_to_fun (f : Π₀ i, β i) (i) : i ∈ f.support ↔ f i ≠ 0 := begin refine quotient.induction_on f (λ x, _), dsimp only [support, quotient.lift_on_beta], rw [finset.mem_filter, multiset.mem_to_finset], exact and_iff_right_of_imp (x.3 i).resolve_right end theorem eq_mk_support (f : Π₀ i, β i) : f = mk f.support (λ i, f i) := begin change f = mk f.support (λ i, f i.1), ext i, by_cases h : f i ≠ 0; [skip, rw [not_not] at h]; simp [h] end @[simp] lemma support_zero : (0 : Π₀ i, β i).support = ∅ := rfl lemma mem_support_iff (f : Π₀ i, β i) : ∀i:ι, i ∈ f.support ↔ f i ≠ 0 := f.mem_support_to_fun @[simp] lemma support_eq_empty {f : Π₀ i, β i} : f.support = ∅ ↔ f = 0 := ⟨λ H, ext $ by simpa [finset.ext_iff] using H, by simp {contextual:=tt}⟩ instance decidable_zero : decidable_pred (eq (0 : Π₀ i, β i)) := λ f, decidable_of_iff _ $ support_eq_empty.trans eq_comm lemma support_subset_iff {s : set ι} {f : Π₀ i, β i} : ↑f.support ⊆ s ↔ (∀i∉s, f i = 0) := by simp [set.subset_def]; exact forall_congr (assume i, not_imp_comm) lemma support_single_ne_zero {i : ι} {b : β i} (hb : b ≠ 0) : (single i b).support = {i} := begin ext j, by_cases h : i = j, { subst h, simp [hb] }, simp [ne.symm h, h] end lemma support_single_subset {i : ι} {b : β i} : (single i b).support ⊆ {i} := support_mk_subset section map_range_and_zip_with variables {β₁ : ι → Type v₁} {β₂ : ι → Type v₂} variables [Π i, has_zero (β₁ i)] [Π i, has_zero (β₂ i)] lemma map_range_def [Π i (x : β₁ i), decidable (x ≠ 0)] {f : Π i, β₁ i → β₂ i} {hf : ∀ i, f i 0 = 0} {g : Π₀ i, β₁ i} : map_range f hf g = mk g.support (λ i, f i.1 (g i.1)) := begin ext i, by_cases h : g i ≠ 0; simp at h; simp [h, hf] end @[simp] lemma map_range_single {f : Π i, β₁ i → β₂ i} {hf : ∀ i, f i 0 = 0} {i : ι} {b : β₁ i} : map_range f hf (single i b) = single i (f i b) := dfinsupp.ext $ λ i', by by_cases i = i'; [{subst i', simp}, simp [h, hf]] variables [Π i (x : β₁ i), decidable (x ≠ 0)] [Π i (x : β₂ i), decidable (x ≠ 0)] lemma support_map_range {f : Π i, β₁ i → β₂ i} {hf : ∀ i, f i 0 = 0} {g : Π₀ i, β₁ i} : (map_range f hf g).support ⊆ g.support := by simp [map_range_def] lemma zip_with_def {f : Π i, β₁ i → β₂ i → β i} {hf : ∀ i, f i 0 0 = 0} {g₁ : Π₀ i, β₁ i} {g₂ : Π₀ i, β₂ i} : zip_with f hf g₁ g₂ = mk (g₁.support ∪ g₂.support) (λ i, f i.1 (g₁ i.1) (g₂ i.1)) := begin ext i, by_cases h1 : g₁ i ≠ 0; by_cases h2 : g₂ i ≠ 0; simp only [not_not, ne.def] at h1 h2; simp [h1, h2, hf] end lemma support_zip_with {f : Π i, β₁ i → β₂ i → β i} {hf : ∀ i, f i 0 0 = 0} {g₁ : Π₀ i, β₁ i} {g₂ : Π₀ i, β₂ i} : (zip_with f hf g₁ g₂).support ⊆ g₁.support ∪ g₂.support := by simp [zip_with_def] end map_range_and_zip_with lemma erase_def (i : ι) (f : Π₀ i, β i) : f.erase i = mk (f.support.erase i) (λ j, f j.1) := by { ext j, by_cases h1 : j = i; by_cases h2 : f j ≠ 0; simp at h2; simp [h1, h2] } @[simp] lemma support_erase (i : ι) (f : Π₀ i, β i) : (f.erase i).support = f.support.erase i := by { ext j, by_cases h1 : j = i; by_cases h2 : f j ≠ 0; simp at h2; simp [h1, h2] } section filter_and_subtype_domain variables {p : ι → Prop} [decidable_pred p] lemma filter_def (f : Π₀ i, β i) : f.filter p = mk (f.support.filter p) (λ i, f i.1) := by ext i; by_cases h1 : p i; by_cases h2 : f i ≠ 0; simp at h2; simp [h1, h2] @[simp] lemma support_filter (f : Π₀ i, β i) : (f.filter p).support = f.support.filter p := by ext i; by_cases h : p i; simp [h] lemma subtype_domain_def (f : Π₀ i, β i) : f.subtype_domain p = mk (f.support.subtype p) (λ i, f i) := by ext i; by_cases h1 : p i; by_cases h2 : f i ≠ 0; try {simp at h2}; dsimp; simp [h1, h2, ← subtype.val_eq_coe] @[simp] lemma support_subtype_domain {f : Π₀ i, β i} : (subtype_domain p f).support = f.support.subtype p := by ext i; by_cases h1 : p i; by_cases h2 : f i ≠ 0; try {simp at h2}; dsimp; simp [h1, h2] end filter_and_subtype_domain end support_basic lemma support_add [Π i, add_monoid (β i)] [Π i (x : β i), decidable (x ≠ 0)] {g₁ g₂ : Π₀ i, β i} : (g₁ + g₂).support ⊆ g₁.support ∪ g₂.support := support_zip_with @[simp] lemma support_neg [Π i, add_group (β i)] [Π i (x : β i), decidable (x ≠ 0)] {f : Π₀ i, β i} : support (-f) = support f := by ext i; simp lemma support_smul {γ : Type w} [semiring γ] [Π i, add_comm_monoid (β i)] [Π i, semimodule γ (β i)] [Π ( i : ι) (x : β i), decidable (x ≠ 0)] (b : γ) (v : Π₀ i, β i) : (b • v).support ⊆ v.support := support_map_range instance [Π i, has_zero (β i)] [Π i, decidable_eq (β i)] : decidable_eq (Π₀ i, β i) := assume f g, decidable_of_iff (f.support = g.support ∧ (∀i∈f.support, f i = g i)) ⟨assume ⟨h₁, h₂⟩, ext $ assume i, if h : i ∈ f.support then h₂ i h else have hf : f i = 0, by rwa [f.mem_support_iff, not_not] at h, have hg : g i = 0, by rwa [h₁, g.mem_support_iff, not_not] at h, by rw [hf, hg], by intro h; subst h; simp⟩ section prod_and_sum variables {γ : Type w} -- [to_additive sum] for dfinsupp.prod doesn't work, the equation lemmas are not generated /-- `sum f g` is the sum of `g i (f i)` over the support of `f`. -/ def sum [Π i, has_zero (β i)] [Π i (x : β i), decidable (x ≠ 0)] [add_comm_monoid γ] (f : Π₀ i, β i) (g : Π i, β i → γ) : γ := ∑ i in f.support, g i (f i) /-- `prod f g` is the product of `g i (f i)` over the support of `f`. -/ @[to_additive] def prod [Π i, has_zero (β i)] [Π i (x : β i), decidable (x ≠ 0)] [comm_monoid γ] (f : Π₀ i, β i) (g : Π i, β i → γ) : γ := ∏ i in f.support, g i (f i) @[to_additive] lemma prod_map_range_index {β₁ : ι → Type v₁} {β₂ : ι → Type v₂} [Π i, has_zero (β₁ i)] [Π i, has_zero (β₂ i)] [Π i (x : β₁ i), decidable (x ≠ 0)] [Π i (x : β₂ i), decidable (x ≠ 0)] [comm_monoid γ] {f : Π i, β₁ i → β₂ i} {hf : ∀ i, f i 0 = 0} {g : Π₀ i, β₁ i} {h : Π i, β₂ i → γ} (h0 : ∀i, h i 0 = 1) : (map_range f hf g).prod h = g.prod (λi b, h i (f i b)) := begin rw [map_range_def], refine (finset.prod_subset support_mk_subset _).trans _, { intros i h1 h2, dsimp, simp [h1] at h2, dsimp at h2, simp [h1, h2, h0] }, { refine finset.prod_congr rfl _, intros i h1, simp [h1] } end @[to_additive] lemma prod_zero_index [Π i, add_comm_monoid (β i)] [Π i (x : β i), decidable (x ≠ 0)] [comm_monoid γ] {h : Π i, β i → γ} : (0 : Π₀ i, β i).prod h = 1 := rfl @[to_additive] lemma prod_single_index [Π i, has_zero (β i)] [Π i (x : β i), decidable (x ≠ 0)] [comm_monoid γ] {i : ι} {b : β i} {h : Π i, β i → γ} (h_zero : h i 0 = 1) : (single i b).prod h = h i b := begin by_cases h : b ≠ 0, { simp [dfinsupp.prod, support_single_ne_zero h] }, { rw [not_not] at h, simp [h, prod_zero_index, h_zero], refl } end @[to_additive] lemma prod_neg_index [Π i, add_group (β i)] [Π i (x : β i), decidable (x ≠ 0)] [comm_monoid γ] {g : Π₀ i, β i} {h : Π i, β i → γ} (h0 : ∀i, h i 0 = 1) : (-g).prod h = g.prod (λi b, h i (- b)) := prod_map_range_index h0 omit dec @[to_additive] lemma prod_comm {ι₁ ι₂ : Sort*} {β₁ : ι₁ → Type*} {β₂ : ι₂ → Type*} [decidable_eq ι₁] [decidable_eq ι₂] [Π i, has_zero (β₁ i)] [Π i, has_zero (β₂ i)] [Π i (x : β₁ i), decidable (x ≠ 0)] [Π i (x : β₂ i), decidable (x ≠ 0)] [comm_monoid γ] (f₁ : Π₀ i, β₁ i) (f₂ : Π₀ i, β₂ i) (h : Π i, β₁ i → Π i, β₂ i → γ) : f₁.prod (λ i₁ x₁, f₂.prod $ λ i₂ x₂, h i₁ x₁ i₂ x₂) = f₂.prod (λ i₂ x₂, f₁.prod $ λ i₁ x₁, h i₁ x₁ i₂ x₂) := finset.prod_comm @[simp] lemma sum_apply {ι₁ : Type u₁} [decidable_eq ι₁] {β₁ : ι₁ → Type v₁} [Π i₁, has_zero (β₁ i₁)] [Π i (x : β₁ i), decidable (x ≠ 0)] [Π i, add_comm_monoid (β i)] {f : Π₀ i₁, β₁ i₁} {g : Π i₁, β₁ i₁ → Π₀ i, β i} {i₂ : ι} : (f.sum g) i₂ = f.sum (λi₁ b, g i₁ b i₂) := (f.support.sum_hom (λf : Π₀ i, β i, f i₂)).symm include dec lemma support_sum {ι₁ : Type u₁} [decidable_eq ι₁] {β₁ : ι₁ → Type v₁} [Π i₁, has_zero (β₁ i₁)] [Π i (x : β₁ i), decidable (x ≠ 0)] [Π i, add_comm_monoid (β i)] [Π i (x : β i), decidable (x ≠ 0)] {f : Π₀ i₁, β₁ i₁} {g : Π i₁, β₁ i₁ → Π₀ i, β i} : (f.sum g).support ⊆ f.support.bUnion (λi, (g i (f i)).support) := have ∀i₁ : ι, f.sum (λ (i : ι₁) (b : β₁ i), (g i b) i₁) ≠ 0 → (∃ (i : ι₁), f i ≠ 0 ∧ ¬ (g i (f i)) i₁ = 0), from assume i₁ h, let ⟨i, hi, ne⟩ := finset.exists_ne_zero_of_sum_ne_zero h in ⟨i, (f.mem_support_iff i).mp hi, ne⟩, by simpa [finset.subset_iff, mem_support_iff, finset.mem_bUnion, sum_apply] using this @[simp, to_additive] lemma prod_one [Π i, add_comm_monoid (β i)] [Π i (x : β i), decidable (x ≠ 0)] [comm_monoid γ] {f : Π₀ i, β i} : f.prod (λi b, (1 : γ)) = 1 := finset.prod_const_one @[simp, to_additive] lemma prod_mul [Π i, add_comm_monoid (β i)] [Π i (x : β i), decidable (x ≠ 0)] [comm_monoid γ] {f : Π₀ i, β i} {h₁ h₂ : Π i, β i → γ} : f.prod (λi b, h₁ i b * h₂ i b) = f.prod h₁ * f.prod h₂ := finset.prod_mul_distrib @[simp, to_additive] lemma prod_inv [Π i, add_comm_monoid (β i)] [Π i (x : β i), decidable (x ≠ 0)] [comm_group γ] {f : Π₀ i, β i} {h : Π i, β i → γ} : f.prod (λi b, (h i b)⁻¹) = (f.prod h)⁻¹ := f.support.prod_hom (@has_inv.inv γ _) @[to_additive] lemma prod_add_index [Π i, add_comm_monoid (β i)] [Π i (x : β i), decidable (x ≠ 0)] [comm_monoid γ] {f g : Π₀ i, β i} {h : Π i, β i → γ} (h_zero : ∀i, h i 0 = 1) (h_add : ∀i b₁ b₂, h i (b₁ + b₂) = h i b₁ * h i b₂) : (f + g).prod h = f.prod h * g.prod h := have f_eq : ∏ i in f.support ∪ g.support, h i (f i) = f.prod h, from (finset.prod_subset (finset.subset_union_left _ _) $ by simp [mem_support_iff, h_zero] {contextual := tt}).symm, have g_eq : ∏ i in f.support ∪ g.support, h i (g i) = g.prod h, from (finset.prod_subset (finset.subset_union_right _ _) $ by simp [mem_support_iff, h_zero] {contextual := tt}).symm, calc ∏ i in (f + g).support, h i ((f + g) i) = ∏ i in f.support ∪ g.support, h i ((f + g) i) : finset.prod_subset support_add $ by simp [mem_support_iff, h_zero] {contextual := tt} ... = (∏ i in f.support ∪ g.support, h i (f i)) * (∏ i in f.support ∪ g.support, h i (g i)) : by simp [h_add, finset.prod_mul_distrib] ... = _ : by rw [f_eq, g_eq] /-- When summing over an `add_monoid_hom`, the decidability assumption is not needed, and the result is also an `add_monoid_hom`. -/ def sum_add_hom [Π i, add_monoid (β i)] [add_comm_monoid γ] (φ : Π i, β i →+ γ) : (Π₀ i, β i) →+ γ := { to_fun := (λ f, quotient.lift_on f (λ x, ∑ i in x.2.to_finset, φ i (x.1 i)) $ λ x y H, begin have H1 : x.2.to_finset ∩ y.2.to_finset ⊆ x.2.to_finset, from finset.inter_subset_left _ _, have H2 : x.2.to_finset ∩ y.2.to_finset ⊆ y.2.to_finset, from finset.inter_subset_right _ _, refine (finset.sum_subset H1 _).symm.trans ((finset.sum_congr rfl _).trans (finset.sum_subset H2 _)), { intros i H1 H2, rw finset.mem_inter at H2, rw H i, simp only [multiset.mem_to_finset] at H1 H2, rw [(y.3 i).resolve_left (mt (and.intro H1) H2), add_monoid_hom.map_zero] }, { intros i H1, rw H i }, { intros i H1 H2, rw finset.mem_inter at H2, rw ← H i, simp only [multiset.mem_to_finset] at H1 H2, rw [(x.3 i).resolve_left (mt (λ H3, and.intro H3 H1) H2), add_monoid_hom.map_zero] } end), map_add' := assume f g, begin refine quotient.induction_on f (λ x, _), refine quotient.induction_on g (λ y, _), change ∑ i in _, _ = (∑ i in _, _) + (∑ i in _, _), simp only, conv { to_lhs, congr, skip, funext, rw add_monoid_hom.map_add }, simp only [finset.sum_add_distrib], congr' 1, { refine (finset.sum_subset _ _).symm, { intro i, simp only [multiset.mem_to_finset, multiset.mem_add], exact or.inl }, { intros i H1 H2, simp only [multiset.mem_to_finset, multiset.mem_add] at H2, rw [(x.3 i).resolve_left H2, add_monoid_hom.map_zero] } }, { refine (finset.sum_subset _ _).symm, { intro i, simp only [multiset.mem_to_finset, multiset.mem_add], exact or.inr }, { intros i H1 H2, simp only [multiset.mem_to_finset, multiset.mem_add] at H2, rw [(y.3 i).resolve_left H2, add_monoid_hom.map_zero] } } end, map_zero' := rfl } @[simp] lemma sum_add_hom_single [Π i, add_monoid (β i)] [add_comm_monoid γ] (φ : Π i, β i →+ γ) (i) (x : β i) : sum_add_hom φ (single i x) = φ i x := (add_zero _).trans $ congr_arg (φ i) $ show (if H : i ∈ ({i} : finset _) then x else 0) = x, from dif_pos $ finset.mem_singleton_self i @[simp] lemma sum_add_hom_comp_single [Π i, add_comm_monoid (β i)] [add_comm_monoid γ] (f : Π i, β i →+ γ) (i : ι) : (sum_add_hom f).comp (single_add_hom β i) = f i := add_monoid_hom.ext $ λ x, sum_add_hom_single f i x /-- While we didn't need decidable instances to define it, we do to reduce it to a sum -/ lemma sum_add_hom_apply [Π i, add_monoid (β i)] [Π i (x : β i), decidable (x ≠ 0)] [add_comm_monoid γ] (φ : Π i, β i →+ γ) (f : Π₀ i, β i) : sum_add_hom φ f = f.sum (λ x, φ x) := begin refine quotient.induction_on f (λ x, _), change ∑ i in _, _ = (∑ i in finset.filter _ _, _), rw [finset.sum_filter, finset.sum_congr rfl], intros i _, dsimp only, split_ifs, refl, rw [(not_not.mp h), add_monoid_hom.map_zero], end /-- The `dfinsupp` version of `finsupp.lift_add_hom`,-/ @[simps apply symm_apply] def lift_add_hom [Π i, add_monoid (β i)] [add_comm_monoid γ] : (Π i, β i →+ γ) ≃+ ((Π₀ i, β i) →+ γ) := { to_fun := sum_add_hom, inv_fun := λ F i, F.comp (single_add_hom β i), left_inv := λ x, by { ext, simp }, right_inv := λ ψ, by { ext, simp }, map_add' := λ F G, by { ext, simp } } /-- The `dfinsupp` version of `finsupp.lift_add_hom_single_add_hom`,-/ @[simp] lemma lift_add_hom_single_add_hom [Π i, add_comm_monoid (β i)] : lift_add_hom (single_add_hom β) = add_monoid_hom.id (Π₀ i, β i) := lift_add_hom.to_equiv.apply_eq_iff_eq_symm_apply.2 rfl /-- The `dfinsupp` version of `finsupp.lift_add_hom_apply_single`,-/ lemma lift_add_hom_apply_single [Π i, add_comm_monoid (β i)] [add_comm_monoid γ] (f : Π i, β i →+ γ) (i : ι) (x : β i) : lift_add_hom f (single i x) = f i x := by simp /-- The `dfinsupp` version of `finsupp.lift_add_hom_comp_single`,-/ lemma lift_add_hom_comp_single [Π i, add_comm_monoid (β i)] [add_comm_monoid γ] (f : Π i, β i →+ γ) (i : ι) : (lift_add_hom f).comp (single_add_hom β i) = f i := by simp /-- The `dfinsupp` version of `finsupp.comp_lift_add_hom`,-/ lemma comp_lift_add_hom {δ : Type*} [Π i, add_comm_monoid (β i)] [add_comm_monoid γ] [add_comm_monoid δ] (g : γ →+ δ) (f : Π i, β i →+ γ) : g.comp (lift_add_hom f) = lift_add_hom (λ a, g.comp (f a)) := lift_add_hom.symm_apply_eq.1 $ funext $ λ a, by rw [lift_add_hom_symm_apply, add_monoid_hom.comp_assoc, lift_add_hom_comp_single] lemma sum_sub_index [Π i, add_comm_group (β i)] [Π i (x : β i), decidable (x ≠ 0)] [add_comm_group γ] {f g : Π₀ i, β i} {h : Π i, β i → γ} (h_sub : ∀i b₁ b₂, h i (b₁ - b₂) = h i b₁ - h i b₂) : (f - g).sum h = f.sum h - g.sum h := begin have := (lift_add_hom (λ a, add_monoid_hom.of_map_sub (h a) (h_sub a))).map_sub f g, rw [lift_add_hom_apply, sum_add_hom_apply, sum_add_hom_apply, sum_add_hom_apply] at this, exact this, end @[to_additive] lemma prod_finset_sum_index {γ : Type w} {α : Type x} [Π i, add_comm_monoid (β i)] [Π i (x : β i), decidable (x ≠ 0)] [comm_monoid γ] {s : finset α} {g : α → Π₀ i, β i} {h : Π i, β i → γ} (h_zero : ∀i, h i 0 = 1) (h_add : ∀i b₁ b₂, h i (b₁ + b₂) = h i b₁ * h i b₂) : ∏ i in s, (g i).prod h = (∑ i in s, g i).prod h := begin classical, exact finset.induction_on s (by simp [prod_zero_index]) (by simp [prod_add_index, h_zero, h_add] {contextual := tt}) end @[to_additive] lemma prod_sum_index {ι₁ : Type u₁} [decidable_eq ι₁] {β₁ : ι₁ → Type v₁} [Π i₁, has_zero (β₁ i₁)] [Π i (x : β₁ i), decidable (x ≠ 0)] [Π i, add_comm_monoid (β i)] [Π i (x : β i), decidable (x ≠ 0)] [comm_monoid γ] {f : Π₀ i₁, β₁ i₁} {g : Π i₁, β₁ i₁ → Π₀ i, β i} {h : Π i, β i → γ} (h_zero : ∀i, h i 0 = 1) (h_add : ∀i b₁ b₂, h i (b₁ + b₂) = h i b₁ * h i b₂) : (f.sum g).prod h = f.prod (λi b, (g i b).prod h) := (prod_finset_sum_index h_zero h_add).symm @[simp] lemma sum_single [Π i, add_comm_monoid (β i)] [Π i (x : β i), decidable (x ≠ 0)] {f : Π₀ i, β i} : f.sum single = f := begin have := add_monoid_hom.congr_fun lift_add_hom_single_add_hom f, rw [lift_add_hom_apply, sum_add_hom_apply] at this, exact this, end @[to_additive] lemma prod_subtype_domain_index [Π i, has_zero (β i)] [Π i (x : β i), decidable (x ≠ 0)] [comm_monoid γ] {v : Π₀ i, β i} {p : ι → Prop} [decidable_pred p] {h : Π i, β i → γ} (hp : ∀ x ∈ v.support, p x) : (v.subtype_domain p).prod (λi b, h i b) = v.prod h := finset.prod_bij (λp _, p) (by simp) (by simp) (assume ⟨a₀, ha₀⟩ ⟨a₁, ha₁⟩, by simp) (λ i hi, ⟨⟨i, hp i hi⟩, by simpa using hi, rfl⟩) omit dec lemma subtype_domain_sum [Π i, add_comm_monoid (β i)] {s : finset γ} {h : γ → Π₀ i, β i} {p : ι → Prop} [decidable_pred p] : (∑ c in s, h c).subtype_domain p = ∑ c in s, (h c).subtype_domain p := eq.symm (s.sum_hom _) lemma subtype_domain_finsupp_sum {δ : γ → Type x} [decidable_eq γ] [Π c, has_zero (δ c)] [Π c (x : δ c), decidable (x ≠ 0)] [Π i, add_comm_monoid (β i)] {p : ι → Prop} [decidable_pred p] {s : Π₀ c, δ c} {h : Π c, δ c → Π₀ i, β i} : (s.sum h).subtype_domain p = s.sum (λc d, (h c d).subtype_domain p) := subtype_domain_sum end prod_and_sum end dfinsupp /-! ### Product and sum lemmas for bundled morphisms -/ section variables [decidable_eq ι] namespace monoid_hom variables {R S : Type*} [comm_monoid R] [comm_monoid S] variables [Π i, add_comm_monoid (β i)] [Π i (x : β i), decidable (x ≠ 0)] @[simp, to_additive] lemma map_dfinsupp_prod (h : R →* S) (f : Π₀ i, β i) (g : Π i, β i → R) : h (f.prod g) = f.prod (λ a b, h (g a b)) := h.map_prod _ _ @[to_additive] lemma coe_dfinsupp_prod (f : Π₀ i, β i) (g : Π i, β i → R →* S) : ⇑(f.prod g) = f.prod (λ a b, (g a b)) := coe_prod _ _ @[simp, to_additive] lemma dfinsupp_prod_apply (f : Π₀ i, β i) (g : Π i, β i → R →* S) (r : R) : (f.prod g) r = f.prod (λ a b, (g a b) r) := finset_prod_apply _ _ _ end monoid_hom end
3d2452e7610701ed44bacef2448a6f9fed41fc5b
f0050a24971f1b7315211eec6e02a8eee618ce6b
/src/big_step/basic.lean
04c40a1d422527b5a183c4b7f9d4e2b3dfe19104
[ "Apache-2.0" ]
permissive
ttowncompiled/excaLibur
9574f2acb0bafcd59f59423b63a62c15442ea5f7
7d8371bf998012d4f8c49d3fe2bf540e2517c688
refs/heads/master
1,670,710,035,703
1,599,670,584,000
1,599,670,584,000
292,720,923
0
0
null
null
null
null
UTF-8
Lean
false
false
8,542
lean
/- Copyright (c) Ian Riley. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Ian Riley -/ import common inductive big_step : (stmt × scope) → scope → Prop | skip {s : scope} : big_step (stmt.skip, s) s | assign {x : string} {a : scope → Prop} {s : scope} : big_step (stmt.assign x a, s) (s{x ↦ a s}) | comp {S T : stmt} {s t u : scope} (hS : big_step (S, s) t) (hT : big_step (T, t) u) : big_step (S ;; T, s) u | ite_true {b : scope → Prop} {S T : stmt} {s t : scope} (hcond : b s) (hbody : big_step (S, s) t) : big_step (stmt.ite b S T, s) t | ite_false {b : scope → Prop} {S T : stmt} {s t : scope} (hcond : ¬ b s) (hbody : big_step (T, s) t) : big_step (stmt.ite b S T, s) t | while_true {b : scope → Prop} {S : stmt} {s t u: scope} (hcond : b s) (hbody : big_step (S, s) t) (hrest : big_step (stmt.while b S, t) u) : big_step (stmt.while b S, s) u | while_false {b : scope → Prop} {S : stmt} {s : scope} (hcond : ¬ b s) : big_step (stmt.while b S, s) s | call {f : string} {v₀ v₁ : scope → Prop} {F : stmt} {s t : scope} {σ : scope → scope} (args : (v₀ s) ∧ (v₁ s)) (hF : big_step (F, (σ s)) t) : big_step (stmt.call f v₀ v₁ σ F, s) t infix ` ⟹ `:110 := big_step -- ⟹ \==> /- Instructions for how to use big_step and its notation Big step semantics are used to represent the scope change of an instruction or composition of instructions that is executed synchronously/deterministically. A big_step can be defined using the following notation (S, s) ⟹ t where S is a statement (from common.stmt) and s t are each a scope (from common.basic). This notation constructs an instance of big_step that represents the execution of stmt S with scope s that results in scope t. -/ namespace big_step /- Sequent: Skip _______________ (skip, s) ⟹ s -/ @[simp] lemma skip_iff {s t : scope} : (stmt.skip, s) ⟹ t ↔ t = s := begin apply iff.intro, { intro h₁, cases h₁, refl, }, { intro h₂, rw h₂, exact big_step.skip, } end /- Sequent: Assign __________________________ {x := a, s) ⟹ s{x ↦ a s} -/ @[simp] lemma assign_iff {x : string} {a : scope → Prop} {s t : scope} : (stmt.assign x a, s) ⟹ t ↔ t = (s{x ↦ a s}) := begin apply iff.intro, { intro h₁, cases h₁, refl, }, { intro h₂, rw h₂, exact big_step.assign, } end /- Sequent: (S, s) ⟹ t (T, t) ⟹ u Comp ________________________ (S ;; T, s) ⟹ u -/ @[simp] lemma comp_iff {S T : stmt} {s u : scope} : (S ;; T, s) ⟹ u ↔ (∃ (t : scope), (S, s) ⟹ t ∧ (T, t) ⟹ u) := begin apply iff.intro, { intro h₁, cases h₁, apply exists.intro, apply and.intro h₁_hS h₁_hT, }, { intro h₂, cases h₂, cases h₂_h, apply big_step.comp h₂_h_left h₂_h_right, } end /- Sequent: (b s) ∧ (S, s) ⟹ t ¬ (b s) ∧ (T, s) ⟹ t If-Then-Else _____________________________________________ (if b then S else T, s) ⟹ t -/ @[simp] lemma ite_iff {b : scope → Prop} {S T : stmt} {s t : scope} : (stmt.ite b S T, s) ⟹ t ↔ (b s ∧ (S, s) ⟹ t) ∨ (¬ b s ∧ (T, s) ⟹ t) := begin apply iff.intro, { intro h₁, cases h₁, { apply or.intro_left, apply and.intro h₁_hcond h₁_hbody, }, { apply or.intro_right, apply and.intro h₁_hcond h₁_hbody, } }, { intro h₂, cases h₂, { cases h₂, apply big_step.ite_true h₂_left h₂_right, }, { cases h₂, apply big_step.ite_false h₂_left h₂_right, } } end /- Sequent: (S, s) ⟹ t If-Then-Else-True _____________________________ (b s) is TRUE (if b then S else T, s) ⟹ t -/ @[simp] lemma ite_true_iff {b : scope → Prop} {S T : stmt} {s t : scope} (hcond : b s) : (stmt.ite b S T, s) ⟹ t ↔ (S, s) ⟹ t := begin apply iff.intro, { intro h₁, cases h₁, { exact h₁_hbody, }, { exfalso, apply h₁_hcond hcond, } }, { intro h₂, apply big_step.ite_true hcond h₂, } end /- Sequent: (T, s) ⟹ t If-Then-Else-False _____________________________ (b s) is FALSE (if b then S else T, s) ⟹ t -/ @[simp] lemma ite_false_iff {b : scope → Prop} {S T : stmt} {s t : scope} (hcond : ¬ b s) : (stmt.ite b S T, s) ⟹ t ↔ (T, s) ⟹ t := begin apply iff.intro, { intro h₁, cases h₁, { exfalso, apply hcond h₁_hcond, }, { exact h₁_hbody, } }, { intro h₂, apply big_step.ite_false hcond h₂, } end /- Sequent: (b s) ∧ (S, s) ⟹ t (b s) ∧ (while b do S, t) ⟹ u ¬ (b s) ∧ u = s While _____________________________________________________________________ (while b do S, s) ⟹ u -/ lemma while_iff {b : scope → Prop} {S : stmt} {s u : scope} : (stmt.while b S, s) ⟹ u ↔ (b s ∧ (∃ (t : scope), (S, s) ⟹ t ∧ (stmt.while b S, t) ⟹ u)) ∨ (¬ b s ∧ u = s) := begin apply iff.intro, { intro h₁, cases h₁, { apply or.intro_left, split, exact h₁_hcond, apply exists.intro h₁_t, apply and.intro h₁_hbody h₁_hrest, }, { apply or.intro_right, apply and.intro h₁_hcond (rfl), } }, { intro h₂, cases h₂, case or.inl { cases h₂ with hb h₂, cases h₂ with t h₂, cases h₂ with hS hwhile, exact big_step.while_true hb hS hwhile, }, case or.inr { cases h₂ with hb h₂, rw h₂, apply big_step.while_false hb, } } end /- Sequent: (S, s) ⟹ t (while b do S, t) ⟹ u While-True _______________________________________ (b s) is TRUE (while b do S, s) ⟹ u -/ lemma while_true_iff {b : scope → Prop} {S : stmt} {s u : scope} (hcond : b s) : (stmt.while b S, s) ⟹ u ↔ (∃ (t : scope), (S, s) ⟹ t ∧ (stmt.while b S, t) ⟹ u) := begin apply iff.intro, { intro h₁, cases h₁, { apply exists.intro h₁_t, apply and.intro h₁_hbody h₁_hrest, }, { exfalso, apply h₁_hcond hcond, } }, { intro h₂, cases h₂ with t h₂, cases h₂ with hS hwhile, apply big_step.while_true hcond hS hwhile, } end /- Sequent: While-False ______________________ (b s) is FALSE (while b do S, s) ⟹ s -/ @[simp] lemma while_false_iff {b : scope → Prop} {S : stmt} {s t: scope} (hcond : ¬ b s) : (stmt.while b S, s) ⟹ t ↔ t = s := begin apply iff.intro, { intro h₁, cases h₁, { exfalso, apply hcond h₁_hcond, }, { refl, } }, { intro h₂, rw h₂, apply big_step.while_false hcond, } end /- Sequent: (F, (σ s)) ⟹ t Call __________________________ ∀ args, args = (v₀ s) ∧ (v₁ s) (call f v₀ v₁ σ F, s) ⟹ t -/ @[simp] lemma call_iff {f : string} {v₀ v₁ : scope → Prop} {F : stmt} {s t : scope} {σ : scope → scope} (args : (v₀ s) ∧ (v₁ s)) : (stmt.call f v₀ v₁ σ F, s) ⟹ t ↔ ((F, (σ s)) ⟹ t) := begin apply iff.intro, { intro h₁, cases h₁, exact h₁_hF, }, { intro h₂, apply big_step.call args h₂, } end end big_step
7dc90103fd303997387a1d8f976da7c2972e5ed3
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/scopedParsers.lean
44122fd648e308e8c586ae05c98206f9a5fb7f7c
[ "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
305
lean
def f (x y : Nat) := x + 2*y namespace Foo scoped infix:65 (priority := default+1) "+" => f theorem ex1 (x y : Nat) : x + y = f x y := rfl #check 1 + 2 end Foo #check 1 + 2 theorem ex2 (x y : Nat) : x + y = HAdd.hAdd x y := rfl open Foo theorem ex3 (x y : Nat) : x + y = f x y := rfl #check 1 + 2
c0de1ed6df8aa845d510cb074ffa73d80ea228aa
cf39355caa609c0f33405126beee2739aa3cb77e
/library/init/meta/environment.lean
372a792f57a0feaa8ba503af5300f2bd2da5d53b
[ "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
11,417
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.meta.declaration init.meta.exceptional init.data.option.basic import init.meta.rb_map /-- An __environment__ contains all of the declarations and notation that have been defined so far. -/ meta constant environment : Type namespace environment /-- Consider a type `ψ` which is an inductive datatype using a single constructor `mk (a : α) (b : β) : ψ`. Lean will automatically make two projection functions `a : ψ → α`, `b : ψ → β`. Lean tags these declarations as __projections__. This helps the simplifier / rewriter not have to expand projectors. Eg `a (mk x y)` will automatically reduce to `x`. If you `extend` a structure, all of the projections on the parent will also be created for the child. Projections are also treated differently in the VM for efficiency. Note that projections have nothing to do with the dot `mylist.map` syntax. You can find out if a declaration is a projection using `environment.is_projection` which returns `projection_info`. Data for a projection declaration: - `cname` is the name of the constructor associated with the projection. - `nparams` is the number of constructor parameters. Eg `and.intro` has two type parameters. - `idx` is the parameter being projected by this projection. - `is_class` is tt iff this is a typeclass projection. ### Examples: - `and.right` is a projection with ``{cname := `and.intro, nparams := 2, idx := 1, is_class := ff}`` - `ordered_ring.neg` is a projection with ``{cname := `ordered_ring.mk, nparams := 1, idx := 5, is_class := tt}``. -/ structure projection_info := (cname : name) (nparams : nat) (idx : nat) (is_class : bool) /-- A marking on the binders of structures and inductives indicating how this constructor should mark its parameters. inductive foo | one {} : foo -> foo -- relaxed_implicit | two ( ) : foo -> foo -- explicit | two [] : foo -> foo -- implicit | three : foo -> foo -- relaxed implicit (default) -/ inductive implicit_infer_kind | implicit | relaxed_implicit | none instance implicit_infer_kind.inhabited : inhabited implicit_infer_kind := ⟨implicit_infer_kind.implicit⟩ /-- One introduction rule in an inductive declaration -/ meta structure intro_rule := (constr : name) (type : expr) (infer : implicit_infer_kind := implicit_infer_kind.implicit) /-- Create a standard environment using the given trust level -/ meta constant mk_std : nat → environment /-- Return the trust level of the given environment -/ meta constant trust_lvl : environment → nat /-- Add a new declaration to the environment -/ meta constant add : environment → declaration → exceptional environment /-- make declaration `n` protected -/ meta constant mk_protected : environment → name → environment /-- add declaration `d` and make it protected -/ meta def add_protected (env : environment) (d : declaration) : exceptional environment := do env ← env.add d, pure $ env.mk_protected d.to_name /-- check if `n` is the name of a protected declaration -/ meta constant is_protected : environment → name → bool /-- Retrieve a declaration from the environment -/ meta constant get : environment → name → exceptional declaration meta def contains (env : environment) (d : name) : bool := match env.get d with | exceptional.success _ := tt | exceptional.exception _ := ff end meta constant add_defn_eqns (env : environment) (opt : options) (lp_params : list name) (params : list expr) (sig : expr) (eqns : list (list (expr ff) × expr)) (is_meta : bool) : exceptional environment /-- Register the given name as a namespace, making it available to the `open` command -/ meta constant add_namespace : environment → name → environment /-- Mark a namespace as open -/ meta constant mark_namespace_as_open : environment -> name -> environment /-- Modify the environment as if `open %%name` had been parsed -/ meta constant execute_open : environment -> name -> environment /-- Retrieve all registered namespaces -/ meta constant get_namespaces : environment -> list name /-- Return tt iff the given name is a namespace -/ meta constant is_namespace : environment → name → bool /-- Add a new inductive datatype to the environment name, universe parameters, number of parameters, type, constructors (name and type), is_meta -/ meta constant add_inductive (env : environment) (n : name) (levels : list name) (num_params : nat) (type : expr) (intros : list (name × expr)) (is_meta : bool) : exceptional environment /-- Add a new general inductive declaration to the environment. This has the same effect as a `inductive` in the file, including generating all the auxiliary definitions, as well as triggering mutual/nested inductive compilation, by contrast to `environment.add_inductive` which only adds the core axioms supported by the kernel. The `inds` argument should be a list of inductives in the mutual family. The first argument is a pair of the name of the type being constructed and the type of this inductive family (not including the params). The second argument is a list of intro rules, specified by a name, an `implicit_infer_kind` giving the implicitness of the params for this constructor, and an expression with the type of the constructor (not including the params). -/ meta constant add_ginductive (env : environment) (opt : options) (levels : list name) (params : list expr) (inds : list ((name × expr) × list intro_rule)) (is_meta : bool) : exceptional environment /-- Return tt iff the given name is an inductive datatype -/ meta constant is_inductive : environment → name → bool /-- Return tt iff the given name is a constructor -/ meta constant is_constructor : environment → name → bool /-- Return tt iff the given name is a recursor -/ meta constant is_recursor : environment → name → bool /-- Return tt iff the given name is a recursive inductive datatype -/ meta constant is_recursive : environment → name → bool /-- Return the name of the inductive datatype of the given constructor. -/ meta constant inductive_type_of : environment → name → option name /-- Return the constructors of the inductive datatype with the given name -/ meta constant constructors_of : environment → name → list name /-- Return the recursor of the given inductive datatype -/ meta constant recursor_of : environment → name → option name /-- Return the number of parameters of the inductive datatype -/ meta constant inductive_num_params : environment → name → nat /-- Return the number of indices of the inductive datatype -/ meta constant inductive_num_indices : environment → name → nat /-- Return tt iff the inductive datatype recursor supports dependent elimination -/ meta constant inductive_dep_elim : environment → name → bool /-- Functionally equivalent to `is_inductive`. Technically, this works by checking if the name is in the ginductive environment extension which is outside the kernel, whereas `is_inductive` works by looking at the kernel extension. But there are no `is_inductive`s which are not `is_ginductive`. -/ meta constant is_ginductive : environment → name → bool /-- See the docstring for `projection_info`. -/ meta constant is_projection : environment → name → option projection_info /-- Fold over declarations in the environment. -/ meta constant fold {α :Type} : environment → α → (declaration → α → α) → α /-- `relation_info env n` returns some value if n is marked as a relation in the given environment. the tuple contains: total number of arguments of the relation, lhs position and rhs position. -/ meta constant relation_info : environment → name → option (nat × nat × nat) /-- `refl_for env R` returns the name of the reflexivity theorem for the relation R -/ meta constant refl_for : environment → name → option name /-- `symm_for env R` returns the name of the symmetry theorem for the relation R -/ meta constant symm_for : environment → name → option name /-- `trans_for env R` returns the name of the transitivity theorem for the relation R -/ meta constant trans_for : environment → name → option name /-- `decl_olean env d` returns the name of the .olean file where d was defined. The result is none if d was not defined in an imported file. -/ meta constant decl_olean : environment → name → option string /-- `decl_pos env d` returns the source location of d if available. -/ meta constant decl_pos : environment → name → option pos /-- `decl_pos env d` returns the name of a declaration that d inherits noncomputability from, or `none` if it is computable. Note that this also returns `none` on `axiom`s and `constant`s. These can be detected by using `environment.get_decl` and `declaration.is_axiom` and `declaration.is_constant`. -/ meta constant decl_noncomputable_reason : environment → name → option name /-- Return the fields of the structure with the given name, or `none` if it is not a structure -/ meta constant structure_fields : environment → name → option (list name) /-- `get_class_attribute_symbols env attr_name` return symbols occurring in instances of type classes tagged with the attribute `attr_name`. Example: [algebra] -/ meta constant get_class_attribute_symbols : environment → name → name_set /-- The fingerprint of the environment is a hash formed from all of the declarations in the environment. -/ meta constant fingerprint : environment → nat /-- Gets the equation lemmas for the declaration `n`. -/ meta constant get_eqn_lemmas_for (env : environment) (n : name) : list name /-- Gets the equation lemmas for the declaration `n`, including lemmas for match statements, etc. -/ meta constant get_ext_eqn_lemmas_for (env : environment) (n : name) : list name /-- Adds the equation lemma `n`. It is added for the declaration `t.pi_codomain.get_app_fn.const_name` where `t` is the type of the equation lemma. -/ meta constant add_eqn_lemma (env : environment) (n : name) : environment open expr meta constant unfold_untrusted_macros : environment → expr → expr meta constant unfold_all_macros : environment → expr → expr meta def is_constructor_app (env : environment) (e : expr) : bool := is_constant (get_app_fn e) && is_constructor env (const_name (get_app_fn e)) meta def is_refl_app (env : environment) (e : expr) : option (name × expr × expr) := match (refl_for env (const_name (get_app_fn e))) with | (some n) := if get_app_num_args e ≥ 2 then some (n, app_arg (app_fn e), app_arg e) else none | none := none end /-- Return true if 'n' has been declared in the current file -/ meta def in_current_file (env : environment) (n : name) : bool := (env.decl_olean n).is_none && env.contains n && (n ∉ [``quot, ``quot.mk, ``quot.lift, ``quot.ind]) meta def is_definition (env : environment) (n : name) : bool := match env.get n with | exceptional.success (declaration.defn _ _ _ _ _ _) := tt | _ := ff end end environment meta instance : has_repr environment := ⟨λ e, "[environment]"⟩ meta instance : inhabited environment := ⟨environment.mk_std 0⟩
2cd65be8d07f1dfaeb0834230f8d136123c0911b
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/geometry/manifold/instances/real.lean
68c0d91035bb9463e7a4b4784cdd8bc550131ea9
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
7,430
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 Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.geometry.manifold.algebra.smooth_functions import Mathlib.linear_algebra.finite_dimensional import Mathlib.analysis.normed_space.inner_product import Mathlib.PostPort namespace Mathlib /-! # Constructing examples of manifolds over ℝ We introduce the necessary bits to be able to define manifolds modelled over `ℝ^n`, boundaryless or with boundary or with corners. As a concrete example, we construct explicitly the manifold with boundary structure on the real interval `[x, y]`. More specifically, we introduce * `model_with_corners ℝ (euclidean_space ℝ (fin n)) (euclidean_half_space n)` for the model space used to define `n`-dimensional real manifolds with boundary * `model_with_corners ℝ (euclidean_space ℝ (fin n)) (euclidean_quadrant n)` for the model space used to define `n`-dimensional real manifolds with corners ## Notations In the locale `manifold`, we introduce the notations * `𝓡 n` for the identity model with corners on `euclidean_space ℝ (fin n)` * `𝓡∂ n` for `model_with_corners ℝ (euclidean_space ℝ (fin n)) (euclidean_half_space n)`. For instance, if a manifold `M` is boundaryless, smooth and modelled on `euclidean_space ℝ (fin m)`, and `N` is smooth with boundary modelled on `euclidean_half_space n`, and `f : M → N` is a smooth map, then the derivative of `f` can be written simply as `mfderiv (𝓡 m) (𝓡∂ n) f` (as to why the model with corners can not be implicit, see the discussion in `smooth_manifold_with_corners.lean`). ## Implementation notes The manifold structure on the interval `[x, y] = Icc x y` requires the assumption `x < y` as a typeclass. We provide it as `[fact (x < y)]`. -/ /-- The half-space in `ℝ^n`, used to model manifolds with boundary. We only define it when `1 ≤ n`, as the definition only makes sense in this case. -/ def euclidean_half_space (n : ℕ) [HasZero (fin n)] := Subtype fun (x : euclidean_space ℝ (fin n)) => 0 ≤ x 0 /-- The quadrant in `ℝ^n`, used to model manifolds with corners, made of all vectors with nonnegative coordinates. -/ def euclidean_quadrant (n : ℕ) := Subtype fun (x : euclidean_space ℝ (fin n)) => ∀ (i : fin n), 0 ≤ x i /- Register class instances for euclidean half-space and quadrant, that can not be noticed without the following reducibility attribute (which is only set in this section). -/ protected instance euclidean_half_space.topological_space {n : ℕ} [HasZero (fin n)] : topological_space (euclidean_half_space n) := subtype.topological_space protected instance euclidean_quadrant.topological_space {n : ℕ} : topological_space (euclidean_quadrant n) := subtype.topological_space protected instance euclidean_half_space.inhabited {n : ℕ} [HasZero (fin n)] : Inhabited (euclidean_half_space n) := { default := { val := 0, property := sorry } } protected instance euclidean_quadrant.inhabited {n : ℕ} : Inhabited (euclidean_quadrant n) := { default := { val := 0, property := sorry } } theorem range_half_space (n : ℕ) [HasZero (fin n)] : (set.range fun (x : euclidean_half_space n) => subtype.val x) = set_of fun (x : euclidean_space ℝ (fin n)) => 0 ≤ x 0 := sorry theorem range_quadrant (n : ℕ) : (set.range fun (x : euclidean_quadrant n) => subtype.val x) = set_of fun (x : euclidean_space ℝ (fin n)) => ∀ (i : fin n), 0 ≤ x i := sorry /-- Definition of the model with corners `(euclidean_space ℝ (fin n), euclidean_half_space n)`, used as a model for manifolds with boundary. In the locale `manifold`, use the shortcut `𝓡∂ n`. -/ def model_with_corners_euclidean_half_space (n : ℕ) [HasZero (fin n)] : model_with_corners ℝ (euclidean_space ℝ (fin n)) (euclidean_half_space n) := model_with_corners.mk (local_equiv.mk (fun (x : euclidean_half_space n) => subtype.val x) (fun (x : euclidean_space ℝ (fin n)) => { val := fun (i : fin n) => dite (i = 0) (fun (h : i = 0) => max (x i) 0) fun (h : ¬i = 0) => x i, property := sorry }) set.univ (set.range fun (x : euclidean_half_space n) => subtype.val x) sorry sorry sorry sorry) sorry sorry /-- Definition of the model with corners `(euclidean_space ℝ (fin n), euclidean_quadrant n)`, used as a model for manifolds with corners -/ def model_with_corners_euclidean_quadrant (n : ℕ) : model_with_corners ℝ (euclidean_space ℝ (fin n)) (euclidean_quadrant n) := model_with_corners.mk (local_equiv.mk (fun (x : euclidean_quadrant n) => subtype.val x) (fun (x : euclidean_space ℝ (fin n)) => { val := fun (i : fin n) => max (x i) 0, property := sorry }) set.univ (set.range fun (x : euclidean_quadrant n) => subtype.val x) sorry sorry sorry sorry) sorry sorry /-- The left chart for the topological space `[x, y]`, defined on `[x,y)` and sending `x` to `0` in `euclidean_half_space 1`. -/ def Icc_left_chart (x : ℝ) (y : ℝ) [fact (x < y)] : local_homeomorph (↥(set.Icc x y)) (euclidean_half_space 1) := local_homeomorph.mk (local_equiv.mk (fun (z : ↥(set.Icc x y)) => { val := fun (i : fin 1) => subtype.val z - x, property := sorry }) (fun (z : euclidean_half_space 1) => { val := min (subtype.val z 0 + x) y, property := sorry }) (set_of fun (z : ↥(set.Icc x y)) => subtype.val z < y) (set_of fun (z : euclidean_half_space 1) => subtype.val z 0 < y - x) sorry sorry sorry sorry) sorry sorry sorry sorry /-- The right chart for the topological space `[x, y]`, defined on `(x,y]` and sending `y` to `0` in `euclidean_half_space 1`. -/ def Icc_right_chart (x : ℝ) (y : ℝ) [fact (x < y)] : local_homeomorph (↥(set.Icc x y)) (euclidean_half_space 1) := local_homeomorph.mk (local_equiv.mk (fun (z : ↥(set.Icc x y)) => { val := fun (i : fin 1) => y - subtype.val z, property := sorry }) (fun (z : euclidean_half_space 1) => { val := max (y - subtype.val z 0) x, property := sorry }) (set_of fun (z : ↥(set.Icc x y)) => x < subtype.val z) (set_of fun (z : euclidean_half_space 1) => subtype.val z 0 < y - x) sorry sorry sorry sorry) sorry sorry sorry sorry /-- Charted space structure on `[x, y]`, using only two charts taking values in `euclidean_half_space 1`. -/ protected instance Icc_manifold (x : ℝ) (y : ℝ) [fact (x < y)] : charted_space (euclidean_half_space 1) ↥(set.Icc x y) := charted_space.mk (insert (Icc_left_chart x y) (singleton (Icc_right_chart x y))) (fun (z : ↥(set.Icc x y)) => ite (subtype.val z < y) (Icc_left_chart x y) (Icc_right_chart x y)) sorry sorry /-- The manifold structure on `[x, y]` is smooth. -/ protected instance Icc_smooth_manifold (x : ℝ) (y : ℝ) [fact (x < y)] : smooth_manifold_with_corners (model_with_corners_euclidean_half_space 1) ↥(set.Icc x y) := sorry /-! Register the manifold structure on `Icc 0 1`, and also its zero and one. -/ theorem fact_zero_lt_one : fact (0 < 1) := zero_lt_one protected instance set.Icc.charted_space : charted_space (euclidean_half_space 1) ↥(set.Icc 0 1) := Mathlib.Icc_manifold 0 1 protected instance set.Icc.smooth_manifold_with_corners : smooth_manifold_with_corners (model_with_corners_euclidean_half_space 1) ↥(set.Icc 0 1) := Mathlib.Icc_smooth_manifold 0 1
e40e3451a7eaa82138534e6e8c695a45b2d80aa2
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/category_theory/limits/constructions/over/products.lean
23fec24394be3fa445487babce0119857cbd3245
[]
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
5,817
lean
/- Copyright (c) 2018 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Reid Barton, Bhavik Mehta -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.category_theory.over import Mathlib.category_theory.limits.shapes.pullbacks import Mathlib.category_theory.limits.shapes.wide_pullbacks import Mathlib.category_theory.limits.shapes.finite_products import Mathlib.PostPort universes v u namespace Mathlib /-! # Products in the over category Shows that products in the over category can be derived from wide pullbacks in the base category. The main result is `over_product_of_wide_pullback`, which says that if `C` has `J`-indexed wide pullbacks, then `over B` has `J`-indexed products. -/ namespace category_theory.over namespace construct_products /-- (Implementation) Given a product diagram in `C/B`, construct the corresponding wide pullback diagram in `C`. -/ def wide_pullback_diagram_of_diagram_over {C : Type u} [category C] (B : C) {J : Type v} (F : discrete J ⥤ over B) : limits.wide_pullback_shape J ⥤ C := limits.wide_pullback_shape.wide_cospan B (fun (j : J) => comma.left (functor.obj F j)) fun (j : J) => comma.hom (functor.obj F j) /-- (Impl) A preliminary definition to avoid timeouts. -/ def cones_equiv_inverse_obj {C : Type u} [category C] (B : C) {J : Type v} (F : discrete J ⥤ over B) (c : limits.cone F) : limits.cone (wide_pullback_diagram_of_diagram_over B F) := limits.cone.mk (comma.left (limits.cone.X c)) (nat_trans.mk fun (X : limits.wide_pullback_shape J) => option.cases_on X (comma.hom (limits.cone.X c)) fun (j : J) => comma_morphism.left (nat_trans.app (limits.cone.π c) j)) /-- (Impl) A preliminary definition to avoid timeouts. -/ def cones_equiv_inverse {C : Type u} [category C] (B : C) {J : Type v} (F : discrete J ⥤ over B) : limits.cone F ⥤ limits.cone (wide_pullback_diagram_of_diagram_over B F) := functor.mk (cones_equiv_inverse_obj B F) fun (c₁ c₂ : limits.cone F) (f : c₁ ⟶ c₂) => limits.cone_morphism.mk (comma_morphism.left (limits.cone_morphism.hom f)) /-- (Impl) A preliminary definition to avoid timeouts. -/ @[simp] theorem cones_equiv_functor_map_hom {C : Type u} [category C] (B : C) {J : Type v} (F : discrete J ⥤ over B) (c₁ : limits.cone (wide_pullback_diagram_of_diagram_over B F)) (c₂ : limits.cone (wide_pullback_diagram_of_diagram_over B F)) (f : c₁ ⟶ c₂) : limits.cone_morphism.hom (functor.map (cones_equiv_functor B F) f) = hom_mk (limits.cone_morphism.hom f) := Eq.refl (limits.cone_morphism.hom (functor.map (cones_equiv_functor B F) f)) /-- (Impl) A preliminary definition to avoid timeouts. -/ @[simp] def cones_equiv_unit_iso {J : Type v} {C : Type u} [category C] (B : C) (F : discrete J ⥤ over B) : 𝟭 ≅ cones_equiv_functor B F ⋙ cones_equiv_inverse B F := nat_iso.of_components (fun (_x : limits.cone (wide_pullback_diagram_of_diagram_over B F)) => limits.cones.ext (iso.mk 𝟙 𝟙) sorry) sorry /-- (Impl) A preliminary definition to avoid timeouts. -/ @[simp] def cones_equiv_counit_iso {J : Type v} {C : Type u} [category C] (B : C) (F : discrete J ⥤ over B) : cones_equiv_inverse B F ⋙ cones_equiv_functor B F ≅ 𝟭 := nat_iso.of_components (fun (_x : limits.cone F) => limits.cones.ext (iso.mk (hom_mk 𝟙) (hom_mk 𝟙)) sorry) sorry -- TODO: Can we add `. obviously` to the second arguments of `nat_iso.of_components` and -- `cones.ext`? /-- (Impl) Establish an equivalence between the category of cones for `F` and for the "grown" `F`. -/ @[simp] theorem cones_equiv_unit_iso_2 {J : Type v} {C : Type u} [category C] (B : C) (F : discrete J ⥤ over B) : equivalence.unit_iso (cones_equiv B F) = cones_equiv_unit_iso B F := Eq.refl (equivalence.unit_iso (cones_equiv B F)) /-- Use the above equivalence to prove we have a limit. -/ theorem has_over_limit_discrete_of_wide_pullback_limit {J : Type v} {C : Type u} [category C] {B : C} (F : discrete J ⥤ over B) [limits.has_limit (wide_pullback_diagram_of_diagram_over B F)] : limits.has_limit F := sorry /-- Given a wide pullback in `C`, construct a product in `C/B`. -/ theorem over_product_of_wide_pullback {J : Type v} {C : Type u} [category C] [limits.has_limits_of_shape (limits.wide_pullback_shape J) C] {B : C} : limits.has_limits_of_shape (discrete J) (over B) := limits.has_limits_of_shape.mk fun (F : discrete J ⥤ over B) => has_over_limit_discrete_of_wide_pullback_limit F /-- Given a pullback in `C`, construct a binary product in `C/B`. -/ theorem over_binary_product_of_pullback {C : Type u} [category C] [limits.has_pullbacks C] {B : C} : limits.has_binary_products (over B) := over_product_of_wide_pullback /-- Given all wide pullbacks in `C`, construct products in `C/B`. -/ theorem over_products_of_wide_pullbacks {C : Type u} [category C] [limits.has_wide_pullbacks C] {B : C} : limits.has_products (over B) := fun (J : Type v) => over_product_of_wide_pullback /-- Given all finite wide pullbacks in `C`, construct finite products in `C/B`. -/ theorem over_finite_products_of_finite_wide_pullbacks {C : Type u} [category C] [limits.has_finite_wide_pullbacks C] {B : C} : limits.has_finite_products (over B) := fun (J : Type v) (𝒥₁ : DecidableEq J) (𝒥₂ : fintype J) => over_product_of_wide_pullback end construct_products /-- Construct terminal object in the over category. This isn't an instance as it's not typically the way we want to define terminal objects. (For instance, this gives a terminal object which is different from the generic one given by `over_product_of_wide_pullback` above.) -/ theorem over_has_terminal {C : Type u} [category C] (B : C) : limits.has_terminal (over B) := sorry
92bc8c1d27f16d9b0d47ec34bffdb0c397bd2eb7
3618c6e11aa822fd542440674dfb9a7b9921dba0
/src/multirelation/approach2/tactic.lean
f77bb0fedf77989c5714ec671d51dcb5702f5209
[]
no_license
ChrisHughes24/single_relation
99ceedcc02d236ce46d6c65d72caa669857533c5
057e157a59de6d0e43b50fcb537d66792ec20450
refs/heads/master
1,683,652,062,698
1,683,360,089,000
1,683,360,089,000
279,346,432
0
0
null
null
null
null
UTF-8
Lean
false
false
21,088
lean
import .approach2_ref namespace group_rel open expr tactic free_group native meta structure cache := (G : expr) (univ : level) (red : transparency) (ic : ref instance_cache) -- instance_cache for G (atoms : ref (buffer expr)) (free_group_simp_lemmas : simp_lemmas) @[derive [monad, alternative]] meta def group_rel_m (α : Type) : Type := reader_t cache tactic α meta def get_cache : group_rel_m cache := reader_t.read section open tactic.simp_arg_type /- [inv_core, inv_def, bool.bnot_true, bool.bnot_false, eq_self_iff_true, true_and, and_true, one_def, mul_def, list.reverse_core, mul_aux, ne.def, not_false_iff, if_true, if_false, false_and, and_false, nat.succ.inj_eq, nat.zero_eq_succ_eq] -/ meta def gpow_norm_simp_set : tactic simp_lemmas := mk_simp_set tt [] [symm_expr ``(gpow_coe_nat), expr ``(gpow_add), expr ``(gpow_neg), expr ``(bit0), expr ``(bit1), expr ``(gpow_one), expr ``(gpow_zero), expr ``(mul_add), expr ``(add_mul), expr ``(neg_neg), symm_expr ``(neg_mul_eq_neg_mul), symm_expr ``(neg_mul_eq_mul_neg), expr ``(int.coe_nat_add), expr ``(int.coe_nat_zero), expr ``(int.coe_nat_one), expr ``(int.coe_nat_mul), expr ``(nat.succ_eq_add_one), expr ``(mul_one), expr ``(one_mul), expr ``(pow_succ), expr ``(pow_zero), expr ``(pow_one)] >>= λ x, return x.fst end namespace group_rel_m meta def lift {α : Type} : tactic α → group_rel_m α := reader_t.lift meta instance {α : Type} : has_coe (tactic α) (group_rel_m α) := ⟨lift⟩ /-- Lift an instance cache tactic (probably from `norm_num`) to the `ring_m` monad. This version is abstract over the instance cache in question (either the ring `α`, or `ℕ` for exponents). -/ @[inline] meta def ic_lift' (icf : cache → ref instance_cache) {α} (f : instance_cache → tactic (instance_cache × α)) : group_rel_m α := ⟨λ c, do let r := icf c, ic ← read_ref r, (ic', a) ← f ic, a <$ write_ref r ic'⟩ /-- Lift an instance cache tactic (probably from `norm_num`) to the `group_rel_m` monad. This uses the instance cache corresponding to the ring `α`. -/ @[inline] meta def ic_lift {α} : (instance_cache → tactic (instance_cache × α)) → group_rel_m α := ic_lift' cache.ic /-- make the application `n G i l`, where `i` is some instance found in the cache for `G` -/ meta def mk_app (n : name) (l : list expr) : group_rel_m expr := ic_lift $ λ ic, ic.mk_app n l meta def mk_eval_simp_lemmas (ic : instance_cache) : tactic (instance_cache × simp_lemmas) := [``eval.equations._eqn_1, ``eval.equations._eqn_2, ``eval.equations._eqn_3, ``inv_inv, ``one_mul, ``mul_one, ``mul_assoc, ``mul_inv_self, ``inv_mul_self, ``mul_inv_rev, ``one_inv, ``mul_inv_cancel_left, ``inv_mul_cancel_left, ``pow_one, ``gpow_one, ``gpow_neg, ``pow_zero, ``gpow_zero, ``gpow_add, ``pow_add, ``gpow_bit0, ``gpow_bit1, ``pow_bit0, ``pow_bit1].mfoldl (λ (x : instance_cache × simp_lemmas) n, do (ic, e) ← x.1.mk_app n [], sl ← x.2.add e ff, return (ic, sl)) (ic, simp_lemmas.mk) meta def run (red : transparency) (G : expr) {α} (m : group_rel_m α) : tactic α := do u ← mk_meta_univ, infer_type G >>= unify (expr.sort (level.succ u)), u ← get_univ_assignment u, ic ← mk_instance_cache G, fsl ← mk_free_group_simp_lemmas, -- (ic, esl) ← mk_eval_simp_lemmas ic, using_new_ref ic $ λ ric, using_new_ref mk_buffer $ λ atoms, reader_t.run m ⟨G, u, red, ric, atoms, fsl⟩ meta def add_atom (e : expr) : group_rel_m ℕ := ⟨λ l, do es ← read_ref l.atoms, es.iterate failed (λ n e' t, t <|> (is_def_eq e e' l.red $> n.1)) <|> (es.size <$ write_ref l.atoms (es.push_back e))⟩ meta def prove_free_group_eqv (lhs : expr) : group_rel_m expr := do c ← get_cache, free_group_simp lhs c.free_group_simp_lemmas /-- Get an already encountered atom by its index. -/ meta def get_atom (n : ℕ) : group_rel_m expr := ⟨λ c, do es ← read_ref c.atoms, pure (es.read' n)⟩ meta def to_free_group : expr → group_rel_m free_group | `(%%a * %%b) := do a' ← to_free_group a, b' ← to_free_group b, return (a' * b') | `((%%a)⁻¹) := do a' ← to_free_group a, return (a'⁻¹) | `(@has_one.one _ _) := return 1 | e@`((%%a) ^ (%%n)) := cond (is_numeral n) (do ne ← eval_expr' ℤ n, a' ← to_free_group a, return (a' ^ ne)) (do i ← add_atom e, return (of i)) | e := do i ← add_atom e, return (of i) lemma eval_mul_congr {G : Type*} [group G] (atoms : list G) (a b : G) (a' b' ab : free_group) (ha : eval atoms a' = a) (hb : eval atoms b' = b) (hab : eqv (ap a' b') ab) : eval atoms ab = a * b := by simp [← eval_eq_of_eqv atoms hab, eval_ap, *] lemma eval_inv_congr {G : Type*} [group G] (atoms : list G) (a : G) (a' a_inv : free_group) (ha : eval atoms a' = a) (ha_inv : eqv (inv_core a' 1) a_inv) : eval atoms a_inv = a⁻¹ := by simp [inv_core_eq, ← eval_eq_of_eqv atoms ha_inv, eval_inv, eval_append, eval_one, *] meta def to_free_group' (atoms : expr) : expr → group_rel_m (free_group × expr) | `(%%a * %%b) := do (a', pra) ← to_free_group' a, (b', prb) ← to_free_group' b, let ab' := a' * b', fpr ← prove_free_group_eqv `(ap %%(to_expr a') %%(to_expr b')), pr ← mk_app ``eval_mul_congr [atoms, a, b, to_expr a', to_expr b', to_expr ab', pra, prb, fpr], return (a' * b', pr) | `((%%a)⁻¹) := do (a', pr) ← to_free_group' a, let a'_inv := a'⁻¹, fpr ← prove_free_group_eqv `(inv_core %%(to_expr a') 1), pr ← mk_app ``eval_inv_congr [atoms, a, to_expr a', to_expr a'_inv, pr, fpr], return (a'_inv, pr) | `(@has_one.one _ _) := do pr ← mk_app ``eval_one [atoms], return (1, pr) | e := do i ← add_atom e, c ← get_cache, pr ← mk_app `mul_one [e], return (of i, pr) local infix `*'`:70 := ap local infixl `≡` :50 := free_group.eqv inductive proof_eq_one {G : Type*} [group G] (atoms : list G) : free_group → Prop | one : proof_eq_one 1 | step : Π (word₁ rel word₂ conj old_word new_word rel_conj : free_group), proof_eq_one new_word → (word₁ *' word₂) ≡ old_word → eval atoms rel = 1 → inv_core conj word₁ *' inv_core rel_conj rel *' rel_conj *' word₂ *' conj ≡ new_word → proof_eq_one old_word theorem eq_of_eval_eq_one {G : Type*} [group G] (atoms : list G) (lhs rhs : G) (w : free_group) (h : eval atoms w = lhs * rhs⁻¹) (h₂ : eval atoms w = 1) : lhs = rhs := mul_inv_eq_one.1 (h ▸ h₂) theorem eq_one_of_proof_eq_one {G : Type*} [group G] (atoms : list G) (g : free_group) (h : proof_eq_one atoms g) : eval atoms g = 1 := begin induction h with word₁ rel word₂ conj old_word new_word op h₁ h₂ h₃ ih h, { refl }, { rw [← eval_eq_of_eqv atoms ih] at h, simp only [eval_ap, h₃, one_mul, mul_assoc, eval_inv, inv_mul_cancel_left, inv_core_eq, eval_append] at h, rw [inv_mul_eq_one, ← mul_assoc, ← mul_inv_eq_iff_eq_mul, mul_inv_self] at h, rw [← eval_eq_of_eqv atoms h₂, eval_ap, ← h] } end -- reverse list before applying meta def make_proof_eq_one_expr (atoms : expr) (rel_eq_one : buffer expr) (rel_inv_eq_one : buffer expr) (rels : buffer free_group) (rels_inv : buffer free_group) : list path_step → group_rel_m expr | [] := mk_app ``proof_eq_one.one [atoms] | (p::l) := do pr ← make_proof_eq_one_expr l, c ← get_cache, let word₁ := p.old_word.take p.word_letter_index, let word₂ := p.old_word.drop p.word_letter_index, let rel := cond p.rel_is_inv (rels.read' p.rel_index) (rels_inv.read' p.rel_index), let rel_conj := rel.take (let x := rel.length - p.rel_letter_index in if x = rel.length then 0 else x), let conj := cyclically_reduce_conj (word₁ * rel_conj⁻¹ * rel * rel_conj * word₂), proof_rel₁ : expr ← prove_free_group_eqv `(%%(to_expr word₁) *' %%(to_expr word₂)), proof_rel₂ : expr ← prove_free_group_eqv `(inv_core %%(to_expr conj) %%(to_expr word₁) *' inv_core %%(to_expr rel_conj) %%(to_expr rel) *' %%(to_expr rel_conj) *' %%(to_expr word₂) *' %%(to_expr conj)), mk_app ``proof_eq_one.step [atoms, to_expr word₁, to_expr rel, to_expr word₂, to_expr conj, to_expr p.old_word, to_expr p.new_word, to_expr rel_conj, pr, proof_rel₁, cond p.rel_is_inv (rel_eq_one.read' p.rel_index) (rel_inv_eq_one.read' p.rel_index), proof_rel₂] meta def get_atoms : group_rel_m (buffer expr) := do c ← get_cache, read_ref c.atoms meta def list_atoms : group_rel_m expr := do c ← get_cache, atoms ← read_ref c.atoms, atoms.to_list.foldr (λ atom l, do l ← l, mk_mapp `list.cons [some c.G, some atom, some l]) (mk_mapp `list.nil [some c.G]) lemma eval_eq_one₂ {G : Type*} [group G] (atoms : list G) (lhs rhs : G) (h : lhs = rhs) (lhsg rhsg lr : free_group) (hlhs : eval atoms lhsg = lhs) (hrhs : eval atoms rhsg = rhs) (heqv : lr *' rhsg ≡ lhsg) : eval atoms lr = 1 := begin substs lhs rhs, rwa [← eval_eq_of_eqv _ heqv, eval_ap, ← eq_mul_inv_iff_mul_eq, mul_inv_self] at hlhs end lemma eq_of_eval_eq_one₂ {G : Type*} [group G] (atoms : list G) (lhs rhs : G) (lhsg rhsg lr : free_group) (hlhs : eval atoms lhsg = lhs) (hrhs : eval atoms rhsg = rhs) (heqv : lr *' rhsg ≡ lhsg) (hlr : eval atoms lr = 1) : lhs = rhs := by simpa [← eval_eq_of_eqv atoms heqv, hrhs, eval_ap, eval_inv, inv, mul_inv_eq_one, ← hlhs] using hlr lemma eval_conj_eq_one {G : Type*} [group G] (atoms : list G) (rel conj new_rel : free_group) (h : inv_core conj rel *' conj ≡ new_rel) (rel_eq_one : eval atoms rel = 1) : eval atoms new_rel = 1 := by simp [← eval_eq_of_eqv atoms h, inv_core_eq, rel_eq_one, eval_inv, eval_append, eval_ap, inv] meta def cyclically_reduce_rel (atoms : expr) (rel : free_group) (rel_eq_one : expr) : group_rel_m (free_group × expr) := let a : free_group := cyclically_reduce_conj rel in if a = 1 then return (rel, rel_eq_one) else do let new_rel := a⁻¹ * rel * a, pr_eqv ← prove_free_group_eqv `(inv_core %%(to_expr a) %%(to_expr rel) *' %%(to_expr a)), pr ← mk_app ``eval_conj_eq_one [atoms, to_expr rel, to_expr a, to_expr new_rel, pr_eqv, rel_eq_one], return (new_rel, pr) lemma eval_inv_eq_one {G : Type*} [group G] (atoms : list G) (rel rel_inv : free_group) (h : eqv (inv_core rel []) rel_inv) (hrel : eval atoms rel = 1) : eval atoms rel_inv = 1 := by rw [← eval_eq_of_eqv atoms h, inv_core_eq, eval_append, eval, mul_one, eval_inv, hrel, one_inv] meta def make_proof_inv_eq_one (atoms : expr) (rel : free_group) (rel_eq_one : expr) : group_rel_m (free_group × expr) := do let rel_inv := rel⁻¹, pr_eqv ← prove_free_group_eqv `(inv_core %%(to_expr rel) 1), pr ← mk_app ``eval_inv_eq_one [atoms, to_expr rel, to_expr rel_inv, pr_eqv, rel_eq_one], return (rel_inv, pr) meta def make_proof' (atoms : expr) (hyp_type hyp_pr : expr) : group_rel_m (free_group × free_group × expr × expr) := do (lhs, rhs) ← is_eq hyp_type, (lhsg, prl) ← to_free_group' atoms lhs, (rhsg, prr) ← to_free_group' atoms rhs, let lr := lhsg * rhsg⁻¹, pr_eqv ← prove_free_group_eqv `(%%(to_expr lr) *' %%(to_expr rhsg)), pr ← mk_app ``eval_eq_one₂ [atoms, lhs, rhs, hyp_pr, to_expr lhsg, to_expr rhsg, to_expr lr, prl, prr, pr_eqv], (lr, pr) ← cyclically_reduce_rel atoms lr pr, (lr_inv, pr_inv) ← make_proof_inv_eq_one atoms lr pr, pr ← note_anon none pr, pr_inv ← note_anon none pr_inv, return (lr, lr_inv, pr, pr_inv) meta def mk_list_free_group : list (expr × expr) → group_rel_m (list (expr × -- proof expr × expr × -- lhs rhs free_group × free_group -- lhs ehs )) | [] := return [] | ((t, e)::l) := match t with | `(%%e₁= %%e₂) := do l ← mk_list_free_group l, lhsg ← to_free_group e₁, rhsg ← to_free_group e₂, return ((e, e₁, e₂, lhsg, rhsg)::l) | _ := mk_list_free_group l end section subst meta def subst_into_rel (rel word : free_group) (i : ℕ) (r₁ r₂ : free_group) (rel_eq_one word_eq_one : expr) : group_rel_m (free_group × expr) := do atoms ← list_atoms, let new_word := free_group.subst i (r₁⁻¹ * r₂⁻¹) word, pr ← mk_app ``subst_eq_one_of_eq_one [atoms, reflect i, to_expr r₁, to_expr r₂, to_expr rel, to_expr (r₁⁻¹ * r₂⁻¹), to_expr word, to_expr new_word, `(@eq.refl free_group (%%(to_expr (r₁⁻¹ * r₂⁻¹)))), `(@eq.refl free_group %%(to_expr rel)), rel_eq_one, word_eq_one, `(@eq.refl free_group %%(to_expr new_word))], cyclically_reduce_rel atoms new_word pr meta def subst_into_target (rel word : free_group) (i : ℕ) (r₁ r₂ : free_group) (rel_eq_one : expr) : group_rel_m free_group := do atoms ← list_atoms, let new_word := free_group.subst i (r₁⁻¹ * r₂⁻¹) word, pr ← mk_app ``eq_one_of_subst_eq_one [atoms, reflect i, to_expr r₁, to_expr r₂, to_expr rel, to_expr (r₁⁻¹ * r₂⁻¹), to_expr word, to_expr new_word, `(@eq.refl free_group (%%(to_expr (r₁⁻¹ * r₂⁻¹)))), `(@eq.refl free_group %%(to_expr rel)), rel_eq_one, `(@eq.refl free_group new_word)], tactic.apply pr { md := transparency.none }, return new_word meta def perform_substs_core (atoms : expr) : Π (p₁ p₂ : list (free_group × free_group × expr × expr)) (tgt : free_group), group_rel_m (list (free_group × free_group × expr × expr) × free_group) | [] p₂ tgt := return (p₂, tgt) | ((A@(rel, rel_inv, rel_eq_one, rel_inv_eq_one))::p₁) p₂ tgt := match is_subst rel with | none := perform_substs_core p₁ (A :: p₂) tgt | (some (i, b, r₁, r₂)) := do let p' := p₁ ++ p₂, let rel' := cond b rel_inv rel, let rel'_eq_one := cond b rel_inv_eq_one rel_eq_one, let (r₁, r₂) := cond b (r₂⁻¹, r₁⁻¹) (r₁, r₂), new_p : list (free_group × free_group × expr × expr) ← (p₁ ++ p₂).mmap (λ ⟨word, word_inv, word_eq_one, word_inv_eq_one⟩, show group_rel_m (free_group × free_group × expr × expr), from do (new_word, new_word_eq_one) ← subst_into_rel rel' word i r₁ r₂ rel'_eq_one word_eq_one, (new_word_inv, new_word_inv_eq_one) ← make_proof_inv_eq_one atoms new_word new_word_eq_one, return (new_word, new_word_inv, new_word_eq_one, new_word_inv_eq_one)), new_tgt ← subst_into_target rel' tgt i r₁ r₂ rel'_eq_one, perform_substs_core new_p [] new_tgt end meta def perform_substs (atoms : expr) (p : list (free_group × free_group × expr × expr)) (tgt : free_group) : group_rel_m (list (free_group × free_group × expr × expr) × free_group) := perform_substs_core atoms p [] tgt end subst meta def collect_like_exponents : group_rel_m (rb_map expr-- exponee (list (expr × --exponent and exponee option expr --exponent × ℕ -- index in buffer of atoms ))) := do c ← get_cache, atoms ← read_ref c.atoms, atoms.iterate (return mk_rb_map) (λ i atom m, do rb ← m, match atom with | A@`((%%a)^(%%n)) := let e : tactic (rb_map expr (list (expr × option expr × ℕ))) := rb.fold failure (λ e l t, t <|> is_def_eq e a >> return (rb.insert e ((A, some n, i)::l))) in e <|> return (rb.insert a [(A, some n, i)]) | `(%%a) := let e : tactic (rb_map expr (list (expr × option expr × ℕ))) := rb.fold failure (λ e l t, t <|> is_def_eq e a >> return (rb.insert e ((a, none, i)::l))) in e <|> return (rb.insert a [(a, none, i)]) end). lemma eval_gpow_gpow_comm {G : Type*} [group G] (atoms : list G) (i j : ℕ) (g : G) (m n : ℤ) (hi : nth atoms i = g ^ m) (hj : nth atoms j = g ^ n) : eval atoms [⟨i, ff⟩, ⟨j, ff⟩, ⟨i, tt⟩, ⟨j, tt⟩] = 1 := begin simp only [eval, hi, hj, ← gpow_neg, mul_one, ← gpow_add], rw [add_left_comm, add_neg_cancel_left, add_neg_self, gpow_zero] end lemma eval_gpow_comm {G : Type*} [group G] (atoms : list G) (i j : ℕ) (g : G) (m : ℤ) (hi : nth atoms i = g ^ m) (hj : nth atoms j = g) : eval atoms [⟨i, ff⟩, ⟨j, ff⟩, ⟨i, tt⟩, ⟨j, tt⟩] = 1 := eval_gpow_gpow_comm atoms i j g m 1 hi (by simpa) /-- `a` -/ meta def make_pow_comm_proof (atoms : expr) (a : expr) (l : list (expr × (option expr) × ℕ)) : group_rel_m (list (free_group × free_group × expr × expr)) := do l.mfoldl (λ prs₁ e₁, l.mfoldl (λ prs₂ e₂, if e₁.2.2 ≤ e₂.2.2 then return prs₂ else match e₁, e₂ with | (an₁, some n₁, i), (an₂, some n₂, j) := do peq₁ ← mk_eq_refl an₁, peq₂ ← mk_eq_refl an₂, pr ← mk_app ``eval_gpow_gpow_comm [atoms, reflect i, reflect j, a, n₁, n₂, peq₁, peq₂], pr ← note_anon none pr, let rel : free_group := [⟨i, ff⟩, ⟨j, ff⟩, ⟨i, tt⟩, ⟨j, tt⟩], (rel_inv, pr_inv) ← make_proof_inv_eq_one atoms rel pr, return((rel, rel_inv, pr, pr_inv) :: prs₂) | (an₁, some n₁, i), (an₂, none, j) := do peq₁ ← mk_eq_refl an₁, peq₂ ← mk_eq_refl an₂, pr ← mk_app ``eval_gpow_comm [atoms, reflect i, reflect j, a, n₁, peq₁, peq₂], pr ← note_anon none pr, let rel : free_group := [⟨i, ff⟩, ⟨j, ff⟩, ⟨i, tt⟩, ⟨j, tt⟩], (rel_inv, pr_inv) ← make_proof_inv_eq_one atoms rel pr, return ((rel, rel_inv, pr, pr_inv) :: prs₂) | (an₁, none, i), (an₂, some n₂, j) := do peq₁ ← mk_eq_refl an₁, peq₂ ← mk_eq_refl an₂, pr ← mk_app ``eval_gpow_comm [atoms, reflect j, reflect i, a, n₂, peq₂, peq₁], pr ← note_anon none pr, let rel : free_group := [⟨j, ff⟩, ⟨i, ff⟩, ⟨j, tt⟩, ⟨i, tt⟩], (rel_inv, pr_inv) ← make_proof_inv_eq_one atoms rel pr, return ((rel, rel_inv, pr, pr_inv) :: prs₂) | _, _ := return prs₂ end) prs₁) [] meta def make_pow_comm_proofs (atoms : expr) : group_rel_m (list (free_group × free_group × expr × expr)) := do rb ← collect_like_exponents, rb.fold (return []) (λ a l m, do prs ← m, new_prs ← make_pow_comm_proof atoms a l, return (new_prs ++ prs)) meta def simp_rel (sl : simp_lemmas) (pr : expr) : tactic (expr × expr) := do t ← infer_type pr, (do (t, pr') ← simplify sl [] t, new_pr ← mk_eq_mp pr' pr, return (t, new_pr)) <|> return (t, pr) meta def group_rel (sl : simp_lemmas) (hyps : list expr) (tlhs : expr) (trhs : expr) : group_rel_m unit := do type_hyps ← hyps.mmap (lift ∘ infer_type), c ← get_cache, list_G ← tactic.mk_app `list [c.G], atoms' ← mk_meta_var list_G, (lhsg, prl) ← to_free_group' atoms' tlhs, (rhsg, prr) ← to_free_group' atoms' trhs, hyps ← lift $ hyps.mmap $ simp_rel sl, hyps ← hyps.mmap (λ a, make_proof' atoms' a.1 a.2), atoms ← list_atoms, unify atoms' atoms, pow_comm_proofs ← make_pow_comm_proofs atoms, a ← get_atoms, let tgt := lhsg * rhsg⁻¹, pr_eqv ← prove_free_group_eqv `(%%(to_expr tgt) *' %%(to_expr rhsg)), eq_of_eval_eq_one ← mk_app ``eq_of_eval_eq_one₂ [atoms, tlhs, trhs, to_expr lhsg, to_expr rhsg, to_expr tgt, prl, prr, pr_eqv], tactic.apply eq_of_eval_eq_one, (hyps, tgt) ← perform_substs atoms (hyps ++ pow_comm_proofs) tgt, trace (pow_comm_proofs.map prod.fst), solution ← timetac "solve time " (solve (hyps.map prod.fst) tgt a.size), let path := trace_path solution.2, tactic.trace ("path length = " ++ repr path.length), tactic.trace atoms, e ← make_proof_eq_one_expr atoms (list.to_buffer (hyps.map (λ x, x.2.2.1))) (list.to_buffer (hyps.map (λ x, x.2.2.2))) (list.to_buffer (hyps.map (λx, x.1))) (list.to_buffer (hyps.map (λx, x.2.1))) path.reverse, pr ← mk_app ``eq_one_of_proof_eq_one [atoms, to_expr tgt, e], tactic.exact pr end group_rel_m end group_rel namespace tactic.interactive open interactive.types interactive tactic expr group_rel meta def group_rel (hyps : parse pexpr_list) : tactic unit := do sl ← gpow_norm_simp_set, tactic.try (simp_target sl []), tgt ← target, (lhs, rhs) ← is_eq tgt, G ← infer_type lhs, hyps' : list expr ← hyps.mmap i_to_expr, group_rel_m.run transparency.semireducible G (group_rel_m.group_rel sl hyps' lhs rhs) end tactic.interactive
850b0a6c5c7c6875681d54f7a0cb302c5bfcaf9b
38aa1f7792ba7c73b43619c5d089e15d69cd32eb
/grasshopper.lean
d52bb696f05c0e0e1879576fc502cd05940affb5
[]
no_license
mirefek/my-lean-experiments
f8ec3efa4013285b80cd45c219a7bc8b6294b8cc
1218fecbf568669ac123256d430a151a900f67b3
refs/heads/master
1,679,449,694,211
1,616,190,468,000
1,616,190,468,000
154,370,734
1
0
null
null
null
null
UTF-8
Lean
false
false
12,814
lean
import tactic import data.finset ----------------------------------------------------------------- --------------------- helpers ----------------------------- def subtract_emb (c:ℤ) : ℤ ↪ ℤ := ⟨λx:ℤ, x-c, begin intros, unfold function.injective, show ∀ x y : ℤ, x-c = y-c → x = y, by omega, end⟩ lemma lt_of_le_ne (a b : ℤ) (h1 : a ≤ b) (h2 : a ≠ b) : (a < b) := begin cases lt_trichotomy a b, show a < b, by assumption, cases h, by contradiction, omega, end --------------------- helpers ----------------------------- ----------------------------------------------------------------- ------------------ finset operations ------------------------ lemma finset_rest {s : finset ℤ} {x : ℤ} (x_in_s : x ∈ s) : ∃ r : finset ℤ, s.val = x::r.val := begin cases (@multiset.exists_cons_of_mem ℤ s.val x x_in_s) with r_ms r_h, have s_nodup : multiset.nodup (x::r_ms), begin rw ←r_h, exact s.nodup end, have : r_ms.nodup, exact (multiset.nodup_cons.elim_left s_nodup).2, let r : finset ℤ := ⟨r_ms, this⟩, show ∃ (r : finset ℤ), s.val = x :: r.val, from ⟨r, r_h⟩ end lemma finset_cons_subset {s : finset ℤ} {s2 : finset ℤ} {x:ℤ} (h : s.val = x::s2.val) : s2 ⊂ s := begin apply finset.val_lt_iff.elim_left, rw h, show s2.val < x :: s2.val, from multiset.lt_cons_self s2.val x, end theorem sum_filter_split {p : ℤ → Prop} [decidable_pred p] (s : finset ℤ) : s.card = (s.filter p).card + (s.filter (λa, ¬ p a)).card := begin let s1 := s.filter p, let s2 := s.filter (λa, ¬ p a), have inter_empty : s1 ∩ s2 = ∅, by exact finset.filter_inter_filter_neg_eq s, have union_full : s1 ∪ s2 = s, by exact finset.filter_union_filter_neg_eq s, have : (s1 ∪ s2).card + (s1 ∩ s2).card = s1.card + s2.card, by apply finset.card_union_add_card_inter, rw [inter_empty, finset.card_empty, add_zero] at this, show s.card = s1.card + s2.card, rw ←union_full, show (s1 ∪ s2).card = s1.card + s2.card, from this end ------------------ finset operations ------------------------ ----------------------------------------------------------------- ----------------- handling prefixes ------------------------ lemma cons_prefix (x : ℤ) (a : list ℤ) : [x] <+: x::a := begin have : [x] = list.take 1 (x::a), by simp, rw this, show list.take 1 (x :: a) <+: x :: a, by apply list.take_prefix, end lemma prefix_one_eq {x : ℤ} {y : ℤ} {l : list ℤ} (h1 : [x] <+: l) (h2 : [y] <+: l) : x = y := begin have xy : [x] <+: [y] := list.prefix_of_prefix_length_le h1 h2 (by simp), have : [x] = [y], from list.eq_of_prefix_of_length_eq xy (by simp), simp at this, show x = y, from this, end lemma prefix_eq_head {x y : ℤ} {a b : list ℤ} (h : list.cons x a ∈ (list.cons y b).inits) : x = y := begin have pref : x::a <+: y::b, from (list.mem_inits (x::a) (y::b)).1 h, have xxa : [x] <+: x::a, by apply cons_prefix, have yyb : [y] <+: y::b, by apply cons_prefix, have xyb : [x] <+: y::b, from list.is_prefix.trans xxa pref, show x = y, from prefix_one_eq xyb yyb, end lemma prefix_tail_prefix {x y : ℤ} {a b : list ℤ} (h : list.cons x a ∈ (list.cons y b).inits) : a ∈ b.inits := begin have : x = y, from prefix_eq_head h, rw ←this at h, have : x::a <+: x::b, from (list.mem_inits (x::a) (x::b)).1 h, have : a <+: b, from (list.prefix_cons_inj x).1 this, show a ∈ b.inits, from (list.mem_inits a b).2 this, end ----------------- handling prefixes ------------------------ ----------------------------------------------------------------- ------------- sum of positive integers --------------------- lemma l_nonneg_sum {l : list ℤ} (h1 : ∀ x ∈ l, (0:ℤ) < x) : l.sum ≥ 0 := begin induction l, show [].sum ≥ (0:ℤ), by simp, show list.sum (l_hd :: l_tl) ≥ (0:ℤ), have : list.sum (l_hd :: l_tl) = l_hd + l_tl.sum, by simp, rw this, show l_hd + l_tl.sum ≥ 0, have : l_hd ≥ 0, begin apply le_of_lt, apply h1, show l_hd ∈ list.cons l_hd l_tl, by apply list.mem_cons_self, end, have : l_tl.sum ≥ 0, begin apply l_ih, assume (x:ℤ) (tl_in : x ∈ l_tl), show 0 < x, apply h1, apply list.mem_cons_of_mem, show x ∈ l_tl, by assumption, end, omega, end lemma pref_nonneg_sum {jumps : finset ℤ} {jumps_l : list ℤ} {jumps_pref : list ℤ} (h1 : ∀ jump ∈ jumps, (0:ℤ) < jump) (h2 : jumps.val = jumps_l) (h3 : jumps_pref ∈ jumps_l.inits) : jumps_pref.sum ≥ 0 := begin apply l_nonneg_sum, assume (jump:ℤ) (h : jump ∈ jumps_pref), apply h1, show jump ∈ jumps, apply finset.mem_def.2, rw h2, show jump ∈ jumps_l, have : jumps_pref ⊆ jumps_l, begin apply list.subset_of_sublist, apply list.sublist_of_prefix, apply (list.mem_inits jumps_pref jumps_l).1, show jumps_pref ∈ jumps_l.inits, from h3, end, apply (list.subset_def.1 this), show jump ∈ jumps_pref, from h, end ------------- sum of positive integers --------------------- ----------------------------------------------------------------- ----------------- the main theorem ------------------------- theorem grasshopper : forall n : ℕ, forall jumps : finset ℤ, (forall jump ∈ jumps, (0:ℤ) < jump) → (jumps.card = n) → let size := jumps.1.sum in forall mines : finset ℤ, (mines.card < n) → (forall mine ∈ mines, (0:ℤ) < mine ∧ mine < size) → exists jumps_l : list ℤ, jumps.1 = jumps_l ∧ forall jumps_pref ∈ jumps_l.inits, list.sum jumps_pref ∉ mines := begin assume n, induction n with n n_ih, -- zero case is trivial intros, have : mines.card < 0, by assumption, have : ¬mines.card < 0, by apply nat.not_lt_zero, contradiction, intros, -- inductive case -- Take the maximal jump have : jumps.nonempty, by simp [a_1, finset.card_pos.elim_left], cases finset.max_of_nonempty this with maxjump maxjump_ex, have maxjump_in : maxjump ∈ jumps, by exact finset.mem_of_max maxjump_ex, cases finset_rest maxjump_in with jumps_res jumps_res_ex, -- Remove the maximal jump, partial plugging into IH have : jumps_res ⊆ jumps, from and.elim_left (finset_cons_subset jumps_res_ex), have jumps_res_pos : ∀ jump ∈ jumps_res, (0:ℤ) < jump, begin intro jump, assume h : jump ∈ jumps_res, have : jump ∈ jumps, from finset.mem_of_subset this h, show 0 < jump, from a jump this, end, have n_ih := n_ih jumps_res jumps_res_pos begin show jumps_res.card = n, apply nat.succ_inj, rw ←a_1, show jumps_res.card.succ = jumps.card, have : (maxjump :: jumps_res.val).card = jumps_res.val.card + 1, by apply multiset.card_cons, rw ←jumps_res_ex at this, exact eq.symm this, end, -- Calculate the remaining size let size_res := jumps_res.1.sum, have size_res_eq : size_res = size - maxjump, begin show multiset.sum jumps_res.val = multiset.sum jumps.val - maxjump, rw jumps_res_ex, rw multiset.sum_cons, ring, end, -- Shift the mines by maxjump to the left let mines_smaller := finset.filter (λ(x:ℤ), x < maxjump) mines, let mines_bigger := finset.filter (λ(x:ℤ), ¬x < maxjump) mines, have parts_size : mines.card = mines_smaller.card + mines_bigger.card, by apply sum_filter_split, let mines_sub := finset.map (subtract_emb maxjump) mines_bigger, have mines_sub_rev : ∀ mine ∈ mines_sub, mine + maxjump ∈ mines ∧ 0 ≤ mine, begin intros, cases finset.mem_map.elim_left H with mine_ori mine_ori_prop, cases mine_ori_prop with mine_ori_in_bigger mine_ori_def, show mine + maxjump ∈ mines ∧ 0 ≤ mine, rw [←mine_ori_def], show mine_ori - maxjump + maxjump ∈ mines ∧ 0 ≤ mine_ori - maxjump, apply and.intro, begin simp, show mine_ori ∈ mines, apply finset.mem_of_subset, show mine_ori ∈ mines_bigger, by assumption, show mines_bigger ⊆ mines, by simp, end, begin show 0 ≤ mine_ori - maxjump, have : ¬(mine_ori < maxjump), from (finset.mem_filter.1 mine_ori_in_bigger).2, omega, end end, have mines_sub_small : ∀ mine ∈ mines_sub, mine < size_res, begin intros, have : mine + maxjump ∈ mines, from (mines_sub_rev mine H).1, have : mine + maxjump < size, from (a_3 (mine + maxjump) this).2, show mine < size_res, by omega, end, ------------------------------------------ ---------- case analysis cases (classical.em (maxjump ∈ mines)) with mine_on_maxjump mine_not_on_maxjump, -- case A: first jump to mine begin sorry, end, -- cases C and B have mines_sub_positive : ∀ mine ∈ mines_sub, (0:ℤ) < mine, begin assume (mine : ℤ) (mine_in : mine ∈ mines_sub), apply lt_of_le_ne, show 0 ≤ mine, from (mines_sub_rev mine mine_in).2, show 0 ≠ mine, begin assume mine_zero : 0 = mine, have : mine + maxjump ∈ mines, from (mines_sub_rev mine mine_in).1, simp [←mine_zero] at this, contradiction, end end, cases (classical.em mines_smaller.nonempty) with mines_smaller_nonempty mines_smaller_empty, -- case C: we jump over a mine with the first jump begin have : mines_sub.card < n, begin have : mines_sub.card = mines_bigger.card, by apply finset.card_map, rw this, have : finset.card mines_smaller > 0, by exact finset.card_pos.2 mines_smaller_nonempty, have smaller_ge : 1 ≤ finset.card mines_smaller, exact nat.succ_le_iff.2 this, rw parts_size at a_2, have : finset.card mines_smaller + finset.card mines_bigger ≤ n, from nat.lt_succ_iff.1 a_2, show mines_bigger.card < n, from calc mines_bigger.card < mines_bigger.card + 1 : by apply nat.lt_succ_self ... ≤ mines_bigger.card + mines_smaller.card : by apply add_le_add_left smaller_ge ... = mines_smaller.card + mines_bigger.card : by apply nat.add_comm ... ≤ n : this end, -- plug mines_sub to the IH, and get jumps_l_ind, jumps_l_ind_prop cases n_ih mines_sub this begin show ∀ (mine : ℤ), mine ∈ mines_sub → 0 < mine ∧ mine < size_res, assume (mine : ℤ) (mine_in : mine ∈ mines_sub), apply and.intro, show 0 < mine, from mines_sub_positive mine mine_in, show mine < size_res, from mines_sub_small mine mine_in end with jumps_l_ind jumps_l_ind_prop, let jumps_l : list ℤ := maxjump::jumps_l_ind, apply exists.intro jumps_l, apply and.intro, show jumps.val = ↑(maxjump :: jumps_l_ind), by simp [jumps_res_ex, jumps_l_ind_prop.1], show ∀ jumps_pref ∈ jumps_l.inits, list.sum jumps_pref ∉ mines, intros, cases jumps_pref, -- jumps_pref empty assume : (0:ℤ) ∈ mines, show false, from lt_irrefl (0:ℤ) (a_3 (0:ℤ) this).1, -- jumps_pref nonempty have : jumps_pref_hd = maxjump, from prefix_eq_head H, rw this, have : list.sum (maxjump :: jumps_pref_tl) = maxjump + jumps_pref_tl.sum, by simp, rw this, assume in_mines : maxjump + jumps_pref_tl.sum ∈ mines, have pref_tl_in_inits : jumps_pref_tl ∈ jumps_l_ind.inits, from prefix_tail_prefix H, have not_in_mines_sub: jumps_pref_tl.sum ∉ mines_sub, from jumps_l_ind_prop.2 jumps_pref_tl pref_tl_in_inits, have : ¬(maxjump + jumps_pref_tl.sum) < maxjump, begin have jumps_tl_sum_ge : jumps_pref_tl.sum ≥ (0:ℤ), from pref_nonneg_sum jumps_res_pos jumps_l_ind_prop.1 pref_tl_in_inits, have : maxjump + (0:ℤ) ≤ maxjump + jumps_pref_tl.sum, from add_le_add_left jumps_tl_sum_ge maxjump, omega, end, have in_mines_bigger : maxjump + jumps_pref_tl.sum ∈ mines_bigger, by simp [in_mines, this], have : (subtract_emb maxjump) (maxjump + jumps_pref_tl.sum) = jumps_pref_tl.sum, by apply add_sub_cancel', have : jumps_pref_tl.sum ∈ mines_sub, begin apply finset.mem_map.2, apply exists.intro (maxjump + jumps_pref_tl.sum), apply exists.intro in_mines_bigger, exact this, end, contradiction, end, -- case B: all mines are far away begin sorry, end end ----------------- the main theorem ------------------------- -----------------------------------------------------------------
9f2c86daf75c0f2de26a1b4555947872db0b512a
9dc8cecdf3c4634764a18254e94d43da07142918
/src/algebra/order/with_zero.lean
9d019991854eabed9e200c2601266258a2f77138
[ "Apache-2.0" ]
permissive
jcommelin/mathlib
d8456447c36c176e14d96d9e76f39841f69d2d9b
ee8279351a2e434c2852345c51b728d22af5a156
refs/heads/master
1,664,782,136,488
1,663,638,983,000
1,663,638,983,000
132,563,656
0
0
Apache-2.0
1,663,599,929,000
1,525,760,539,000
Lean
UTF-8
Lean
false
false
9,967
lean
/- Copyright (c) 2020 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Johan Commelin, Patrick Massot -/ import algebra.order.group /-! # Linearly ordered commutative groups and monoids with a zero element adjoined This file sets up a special class of linearly ordered commutative monoids that show up as the target of so-called “valuations” in algebraic number theory. Usually, in the informal literature, these objects are constructed by taking a linearly ordered commutative group Γ and formally adjoining a zero element: Γ ∪ {0}. The disadvantage is that a type such as `nnreal` is not of that form, whereas it is a very common target for valuations. The solutions is to use a typeclass, and that is exactly what we do in this file. Note that to avoid issues with import cycles, `linear_ordered_comm_monoid_with_zero` is defined in another file. However, the lemmas about it are stated here. -/ set_option old_structure_cmd true /-- A linearly ordered commutative group with a zero element. -/ @[protect_proj] class linear_ordered_comm_group_with_zero (α : Type*) extends linear_ordered_comm_monoid_with_zero α, comm_group_with_zero α variables {α : Type*} variables {a b c d x y z : α} instance [linear_ordered_add_comm_monoid_with_top α] : linear_ordered_comm_monoid_with_zero (multiplicative αᵒᵈ) := { zero := multiplicative.of_add (⊤ : α), zero_mul := top_add, mul_zero := add_top, zero_le_one := (le_top : (0 : α) ≤ ⊤), ..multiplicative.ordered_comm_monoid, ..multiplicative.linear_order } instance [linear_ordered_add_comm_group_with_top α] : linear_ordered_comm_group_with_zero (multiplicative αᵒᵈ) := { inv_zero := linear_ordered_add_comm_group_with_top.neg_top, mul_inv_cancel := linear_ordered_add_comm_group_with_top.add_neg_cancel, ..multiplicative.div_inv_monoid, ..multiplicative.linear_ordered_comm_monoid_with_zero, ..multiplicative.nontrivial } instance [linear_ordered_comm_monoid α] : linear_ordered_comm_monoid_with_zero (with_zero α) := { mul_le_mul_left := λ x y, mul_le_mul_left', zero_le_one := with_zero.zero_le _, ..with_zero.linear_order, ..with_zero.comm_monoid_with_zero } instance [linear_ordered_comm_group α] : linear_ordered_comm_group_with_zero (with_zero α) := { ..with_zero.linear_ordered_comm_monoid_with_zero, ..with_zero.comm_group_with_zero } section linear_ordered_comm_monoid variables [linear_ordered_comm_monoid_with_zero α] /- The following facts are true more generally in a (linearly) ordered commutative monoid. -/ /-- Pullback a `linear_ordered_comm_monoid_with_zero` under an injective map. See note [reducible non-instances]. -/ @[reducible] def function.injective.linear_ordered_comm_monoid_with_zero {β : Type*} [has_zero β] [has_one β] [has_mul β] [has_pow β ℕ] [has_sup β] [has_inf β] (f : β → α) (hf : function.injective f) (zero : f 0 = 0) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) (npow : ∀ x (n : ℕ), f (x ^ n) = f x ^ n) (hsup : ∀ x y, f (x ⊔ y) = max (f x) (f y)) (hinf : ∀ x y, f (x ⊓ y) = min (f x) (f y)) : linear_ordered_comm_monoid_with_zero β := { zero_le_one := show f 0 ≤ f 1, by simp only [zero, one, linear_ordered_comm_monoid_with_zero.zero_le_one], ..linear_order.lift f hf hsup hinf, ..hf.ordered_comm_monoid f one mul npow, ..hf.comm_monoid_with_zero f zero one mul npow } @[simp] lemma zero_le' : 0 ≤ a := by simpa only [mul_zero, mul_one] using mul_le_mul_left' zero_le_one a @[simp] lemma not_lt_zero' : ¬a < 0 := not_lt_of_le zero_le' @[simp] lemma le_zero_iff : a ≤ 0 ↔ a = 0 := ⟨λ h, le_antisymm h zero_le', λ h, h ▸ le_rfl⟩ lemma zero_lt_iff : 0 < a ↔ a ≠ 0 := ⟨ne_of_gt, λ h, lt_of_le_of_ne zero_le' h.symm⟩ lemma ne_zero_of_lt (h : b < a) : a ≠ 0 := λ h1, not_lt_zero' $ show b < 0, from h1 ▸ h instance : linear_ordered_add_comm_monoid_with_top (additive αᵒᵈ) := { top := (0 : α), top_add' := λ a, (zero_mul a : (0 : α) * a = 0), le_top := λ _, zero_le', ..additive.ordered_add_comm_monoid, ..additive.linear_order } end linear_ordered_comm_monoid variables [linear_ordered_comm_group_with_zero α] lemma zero_lt_one₀ : (0 : α) < 1 := lt_of_le_of_ne zero_le_one zero_ne_one -- TODO: Do we really need the following two? /-- Alias of `mul_le_one'` for unification. -/ lemma mul_le_one₀ (ha : a ≤ 1) (hb : b ≤ 1) : a * b ≤ 1 := mul_le_one' ha hb /-- Alias of `one_le_mul'` for unification. -/ lemma one_le_mul₀ (ha : 1 ≤ a) (hb : 1 ≤ b) : 1 ≤ a * b := one_le_mul ha hb lemma le_of_le_mul_right (h : c ≠ 0) (hab : a * c ≤ b * c) : a ≤ b := by simpa only [mul_inv_cancel_right₀ h] using (mul_le_mul_right' hab c⁻¹) lemma le_mul_inv_of_mul_le (h : c ≠ 0) (hab : a * c ≤ b) : a ≤ b * c⁻¹ := le_of_le_mul_right h (by simpa [h] using hab) lemma mul_inv_le_of_le_mul (hab : a ≤ b * c) : a * c⁻¹ ≤ b := begin by_cases h : c = 0, { simp [h], }, { exact le_of_le_mul_right h (by simpa [h] using hab), }, end lemma inv_le_one₀ (ha : a ≠ 0) : a⁻¹ ≤ 1 ↔ 1 ≤ a := @inv_le_one' _ _ _ _ $ units.mk0 a ha lemma one_le_inv₀ (ha : a ≠ 0) : 1 ≤ a⁻¹ ↔ a ≤ 1 := @one_le_inv' _ _ _ _ $ units.mk0 a ha lemma le_mul_inv_iff₀ (hc : c ≠ 0) : a ≤ b * c⁻¹ ↔ a * c ≤ b := ⟨λ h, inv_inv c ▸ mul_inv_le_of_le_mul h, le_mul_inv_of_mul_le hc⟩ lemma mul_inv_le_iff₀ (hc : c ≠ 0) : a * c⁻¹ ≤ b ↔ a ≤ b * c := ⟨λ h, inv_inv c ▸ le_mul_inv_of_mul_le (inv_ne_zero hc) h, mul_inv_le_of_le_mul⟩ lemma div_le_div₀ (a b c d : α) (hb : b ≠ 0) (hd : d ≠ 0) : a * b⁻¹ ≤ c * d⁻¹ ↔ a * d ≤ c * b := if ha : a = 0 then by simp [ha] else if hc : c = 0 then by simp [inv_ne_zero hb, hc, hd] else show (units.mk0 a ha) * (units.mk0 b hb)⁻¹ ≤ (units.mk0 c hc) * (units.mk0 d hd)⁻¹ ↔ (units.mk0 a ha) * (units.mk0 d hd) ≤ (units.mk0 c hc) * (units.mk0 b hb), from mul_inv_le_mul_inv_iff' @[simp] lemma units.zero_lt (u : αˣ) : (0 : α) < u := zero_lt_iff.2 $ u.ne_zero lemma mul_lt_mul_of_lt_of_le₀ (hab : a ≤ b) (hb : b ≠ 0) (hcd : c < d) : a * c < b * d := have hd : d ≠ 0 := ne_zero_of_lt hcd, if ha : a = 0 then by { rw [ha, zero_mul, zero_lt_iff], exact mul_ne_zero hb hd } else if hc : c = 0 then by { rw [hc, mul_zero, zero_lt_iff], exact mul_ne_zero hb hd } else show (units.mk0 a ha) * (units.mk0 c hc) < (units.mk0 b hb) * (units.mk0 d hd), from mul_lt_mul_of_le_of_lt hab hcd lemma mul_lt_mul₀ (hab : a < b) (hcd : c < d) : a * c < b * d := mul_lt_mul_of_lt_of_le₀ hab.le (ne_zero_of_lt hab) hcd lemma mul_inv_lt_of_lt_mul₀ (h : x < y * z) : x * z⁻¹ < y := by { contrapose! h, simpa only [inv_inv] using mul_inv_le_of_le_mul h } lemma inv_mul_lt_of_lt_mul₀ (h : x < y * z) : y⁻¹ * x < z := by { rw mul_comm at *, exact mul_inv_lt_of_lt_mul₀ h } lemma mul_lt_right₀ (c : α) (h : a < b) (hc : c ≠ 0) : a * c < b * c := by { contrapose! h, exact le_of_le_mul_right hc h } lemma inv_lt_inv₀ (ha : a ≠ 0) (hb : b ≠ 0) : a⁻¹ < b⁻¹ ↔ b < a := show (units.mk0 a ha)⁻¹ < (units.mk0 b hb)⁻¹ ↔ (units.mk0 b hb) < (units.mk0 a ha), from inv_lt_inv_iff lemma inv_le_inv₀ (ha : a ≠ 0) (hb : b ≠ 0) : a⁻¹ ≤ b⁻¹ ↔ b ≤ a := show (units.mk0 a ha)⁻¹ ≤ (units.mk0 b hb)⁻¹ ↔ (units.mk0 b hb) ≤ (units.mk0 a ha), from inv_le_inv_iff lemma lt_of_mul_lt_mul_of_le₀ (h : a * b < c * d) (hc : 0 < c) (hh : c ≤ a) : b < d := begin have ha : a ≠ 0 := ne_of_gt (lt_of_lt_of_le hc hh), simp_rw ← inv_le_inv₀ ha (ne_of_gt hc) at hh, have := mul_lt_mul_of_lt_of_le₀ hh (inv_ne_zero (ne_of_gt hc)) h, simpa [inv_mul_cancel_left₀ ha, inv_mul_cancel_left₀ (ne_of_gt hc)] using this, end lemma mul_le_mul_right₀ (hc : c ≠ 0) : a * c ≤ b * c ↔ a ≤ b := ⟨le_of_le_mul_right hc, λ hab, mul_le_mul_right' hab _⟩ lemma mul_le_mul_left₀ (ha : a ≠ 0) : a * b ≤ a * c ↔ b ≤ c := by {simp only [mul_comm a], exact mul_le_mul_right₀ ha } lemma div_le_div_right₀ (hc : c ≠ 0) : a / c ≤ b / c ↔ a ≤ b := by rw [div_eq_mul_inv, div_eq_mul_inv, mul_le_mul_right₀ (inv_ne_zero hc)] lemma div_le_div_left₀ (ha : a ≠ 0) (hb : b ≠ 0) (hc : c ≠ 0) : a / b ≤ a / c ↔ c ≤ b := by simp only [div_eq_mul_inv, mul_le_mul_left₀ ha, inv_le_inv₀ hb hc] lemma le_div_iff₀ (hc : c ≠ 0) : a ≤ b / c ↔ a*c ≤ b := by rw [div_eq_mul_inv, le_mul_inv_iff₀ hc] lemma div_le_iff₀ (hc : c ≠ 0) : a / c ≤ b ↔ a ≤ b*c := by rw [div_eq_mul_inv, mul_inv_le_iff₀ hc] /-- `equiv.mul_left₀` as an order_iso on a `linear_ordered_comm_group_with_zero.`. Note that `order_iso.mul_left₀` refers to the `linear_ordered_field` version. -/ @[simps apply to_equiv {simp_rhs := tt}] def order_iso.mul_left₀' {a : α} (ha : a ≠ 0) : α ≃o α := { map_rel_iff' := λ x y, mul_le_mul_left₀ ha, ..equiv.mul_left₀ a ha } lemma order_iso.mul_left₀'_symm {a : α} (ha : a ≠ 0) : (order_iso.mul_left₀' ha).symm = order_iso.mul_left₀' (inv_ne_zero ha) := by { ext, refl } /-- `equiv.mul_right₀` as an order_iso on a `linear_ordered_comm_group_with_zero.`. Note that `order_iso.mul_right₀` refers to the `linear_ordered_field` version. -/ @[simps apply to_equiv {simp_rhs := tt}] def order_iso.mul_right₀' {a : α} (ha : a ≠ 0) : α ≃o α := { map_rel_iff' := λ _ _, mul_le_mul_right₀ ha, ..equiv.mul_right₀ a ha } lemma order_iso.mul_right₀'_symm {a : α} (ha : a ≠ 0) : (order_iso.mul_right₀' ha).symm = order_iso.mul_right₀' (inv_ne_zero ha) := by { ext, refl } instance : linear_ordered_add_comm_group_with_top (additive αᵒᵈ) := { neg_top := inv_zero, add_neg_cancel := λ a ha, mul_inv_cancel ha, ..additive.sub_neg_monoid, ..additive.linear_ordered_add_comm_monoid_with_top, ..additive.nontrivial }
8beb877031329c919983cdc410d84c9eea5a9ffa
b147e1312077cdcfea8e6756207b3fa538982e12
/group_theory/coset.lean
c82b52ef2603133bf25c88f05160b3702554af07
[ "Apache-2.0" ]
permissive
SzJS/mathlib
07836ee708ca27cd18347e1e11ce7dd5afb3e926
23a5591fca0d43ee5d49d89f6f0ee07a24a6ca29
refs/heads/master
1,584,980,332,064
1,532,063,841,000
1,532,063,841,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
6,824
lean
/- Copyright (c) 2018 Mitchell Rowett. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mitchell Rowett, Scott Morrison -/ import group_theory.subgroup data.equiv.basic data.quot open set function variable {α : Type*} def left_coset [has_mul α] (a : α) (s : set α) : set α := (λ x, a * x) '' s def right_coset [has_mul α] (s : set α) (a : α) : set α := (λ x, x * a) '' s local infix ` *l `:70 := left_coset local infix ` *r `:70 := right_coset section coset_mul variable [has_mul α] lemma mem_left_coset {s : set α} {x : α} (a : α) (hxS : x ∈ s) : a * x ∈ a *l s := mem_image_of_mem (λ b : α, a * b) hxS lemma mem_right_coset {s : set α} {x : α} (a : α) (hxS : x ∈ s) : x * a ∈ s *r a := mem_image_of_mem (λ b : α, b * a) hxS def left_coset_equiv (s : set α) (a b : α) := a *l s = b *l s lemma left_coset_equiv_rel (s : set α) : equivalence (left_coset_equiv s) := mk_equivalence (left_coset_equiv s) (λ a, rfl) (λ a b, eq.symm) (λ a b c, eq.trans) end coset_mul section coset_semigroup variable [semigroup α] @[simp] lemma left_coset_assoc (s : set α) (a b : α) : a *l (b *l s) = (a * b) *l s := by simp [left_coset, right_coset, (image_comp _ _ _).symm, function.comp, mul_assoc] @[simp] lemma right_coset_assoc (s : set α) (a b : α) : s *r a *r b = s *r (a * b) := by simp [left_coset, right_coset, (image_comp _ _ _).symm, function.comp, mul_assoc] lemma left_coset_right_coset (s : set α) (a b : α) : a *l s *r b = a *l (s *r b) := by simp [left_coset, right_coset, (image_comp _ _ _).symm, function.comp, mul_assoc] end coset_semigroup section coset_monoid variables [monoid α] (s : set α) @[simp] lemma one_left_coset : 1 *l s = s := set.ext $ by simp [left_coset] @[simp] lemma right_coset_one : s *r 1 = s := set.ext $ by simp [right_coset] end coset_monoid section coset_submonoid open is_submonoid variables [monoid α] (s : set α) [is_submonoid s] lemma mem_own_left_coset (a : α) : a ∈ a *l s := suffices a * 1 ∈ a *l s, by simpa, mem_left_coset a (one_mem s) lemma mem_own_right_coset (a : α) : a ∈ s *r a := suffices 1 * a ∈ s *r a, by simpa, mem_right_coset a (one_mem s) lemma mem_left_coset_left_coset {a : α} (ha : a *l s = s) : a ∈ s := by rw [←ha]; exact mem_own_left_coset s a lemma mem_right_coset_right_coset {a : α} (ha : s *r a = s) : a ∈ s := by rw [←ha]; exact mem_own_right_coset s a end coset_submonoid section coset_group variables [group α] {s : set α} {x : α} lemma mem_left_coset_iff (a : α) : x ∈ a *l s ↔ a⁻¹ * x ∈ s := iff.intro (assume ⟨b, hb, eq⟩, by simp [eq.symm, hb]) (assume h, ⟨a⁻¹ * x, h, by simp⟩) lemma mem_right_coset_iff (a : α) : x ∈ s *r a ↔ x * a⁻¹ ∈ s := iff.intro (assume ⟨b, hb, eq⟩, by simp [eq.symm, hb]) (assume h, ⟨x * a⁻¹, h, by simp⟩) end coset_group section coset_subgroup open is_submonoid open is_subgroup variables [group α] (s : set α) [is_subgroup s] lemma left_coset_mem_left_coset {a : α} (ha : a ∈ s) : a *l s = s := set.ext $ by simp [mem_left_coset_iff, mul_mem_cancel_right s (inv_mem ha)] lemma right_coset_mem_right_coset {a : α} (ha : a ∈ s) : s *r a = s := set.ext $ assume b, by simp [mem_right_coset_iff, mul_mem_cancel_left s (inv_mem ha)] theorem normal_of_eq_cosets [normal_subgroup s] (g : α) : g *l s = s *r g := set.ext $ assume a, by simp [mem_left_coset_iff, mem_right_coset_iff]; rw [mem_norm_comm_iff] theorem eq_cosets_of_normal (h : ∀ g, g *l s = s *r g) : normal_subgroup s := ⟨assume a ha g, show g * a * g⁻¹ ∈ s, by rw [← mem_right_coset_iff, ← h]; exact mem_left_coset g ha⟩ theorem normal_iff_eq_cosets : normal_subgroup s ↔ ∀ g, g *l s = s *r g := ⟨@normal_of_eq_cosets _ _ s _, eq_cosets_of_normal s⟩ end coset_subgroup def left_rel [group α] (s : set α) [is_subgroup s] : setoid α := ⟨λ x y, x⁻¹ * y ∈ s, assume x, by simp [is_submonoid.one_mem], assume x y hxy, have (x⁻¹ * y)⁻¹ ∈ s, from is_subgroup.inv_mem hxy, by simpa using this, assume x y z hxy hyz, have x⁻¹ * y * (y⁻¹ * z) ∈ s, from is_submonoid.mul_mem hxy hyz, by simpa [mul_assoc] using this⟩ def left_cosets [group α] (s : set α) [is_subgroup s] : Type* := quotient (left_rel s) namespace left_cosets local attribute [instance] left_rel instance [group α] (s : set α) [is_subgroup s] : inhabited (left_cosets s) := ⟨⟦1⟧⟩ lemma eq_class_eq_left_coset [group α] (s : set α) [is_subgroup s] (g : α) : {x | ⟦x⟧ = ⟦g⟧} = left_coset g s := set.ext $ λ z, by simp [eq_comm, mem_left_coset_iff]; refl end left_cosets namespace is_subgroup variables [group α] {s : set α} def left_coset_equiv_subgroup (g : α) : left_coset g s ≃ s := ⟨λ x, ⟨g⁻¹ * x.1, (mem_left_coset_iff _).1 x.2⟩, λ x, ⟨g * x.1, x.1, x.2, rfl⟩, λ ⟨x, hx⟩, subtype.eq $ by simp, λ ⟨g, hg⟩, subtype.eq $ by simp⟩ local attribute [instance] left_rel noncomputable def group_equiv_left_cosets_times_subgroup (hs : is_subgroup s) : α ≃ (left_cosets s × s) := calc α ≃ Σ L : left_cosets s, {x // ⟦x⟧ = L} : equiv.equiv_fib quotient.mk ... ≃ Σ L : left_cosets s, left_coset (quotient.out L) s : equiv.sigma_congr_right (λ L, by rw ← left_cosets.eq_class_eq_left_coset; simp) ... ≃ Σ L : left_cosets s, s : equiv.sigma_congr_right (λ L, left_coset_equiv_subgroup _) ... ≃ (left_cosets s × s) : equiv.sigma_equiv_prod _ _ end is_subgroup section quotient_group local attribute [instance] left_rel normal_subgroup.to_is_subgroup instance [group α] (s : set α) [normal_subgroup s] : group (left_cosets s) := { one := ⟦1⟧, mul := λ a b, quotient.lift_on₂ a b (λ a b, ⟦a * b⟧) (λ a₁ a₂ b₁ b₂ hab₁ hab₂, quotient.sound ((is_subgroup.mul_mem_cancel_left s (is_subgroup.inv_mem hab₂)).1 (by rw [mul_inv_rev, mul_inv_rev, ← mul_assoc (a₂⁻¹ * a₁⁻¹), mul_assoc _ b₂, ← mul_assoc b₂, mul_inv_self, one_mul, mul_assoc (a₂⁻¹)]; exact normal_subgroup.normal _ hab₁ _))), mul_assoc := λ a b c, quotient.induction_on₃ a b c (λ a b c, show ⟦_⟧ = ⟦_⟧, by rw mul_assoc), one_mul := λ a, quotient.induction_on a (λ a, show ⟦_⟧ = ⟦_⟧, by rw one_mul), mul_one := λ a, quotient.induction_on a (λ a, show ⟦_⟧ = ⟦_⟧, by rw mul_one), inv := λ a, quotient.lift_on a (λ a, ⟦a⁻¹⟧) (λ a b hab, quotient.sound begin show a⁻¹⁻¹ * b⁻¹ ∈ s, rw ← mul_inv_rev, exact is_subgroup.inv_mem (is_subgroup.mem_norm_comm hab) end), mul_left_inv := λ a, quotient.induction_on a (λ a, show ⟦_⟧ = ⟦_⟧, by rw inv_mul_self) } end quotient_group
9bdcef6896f47340f0db8c898a6922b952e0cc0b
500f65bb93c499cd35c3254d894d762208cae042
/src/tactic/sanity_check.lean
50552319a8227c26147266618a3a7787f893c6bc
[ "Apache-2.0" ]
permissive
PatrickMassot/mathlib
c39dc0ff18bbde42f1c93a1642f6e429adad538c
45df75b3c9da159fe3192fa7f769dfbec0bd6bda
refs/heads/master
1,623,168,646,390
1,566,940,765,000
1,566,940,765,000
115,220,590
0
1
null
1,514,061,524,000
1,514,061,524,000
null
UTF-8
Lean
false
false
7,233
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 -/ import tactic.core /-! # sanity_check command This file defines the `#sanity_check` and `#sanity_check_mathlib` commands, to spot common mistakes in the current file or in all of mathlib, respectively. Currently this will check for unused arguments in declarations and whether a declaration is incorrectly marked as a def/lemma. ## Tags sanity check, sanity_check, cleanup, command, tactic -/ universe variable u open expr tactic native reserve notation `#sanity_check` reserve notation `#sanity_check_mathlib` setup_tactic_parser /-- Find all (non-internal) declarations where tac returns `some x` and list them. -/ meta def fold_over_with_cond {α} (tac : declaration → tactic (option α)) : tactic (list (declaration × α)) := do e ← get_env, e.mfold [] $ λ d ds, if name.is_internal d.to_name then return ds else do o ← tac d, if h : o.is_some then return $ (d, option.get h)::ds else return ds /-- Find all declarations where tac returns `some x` and sort the resulting list by file name. -/ meta def fold_over_with_cond_sorted {α} (tac : declaration → tactic (option α)) : tactic (list (string × list (declaration × α))) := do e ← get_env, ds ← fold_over_with_cond tac, let ds₂ := rb_lmap.of_list (ds.map (λ x, ((e.decl_olean x.1.to_name).get_or_else "", x))), return $ ds₂.to_list /-- Make the output of `fold_over_with_cond` printable, in the following form: #print <name> -- <elt of α> -/ meta def print_decls {α} [has_to_format α] (ds : list (declaration × α)) : format := ds.foldl (λ f x, f ++ format.line ++ to_fmt "#print " ++ to_fmt x.1.to_name ++ " -- " ++ to_fmt x.2) format.nil /-- Make the output of `fold_over_with_cond_sorted` printable, with the file path + name inserted.-/ meta def print_decls_sorted {α} [has_to_format α] (ds : list (string × list (declaration × α))) : format := ds.foldl (λ f x, f ++ format.line ++ format.line ++ to_fmt "-- " ++ to_fmt x.1 ++ print_decls x.2) format.nil /- Print all (non-internal) declarations where tac return `some x`-/ meta def print_all_decls {α} [has_to_format α] (tac : declaration → tactic (option α)) : tactic format := print_decls_sorted <$> fold_over_with_cond_sorted tac /- Print (non-internal) declarations in the current file where tac return `some x`-/ meta def print_decls_current_file {α} [has_to_format α] (tac : declaration → tactic (option α)) : tactic format := print_decls <$> fold_over_with_cond (λ d, d.in_current_file >>= λ b, if b then tac d else return none) /- Print (non-internal) declarations in mathlib where tac return `some x` -/ meta def print_decls_mathlib {α} [has_to_format α] (tac : declaration → tactic (option α)) : tactic format := do ml ← get_mathlib_dir, f ← fold_over_with_cond_sorted (λ d, is_in_mathlib_aux ml d.to_name >>= λ b, if b then tac d else return none), return $ print_decls_sorted $ f.map (λ x, ⟨x.1.popn ml.length, x.2⟩) /-- Auxilliary definition for `check_unused_arguments_aux` -/ meta def check_unused_arguments_aux : list ℕ → ℕ → ℕ → expr → list ℕ := λ l n n_max e, if n > n_max then l else if ¬is_lambda e then if e = const `true.intro [] ∨ e = const `trivial [] then [] else l -- don't return if the target is true else let b := e.binding_body in let l' := if b.has_var_idx 0 then l else n :: l in check_unused_arguments_aux l' (n+1) n_max b /-- Check which arguments of a declaration are not used. Prints a list of natural numbers corresponding to which arguments are not used (e.g. this outputs [1, 4] if the first and fourth arguments are unused). We return [] if the body of `e` is `true.intro` or `trivial`, to filter many automatically generated declarations. We don't print arguments that are larger than the arity of the type of the declaration. -/ meta def check_unused_arguments (d : declaration) : option (list ℕ) := let l := check_unused_arguments_aux [] 1 (d.type.pi_arity) d.value in if l = [] then none else l.reverse /-- Get all declarations with unused arguments -/ meta def get_all_unused_args : tactic unit := print_all_decls (return ∘ check_unused_arguments) >>= trace /-- Get all declarations in mathlib with unused arguments -/ meta def get_all_unused_args_mathlib : tactic unit := print_decls_mathlib (return ∘ check_unused_arguments) >>= trace /-- Get all declarations in current file with unused arguments. -/ meta def get_all_unused_args_current_file : tactic unit := print_decls_current_file (return ∘ check_unused_arguments) >>= trace /-- Checks whether the correct declaration constructor (definition of theorem) by comparing it to its sort. This will automatically remove all instances and automatically generated definitions -/ meta def incorrect_def_lemma (d : declaration) : tactic (option string) := do e ← get_env, expr.sort n ← infer_type d.type, if d.is_constant ∨ d.is_axiom ∨ (e.is_projection d.to_name).is_some ∨ (d.is_definition : bool) = (n ≠ level.zero : bool) ∨ (d.to_name.last ∈ ["inj","inj_eq","sizeof_spec"] ∧ e.is_constructor d.to_name.get_prefix) ∨ (d.to_name.last ∈ ["dcases_on","drec_on","drec","cases_on","rec_on","binduction_on"] ∧ e.is_inductive d.to_name.get_prefix) then return none else (option.is_some <$> try_core (has_attribute `instance d.to_name)) >>= λ b, return $ if b then none else if (d.is_definition : bool) then "is a def, should be a lemma/theorem" else "is a lemma/theorem, should be a def" /-- Get all declarations in mathlib incorrectly marked as def/lemma -/ meta def incorrect_def_lemma_mathlib : tactic unit := print_decls_mathlib (return ∘ check_unused_arguments) >>= trace /-- The command `#sanity_check` at the bottom of a file will warn you about some common mistakes in that file. -/ @[user_command] meta def sanity_check_cmd (_ : parse $ tk "#sanity_check") : parser unit := do trace "/- Note: This command is still in development. -/\n", f ← print_decls_current_file (return ∘ check_unused_arguments), if f.is_nil then trace "/- OK: No unused arguments in the current file. -/" else trace (to_fmt "/- Unused arguments in the current file: -/" ++ f ++ format.line), f ← print_decls_current_file incorrect_def_lemma, if f.is_nil then trace "/-OK: All declarations correctly marked as def/lemma -/" else trace (to_fmt "/- Declarations incorrectly marked as def/lemma: -/" ++ f ++ format.line), skip /-- The command `#sanity_check_mathlib` checks all of mathlib for certain mistakes. -/ @[user_command] meta def sanity_check_mathlib_cmd (_ : parse $ tk "#sanity_check_mathlib") : parser unit := do trace "/- Note: This command is still in development. -/\n", f ← print_decls_mathlib (return ∘ check_unused_arguments), trace (to_fmt "/- UNUSED ARGUMENTS: -/" ++ f ++ format.line), f ← print_decls_mathlib incorrect_def_lemma, trace (to_fmt "/- INCORRECT DEF/LEMMA: -/" ++ f ++ format.line), skip -- #sanity_check -- #sanity_check_mathlib
1729093cd42909882fd847b6bb69a2b5bbeed35e
1abd1ed12aa68b375cdef28959f39531c6e95b84
/src/analysis/inner_product_space/dual.lean
285d397dc7f6b21615964e640b9c20af66a6c542
[ "Apache-2.0" ]
permissive
jumpy4/mathlib
d3829e75173012833e9f15ac16e481e17596de0f
af36f1a35f279f0e5b3c2a77647c6bf2cfd51a13
refs/heads/master
1,693,508,842,818
1,636,203,271,000
1,636,203,271,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
5,191
lean
/- Copyright (c) 2020 Frédéric Dupuis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Frédéric Dupuis -/ import analysis.inner_product_space.projection import analysis.normed_space.dual /-! # The Fréchet-Riesz representation theorem We consider an inner product space `E` over `𝕜`, which is either `ℝ` or `ℂ`. We define `to_dual_map`, a conjugate-linear isometric embedding of `E` into its dual, which maps an element `x` of the space to `λ y, ⟪x, y⟫`. Under the hypothesis of completeness (i.e., for Hilbert spaces), we upgrade this to `to_dual`, a conjugate-linear isometric *equivalence* of `E` onto its dual; that is, we establish the surjectivity of `to_dual_map`. This is the Fréchet-Riesz representation theorem: every element of the dual of a Hilbert space `E` has the form `λ u, ⟪x, u⟫` for some `x : E`. ## References * [M. Einsiedler and T. Ward, *Functional Analysis, Spectral Theory, and Applications*] [EinsiedlerWard2017] ## Tags dual, Fréchet-Riesz -/ noncomputable theory open_locale classical universes u v namespace inner_product_space open is_R_or_C continuous_linear_map variables (𝕜 : Type*) variables (E : Type*) [is_R_or_C 𝕜] [inner_product_space 𝕜 E] local notation `⟪`x`, `y`⟫` := @inner 𝕜 E _ x y local postfix `†`:90 := star_ring_aut /-- An element `x` of an inner product space `E` induces an element of the dual space `dual 𝕜 E`, the map `λ y, ⟪x, y⟫`; moreover this operation is a conjugate-linear isometric embedding of `E` into `dual 𝕜 E`. If `E` is complete, this operation is surjective, hence a conjugate-linear isometric equivalence; see `to_dual`. -/ def to_dual_map : E →ₗᵢ⋆[𝕜] normed_space.dual 𝕜 E := { to_fun := λ x, linear_map.mk_continuous { to_fun := λ y, ⟪x, y⟫, map_add' := λ _ _, inner_add_right, map_smul' := λ _ _, inner_smul_right } ∥x∥ (λ y, by { rw [is_R_or_C.norm_eq_abs], exact abs_inner_le_norm _ _ }), map_add' := λ x y, by { ext z, simp [inner_add_left] }, map_smul' := λ c y, by { ext z, simp [inner_smul_left] }, norm_map' := λ x, begin refine le_antisymm _ _, { exact linear_map.mk_continuous_norm_le _ (norm_nonneg _) _ }, { cases eq_or_lt_of_le (norm_nonneg x) with h h, { have : x = 0 := norm_eq_zero.mp (eq.symm h), simp [this] }, { refine (mul_le_mul_right h).mp _, calc ∥x∥ * ∥x∥ = ∥x∥ ^ 2 : by ring ... = re ⟪x, x⟫ : norm_sq_eq_inner _ ... ≤ abs ⟪x, x⟫ : re_le_abs _ ... = ∥linear_map.mk_continuous _ _ _ x∥ : by simp [norm_eq_abs] ... ≤ ∥linear_map.mk_continuous _ _ _∥ * ∥x∥ : le_op_norm _ x } } end } variables {E} @[simp] lemma to_dual_map_apply {x y : E} : to_dual_map 𝕜 E x y = ⟪x, y⟫ := rfl variables (E) [complete_space E] /-- Fréchet-Riesz representation: any `ℓ` in the dual of a Hilbert space `E` is of the form `λ u, ⟪y, u⟫` for some `y : E`, i.e. `to_dual_map` is surjective. -/ def to_dual : E ≃ₗᵢ⋆[𝕜] normed_space.dual 𝕜 E := linear_isometry_equiv.of_surjective (to_dual_map 𝕜 E) begin intros ℓ, set Y := ker ℓ with hY, by_cases htriv : Y = ⊤, { have hℓ : ℓ = 0, { have h' := linear_map.ker_eq_top.mp htriv, rw [←coe_zero] at h', apply coe_injective, exact h' }, exact ⟨0, by simp [hℓ]⟩ }, { have Ycomplete := is_complete_ker ℓ, rw [← submodule.orthogonal_eq_bot_iff Ycomplete, ←hY] at htriv, change Yᗮ ≠ ⊥ at htriv, rw [submodule.ne_bot_iff] at htriv, obtain ⟨z : E, hz : z ∈ Yᗮ, z_ne_0 : z ≠ 0⟩ := htriv, refine ⟨((ℓ z)† / ⟪z, z⟫) • z, _⟩, ext x, have h₁ : (ℓ z) • x - (ℓ x) • z ∈ Y, { rw [mem_ker, map_sub, map_smul, map_smul, algebra.id.smul_eq_mul, algebra.id.smul_eq_mul, mul_comm], exact sub_self (ℓ x * ℓ z) }, have h₂ : (ℓ z) * ⟪z, x⟫ = (ℓ x) * ⟪z, z⟫, { have h₃ := calc 0 = ⟪z, (ℓ z) • x - (ℓ x) • z⟫ : by { rw [(Y.mem_orthogonal' z).mp hz], exact h₁ } ... = ⟪z, (ℓ z) • x⟫ - ⟪z, (ℓ x) • z⟫ : by rw [inner_sub_right] ... = (ℓ z) * ⟪z, x⟫ - (ℓ x) * ⟪z, z⟫ : by simp [inner_smul_right], exact sub_eq_zero.mp (eq.symm h₃) }, have h₄ := calc ⟪((ℓ z)† / ⟪z, z⟫) • z, x⟫ = (ℓ z) / ⟪z, z⟫ * ⟪z, x⟫ : by simp [inner_smul_left, ring_equiv.map_div, conj_conj] ... = (ℓ z) * ⟪z, x⟫ / ⟪z, z⟫ : by rw [←div_mul_eq_mul_div] ... = (ℓ x) * ⟪z, z⟫ / ⟪z, z⟫ : by rw [h₂] ... = ℓ x : begin have : ⟪z, z⟫ ≠ 0, { change z = 0 → false at z_ne_0, rwa ←inner_self_eq_zero at z_ne_0 }, field_simp [this] end, exact h₄ } end variables {E} @[simp] lemma to_dual_apply {x y : E} : to_dual 𝕜 E x y = ⟪x, y⟫ := rfl end inner_product_space
2249b2730a0c9dbe68a734d1c24e5ddd0d7ee18b
82e44445c70db0f03e30d7be725775f122d72f3e
/src/data/fintype/basic.lean
a4af095ec33017a300df9582f30142c9736304ef
[ "Apache-2.0" ]
permissive
stjordanis/mathlib
51e286d19140e3788ef2c470bc7b953e4991f0c9
2568d41bca08f5d6bf39d915434c8447e21f42ee
refs/heads/master
1,631,748,053,501
1,627,938,886,000
1,627,938,886,000
228,728,358
0
0
Apache-2.0
1,576,630,588,000
1,576,630,587,000
null
UTF-8
Lean
false
false
72,854
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.array.lemmas import data.finset.pi import data.finset.powerset import data.sym.basic import group_theory.perm.basic import order.well_founded import tactic.wlog /-! # Finite types This file defines a typeclass to state that a type is finite. ## Main declarations * `fintype α`: Typeclass saying that a type is finite. It takes as fields a `finset` and a proof that all terms of type `α` are in it. * `finset.univ`: The finset of all elements of a fintype. * `fintype.card α`: Cardinality of a fintype. Equal to `finset.univ.card`. * `perms_of_finset s`: The finset of permutations of the finset `s`. * `fintype.trunc_equiv_fin`: A fintype `α` is computably equivalent to `fin (card α)`. The `trunc`-free, noncomputable version is `fintype.equiv_fin`. * `fintype.trunc_equiv_of_card_eq` `fintype.equiv_of_card_eq`: Two fintypes of same cardinality are equivalent. See above. * `fin.equiv_iff_eq`: `fin m ≃ fin n` iff `m = n`. * `infinite α`: Typeclass saying that a type is infinite. Defined as `fintype α → false`. * `not_fintype`: No `fintype` has an `infinite` instance. * `infinite.nat_embedding`: An embedding of `ℕ` into an infinite type. We also provide the following versions of the pigeonholes principle. * `fintype.exists_ne_map_eq_of_card_lt` and `is_empty_of_card_lt`: Finitely many pigeons and pigeonholes. Weak formulation. * `fintype.exists_ne_map_eq_of_infinite`: Infinitely many pigeons in finitely many pigeonholes. Weak formulation. * `fintype.exists_infinite_fiber`: Infinitely many pigeons in finitely many pigeonholes. Strong formulation. Some more pigeonhole-like statements can be found in `data.fintype.card_embedding`. ## Instances Among others, we provide `fintype` instances for * A `subtype` of a fintype. See `fintype.subtype`. * The `option` of a fintype. * The product of two fintypes. * The sum of two fintypes. * `Prop`. and `infinite` instances for * `ℕ` * `ℤ` along with some machinery * Types which have a surjection from/an injection to a `fintype` are themselves fintypes. See `fintype.of_injective` and `fintype.of_surjective`. * Types which have an injection from/a surjection to an `infinite` type are themselves `infinite`. See `infinite.of_injective` and `infinite.of_surjective`. -/ open_locale nat universes u v variables {α β γ : Type*} /-- `fintype α` means that `α` is finite, i.e. there are only finitely many distinct elements of type `α`. The evidence of this is a finset `elems` (a list up to permutation without duplicates), together with a proof that everything of type `α` is in the list. -/ class fintype (α : Type*) := (elems [] : finset α) (complete : ∀ x : α, x ∈ elems) namespace finset variable [fintype α] /-- `univ` is the universal finite set of type `finset α` implied from the assumption `fintype α`. -/ def univ : finset α := fintype.elems α @[simp] theorem mem_univ (x : α) : x ∈ (univ : finset α) := fintype.complete x @[simp] theorem mem_univ_val : ∀ x, x ∈ (univ : finset α).1 := mem_univ @[simp] lemma coe_univ : ↑(univ : finset α) = (set.univ : set α) := by ext; simp lemma univ_nonempty_iff : (univ : finset α).nonempty ↔ nonempty α := by rw [← coe_nonempty, coe_univ, set.nonempty_iff_univ_nonempty] lemma univ_nonempty [nonempty α] : (univ : finset α).nonempty := univ_nonempty_iff.2 ‹_› lemma univ_eq_empty : (univ : finset α) = ∅ ↔ ¬nonempty α := by rw [← univ_nonempty_iff, nonempty_iff_ne_empty, ne.def, not_not] lemma univ_eq_empty' : (univ : finset α) = ∅ ↔ is_empty α := univ_eq_empty.trans (not_nonempty_iff) @[simp] theorem subset_univ (s : finset α) : s ⊆ univ := λ a _, mem_univ a instance : order_top (finset α) := { top := univ, le_top := subset_univ, .. finset.partial_order } instance [decidable_eq α] : boolean_algebra (finset α) := { compl := λ s, univ \ s, inf_compl_le_bot := λ s x hx, by simpa using hx, top_le_sup_compl := λ s x hx, by simp, sdiff_eq := λ s t, by simp [ext_iff, compl], ..finset.order_top, ..finset.generalized_boolean_algebra } lemma compl_eq_univ_sdiff [decidable_eq α] (s : finset α) : sᶜ = univ \ s := rfl @[simp] lemma mem_compl [decidable_eq α] {s : finset α} {x : α} : x ∈ sᶜ ↔ x ∉ s := by simp [compl_eq_univ_sdiff] @[simp, norm_cast] lemma coe_compl [decidable_eq α] (s : finset α) : ↑(sᶜ) = (↑s : set α)ᶜ := set.ext $ λ x, mem_compl @[simp] theorem union_compl [decidable_eq α] (s : finset α) : s ∪ sᶜ = finset.univ := sup_compl_eq_top @[simp] lemma compl_filter [decidable_eq α] (p : α → Prop) [decidable_pred p] [Π x, decidable (¬p x)] : (univ.filter p)ᶜ = univ.filter (λ x, ¬p x) := (filter_not _ _).symm theorem eq_univ_iff_forall {s : finset α} : s = univ ↔ ∀ x, x ∈ s := by simp [ext_iff] lemma compl_ne_univ_iff_nonempty [decidable_eq α] (s : finset α) : sᶜ ≠ univ ↔ s.nonempty := by simp [eq_univ_iff_forall, finset.nonempty] @[simp] lemma univ_inter [decidable_eq α] (s : finset α) : univ ∩ s = s := ext $ λ a, by simp @[simp] lemma inter_univ [decidable_eq α] (s : finset α) : s ∩ univ = s := by rw [inter_comm, univ_inter] @[simp] lemma piecewise_univ [Π i : α, decidable (i ∈ (univ : finset α))] {δ : α → Sort*} (f g : Π i, δ i) : univ.piecewise f g = f := by { ext i, simp [piecewise] } lemma piecewise_compl [decidable_eq α] (s : finset α) [Π i : α, decidable (i ∈ s)] [Π i : α, decidable (i ∈ sᶜ)] {δ : α → Sort*} (f g : Π i, δ i) : sᶜ.piecewise f g = s.piecewise g f := by { ext i, simp [piecewise] } lemma univ_map_equiv_to_embedding {α β : Type*} [fintype α] [fintype β] (e : α ≃ β) : univ.map e.to_embedding = univ := eq_univ_iff_forall.mpr (λ b, mem_map.mpr ⟨e.symm b, mem_univ _, by simp⟩) @[simp] lemma univ_filter_exists (f : α → β) [fintype β] [decidable_pred (λ y, ∃ x, f x = y)] [decidable_eq β] : finset.univ.filter (λ y, ∃ x, f x = y) = finset.univ.image f := by { ext, simp } /-- Note this is a special case of `(finset.image_preimage f univ _).symm`. -/ lemma univ_filter_mem_range (f : α → β) [fintype β] [decidable_pred (λ y, y ∈ set.range f)] [decidable_eq β] : finset.univ.filter (λ y, y ∈ set.range f) = finset.univ.image f := univ_filter_exists f /-- A special case of `finset.sup_eq_supr` that omits the useless `x ∈ univ` binder. -/ lemma sup_univ_eq_supr [complete_lattice β] (f : α → β) : finset.univ.sup f = supr f := (sup_eq_supr _ f).trans $ congr_arg _ $ funext $ λ a, supr_pos (mem_univ _) /-- A special case of `finset.inf_eq_infi` that omits the useless `x ∈ univ` binder. -/ lemma inf_univ_eq_infi [complete_lattice β] (f : α → β) : finset.univ.inf f = infi f := sup_univ_eq_supr (by exact f : α → order_dual β) end finset open finset function namespace fintype instance decidable_pi_fintype {α} {β : α → Type*} [∀ a, decidable_eq (β a)] [fintype α] : decidable_eq (Π a, β a) := λ f g, decidable_of_iff (∀ a ∈ fintype.elems α, f a = g a) (by simp [function.funext_iff, fintype.complete]) instance decidable_forall_fintype {p : α → Prop} [decidable_pred p] [fintype α] : decidable (∀ a, p a) := decidable_of_iff (∀ a ∈ @univ α _, p a) (by simp) instance decidable_exists_fintype {p : α → Prop} [decidable_pred p] [fintype α] : decidable (∃ a, p a) := decidable_of_iff (∃ a ∈ @univ α _, p a) (by simp) instance decidable_mem_range_fintype [fintype α] [decidable_eq β] (f : α → β) : decidable_pred (∈ set.range f) := λ x, fintype.decidable_exists_fintype section bundled_homs instance decidable_eq_equiv_fintype [decidable_eq β] [fintype α] : decidable_eq (α ≃ β) := λ a b, decidable_of_iff (a.1 = b.1) equiv.coe_fn_injective.eq_iff instance decidable_eq_embedding_fintype [decidable_eq β] [fintype α] : decidable_eq (α ↪ β) := λ a b, decidable_of_iff (⇑a = b) function.embedding.coe_injective.eq_iff @[to_additive] instance decidable_eq_one_hom_fintype [decidable_eq β] [fintype α] [has_one α] [has_one β]: decidable_eq (one_hom α β) := λ a b, decidable_of_iff (⇑a = b) (injective.eq_iff one_hom.coe_inj) @[to_additive] instance decidable_eq_mul_hom_fintype [decidable_eq β] [fintype α] [has_mul α] [has_mul β]: decidable_eq (mul_hom α β) := λ a b, decidable_of_iff (⇑a = b) (injective.eq_iff mul_hom.coe_inj) @[to_additive] instance decidable_eq_monoid_hom_fintype [decidable_eq β] [fintype α] [mul_one_class α] [mul_one_class β]: decidable_eq (α →* β) := λ a b, decidable_of_iff (⇑a = b) (injective.eq_iff monoid_hom.coe_inj) instance decidable_eq_monoid_with_zero_hom_fintype [decidable_eq β] [fintype α] [mul_zero_one_class α] [mul_zero_one_class β]: decidable_eq (monoid_with_zero_hom α β) := λ a b, decidable_of_iff (⇑a = b) (injective.eq_iff monoid_with_zero_hom.coe_inj) instance decidable_eq_ring_hom_fintype [decidable_eq β] [fintype α] [semiring α] [semiring β]: decidable_eq (α →+* β) := λ a b, decidable_of_iff (⇑a = b) (injective.eq_iff ring_hom.coe_inj) end bundled_homs instance decidable_injective_fintype [decidable_eq α] [decidable_eq β] [fintype α] : decidable_pred (injective : (α → β) → Prop) := λ x, by unfold injective; apply_instance instance decidable_surjective_fintype [decidable_eq β] [fintype α] [fintype β] : decidable_pred (surjective : (α → β) → Prop) := λ x, by unfold surjective; apply_instance instance decidable_bijective_fintype [decidable_eq α] [decidable_eq β] [fintype α] [fintype β] : decidable_pred (bijective : (α → β) → Prop) := λ x, by unfold bijective; apply_instance instance decidable_right_inverse_fintype [decidable_eq α] [fintype α] (f : α → β) (g : β → α) : decidable (function.right_inverse f g) := show decidable (∀ x, g (f x) = x), by apply_instance instance decidable_left_inverse_fintype [decidable_eq β] [fintype β] (f : α → β) (g : β → α) : decidable (function.left_inverse f g) := show decidable (∀ x, f (g x) = x), by apply_instance lemma exists_max [fintype α] [nonempty α] {β : Type*} [linear_order β] (f : α → β) : ∃ x₀ : α, ∀ x, f x ≤ f x₀ := by simpa using exists_max_image univ f univ_nonempty lemma exists_min [fintype α] [nonempty α] {β : Type*} [linear_order β] (f : α → β) : ∃ x₀ : α, ∀ x, f x₀ ≤ f x := by simpa using exists_min_image univ f univ_nonempty /-- Construct a proof of `fintype α` from a universal multiset -/ def of_multiset [decidable_eq α] (s : multiset α) (H : ∀ x : α, x ∈ s) : fintype α := ⟨s.to_finset, by simpa using H⟩ /-- Construct a proof of `fintype α` from a universal list -/ def of_list [decidable_eq α] (l : list α) (H : ∀ x : α, x ∈ l) : fintype α := ⟨l.to_finset, by simpa using H⟩ theorem exists_univ_list (α) [fintype α] : ∃ l : list α, l.nodup ∧ ∀ x : α, x ∈ l := let ⟨l, e⟩ := quotient.exists_rep (@univ α _).1 in by have := and.intro univ.2 mem_univ_val; exact ⟨_, by rwa ←e at this⟩ /-- `card α` is the number of elements in `α`, defined when `α` is a fintype. -/ def card (α) [fintype α] : ℕ := (@univ α _).card /-- If `l` lists all the elements of `α` without duplicates, then `α ≃ fin (l.length)`. -/ def equiv_fin_of_forall_mem_list {α} [decidable_eq α] {l : list α} (h : ∀ x : α, x ∈ l) (nd : l.nodup) : α ≃ fin (l.length) := ⟨λ a, ⟨_, list.index_of_lt_length.2 (h a)⟩, λ i, l.nth_le i.1 i.2, λ a, by simp, λ ⟨i, h⟩, fin.eq_of_veq $ list.nodup_iff_nth_le_inj.1 nd _ _ (list.index_of_lt_length.2 (list.nth_le_mem _ _ _)) h $ by simp⟩ /-- There is (computably) a bijection between `α` and `fin (card α)`. Since it is not unique, and depends on which permutation of the universe list is used, the bijection is wrapped in `trunc` to preserve computability. See `fintype.equiv_fin` for the noncomputable version, and `fintype.trunc_equiv_fin_of_card_eq` and `fintype.equiv_fin_of_card_eq` for an equiv `α ≃ fin n` given `fintype.card α = n`. -/ def trunc_equiv_fin (α) [decidable_eq α] [fintype α] : trunc (α ≃ fin (card α)) := by unfold card finset.card; exact quot.rec_on_subsingleton (@univ α _).1 (λ l (h : ∀ x : α, x ∈ l) (nd : l.nodup), trunc.mk (equiv_fin_of_forall_mem_list h nd)) mem_univ_val univ.2 /-- There is a (noncomputable) bijection between `α` and `fin (card α)`. See `fintype.trunc_equiv_fin` for the computable version, and `fintype.trunc_equiv_fin_of_card_eq` and `fintype.equiv_fin_of_card_eq` for an equiv `α ≃ fin n` given `fintype.card α = n`. -/ noncomputable def equiv_fin (α) [fintype α] : α ≃ fin (card α) := by { letI := classical.dec_eq α, exact (trunc_equiv_fin α).out } instance (α : Type*) : subsingleton (fintype α) := ⟨λ ⟨s₁, h₁⟩ ⟨s₂, h₂⟩, by congr; simp [finset.ext_iff, h₁, h₂]⟩ /-- Given a predicate that can be represented by a finset, the subtype associated to the predicate is a fintype. -/ protected def subtype {p : α → Prop} (s : finset α) (H : ∀ x : α, x ∈ s ↔ p x) : fintype {x // p x} := ⟨⟨multiset.pmap subtype.mk s.1 (λ x, (H x).1), multiset.nodup_pmap (λ a _ b _, congr_arg subtype.val) s.2⟩, λ ⟨x, px⟩, multiset.mem_pmap.2 ⟨x, (H x).2 px, rfl⟩⟩ theorem subtype_card {p : α → Prop} (s : finset α) (H : ∀ x : α, x ∈ s ↔ p x) : @card {x // p x} (fintype.subtype s H) = s.card := multiset.card_pmap _ _ _ theorem card_of_subtype {p : α → Prop} (s : finset α) (H : ∀ x : α, x ∈ s ↔ p x) [fintype {x // p x}] : card {x // p x} = s.card := by { rw ← subtype_card s H, congr } /-- Construct a fintype from a finset with the same elements. -/ def of_finset {p : set α} (s : finset α) (H : ∀ x, x ∈ s ↔ x ∈ p) : fintype p := fintype.subtype s H @[simp] theorem card_of_finset {p : set α} (s : finset α) (H : ∀ x, x ∈ s ↔ x ∈ p) : @fintype.card p (of_finset s H) = s.card := fintype.subtype_card s H theorem card_of_finset' {p : set α} (s : finset α) (H : ∀ x, x ∈ s ↔ x ∈ p) [fintype p] : fintype.card p = s.card := by rw ←card_of_finset s H; congr /-- If `f : α → β` is a bijection and `α` is a fintype, then `β` is also a fintype. -/ def of_bijective [fintype α] (f : α → β) (H : function.bijective f) : fintype β := ⟨univ.map ⟨f, H.1⟩, λ b, let ⟨a, e⟩ := H.2 b in e ▸ mem_map_of_mem _ (mem_univ _)⟩ /-- If `f : α → β` is a surjection and `α` is a fintype, then `β` is also a fintype. -/ def of_surjective [decidable_eq β] [fintype α] (f : α → β) (H : function.surjective f) : fintype β := ⟨univ.image f, λ b, let ⟨a, e⟩ := H b in e ▸ mem_image_of_mem _ (mem_univ _)⟩ end fintype section inv namespace function variables [fintype α] [decidable_eq β] namespace injective variables {f : α → β} (hf : function.injective f) /-- The inverse of an `hf : injective` function `f : α → β`, of the type `↥(set.range f) → α`. This is the computable version of `function.inv_fun` that requires `fintype α` and `decidable_eq β`, or the function version of applying `(equiv.of_injective f hf).symm`. This function should not usually be used for actual computation because for most cases, an explicit inverse can be stated that has better computational properties. This function computes by checking all terms `a : α` to find the `f a = b`, so it is O(N) where `N = fintype.card α`. -/ def inv_of_mem_range : set.range f → α := λ b, finset.choose (λ a, f a = b) finset.univ ((exists_unique_congr (by simp)).mp (hf.exists_unique_of_mem_range b.property)) lemma left_inv_of_inv_of_mem_range (b : set.range f) : f (hf.inv_of_mem_range b) = b := (finset.choose_spec (λ a, f a = b) _ _).right @[simp] lemma right_inv_of_inv_of_mem_range (a : α) : hf.inv_of_mem_range (⟨f a, set.mem_range_self a⟩) = a := hf (finset.choose_spec (λ a', f a' = f a) _ _).right lemma inv_fun_restrict [nonempty α] : (set.range f).restrict (inv_fun f) = hf.inv_of_mem_range := begin ext ⟨b, h⟩, apply hf, simp [hf.left_inv_of_inv_of_mem_range, @inv_fun_eq _ _ _ f b (set.mem_range.mp h)] end lemma inv_of_mem_range_surjective : function.surjective hf.inv_of_mem_range := λ a, ⟨⟨f a, set.mem_range_self a⟩, by simp⟩ end injective namespace embedding variables (f : α ↪ β) (b : set.range f) /-- The inverse of an embedding `f : α ↪ β`, of the type `↥(set.range f) → α`. This is the computable version of `function.inv_fun` that requires `fintype α` and `decidable_eq β`, or the function version of applying `(equiv.of_injective f f.injective).symm`. This function should not usually be used for actual computation because for most cases, an explicit inverse can be stated that has better computational properties. This function computes by checking all terms `a : α` to find the `f a = b`, so it is O(N) where `N = fintype.card α`. -/ def inv_of_mem_range : α := f.injective.inv_of_mem_range b @[simp] lemma left_inv_of_inv_of_mem_range : f (f.inv_of_mem_range b) = b := f.injective.left_inv_of_inv_of_mem_range b @[simp] lemma right_inv_of_inv_of_mem_range (a : α) : f.inv_of_mem_range ⟨f a, set.mem_range_self a⟩ = a := f.injective.right_inv_of_inv_of_mem_range a lemma inv_fun_restrict [nonempty α] : (set.range f).restrict (inv_fun f) = f.inv_of_mem_range := begin ext ⟨b, h⟩, apply f.injective, simp [f.left_inv_of_inv_of_mem_range, @inv_fun_eq _ _ _ f b (set.mem_range.mp h)] end lemma inv_of_mem_range_surjective : function.surjective f.inv_of_mem_range := λ a, ⟨⟨f a, set.mem_range_self a⟩, by simp⟩ end embedding end function end inv namespace fintype /-- Given an injective function to a fintype, the domain is also a fintype. This is noncomputable because injectivity alone cannot be used to construct preimages. -/ noncomputable def of_injective [fintype β] (f : α → β) (H : function.injective f) : fintype α := by letI := classical.dec; exact if hα : nonempty α then by letI := classical.inhabited_of_nonempty hα; exact of_surjective (inv_fun f) (inv_fun_surjective H) else ⟨∅, λ x, (hα ⟨x⟩).elim⟩ /-- If `f : α ≃ β` and `α` is a fintype, then `β` is also a fintype. -/ def of_equiv (α : Type*) [fintype α] (f : α ≃ β) : fintype β := of_bijective _ f.bijective theorem of_equiv_card [fintype α] (f : α ≃ β) : @card β (of_equiv α f) = card α := multiset.card_map _ _ theorem card_congr {α β} [fintype α] [fintype β] (f : α ≃ β) : card α = card β := by rw ← of_equiv_card f; congr section variables [fintype α] [fintype β] /-- If the cardinality of `α` is `n`, there is computably a bijection between `α` and `fin n`. See `fintype.equiv_fin_of_card_eq` for the noncomputable definition, and `fintype.trunc_equiv_fin` and `fintype.equiv_fin` for the bijection `α ≃ fin (card α)`. -/ def trunc_equiv_fin_of_card_eq [decidable_eq α] {n : ℕ} (h : fintype.card α = n) : trunc (α ≃ fin n) := (trunc_equiv_fin α).map (λ e, e.trans (fin.cast h).to_equiv) /-- If the cardinality of `α` is `n`, there is noncomputably a bijection between `α` and `fin n`. See `fintype.trunc_equiv_fin_of_card_eq` for the computable definition, and `fintype.trunc_equiv_fin` and `fintype.equiv_fin` for the bijection `α ≃ fin (card α)`. -/ noncomputable def equiv_fin_of_card_eq {n : ℕ} (h : fintype.card α = n) : α ≃ fin n := by { letI := classical.dec_eq α, exact (trunc_equiv_fin_of_card_eq h).out } /-- Two `fintype`s with the same cardinality are (computably) in bijection. See `fintype.equiv_of_card_eq` for the noncomputable version, and `fintype.trunc_equiv_fin_of_card_eq` and `fintype.equiv_fin_of_card_eq` for the specialization to `fin`. -/ def trunc_equiv_of_card_eq [decidable_eq α] [decidable_eq β] (h : card α = card β) : trunc (α ≃ β) := (trunc_equiv_fin_of_card_eq h).bind (λ e, (trunc_equiv_fin β).map (λ e', e.trans e'.symm)) /-- Two `fintype`s with the same cardinality are (noncomputably) in bijection. See `fintype.trunc_equiv_of_card_eq` for the computable version, and `fintype.trunc_equiv_fin_of_card_eq` and `fintype.equiv_fin_of_card_eq` for the specialization to `fin`. -/ noncomputable def equiv_of_card_eq (h : card α = card β) : α ≃ β := by { letI := classical.dec_eq α, letI := classical.dec_eq β, exact (trunc_equiv_of_card_eq h).out } end theorem card_eq {α β} [F : fintype α] [G : fintype β] : card α = card β ↔ nonempty (α ≃ β) := ⟨λ h, by { haveI := classical.prop_decidable, exact (trunc_equiv_of_card_eq h).nonempty }, λ ⟨f⟩, card_congr f⟩ /-- Any subsingleton type with a witness is a fintype (with one term). -/ def of_subsingleton (a : α) [subsingleton α] : fintype α := ⟨{a}, λ b, finset.mem_singleton.2 (subsingleton.elim _ _)⟩ @[simp] theorem univ_of_subsingleton (a : α) [subsingleton α] : @univ _ (of_subsingleton a) = {a} := rfl /-- Note: this lemma is specifically about `fintype.of_subsingleton`. For a statement about arbitrary `fintype` instances, use either `fintype.card_le_one_iff_subsingleton` or `fintype.card_unique`. -/ @[simp] theorem card_of_subsingleton (a : α) [subsingleton α] : @fintype.card _ (of_subsingleton a) = 1 := rfl @[simp] theorem card_unique [unique α] [h : fintype α] : fintype.card α = 1 := subsingleton.elim (of_subsingleton $ default α) h ▸ card_of_subsingleton _ @[priority 100] -- see Note [lower instance priority] instance of_is_empty [is_empty α] : fintype α := ⟨∅, is_empty_elim⟩ /-- Note: this lemma is specifically about `fintype.of_is_empty`. For a statement about arbitrary `fintype` instances, use `fintype.univ_is_empty`. -/ -- no-lint since while `fintype.of_is_empty` can prove this, it isn't applicable for `dsimp`. @[simp, nolint simp_nf] theorem univ_of_is_empty [is_empty α] : @univ α _ = ∅ := rfl /-- Note: this lemma is specifically about `fintype.of_is_empty`. For a statement about arbitrary `fintype` instances, use `fintype.card_eq_zero_iff`. -/ @[simp] theorem card_of_is_empty [is_empty α] : fintype.card α = 0 := rfl open_locale classical variables (α) /-- Any subsingleton type is (noncomputably) a fintype (with zero or one term). -/ @[priority 5] -- see Note [lower instance priority] noncomputable instance of_subsingleton' [subsingleton α] : fintype α := if h : nonempty α then of_subsingleton (nonempty.some h) else @fintype.of_is_empty _ $ not_nonempty_iff.mp h end fintype namespace set /-- Construct a finset enumerating a set `s`, given a `fintype` instance. -/ def to_finset (s : set α) [fintype s] : finset α := ⟨(@finset.univ s _).1.map subtype.val, multiset.nodup_map (λ a b, subtype.eq) finset.univ.2⟩ @[simp] theorem mem_to_finset {s : set α} [fintype s] {a : α} : a ∈ s.to_finset ↔ a ∈ s := by simp [to_finset] @[simp] theorem mem_to_finset_val {s : set α} [fintype s] {a : α} : a ∈ s.to_finset.1 ↔ a ∈ s := mem_to_finset -- We use an arbitrary `[fintype s]` instance here, -- not necessarily coming from a `[fintype α]`. @[simp] lemma to_finset_card {α : Type*} (s : set α) [fintype s] : s.to_finset.card = fintype.card s := multiset.card_map subtype.val finset.univ.val @[simp] theorem coe_to_finset (s : set α) [fintype s] : (↑s.to_finset : set α) = s := set.ext $ λ _, mem_to_finset @[simp] theorem to_finset_inj {s t : set α} [fintype s] [fintype t] : s.to_finset = t.to_finset ↔ s = t := ⟨λ h, by rw [←s.coe_to_finset, h, t.coe_to_finset], λ h, by simp [h]; congr⟩ @[simp, mono] theorem to_finset_mono {s t : set α} [fintype s] [fintype t] : s.to_finset ⊆ t.to_finset ↔ s ⊆ t := by simp [finset.subset_iff, set.subset_def] @[simp, mono] theorem to_finset_strict_mono {s t : set α} [fintype s] [fintype t] : s.to_finset ⊂ t.to_finset ↔ s ⊂ t := begin rw [←lt_eq_ssubset, ←finset.lt_iff_ssubset, lt_iff_le_and_ne, lt_iff_le_and_ne], simp end @[simp] theorem to_finset_disjoint_iff [decidable_eq α] {s t : set α} [fintype s] [fintype t] : disjoint s.to_finset t.to_finset ↔ disjoint s t := ⟨λ h x hx, h (by simpa using hx), λ h x hx, h (by simpa using hx)⟩ end set lemma finset.card_univ [fintype α] : (finset.univ : finset α).card = fintype.card α := rfl lemma finset.eq_univ_of_card [fintype α] (s : finset α) (hs : s.card = fintype.card α) : s = univ := eq_of_subset_of_card_le (subset_univ _) $ by rw [hs, finset.card_univ] lemma finset.card_eq_iff_eq_univ [fintype α] (s : finset α) : s.card = fintype.card α ↔ s = finset.univ := ⟨s.eq_univ_of_card, by { rintro rfl, exact finset.card_univ, }⟩ lemma finset.card_le_univ [fintype α] (s : finset α) : s.card ≤ fintype.card α := card_le_of_subset (subset_univ s) lemma finset.card_lt_univ_of_not_mem [fintype α] {s : finset α} {x : α} (hx : x ∉ s) : s.card < fintype.card α := card_lt_card ⟨subset_univ s, not_forall.2 ⟨x, λ hx', hx (hx' $ mem_univ x)⟩⟩ lemma finset.card_lt_iff_ne_univ [fintype α] (s : finset α) : s.card < fintype.card α ↔ s ≠ finset.univ := s.card_le_univ.lt_iff_ne.trans (not_iff_not_of_iff s.card_eq_iff_eq_univ) lemma finset.card_compl_lt_iff_nonempty [fintype α] [decidable_eq α] (s : finset α) : sᶜ.card < fintype.card α ↔ s.nonempty := sᶜ.card_lt_iff_ne_univ.trans s.compl_ne_univ_iff_nonempty lemma finset.card_univ_diff [decidable_eq α] [fintype α] (s : finset α) : (finset.univ \ s).card = fintype.card α - s.card := finset.card_sdiff (subset_univ s) lemma finset.card_compl [decidable_eq α] [fintype α] (s : finset α) : sᶜ.card = fintype.card α - s.card := finset.card_univ_diff s instance (n : ℕ) : fintype (fin n) := ⟨finset.fin_range n, finset.mem_fin_range⟩ lemma fin.univ_def (n : ℕ) : (univ : finset (fin n)) = finset.fin_range n := rfl @[simp] theorem fintype.card_fin (n : ℕ) : fintype.card (fin n) = n := list.length_fin_range n @[simp] lemma finset.card_fin (n : ℕ) : finset.card (finset.univ : finset (fin n)) = n := by rw [finset.card_univ, fintype.card_fin] lemma card_finset_fin_le {n : ℕ} (s : finset (fin n)) : s.card ≤ n := by simpa only [fintype.card_fin] using s.card_le_univ lemma fin.equiv_iff_eq {m n : ℕ} : nonempty (fin m ≃ fin n) ↔ m = n := ⟨λ ⟨h⟩, by simpa using fintype.card_congr h, λ h, ⟨equiv.cast $ h ▸ rfl ⟩ ⟩ /-- Embed `fin n` into `fin (n + 1)` by prepending zero to the `univ` -/ lemma fin.univ_succ (n : ℕ) : (univ : finset (fin (n + 1))) = insert 0 (univ.image fin.succ) := begin ext m, simp only [mem_univ, mem_insert, true_iff, mem_image, exists_prop], exact fin.cases (or.inl rfl) (λ i, or.inr ⟨i, trivial, rfl⟩) m end /-- Embed `fin n` into `fin (n + 1)` by appending a new `fin.last n` to the `univ` -/ lemma fin.univ_cast_succ (n : ℕ) : (univ : finset (fin (n + 1))) = insert (fin.last n) (univ.image fin.cast_succ) := begin ext m, simp only [mem_univ, mem_insert, true_iff, mem_image, exists_prop, true_and], by_cases h : m.val < n, { right, use fin.cast_lt m h, rw fin.cast_succ_cast_lt }, { left, exact fin.eq_last_of_not_lt h } end /-- Embed `fin n` into `fin (n + 1)` by inserting around a specified pivot `p : fin (n + 1)` into the `univ` -/ lemma fin.univ_succ_above (n : ℕ) (p : fin (n + 1)) : (univ : finset (fin (n + 1))) = insert p (univ.image (fin.succ_above p)) := begin obtain hl | rfl := (fin.le_last p).lt_or_eq, { ext m, simp only [finset.mem_univ, finset.mem_insert, true_iff, finset.mem_image, exists_prop], refine or_iff_not_imp_left.mpr (λ h, _), cases n, { have : m = p := by simp, exact absurd this h }, use p.cast_pred.pred_above m, rw fin.pred_above, split_ifs with H, { simp only [fin.coe_cast_succ, true_and, fin.coe_coe_eq_self, coe_coe], rw fin.lt_last_iff_coe_cast_pred at hl, rw fin.succ_above_above, { simp }, { simp only [fin.lt_iff_coe_lt_coe, fin.coe_cast_succ] at H, simpa [fin.le_iff_coe_le_coe, ←hl] using nat.le_pred_of_lt H } }, { rw fin.succ_above_below, { simp }, { simp only [fin.cast_succ_cast_pred hl, not_lt] at H, simpa using lt_of_le_of_ne H h } } }, { rw fin.succ_above_last, exact fin.univ_cast_succ n } end @[instance, priority 10] def unique.fintype {α : Type*} [unique α] : fintype α := fintype.of_subsingleton (default α) @[simp] lemma univ_unique {α : Type*} [unique α] [f : fintype α] : @finset.univ α _ = {default α} := by rw [subsingleton.elim f (@unique.fintype α _)]; refl @[simp] lemma univ_is_empty {α : Type*} [is_empty α] [fintype α] : @finset.univ α _ = ∅ := finset.ext is_empty_elim @[simp] theorem fintype.univ_empty : @univ empty _ = ∅ := rfl @[simp] theorem fintype.card_empty : fintype.card empty = 0 := rfl @[simp] theorem fintype.univ_pempty : @univ pempty _ = ∅ := rfl @[simp] theorem fintype.card_pempty : fintype.card pempty = 0 := rfl instance : fintype unit := fintype.of_subsingleton () theorem fintype.univ_unit : @univ unit _ = {()} := rfl theorem fintype.card_unit : fintype.card unit = 1 := rfl instance : fintype punit := fintype.of_subsingleton punit.star @[simp] theorem fintype.univ_punit : @univ punit _ = {punit.star} := rfl @[simp] theorem fintype.card_punit : fintype.card punit = 1 := rfl instance : fintype bool := ⟨⟨tt ::ₘ ff ::ₘ 0, by simp⟩, λ x, by cases x; simp⟩ @[simp] theorem fintype.univ_bool : @univ bool _ = {tt, ff} := rfl instance units_int.fintype : fintype (units ℤ) := ⟨{1, -1}, λ x, by cases int.units_eq_one_or x; simp *⟩ @[simp] lemma units_int.univ : (finset.univ : finset (units ℤ)) = {1, -1} := rfl instance additive.fintype : Π [fintype α], fintype (additive α) := id instance multiplicative.fintype : Π [fintype α], fintype (multiplicative α) := id @[simp] theorem fintype.card_units_int : fintype.card (units ℤ) = 2 := rfl noncomputable instance [monoid α] [fintype α] : fintype (units α) := by classical; exact fintype.of_injective units.val units.ext @[simp] theorem fintype.card_bool : fintype.card bool = 2 := rfl /-- Given a finset on `α`, lift it to being a finset on `option α` using `option.some` and then insert `option.none`. -/ def finset.insert_none (s : finset α) : finset (option α) := ⟨none ::ₘ s.1.map some, multiset.nodup_cons.2 ⟨by simp, multiset.nodup_map (λ a b, option.some.inj) s.2⟩⟩ @[simp] theorem finset.mem_insert_none {s : finset α} : ∀ {o : option α}, o ∈ s.insert_none ↔ ∀ a ∈ o, a ∈ s | none := iff_of_true (multiset.mem_cons_self _ _) (λ a h, by cases h) | (some a) := multiset.mem_cons.trans $ by simp; refl theorem finset.some_mem_insert_none {s : finset α} {a : α} : some a ∈ s.insert_none ↔ a ∈ s := by simp instance {α : Type*} [fintype α] : fintype (option α) := ⟨univ.insert_none, λ a, by simp⟩ @[simp] theorem fintype.card_option {α : Type*} [fintype α] : fintype.card (option α) = fintype.card α + 1 := (multiset.card_cons _ _).trans (by rw multiset.card_map; refl) instance {α : Type*} (β : α → Type*) [fintype α] [∀ a, fintype (β a)] : fintype (sigma β) := ⟨univ.sigma (λ _, univ), λ ⟨a, b⟩, by simp⟩ @[simp] lemma finset.univ_sigma_univ {α : Type*} {β : α → Type*} [fintype α] [∀ a, fintype (β a)] : (univ : finset α).sigma (λ a, (univ : finset (β a))) = univ := rfl instance (α β : Type*) [fintype α] [fintype β] : fintype (α × β) := ⟨univ.product univ, λ ⟨a, b⟩, by simp⟩ @[simp] lemma finset.univ_product_univ {α β : Type*} [fintype α] [fintype β] : (univ : finset α).product (univ : finset β) = univ := rfl @[simp] theorem fintype.card_prod (α β : Type*) [fintype α] [fintype β] : fintype.card (α × β) = fintype.card α * fintype.card β := card_product _ _ /-- Given that `α × β` is a fintype, `α` is also a fintype. -/ def fintype.prod_left {α β} [decidable_eq α] [fintype (α × β)] [nonempty β] : fintype α := ⟨(fintype.elems (α × β)).image prod.fst, λ a, let ⟨b⟩ := ‹nonempty β› in by simp; exact ⟨b, fintype.complete _⟩⟩ /-- Given that `α × β` is a fintype, `β` is also a fintype. -/ def fintype.prod_right {α β} [decidable_eq β] [fintype (α × β)] [nonempty α] : fintype β := ⟨(fintype.elems (α × β)).image prod.snd, λ b, let ⟨a⟩ := ‹nonempty α› in by simp; exact ⟨a, fintype.complete _⟩⟩ instance (α : Type*) [fintype α] : fintype (ulift α) := fintype.of_equiv _ equiv.ulift.symm @[simp] theorem fintype.card_ulift (α : Type*) [fintype α] : fintype.card (ulift α) = fintype.card α := fintype.of_equiv_card _ lemma univ_sum_type {α β : Type*} [fintype α] [fintype β] [fintype (α ⊕ β)] [decidable_eq (α ⊕ β)] : (univ : finset (α ⊕ β)) = map function.embedding.inl univ ∪ map function.embedding.inr univ := begin rw [eq_comm, eq_univ_iff_forall], simp only [mem_union, mem_map, exists_prop, mem_univ, true_and], rintro (x|y), exacts [or.inl ⟨x, rfl⟩, or.inr ⟨y, rfl⟩] end instance (α : Type u) (β : Type v) [fintype α] [fintype β] : fintype (α ⊕ β) := @fintype.of_equiv _ _ (@sigma.fintype _ (λ b, cond b (ulift α) (ulift.{(max u v) v} β)) _ (λ b, by cases b; apply ulift.fintype)) ((equiv.sum_equiv_sigma_bool _ _).symm.trans (equiv.sum_congr equiv.ulift equiv.ulift)) /-- Given that `α ⊕ β` is a fintype, `α` is also a fintype. This is non-computable as it uses that `sum.inl` is an injection, but there's no clear inverse if `α` is empty. -/ noncomputable def fintype.sum_left {α β} [fintype (α ⊕ β)] : fintype α := fintype.of_injective (sum.inl : α → α ⊕ β) sum.inl_injective /-- Given that `α ⊕ β` is a fintype, `β` is also a fintype. This is non-computable as it uses that `sum.inr` is an injection, but there's no clear inverse if `β` is empty. -/ noncomputable def fintype.sum_right {α β} [fintype (α ⊕ β)] : fintype β := fintype.of_injective (sum.inr : β → α ⊕ β) sum.inr_injective section finset /-! ### `fintype (s : finset α)` -/ instance finset.fintype_coe_sort {α : Type u} (s : finset α) : fintype s := ⟨s.attach, s.mem_attach⟩ @[simp] lemma finset.univ_eq_attach {α : Type u} (s : finset α) : (univ : finset s) = s.attach := rfl end finset namespace fintype variables [fintype α] [fintype β] lemma card_le_of_injective (f : α → β) (hf : function.injective f) : card α ≤ card β := finset.card_le_card_of_inj_on f (λ _ _, finset.mem_univ _) (λ _ _ _ _ h, hf h) lemma card_le_of_embedding (f : α ↪ β) : card α ≤ card β := card_le_of_injective f f.2 lemma card_lt_of_injective_of_not_mem (f : α → β) (h : function.injective f) {b : β} (w : b ∉ set.range f) : card α < card β := calc card α = (univ.map ⟨f, h⟩).card : (card_map _).symm ... < card β : finset.card_lt_univ_of_not_mem $ by rwa [← mem_coe, coe_map, coe_univ, set.image_univ] lemma card_lt_of_injective_not_surjective (f : α → β) (h : function.injective f) (h' : ¬function.surjective f) : card α < card β := let ⟨y, hy⟩ := not_forall.1 h' in card_lt_of_injective_of_not_mem f h hy lemma card_le_of_surjective (f : α → β) (h : function.surjective f) : card β ≤ card α := card_le_of_injective _ (function.injective_surj_inv h) /-- The pigeonhole principle for finitely many pigeons and pigeonholes. This is the `fintype` version of `finset.exists_ne_map_eq_of_card_lt_of_maps_to`. -/ lemma exists_ne_map_eq_of_card_lt (f : α → β) (h : fintype.card β < fintype.card α) : ∃ x y, x ≠ y ∧ f x = f y := let ⟨x, _, y, _, h⟩ := finset.exists_ne_map_eq_of_card_lt_of_maps_to h (λ x _, mem_univ (f x)) in ⟨x, y, h⟩ lemma card_eq_one_iff : card α = 1 ↔ (∃ x : α, ∀ y, y = x) := by rw [←card_unit, card_eq]; exact ⟨λ ⟨a⟩, ⟨a.symm (), λ y, a.injective (subsingleton.elim _ _)⟩, λ ⟨x, hx⟩, ⟨⟨λ _, (), λ _, x, λ _, (hx _).trans (hx _).symm, λ _, subsingleton.elim _ _⟩⟩⟩ lemma card_eq_zero_iff : card α = 0 ↔ is_empty α := ⟨λ h, ⟨λ a, have e : α ≃ empty := classical.choice (card_eq.1 (by simp [h])), (e a).elim⟩, λ h, by { have e : α ≃ empty, exactI equiv.equiv_empty α, simp [card_congr e] }⟩ lemma card_eq_one_iff_nonempty_unique : card α = 1 ↔ nonempty (unique α) := ⟨λ h, let ⟨d, h⟩ := fintype.card_eq_one_iff.mp h in ⟨{ default := d, uniq := h}⟩, λ ⟨h⟩, by exactI fintype.card_unique⟩ /-- A `fintype` with cardinality zero is equivalent to `empty`. -/ def card_eq_zero_equiv_equiv_empty : card α = 0 ≃ (α ≃ empty) := (equiv.of_iff card_eq_zero_iff).trans (equiv.equiv_empty_equiv α).symm lemma card_pos_iff : 0 < card α ↔ nonempty α := pos_iff_ne_zero.trans $ not_iff_comm.mp $ not_nonempty_iff.trans card_eq_zero_iff.symm lemma card_le_one_iff : card α ≤ 1 ↔ (∀ a b : α, a = b) := let n := card α in have hn : n = card α := rfl, match n, hn with | 0 := λ ha, ⟨λ h, λ a, (card_eq_zero_iff.1 ha.symm).elim a, λ _, ha ▸ nat.le_succ _⟩ | 1 := λ ha, ⟨λ h, λ a b, let ⟨x, hx⟩ := card_eq_one_iff.1 ha.symm in by rw [hx a, hx b], λ _, ha ▸ le_refl _⟩ | (n+2) := λ ha, ⟨λ h, by rw ← ha at h; exact absurd h dec_trivial, (λ h, card_unit ▸ card_le_of_injective (λ _, ()) (λ _ _ _, h _ _))⟩ end lemma card_le_one_iff_subsingleton : card α ≤ 1 ↔ subsingleton α := card_le_one_iff.trans subsingleton_iff.symm lemma one_lt_card_iff_nontrivial : 1 < card α ↔ nontrivial α := begin classical, rw ←not_iff_not, push_neg, rw [not_nontrivial_iff_subsingleton, card_le_one_iff_subsingleton] end lemma exists_ne_of_one_lt_card (h : 1 < card α) (a : α) : ∃ b : α, b ≠ a := by { haveI : nontrivial α := one_lt_card_iff_nontrivial.1 h, exact exists_ne a } lemma exists_pair_of_one_lt_card (h : 1 < card α) : ∃ (a b : α), a ≠ b := by { haveI : nontrivial α := one_lt_card_iff_nontrivial.1 h, exact exists_pair_ne α } lemma card_eq_one_of_forall_eq {i : α} (h : ∀ j, j = i) : card α = 1 := fintype.card_eq_one_iff.2 ⟨i,h⟩ lemma injective_iff_surjective {f : α → α} : injective f ↔ surjective f := by haveI := classical.prop_decidable; exact have ∀ {f : α → α}, injective f → surjective f, from λ f hinj x, have h₁ : image f univ = univ := eq_of_subset_of_card_le (subset_univ _) ((card_image_of_injective univ hinj).symm ▸ le_refl _), have h₂ : x ∈ image f univ := h₁.symm ▸ mem_univ _, exists_of_bex (mem_image.1 h₂), ⟨this, λ hsurj, has_left_inverse.injective ⟨surj_inv hsurj, left_inverse_of_surjective_of_right_inverse (this (injective_surj_inv _)) (right_inverse_surj_inv _)⟩⟩ lemma injective_iff_bijective {f : α → α} : injective f ↔ bijective f := by simp [bijective, injective_iff_surjective] lemma surjective_iff_bijective {f : α → α} : surjective f ↔ bijective f := by simp [bijective, injective_iff_surjective] lemma injective_iff_surjective_of_equiv {β : Type*} {f : α → β} (e : α ≃ β) : injective f ↔ surjective f := have injective (e.symm ∘ f) ↔ surjective (e.symm ∘ f), from injective_iff_surjective, ⟨λ hinj, by simpa [function.comp] using e.surjective.comp (this.1 (e.symm.injective.comp hinj)), λ hsurj, by simpa [function.comp] using e.injective.comp (this.2 (e.symm.surjective.comp hsurj))⟩ lemma bijective_iff_injective_and_card (f : α → β) : bijective f ↔ injective f ∧ card α = card β := begin split, { intro h, exact ⟨h.1, card_congr (equiv.of_bijective f h)⟩ }, { rintro ⟨hf, h⟩, refine ⟨hf, _⟩, rwa ←injective_iff_surjective_of_equiv (equiv_of_card_eq h) } end lemma bijective_iff_surjective_and_card (f : α → β) : bijective f ↔ surjective f ∧ card α = card β := begin split, { intro h, exact ⟨h.2, card_congr (equiv.of_bijective f h)⟩, }, { rintro ⟨hf, h⟩, refine ⟨_, hf⟩, rwa injective_iff_surjective_of_equiv (equiv_of_card_eq h) } end lemma right_inverse_of_left_inverse_of_card_le {f : α → β} {g : β → α} (hfg : left_inverse f g) (hcard : card α ≤ card β) : right_inverse f g := have hsurj : surjective f, from surjective_iff_has_right_inverse.2 ⟨g, hfg⟩, right_inverse_of_injective_of_left_inverse ((bijective_iff_surjective_and_card _).2 ⟨hsurj, le_antisymm hcard (card_le_of_surjective f hsurj)⟩ ).1 hfg lemma left_inverse_of_right_inverse_of_card_le {f : α → β} {g : β → α} (hfg : right_inverse f g) (hcard : card β ≤ card α) : left_inverse f g := right_inverse_of_left_inverse_of_card_le hfg hcard end fintype lemma fintype.coe_image_univ [fintype α] [decidable_eq β] {f : α → β} : ↑(finset.image f finset.univ) = set.range f := by { ext x, simp } instance list.subtype.fintype [decidable_eq α] (l : list α) : fintype {x // x ∈ l} := fintype.of_list l.attach l.mem_attach instance multiset.subtype.fintype [decidable_eq α] (s : multiset α) : fintype {x // x ∈ s} := fintype.of_multiset s.attach s.mem_attach instance finset.subtype.fintype (s : finset α) : fintype {x // x ∈ s} := ⟨s.attach, s.mem_attach⟩ instance finset_coe.fintype (s : finset α) : fintype (↑s : set α) := finset.subtype.fintype s @[simp] lemma fintype.card_coe (s : finset α) : fintype.card s = s.card := card_attach lemma finset.attach_eq_univ {s : finset α} : s.attach = finset.univ := rfl instance plift.fintype (p : Prop) [decidable p] : fintype (plift p) := ⟨if h : p then {⟨h⟩} else ∅, λ ⟨h⟩, by simp [h]⟩ instance Prop.fintype : fintype Prop := ⟨⟨true ::ₘ false ::ₘ 0, by simp [true_ne_false]⟩, classical.cases (by simp) (by simp)⟩ instance subtype.fintype (p : α → Prop) [decidable_pred p] [fintype α] : fintype {x // p x} := fintype.subtype (univ.filter p) (by simp) /-- A set on a fintype, when coerced to a type, is a fintype. -/ def set_fintype {α} [fintype α] (s : set α) [decidable_pred (∈ s)] : fintype s := subtype.fintype (λ x, x ∈ s) lemma set_fintype_card_le_univ {α : Type*} [fintype α] (s : set α) [fintype ↥s] : fintype.card ↥s ≤ fintype.card α := fintype.card_le_of_embedding (function.embedding.subtype s) namespace function.embedding /-- An embedding from a `fintype` to itself can be promoted to an equivalence. -/ noncomputable def equiv_of_fintype_self_embedding {α : Type*} [fintype α] (e : α ↪ α) : α ≃ α := equiv.of_bijective e (fintype.injective_iff_bijective.1 e.2) @[simp] lemma equiv_of_fintype_self_embedding_to_embedding {α : Type*} [fintype α] (e : α ↪ α) : e.equiv_of_fintype_self_embedding.to_embedding = e := by { ext, refl, } /-- If `‖β‖ < ‖α‖` there are no embeddings `α ↪ β`. This is a formulation of the pigeonhole principle. Note this cannot be an instance as it needs `h`. -/ @[simp] lemma is_empty_of_card_lt {α β} [fintype α] [fintype β] (h : fintype.card β < fintype.card α) : is_empty (α ↪ β) := ⟨λ f, let ⟨x, y, ne, feq⟩ := fintype.exists_ne_map_eq_of_card_lt f h in ne $ f.injective feq⟩ end function.embedding @[simp] lemma finset.univ_map_embedding {α : Type*} [fintype α] (e : α ↪ α) : univ.map e = univ := by rw [←e.equiv_of_fintype_self_embedding_to_embedding, univ_map_equiv_to_embedding] namespace fintype lemma card_lt_of_surjective_not_injective [fintype α] [fintype β] (f : α → β) (h : function.surjective f) (h' : ¬function.injective f) : card β < card α := card_lt_of_injective_not_surjective _ (function.injective_surj_inv h) $ λ hg, have w : function.bijective (function.surj_inv h) := ⟨function.injective_surj_inv h, hg⟩, h' $ (injective_iff_surjective_of_equiv (equiv.of_bijective _ w).symm).mpr h variables [decidable_eq α] [fintype α] {δ : α → Type*} /-- Given for all `a : α` a finset `t a` of `δ a`, then one can define the finset `fintype.pi_finset t` of all functions taking values in `t a` for all `a`. This is the analogue of `finset.pi` where the base finset is `univ` (but formally they are not the same, as there is an additional condition `i ∈ finset.univ` in the `finset.pi` definition). -/ def pi_finset (t : Π a, finset (δ a)) : finset (Π a, δ a) := (finset.univ.pi t).map ⟨λ f a, f a (mem_univ a), λ _ _, by simp [function.funext_iff]⟩ @[simp] lemma mem_pi_finset {t : Π a, finset (δ a)} {f : Π a, δ a} : f ∈ pi_finset t ↔ (∀ a, f a ∈ t a) := begin split, { simp only [pi_finset, mem_map, and_imp, forall_prop_of_true, exists_prop, mem_univ, exists_imp_distrib, mem_pi], rintro g hg hgf a, rw ← hgf, exact hg a }, { simp only [pi_finset, mem_map, forall_prop_of_true, exists_prop, mem_univ, mem_pi], exact λ hf, ⟨λ a ha, f a, hf, rfl⟩ } end lemma pi_finset_subset (t₁ t₂ : Π a, finset (δ a)) (h : ∀ a, t₁ a ⊆ t₂ a) : pi_finset t₁ ⊆ pi_finset t₂ := λ g hg, mem_pi_finset.2 $ λ a, h a $ mem_pi_finset.1 hg a lemma pi_finset_disjoint_of_disjoint [∀ a, decidable_eq (δ a)] (t₁ t₂ : Π a, finset (δ a)) {a : α} (h : disjoint (t₁ a) (t₂ a)) : disjoint (pi_finset t₁) (pi_finset t₂) := disjoint_iff_ne.2 $ λ f₁ hf₁ f₂ hf₂ eq₁₂, disjoint_iff_ne.1 h (f₁ a) (mem_pi_finset.1 hf₁ a) (f₂ a) (mem_pi_finset.1 hf₂ a) (congr_fun eq₁₂ a) end fintype /-! ### pi -/ /-- A dependent product of fintypes, indexed by a fintype, is a fintype. -/ instance pi.fintype {α : Type*} {β : α → Type*} [decidable_eq α] [fintype α] [∀ a, fintype (β a)] : fintype (Π a, β a) := ⟨fintype.pi_finset (λ _, univ), by simp⟩ @[simp] lemma fintype.pi_finset_univ {α : Type*} {β : α → Type*} [decidable_eq α] [fintype α] [∀ a, fintype (β a)] : fintype.pi_finset (λ a : α, (finset.univ : finset (β a))) = (finset.univ : finset (Π a, β a)) := rfl instance d_array.fintype {n : ℕ} {α : fin n → Type*} [∀ n, fintype (α n)] : fintype (d_array n α) := fintype.of_equiv _ (equiv.d_array_equiv_fin _).symm instance array.fintype {n : ℕ} {α : Type*} [fintype α] : fintype (array n α) := d_array.fintype instance vector.fintype {α : Type*} [fintype α] {n : ℕ} : fintype (vector α n) := fintype.of_equiv _ (equiv.vector_equiv_fin _ _).symm instance quotient.fintype [fintype α] (s : setoid α) [decidable_rel ((≈) : α → α → Prop)] : fintype (quotient s) := fintype.of_surjective quotient.mk (λ x, quotient.induction_on x (λ x, ⟨x, rfl⟩)) instance finset.fintype [fintype α] : fintype (finset α) := ⟨univ.powerset, λ x, finset.mem_powerset.2 (finset.subset_univ _)⟩ -- irreducible due to this conversation on Zulip: -- https://leanprover.zulipchat.com/#narrow/stream/113488-general/ -- topic/.60simp.60.20ignoring.20lemmas.3F/near/241824115 @[irreducible] instance function.embedding.fintype {α β} [fintype α] [fintype β] [decidable_eq α] [decidable_eq β] : fintype (α ↪ β) := fintype.of_equiv _ (equiv.subtype_injective_equiv_embedding α β) instance [decidable_eq α] [fintype α] {n : ℕ} : fintype (sym.sym' α n) := quotient.fintype _ instance [decidable_eq α] [fintype α] {n : ℕ} : fintype (sym α n) := fintype.of_equiv _ sym.sym_equiv_sym'.symm @[simp] lemma fintype.card_finset [fintype α] : fintype.card (finset α) = 2 ^ (fintype.card α) := finset.card_powerset finset.univ @[simp] lemma finset.univ_filter_card_eq (α : Type*) [fintype α] (k : ℕ) : (finset.univ : finset (finset α)).filter (λ s, s.card = k) = finset.univ.powerset_len k := by { ext, simp [finset.mem_powerset_len] } @[simp] lemma fintype.card_finset_len [fintype α] (k : ℕ) : fintype.card {s : finset α // s.card = k} = nat.choose (fintype.card α) k := by simp [fintype.subtype_card, finset.card_univ] @[simp] lemma set.to_finset_univ [fintype α] : (set.univ : set α).to_finset = finset.univ := by { ext, simp only [set.mem_univ, mem_univ, set.mem_to_finset] } @[simp] lemma set.to_finset_eq_empty_iff {s : set α} [fintype s] : s.to_finset = ∅ ↔ s = ∅ := by simp [ext_iff, set.ext_iff] @[simp] lemma set.to_finset_empty : (∅ : set α).to_finset = ∅ := set.to_finset_eq_empty_iff.mpr rfl @[simp] lemma set.to_finset_range [decidable_eq α] [fintype β] (f : β → α) [fintype (set.range f)] : (set.range f).to_finset = finset.univ.image f := by simp [ext_iff] theorem fintype.card_subtype_le [fintype α] (p : α → Prop) [decidable_pred p] : fintype.card {x // p x} ≤ fintype.card α := fintype.card_le_of_embedding (function.embedding.subtype _) theorem fintype.card_subtype_lt [fintype α] {p : α → Prop} [decidable_pred p] {x : α} (hx : ¬ p x) : fintype.card {x // p x} < fintype.card α := fintype.card_lt_of_injective_of_not_mem coe subtype.coe_injective $ by rwa subtype.range_coe_subtype theorem fintype.card_quotient_le [fintype α] (s : setoid α) [decidable_rel ((≈) : α → α → Prop)] : fintype.card (quotient s) ≤ fintype.card α := fintype.card_le_of_surjective _ (surjective_quotient_mk _) theorem fintype.card_quotient_lt [fintype α] {s : setoid α} [decidable_rel ((≈) : α → α → Prop)] {x y : α} (h1 : x ≠ y) (h2 : x ≈ y) : fintype.card (quotient s) < fintype.card α := fintype.card_lt_of_surjective_not_injective _ (surjective_quotient_mk _) $ λ w, h1 (w $ quotient.eq.mpr h2) instance psigma.fintype {α : Type*} {β : α → Type*} [fintype α] [∀ a, fintype (β a)] : fintype (Σ' a, β a) := fintype.of_equiv _ (equiv.psigma_equiv_sigma _).symm instance psigma.fintype_prop_left {α : Prop} {β : α → Type*} [decidable α] [∀ a, fintype (β a)] : fintype (Σ' a, β a) := if h : α then fintype.of_equiv (β h) ⟨λ x, ⟨h, x⟩, psigma.snd, λ _, rfl, λ ⟨_, _⟩, rfl⟩ else ⟨∅, λ x, h x.1⟩ instance psigma.fintype_prop_right {α : Type*} {β : α → Prop} [∀ a, decidable (β a)] [fintype α] : fintype (Σ' a, β a) := fintype.of_equiv {a // β a} ⟨λ ⟨x, y⟩, ⟨x, y⟩, λ ⟨x, y⟩, ⟨x, y⟩, λ ⟨x, y⟩, rfl, λ ⟨x, y⟩, rfl⟩ instance psigma.fintype_prop_prop {α : Prop} {β : α → Prop} [decidable α] [∀ a, decidable (β a)] : fintype (Σ' a, β a) := if h : ∃ a, β a then ⟨{⟨h.fst, h.snd⟩}, λ ⟨_, _⟩, by simp⟩ else ⟨∅, λ ⟨x, y⟩, h ⟨x, y⟩⟩ instance set.fintype [fintype α] : fintype (set α) := ⟨(@finset.univ α _).powerset.map ⟨coe, coe_injective⟩, λ s, begin classical, refine mem_map.2 ⟨finset.univ.filter s, mem_powerset.2 (subset_univ _), _⟩, apply (coe_filter _ _).trans, rw [coe_univ, set.sep_univ], refl end⟩ instance pfun_fintype (p : Prop) [decidable p] (α : p → Type*) [Π hp, fintype (α hp)] : fintype (Π hp : p, α hp) := if hp : p then fintype.of_equiv (α hp) ⟨λ a _, a, λ f, f hp, λ _, rfl, λ _, rfl⟩ else ⟨singleton (λ h, (hp h).elim), by simp [hp, function.funext_iff]⟩ @[simp] lemma finset.univ_pi_univ {α : Type*} {β : α → Type*} [decidable_eq α] [fintype α] [∀ a, fintype (β a)] : finset.univ.pi (λ a : α, (finset.univ : finset (β a))) = finset.univ := by { ext, simp } lemma mem_image_univ_iff_mem_range {α β : Type*} [fintype α] [decidable_eq β] {f : α → β} {b : β} : b ∈ univ.image f ↔ b ∈ set.range f := by simp /-- An auxiliary function for `quotient.fin_choice`. Given a collection of setoids indexed by a type `ι`, a (finite) list `l` of indices, and a function that for each `i ∈ l` gives a term of the corresponding quotient type, then there is a corresponding term in the quotient of the product of the setoids indexed by `l`. -/ def quotient.fin_choice_aux {ι : Type*} [decidable_eq ι] {α : ι → Type*} [S : ∀ i, setoid (α i)] : Π (l : list ι), (Π i ∈ l, quotient (S i)) → @quotient (Π i ∈ l, α i) (by apply_instance) | [] f := ⟦λ i, false.elim⟧ | (i :: l) f := begin refine quotient.lift_on₂ (f i (list.mem_cons_self _ _)) (quotient.fin_choice_aux l (λ j h, f j (list.mem_cons_of_mem _ h))) _ _, exact λ a l, ⟦λ j h, if e : j = i then by rw e; exact a else l _ (h.resolve_left e)⟧, refine λ a₁ l₁ a₂ l₂ h₁ h₂, quotient.sound (λ j h, _), by_cases e : j = i; simp [e], { subst j, exact h₁ }, { exact h₂ _ _ } end theorem quotient.fin_choice_aux_eq {ι : Type*} [decidable_eq ι] {α : ι → Type*} [S : ∀ i, setoid (α i)] : ∀ (l : list ι) (f : Π i ∈ l, α i), quotient.fin_choice_aux l (λ i h, ⟦f i h⟧) = ⟦f⟧ | [] f := quotient.sound (λ i h, h.elim) | (i :: l) f := begin simp [quotient.fin_choice_aux, quotient.fin_choice_aux_eq l], refine quotient.sound (λ j h, _), by_cases e : j = i; simp [e], subst j, refl end /-- Given a collection of setoids indexed by a fintype `ι` and a function that for each `i : ι` gives a term of the corresponding quotient type, then there is corresponding term in the quotient of the product of the setoids. -/ def quotient.fin_choice {ι : Type*} [decidable_eq ι] [fintype ι] {α : ι → Type*} [S : ∀ i, setoid (α i)] (f : Π i, quotient (S i)) : @quotient (Π i, α i) (by apply_instance) := quotient.lift_on (@quotient.rec_on _ _ (λ l : multiset ι, @quotient (Π i ∈ l, α i) (by apply_instance)) finset.univ.1 (λ l, quotient.fin_choice_aux l (λ i _, f i)) (λ a b h, begin have := λ a, quotient.fin_choice_aux_eq a (λ i h, quotient.out (f i)), simp [quotient.out_eq] at this, simp [this], let g := λ a:multiset ι, ⟦λ (i : ι) (h : i ∈ a), quotient.out (f i)⟧, refine eq_of_heq ((eq_rec_heq _ _).trans (_ : g a == g b)), congr' 1, exact quotient.sound h, end)) (λ f, ⟦λ i, f i (finset.mem_univ _)⟧) (λ a b h, quotient.sound $ λ i, h _ _) theorem quotient.fin_choice_eq {ι : Type*} [decidable_eq ι] [fintype ι] {α : ι → Type*} [∀ i, setoid (α i)] (f : Π i, α i) : quotient.fin_choice (λ i, ⟦f i⟧) = ⟦f⟧ := begin let q, swap, change quotient.lift_on q _ _ = _, have : q = ⟦λ i h, f i⟧, { dsimp [q], exact quotient.induction_on (@finset.univ ι _).1 (λ l, quotient.fin_choice_aux_eq _ _) }, simp [this], exact setoid.refl _ end section equiv open list equiv equiv.perm variables [decidable_eq α] [decidable_eq β] /-- Given a list, produce a list of all permutations of its elements. -/ def perms_of_list : list α → list (perm α) | [] := [1] | (a :: l) := perms_of_list l ++ l.bind (λ b, (perms_of_list l).map (λ f, swap a b * f)) lemma length_perms_of_list : ∀ l : list α, length (perms_of_list l) = l.length! | [] := rfl | (a :: l) := begin rw [length_cons, nat.factorial_succ], simp [perms_of_list, length_bind, length_perms_of_list, function.comp, nat.succ_mul], cc end lemma mem_perms_of_list_of_mem {l : list α} {f : perm α} (h : ∀ x, f x ≠ x → x ∈ l) : f ∈ perms_of_list l := begin induction l with a l IH generalizing f h, { exact list.mem_singleton.2 (equiv.ext $ λ x, decidable.by_contradiction $ h _) }, by_cases hfa : f a = a, { refine mem_append_left _ (IH (λ x hx, mem_of_ne_of_mem _ (h x hx))), rintro rfl, exact hx hfa }, have hfa' : f (f a) ≠ f a := mt (λ h, f.injective h) hfa, have : ∀ (x : α), (swap a (f a) * f) x ≠ x → x ∈ l, { intros x hx, have hxa : x ≠ a, { rintro rfl, apply hx, simp only [mul_apply, swap_apply_right] }, refine list.mem_of_ne_of_mem hxa (h x (λ h, _)), simp only [h, mul_apply, swap_apply_def, mul_apply, ne.def, apply_eq_iff_eq] at hx; split_ifs at hx, exacts [hxa (h.symm.trans h_1), hx h] }, suffices : f ∈ perms_of_list l ∨ ∃ (b ∈ l) (g ∈ perms_of_list l), swap a b * g = f, { simpa only [perms_of_list, exists_prop, list.mem_map, mem_append, list.mem_bind] }, refine or_iff_not_imp_left.2 (λ hfl, ⟨f a, _, swap a (f a) * f, IH this, _⟩), { by_cases hffa : f (f a) = a, { exact mem_of_ne_of_mem hfa (h _ (mt (λ h, f.injective h) hfa)) }, { apply this, simp only [mul_apply, swap_apply_def, mul_apply, ne.def, apply_eq_iff_eq], split_ifs; cc } }, { rw [←mul_assoc, mul_def (swap a (f a)) (swap a (f a)), swap_swap, ←perm.one_def, one_mul] } end lemma mem_of_mem_perms_of_list : ∀ {l : list α} {f : perm α}, f ∈ perms_of_list l → ∀ {x}, f x ≠ x → x ∈ l | [] f h := have f = 1 := by simpa [perms_of_list] using h, by rw this; simp | (a :: l) f h := (mem_append.1 h).elim (λ h x hx, mem_cons_of_mem _ (mem_of_mem_perms_of_list h hx)) (λ h x hx, let ⟨y, hy, hy'⟩ := list.mem_bind.1 h in let ⟨g, hg₁, hg₂⟩ := list.mem_map.1 hy' in if hxa : x = a then by simp [hxa] else if hxy : x = y then mem_cons_of_mem _ $ by rwa hxy else mem_cons_of_mem _ $ mem_of_mem_perms_of_list hg₁ $ by rw [eq_inv_mul_iff_mul_eq.2 hg₂, mul_apply, swap_inv, swap_apply_def]; split_ifs; cc) lemma mem_perms_of_list_iff {l : list α} {f : perm α} : f ∈ perms_of_list l ↔ ∀ {x}, f x ≠ x → x ∈ l := ⟨mem_of_mem_perms_of_list, mem_perms_of_list_of_mem⟩ lemma nodup_perms_of_list : ∀ {l : list α} (hl : l.nodup), (perms_of_list l).nodup | [] hl := by simp [perms_of_list] | (a :: l) hl := have hl' : l.nodup, from nodup_of_nodup_cons hl, have hln' : (perms_of_list l).nodup, from nodup_perms_of_list hl', have hmeml : ∀ {f : perm α}, f ∈ perms_of_list l → f a = a, from λ f hf, not_not.1 (mt (mem_of_mem_perms_of_list hf) (nodup_cons.1 hl).1), by rw [perms_of_list, list.nodup_append, list.nodup_bind, pairwise_iff_nth_le]; exact ⟨hln', ⟨λ _ _, nodup_map (λ _ _, mul_left_cancel) hln', λ i j hj hij x hx₁ hx₂, let ⟨f, hf⟩ := list.mem_map.1 hx₁ in let ⟨g, hg⟩ := list.mem_map.1 hx₂ in have hix : x a = nth_le l i (lt_trans hij hj), by rw [←hf.2, mul_apply, hmeml hf.1, swap_apply_left], have hiy : x a = nth_le l j hj, by rw [← hg.2, mul_apply, hmeml hg.1, swap_apply_left], absurd (hf.2.trans (hg.2.symm)) $ λ h, ne_of_lt hij $ nodup_iff_nth_le_inj.1 hl' i j (lt_trans hij hj) hj $ by rw [← hix, hiy]⟩, λ f hf₁ hf₂, let ⟨x, hx, hx'⟩ := list.mem_bind.1 hf₂ in let ⟨g, hg⟩ := list.mem_map.1 hx' in have hgxa : g⁻¹ x = a, from f.injective $ by rw [hmeml hf₁, ← hg.2]; simp, have hxa : x ≠ a, from λ h, (list.nodup_cons.1 hl).1 (h ▸ hx), (list.nodup_cons.1 hl).1 $ hgxa ▸ mem_of_mem_perms_of_list hg.1 (by rwa [apply_inv_self, hgxa])⟩ /-- Given a finset, produce the finset of all permutations of its elements. -/ def perms_of_finset (s : finset α) : finset (perm α) := quotient.hrec_on s.1 (λ l hl, ⟨perms_of_list l, nodup_perms_of_list hl⟩) (λ a b hab, hfunext (congr_arg _ (quotient.sound hab)) (λ ha hb _, heq_of_eq $ finset.ext $ by simp [mem_perms_of_list_iff, hab.mem_iff])) s.2 lemma mem_perms_of_finset_iff : ∀ {s : finset α} {f : perm α}, f ∈ perms_of_finset s ↔ ∀ {x}, f x ≠ x → x ∈ s := by rintros ⟨⟨l⟩, hs⟩ f; exact mem_perms_of_list_iff lemma card_perms_of_finset : ∀ (s : finset α), (perms_of_finset s).card = s.card! := by rintros ⟨⟨l⟩, hs⟩; exact length_perms_of_list l /-- The collection of permutations of a fintype is a fintype. -/ def fintype_perm [fintype α] : fintype (perm α) := ⟨perms_of_finset (@finset.univ α _), by simp [mem_perms_of_finset_iff]⟩ instance [fintype α] [fintype β] : fintype (α ≃ β) := if h : fintype.card β = fintype.card α then trunc.rec_on_subsingleton (fintype.trunc_equiv_fin α) (λ eα, trunc.rec_on_subsingleton (fintype.trunc_equiv_fin β) (λ eβ, @fintype.of_equiv _ (perm α) fintype_perm (equiv_congr (equiv.refl α) (eα.trans (eq.rec_on h eβ.symm)) : (α ≃ α) ≃ (α ≃ β)))) else ⟨∅, λ x, false.elim (h (fintype.card_eq.2 ⟨x.symm⟩))⟩ lemma fintype.card_perm [fintype α] : fintype.card (perm α) = (fintype.card α)! := subsingleton.elim (@fintype_perm α _ _) (@equiv.fintype α α _ _ _ _) ▸ card_perms_of_finset _ lemma fintype.card_equiv [fintype α] [fintype β] (e : α ≃ β) : fintype.card (α ≃ β) = (fintype.card α)! := fintype.card_congr (equiv_congr (equiv.refl α) e) ▸ fintype.card_perm lemma univ_eq_singleton_of_card_one {α} [fintype α] (x : α) (h : fintype.card α = 1) : (univ : finset α) = {x} := begin symmetry, apply eq_of_subset_of_card_le (subset_univ ({x})), apply le_of_eq, simp [h, finset.card_univ] end end equiv namespace fintype section choose open fintype equiv variables [fintype α] (p : α → Prop) [decidable_pred p] /-- Given a fintype `α` and a predicate `p`, associate to a proof that there is a unique element of `α` satisfying `p` this unique element, as an element of the corresponding subtype. -/ def choose_x (hp : ∃! a : α, p a) : {a // p a} := ⟨finset.choose p univ (by simp; exact hp), finset.choose_property _ _ _⟩ /-- Given a fintype `α` and a predicate `p`, associate to a proof that there is a unique element of `α` satisfying `p` this unique element, as an element of `α`. -/ def choose (hp : ∃! a, p a) : α := choose_x p hp lemma choose_spec (hp : ∃! a, p a) : p (choose p hp) := (choose_x p hp).property end choose section bijection_inverse open function variables [fintype α] [decidable_eq β] {f : α → β} /-- `bij_inv f` is the unique inverse to a bijection `f`. This acts as a computable alternative to `function.inv_fun`. -/ def bij_inv (f_bij : bijective f) (b : β) : α := fintype.choose (λ a, f a = b) begin rcases f_bij.right b with ⟨a', fa_eq_b⟩, rw ← fa_eq_b, exact ⟨a', ⟨rfl, (λ a h, f_bij.left h)⟩⟩ end lemma left_inverse_bij_inv (f_bij : bijective f) : left_inverse (bij_inv f_bij) f := λ a, f_bij.left (choose_spec (λ a', f a' = f a) _) lemma right_inverse_bij_inv (f_bij : bijective f) : right_inverse (bij_inv f_bij) f := λ b, choose_spec (λ a', f a' = b) _ lemma bijective_bij_inv (f_bij : bijective f) : bijective (bij_inv f_bij) := ⟨(right_inverse_bij_inv _).injective, (left_inverse_bij_inv _).surjective⟩ end bijection_inverse lemma well_founded_of_trans_of_irrefl [fintype α] (r : α → α → Prop) [is_trans α r] [is_irrefl α r] : well_founded r := by classical; exact have ∀ x y, r x y → (univ.filter (λ z, r z x)).card < (univ.filter (λ z, r z y)).card, from λ x y hxy, finset.card_lt_card $ by simp only [finset.lt_iff_ssubset.symm, lt_iff_le_not_le, finset.le_iff_subset, finset.subset_iff, mem_filter, true_and, mem_univ, hxy]; exact ⟨λ z hzx, trans hzx hxy, not_forall_of_exists_not ⟨x, not_imp.2 ⟨hxy, irrefl x⟩⟩⟩, subrelation.wf this (measure_wf _) lemma preorder.well_founded [fintype α] [preorder α] : well_founded ((<) : α → α → Prop) := well_founded_of_trans_of_irrefl _ @[instance, priority 10] lemma linear_order.is_well_order [fintype α] [linear_order α] : is_well_order α (<) := { wf := preorder.well_founded } end fintype /-- A type is said to be infinite if it has no fintype instance. Note that `infinite α` is equivalent to `is_empty (fintype α)`. -/ class infinite (α : Type*) : Prop := (not_fintype : fintype α → false) lemma not_fintype (α : Type*) [h1 : infinite α] [h2 : fintype α] : false := infinite.not_fintype h2 protected lemma fintype.false {α : Type*} [infinite α] (h : fintype α) : false := not_fintype α protected lemma infinite.false {α : Type*} [fintype α] (h : infinite α) : false := not_fintype α @[simp] lemma is_empty_fintype {α : Type*} : is_empty (fintype α) ↔ infinite α := ⟨λ ⟨x⟩, ⟨x⟩, λ ⟨x⟩, ⟨x⟩⟩ @[simp] lemma not_nonempty_fintype {α : Type*} : ¬ nonempty (fintype α) ↔ infinite α := not_nonempty_iff.trans is_empty_fintype /-- A non-infinite type is a fintype. -/ noncomputable def fintype_of_not_infinite {α : Type*} (h : ¬ infinite α) : fintype α := ((not_iff_comm.mp not_nonempty_fintype).mp h).some lemma finset.exists_minimal {α : Type*} [preorder α] (s : finset α) (h : s.nonempty) : ∃ m ∈ s, ∀ x ∈ s, ¬ (x < m) := begin obtain ⟨c, hcs : c ∈ s⟩ := h, have : well_founded (@has_lt.lt {x // x ∈ s} _) := fintype.well_founded_of_trans_of_irrefl _, obtain ⟨⟨m, hms : m ∈ s⟩, -, H⟩ := this.has_min set.univ ⟨⟨c, hcs⟩, trivial⟩, exact ⟨m, hms, λ x hx hxm, H ⟨x, hx⟩ trivial hxm⟩, end lemma finset.exists_maximal {α : Type*} [preorder α] (s : finset α) (h : s.nonempty) : ∃ m ∈ s, ∀ x ∈ s, ¬ (m < x) := @finset.exists_minimal (order_dual α) _ s h namespace infinite lemma exists_not_mem_finset [infinite α] (s : finset α) : ∃ x, x ∉ s := not_forall.1 $ λ h, fintype.false ⟨s, h⟩ @[priority 100] -- see Note [lower instance priority] instance (α : Type*) [H : infinite α] : nontrivial α := ⟨let ⟨x, hx⟩ := exists_not_mem_finset (∅ : finset α) in let ⟨y, hy⟩ := exists_not_mem_finset ({x} : finset α) in ⟨y, x, by simpa only [mem_singleton] using hy⟩⟩ lemma nonempty (α : Type*) [infinite α] : nonempty α := by apply_instance lemma of_injective [infinite β] (f : β → α) (hf : injective f) : infinite α := ⟨λ I, by exactI (fintype.of_injective f hf).false⟩ lemma of_surjective [infinite β] (f : α → β) (hf : surjective f) : infinite α := ⟨λ I, by { classical, exactI (fintype.of_surjective f hf).false }⟩ private noncomputable def nat_embedding_aux (α : Type*) [infinite α] : ℕ → α | n := by letI := classical.dec_eq α; exact classical.some (exists_not_mem_finset ((multiset.range n).pmap (λ m (hm : m < n), nat_embedding_aux m) (λ _, multiset.mem_range.1)).to_finset) private lemma nat_embedding_aux_injective (α : Type*) [infinite α] : function.injective (nat_embedding_aux α) := begin rintro m n h, letI := classical.dec_eq α, wlog hmlen : m ≤ n using m n, by_contradiction hmn, have hmn : m < n, from lt_of_le_of_ne hmlen hmn, refine (classical.some_spec (exists_not_mem_finset ((multiset.range n).pmap (λ m (hm : m < n), nat_embedding_aux α m) (λ _, multiset.mem_range.1)).to_finset)) _, refine multiset.mem_to_finset.2 (multiset.mem_pmap.2 ⟨m, multiset.mem_range.2 hmn, _⟩), rw [h, nat_embedding_aux] end /-- Embedding of `ℕ` into an infinite type. -/ noncomputable def nat_embedding (α : Type*) [infinite α] : ℕ ↪ α := ⟨_, nat_embedding_aux_injective α⟩ lemma exists_subset_card_eq (α : Type*) [infinite α] (n : ℕ) : ∃ s : finset α, s.card = n := ⟨(range n).map (nat_embedding α), by rw [card_map, card_range]⟩ end infinite lemma not_injective_infinite_fintype [infinite α] [fintype β] (f : α → β) : ¬ injective f := λ hf, (fintype.of_injective f hf).false /-- The pigeonhole principle for infinitely many pigeons in finitely many pigeonholes. If there are infinitely many pigeons in finitely many pigeonholes, then there are at least two pigeons in the same pigeonhole. See also: `fintype.exists_ne_map_eq_of_card_lt`, `fintype.exists_infinite_fiber`. -/ lemma fintype.exists_ne_map_eq_of_infinite [infinite α] [fintype β] (f : α → β) : ∃ x y : α, x ≠ y ∧ f x = f y := begin classical, by_contra hf, push_neg at hf, apply not_injective_infinite_fintype f, intros x y, contrapose, apply hf, end -- irreducible due to this conversation on Zulip: -- https://leanprover.zulipchat.com/#narrow/stream/113488-general/ -- topic/.60simp.60.20ignoring.20lemmas.3F/near/241824115 @[irreducible] instance function.embedding.is_empty {α β} [infinite α] [fintype β] : is_empty (α ↪ β) := ⟨λ f, let ⟨x, y, ne, feq⟩ := fintype.exists_ne_map_eq_of_infinite f in ne $ f.injective feq⟩ @[priority 100] noncomputable instance function.embedding.fintype' {α β : Type*} [fintype β] : fintype (α ↪ β) := begin by_cases h : infinite α, { resetI, apply_instance }, { have := fintype_of_not_infinite h, classical, apply_instance } -- the `classical` generates `decidable_eq α/β` instances, and resets instance cache end /-- The strong pigeonhole principle for infinitely many pigeons in finitely many pigeonholes. If there are infinitely many pigeons in finitely many pigeonholes, then there is a pigeonhole with infinitely many pigeons. See also: `fintype.exists_ne_map_eq_of_infinite` -/ lemma fintype.exists_infinite_fiber [infinite α] [fintype β] (f : α → β) : ∃ y : β, infinite (f ⁻¹' {y}) := begin classical, by_contra hf, push_neg at hf, haveI := λ y, fintype_of_not_infinite $ hf y, let key : fintype α := { elems := univ.bUnion (λ (y : β), (f ⁻¹' {y}).to_finset), complete := by simp }, exact key.false, end lemma not_surjective_fintype_infinite [fintype α] [infinite β] (f : α → β) : ¬ surjective f := assume (hf : surjective f), have H : infinite α := infinite.of_surjective f hf, by exactI not_fintype α instance nat.infinite : infinite ℕ := ⟨λ ⟨s, hs⟩, finset.not_mem_range_self $ s.subset_range_sup_succ (hs _)⟩ instance int.infinite : infinite ℤ := infinite.of_injective int.of_nat (λ _ _, int.of_nat.inj) section trunc /-- For `s : multiset α`, we can lift the existential statement that `∃ x, x ∈ s` to a `trunc α`. -/ def trunc_of_multiset_exists_mem {α} (s : multiset α) : (∃ x, x ∈ s) → trunc α := quotient.rec_on_subsingleton s $ λ l h, match l, h with | [], _ := false.elim (by tauto) | (a :: _), _ := trunc.mk a end /-- A `nonempty` `fintype` constructively contains an element. -/ def trunc_of_nonempty_fintype (α) [nonempty α] [fintype α] : trunc α := trunc_of_multiset_exists_mem finset.univ.val (by simp) /-- A `fintype` with positive cardinality constructively contains an element. -/ def trunc_of_card_pos {α} [fintype α] (h : 0 < fintype.card α) : trunc α := by { letI := (fintype.card_pos_iff.mp h), exact trunc_of_nonempty_fintype α } /-- By iterating over the elements of a fintype, we can lift an existential statement `∃ a, P a` to `trunc (Σ' a, P a)`, containing data. -/ def trunc_sigma_of_exists {α} [fintype α] {P : α → Prop} [decidable_pred P] (h : ∃ a, P a) : trunc (Σ' a, P a) := @trunc_of_nonempty_fintype (Σ' a, P a) (exists.elim h $ λ a ha, ⟨⟨a, ha⟩⟩) _ end trunc namespace multiset variables [fintype α] [decidable_eq α] @[simp] lemma count_univ (a : α) : count a finset.univ.val = 1 := count_eq_one_of_mem finset.univ.nodup (finset.mem_univ _) end multiset namespace fintype /-- A recursor principle for finite types, analogous to `nat.rec`. It effectively says that every `fintype` is either `empty` or `option α`, up to an `equiv`. -/ def trunc_rec_empty_option {P : Type u → Sort v} (of_equiv : ∀ {α β}, α ≃ β → P α → P β) (h_empty : P pempty) (h_option : ∀ {α} [fintype α] [decidable_eq α], P α → P (option α)) (α : Type u) [fintype α] [decidable_eq α] : trunc (P α) := begin suffices : ∀ n : ℕ, trunc (P (ulift $ fin n)), { apply trunc.bind (this (fintype.card α)), intro h, apply trunc.map _ (fintype.trunc_equiv_fin α), intro e, exact of_equiv (equiv.ulift.trans e.symm) h }, intro n, induction n with n ih, { have : card pempty = card (ulift (fin 0)), { simp only [card_fin, card_pempty, card_ulift] }, apply trunc.bind (trunc_equiv_of_card_eq this), intro e, apply trunc.mk, refine of_equiv e h_empty, }, { have : card (option (ulift (fin n))) = card (ulift (fin n.succ)), { simp only [card_fin, card_option, card_ulift] }, apply trunc.bind (trunc_equiv_of_card_eq this), intro e, apply trunc.map _ ih, intro ih, refine of_equiv e (h_option ih), }, end /-- An induction principle for finite types, analogous to `nat.rec`. It effectively says that every `fintype` is either `empty` or `option α`, up to an `equiv`. -/ lemma induction_empty_option {P : Type u → Prop} (of_equiv : ∀ {α β}, α ≃ β → P α → P β) (h_empty : P pempty) (h_option : ∀ {α} [fintype α], P α → P (option α)) (α : Type u) [fintype α] : P α := begin haveI := classical.dec_eq α, obtain ⟨p⟩ := trunc_rec_empty_option @of_equiv h_empty (λ _ _ _, by exactI h_option) α, exact p, end end fintype
739fdc9a6e7611036967d242c6943eade50f515d
367134ba5a65885e863bdc4507601606690974c1
/src/order/countable_dense_linear_order.lean
26f6e2e4bab10c3397565b7cfa96d21f94303dc8
[ "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
9,632
lean
/- Copyright (c) 2020 David Wärn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: David Wärn -/ import order.ideal import data.finset /-! # The back and forth method and countable dense linear orders ## Results Suppose `α β` are linear orders, with `α` countable and `β` dense, nonempty, without endpoints. Then there is an order embedding `α ↪ β`. If in addition `α` is dense, nonempty, without endpoints and `β` is countable, then we can upgrade this to an order isomorhpism `α ≃ β`. The idea for both results is to consider "partial isomorphisms", which identify a finite subset of `α` with a finite subset of `β`, and prove that for any such partial isomorphism `f` and `a : α`, we can extend `f` to include `a` in its domain. ## References https://en.wikipedia.org/wiki/Back-and-forth_method ## Tags back and forth, dense, countable, order -/ noncomputable theory open_locale classical namespace order /-- Suppose `α` is a nonempty dense linear order without endpoints, and suppose `lo`, `hi`, are finite subssets with all of `lo` strictly before `hi`. Then there is an element of `α` strictly between `lo` and `hi`. -/ lemma exists_between_finsets {α : Type*} [linear_order α] [densely_ordered α] [no_bot_order α] [no_top_order α] [nonem : nonempty α] (lo hi : finset α) (lo_lt_hi : ∀ (x ∈ lo) (y ∈ hi), x < y) : ∃ m : α, (∀ x ∈ lo, x < m) ∧ (∀ y ∈ hi, m < y) := if nlo : lo.nonempty then if nhi : hi.nonempty then -- both sets are nonempty, use densely_ordered exists.elim (exists_between (lo_lt_hi _ (finset.max'_mem _ nlo) _ (finset.min'_mem _ nhi))) (λ m hm, ⟨m, λ x hx, lt_of_le_of_lt (finset.le_max' lo x hx) hm.1, λ y hy, lt_of_lt_of_le hm.2 (finset.min'_le hi y hy)⟩) else -- upper set is empty, use no_top_order exists.elim (no_top (finset.max' lo nlo)) (λ m hm, ⟨m, λ x hx, lt_of_le_of_lt (finset.le_max' lo x hx) hm, λ y hy, (nhi ⟨y, hy⟩).elim⟩) else if nhi : hi.nonempty then -- lower set is empty, use no_bot_order exists.elim (no_bot (finset.min' hi nhi)) (λ m hm, ⟨m, λ x hx, (nlo ⟨x, hx⟩).elim, λ y hy, lt_of_lt_of_le hm (finset.min'_le hi y hy)⟩) else -- both sets are empty, use nonempty nonem.elim (λ m, ⟨m, λ x hx, (nlo ⟨x, hx⟩).elim, λ y hy, (nhi ⟨y, hy⟩).elim⟩) variables (α β : Type*) [linear_order α] [linear_order β] /-- The type of partial order isomorphisms between `α` and `β` defined on finite subsets. A partial order isomorphism is encoded as a finite subset of `α × β`, consisting of pairs which should be identified. -/ def partial_iso : Type* := { f : finset (α × β) // ∀ (p q ∈ f), cmp (prod.fst p) (prod.fst q) = cmp (prod.snd p) (prod.snd q) } namespace partial_iso instance : inhabited (partial_iso α β) := ⟨⟨∅, λ p q h, h.elim⟩⟩ instance : preorder (partial_iso α β) := subtype.preorder _ variables {α β} /-- For each `a`, we can find a `b` in the codomain, such that `a`'s relation to the domain of `f` is `b`'s relation to the image of `f`. Thus, if `a` is not already in `f`, then we can extend `f` by sending `a` to `b`. -/ lemma exists_across [densely_ordered β] [no_bot_order β] [no_top_order β] [nonempty β] (f : partial_iso α β) (a : α) : ∃ b : β, ∀ (p ∈ f.val), cmp (prod.fst p) a = cmp (prod.snd p) b := begin by_cases h : ∃ b, (a, b) ∈ f.val, { cases h with b hb, exact ⟨b, λ p hp, f.property _ _ hp hb⟩, }, have : ∀ (x ∈ (f.val.filter (λ (p : α × β), p.fst < a)).image prod.snd) (y ∈ (f.val.filter (λ (p : α × β), a < p.fst)).image prod.snd), x < y, { intros x hx y hy, rw finset.mem_image at hx hy, rcases hx with ⟨p, hp1, rfl⟩, rcases hy with ⟨q, hq1, rfl⟩, rw finset.mem_filter at hp1 hq1, rw ←lt_iff_lt_of_cmp_eq_cmp (f.property _ _ hp1.1 hq1.1), exact lt_trans hp1.right hq1.right, }, cases exists_between_finsets _ _ this with b hb, use b, rintros ⟨p1, p2⟩ hp, have : p1 ≠ a := λ he, h ⟨p2, he ▸ hp⟩, cases lt_or_gt_of_ne this with hl hr, { have : p1 < a ∧ p2 < b := ⟨hl, hb.1 _ (finset.mem_image.mpr ⟨(p1, p2), finset.mem_filter.mpr ⟨hp, hl⟩, rfl⟩)⟩, rw [←cmp_eq_lt_iff, ←cmp_eq_lt_iff] at this, cc, }, { have : a < p1 ∧ b < p2 := ⟨hr, hb.2 _ (finset.mem_image.mpr ⟨(p1, p2), finset.mem_filter.mpr ⟨hp, hr⟩, rfl⟩)⟩, rw [←cmp_eq_gt_iff, ←cmp_eq_gt_iff] at this, cc, }, end /-- A partial isomorphism between `α` and `β` is also a partial isomorphism between `β` and `α`. -/ protected def comm : partial_iso α β → partial_iso β α := subtype.map (finset.image (equiv.prod_comm _ _)) $ λ f hf p q hp hq, eq.symm $ hf ((equiv.prod_comm α β).symm p) ((equiv.prod_comm α β).symm q) (by { rw [←finset.mem_coe, finset.coe_image, equiv.image_eq_preimage] at hp, rwa ←finset.mem_coe }) (by { rw [←finset.mem_coe, finset.coe_image, equiv.image_eq_preimage] at hq, rwa ←finset.mem_coe }) variable (β) /-- The set of partial isomorphisms defined at `a : α`, together with a proof that any partial isomorphism can be extended to one defined at `a`. -/ def defined_at_left [densely_ordered β] [no_bot_order β] [no_top_order β] [nonempty β] (a : α) : cofinal (partial_iso α β) := { carrier := λ f, ∃ b : β, (a, b) ∈ f.val, mem_gt := begin intro f, cases exists_across f a with b a_b, refine ⟨⟨insert (a, b) f.val, _⟩, ⟨b, finset.mem_insert_self _ _⟩, finset.subset_insert _ _⟩, intros p q hp hq, rw finset.mem_insert at hp hq, rcases hp with rfl | pf; rcases hq with rfl | qf, { simp }, { rw cmp_eq_cmp_symm, exact a_b _ qf }, { exact a_b _ pf }, { exact f.property _ _ pf qf }, end } variables (α) {β} /-- The set of partial isomorphisms defined at `b : β`, together with a proof that any partial isomorphism can be extended to include `b`. We prove this by symmetry. -/ def defined_at_right [densely_ordered α] [no_bot_order α] [no_top_order α] [nonempty α] (b : β) : cofinal (partial_iso α β) := { carrier := λ f, ∃ a, (a, b) ∈ f.val, mem_gt := begin intro f, rcases (defined_at_left α b).mem_gt f.comm with ⟨f', ⟨a, ha⟩, hl⟩, use f'.comm, split, { use a, change (a, b) ∈ f'.val.image _, rwa [←finset.mem_coe, finset.coe_image, equiv.image_eq_preimage] }, { change _ ⊆ f'.val.image _, rw [←finset.coe_subset, finset.coe_image, equiv.subset_image], change f.val.image _ ⊆ _ at hl, rwa [←finset.coe_subset, finset.coe_image] at hl } end } variable {α} /-- Given an ideal which intersects `defined_at_left β a`, pick `b : β` such that some partial function in the ideal maps `a` to `b`. -/ def fun_of_ideal [densely_ordered β] [no_bot_order β] [no_top_order β] [nonempty β] (a : α) (I : ideal (partial_iso α β)) : (∃ f, f ∈ defined_at_left β a ∧ f ∈ I) → { b // ∃ f ∈ I, (a, b) ∈ subtype.val f } := classical.indefinite_description _ ∘ (λ ⟨f, ⟨b, hb⟩, hf⟩, ⟨b, f, hf, hb⟩) /-- Given an ideal which intersects `defined_at_right α b`, pick `a : α` such that some partial function in the ideal maps `a` to `b`. -/ def inv_of_ideal [densely_ordered α] [no_bot_order α] [no_top_order α] [nonempty α] (b : β) (I : ideal (partial_iso α β)) : (∃ f, f ∈ defined_at_right α b ∧ f ∈ I) → { a // ∃ f ∈ I, (a, b) ∈ subtype.val f } := classical.indefinite_description _ ∘ (λ ⟨f, ⟨a, ha⟩, hf⟩, ⟨a, f, hf, ha⟩) end partial_iso open partial_iso variables (α β) /-- Any countable linear order embeds in any nonempty dense linear order without endpoints. -/ def embedding_from_countable_to_dense [encodable α] [densely_ordered β] [no_bot_order β] [no_top_order β] [nonempty β] : α ↪o β := let our_ideal : ideal (partial_iso α β) := ideal_of_cofinals (default _) (defined_at_left β) in let F := λ a, fun_of_ideal a our_ideal (cofinal_meets_ideal_of_cofinals _ _ a) in order_embedding.of_strict_mono (λ a, (F a).val) begin intros a₁ a₂, rcases (F a₁).property with ⟨f, hf, ha₁⟩, rcases (F a₂).property with ⟨g, hg, ha₂⟩, rcases our_ideal.directed _ hf _ hg with ⟨m, hm, fm, gm⟩, exact (lt_iff_lt_of_cmp_eq_cmp $ m.property (a₁, _) (a₂, _) (fm ha₁) (gm ha₂)).mp end /-- Any two countable dense, nonempty linear orders without endpoints are order isomorphic. -/ def iso_of_countable_dense [encodable α] [densely_ordered α] [no_bot_order α] [no_top_order α] [nonempty α] [encodable β] [densely_ordered β] [no_bot_order β] [no_top_order β] [nonempty β] : α ≃o β := let to_cofinal : α ⊕ β → cofinal (partial_iso α β) := λ p, sum.rec_on p (defined_at_left β) (defined_at_right α) in let our_ideal : ideal (partial_iso α β) := ideal_of_cofinals (default _) to_cofinal in let F := λ a, fun_of_ideal a our_ideal (cofinal_meets_ideal_of_cofinals _ to_cofinal (sum.inl a)) in let G := λ b, inv_of_ideal b our_ideal (cofinal_meets_ideal_of_cofinals _ to_cofinal (sum.inr b)) in order_iso.of_cmp_eq_cmp (λ a, (F a).val) (λ b, (G b).val) begin intros a b, rcases (F a).property with ⟨f, hf, ha⟩, rcases (G b).property with ⟨g, hg, hb⟩, rcases our_ideal.directed _ hf _ hg with ⟨m, hm, fm, gm⟩, exact m.property (a, _) (_, b) (fm ha) (gm hb) end end order
9d87256717d8ab129fe5cf2fb8085c469aa76434
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Meta/Constructions.lean
a3dc55cc46bf46529ba6bc936597eb2d6de350cc
[ "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
5,752
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.AuxRecursor import Lean.Meta.AppBuilder namespace Lean @[extern "lean_mk_cases_on"] opaque mkCasesOnImp (env : Environment) (declName : @& Name) : Except KernelException Environment @[extern "lean_mk_rec_on"] opaque mkRecOnImp (env : Environment) (declName : @& Name) : Except KernelException Environment @[extern "lean_mk_no_confusion"] opaque mkNoConfusionCoreImp (env : Environment) (declName : @& Name) : Except KernelException Environment @[extern "lean_mk_below"] opaque mkBelowImp (env : Environment) (declName : @& Name) : Except KernelException Environment @[extern "lean_mk_ibelow"] opaque mkIBelowImp (env : Environment) (declName : @& Name) : Except KernelException Environment @[extern "lean_mk_brec_on"] opaque mkBRecOnImp (env : Environment) (declName : @& Name) : Except KernelException Environment @[extern "lean_mk_binduction_on"] opaque mkBInductionOnImp (env : Environment) (declName : @& Name) : Except KernelException Environment variable [Monad m] [MonadEnv m] [MonadError m] [MonadOptions m] @[inline] private def adaptFn (f : Environment → Name → Except KernelException Environment) (declName : Name) : m Unit := do let env ← ofExceptKernelException (f (← getEnv) declName) modifyEnv fun _ => env def mkCasesOn (declName : Name) : m Unit := adaptFn mkCasesOnImp declName def mkRecOn (declName : Name) : m Unit := adaptFn mkRecOnImp declName def mkNoConfusionCore (declName : Name) : m Unit := adaptFn mkNoConfusionCoreImp 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 open Meta def mkNoConfusionEnum (enumName : Name) : MetaM Unit := do if (← getEnv).contains ``noConfusionEnum then mkToCtorIdx mkNoConfusionType mkNoConfusion else -- `noConfusionEnum` was not defined yet, so we use `mkNoConfusionCore` mkNoConfusionCore enumName where mkToCtorIdx : MetaM Unit := do let ConstantInfo.inductInfo info ← getConstInfo enumName | unreachable! let us := info.levelParams.map mkLevelParam let numCtors := info.ctors.length let declName := Name.mkStr enumName "toCtorIdx" let enumType := mkConst enumName us let natType := mkConst ``Nat let declType ← mkArrow enumType natType let mut minors := #[] for i in [:numCtors] do minors := minors.push <| mkNatLit i withLocalDeclD `x enumType fun x => do let motive ← mkLambdaFVars #[x] natType let declValue ← mkLambdaFVars #[x] <| mkAppN (mkApp2 (mkConst (mkCasesOnName enumName) (levelOne::us)) motive x) minors addAndCompile <| Declaration.defnDecl { name := declName levelParams := info.levelParams type := declType value := declValue safety := DefinitionSafety.safe hints := ReducibilityHints.abbrev } setReducibleAttribute declName mkNoConfusionType : MetaM Unit := do let ConstantInfo.inductInfo info ← getConstInfo enumName | unreachable! let us := info.levelParams.map mkLevelParam let v ← mkFreshUserName `v let enumType := mkConst enumName us let sortV := mkSort (mkLevelParam v) let toCtorIdx := mkConst (Name.mkStr enumName "toCtorIdx") us withLocalDeclD `P sortV fun P => withLocalDeclD `x enumType fun x => withLocalDeclD `y enumType fun y => do let declType ← mkForallFVars #[P, x, y] sortV let declValue ← mkLambdaFVars #[P, x, y] (← mkAppM ``noConfusionTypeEnum #[toCtorIdx, P, x, y]) let declName := Name.mkStr enumName "noConfusionType" addAndCompile <| Declaration.defnDecl { name := declName levelParams := v :: info.levelParams type := declType value := declValue safety := DefinitionSafety.safe hints := ReducibilityHints.abbrev } setReducibleAttribute declName mkNoConfusion : MetaM Unit := do let ConstantInfo.inductInfo info ← getConstInfo enumName | unreachable! let us := info.levelParams.map mkLevelParam let v ← mkFreshUserName `v let enumType := mkConst enumName us let sortV := mkSort (mkLevelParam v) let toCtorIdx := mkConst (Name.mkStr enumName "toCtorIdx") us let noConfusionType := mkConst (Name.mkStr enumName "noConfusionType") (mkLevelParam v :: us) withLocalDecl `P BinderInfo.implicit sortV fun P => withLocalDecl `x BinderInfo.implicit enumType fun x => withLocalDecl `y BinderInfo.implicit enumType fun y => do withLocalDeclD `h (← mkEq x y) fun h => do let declType ← mkForallFVars #[P, x, y, h] (mkApp3 noConfusionType P x y) let declValue ← mkLambdaFVars #[P, x, y, h] (← mkAppOptM ``noConfusionEnum #[none, none, none, toCtorIdx, P, x, y, h]) let declName := Name.mkStr enumName "noConfusion" addAndCompile <| Declaration.defnDecl { name := declName levelParams := v :: info.levelParams type := declType value := declValue safety := DefinitionSafety.safe hints := ReducibilityHints.abbrev } setReducibleAttribute declName modifyEnv fun env => markNoConfusion env declName def mkNoConfusion (declName : Name) : MetaM Unit := do if (← isEnumType declName) then mkNoConfusionEnum declName else mkNoConfusionCore declName end Lean
8fb301cfd4ef5350aef6b0150b1b771b6425f304
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/data/set/intervals/unordered_interval.lean
49135fd958b78c3f27322bb758f7d018074f548f
[ "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
8,277
lean
/- Copyright (c) 2020 Zhouhang Zhou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Zhouhang Zhou -/ import order.bounds import data.set.intervals.image_preimage /-! # Intervals without endpoints ordering In any decidable linear order `α`, we define the set of elements lying between two elements `a` and `b` as `Icc (min a b) (max a b)`. `Icc a b` requires the assumption `a ≤ b` to be meaningful, which is sometimes inconvenient. The interval as defined in this file is always the set of things lying between `a` and `b`, regardless of the relative order of `a` and `b`. For real numbers, `Icc (min a b) (max a b)` is the same as `segment a b`. ## Notation We use the localized notation `[a, b]` for `interval a b`. One can open the locale `interval` to make the notation available. -/ universe u namespace set section linear_order variables {α : Type u} [linear_order α] {a a₁ a₂ b b₁ b₂ x : α} /-- `interval a b` is the set of elements lying between `a` and `b`, with `a` and `b` included. -/ def interval (a b : α) := Icc (min a b) (max a b) localized "notation `[`a `, ` b `]` := interval a b" in interval @[simp] lemma interval_of_le (h : a ≤ b) : [a, b] = Icc a b := by rw [interval, min_eq_left h, max_eq_right h] @[simp] lemma interval_of_ge (h : b ≤ a) : [a, b] = Icc b a := by { rw [interval, min_eq_right h, max_eq_left h] } lemma interval_swap (a b : α) : [a, b] = [b, a] := or.elim (le_total a b) (by simp {contextual := tt}) (by simp {contextual := tt}) lemma interval_of_lt (h : a < b) : [a, b] = Icc a b := interval_of_le (le_of_lt h) lemma interval_of_gt (h : b < a) : [a, b] = Icc b a := interval_of_ge (le_of_lt h) lemma interval_of_not_le (h : ¬ a ≤ b) : [a, b] = Icc b a := interval_of_gt (lt_of_not_ge h) lemma interval_of_not_ge (h : ¬ b ≤ a) : [a, b] = Icc a b := interval_of_lt (lt_of_not_ge h) @[simp] lemma interval_self : [a, a] = {a} := set.ext $ by simp [le_antisymm_iff, and_comm] @[simp] lemma nonempty_interval : set.nonempty [a, b] := by { simp only [interval, min_le_iff, le_max_iff, nonempty_Icc], left, left, refl } @[simp] lemma left_mem_interval : a ∈ [a, b] := by { rw [interval, mem_Icc], exact ⟨min_le_left _ _, le_max_left _ _⟩ } @[simp] lemma right_mem_interval : b ∈ [a, b] := by { rw interval_swap, exact left_mem_interval } lemma Icc_subset_interval : Icc a b ⊆ [a, b] := by { assume x h, rwa interval_of_le, exact le_trans h.1 h.2 } lemma Icc_subset_interval' : Icc b a ⊆ [a, b] := by { rw interval_swap, apply Icc_subset_interval } lemma mem_interval_of_le (ha : a ≤ x) (hb : x ≤ b) : x ∈ [a, b] := Icc_subset_interval ⟨ha, hb⟩ lemma mem_interval_of_ge (hb : b ≤ x) (ha : x ≤ a) : x ∈ [a, b] := Icc_subset_interval' ⟨hb, ha⟩ lemma not_mem_interval_of_lt {c : α} (ha : c < a) (hb : c < b) : c ∉ interval a b := not_mem_Icc_of_lt $ lt_min_iff.mpr ⟨ha, hb⟩ lemma not_mem_interval_of_gt {c : α} (ha : a < c) (hb : b < c) : c ∉ interval a b := not_mem_Icc_of_gt $ max_lt_iff.mpr ⟨ha, hb⟩ lemma interval_subset_interval (h₁ : a₁ ∈ [a₂, b₂]) (h₂ : b₁ ∈ [a₂, b₂]) : [a₁, b₁] ⊆ [a₂, b₂] := Icc_subset_Icc (le_min h₁.1 h₂.1) (max_le h₁.2 h₂.2) lemma interval_subset_interval_iff_mem : [a₁, b₁] ⊆ [a₂, b₂] ↔ a₁ ∈ [a₂, b₂] ∧ b₁ ∈ [a₂, b₂] := iff.intro (λh, ⟨h left_mem_interval, h right_mem_interval⟩) (λ h, interval_subset_interval h.1 h.2) lemma interval_subset_interval_iff_le : [a₁, b₁] ⊆ [a₂, b₂] ↔ min a₂ b₂ ≤ min a₁ b₁ ∧ max a₁ b₁ ≤ max a₂ b₂ := by { rw [interval, interval, Icc_subset_Icc_iff], exact min_le_max } lemma interval_subset_interval_right (h : x ∈ [a, b]) : [x, b] ⊆ [a, b] := interval_subset_interval h right_mem_interval lemma interval_subset_interval_left (h : x ∈ [a, b]) : [a, x] ⊆ [a, b] := interval_subset_interval left_mem_interval h lemma bdd_below_bdd_above_iff_subset_interval (s : set α) : bdd_below s ∧ bdd_above s ↔ ∃ a b, s ⊆ [a, b] := begin rw [bdd_below_bdd_above_iff_subset_Icc], split, { rintro ⟨a, b, h⟩, exact ⟨a, b, λ x hx, Icc_subset_interval (h hx)⟩ }, { rintro ⟨a, b, h⟩, exact ⟨min a b, max a b, h⟩ } end end linear_order open_locale interval section ordered_add_comm_group variables {α : Type u} [linear_ordered_add_comm_group α] (a b c x y : α) @[simp] lemma preimage_const_add_interval : (λ x, a + x) ⁻¹' [b, c] = [b - a, c - a] := by simp only [interval, preimage_const_add_Icc, min_sub_sub_right, max_sub_sub_right] @[simp] lemma preimage_add_const_interval : (λ x, x + a) ⁻¹' [b, c] = [b - a, c - a] := by simpa only [add_comm] using preimage_const_add_interval a b c @[simp] lemma preimage_neg_interval : -([a, b]) = [-a, -b] := by simp only [interval, preimage_neg_Icc, min_neg_neg, max_neg_neg] @[simp] lemma preimage_sub_const_interval : (λ x, x - a) ⁻¹' [b, c] = [b + a, c + a] := by simp [sub_eq_add_neg] @[simp] lemma preimage_const_sub_interval : (λ x, a - x) ⁻¹' [b, c] = [a - b, a - c] := by { rw [interval, interval, preimage_const_sub_Icc], simp only [sub_eq_add_neg, min_add_add_left, max_add_add_left, min_neg_neg, max_neg_neg], } @[simp] lemma image_const_add_interval : (λ x, a + x) '' [b, c] = [a + b, a + c] := by simp [add_comm] @[simp] lemma image_add_const_interval : (λ x, x + a) '' [b, c] = [b + a, c + a] := by simp @[simp] lemma image_const_sub_interval : (λ x, a - x) '' [b, c] = [a - b, a - c] := by simp [sub_eq_add_neg, image_comp (λ x, a + x) (λ x, -x)] @[simp] lemma image_sub_const_interval : (λ x, x - a) '' [b, c] = [b - a, c - a] := by simp [sub_eq_add_neg, add_comm] lemma image_neg_interval : has_neg.neg '' [a, b] = [-a, -b] := by simp variables {a b c x y} /-- If `[x, y]` is a subinterval of `[a, b]`, then the distance between `x` and `y` is less than or equal to that of `a` and `b` -/ lemma abs_sub_le_of_subinterval (h : [x, y] ⊆ [a, b]) : abs (y - x) ≤ abs (b - a) := begin rw [← max_sub_min_eq_abs, ← max_sub_min_eq_abs], rw [interval_subset_interval_iff_le] at h, exact sub_le_sub h.2 h.1, end /-- If `x ∈ [a, b]`, then the distance between `a` and `x` is less than or equal to that of `a` and `b` -/ lemma abs_sub_left_of_mem_interval (h : x ∈ [a, b]) : abs (x - a) ≤ abs (b - a) := abs_sub_le_of_subinterval (interval_subset_interval_left h) /-- If `x ∈ [a, b]`, then the distance between `x` and `b` is less than or equal to that of `a` and `b` -/ lemma abs_sub_right_of_mem_interval (h : x ∈ [a, b]) : abs (b - x) ≤ abs (b - a) := abs_sub_le_of_subinterval (interval_subset_interval_right h) end ordered_add_comm_group section linear_ordered_field variables {k : Type u} [linear_ordered_field k] {a : k} @[simp] lemma preimage_mul_const_interval (ha : a ≠ 0) (b c : k) : (λ x, x * a) ⁻¹' [b, c] = [b / a, c / a] := (lt_or_gt_of_ne ha).elim (λ ha, by simp [interval, ha, ha.le, min_div_div_right_of_nonpos, max_div_div_right_of_nonpos]) (λ (ha : 0 < a), by simp [interval, ha, ha.le, min_div_div_right, max_div_div_right]) @[simp] lemma preimage_const_mul_interval (ha : a ≠ 0) (b c : k) : (λ x, a * x) ⁻¹' [b, c] = [b / a, c / a] := by simp only [← preimage_mul_const_interval ha, mul_comm] @[simp] lemma preimage_div_const_interval (ha : a ≠ 0) (b c : k) : (λ x, x / a) ⁻¹' [b, c] = [b * a, c * a] := by simp only [div_eq_mul_inv, preimage_mul_const_interval (inv_ne_zero ha), inv_inv'] @[simp] lemma image_mul_const_interval (a b c : k) : (λ x, x * a) '' [b, c] = [b * a, c * a] := if ha : a = 0 then by simp [ha] else calc (λ x, x * a) '' [b, c] = (λ x, x * a⁻¹) ⁻¹' [b, c] : (units.mk0 a ha).mul_right.image_eq_preimage _ ... = (λ x, x / a) ⁻¹' [b, c] : by simp only [div_eq_mul_inv] ... = [b * a, c * a] : preimage_div_const_interval ha _ _ @[simp] lemma image_const_mul_interval (a b c : k) : (λ x, a * x) '' [b, c] = [a * b, a * c] := by simpa only [mul_comm] using image_mul_const_interval a b c @[simp] lemma image_div_const_interval (a b c : k) : (λ x, x / a) '' [b, c] = [b / a, c / a] := by simp only [div_eq_mul_inv, image_mul_const_interval] end linear_ordered_field end set
84773e20d2a8bb59770a95626d33f6ce5a418663
432d948a4d3d242fdfb44b81c9e1b1baacd58617
/src/topology/category/Profinite.lean
6c089b227647dfbf6de1bd4235cdb7cd37f01a6b
[ "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
6,706
lean
/- Copyright (c) 2020 Kevin Buzzard. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Buzzard, Calle Sönne -/ import topology.category.CompHaus import topology.connected import topology.subset_properties import category_theory.adjunction.reflective import category_theory.monad.limits /-! # The category of Profinite Types We construct the category of profinite topological spaces, often called profinite sets -- perhaps they could be called profinite types in Lean. The type of profinite topological spaces is called `Profinite`. It has a category instance and is a fully faithful subcategory of `Top`. The fully faithful functor is called `Profinite_to_Top`. ## Implementation notes A profinite type is defined to be a topological space which is compact, Hausdorff and totally disconnected. ## TODO 0. Link to category of projective limits of finite discrete sets. 1. finite coproducts 2. Clausen/Scholze topology on the category `Profinite`. ## Tags profinite -/ open category_theory /-- The type of profinite topological spaces. -/ structure Profinite := (to_Top : Top) [is_compact : compact_space to_Top] [is_t2 : t2_space to_Top] [is_totally_disconnected : totally_disconnected_space to_Top] namespace Profinite instance : inhabited Profinite := ⟨{to_Top := { α := pempty }}⟩ instance category : category Profinite := induced_category.category to_Top instance concrete_category : concrete_category Profinite := induced_category.concrete_category _ instance has_forget₂ : has_forget₂ Profinite Top := induced_category.has_forget₂ _ instance : has_coe_to_sort Profinite := ⟨Type*, λ X, X.to_Top⟩ instance {X : Profinite} : compact_space X := X.is_compact instance {X : Profinite} : t2_space X := X.is_t2 instance {X : Profinite} : totally_disconnected_space X := X.is_totally_disconnected @[simp] lemma coe_to_Top {X : Profinite} : (X.to_Top : Type*) = X := rfl @[simp] lemma coe_id (X : Profinite) : (𝟙 X : X → X) = id := rfl @[simp] lemma coe_comp {X Y Z : Profinite} (f : X ⟶ Y) (g : Y ⟶ Z) : (f ≫ g : X → Z) = g ∘ f := rfl end Profinite /-- The fully faithful embedding of `Profinite` in `Top`. -/ @[simps, derive [full, faithful]] def Profinite_to_Top : Profinite ⥤ Top := forget₂ _ _ /-- The fully faithful embedding of `Profinite` in `CompHaus`. -/ @[simps] def Profinite.to_CompHaus : Profinite ⥤ CompHaus := { obj := λ X, { to_Top := X.to_Top }, map := λ _ _ f, f } instance : full Profinite.to_CompHaus := { preimage := λ _ _ f, f } instance : faithful Profinite.to_CompHaus := {} @[simp] lemma Profinite.to_CompHaus_to_Top : Profinite.to_CompHaus ⋙ CompHaus_to_Top = Profinite_to_Top := rfl section Profinite local attribute [instance] connected_component_setoid universes u /-- (Implementation) The object part of the connected_components functor from compact Hausdorff spaces to Profinite spaces, given by quotienting a space by its connected components. See: https://stacks.math.columbia.edu/tag/0900 -/ -- Without explicit universe annotations here, Lean introduces two universe variables and -- unhelpfully defines a function `CompHaus.{max u₁ u₂} → Profinite.{max u₁ u₂}`. def CompHaus.to_Profinite_obj (X : CompHaus.{u}) : Profinite.{u} := { to_Top := { α := connected_components X.to_Top.α }, is_compact := quotient.compact_space, is_t2 := connected_components.t2, is_totally_disconnected := connected_components.totally_disconnected_space } /-- (Implementation) The bijection of homsets to establish the reflective adjunction of Profinite spaces in compact Hausdorff spaces. -/ def Profinite.to_CompHaus_equivalence (X : CompHaus.{u}) (Y : Profinite.{u}) : (CompHaus.to_Profinite_obj X ⟶ Y) ≃ (X ⟶ Profinite.to_CompHaus.obj Y) := { to_fun := λ f, { to_fun := f.1 ∘ quotient.mk, continuous_to_fun := continuous.comp f.2 (continuous_quotient_mk) }, inv_fun := λ g, { to_fun := continuous.connected_components_lift g.2, continuous_to_fun := continuous.connected_components_lift_continuous g.2}, left_inv := λ f, continuous_map.ext $ λ x, quotient.induction_on x $ λ a, rfl, right_inv := λ f, continuous_map.ext $ λ x, rfl } /-- The connected_components functor from compact Hausdorff spaces to profinite spaces, left adjoint to the inclusion functor. -/ def CompHaus.to_Profinite : CompHaus ⥤ Profinite := adjunction.left_adjoint_of_equiv Profinite.to_CompHaus_equivalence (λ _ _ _ _ _, rfl) lemma CompHaus.to_Profinite_obj' (X : CompHaus) : ↥(CompHaus.to_Profinite.obj X) = connected_components X.to_Top.α := rfl end Profinite namespace Profinite /-- The adjunction between CompHaus.to_Profinite and Profinite.to_CompHaus -/ def to_Profinite_adj_to_CompHaus : CompHaus.to_Profinite ⊣ Profinite.to_CompHaus := adjunction.adjunction_of_equiv_left _ _ /-- The category of profinite sets is reflective in the category of compact hausdroff spaces -/ instance to_CompHaus.reflective : reflective Profinite.to_CompHaus := { to_is_right_adjoint := ⟨CompHaus.to_Profinite, Profinite.to_Profinite_adj_to_CompHaus⟩ } noncomputable instance to_CompHaus.creates_limits : creates_limits Profinite.to_CompHaus := monadic_creates_limits _ noncomputable instance to_Top.reflective : reflective (Profinite_to_Top : Profinite ⥤ Top) := reflective.comp Profinite.to_CompHaus CompHaus_to_Top noncomputable instance to_Top.creates_limits : creates_limits Profinite_to_Top := monadic_creates_limits _ instance has_limits : limits.has_limits Profinite := has_limits_of_has_limits_creates_limits Profinite_to_Top instance has_colimits : limits.has_colimits Profinite := has_colimits_of_reflective to_CompHaus /-- Any morphism of profinite spaces is a closed map. -/ lemma is_closed_map {X Y : Profinite} (f : X ⟶ Y) : is_closed_map f := show is_closed_map (Profinite.to_CompHaus.map f), from CompHaus.is_closed_map _ /-- Any continuous bijection of profinite spaces induces an isomorphism. -/ lemma is_iso_of_bijective {X Y : Profinite} (f : X ⟶ Y) (bij : function.bijective f) : is_iso f := begin haveI := CompHaus.is_iso_of_bijective (Profinite.to_CompHaus.map f) bij, exact is_iso_of_fully_faithful Profinite.to_CompHaus _ end /-- Any continuous bijection of profinite spaces induces an isomorphism. -/ noncomputable def iso_of_bijective {X Y : Profinite} (f : X ⟶ Y) (bij : function.bijective f) : X ≅ Y := by letI := Profinite.is_iso_of_bijective f bij; exact as_iso f instance forget_reflects_isomorphisms : reflects_isomorphisms (forget Profinite) := ⟨by introsI A B f hf; exact Profinite.is_iso_of_bijective _ ((is_iso_iff_bijective ⇑f).mp hf)⟩ end Profinite
f0703d6491906485588ee41832d3018412165b71
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/category_theory/groupoid.lean
f6f72ba74b7fe2094c5d02680ad16474c675f8e9
[ "Apache-2.0" ]
permissive
gebner/mathlib
eab0150cc4f79ec45d2016a8c21750244a2e7ff0
cc6a6edc397c55118df62831e23bfbd6e6c6b4ab
refs/heads/master
1,625,574,853,976
1,586,712,827,000
1,586,712,827,000
99,101,412
1
0
Apache-2.0
1,586,716,389,000
1,501,667,958,000
Lean
UTF-8
Lean
false
false
2,300
lean
/- Copyright (c) 2018 Reid Barton All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Reid Barton, Scott Morrison, David Wärn -/ import category_theory.category import category_theory.isomorphism import category_theory.epi_mono import data.equiv.basic namespace category_theory universes v u -- declare the `v`'s first; see `category_theory.category` for an explanation section prio set_option default_priority 100 -- see Note [default priority] /-- A `groupoid` is a category such that all morphisms are isomorphisms. -/ class groupoid (obj : Type u) extends category.{v} obj : Type (max u (v+1)) := (inv : Π {X Y : obj}, (X ⟶ Y) → (Y ⟶ X)) (inv_comp' : ∀ {X Y : obj} (f : X ⟶ Y), comp (inv f) f = id Y . obviously) (comp_inv' : ∀ {X Y : obj} (f : X ⟶ Y), comp f (inv f) = id X . obviously) end prio restate_axiom groupoid.inv_comp' restate_axiom groupoid.comp_inv' attribute [simp] groupoid.inv_comp groupoid.comp_inv abbreviation large_groupoid (C : Type (u+1)) : Type (u+1) := groupoid.{u} C abbreviation small_groupoid (C : Type u) : Type (u+1) := groupoid.{u} C section variables {C : Type u} [𝒞 : groupoid.{v} C] {X Y : C} include 𝒞 @[priority 100] -- see Note [lower instance priority] instance is_iso.of_groupoid (f : X ⟶ Y) : is_iso f := { inv := groupoid.inv f } variables (X Y) /-- In a groupoid, isomorphisms are equivalent to morphisms. -/ def groupoid.iso_equiv_hom : (X ≅ Y) ≃ (X ⟶ Y) := { to_fun := iso.hom, inv_fun := λ f, as_iso f, left_inv := λ i, iso.ext rfl, right_inv := λ f, rfl } end section variables {C : Type u} [𝒞 : category.{v} C] include 𝒞 /-- A category where every morphism `is_iso` is a groupoid. -/ def groupoid.of_is_iso (all_is_iso : ∀ {X Y : C} (f : X ⟶ Y), is_iso.{v} f) : groupoid.{v} C := { inv := λ X Y f, (all_is_iso f).inv } /-- A category where every morphism has a `trunc` retraction is computably a groupoid. -/ def groupoid.of_trunc_split_mono (all_split_mono : ∀ {X Y : C} (f : X ⟶ Y), trunc (split_mono.{v} f)) : groupoid.{v} C := begin apply groupoid.of_is_iso, intros X Y f, trunc_cases all_split_mono f, trunc_cases all_split_mono (retraction f), apply is_iso.of_mono_retraction, end end end category_theory
9e99f0819db25fa58a3aee7dcd93764ea09689c7
4efff1f47634ff19e2f786deadd394270a59ecd2
/src/topology/algebra/ring.lean
84f505da62f7e792c085a8b53106516b33d417d1
[ "Apache-2.0" ]
permissive
agjftucker/mathlib
d634cd0d5256b6325e3c55bb7fb2403548371707
87fe50de17b00af533f72a102d0adefe4a2285e8
refs/heads/master
1,625,378,131,941
1,599,166,526,000
1,599,166,526,000
160,748,509
0
0
Apache-2.0
1,544,141,789,000
1,544,141,789,000
null
UTF-8
Lean
false
false
4,455
lean
/- Copyright (c) 2018 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot, Johannes Hölzl Theory of topological rings. -/ import topology.algebra.group import ring_theory.ideal.basic open classical set filter topological_space open_locale classical section topological_ring universes u v w variables (α : Type u) [topological_space α] section prio set_option default_priority 100 -- see Note [default priority] /-- A topological semiring is a semiring where addition and multiplication are continuous. -/ class topological_semiring [semiring α] extends has_continuous_add α, has_continuous_mul α : Prop end prio variables [ring α] section prio set_option default_priority 100 -- see Note [default priority] /-- A topological ring is a ring where the ring operations are continuous. -/ class topological_ring extends has_continuous_add α, has_continuous_mul α : Prop := (continuous_neg : continuous (λa:α, -a)) end prio variables [t : topological_ring α] @[priority 100] -- see Note [lower instance priority] instance topological_ring.to_topological_semiring : topological_semiring α := {..t} @[priority 100] -- see Note [lower instance priority] instance topological_ring.to_topological_add_group : topological_add_group α := {..t} variables {α} [topological_ring α] /-- In a topological ring, the left-multiplication `add_monoid_hom` is continuous. -/ lemma mul_left_continuous (x : α) : continuous (add_monoid_hom.mul_left x) := continuous_const.mul continuous_id /-- In a topological ring, the right-multiplication `add_monoid_hom` is continuous. -/ lemma mul_right_continuous (x : α) : continuous (add_monoid_hom.mul_right x) := continuous_id.mul continuous_const end topological_ring section topological_comm_ring variables {α : Type*} [topological_space α] [comm_ring α] [topological_ring α] def ideal.closure (S : ideal α) : ideal α := { carrier := closure S, zero_mem' := subset_closure S.zero_mem, add_mem' := assume x y hx hy, mem_closure2 continuous_add hx hy $ assume a b, S.add_mem, smul_mem' := assume c x hx, have continuous (λx:α, c * x) := continuous_const.mul continuous_id, mem_closure this hx $ assume a, S.mul_mem_left } @[simp] lemma ideal.coe_closure (S : ideal α) : (S.closure : set α) = closure S := rfl end topological_comm_ring section topological_ring variables {α : Type*} [topological_space α] [comm_ring α] (N : ideal α) open ideal.quotient instance topological_ring_quotient_topology : topological_space N.quotient := by dunfold ideal.quotient submodule.quotient; apply_instance lemma quotient_ring_saturate {α : Type*} [comm_ring α] (N : ideal α) (s : set α) : mk N ⁻¹' (mk N '' s) = (⋃ x : N, (λ y, x.1 + y) '' s) := begin ext x, simp only [mem_preimage, mem_image, mem_Union, ideal.quotient.eq], split, { exact assume ⟨a, a_in, h⟩, ⟨⟨_, N.neg_mem h⟩, a, a_in, by simp⟩ }, { exact assume ⟨⟨i, hi⟩, a, ha, eq⟩, ⟨a, ha, by rw [← eq, sub_add_eq_sub_sub_swap, sub_self, zero_sub]; exact N.neg_mem hi⟩ } end variable [topological_ring α] lemma quotient_ring.is_open_map_coe : is_open_map (mk N) := begin assume s s_op, show is_open (mk N ⁻¹' (mk N '' s)), rw quotient_ring_saturate N s, exact is_open_Union (assume ⟨n, _⟩, is_open_map_add_left n s s_op) end lemma quotient_ring.quotient_map_coe_coe : quotient_map (λ p : α × α, (mk N p.1, mk N p.2)) := begin apply is_open_map.to_quotient_map, { exact (quotient_ring.is_open_map_coe N).prod (quotient_ring.is_open_map_coe N) }, { exact (continuous_quot_mk.comp continuous_fst).prod_mk (continuous_quot_mk.comp continuous_snd) }, { rintro ⟨⟨x⟩, ⟨y⟩⟩, exact ⟨(x, y), rfl⟩ } end instance topological_ring_quotient : topological_ring N.quotient := { continuous_add := have cont : continuous (mk N ∘ (λ (p : α × α), p.fst + p.snd)) := continuous_quot_mk.comp continuous_add, (quotient_map.continuous_iff (quotient_ring.quotient_map_coe_coe N)).2 cont, continuous_neg := continuous_quotient_lift _ (continuous_quot_mk.comp continuous_neg), continuous_mul := have cont : continuous (mk N ∘ (λ (p : α × α), p.fst * p.snd)) := continuous_quot_mk.comp continuous_mul, (quotient_map.continuous_iff (quotient_ring.quotient_map_coe_coe N)).2 cont } end topological_ring
3df89a0e003b4287ab2356b8629b170514476a65
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/category_theory/sites/pretopology.lean
93243383e6e1c171f8cb851544fd8b42256b5b47
[ "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
7,441
lean
/- Copyright (c) 2020 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta -/ import category_theory.sites.grothendieck /-! # Grothendieck pretopologies Definition and lemmas about Grothendieck pretopologies. A Grothendieck pretopology for a category `C` is a set of families of morphisms with fixed codomain, satisfying certain closure conditions. We show that a pretopology generates a genuine Grothendieck topology, and every topology has a maximal pretopology which generates it. The pretopology associated to a topological space is defined in `spaces.lean`. ## Tags coverage, pretopology, site ## References * [https://ncatlab.org/nlab/show/Grothendieck+pretopology][nlab] * [S. MacLane, I. Moerdijk, *Sheaves in Geometry and Logic*][MM92] * [https://stacks.math.columbia.edu/tag/00VG][Stacks] -/ universes v u noncomputable theory namespace category_theory open category_theory category limits presieve variables {C : Type u} [category.{v} C] [has_pullbacks C] variables (C) /-- A (Grothendieck) pretopology on `C` consists of a collection of families of morphisms with a fixed target `X` for every object `X` in `C`, called "coverings" of `X`, which satisfies the following three axioms: 1. Every family consisting of a single isomorphism is a covering family. 2. The collection of covering families is stable under pullback. 3. Given a covering family, and a covering family on each domain of the former, the composition is a covering family. In some sense, a pretopology can be seen as Grothendieck topology with weaker saturation conditions, in that each covering is not necessarily downward closed. See: https://ncatlab.org/nlab/show/Grothendieck+pretopology, or https://stacks.math.columbia.edu/tag/00VH, or [MM92] Chapter III, Section 2, Definition 2. Note that Stacks calls a category together with a pretopology a site, and [MM92] calls this a basis for a topology. -/ @[ext] structure pretopology := (coverings : Π (X : C), set (presieve X)) (has_isos : ∀ ⦃X Y⦄ (f : Y ⟶ X) [is_iso f], presieve.singleton f ∈ coverings X) (pullbacks : ∀ ⦃X Y⦄ (f : Y ⟶ X) S, S ∈ coverings X → pullback_arrows f S ∈ coverings Y) (transitive : ∀ ⦃X : C⦄ (S : presieve X) (Ti : Π ⦃Y⦄ (f : Y ⟶ X), S f → presieve Y), S ∈ coverings X → (∀ ⦃Y⦄ f (H : S f), Ti f H ∈ coverings Y) → S.bind Ti ∈ coverings X) namespace pretopology instance : has_coe_to_fun (pretopology C) (λ _, Π X : C, set (presieve X)) := ⟨coverings⟩ variable {C} instance : has_le (pretopology C) := { le := λ K₁ K₂, (K₁ : Π (X : C), set (presieve X)) ≤ K₂ } lemma le_def {K₁ K₂ : pretopology C} : K₁ ≤ K₂ ↔ (K₁ : Π (X : C), set (presieve X)) ≤ K₂ := iff.rfl variable (C) instance : partial_order (pretopology C) := { le_refl := λ K, le_def.mpr le_rfl, le_trans := λ K₁ K₂ K₃ h₁₂ h₂₃, le_def.mpr (le_trans h₁₂ h₂₃), le_antisymm := λ K₁ K₂ h₁₂ h₂₁, pretopology.ext _ _ (le_antisymm h₁₂ h₂₁), ..pretopology.has_le } instance : order_top (pretopology C) := { top := { coverings := λ _, set.univ, has_isos := λ _ _ _ _, set.mem_univ _, pullbacks := λ _ _ _ _ _, set.mem_univ _, transitive := λ _ _ _ _ _, set.mem_univ _ }, le_top := λ K X S hS, set.mem_univ _ } instance : inhabited (pretopology C) := ⟨⊤⟩ /-- A pretopology `K` can be completed to a Grothendieck topology `J` by declaring a sieve to be `J`-covering if it contains a family in `K`. See https://stacks.math.columbia.edu/tag/00ZC, or [MM92] Chapter III, Section 2, Equation (2). -/ def to_grothendieck (K : pretopology C) : grothendieck_topology C := { sieves := λ X S, ∃ R ∈ K X, R ≤ (S : presieve _), top_mem' := λ X, ⟨presieve.singleton (𝟙 _), K.has_isos _, λ _ _ _, ⟨⟩⟩, pullback_stable' := λ X Y S g, begin rintro ⟨R, hR, RS⟩, refine ⟨_, K.pullbacks g _ hR, _⟩, rw [← sieve.sets_iff_generate, sieve.pullback_arrows_comm], apply sieve.pullback_monotone, rwa sieve.gi_generate.gc, end, transitive' := begin rintro X S ⟨R', hR', RS⟩ R t, choose t₁ t₂ t₃ using t, refine ⟨_, K.transitive _ _ hR' (λ _ f hf, t₂ (RS _ hf)), _⟩, rintro Y _ ⟨Z, g, f, hg, hf, rfl⟩, apply t₃ (RS _ hg) _ hf, end } lemma mem_to_grothendieck (K : pretopology C) (X S) : S ∈ to_grothendieck C K X ↔ ∃ R ∈ K X, R ≤ (S : presieve X) := iff.rfl /-- The largest pretopology generating the given Grothendieck topology. See [MM92] Chapter III, Section 2, Equations (3,4). -/ def of_grothendieck (J : grothendieck_topology C) : pretopology C := { coverings := λ X R, sieve.generate R ∈ J X, has_isos := λ X Y f i, by exactI J.covering_of_eq_top (by simp), pullbacks := λ X Y f R hR, begin rw [set.mem_def, sieve.pullback_arrows_comm], apply J.pullback_stable f hR, end, transitive := λ X S Ti hS hTi, begin apply J.transitive hS, intros Y f, rintros ⟨Z, g, f, hf, rfl⟩, rw sieve.pullback_comp, apply J.pullback_stable g, apply J.superset_covering _ (hTi _ hf), rintro Y g ⟨W, h, g, hg, rfl⟩, exact ⟨_, h, _, ⟨_, _, _, hf, hg, rfl⟩, by simp⟩, end } /-- We have a galois insertion from pretopologies to Grothendieck topologies. -/ def gi : galois_insertion (to_grothendieck C) (of_grothendieck C) := { gc := λ K J, begin split, { intros h X R hR, exact h _ ⟨_, hR, sieve.le_generate R⟩ }, { rintro h X S ⟨R, hR, RS⟩, apply J.superset_covering _ (h _ hR), rwa sieve.gi_generate.gc } end, le_l_u := λ J X S hS, ⟨S, J.superset_covering S.le_generate hS, le_rfl⟩, choice := λ x hx, to_grothendieck C x, choice_eq := λ _ _, rfl } /-- The trivial pretopology, in which the coverings are exactly singleton isomorphisms. This topology is also known as the indiscrete, coarse, or chaotic topology. See https://stacks.math.columbia.edu/tag/07GE -/ def trivial : pretopology C := { coverings := λ X S, ∃ Y (f : Y ⟶ X) (h : is_iso f), S = presieve.singleton f, has_isos := λ X Y f i, ⟨_, _, i, rfl⟩, pullbacks := λ X Y f S, begin rintro ⟨Z, g, i, rfl⟩, refine ⟨pullback g f, pullback.snd, _, _⟩, { resetI, refine ⟨⟨pullback.lift (f ≫ inv g) (𝟙 _) (by simp), ⟨_, by tidy⟩⟩⟩, apply pullback.hom_ext, { rw [assoc, pullback.lift_fst, ←pullback.condition_assoc], simp }, { simp } }, { apply pullback_singleton }, end, transitive := begin rintro X S Ti ⟨Z, g, i, rfl⟩ hS, rcases hS g (singleton_self g) with ⟨Y, f, i, hTi⟩, refine ⟨_, f ≫ g, _, _⟩, { resetI, apply_instance }, ext W k, split, { rintro ⟨V, h, k, ⟨_⟩, hh, rfl⟩, rw hTi at hh, cases hh, apply singleton.mk }, { rintro ⟨_⟩, refine bind_comp g presieve.singleton.mk _, rw hTi, apply presieve.singleton.mk } end } instance : order_bot (pretopology C) := { bot := trivial C, bot_le := λ K X R, begin rintro ⟨Y, f, hf, rfl⟩, exactI K.has_isos f, end } /-- The trivial pretopology induces the trivial grothendieck topology. -/ lemma to_grothendieck_bot : to_grothendieck C ⊥ = ⊥ := (gi C).gc.l_bot end pretopology end category_theory
5bae8df60c30bbadbc9fa57a2779c858aa8d0ed1
d9d511f37a523cd7659d6f573f990e2a0af93c6f
/src/topology/metric_space/emetric_space.lean
2c7cc51777bf12db0deec72a83aface6281d32be
[ "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
46,764
lean
/- Copyright (c) 2015, 2017 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Robert Y. Lewis, Johannes Hölzl, Mario Carneiro, Sébastien Gouëzel -/ import data.real.ennreal import data.finset.intervals import topology.uniform_space.uniform_embedding import topology.uniform_space.pi import topology.uniform_space.uniform_convergence /-! # Extended metric spaces This file is devoted to the definition and study of `emetric_spaces`, i.e., metric spaces in which the distance is allowed to take the value ∞. This extended distance is called `edist`, and takes values in `ℝ≥0∞`. Many definitions and theorems expected on emetric spaces are already introduced on uniform spaces and topological spaces. For example: open and closed sets, compactness, completeness, continuity and uniform continuity. The class `emetric_space` therefore extends `uniform_space` (and `topological_space`). Since a lot of elementary properties don't require `eq_of_edist_eq_zero` we start setting up the theory of `pseudo_emetric_space`, where we don't require `edist x y = 0 → x = y` and we specialize to `emetric_space` at the end. -/ open set filter classical noncomputable theory open_locale uniformity topological_space big_operators filter nnreal ennreal universes u v w variables {α : Type u} {β : Type v} /-- Characterizing uniformities associated to a (generalized) distance function `D` in terms of the elements of the uniformity. -/ theorem uniformity_dist_of_mem_uniformity [linear_order β] {U : filter (α × α)} (z : β) (D : α → α → β) (H : ∀ s, s ∈ U ↔ ∃ε>z, ∀{a b:α}, D a b < ε → (a, b) ∈ s) : U = ⨅ ε>z, 𝓟 {p:α×α | D p.1 p.2 < ε} := le_antisymm (le_infi $ λ ε, le_infi $ λ ε0, le_principal_iff.2 $ (H _).2 ⟨ε, ε0, λ a b, id⟩) (λ r ur, let ⟨ε, ε0, h⟩ := (H _).1 ur in mem_infi_of_mem ε $ mem_infi_of_mem ε0 $ mem_principal.2 $ λ ⟨a, b⟩, h) /-- `has_edist α` means that `α` is equipped with an extended distance. -/ class has_edist (α : Type*) := (edist : α → α → ℝ≥0∞) export has_edist (edist) /-- Creating a uniform space from an extended distance. -/ def uniform_space_of_edist (edist : α → α → ℝ≥0∞) (edist_self : ∀ x : α, edist x x = 0) (edist_comm : ∀ x y : α, edist x y = edist y x) (edist_triangle : ∀ x y z : α, edist x z ≤ edist x y + edist y z) : uniform_space α := uniform_space.of_core { uniformity := (⨅ ε>0, 𝓟 {p:α×α | edist p.1 p.2 < ε}), refl := le_infi $ assume ε, le_infi $ by simp [set.subset_def, id_rel, edist_self, (>)] {contextual := tt}, comp := le_infi $ assume ε, le_infi $ assume h, have (2 : ℝ≥0∞) = (2 : ℕ) := by simp, have A : 0 < ε / 2 := ennreal.div_pos_iff.2 ⟨ne_of_gt h, by { convert ennreal.nat_ne_top 2 }⟩, lift'_le (mem_infi_of_mem (ε / 2) $ mem_infi_of_mem A (subset.refl _)) $ have ∀ (a b c : α), edist a c < ε / 2 → edist c b < ε / 2 → edist a b < ε, from assume a b c hac hcb, calc edist a b ≤ edist a c + edist c b : edist_triangle _ _ _ ... < ε / 2 + ε / 2 : ennreal.add_lt_add hac hcb ... = ε : by rw [ennreal.add_halves], by simpa [comp_rel], symm := tendsto_infi.2 $ assume ε, tendsto_infi.2 $ assume h, tendsto_infi' ε $ tendsto_infi' h $ tendsto_principal_principal.2 $ by simp [edist_comm] } -- the uniform structure is embedded in the emetric space structure -- to avoid instance diamond issues. See Note [forgetful inheritance]. /-- Extended (pseudo) metric spaces, with an extended distance `edist` possibly taking the value ∞ Each pseudo_emetric space induces a canonical `uniform_space` and hence a canonical `topological_space`. This is enforced in the type class definition, by extending the `uniform_space` structure. When instantiating a `pseudo_emetric_space` structure, the uniformity fields are not necessary, they will be filled in by default. There is a default value for the uniformity, that can be substituted in cases of interest, for instance when instantiating a `pseudo_emetric_space` structure on a product. Continuity of `edist` is proved in `topology.instances.ennreal` -/ class pseudo_emetric_space (α : Type u) extends has_edist α : Type u := (edist_self : ∀ x : α, edist x x = 0) (edist_comm : ∀ x y : α, edist x y = edist y x) (edist_triangle : ∀ x y z : α, edist x z ≤ edist x y + edist y z) (to_uniform_space : uniform_space α := uniform_space_of_edist edist edist_self edist_comm edist_triangle) (uniformity_edist : 𝓤 α = ⨅ ε>0, 𝓟 {p:α×α | edist p.1 p.2 < ε} . control_laws_tac) /- Pseudoemetric spaces are less common than metric spaces. Therefore, we work in a dedicated namespace, while notions associated to metric spaces are mostly in the root namespace. -/ variables [pseudo_emetric_space α] @[priority 100] -- see Note [lower instance priority] instance pseudo_emetric_space.to_uniform_space' : uniform_space α := pseudo_emetric_space.to_uniform_space export pseudo_emetric_space (edist_self edist_comm edist_triangle) attribute [simp] edist_self /-- Triangle inequality for the extended distance -/ theorem edist_triangle_left (x y z : α) : edist x y ≤ edist z x + edist z y := by rw edist_comm z; apply edist_triangle theorem edist_triangle_right (x y z : α) : edist x y ≤ edist x z + edist y z := by rw edist_comm y; apply edist_triangle lemma edist_triangle4 (x y z t : α) : edist x t ≤ edist x y + edist y z + edist z t := calc edist x t ≤ edist x z + edist z t : edist_triangle x z t ... ≤ (edist x y + edist y z) + edist z t : add_le_add_right (edist_triangle x y z) _ /-- The triangle (polygon) inequality for sequences of points; `finset.Ico` version. -/ lemma edist_le_Ico_sum_edist (f : ℕ → α) {m n} (h : m ≤ n) : edist (f m) (f n) ≤ ∑ i in finset.Ico m n, edist (f i) (f (i + 1)) := begin revert n, refine nat.le_induction _ _, { simp only [finset.sum_empty, finset.Ico.self_eq_empty, edist_self], -- TODO: Why doesn't Lean close this goal automatically? `apply le_refl` fails too. exact le_refl (0:ℝ≥0∞) }, { assume n hn hrec, calc edist (f m) (f (n+1)) ≤ edist (f m) (f n) + edist (f n) (f (n+1)) : edist_triangle _ _ _ ... ≤ ∑ i in finset.Ico m n, _ + _ : add_le_add hrec (le_refl _) ... = ∑ i in finset.Ico m (n+1), _ : by rw [finset.Ico.succ_top hn, finset.sum_insert, add_comm]; simp } end /-- The triangle (polygon) inequality for sequences of points; `finset.range` version. -/ lemma edist_le_range_sum_edist (f : ℕ → α) (n : ℕ) : edist (f 0) (f n) ≤ ∑ i in finset.range n, edist (f i) (f (i + 1)) := finset.Ico.zero_bot n ▸ edist_le_Ico_sum_edist f (nat.zero_le n) /-- A version of `edist_le_Ico_sum_edist` with each intermediate distance replaced with an upper estimate. -/ lemma edist_le_Ico_sum_of_edist_le {f : ℕ → α} {m n} (hmn : m ≤ n) {d : ℕ → ℝ≥0∞} (hd : ∀ {k}, m ≤ k → k < n → edist (f k) (f (k + 1)) ≤ d k) : edist (f m) (f n) ≤ ∑ i in finset.Ico m n, d i := le_trans (edist_le_Ico_sum_edist f hmn) $ finset.sum_le_sum $ λ k hk, hd (finset.Ico.mem.1 hk).1 (finset.Ico.mem.1 hk).2 /-- A version of `edist_le_range_sum_edist` with each intermediate distance replaced with an upper estimate. -/ lemma edist_le_range_sum_of_edist_le {f : ℕ → α} (n : ℕ) {d : ℕ → ℝ≥0∞} (hd : ∀ {k}, k < n → edist (f k) (f (k + 1)) ≤ d k) : edist (f 0) (f n) ≤ ∑ i in finset.range n, d i := finset.Ico.zero_bot n ▸ edist_le_Ico_sum_of_edist_le (zero_le n) (λ _ _, hd) /-- Reformulation of the uniform structure in terms of the extended distance -/ theorem uniformity_pseudoedist : 𝓤 α = ⨅ ε>0, 𝓟 {p:α×α | edist p.1 p.2 < ε} := pseudo_emetric_space.uniformity_edist theorem uniformity_basis_edist : (𝓤 α).has_basis (λ ε : ℝ≥0∞, 0 < ε) (λ ε, {p:α×α | edist p.1 p.2 < ε}) := (@uniformity_pseudoedist α _).symm ▸ has_basis_binfi_principal (λ r hr p hp, ⟨min r p, lt_min hr hp, λ x hx, lt_of_lt_of_le hx (min_le_left _ _), λ x hx, lt_of_lt_of_le hx (min_le_right _ _)⟩) ⟨1, ennreal.zero_lt_one⟩ /-- Characterization of the elements of the uniformity in terms of the extended distance -/ theorem mem_uniformity_edist {s : set (α×α)} : s ∈ 𝓤 α ↔ (∃ε>0, ∀{a b:α}, edist a b < ε → (a, b) ∈ s) := uniformity_basis_edist.mem_uniformity_iff /-- Given `f : β → ℝ≥0∞`, if `f` sends `{i | p i}` to a set of positive numbers accumulating to zero, then `f i`-neighborhoods of the diagonal form a basis of `𝓤 α`. For specific bases see `uniformity_basis_edist`, `uniformity_basis_edist'`, `uniformity_basis_edist_nnreal`, and `uniformity_basis_edist_inv_nat`. -/ protected theorem emetric.mk_uniformity_basis {β : Type*} {p : β → Prop} {f : β → ℝ≥0∞} (hf₀ : ∀ x, p x → 0 < f x) (hf : ∀ ε, 0 < ε → ∃ x (hx : p x), f x ≤ ε) : (𝓤 α).has_basis p (λ x, {p:α×α | edist p.1 p.2 < f x}) := begin refine ⟨λ s, uniformity_basis_edist.mem_iff.trans _⟩, split, { rintros ⟨ε, ε₀, hε⟩, rcases hf ε ε₀ with ⟨i, hi, H⟩, exact ⟨i, hi, λ x hx, hε $ lt_of_lt_of_le hx H⟩ }, { exact λ ⟨i, hi, H⟩, ⟨f i, hf₀ i hi, H⟩ } end /-- Given `f : β → ℝ≥0∞`, if `f` sends `{i | p i}` to a set of positive numbers accumulating to zero, then closed `f i`-neighborhoods of the diagonal form a basis of `𝓤 α`. For specific bases see `uniformity_basis_edist_le` and `uniformity_basis_edist_le'`. -/ protected theorem emetric.mk_uniformity_basis_le {β : Type*} {p : β → Prop} {f : β → ℝ≥0∞} (hf₀ : ∀ x, p x → 0 < f x) (hf : ∀ ε, 0 < ε → ∃ x (hx : p x), f x ≤ ε) : (𝓤 α).has_basis p (λ x, {p:α×α | edist p.1 p.2 ≤ f x}) := begin refine ⟨λ s, uniformity_basis_edist.mem_iff.trans _⟩, split, { rintros ⟨ε, ε₀, hε⟩, rcases exists_between ε₀ with ⟨ε', hε'⟩, rcases hf ε' hε'.1 with ⟨i, hi, H⟩, exact ⟨i, hi, λ x hx, hε $ lt_of_le_of_lt (le_trans hx H) hε'.2⟩ }, { exact λ ⟨i, hi, H⟩, ⟨f i, hf₀ i hi, λ x hx, H (le_of_lt hx)⟩ } end theorem uniformity_basis_edist_le : (𝓤 α).has_basis (λ ε : ℝ≥0∞, 0 < ε) (λ ε, {p:α×α | edist p.1 p.2 ≤ ε}) := emetric.mk_uniformity_basis_le (λ _, id) (λ ε ε₀, ⟨ε, ε₀, le_refl ε⟩) theorem uniformity_basis_edist' (ε' : ℝ≥0∞) (hε' : 0 < ε') : (𝓤 α).has_basis (λ ε : ℝ≥0∞, ε ∈ Ioo 0 ε') (λ ε, {p:α×α | edist p.1 p.2 < ε}) := emetric.mk_uniformity_basis (λ _, and.left) (λ ε ε₀, let ⟨δ, hδ⟩ := exists_between hε' in ⟨min ε δ, ⟨lt_min ε₀ hδ.1, lt_of_le_of_lt (min_le_right _ _) hδ.2⟩, min_le_left _ _⟩) theorem uniformity_basis_edist_le' (ε' : ℝ≥0∞) (hε' : 0 < ε') : (𝓤 α).has_basis (λ ε : ℝ≥0∞, ε ∈ Ioo 0 ε') (λ ε, {p:α×α | edist p.1 p.2 ≤ ε}) := emetric.mk_uniformity_basis_le (λ _, and.left) (λ ε ε₀, let ⟨δ, hδ⟩ := exists_between hε' in ⟨min ε δ, ⟨lt_min ε₀ hδ.1, lt_of_le_of_lt (min_le_right _ _) hδ.2⟩, min_le_left _ _⟩) theorem uniformity_basis_edist_nnreal : (𝓤 α).has_basis (λ ε : ℝ≥0, 0 < ε) (λ ε, {p:α×α | edist p.1 p.2 < ε}) := emetric.mk_uniformity_basis (λ _, ennreal.coe_pos.2) (λ ε ε₀, let ⟨δ, hδ⟩ := ennreal.lt_iff_exists_nnreal_btwn.1 ε₀ in ⟨δ, ennreal.coe_pos.1 hδ.1, le_of_lt hδ.2⟩) theorem uniformity_basis_edist_inv_nat : (𝓤 α).has_basis (λ _, true) (λ n:ℕ, {p:α×α | edist p.1 p.2 < (↑n)⁻¹}) := emetric.mk_uniformity_basis (λ n _, ennreal.inv_pos.2 $ ennreal.nat_ne_top n) (λ ε ε₀, let ⟨n, hn⟩ := ennreal.exists_inv_nat_lt (ne_of_gt ε₀) in ⟨n, trivial, le_of_lt hn⟩) theorem uniformity_basis_edist_inv_two_pow : (𝓤 α).has_basis (λ _, true) (λ n:ℕ, {p:α×α | edist p.1 p.2 < 2⁻¹ ^ n}) := emetric.mk_uniformity_basis (λ n _, ennreal.pow_pos (ennreal.inv_pos.2 ennreal.two_ne_top) _) (λ ε ε₀, let ⟨n, hn⟩ := ennreal.exists_inv_two_pow_lt (ne_of_gt ε₀) in ⟨n, trivial, le_of_lt hn⟩) /-- Fixed size neighborhoods of the diagonal belong to the uniform structure -/ theorem edist_mem_uniformity {ε:ℝ≥0∞} (ε0 : 0 < ε) : {p:α×α | edist p.1 p.2 < ε} ∈ 𝓤 α := mem_uniformity_edist.2 ⟨ε, ε0, λ a b, id⟩ namespace emetric theorem uniformity_has_countable_basis : is_countably_generated (𝓤 α) := is_countably_generated_of_seq ⟨_, uniformity_basis_edist_inv_nat.eq_infi⟩ /-- ε-δ characterization of uniform continuity on a set for pseudoemetric spaces -/ theorem uniform_continuous_on_iff [pseudo_emetric_space β] {f : α → β} {s : set α} : uniform_continuous_on f s ↔ ∀ ε > 0, ∃ δ > 0, ∀{a b}, a ∈ s → b ∈ s → edist a b < δ → edist (f a) (f b) < ε := uniformity_basis_edist.uniform_continuous_on_iff uniformity_basis_edist /-- ε-δ characterization of uniform continuity on pseudoemetric spaces -/ theorem uniform_continuous_iff [pseudo_emetric_space β] {f : α → β} : uniform_continuous f ↔ ∀ ε > 0, ∃ δ > 0, ∀{a b:α}, edist a b < δ → edist (f a) (f b) < ε := uniformity_basis_edist.uniform_continuous_iff uniformity_basis_edist /-- ε-δ characterization of uniform embeddings on pseudoemetric spaces -/ theorem uniform_embedding_iff [pseudo_emetric_space β] {f : α → β} : uniform_embedding f ↔ function.injective f ∧ uniform_continuous f ∧ ∀ δ > 0, ∃ ε > 0, ∀ {a b : α}, edist (f a) (f b) < ε → edist a b < δ := uniform_embedding_def'.trans $ and_congr iff.rfl $ and_congr iff.rfl ⟨λ H δ δ0, let ⟨t, tu, ht⟩ := H _ (edist_mem_uniformity δ0), ⟨ε, ε0, hε⟩ := mem_uniformity_edist.1 tu in ⟨ε, ε0, λ a b h, ht _ _ (hε h)⟩, λ H s su, let ⟨δ, δ0, hδ⟩ := mem_uniformity_edist.1 su, ⟨ε, ε0, hε⟩ := H _ δ0 in ⟨_, edist_mem_uniformity ε0, λ a b h, hδ (hε h)⟩⟩ /-- If a map between pseudoemetric spaces is a uniform embedding then the edistance between `f x` and `f y` is controlled in terms of the distance between `x` and `y`. -/ theorem controlled_of_uniform_embedding [pseudo_emetric_space β] {f : α → β} : uniform_embedding f → (∀ ε > 0, ∃ δ > 0, ∀ {a b : α}, edist a b < δ → edist (f a) (f b) < ε) ∧ (∀ δ > 0, ∃ ε > 0, ∀ {a b : α}, edist (f a) (f b) < ε → edist a b < δ) := begin assume h, exact ⟨uniform_continuous_iff.1 (uniform_embedding_iff.1 h).2.1, (uniform_embedding_iff.1 h).2.2⟩, end /-- ε-δ characterization of Cauchy sequences on pseudoemetric spaces -/ protected lemma cauchy_iff {f : filter α} : cauchy f ↔ f ≠ ⊥ ∧ ∀ ε > 0, ∃ t ∈ f, ∀ x y ∈ t, edist x y < ε := by rw ← ne_bot_iff; exact uniformity_basis_edist.cauchy_iff /-- A very useful criterion to show that a space is complete is to show that all sequences which satisfy a bound of the form `edist (u n) (u m) < B N` for all `n m ≥ N` are converging. This is often applied for `B N = 2^{-N}`, i.e., with a very fast convergence to `0`, which makes it possible to use arguments of converging series, while this is impossible to do in general for arbitrary Cauchy sequences. -/ theorem complete_of_convergent_controlled_sequences (B : ℕ → ℝ≥0∞) (hB : ∀n, 0 < B n) (H : ∀u : ℕ → α, (∀N n m : ℕ, N ≤ n → N ≤ m → edist (u n) (u m) < B N) → ∃x, tendsto u at_top (𝓝 x)) : complete_space α := uniform_space.complete_of_convergent_controlled_sequences uniformity_has_countable_basis (λ n, {p:α×α | edist p.1 p.2 < B n}) (λ n, edist_mem_uniformity $ hB n) H /-- A sequentially complete pseudoemetric space is complete. -/ theorem complete_of_cauchy_seq_tendsto : (∀ u : ℕ → α, cauchy_seq u → ∃a, tendsto u at_top (𝓝 a)) → complete_space α := uniform_space.complete_of_cauchy_seq_tendsto uniformity_has_countable_basis /-- Expressing locally uniform convergence on a set using `edist`. -/ lemma tendsto_locally_uniformly_on_iff {ι : Type*} [topological_space β] {F : ι → β → α} {f : β → α} {p : filter ι} {s : set β} : tendsto_locally_uniformly_on F f p s ↔ ∀ ε > 0, ∀ x ∈ s, ∃ t ∈ 𝓝[s] x, ∀ᶠ n in p, ∀ y ∈ t, edist (f y) (F n y) < ε := begin refine ⟨λ H ε hε, H _ (edist_mem_uniformity hε), λ H u hu x hx, _⟩, rcases mem_uniformity_edist.1 hu with ⟨ε, εpos, hε⟩, rcases H ε εpos x hx with ⟨t, ht, Ht⟩, exact ⟨t, ht, Ht.mono (λ n hs x hx, hε (hs x hx))⟩ end /-- Expressing uniform convergence on a set using `edist`. -/ lemma tendsto_uniformly_on_iff {ι : Type*} {F : ι → β → α} {f : β → α} {p : filter ι} {s : set β} : tendsto_uniformly_on F f p s ↔ ∀ ε > 0, ∀ᶠ n in p, ∀ x ∈ s, edist (f x) (F n x) < ε := begin refine ⟨λ H ε hε, H _ (edist_mem_uniformity hε), λ H u hu, _⟩, rcases mem_uniformity_edist.1 hu with ⟨ε, εpos, hε⟩, exact (H ε εpos).mono (λ n hs x hx, hε (hs x hx)) end /-- Expressing locally uniform convergence using `edist`. -/ lemma tendsto_locally_uniformly_iff {ι : Type*} [topological_space β] {F : ι → β → α} {f : β → α} {p : filter ι} : tendsto_locally_uniformly F f p ↔ ∀ ε > 0, ∀ (x : β), ∃ t ∈ 𝓝 x, ∀ᶠ n in p, ∀ y ∈ t, edist (f y) (F n y) < ε := by simp only [← tendsto_locally_uniformly_on_univ, tendsto_locally_uniformly_on_iff, mem_univ, forall_const, exists_prop, nhds_within_univ] /-- Expressing uniform convergence using `edist`. -/ lemma tendsto_uniformly_iff {ι : Type*} {F : ι → β → α} {f : β → α} {p : filter ι} : tendsto_uniformly F f p ↔ ∀ ε > 0, ∀ᶠ n in p, ∀ x, edist (f x) (F n x) < ε := by simp only [← tendsto_uniformly_on_univ, tendsto_uniformly_on_iff, mem_univ, forall_const] end emetric open emetric /-- Auxiliary function to replace the uniformity on a pseudoemetric space with a uniformity which is equal to the original one, but maybe not defeq. This is useful if one wants to construct a pseudoemetric space with a specified uniformity. See Note [forgetful inheritance] explaining why having definitionally the right uniformity is often important. -/ def pseudo_emetric_space.replace_uniformity {α} [U : uniform_space α] (m : pseudo_emetric_space α) (H : @uniformity _ U = @uniformity _ pseudo_emetric_space.to_uniform_space) : pseudo_emetric_space α := { edist := @edist _ m.to_has_edist, edist_self := edist_self, edist_comm := edist_comm, edist_triangle := edist_triangle, to_uniform_space := U, uniformity_edist := H.trans (@pseudo_emetric_space.uniformity_edist α _) } /-- The extended pseudometric induced by a function taking values in a pseudoemetric space. -/ def pseudo_emetric_space.induced {α β} (f : α → β) (m : pseudo_emetric_space β) : pseudo_emetric_space α := { edist := λ x y, edist (f x) (f y), edist_self := λ x, edist_self _, edist_comm := λ x y, edist_comm _ _, edist_triangle := λ x y z, edist_triangle _ _ _, to_uniform_space := uniform_space.comap f m.to_uniform_space, uniformity_edist := begin apply @uniformity_dist_of_mem_uniformity _ _ _ _ _ (λ x y, edist (f x) (f y)), refine λ s, mem_comap.trans _, split; intro H, { rcases H with ⟨r, ru, rs⟩, rcases mem_uniformity_edist.1 ru with ⟨ε, ε0, hε⟩, refine ⟨ε, ε0, λ a b h, rs (hε _)⟩, exact h }, { rcases H with ⟨ε, ε0, hε⟩, exact ⟨_, edist_mem_uniformity ε0, λ ⟨a, b⟩, hε⟩ } end } /-- Pseudoemetric space instance on subsets of pseudoemetric spaces -/ instance {α : Type*} {p : α → Prop} [t : pseudo_emetric_space α] : pseudo_emetric_space (subtype p) := t.induced coe /-- The extended psuedodistance on a subset of a pseudoemetric space is the restriction of the original pseudodistance, by definition -/ theorem subtype.edist_eq {p : α → Prop} (x y : subtype p) : edist x y = edist (x : α) y := rfl /-- The product of two pseudoemetric spaces, with the max distance, is an extended pseudometric spaces. We make sure that the uniform structure thus constructed is the one corresponding to the product of uniform spaces, to avoid diamond problems. -/ instance prod.pseudo_emetric_space_max [pseudo_emetric_space β] : pseudo_emetric_space (α × β) := { edist := λ x y, max (edist x.1 y.1) (edist x.2 y.2), edist_self := λ x, by simp, edist_comm := λ x y, by simp [edist_comm], edist_triangle := λ x y z, max_le (le_trans (edist_triangle _ _ _) (add_le_add (le_max_left _ _) (le_max_left _ _))) (le_trans (edist_triangle _ _ _) (add_le_add (le_max_right _ _) (le_max_right _ _))), uniformity_edist := begin refine uniformity_prod.trans _, simp [pseudo_emetric_space.uniformity_edist, comap_infi], rw ← infi_inf_eq, congr, funext, rw ← infi_inf_eq, congr, funext, simp [inf_principal, ext_iff, max_lt_iff] end, to_uniform_space := prod.uniform_space } lemma prod.edist_eq [pseudo_emetric_space β] (x y : α × β) : edist x y = max (edist x.1 y.1) (edist x.2 y.2) := rfl section pi open finset variables {π : β → Type*} [fintype β] /-- The product of a finite number of pseudoemetric spaces, with the max distance, is still a pseudoemetric space. This construction would also work for infinite products, but it would not give rise to the product topology. Hence, we only formalize it in the good situation of finitely many spaces. -/ instance pseudo_emetric_space_pi [∀b, pseudo_emetric_space (π b)] : pseudo_emetric_space (Πb, π b) := { edist := λ f g, finset.sup univ (λb, edist (f b) (g b)), edist_self := assume f, bot_unique $ finset.sup_le $ by simp, edist_comm := assume f g, by unfold edist; congr; funext a; exact edist_comm _ _, edist_triangle := assume f g h, begin simp only [finset.sup_le_iff], assume b hb, exact le_trans (edist_triangle _ (g b) _) (add_le_add (le_sup hb) (le_sup hb)) end, to_uniform_space := Pi.uniform_space _, uniformity_edist := begin simp only [Pi.uniformity, pseudo_emetric_space.uniformity_edist, comap_infi, gt_iff_lt, preimage_set_of_eq, comap_principal], rw infi_comm, congr, funext ε, rw infi_comm, congr, funext εpos, change 0 < ε at εpos, simp [set.ext_iff, εpos] end } lemma edist_pi_def [Π b, pseudo_emetric_space (π b)] (f g : Π b, π b) : edist f g = finset.sup univ (λb, edist (f b) (g b)) := rfl @[simp] lemma edist_pi_const [nonempty β] (a b : α) : edist (λ x : β, a) (λ _, b) = edist a b := finset.sup_const univ_nonempty (edist a b) lemma edist_le_pi_edist [Π b, pseudo_emetric_space (π b)] (f g : Π b, π b) (b : β) : edist (f b) (g b) ≤ edist f g := finset.le_sup (finset.mem_univ b) lemma edist_pi_le_iff [Π b, pseudo_emetric_space (π b)] {f g : Π b, π b} {d : ℝ≥0∞} : edist f g ≤ d ↔ ∀ b, edist (f b) (g b) ≤ d := finset.sup_le_iff.trans $ by simp only [finset.mem_univ, forall_const] end pi namespace emetric variables {x y z : α} {ε ε₁ ε₂ : ℝ≥0∞} {s : set α} /-- `emetric.ball x ε` is the set of all points `y` with `edist y x < ε` -/ def ball (x : α) (ε : ℝ≥0∞) : set α := {y | edist y x < ε} @[simp] theorem mem_ball : y ∈ ball x ε ↔ edist y x < ε := iff.rfl theorem mem_ball' : y ∈ ball x ε ↔ edist x y < ε := by rw edist_comm; refl /-- `emetric.closed_ball x ε` is the set of all points `y` with `edist y x ≤ ε` -/ def closed_ball (x : α) (ε : ℝ≥0∞) := {y | edist y x ≤ ε} @[simp] theorem mem_closed_ball : y ∈ closed_ball x ε ↔ edist y x ≤ ε := iff.rfl @[simp] theorem closed_ball_top (x : α) : closed_ball x ∞ = univ := eq_univ_of_forall $ λ y, @le_top _ _ (edist y x) theorem ball_subset_closed_ball : ball x ε ⊆ closed_ball x ε := assume y hy, le_of_lt hy theorem pos_of_mem_ball (hy : y ∈ ball x ε) : 0 < ε := lt_of_le_of_lt (zero_le _) hy theorem mem_ball_self (h : 0 < ε) : x ∈ ball x ε := show edist x x < ε, by rw edist_self; assumption theorem mem_closed_ball_self : x ∈ closed_ball x ε := show edist x x ≤ ε, by rw edist_self; exact bot_le theorem mem_ball_comm : x ∈ ball y ε ↔ y ∈ ball x ε := by simp [edist_comm] theorem ball_subset_ball (h : ε₁ ≤ ε₂) : ball x ε₁ ⊆ ball x ε₂ := λ y (yx : _ < ε₁), lt_of_lt_of_le yx h theorem closed_ball_subset_closed_ball (h : ε₁ ≤ ε₂) : closed_ball x ε₁ ⊆ closed_ball x ε₂ := λ y (yx : _ ≤ ε₁), le_trans yx h theorem ball_disjoint (h : ε₁ + ε₂ ≤ edist x y) : ball x ε₁ ∩ ball y ε₂ = ∅ := eq_empty_iff_forall_not_mem.2 $ λ z ⟨h₁, h₂⟩, not_lt_of_le (edist_triangle_left x y z) (lt_of_lt_of_le (ennreal.add_lt_add h₁ h₂) h) theorem ball_subset (h : edist x y + ε₁ ≤ ε₂) (h' : edist x y ≠ ∞) : ball x ε₁ ⊆ ball y ε₂ := λ z zx, calc edist z y ≤ edist z x + edist x y : edist_triangle _ _ _ ... = edist x y + edist z x : add_comm _ _ ... < edist x y + ε₁ : (ennreal.add_lt_add_iff_left h').2 zx ... ≤ ε₂ : h theorem exists_ball_subset_ball (h : y ∈ ball x ε) : ∃ ε' > 0, ball y ε' ⊆ ball x ε := begin have : 0 < ε - edist y x := by simpa using h, refine ⟨ε - edist y x, this, ball_subset _ (ne_top_of_lt h)⟩, rw ennreal.add_sub_cancel_of_le (le_of_lt h), exact le_refl ε end theorem ball_eq_empty_iff : ball x ε = ∅ ↔ ε = 0 := eq_empty_iff_forall_not_mem.trans ⟨λh, le_bot_iff.1 (le_of_not_gt (λ ε0, h _ (mem_ball_self ε0))), λε0 y h, not_lt_of_le (le_of_eq ε0) (pos_of_mem_ball h)⟩ /-- Relation “two points are at a finite edistance” is an equivalence relation. -/ def edist_lt_top_setoid : setoid α := { r := λ x y, edist x y < ⊤, iseqv := ⟨λ x, by { rw edist_self, exact ennreal.coe_lt_top }, λ x y h, by rwa edist_comm, λ x y z hxy hyz, lt_of_le_of_lt (edist_triangle x y z) (ennreal.add_lt_top.2 ⟨hxy, hyz⟩)⟩ } @[simp] lemma ball_zero : ball x 0 = ∅ := by rw [emetric.ball_eq_empty_iff] theorem nhds_basis_eball : (𝓝 x).has_basis (λ ε:ℝ≥0∞, 0 < ε) (ball x) := nhds_basis_uniformity uniformity_basis_edist theorem nhds_basis_closed_eball : (𝓝 x).has_basis (λ ε:ℝ≥0∞, 0 < ε) (closed_ball x) := nhds_basis_uniformity uniformity_basis_edist_le theorem nhds_eq : 𝓝 x = (⨅ε>0, 𝓟 (ball x ε)) := nhds_basis_eball.eq_binfi theorem mem_nhds_iff : s ∈ 𝓝 x ↔ ∃ε>0, ball x ε ⊆ s := nhds_basis_eball.mem_iff theorem is_open_iff : is_open s ↔ ∀x∈s, ∃ε>0, ball x ε ⊆ s := by simp [is_open_iff_nhds, mem_nhds_iff] theorem is_open_ball : is_open (ball x ε) := is_open_iff.2 $ λ y, exists_ball_subset_ball theorem is_closed_ball_top : is_closed (ball x ⊤) := is_open_compl_iff.1 $ is_open_iff.2 $ λ y hy, ⟨⊤, ennreal.coe_lt_top, subset_compl_iff_disjoint.2 $ ball_disjoint $ by { rw ennreal.top_add, exact le_of_not_lt hy }⟩ theorem ball_mem_nhds (x : α) {ε : ℝ≥0∞} (ε0 : 0 < ε) : ball x ε ∈ 𝓝 x := is_open_ball.mem_nhds (mem_ball_self ε0) theorem closed_ball_mem_nhds (x : α) {ε : ℝ≥0∞} (ε0 : 0 < ε) : closed_ball x ε ∈ 𝓝 x := mem_of_superset (ball_mem_nhds x ε0) ball_subset_closed_ball theorem ball_prod_same [pseudo_emetric_space β] (x : α) (y : β) (r : ℝ≥0∞) : (ball x r).prod (ball y r) = ball (x, y) r := ext $ λ z, max_lt_iff.symm theorem closed_ball_prod_same [pseudo_emetric_space β] (x : α) (y : β) (r : ℝ≥0∞) : (closed_ball x r).prod (closed_ball y r) = closed_ball (x, y) r := ext $ λ z, max_le_iff.symm /-- ε-characterization of the closure in pseudoemetric spaces -/ theorem mem_closure_iff : x ∈ closure s ↔ ∀ε>0, ∃y ∈ s, edist x y < ε := (mem_closure_iff_nhds_basis nhds_basis_eball).trans $ by simp only [mem_ball, edist_comm x] theorem tendsto_nhds {f : filter β} {u : β → α} {a : α} : tendsto u f (𝓝 a) ↔ ∀ ε > 0, ∀ᶠ x in f, edist (u x) a < ε := nhds_basis_eball.tendsto_right_iff theorem tendsto_at_top [nonempty β] [semilattice_sup β] {u : β → α} {a : α} : tendsto u at_top (𝓝 a) ↔ ∀ε>0, ∃N, ∀n≥N, edist (u n) a < ε := (at_top_basis.tendsto_iff nhds_basis_eball).trans $ by simp only [exists_prop, true_and, mem_Ici, mem_ball] /-- In a pseudoemetric space, Cauchy sequences are characterized by the fact that, eventually, the pseudoedistance between its elements is arbitrarily small -/ @[nolint ge_or_gt] -- see Note [nolint_ge] theorem cauchy_seq_iff [nonempty β] [semilattice_sup β] {u : β → α} : cauchy_seq u ↔ ∀ε>0, ∃N, ∀m n≥N, edist (u m) (u n) < ε := uniformity_basis_edist.cauchy_seq_iff /-- A variation around the emetric characterization of Cauchy sequences -/ theorem cauchy_seq_iff' [nonempty β] [semilattice_sup β] {u : β → α} : cauchy_seq u ↔ ∀ε>(0 : ℝ≥0∞), ∃N, ∀n≥N, edist (u n) (u N) < ε := uniformity_basis_edist.cauchy_seq_iff' /-- A variation of the emetric characterization of Cauchy sequences that deals with `ℝ≥0` upper bounds. -/ theorem cauchy_seq_iff_nnreal [nonempty β] [semilattice_sup β] {u : β → α} : cauchy_seq u ↔ ∀ ε : ℝ≥0, 0 < ε → ∃ N, ∀ n, N ≤ n → edist (u n) (u N) < ε := uniformity_basis_edist_nnreal.cauchy_seq_iff' theorem totally_bounded_iff {s : set α} : totally_bounded s ↔ ∀ ε > 0, ∃t : set α, finite t ∧ s ⊆ ⋃y∈t, ball y ε := ⟨λ H ε ε0, H _ (edist_mem_uniformity ε0), λ H r ru, let ⟨ε, ε0, hε⟩ := mem_uniformity_edist.1 ru, ⟨t, ft, h⟩ := H ε ε0 in ⟨t, ft, subset.trans h $ Union_subset_Union $ λ y, Union_subset_Union $ λ yt z, hε⟩⟩ theorem totally_bounded_iff' {s : set α} : totally_bounded s ↔ ∀ ε > 0, ∃t⊆s, finite t ∧ s ⊆ ⋃y∈t, ball y ε := ⟨λ H ε ε0, (totally_bounded_iff_subset.1 H) _ (edist_mem_uniformity ε0), λ H r ru, let ⟨ε, ε0, hε⟩ := mem_uniformity_edist.1 ru, ⟨t, _, ft, h⟩ := H ε ε0 in ⟨t, ft, subset.trans h $ Union_subset_Union $ λ y, Union_subset_Union $ λ yt z, hε⟩⟩ section first_countable @[priority 100] -- see Note [lower instance priority] instance (α : Type u) [pseudo_emetric_space α] : topological_space.first_countable_topology α := uniform_space.first_countable_topology uniformity_has_countable_basis end first_countable section compact /-- For a set `s` in a pseudo emetric space, if for every `ε > 0` there exists a countable set that is `ε`-dense in `s`, then there exists a countable subset `t ⊆ s` that is dense in `s`. -/ lemma subset_countable_closure_of_almost_dense_set (s : set α) (hs : ∀ ε > 0, ∃ t : set α, countable t ∧ s ⊆ ⋃ x ∈ t, closed_ball x ε) : ∃ t ⊆ s, (countable t ∧ s ⊆ closure t) := begin rcases s.eq_empty_or_nonempty with rfl|⟨x₀, hx₀⟩, { exact ⟨∅, empty_subset _, countable_empty, empty_subset _⟩ }, choose! T hTc hsT using (λ n : ℕ, hs n⁻¹ (by simp)), have : ∀ r x, ∃ y ∈ s, closed_ball x r ∩ s ⊆ closed_ball y (r * 2), { intros r x, rcases (closed_ball x r ∩ s).eq_empty_or_nonempty with he|⟨y, hxy, hys⟩, { refine ⟨x₀, hx₀, _⟩, rw he, exact empty_subset _ }, { refine ⟨y, hys, λ z hz, _⟩, calc edist z y ≤ edist z x + edist y x : edist_triangle_right _ _ _ ... ≤ r + r : add_le_add hz.1 hxy ... = r * 2 : (mul_two r).symm } }, choose f hfs hf, refine ⟨⋃ n : ℕ, (f n⁻¹) '' (T n), Union_subset $ λ n, image_subset_iff.2 (λ z hz, hfs _ _), countable_Union $ λ n, (hTc n).image _, _⟩, refine λ x hx, mem_closure_iff.2 (λ ε ε0, _), rcases ennreal.exists_inv_nat_lt (ennreal.half_pos ε0).ne' with ⟨n, hn⟩, rcases mem_bUnion_iff.1 (hsT n hx) with ⟨y, hyn, hyx⟩, refine ⟨f n⁻¹ y, mem_Union.2 ⟨n, mem_image_of_mem _ hyn⟩, _⟩, calc edist x (f n⁻¹ y) ≤ n⁻¹ * 2 : hf _ _ ⟨hyx, hx⟩ ... < ε : ennreal.mul_lt_of_lt_div hn end /-- A compact set in a pseudo emetric space is separable, i.e., it is a subset of the closure of a countable set. -/ lemma subset_countable_closure_of_compact {s : set α} (hs : is_compact s) : ∃ t ⊆ s, (countable t ∧ s ⊆ closure t) := begin refine subset_countable_closure_of_almost_dense_set s (λ ε hε, _), rcases totally_bounded_iff'.1 hs.totally_bounded ε hε with ⟨t, hts, htf, hst⟩, exact ⟨t, htf.countable, subset.trans hst (bUnion_subset_bUnion_right $ λ _ _, ball_subset_closed_ball)⟩ end end compact section second_countable open topological_space variables (α) /-- A separable pseudoemetric space is second countable: one obtains a countable basis by taking the balls centered at points in a dense subset, and with rational radii. We do not register this as an instance, as there is already an instance going in the other direction from second countable spaces to separable spaces, and we want to avoid loops. -/ lemma second_countable_of_separable [separable_space α] : second_countable_topology α := uniform_space.second_countable_of_separable uniformity_has_countable_basis /-- A sigma compact pseudo emetric space has second countable topology. This is not an instance to avoid a loop with `sigma_compact_space_of_locally_compact_second_countable`. -/ lemma second_countable_of_sigma_compact [sigma_compact_space α] : second_countable_topology α := begin suffices : separable_space α, by exactI second_countable_of_separable α, choose T hTsub hTc hsubT using λ n, subset_countable_closure_of_compact (is_compact_compact_covering α n), refine ⟨⟨⋃ n, T n, countable_Union hTc, λ x, _⟩⟩, rcases Union_eq_univ_iff.1 (Union_compact_covering α) x with ⟨n, hn⟩, exact closure_mono (subset_Union _ n) (hsubT _ hn) end variable {α} lemma second_countable_of_almost_dense_set (hs : ∀ ε > 0, ∃ t : set α, countable t ∧ (⋃ x ∈ t, closed_ball x ε) = univ) : second_countable_topology α := begin suffices : separable_space α, by exactI second_countable_of_separable α, rcases subset_countable_closure_of_almost_dense_set (univ : set α) (λ ε ε0, _) with ⟨t, -, htc, ht⟩, { exact ⟨⟨t, htc, λ x, ht (mem_univ x)⟩⟩ }, { rcases hs ε ε0 with ⟨t, htc, ht⟩, exact ⟨t, htc, univ_subset_iff.2 ht⟩ } end end second_countable section diam /-- The diameter of a set in a pseudoemetric space, named `emetric.diam` -/ def diam (s : set α) := ⨆ (x ∈ s) (y ∈ s), edist x y lemma diam_le_iff {d : ℝ≥0∞} : diam s ≤ d ↔ ∀ (x ∈ s) (y ∈ s), edist x y ≤ d := by simp only [diam, supr_le_iff] lemma diam_image_le_iff {d : ℝ≥0∞} {f : β → α} {s : set β} : diam (f '' s) ≤ d ↔ ∀ (x ∈ s) (y ∈ s), edist (f x) (f y) ≤ d := by simp only [diam_le_iff, ball_image_iff] lemma edist_le_of_diam_le {d} (hx : x ∈ s) (hy : y ∈ s) (hd : diam s ≤ d) : edist x y ≤ d := diam_le_iff.1 hd x hx y hy /-- If two points belong to some set, their edistance is bounded by the diameter of the set -/ lemma edist_le_diam_of_mem (hx : x ∈ s) (hy : y ∈ s) : edist x y ≤ diam s := edist_le_of_diam_le hx hy le_rfl /-- If the distance between any two points in a set is bounded by some constant, this constant bounds the diameter. -/ lemma diam_le {d : ℝ≥0∞} (h : ∀ (x ∈ s) (y ∈ s), edist x y ≤ d) : diam s ≤ d := diam_le_iff.2 h /-- The diameter of a subsingleton vanishes. -/ lemma diam_subsingleton (hs : s.subsingleton) : diam s = 0 := nonpos_iff_eq_zero.1 $ diam_le $ λ x hx y hy, (hs hx hy).symm ▸ edist_self y ▸ le_rfl /-- The diameter of the empty set vanishes -/ @[simp] lemma diam_empty : diam (∅ : set α) = 0 := diam_subsingleton subsingleton_empty /-- The diameter of a singleton vanishes -/ @[simp] lemma diam_singleton : diam ({x} : set α) = 0 := diam_subsingleton subsingleton_singleton lemma diam_Union_mem_option {ι : Type*} (o : option ι) (s : ι → set α) : diam (⋃ i ∈ o, s i) = ⨆ i ∈ o, diam (s i) := by cases o; simp lemma diam_insert : diam (insert x s) = max (⨆ y ∈ s, edist x y) (diam s) := eq_of_forall_ge_iff $ λ d, by simp only [diam_le_iff, ball_insert_iff, edist_self, edist_comm x, max_le_iff, supr_le_iff, zero_le, true_and, forall_and_distrib, and_self, ← and_assoc] lemma diam_pair : diam ({x, y} : set α) = edist x y := by simp only [supr_singleton, diam_insert, diam_singleton, ennreal.max_zero_right] lemma diam_triple : diam ({x, y, z} : set α) = max (max (edist x y) (edist x z)) (edist y z) := by simp only [diam_insert, supr_insert, supr_singleton, diam_singleton, ennreal.max_zero_right, ennreal.sup_eq_max] /-- The diameter is monotonous with respect to inclusion -/ lemma diam_mono {s t : set α} (h : s ⊆ t) : diam s ≤ diam t := diam_le $ λ x hx y hy, edist_le_diam_of_mem (h hx) (h hy) /-- The diameter of a union is controlled by the diameter of the sets, and the edistance between two points in the sets. -/ lemma diam_union {t : set α} (xs : x ∈ s) (yt : y ∈ t) : diam (s ∪ t) ≤ diam s + edist x y + diam t := begin have A : ∀a ∈ s, ∀b ∈ t, edist a b ≤ diam s + edist x y + diam t := λa ha b hb, calc edist a b ≤ edist a x + edist x y + edist y b : edist_triangle4 _ _ _ _ ... ≤ diam s + edist x y + diam t : add_le_add (add_le_add (edist_le_diam_of_mem ha xs) (le_refl _)) (edist_le_diam_of_mem yt hb), refine diam_le (λa ha b hb, _), cases (mem_union _ _ _).1 ha with h'a h'a; cases (mem_union _ _ _).1 hb with h'b h'b, { calc edist a b ≤ diam s : edist_le_diam_of_mem h'a h'b ... ≤ diam s + (edist x y + diam t) : le_self_add ... = diam s + edist x y + diam t : (add_assoc _ _ _).symm }, { exact A a h'a b h'b }, { have Z := A b h'b a h'a, rwa [edist_comm] at Z }, { calc edist a b ≤ diam t : edist_le_diam_of_mem h'a h'b ... ≤ (diam s + edist x y) + diam t : le_add_self } end lemma diam_union' {t : set α} (h : (s ∩ t).nonempty) : diam (s ∪ t) ≤ diam s + diam t := let ⟨x, ⟨xs, xt⟩⟩ := h in by simpa using diam_union xs xt lemma diam_closed_ball {r : ℝ≥0∞} : diam (closed_ball x r) ≤ 2 * r := diam_le $ λa ha b hb, calc edist a b ≤ edist a x + edist b x : edist_triangle_right _ _ _ ... ≤ r + r : add_le_add ha hb ... = 2 * r : (two_mul r).symm lemma diam_ball {r : ℝ≥0∞} : diam (ball x r) ≤ 2 * r := le_trans (diam_mono ball_subset_closed_ball) diam_closed_ball lemma diam_pi_le_of_le {π : β → Type*} [fintype β] [∀ b, pseudo_emetric_space (π b)] {s : Π (b : β), set (π b)} {c : ℝ≥0∞} (h : ∀ b, diam (s b) ≤ c) : diam (set.pi univ s) ≤ c := begin apply diam_le (λ x hx y hy, edist_pi_le_iff.mpr _), rw [mem_univ_pi] at hx hy, exact λ b, diam_le_iff.1 (h b) (x b) (hx b) (y b) (hy b), end end diam end emetric --namespace /-- We now define `emetric_space`, extending `pseudo_emetric_space`. -/ class emetric_space (α : Type u) extends pseudo_emetric_space α : Type u := (eq_of_edist_eq_zero : ∀ {x y : α}, edist x y = 0 → x = y) variables {γ : Type w} [emetric_space γ] @[priority 100] -- see Note [lower instance priority] instance emetric_space.to_uniform_space' : uniform_space γ := pseudo_emetric_space.to_uniform_space export emetric_space (eq_of_edist_eq_zero) /-- Characterize the equality of points by the vanishing of their extended distance -/ @[simp] theorem edist_eq_zero {x y : γ} : edist x y = 0 ↔ x = y := iff.intro eq_of_edist_eq_zero (assume : x = y, this ▸ edist_self _) @[simp] theorem zero_eq_edist {x y : γ} : 0 = edist x y ↔ x = y := iff.intro (assume h, eq_of_edist_eq_zero (h.symm)) (assume : x = y, this ▸ (edist_self _).symm) theorem edist_le_zero {x y : γ} : (edist x y ≤ 0) ↔ x = y := nonpos_iff_eq_zero.trans edist_eq_zero @[simp] theorem edist_pos {x y : γ} : 0 < edist x y ↔ x ≠ y := by simp [← not_le] /-- Two points coincide if their distance is `< ε` for all positive ε -/ theorem eq_of_forall_edist_le {x y : γ} (h : ∀ε > 0, edist x y ≤ ε) : x = y := eq_of_edist_eq_zero (eq_of_le_of_forall_le_of_dense bot_le h) /-- A map between emetric spaces is a uniform embedding if and only if the edistance between `f x` and `f y` is controlled in terms of the distance between `x` and `y` and conversely. -/ theorem uniform_embedding_iff' [emetric_space β] {f : γ → β} : uniform_embedding f ↔ (∀ ε > 0, ∃ δ > 0, ∀ {a b : γ}, edist a b < δ → edist (f a) (f b) < ε) ∧ (∀ δ > 0, ∃ ε > 0, ∀ {a b : γ}, edist (f a) (f b) < ε → edist a b < δ) := begin split, { assume h, exact ⟨emetric.uniform_continuous_iff.1 (uniform_embedding_iff.1 h).2.1, (uniform_embedding_iff.1 h).2.2⟩ }, { rintros ⟨h₁, h₂⟩, refine uniform_embedding_iff.2 ⟨_, emetric.uniform_continuous_iff.2 h₁, h₂⟩, assume x y hxy, have : edist x y ≤ 0, { refine le_of_forall_lt' (λδ δpos, _), rcases h₂ δ δpos with ⟨ε, εpos, hε⟩, have : edist (f x) (f y) < ε, by simpa [hxy], exact hε this }, simpa using this } end /-- An emetric space is separated -/ @[priority 100] -- see Note [lower instance priority] instance to_separated : separated_space γ := separated_def.2 $ λ x y h, eq_of_forall_edist_le $ λ ε ε0, le_of_lt (h _ (edist_mem_uniformity ε0)) /-- If a `pseudo_emetric_space` is separated, then it is an `emetric_space`. -/ def emetric_of_t2_pseudo_emetric_space {α : Type*} [pseudo_emetric_space α] (h : separated_space α) : emetric_space α := { eq_of_edist_eq_zero := λ x y hdist, begin refine separated_def.1 h x y (λ s hs, _), obtain ⟨ε, hε, H⟩ := mem_uniformity_edist.1 hs, exact H (show edist x y < ε, by rwa [hdist]) end ..‹pseudo_emetric_space α› } /-- Auxiliary function to replace the uniformity on an emetric space with a uniformity which is equal to the original one, but maybe not defeq. This is useful if one wants to construct an emetric space with a specified uniformity. See Note [forgetful inheritance] explaining why having definitionally the right uniformity is often important. -/ def emetric_space.replace_uniformity {γ} [U : uniform_space γ] (m : emetric_space γ) (H : @uniformity _ U = @uniformity _ pseudo_emetric_space.to_uniform_space) : emetric_space γ := { edist := @edist _ m.to_has_edist, edist_self := edist_self, eq_of_edist_eq_zero := @eq_of_edist_eq_zero _ _, edist_comm := edist_comm, edist_triangle := edist_triangle, to_uniform_space := U, uniformity_edist := H.trans (@pseudo_emetric_space.uniformity_edist γ _) } /-- The extended metric induced by an injective function taking values in a emetric space. -/ def emetric_space.induced {γ β} (f : γ → β) (hf : function.injective f) (m : emetric_space β) : emetric_space γ := { edist := λ x y, edist (f x) (f y), edist_self := λ x, edist_self _, eq_of_edist_eq_zero := λ x y h, hf (edist_eq_zero.1 h), edist_comm := λ x y, edist_comm _ _, edist_triangle := λ x y z, edist_triangle _ _ _, to_uniform_space := uniform_space.comap f m.to_uniform_space, uniformity_edist := begin apply @uniformity_dist_of_mem_uniformity _ _ _ _ _ (λ x y, edist (f x) (f y)), refine λ s, mem_comap.trans _, split; intro H, { rcases H with ⟨r, ru, rs⟩, rcases mem_uniformity_edist.1 ru with ⟨ε, ε0, hε⟩, refine ⟨ε, ε0, λ a b h, rs (hε _)⟩, exact h }, { rcases H with ⟨ε, ε0, hε⟩, exact ⟨_, edist_mem_uniformity ε0, λ ⟨a, b⟩, hε⟩ } end } /-- Emetric space instance on subsets of emetric spaces -/ instance {α : Type*} {p : α → Prop} [t : emetric_space α] : emetric_space (subtype p) := t.induced coe (λ x y, subtype.ext_iff_val.2) /-- The product of two emetric spaces, with the max distance, is an extended metric spaces. We make sure that the uniform structure thus constructed is the one corresponding to the product of uniform spaces, to avoid diamond problems. -/ instance prod.emetric_space_max [emetric_space β] : emetric_space (γ × β) := { eq_of_edist_eq_zero := λ x y h, begin cases max_le_iff.1 (le_of_eq h) with h₁ h₂, have A : x.fst = y.fst := edist_le_zero.1 h₁, have B : x.snd = y.snd := edist_le_zero.1 h₂, exact prod.ext_iff.2 ⟨A, B⟩ end, ..prod.pseudo_emetric_space_max } /-- Reformulation of the uniform structure in terms of the extended distance -/ theorem uniformity_edist : 𝓤 γ = ⨅ ε>0, 𝓟 {p:γ×γ | edist p.1 p.2 < ε} := pseudo_emetric_space.uniformity_edist section pi open finset variables {π : β → Type*} [fintype β] /-- The product of a finite number of emetric spaces, with the max distance, is still an emetric space. This construction would also work for infinite products, but it would not give rise to the product topology. Hence, we only formalize it in the good situation of finitely many spaces. -/ instance emetric_space_pi [∀b, emetric_space (π b)] : emetric_space (Πb, π b) := { eq_of_edist_eq_zero := assume f g eq0, begin have eq1 : sup univ (λ (b : β), edist (f b) (g b)) ≤ 0 := le_of_eq eq0, simp only [finset.sup_le_iff] at eq1, exact (funext $ assume b, edist_le_zero.1 $ eq1 b $ mem_univ b), end, ..pseudo_emetric_space_pi } end pi namespace emetric /-- A compact set in an emetric space is separable, i.e., it is the closure of a countable set. -/ lemma countable_closure_of_compact {s : set γ} (hs : is_compact s) : ∃ t ⊆ s, (countable t ∧ s = closure t) := begin rcases subset_countable_closure_of_compact hs with ⟨t, hts, htc, hsub⟩, exact ⟨t, hts, htc, subset.antisymm hsub (closure_minimal hts hs.is_closed)⟩ end section diam variables {s : set γ} lemma diam_eq_zero_iff : diam s = 0 ↔ s.subsingleton := ⟨λ h x hx y hy, edist_le_zero.1 $ h ▸ edist_le_diam_of_mem hx hy, diam_subsingleton⟩ lemma diam_pos_iff : 0 < diam s ↔ ∃ (x ∈ s) (y ∈ s), x ≠ y := begin have := not_congr (@diam_eq_zero_iff _ _ s), dunfold set.subsingleton at this, push_neg at this, simpa only [pos_iff_ne_zero, exists_prop] using this end end diam end emetric
2c23bba15d7c8c758455c97ce2740b0220677f58
ce6917c5bacabee346655160b74a307b4a5ab620
/src/ch4/ex0503.lean
b6ff654feea8b1f29dc900e9d48ceb60c2112414
[]
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
336
lean
variable f : ℕ → ℕ variable h : ∀ x : ℕ, f x ≤ f (x + 1) example : f 0 ≥ f 1 → f 1 ≥ f 2 → f 0 = f 2 := assume : f 0 ≥ f 1, assume : f 1 ≥ f 2, have f 0 ≥ f 2, from le_trans this ‹f 0 ≥ f 1›, have f 0 ≤ f 2, from le_trans (h 0) (h 1), show f 0 = f 2, from le_antisymm this ‹f 0 ≥ f 2›
b151636332df99d4d0c5e19b34a4ec3b9170d8b2
b210f3162055e6c91af0e5938b8e29ad2b66957d
/notes02.18.20.lean
a324f25af8c8688d8aec16b9a19d8057ac10e7ca
[]
no_license
colemanjenkins/SharedFiles
db8a5cea23e51b7781ce779af546045c4230c17d
6ac3cc21a2912f3c8e62a23a882384b0b2a5d41b
refs/heads/master
1,608,650,217,053
1,598,992,893,000
1,598,992,893,000
236,838,099
0
0
null
null
null
null
UTF-8
Lean
false
false
568
lean
def fac : ℕ → ℕ | 0 := 1 | (n' + 1) := (n' + 1)*(fac n') --n' = n-1 inductive dm_list (α : Type) | nil {} : dm_list | cons (h: α)(t :dm_list) : dm_list def length {α :Type} : dm_list α → ℕ | dm_list.nil := 0 | (dm_list.cons h t) := 1 + length t def append {α : Type} : dm_list α → dm_list α → dm_list α | (dm_list.nil) l2 := l2 | (dm_list.cons h t) l2 := dm_list.cons h (append t l2) def reverse {α : Type} : dm_list α → dm_list α | dm_list.nil := dm_list.nil | (dm_list.cons h t) := (append (reverse t) (dm_list.cons h dm_list.nil))
707260e19852631cd03d5e439d8182edfd3d4c89
4727251e0cd73359b15b664c3170e5d754078599
/src/category_theory/limits/types.lean
92862aed37746a1bd9f1747692d83818d2df3d25
[ "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
17,527
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Reid Barton -/ import category_theory.limits.shapes.images import category_theory.filtered import tactic.equiv_rw universes v u open category_theory open category_theory.limits namespace category_theory.limits.types variables {J : Type v} [small_category J] /-- (internal implementation) the limit cone of a functor, implemented as flat sections of a pi type -/ def limit_cone (F : J ⥤ Type (max v u)) : cone F := { X := F.sections, π := { app := λ j u, u.val j } } local attribute [elab_simple] congr_fun /-- (internal implementation) the fact that the proposed limit cone is the limit -/ def limit_cone_is_limit (F : J ⥤ Type (max v u)) : is_limit (limit_cone F) := { lift := λ s v, ⟨λ j, s.π.app j v, λ j j' f, congr_fun (cone.w s f) _⟩, uniq' := by { intros, ext x j, exact congr_fun (w j) x } } /-- The category of types has all limits. See <https://stacks.math.columbia.edu/tag/002U>. -/ instance has_limits_of_size : has_limits_of_size.{v} (Type (max v u)) := { has_limits_of_shape := λ J 𝒥, by exactI { has_limit := λ F, has_limit.mk { cone := limit_cone F, is_limit := limit_cone_is_limit F } } } instance : has_limits (Type u) := types.has_limits_of_size.{u u} /-- The equivalence between a limiting cone of `F` in `Type u` and the "concrete" definition as the sections of `F`. -/ def is_limit_equiv_sections {F : J ⥤ Type (max v u)} {c : cone F} (t : is_limit c) : c.X ≃ F.sections := (is_limit.cone_point_unique_up_to_iso t (limit_cone_is_limit F)).to_equiv @[simp] lemma is_limit_equiv_sections_apply {F : J ⥤ Type (max v u)} {c : cone F} (t : is_limit c) (j : J) (x : c.X) : (((is_limit_equiv_sections t) x) : Π j, F.obj j) j = c.π.app j x := rfl @[simp] lemma is_limit_equiv_sections_symm_apply {F : J ⥤ Type (max v u)} {c : cone F} (t : is_limit c) (x : F.sections) (j : J) : c.π.app j ((is_limit_equiv_sections t).symm x) = (x : Π j, F.obj j) j := begin equiv_rw (is_limit_equiv_sections t).symm at x, simp, end /-- The equivalence between the abstract limit of `F` in `Type u` and the "concrete" definition as the sections of `F`. -/ noncomputable def limit_equiv_sections (F : J ⥤ Type (max v u)) : (limit F : Type (max v u)) ≃ F.sections := is_limit_equiv_sections (limit.is_limit _) @[simp] lemma limit_equiv_sections_apply (F : J ⥤ Type (max v u)) (x : limit F) (j : J) : (((limit_equiv_sections F) x) : Π j, F.obj j) j = limit.π F j x := rfl @[simp] lemma limit_equiv_sections_symm_apply (F : J ⥤ Type (max v u)) (x : F.sections) (j : J) : limit.π F j ((limit_equiv_sections F).symm x) = (x : Π j, F.obj j) j := is_limit_equiv_sections_symm_apply _ _ _ @[simp] lemma limit_equiv_sections_symm_apply' (F : J ⥤ Type v) (x : F.sections) (j : J) : limit.π F j ((limit_equiv_sections.{v v} F).symm x) = (x : Π j, F.obj j) j := is_limit_equiv_sections_symm_apply _ _ _ /-- Construct a term of `limit F : Type u` from a family of terms `x : Π j, F.obj j` which are "coherent": `∀ (j j') (f : j ⟶ j'), F.map f (x j) = x j'`. -/ @[ext] noncomputable def limit.mk (F : J ⥤ Type (max v u)) (x : Π j, F.obj j) (h : ∀ (j j') (f : j ⟶ j'), F.map f (x j) = x j') : (limit F : Type (max v u)) := (limit_equiv_sections F).symm ⟨x, h⟩ @[simp] lemma limit.π_mk (F : J ⥤ Type (max v u)) (x : Π j, F.obj j) (h : ∀ (j j') (f : j ⟶ j'), F.map f (x j) = x j') (j) : limit.π F j (limit.mk F x h) = x j := by { dsimp [limit.mk], simp, } @[simp] lemma limit.π_mk' (F : J ⥤ Type v) (x : Π j, F.obj j) (h : ∀ (j j') (f : j ⟶ j'), F.map f (x j) = x j') (j) : limit.π F j (limit.mk.{v v} F x h) = x j := by { dsimp [limit.mk], simp, } -- PROJECT: prove this for concrete categories where the forgetful functor preserves limits @[ext] lemma limit_ext (F : J ⥤ Type (max v u)) (x y : limit F) (w : ∀ j, limit.π F j x = limit.π F j y) : x = y := begin apply (limit_equiv_sections F).injective, ext j, simp [w j], end @[ext] lemma limit_ext' (F : J ⥤ Type v) (x y : limit F) (w : ∀ j, limit.π F j x = limit.π F j y) : x = y := begin apply (limit_equiv_sections.{v v} F).injective, ext j, simp [w j], end lemma limit_ext_iff (F : J ⥤ Type (max v u)) (x y : limit F) : x = y ↔ (∀ j, limit.π F j x = limit.π F j y) := ⟨λ t _, t ▸ rfl, limit_ext _ _ _⟩ lemma limit_ext_iff' (F : J ⥤ Type v) (x y : limit F) : x = y ↔ (∀ j, limit.π F j x = limit.π F j y) := ⟨λ t _, t ▸ rfl, limit_ext _ _ _⟩ -- TODO: are there other limits lemmas that should have `_apply` versions? -- Can we generate these like with `@[reassoc]`? -- PROJECT: prove these for any concrete category where the forgetful functor preserves limits? @[simp] lemma limit.w_apply {F : J ⥤ Type (max v u)} {j j' : J} {x : limit F} (f : j ⟶ j') : F.map f (limit.π F j x) = limit.π F j' x := congr_fun (limit.w F f) x @[simp] lemma limit.lift_π_apply (F : J ⥤ Type (max v u)) (s : cone F) (j : J) (x : s.X) : limit.π F j (limit.lift F s x) = s.π.app j x := congr_fun (limit.lift_π s j) x @[simp] lemma limit.map_π_apply {F G : J ⥤ Type (max v u)} (α : F ⟶ G) (j : J) (x) : limit.π G j (lim_map α x) = α.app j (limit.π F j x) := congr_fun (lim_map_π α j) x @[simp] lemma limit.w_apply' {F : J ⥤ Type v} {j j' : J} {x : limit F} (f : j ⟶ j') : F.map f (limit.π F j x) = limit.π F j' x := congr_fun (limit.w F f) x @[simp] lemma limit.lift_π_apply' (F : J ⥤ Type v) (s : cone F) (j : J) (x : s.X) : limit.π F j (limit.lift F s x) = s.π.app j x := congr_fun (limit.lift_π s j) x @[simp] lemma limit.map_π_apply' {F G : J ⥤ Type v} (α : F ⟶ G) (j : J) (x) : limit.π G j (lim_map α x) = α.app j (limit.π F j x) := congr_fun (lim_map_π α j) x /-- The relation defining the quotient type which implements the colimit of a functor `F : J ⥤ Type u`. See `category_theory.limits.types.quot`. -/ def quot.rel (F : J ⥤ Type (max v u)) : (Σ j, F.obj j) → (Σ j, F.obj j) → Prop := (λ p p', ∃ f : p.1 ⟶ p'.1, p'.2 = F.map f p.2) /-- A quotient type implementing the colimit of a functor `F : J ⥤ Type u`, as pairs `⟨j, x⟩` where `x : F.obj j`, modulo the equivalence relation generated by `⟨j, x⟩ ~ ⟨j', x'⟩` whenever there is a morphism `f : j ⟶ j'` so `F.map f x = x'`. -/ @[nolint has_inhabited_instance] def quot (F : J ⥤ Type (max v u)) : Type (max v u) := @quot (Σ j, F.obj j) (quot.rel F) /-- (internal implementation) the colimit cocone of a functor, implemented as a quotient of a sigma type -/ def colimit_cocone (F : J ⥤ Type (max v u)) : cocone F := { X := quot F, ι := { app := λ j x, quot.mk _ ⟨j, x⟩, naturality' := λ j j' f, funext $ λ x, eq.symm (quot.sound ⟨f, rfl⟩) } } local attribute [elab_with_expected_type] quot.lift /-- (internal implementation) the fact that the proposed colimit cocone is the colimit -/ def colimit_cocone_is_colimit (F : J ⥤ Type (max v u)) : is_colimit (colimit_cocone F) := { desc := λ s, quot.lift (λ (p : Σ j, F.obj j), s.ι.app p.1 p.2) (assume ⟨j, x⟩ ⟨j', x'⟩ ⟨f, hf⟩, by rw hf; exact (congr_fun (cocone.w s f) x).symm) } /-- The category of types has all colimits. See <https://stacks.math.columbia.edu/tag/002U>. -/ instance has_colimits_of_size : has_colimits_of_size.{v} (Type (max v u)) := { has_colimits_of_shape := λ J 𝒥, by exactI { has_colimit := λ F, has_colimit.mk { cocone := colimit_cocone F, is_colimit := colimit_cocone_is_colimit F } } } instance : has_colimits (Type u) := types.has_colimits_of_size.{u u} /-- The equivalence between the abstract colimit of `F` in `Type u` and the "concrete" definition as a quotient. -/ noncomputable def colimit_equiv_quot (F : J ⥤ Type (max v u)) : (colimit F : Type (max v u)) ≃ quot F := (is_colimit.cocone_point_unique_up_to_iso (colimit.is_colimit F) (colimit_cocone_is_colimit F)).to_equiv @[simp] lemma colimit_equiv_quot_symm_apply (F : J ⥤ Type (max v u)) (j : J) (x : F.obj j) : (colimit_equiv_quot F).symm (quot.mk _ ⟨j, x⟩) = colimit.ι F j x := rfl @[simp] lemma colimit_equiv_quot_apply (F : J ⥤ Type (max v u)) (j : J) (x : F.obj j) : (colimit_equiv_quot F) (colimit.ι F j x) = quot.mk _ ⟨j, x⟩ := begin apply (colimit_equiv_quot F).symm.injective, simp, end @[simp] lemma colimit.w_apply {F : J ⥤ Type (max v u)} {j j' : J} {x : F.obj j} (f : j ⟶ j') : colimit.ι F j' (F.map f x) = colimit.ι F j x := congr_fun (colimit.w F f) x @[simp] lemma colimit.ι_desc_apply (F : J ⥤ Type (max v u)) (s : cocone F) (j : J) (x : F.obj j) : colimit.desc F s (colimit.ι F j x) = s.ι.app j x := congr_fun (colimit.ι_desc s j) x @[simp] lemma colimit.ι_map_apply {F G : J ⥤ Type (max v u)} (α : F ⟶ G) (j : J) (x) : colim.map α (colimit.ι F j x) = colimit.ι G j (α.app j x) := congr_fun (colimit.ι_map α j) x @[simp] lemma colimit.w_apply' {F : J ⥤ Type v} {j j' : J} {x : F.obj j} (f : j ⟶ j') : colimit.ι F j' (F.map f x) = colimit.ι F j x := congr_fun (colimit.w F f) x @[simp] lemma colimit.ι_desc_apply' (F : J ⥤ Type v) (s : cocone F) (j : J) (x : F.obj j) : colimit.desc F s (colimit.ι F j x) = s.ι.app j x := congr_fun (colimit.ι_desc s j) x @[simp] lemma colimit.ι_map_apply' {F G : J ⥤ Type v} (α : F ⟶ G) (j : J) (x) : colim.map α (colimit.ι F j x) = colimit.ι G j (α.app j x) := congr_fun (colimit.ι_map α j) x lemma colimit_sound {F : J ⥤ Type (max v u)} {j j' : J} {x : F.obj j} {x' : F.obj j'} (f : j ⟶ j') (w : F.map f x = x') : colimit.ι F j x = colimit.ι F j' x' := begin rw [←w], simp, end lemma colimit_sound' {F : J ⥤ Type (max v u)} {j j' : J} {x : F.obj j} {x' : F.obj j'} {j'' : J} (f : j ⟶ j'') (f' : j' ⟶ j'') (w : F.map f x = F.map f' x') : colimit.ι F j x = colimit.ι F j' x' := begin rw [←colimit.w _ f, ←colimit.w _ f'], rw [types_comp_apply, types_comp_apply, w], end lemma colimit_eq {F : J ⥤ Type (max v u)} {j j' : J} {x : F.obj j} {x' : F.obj j'} (w : colimit.ι F j x = colimit.ι F j' x') : eqv_gen (quot.rel F) ⟨j, x⟩ ⟨j', x'⟩ := begin apply quot.eq.1, simpa using congr_arg (colimit_equiv_quot F) w, end lemma jointly_surjective (F : J ⥤ Type (max v u)) {t : cocone F} (h : is_colimit t) (x : t.X) : ∃ j y, t.ι.app j y = x := begin suffices : (λ (x : t.X), ulift.up (∃ j y, t.ι.app j y = x)) = (λ _, ulift.up true), { have := congr_fun this x, have H := congr_arg ulift.down this, dsimp at H, rwa eq_true at H }, refine h.hom_ext _, intro j, ext y, erw iff_true, exact ⟨j, y, rfl⟩ end /-- A variant of `jointly_surjective` for `x : colimit F`. -/ lemma jointly_surjective' {F : J ⥤ Type (max v u)} (x : colimit F) : ∃ j y, colimit.ι F j y = x := jointly_surjective F (colimit.is_colimit _) x namespace filtered_colimit /- For filtered colimits of types, we can give an explicit description of the equivalence relation generated by the relation used to form the colimit. -/ variables (F : J ⥤ Type (max v u)) /-- An alternative relation on `Σ j, F.obj j`, which generates the same equivalence relation as we use to define the colimit in `Type` above, but that is more convenient when working with filtered colimits. Elements in `F.obj j` and `F.obj j'` are equivalent if there is some `k : J` to the right where their images are equal. -/ protected def rel (x y : Σ j, F.obj j) : Prop := ∃ k (f : x.1 ⟶ k) (g : y.1 ⟶ k), F.map f x.2 = F.map g y.2 lemma rel_of_quot_rel (x y : Σ j, F.obj j) : quot.rel F x y → filtered_colimit.rel F x y := λ ⟨f, h⟩, ⟨y.1, f, 𝟙 y.1, by rw [← h, functor_to_types.map_id_apply]⟩ lemma eqv_gen_quot_rel_of_rel (x y : Σ j, F.obj j) : filtered_colimit.rel F x y → eqv_gen (quot.rel F) x y := λ ⟨k, f, g, h⟩, eqv_gen.trans _ ⟨k, F.map f x.2⟩ _ (eqv_gen.rel _ _ ⟨f, rfl⟩) (eqv_gen.symm _ _ (eqv_gen.rel _ _ ⟨g, h⟩)) local attribute [elab_simple] nat_trans.app /-- Recognizing filtered colimits of types. -/ noncomputable def is_colimit_of (t : cocone F) (hsurj : ∀ (x : t.X), ∃ i xi, x = t.ι.app i xi) (hinj : ∀ i j xi xj, t.ι.app i xi = t.ι.app j xj → ∃ k (f : i ⟶ k) (g : j ⟶ k), F.map f xi = F.map g xj) : is_colimit t := -- Strategy: Prove that the map from "the" colimit of F (defined above) to t.X -- is a bijection. begin apply is_colimit.of_iso_colimit (colimit.is_colimit F), refine cocones.ext (equiv.to_iso (equiv.of_bijective _ _)) _, { exact colimit.desc F t }, { split, { show function.injective _, intros a b h, rcases jointly_surjective F (colimit.is_colimit F) a with ⟨i, xi, rfl⟩, rcases jointly_surjective F (colimit.is_colimit F) b with ⟨j, xj, rfl⟩, change (colimit.ι F i ≫ colimit.desc F t) xi = (colimit.ι F j ≫ colimit.desc F t) xj at h, rw [colimit.ι_desc, colimit.ι_desc] at h, rcases hinj i j xi xj h with ⟨k, f, g, h'⟩, change colimit.ι F i xi = colimit.ι F j xj, rw [←colimit.w F f, ←colimit.w F g], change colimit.ι F k (F.map f xi) = colimit.ι F k (F.map g xj), rw h' }, { show function.surjective _, intro x, rcases hsurj x with ⟨i, xi, rfl⟩, use colimit.ι F i xi, simp } }, { intro j, apply colimit.ι_desc } end variables [is_filtered_or_empty J] protected lemma rel_equiv : equivalence (filtered_colimit.rel F) := ⟨λ x, ⟨x.1, 𝟙 x.1, 𝟙 x.1, rfl⟩, λ x y ⟨k, f, g, h⟩, ⟨k, g, f, h.symm⟩, λ x y z ⟨k, f, g, h⟩ ⟨k', f', g', h'⟩, let ⟨l, fl, gl, _⟩ := is_filtered_or_empty.cocone_objs k k', ⟨m, n, hn⟩ := is_filtered_or_empty.cocone_maps (g ≫ fl) (f' ≫ gl) in ⟨m, f ≫ fl ≫ n, g' ≫ gl ≫ n, calc F.map (f ≫ fl ≫ n) x.2 = F.map (fl ≫ n) (F.map f x.2) : by simp ... = F.map (fl ≫ n) (F.map g y.2) : by rw h ... = F.map ((g ≫ fl) ≫ n) y.2 : by simp ... = F.map ((f' ≫ gl) ≫ n) y.2 : by rw hn ... = F.map (gl ≫ n) (F.map f' y.2) : by simp ... = F.map (gl ≫ n) (F.map g' z.2) : by rw h' ... = F.map (g' ≫ gl ≫ n) z.2 : by simp⟩⟩ protected lemma rel_eq_eqv_gen_quot_rel : filtered_colimit.rel F = eqv_gen (quot.rel F) := begin ext ⟨j, x⟩ ⟨j', y⟩, split, { apply eqv_gen_quot_rel_of_rel }, { rw ←(filtered_colimit.rel_equiv F).eqv_gen_iff, exact eqv_gen.mono (rel_of_quot_rel F) } end lemma colimit_eq_iff_aux {i j : J} {xi : F.obj i} {xj : F.obj j} : (colimit_cocone F).ι.app i xi = (colimit_cocone F).ι.app j xj ↔ filtered_colimit.rel F ⟨i, xi⟩ ⟨j, xj⟩ := begin change quot.mk _ _ = quot.mk _ _ ↔ _, rw [quot.eq, filtered_colimit.rel_eq_eqv_gen_quot_rel], end lemma is_colimit_eq_iff {t : cocone F} (ht : is_colimit t) {i j : J} {xi : F.obj i} {xj : F.obj j} : t.ι.app i xi = t.ι.app j xj ↔ ∃ k (f : i ⟶ k) (g : j ⟶ k), F.map f xi = F.map g xj := let t' := colimit_cocone F, e : t' ≅ t := is_colimit.unique_up_to_iso (colimit_cocone_is_colimit F) ht, e' : t'.X ≅ t.X := (cocones.forget _).map_iso e in begin refine iff.trans _ (colimit_eq_iff_aux F), convert e'.to_equiv.apply_eq_iff_eq; rw ←e.hom.w; refl end lemma colimit_eq_iff {i j : J} {xi : F.obj i} {xj : F.obj j} : colimit.ι F i xi = colimit.ι F j xj ↔ ∃ k (f : i ⟶ k) (g : j ⟶ k), F.map f xi = F.map g xj := is_colimit_eq_iff _ (colimit.is_colimit F) end filtered_colimit variables {α β : Type u} (f : α ⟶ β) section -- implementation of `has_image` /-- the image of a morphism in Type is just `set.range f` -/ def image : Type u := set.range f instance [inhabited α] : inhabited (image f) := { default := ⟨f default, ⟨_, rfl⟩⟩ } /-- the inclusion of `image f` into the target -/ def image.ι : image f ⟶ β := subtype.val instance : mono (image.ι f) := (mono_iff_injective _).2 subtype.val_injective variables {f} /-- the universal property for the image factorisation -/ noncomputable def image.lift (F' : mono_factorisation f) : image f ⟶ F'.I := (λ x, F'.e (classical.indefinite_description _ x.2).1 : image f → F'.I) lemma image.lift_fac (F' : mono_factorisation f) : image.lift F' ≫ F'.m = image.ι f := begin ext x, change (F'.e ≫ F'.m) _ = _, rw [F'.fac, (classical.indefinite_description _ x.2).2], refl, end end /-- the factorisation of any morphism in Type through a mono. -/ def mono_factorisation : mono_factorisation f := { I := image f, m := image.ι f, e := set.range_factorization f } /-- the facorisation through a mono has the universal property of the image. -/ noncomputable def is_image : is_image (mono_factorisation f) := { lift := image.lift, lift_fac' := image.lift_fac } instance : has_image f := has_image.mk ⟨_, is_image f⟩ instance : has_images (Type u) := { has_image := by apply_instance } instance : has_image_maps (Type u) := { has_image_map := λ f g st, has_image_map.transport st (mono_factorisation f.hom) (is_image g.hom) (λ x, ⟨st.right x.1, ⟨st.left (classical.some x.2), begin have p := st.w, replace p := congr_fun p (classical.some x.2), simp only [functor.id_map, types_comp_apply, subtype.val_eq_coe] at p, erw [p, classical.some_spec x.2], end⟩⟩) rfl } end category_theory.limits.types
dfcd6ec081fcd30d886671bded9c0763297a29c1
30b012bb72d640ec30c8fdd4c45fdfa67beb012c
/core/data/list.lean
937af0f701a166db20f424a217e608e034ac5934
[ "Apache-2.0" ]
permissive
kckennylau/mathlib
21fb810b701b10d6606d9002a4004f7672262e83
47b3477e20ffb5a06588dd3abb01fe0fe3205646
refs/heads/master
1,634,976,409,281
1,542,042,832,000
1,542,319,733,000
109,560,458
0
0
Apache-2.0
1,542,369,208,000
1,509,867,494,000
Lean
UTF-8
Lean
false
false
420
lean
namespace list universes u v w variables {α : Type u} {β : Type v} {γ : Type w} instance [decidable_eq α] : has_sdiff (list α) := ⟨ list.diff ⟩ /- partition -/ def partition_map (f : α → β ⊕ γ) : list α → list β × list γ | [] := ([],[]) | (x::xs) := match f x with | (sum.inr r) := prod.map id (cons r) $ partition_map xs | (sum.inl l) := prod.map (cons l) id $ partition_map xs end end list
01a1851d4e7e129d287342902a7428e20aac06f6
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/data/complex/basic.lean
f503c786cc88619bbc0ae72f2d88e75854b6d019
[ "Apache-2.0" ]
permissive
dupuisf/mathlib
62de4ec6544bf3b79086afd27b6529acfaf2c1bb
8582b06b0a5d06c33ee07d0bdf7c646cae22cf36
refs/heads/master
1,669,494,854,016
1,595,692,409,000
1,595,692,409,000
272,046,630
0
0
Apache-2.0
1,592,066,143,000
1,592,066,142,000
null
UTF-8
Lean
false
false
20,084
lean
/- Copyright (c) 2017 Kevin Buzzard. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Buzzard, Mario Carneiro -/ import data.real.basic /-! # The complex numbers The complex numbers are modelled as ℝ^2 in the obvious way. -/ /-! ### Definition and basic arithmmetic -/ /-- Complex numbers consist of two `real`s: a real part `re` and an imaginary part `im`. -/ structure complex : Type := (re : ℝ) (im : ℝ) notation `ℂ` := complex namespace complex noncomputable instance : decidable_eq ℂ := classical.dec_eq _ /-- The equivalence between the complex numbers and `ℝ × ℝ`. -/ def equiv_real_prod : ℂ ≃ (ℝ × ℝ) := { to_fun := λ z, ⟨z.re, z.im⟩, inv_fun := λ p, ⟨p.1, p.2⟩, left_inv := λ ⟨x, y⟩, rfl, right_inv := λ ⟨x, y⟩, rfl } @[simp] theorem equiv_real_prod_apply (z : ℂ) : equiv_real_prod z = (z.re, z.im) := rfl theorem equiv_real_prod_symm_re (x y : ℝ) : (equiv_real_prod.symm (x, y)).re = x := rfl theorem equiv_real_prod_symm_im (x y : ℝ) : (equiv_real_prod.symm (x, y)).im = y := rfl @[simp] theorem eta : ∀ z : ℂ, complex.mk z.re z.im = z | ⟨a, b⟩ := rfl @[ext] theorem ext : ∀ {z w : ℂ}, z.re = w.re → z.im = w.im → z = w | ⟨zr, zi⟩ ⟨_, _⟩ rfl rfl := rfl theorem ext_iff {z w : ℂ} : z = w ↔ z.re = w.re ∧ z.im = w.im := ⟨λ H, by simp [H], and.rec ext⟩ instance : has_coe ℝ ℂ := ⟨λ r, ⟨r, 0⟩⟩ @[simp, norm_cast] lemma of_real_re (r : ℝ) : (r : ℂ).re = r := rfl @[simp, norm_cast] lemma of_real_im (r : ℝ) : (r : ℂ).im = 0 := rfl @[simp, norm_cast] theorem of_real_inj {z w : ℝ} : (z : ℂ) = w ↔ z = w := ⟨congr_arg re, congr_arg _⟩ instance : has_zero ℂ := ⟨(0 : ℝ)⟩ instance : inhabited ℂ := ⟨0⟩ @[simp] lemma zero_re : (0 : ℂ).re = 0 := rfl @[simp] lemma zero_im : (0 : ℂ).im = 0 := rfl @[simp, norm_cast] lemma of_real_zero : ((0 : ℝ) : ℂ) = 0 := rfl @[simp] theorem of_real_eq_zero {z : ℝ} : (z : ℂ) = 0 ↔ z = 0 := of_real_inj theorem of_real_ne_zero {z : ℝ} : (z : ℂ) ≠ 0 ↔ z ≠ 0 := not_congr of_real_eq_zero instance : has_one ℂ := ⟨(1 : ℝ)⟩ @[simp] lemma one_re : (1 : ℂ).re = 1 := rfl @[simp] lemma one_im : (1 : ℂ).im = 0 := rfl @[simp, norm_cast] lemma of_real_one : ((1 : ℝ) : ℂ) = 1 := rfl instance : has_add ℂ := ⟨λ z w, ⟨z.re + w.re, z.im + w.im⟩⟩ @[simp] lemma add_re (z w : ℂ) : (z + w).re = z.re + w.re := rfl @[simp] lemma add_im (z w : ℂ) : (z + w).im = z.im + w.im := rfl @[simp] lemma bit0_re (z : ℂ) : (bit0 z).re = bit0 z.re := rfl @[simp] lemma bit1_re (z : ℂ) : (bit1 z).re = bit1 z.re := rfl @[simp] lemma bit0_im (z : ℂ) : (bit0 z).im = bit0 z.im := eq.refl _ @[simp] lemma bit1_im (z : ℂ) : (bit1 z).im = bit0 z.im := add_zero _ @[simp, norm_cast] lemma of_real_add (r s : ℝ) : ((r + s : ℝ) : ℂ) = r + s := ext_iff.2 $ by simp @[simp, norm_cast] lemma of_real_bit0 (r : ℝ) : ((bit0 r : ℝ) : ℂ) = bit0 r := ext_iff.2 $ by simp [bit0] @[simp, norm_cast] lemma of_real_bit1 (r : ℝ) : ((bit1 r : ℝ) : ℂ) = bit1 r := ext_iff.2 $ by simp [bit1] instance : has_neg ℂ := ⟨λ z, ⟨-z.re, -z.im⟩⟩ @[simp] lemma neg_re (z : ℂ) : (-z).re = -z.re := rfl @[simp] lemma neg_im (z : ℂ) : (-z).im = -z.im := rfl @[simp, norm_cast] lemma of_real_neg (r : ℝ) : ((-r : ℝ) : ℂ) = -r := ext_iff.2 $ by simp instance : has_mul ℂ := ⟨λ z w, ⟨z.re * w.re - z.im * w.im, z.re * w.im + z.im * w.re⟩⟩ @[simp] lemma mul_re (z w : ℂ) : (z * w).re = z.re * w.re - z.im * w.im := rfl @[simp] lemma mul_im (z w : ℂ) : (z * w).im = z.re * w.im + z.im * w.re := rfl @[simp, norm_cast] lemma of_real_mul (r s : ℝ) : ((r * s : ℝ) : ℂ) = r * s := ext_iff.2 $ by simp lemma smul_re (r : ℝ) (z : ℂ) : (↑r * z).re = r * z.re := by simp lemma smul_im (r : ℝ) (z : ℂ) : (↑r * z).im = r * z.im := by simp lemma of_real_smul (r : ℝ) (z : ℂ) : (↑r * z) = ⟨r * z.re, r * z.im⟩ := ext (smul_re _ _) (smul_im _ _) /-! ### The imaginary unit, `I` -/ /-- The imaginary unit. -/ def I : ℂ := ⟨0, 1⟩ @[simp] lemma I_re : I.re = 0 := rfl @[simp] lemma I_im : I.im = 1 := rfl @[simp] lemma I_mul_I : I * I = -1 := ext_iff.2 $ by simp lemma I_mul (z : ℂ) : I * z = ⟨-z.im, z.re⟩ := ext_iff.2 $ by simp lemma I_ne_zero : (I : ℂ) ≠ 0 := mt (congr_arg im) zero_ne_one.symm lemma mk_eq_add_mul_I (a b : ℝ) : complex.mk a b = a + b * I := ext_iff.2 $ by simp @[simp] lemma re_add_im (z : ℂ) : (z.re : ℂ) + z.im * I = z := ext_iff.2 $ by simp /-! ### Commutative ring instance and lemmas -/ instance : comm_ring ℂ := by refine { zero := 0, add := (+), neg := has_neg.neg, one := 1, mul := (*), ..}; { intros, apply ext_iff.2; split; simp; ring } instance re.is_add_group_hom : is_add_group_hom complex.re := { map_add := complex.add_re } instance im.is_add_group_hom : is_add_group_hom complex.im := { map_add := complex.add_im } /-! ### Complex conjugation -/ /-- The complex conjugate. -/ def conj : ℂ →+* ℂ := begin refine_struct { to_fun := λ z : ℂ, (⟨z.re, -z.im⟩ : ℂ), .. }; { intros, ext; simp [add_comm], }, end @[simp] lemma conj_re (z : ℂ) : (conj z).re = z.re := rfl @[simp] lemma conj_im (z : ℂ) : (conj z).im = -z.im := rfl @[simp] lemma conj_of_real (r : ℝ) : conj r = r := ext_iff.2 $ by simp [conj] @[simp] lemma conj_I : conj I = -I := ext_iff.2 $ by simp @[simp] lemma conj_bit0 (z : ℂ) : conj (bit0 z) = bit0 (conj z) := ext_iff.2 $ by simp [bit0] @[simp] lemma conj_bit1 (z : ℂ) : conj (bit1 z) = bit1 (conj z) := ext_iff.2 $ by simp [bit0] @[simp] lemma conj_neg_I : conj (-I) = I := ext_iff.2 $ by simp @[simp] lemma conj_conj (z : ℂ) : conj (conj z) = z := ext_iff.2 $ by simp lemma conj_involutive : function.involutive conj := conj_conj lemma conj_bijective : function.bijective conj := conj_involutive.bijective lemma conj_inj {z w : ℂ} : conj z = conj w ↔ z = w := conj_bijective.1.eq_iff @[simp] lemma conj_eq_zero {z : ℂ} : conj z = 0 ↔ z = 0 := by simpa using @conj_inj z 0 lemma eq_conj_iff_real {z : ℂ} : conj z = z ↔ ∃ r : ℝ, z = r := ⟨λ h, ⟨z.re, ext rfl $ eq_zero_of_neg_eq (congr_arg im h)⟩, λ ⟨h, e⟩, by rw [e, conj_of_real]⟩ lemma eq_conj_iff_re {z : ℂ} : conj z = z ↔ (z.re : ℂ) = z := eq_conj_iff_real.trans ⟨by rintro ⟨r, rfl⟩; simp, λ h, ⟨_, h.symm⟩⟩ /-! ### Norm squared -/ /-- The norm squared function. -/ @[pp_nodot] def norm_sq (z : ℂ) : ℝ := z.re * z.re + z.im * z.im @[simp] lemma norm_sq_of_real (r : ℝ) : norm_sq r = r * r := by simp [norm_sq] @[simp] lemma norm_sq_zero : norm_sq 0 = 0 := by simp [norm_sq] @[simp] lemma norm_sq_one : norm_sq 1 = 1 := by simp [norm_sq] @[simp] lemma norm_sq_I : norm_sq I = 1 := by simp [norm_sq] lemma norm_sq_nonneg (z : ℂ) : 0 ≤ norm_sq z := add_nonneg (mul_self_nonneg _) (mul_self_nonneg _) @[simp] lemma norm_sq_eq_zero {z : ℂ} : norm_sq z = 0 ↔ z = 0 := ⟨λ h, ext (eq_zero_of_mul_self_add_mul_self_eq_zero h) (eq_zero_of_mul_self_add_mul_self_eq_zero $ (add_comm _ _).trans h), λ h, h.symm ▸ norm_sq_zero⟩ @[simp] lemma norm_sq_pos {z : ℂ} : 0 < norm_sq z ↔ z ≠ 0 := by rw [lt_iff_le_and_ne, ne, eq_comm]; simp [norm_sq_nonneg] @[simp] lemma norm_sq_neg (z : ℂ) : norm_sq (-z) = norm_sq z := by simp [norm_sq] @[simp] lemma norm_sq_conj (z : ℂ) : norm_sq (conj z) = norm_sq z := by simp [norm_sq] @[simp] lemma norm_sq_mul (z w : ℂ) : norm_sq (z * w) = norm_sq z * norm_sq w := by dsimp [norm_sq]; ring lemma norm_sq_add (z w : ℂ) : norm_sq (z + w) = norm_sq z + norm_sq w + 2 * (z * conj w).re := by dsimp [norm_sq]; ring lemma re_sq_le_norm_sq (z : ℂ) : z.re * z.re ≤ norm_sq z := le_add_of_nonneg_right (mul_self_nonneg _) lemma im_sq_le_norm_sq (z : ℂ) : z.im * z.im ≤ norm_sq z := le_add_of_nonneg_left (mul_self_nonneg _) theorem mul_conj (z : ℂ) : z * conj z = norm_sq z := ext_iff.2 $ by simp [norm_sq, mul_comm, sub_eq_neg_add, add_comm] theorem add_conj (z : ℂ) : z + conj z = (2 * z.re : ℝ) := ext_iff.2 $ by simp [two_mul] /-- The coercion `ℝ → ℂ` as a `ring_hom`. -/ def of_real : ℝ →+* ℂ := ⟨coe, of_real_one, of_real_mul, of_real_zero, of_real_add⟩ @[simp] lemma of_real_eq_coe (r : ℝ) : of_real r = r := rfl @[simp] lemma I_sq : I ^ 2 = -1 := by rw [pow_two, I_mul_I] @[simp] lemma sub_re (z w : ℂ) : (z - w).re = z.re - w.re := rfl @[simp] lemma sub_im (z w : ℂ) : (z - w).im = z.im - w.im := rfl @[simp, norm_cast] lemma of_real_sub (r s : ℝ) : ((r - s : ℝ) : ℂ) = r - s := ext_iff.2 $ by simp @[simp, norm_cast] lemma of_real_pow (r : ℝ) (n : ℕ) : ((r ^ n : ℝ) : ℂ) = r ^ n := by induction n; simp [*, of_real_mul, pow_succ] theorem sub_conj (z : ℂ) : z - conj z = (2 * z.im : ℝ) * I := ext_iff.2 $ by simp [two_mul, sub_eq_add_neg] lemma norm_sq_sub (z w : ℂ) : norm_sq (z - w) = norm_sq z + norm_sq w - 2 * (z * conj w).re := by rw [sub_eq_add_neg, norm_sq_add]; simp [-mul_re, add_comm, add_left_comm, sub_eq_add_neg] /-! ### Inversion -/ noncomputable instance : has_inv ℂ := ⟨λ z, conj z * ((norm_sq z)⁻¹:ℝ)⟩ theorem inv_def (z : ℂ) : z⁻¹ = conj z * ((norm_sq z)⁻¹:ℝ) := rfl @[simp] lemma inv_re (z : ℂ) : (z⁻¹).re = z.re / norm_sq z := by simp [inv_def, division_def] @[simp] lemma inv_im (z : ℂ) : (z⁻¹).im = -z.im / norm_sq z := by simp [inv_def, division_def] @[simp, norm_cast] lemma of_real_inv (r : ℝ) : ((r⁻¹ : ℝ) : ℂ) = r⁻¹ := ext_iff.2 $ begin simp, by_cases r = 0, { simp [h] }, { rw [← div_div_eq_div_mul, div_self h, one_div_eq_inv] }, end protected lemma inv_zero : (0⁻¹ : ℂ) = 0 := by rw [← of_real_zero, ← of_real_inv, inv_zero] protected theorem mul_inv_cancel {z : ℂ} (h : z ≠ 0) : z * z⁻¹ = 1 := by rw [inv_def, ← mul_assoc, mul_conj, ← of_real_mul, mul_inv_cancel (mt norm_sq_eq_zero.1 h), of_real_one] /-! ### Field instance and lemmas -/ noncomputable instance : field ℂ := { inv := has_inv.inv, exists_pair_ne := ⟨0, 1, mt (congr_arg re) zero_ne_one⟩, mul_inv_cancel := @complex.mul_inv_cancel, inv_zero := complex.inv_zero, ..complex.comm_ring } lemma div_re (z w : ℂ) : (z / w).re = z.re * w.re / norm_sq w + z.im * w.im / norm_sq w := by simp [div_eq_mul_inv, mul_assoc, sub_eq_add_neg] lemma div_im (z w : ℂ) : (z / w).im = z.im * w.re / norm_sq w - z.re * w.im / norm_sq w := by simp [div_eq_mul_inv, mul_assoc, sub_eq_add_neg, add_comm] @[simp, norm_cast] lemma of_real_div (r s : ℝ) : ((r / s : ℝ) : ℂ) = r / s := of_real.map_div r s @[simp, norm_cast] lemma of_real_fpow (r : ℝ) (n : ℤ) : ((r ^ n : ℝ) : ℂ) = (r : ℂ) ^ n := of_real.map_fpow r n @[simp] lemma div_I (z : ℂ) : z / I = -(z * I) := (div_eq_iff_mul_eq I_ne_zero).2 $ by simp [mul_assoc] @[simp] lemma inv_I : I⁻¹ = -I := by simp [inv_eq_one_div] @[simp] lemma norm_sq_inv (z : ℂ) : norm_sq z⁻¹ = (norm_sq z)⁻¹ := if h : z = 0 then by simp [h] else mul_right_cancel' (mt norm_sq_eq_zero.1 h) $ by rw [← norm_sq_mul]; simp [h, -norm_sq_mul] @[simp] lemma norm_sq_div (z w : ℂ) : norm_sq (z / w) = norm_sq z / norm_sq w := by rw [division_def, norm_sq_mul, norm_sq_inv]; refl /-! ### Cast lemmas -/ @[simp, norm_cast] theorem of_real_nat_cast (n : ℕ) : ((n : ℝ) : ℂ) = n := of_real.map_nat_cast n @[simp, norm_cast] lemma nat_cast_re (n : ℕ) : (n : ℂ).re = n := by rw [← of_real_nat_cast, of_real_re] @[simp, norm_cast] lemma nat_cast_im (n : ℕ) : (n : ℂ).im = 0 := by rw [← of_real_nat_cast, of_real_im] @[simp, norm_cast] theorem of_real_int_cast (n : ℤ) : ((n : ℝ) : ℂ) = n := of_real.map_int_cast n @[simp, norm_cast] lemma int_cast_re (n : ℤ) : (n : ℂ).re = n := by rw [← of_real_int_cast, of_real_re] @[simp, norm_cast] lemma int_cast_im (n : ℤ) : (n : ℂ).im = 0 := by rw [← of_real_int_cast, of_real_im] @[simp, norm_cast] theorem of_real_rat_cast (n : ℚ) : ((n : ℝ) : ℂ) = n := of_real.map_rat_cast n @[simp, norm_cast] lemma rat_cast_re (q : ℚ) : (q : ℂ).re = q := by rw [← of_real_rat_cast, of_real_re] @[simp, norm_cast] lemma rat_cast_im (q : ℚ) : (q : ℂ).im = 0 := by rw [← of_real_rat_cast, of_real_im] /-! ### Characteristic zero -/ instance char_zero_complex : char_zero ℂ := add_group.char_zero_of_inj_zero $ λ n h, by rwa [← of_real_nat_cast, of_real_eq_zero, nat.cast_eq_zero] at h theorem re_eq_add_conj (z : ℂ) : (z.re : ℂ) = (z + conj z) / 2 := by rw [add_conj]; simp; rw [mul_div_cancel_left (z.re:ℂ) two_ne_zero'] /-! ### Absolute value -/ /-- The complex absolute value function, defined as the square root of the norm squared. -/ @[pp_nodot] noncomputable def abs (z : ℂ) : ℝ := (norm_sq z).sqrt local notation `abs'` := _root_.abs @[simp] lemma abs_of_real (r : ℝ) : abs r = abs' r := by simp [abs, norm_sq_of_real, real.sqrt_mul_self_eq_abs] lemma abs_of_nonneg {r : ℝ} (h : 0 ≤ r) : abs r = r := (abs_of_real _).trans (abs_of_nonneg h) lemma abs_of_nat (n : ℕ) : complex.abs n = n := calc complex.abs n = complex.abs (n:ℝ) : by rw [of_real_nat_cast] ... = _ : abs_of_nonneg (nat.cast_nonneg n) lemma mul_self_abs (z : ℂ) : abs z * abs z = norm_sq z := real.mul_self_sqrt (norm_sq_nonneg _) @[simp] lemma abs_zero : abs 0 = 0 := by simp [abs] @[simp] lemma abs_one : abs 1 = 1 := by simp [abs] @[simp] lemma abs_I : abs I = 1 := by simp [abs] @[simp] lemma abs_two : abs 2 = 2 := calc abs 2 = abs (2 : ℝ) : by rw [of_real_bit0, of_real_one] ... = (2 : ℝ) : abs_of_nonneg (by norm_num) lemma abs_nonneg (z : ℂ) : 0 ≤ abs z := real.sqrt_nonneg _ @[simp] lemma abs_eq_zero {z : ℂ} : abs z = 0 ↔ z = 0 := (real.sqrt_eq_zero $ norm_sq_nonneg _).trans norm_sq_eq_zero lemma abs_ne_zero {z : ℂ} : abs z ≠ 0 ↔ z ≠ 0 := not_congr abs_eq_zero @[simp] lemma abs_conj (z : ℂ) : abs (conj z) = abs z := by simp [abs] @[simp] lemma abs_mul (z w : ℂ) : abs (z * w) = abs z * abs w := by rw [abs, norm_sq_mul, real.sqrt_mul (norm_sq_nonneg _)]; refl lemma abs_re_le_abs (z : ℂ) : abs' z.re ≤ abs z := by rw [mul_self_le_mul_self_iff (_root_.abs_nonneg z.re) (abs_nonneg _), abs_mul_abs_self, mul_self_abs]; apply re_sq_le_norm_sq lemma abs_im_le_abs (z : ℂ) : abs' z.im ≤ abs z := by rw [mul_self_le_mul_self_iff (_root_.abs_nonneg z.im) (abs_nonneg _), abs_mul_abs_self, mul_self_abs]; apply im_sq_le_norm_sq lemma re_le_abs (z : ℂ) : z.re ≤ abs z := (abs_le.1 (abs_re_le_abs _)).2 lemma im_le_abs (z : ℂ) : z.im ≤ abs z := (abs_le.1 (abs_im_le_abs _)).2 lemma abs_add (z w : ℂ) : abs (z + w) ≤ abs z + abs w := (mul_self_le_mul_self_iff (abs_nonneg _) (add_nonneg (abs_nonneg _) (abs_nonneg _))).2 $ begin rw [mul_self_abs, add_mul_self_eq, mul_self_abs, mul_self_abs, add_right_comm, norm_sq_add, add_le_add_iff_left, mul_assoc, mul_le_mul_left (@two_pos ℝ _)], simpa [-mul_re] using re_le_abs (z * conj w) end instance : is_absolute_value abs := { abv_nonneg := abs_nonneg, abv_eq_zero := λ _, abs_eq_zero, abv_add := abs_add, abv_mul := abs_mul } open is_absolute_value @[simp] lemma abs_abs (z : ℂ) : abs' (abs z) = abs z := _root_.abs_of_nonneg (abs_nonneg _) @[simp] lemma abs_pos {z : ℂ} : 0 < abs z ↔ z ≠ 0 := abv_pos abs @[simp] lemma abs_neg : ∀ z, abs (-z) = abs z := abv_neg abs lemma abs_sub : ∀ z w, abs (z - w) = abs (w - z) := abv_sub abs lemma abs_sub_le : ∀ a b c, abs (a - c) ≤ abs (a - b) + abs (b - c) := abv_sub_le abs @[simp] theorem abs_inv : ∀ z, abs z⁻¹ = (abs z)⁻¹ := abv_inv abs @[simp] theorem abs_div : ∀ z w, abs (z / w) = abs z / abs w := abv_div abs lemma abs_abs_sub_le_abs_sub : ∀ z w, abs' (abs z - abs w) ≤ abs (z - w) := abs_abv_sub_le_abv_sub abs lemma abs_le_abs_re_add_abs_im (z : ℂ) : abs z ≤ abs' z.re + abs' z.im := by simpa [re_add_im] using abs_add z.re (z.im * I) lemma abs_re_div_abs_le_one (z : ℂ) : abs' (z.re / z.abs) ≤ 1 := if hz : z = 0 then by simp [hz, zero_le_one] else by rw [_root_.abs_div, abs_abs]; exact div_le_of_le_mul (abs_pos.2 hz) (by rw mul_one; exact abs_re_le_abs _) lemma abs_im_div_abs_le_one (z : ℂ) : abs' (z.im / z.abs) ≤ 1 := if hz : z = 0 then by simp [hz, zero_le_one] else by rw [_root_.abs_div, abs_abs]; exact div_le_of_le_mul (abs_pos.2 hz) (by rw mul_one; exact abs_im_le_abs _) @[simp, norm_cast] lemma abs_cast_nat (n : ℕ) : abs (n : ℂ) = n := by rw [← of_real_nat_cast, abs_of_nonneg (nat.cast_nonneg n)] lemma norm_sq_eq_abs (x : ℂ) : norm_sq x = abs x ^ 2 := by rw [abs, pow_two, real.mul_self_sqrt (norm_sq_nonneg _)] /-! ### Cauchy sequences -/ theorem is_cau_seq_re (f : cau_seq ℂ abs) : is_cau_seq abs' (λ n, (f n).re) := λ ε ε0, (f.cauchy ε0).imp $ λ i H j ij, lt_of_le_of_lt (by simpa using abs_re_le_abs (f j - f i)) (H _ ij) theorem is_cau_seq_im (f : cau_seq ℂ abs) : is_cau_seq abs' (λ n, (f n).im) := λ ε ε0, (f.cauchy ε0).imp $ λ i H j ij, lt_of_le_of_lt (by simpa using abs_im_le_abs (f j - f i)) (H _ ij) /-- The real part of a complex Cauchy sequence, as a real Cauchy sequence. -/ noncomputable def cau_seq_re (f : cau_seq ℂ abs) : cau_seq ℝ abs' := ⟨_, is_cau_seq_re f⟩ /-- The imaginary part of a complex Cauchy sequence, as a real Cauchy sequence. -/ noncomputable def cau_seq_im (f : cau_seq ℂ abs) : cau_seq ℝ abs' := ⟨_, is_cau_seq_im f⟩ lemma is_cau_seq_abs {f : ℕ → ℂ} (hf : is_cau_seq abs f) : is_cau_seq abs' (abs ∘ f) := λ ε ε0, let ⟨i, hi⟩ := hf ε ε0 in ⟨i, λ j hj, lt_of_le_of_lt (abs_abs_sub_le_abs_sub _ _) (hi j hj)⟩ /-- The limit of a Cauchy sequence of complex numbers. -/ noncomputable def lim_aux (f : cau_seq ℂ abs) : ℂ := ⟨cau_seq.lim (cau_seq_re f), cau_seq.lim (cau_seq_im f)⟩ theorem equiv_lim_aux (f : cau_seq ℂ abs) : f ≈ cau_seq.const abs (lim_aux f) := λ ε ε0, (exists_forall_ge_and (cau_seq.equiv_lim ⟨_, is_cau_seq_re f⟩ _ (half_pos ε0)) (cau_seq.equiv_lim ⟨_, is_cau_seq_im f⟩ _ (half_pos ε0))).imp $ λ i H j ij, begin cases H _ ij with H₁ H₂, apply lt_of_le_of_lt (abs_le_abs_re_add_abs_im _), dsimp [lim_aux] at *, have := add_lt_add H₁ H₂, rwa add_halves at this, end noncomputable instance : cau_seq.is_complete ℂ abs := ⟨λ f, ⟨lim_aux f, equiv_lim_aux f⟩⟩ open cau_seq lemma lim_eq_lim_im_add_lim_re (f : cau_seq ℂ abs) : lim f = ↑(lim (cau_seq_re f)) + ↑(lim (cau_seq_im f)) * I := lim_eq_of_equiv_const $ calc f ≈ _ : equiv_lim_aux f ... = cau_seq.const abs (↑(lim (cau_seq_re f)) + ↑(lim (cau_seq_im f)) * I) : cau_seq.ext (λ _, complex.ext (by simp [lim_aux, cau_seq_re]) (by simp [lim_aux, cau_seq_im])) lemma lim_re (f : cau_seq ℂ abs) : lim (cau_seq_re f) = (lim f).re := by rw [lim_eq_lim_im_add_lim_re]; simp lemma lim_im (f : cau_seq ℂ abs) : lim (cau_seq_im f) = (lim f).im := by rw [lim_eq_lim_im_add_lim_re]; simp lemma is_cau_seq_conj (f : cau_seq ℂ abs) : is_cau_seq abs (λ n, conj (f n)) := λ ε ε0, let ⟨i, hi⟩ := f.2 ε ε0 in ⟨i, λ j hj, by rw [← conj.map_sub, abs_conj]; exact hi j hj⟩ /-- The complex conjugate of a complex Cauchy sequence, as a complex Cauchy sequence. -/ noncomputable def cau_seq_conj (f : cau_seq ℂ abs) : cau_seq ℂ abs := ⟨_, is_cau_seq_conj f⟩ lemma lim_conj (f : cau_seq ℂ abs) : lim (cau_seq_conj f) = conj (lim f) := complex.ext (by simp [cau_seq_conj, (lim_re _).symm, cau_seq_re]) (by simp [cau_seq_conj, (lim_im _).symm, cau_seq_im, (lim_neg _).symm]; refl) /-- The absolute value of a complex Cauchy sequence, as a real Cauchy sequence. -/ noncomputable def cau_seq_abs (f : cau_seq ℂ abs) : cau_seq ℝ abs' := ⟨_, is_cau_seq_abs f.2⟩ lemma lim_abs (f : cau_seq ℂ abs) : lim (cau_seq_abs f) = abs (lim f) := lim_eq_of_equiv_const (λ ε ε0, let ⟨i, hi⟩ := equiv_lim f ε ε0 in ⟨i, λ j hj, lt_of_le_of_lt (abs_abs_sub_le_abs_sub _ _) (hi j hj)⟩) end complex
e8892047d0a6d2c6aa091a48b34c1b1737e14f13
94e33a31faa76775069b071adea97e86e218a8ee
/src/data/sum/basic.lean
590a4957cca64d6bb810e504fa0437296c352aae
[ "Apache-2.0" ]
permissive
urkud/mathlib
eab80095e1b9f1513bfb7f25b4fa82fa4fd02989
6379d39e6b5b279df9715f8011369a301b634e41
refs/heads/master
1,658,425,342,662
1,658,078,703,000
1,658,078,703,000
186,910,338
0
0
Apache-2.0
1,568,512,083,000
1,557,958,709,000
Lean
UTF-8
Lean
false
false
14,885
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Yury G. Kudryashov -/ import data.option.basic /-! # Disjoint union of types This file proves basic results about the sum type `α ⊕ β`. `α ⊕ β` is the type made of a copy of `α` and a copy of `β`. It is also called *disjoint union*. ## Main declarations * `sum.get_left`: Retrieves the left content of `x : α ⊕ β` or returns `none` if it's coming from the right. * `sum.get_right`: Retrieves the right content of `x : α ⊕ β` or returns `none` if it's coming from the left. * `sum.is_left`: Returns whether `x : α ⊕ β` comes from the left component or not. * `sum.is_right`: Returns whether `x : α ⊕ β` comes from the right component or not. * `sum.map`: Maps `α ⊕ β` to `γ ⊕ δ` component-wise. * `sum.elim`: Nondependent eliminator/induction principle for `α ⊕ β`. * `sum.swap`: Maps `α ⊕ β` to `β ⊕ α` by swapping components. * `sum.lex`: Lexicographic order on `α ⊕ β` induced by a relation on `α` and a relation on `β`. ## Notes The definition of `sum` takes values in `Type*`. This effectively forbids `Prop`- valued sum types. To this effect, we have `psum`, which takes value in `Sort*` and carries a more complicated universe signature in consequence. The `Prop` version is `or`. -/ universes u v w x variables {α : Type u} {α' : Type w} {β : Type v} {β' : Type x} {γ δ : Type*} namespace sum attribute [derive decidable_eq] sum @[simp] lemma «forall» {p : α ⊕ β → Prop} : (∀ x, p x) ↔ (∀ a, p (inl a)) ∧ ∀ b, p (inr b) := ⟨λ h, ⟨λ a, h _, λ b, h _⟩, λ ⟨h₁, h₂⟩, sum.rec h₁ h₂⟩ @[simp] lemma «exists» {p : α ⊕ β → Prop} : (∃ x, p x) ↔ (∃ a, p (inl a)) ∨ ∃ b, p (inr b) := ⟨λ h, match h with | ⟨inl a, h⟩ := or.inl ⟨a, h⟩ | ⟨inr b, h⟩ := or.inr ⟨b, h⟩ end, λ h, match h with | or.inl ⟨a, h⟩ := ⟨inl a, h⟩ | or.inr ⟨b, h⟩ := ⟨inr b, h⟩ end⟩ lemma inl_injective : function.injective (inl : α → α ⊕ β) := λ x y, inl.inj lemma inr_injective : function.injective (inr : β → α ⊕ β) := λ x y, inr.inj section get /-- Check if a sum is `inl` and if so, retrieve its contents. -/ @[simp] def get_left : α ⊕ β → option α | (inl a) := some a | (inr _) := none /-- Check if a sum is `inr` and if so, retrieve its contents. -/ @[simp] def get_right : α ⊕ β → option β | (inr b) := some b | (inl _) := none /-- Check if a sum is `inl`. -/ @[simp] def is_left : α ⊕ β → bool | (inl _) := tt | (inr _) := ff /-- Check if a sum is `inr`. -/ @[simp] def is_right : α ⊕ β → bool | (inl _) := ff | (inr _) := tt variables {x y : α ⊕ β} lemma get_left_eq_none_iff : x.get_left = none ↔ x.is_right := by cases x; simp only [get_left, is_right, coe_sort_tt, coe_sort_ff, eq_self_iff_true] lemma get_right_eq_none_iff : x.get_right = none ↔ x.is_left := by cases x; simp only [get_right, is_left, coe_sort_tt, coe_sort_ff, eq_self_iff_true] end get theorem inl.inj_iff {a b} : (inl a : α ⊕ β) = inl b ↔ a = b := ⟨inl.inj, congr_arg _⟩ theorem inr.inj_iff {a b} : (inr a : α ⊕ β) = inr b ↔ a = b := ⟨inr.inj, congr_arg _⟩ theorem inl_ne_inr {a : α} {b : β} : inl a ≠ inr b. theorem inr_ne_inl {a : α} {b : β} : inr b ≠ inl a. /-- Define a function on `α ⊕ β` by giving separate definitions on `α` and `β`. -/ protected def elim {α β γ : Sort*} (f : α → γ) (g : β → γ) : α ⊕ β → γ := λ x, sum.rec_on x f g @[simp] lemma elim_inl {α β γ : Sort*} (f : α → γ) (g : β → γ) (x : α) : sum.elim f g (inl x) = f x := rfl @[simp] lemma elim_inr {α β γ : Sort*} (f : α → γ) (g : β → γ) (x : β) : sum.elim f g (inr x) = g x := rfl @[simp] lemma elim_comp_inl {α β γ : Sort*} (f : α → γ) (g : β → γ) : sum.elim f g ∘ inl = f := rfl @[simp] lemma elim_comp_inr {α β γ : Sort*} (f : α → γ) (g : β → γ) : sum.elim f g ∘ inr = g := rfl @[simp] lemma elim_inl_inr {α β : Sort*} : @sum.elim α β _ inl inr = id := funext $ λ x, sum.cases_on x (λ _, rfl) (λ _, rfl) lemma comp_elim {α β γ δ : Sort*} (f : γ → δ) (g : α → γ) (h : β → γ): f ∘ sum.elim g h = sum.elim (f ∘ g) (f ∘ h) := funext $ λ x, sum.cases_on x (λ _, rfl) (λ _, rfl) @[simp] lemma elim_comp_inl_inr {α β γ : Sort*} (f : α ⊕ β → γ) : sum.elim (f ∘ inl) (f ∘ inr) = f := funext $ λ x, sum.cases_on x (λ _, rfl) (λ _, rfl) /-- Map `α ⊕ β` to `α' ⊕ β'` sending `α` to `α'` and `β` to `β'`. -/ protected def map (f : α → α') (g : β → β') : α ⊕ β → α' ⊕ β' := sum.elim (inl ∘ f) (inr ∘ g) @[simp] lemma map_inl (f : α → α') (g : β → β') (x : α) : (inl x).map f g = inl (f x) := rfl @[simp] lemma map_inr (f : α → α') (g : β → β') (x : β) : (inr x).map f g = inr (g x) := rfl @[simp] lemma map_map {α'' β''} (f' : α' → α'') (g' : β' → β'') (f : α → α') (g : β → β') : ∀ x : α ⊕ β, (x.map f g).map f' g' = x.map (f' ∘ f) (g' ∘ g) | (inl a) := rfl | (inr b) := rfl @[simp] lemma map_comp_map {α'' β''} (f' : α' → α'') (g' : β' → β'') (f : α → α') (g : β → β') : (sum.map f' g') ∘ (sum.map f g) = sum.map (f' ∘ f) (g' ∘ g) := funext $ map_map f' g' f g @[simp] lemma map_id_id (α β) : sum.map (@id α) (@id β) = id := funext $ λ x, sum.rec_on x (λ _, rfl) (λ _, rfl) lemma elim_comp_map {α β γ δ ε : Sort*} {f₁ : α → β} {f₂ : β → ε} {g₁ : γ → δ} {g₂ : δ → ε} : sum.elim f₂ g₂ ∘ sum.map f₁ g₁ = sum.elim (f₂ ∘ f₁) (g₂ ∘ g₁) := by ext (_|_); refl open function (update update_eq_iff update_comp_eq_of_injective update_comp_eq_of_forall_ne) @[simp] lemma update_elim_inl [decidable_eq α] [decidable_eq (α ⊕ β)] {f : α → γ} {g : β → γ} {i : α} {x : γ} : update (sum.elim f g) (inl i) x = sum.elim (update f i x) g := update_eq_iff.2 ⟨by simp, by simp { contextual := tt }⟩ @[simp] lemma update_elim_inr [decidable_eq β] [decidable_eq (α ⊕ β)] {f : α → γ} {g : β → γ} {i : β} {x : γ} : update (sum.elim f g) (inr i) x = sum.elim f (update g i x) := update_eq_iff.2 ⟨by simp, by simp { contextual := tt }⟩ @[simp] lemma update_inl_comp_inl [decidable_eq α] [decidable_eq (α ⊕ β)] {f : α ⊕ β → γ} {i : α} {x : γ} : update f (inl i) x ∘ inl = update (f ∘ inl) i x := update_comp_eq_of_injective _ inl_injective _ _ @[simp] lemma update_inl_apply_inl [decidable_eq α] [decidable_eq (α ⊕ β)] {f : α ⊕ β → γ} {i j : α} {x : γ} : update f (inl i) x (inl j) = update (f ∘ inl) i x j := by rw ← update_inl_comp_inl @[simp] lemma update_inl_comp_inr [decidable_eq (α ⊕ β)] {f : α ⊕ β → γ} {i : α} {x : γ} : update f (inl i) x ∘ inr = f ∘ inr := update_comp_eq_of_forall_ne _ _ $ λ _, inr_ne_inl @[simp] lemma update_inl_apply_inr [decidable_eq (α ⊕ β)] {f : α ⊕ β → γ} {i : α} {j : β} {x : γ} : update f (inl i) x (inr j) = f (inr j) := function.update_noteq inr_ne_inl _ _ @[simp] lemma update_inr_comp_inl [decidable_eq (α ⊕ β)] {f : α ⊕ β → γ} {i : β} {x : γ} : update f (inr i) x ∘ inl = f ∘ inl := update_comp_eq_of_forall_ne _ _ $ λ _, inl_ne_inr @[simp] lemma update_inr_apply_inl [decidable_eq (α ⊕ β)] {f : α ⊕ β → γ} {i : α} {j : β} {x : γ} : update f (inr j) x (inl i) = f (inl i) := function.update_noteq inl_ne_inr _ _ @[simp] lemma update_inr_comp_inr [decidable_eq β] [decidable_eq (α ⊕ β)] {f : α ⊕ β → γ} {i : β} {x : γ} : update f (inr i) x ∘ inr = update (f ∘ inr) i x := update_comp_eq_of_injective _ inr_injective _ _ @[simp] lemma update_inr_apply_inr [decidable_eq β] [decidable_eq (α ⊕ β)] {f : α ⊕ β → γ} {i j : β} {x : γ} : update f (inr i) x (inr j) = update (f ∘ inr) i x j := by rw ← update_inr_comp_inr /-- Swap the factors of a sum type -/ def swap : α ⊕ β → β ⊕ α := sum.elim inr inl @[simp] lemma swap_inl (x : α) : swap (inl x : α ⊕ β) = inr x := rfl @[simp] lemma swap_inr (x : β) : swap (inr x : α ⊕ β) = inl x := rfl @[simp] lemma swap_swap (x : α ⊕ β) : swap (swap x) = x := by cases x; refl @[simp] lemma swap_swap_eq : swap ∘ swap = @id (α ⊕ β) := funext $ swap_swap @[simp] lemma swap_left_inverse : function.left_inverse (@swap α β) swap := swap_swap @[simp] lemma swap_right_inverse : function.right_inverse (@swap α β) swap := swap_swap section lift_rel /-- Lifts pointwise two relations between `α` and `γ` and between `β` and `δ` to a relation between `α ⊕ β` and `γ ⊕ δ`. -/ inductive lift_rel (r : α → γ → Prop) (s : β → δ → Prop) : α ⊕ β → γ ⊕ δ → Prop | inl {a c} : r a c → lift_rel (inl a) (inl c) | inr {b d} : s b d → lift_rel (inr b) (inr d) attribute [protected] lift_rel.inl lift_rel.inr variables {r r₁ r₂ : α → γ → Prop} {s s₁ s₂ : β → δ → Prop} {a : α} {b : β} {c : γ} {d : δ} {x : α ⊕ β} {y : γ ⊕ δ} @[simp] lemma lift_rel_inl_inl : lift_rel r s (inl a) (inl c) ↔ r a c := ⟨λ h, by { cases h, assumption }, lift_rel.inl⟩ @[simp] lemma not_lift_rel_inl_inr : ¬ lift_rel r s (inl a) (inr d) . @[simp] lemma not_lift_rel_inr_inl : ¬ lift_rel r s (inr b) (inl c) . @[simp] lemma lift_rel_inr_inr : lift_rel r s (inr b) (inr d) ↔ s b d := ⟨λ h, by { cases h, assumption }, lift_rel.inr⟩ instance [Π a c, decidable (r a c)] [Π b d, decidable (s b d)] : Π (ab : α ⊕ β) (cd : γ ⊕ δ), decidable (lift_rel r s ab cd) | (inl a) (inl c) := decidable_of_iff' _ lift_rel_inl_inl | (inl a) (inr d) := decidable.is_false not_lift_rel_inl_inr | (inr b) (inl c) := decidable.is_false not_lift_rel_inr_inl | (inr b) (inr d) := decidable_of_iff' _ lift_rel_inr_inr lemma lift_rel.mono (hr : ∀ a b, r₁ a b → r₂ a b) (hs : ∀ a b, s₁ a b → s₂ a b) (h : lift_rel r₁ s₁ x y) : lift_rel r₂ s₂ x y := by { cases h, exacts [lift_rel.inl (hr _ _ ‹_›), lift_rel.inr (hs _ _ ‹_›)] } lemma lift_rel.mono_left (hr : ∀ a b, r₁ a b → r₂ a b) (h : lift_rel r₁ s x y) : lift_rel r₂ s x y := h.mono hr $ λ _ _, id lemma lift_rel.mono_right (hs : ∀ a b, s₁ a b → s₂ a b) (h : lift_rel r s₁ x y) : lift_rel r s₂ x y := h.mono (λ _ _, id) hs protected lemma lift_rel.swap (h : lift_rel r s x y) : lift_rel s r x.swap y.swap := by { cases h, exacts [lift_rel.inr ‹_›, lift_rel.inl ‹_›] } @[simp] lemma lift_rel_swap_iff : lift_rel s r x.swap y.swap ↔ lift_rel r s x y := ⟨λ h, by { rw [←swap_swap x, ←swap_swap y], exact h.swap }, lift_rel.swap⟩ end lift_rel section lex /-- Lexicographic order for sum. Sort all the `inl a` before the `inr b`, otherwise use the respective order on `α` or `β`. -/ inductive lex (r : α → α → Prop) (s : β → β → Prop) : α ⊕ β → α ⊕ β → Prop | inl {a₁ a₂} (h : r a₁ a₂) : lex (inl a₁) (inl a₂) | inr {b₁ b₂} (h : s b₁ b₂) : lex (inr b₁) (inr b₂) | sep (a b) : lex (inl a) (inr b) attribute [protected] sum.lex.inl sum.lex.inr attribute [simp] lex.sep variables {r r₁ r₂ : α → α → Prop} {s s₁ s₂ : β → β → Prop} {a a₁ a₂ : α} {b b₁ b₂ : β} {x y : α ⊕ β} @[simp] lemma lex_inl_inl : lex r s (inl a₁) (inl a₂) ↔ r a₁ a₂ := ⟨λ h, by { cases h, assumption }, lex.inl⟩ @[simp] lemma lex_inr_inr : lex r s (inr b₁) (inr b₂) ↔ s b₁ b₂ := ⟨λ h, by { cases h, assumption }, lex.inr⟩ @[simp] lemma lex_inr_inl : ¬ lex r s (inr b) (inl a) . instance [decidable_rel r] [decidable_rel s] : decidable_rel (lex r s) | (inl a) (inl c) := decidable_of_iff' _ lex_inl_inl | (inl a) (inr d) := decidable.is_true (lex.sep _ _) | (inr b) (inl c) := decidable.is_false lex_inr_inl | (inr b) (inr d) := decidable_of_iff' _ lex_inr_inr protected lemma lift_rel.lex {a b : α ⊕ β} (h : lift_rel r s a b) : lex r s a b := by { cases h, exacts [lex.inl ‹_›, lex.inr ‹_›] } lemma lift_rel_subrelation_lex : subrelation (lift_rel r s) (lex r s) := λ a b, lift_rel.lex lemma lex.mono (hr : ∀ a b, r₁ a b → r₂ a b) (hs : ∀ a b, s₁ a b → s₂ a b) (h : lex r₁ s₁ x y) : lex r₂ s₂ x y := by { cases h, exacts [lex.inl (hr _ _ ‹_›), lex.inr (hs _ _ ‹_›), lex.sep _ _] } lemma lex.mono_left (hr : ∀ a b, r₁ a b → r₂ a b) (h : lex r₁ s x y) : lex r₂ s x y := h.mono hr $ λ _ _, id lemma lex.mono_right (hs : ∀ a b, s₁ a b → s₂ a b) (h : lex r s₁ x y) : lex r s₂ x y := h.mono (λ _ _, id) hs lemma lex_acc_inl {a} (aca : acc r a) : acc (lex r s) (inl a) := begin induction aca with a H IH, constructor, intros y h, cases h with a' _ h', exact IH _ h' end lemma lex_acc_inr (aca : ∀ a, acc (lex r s) (inl a)) {b} (acb : acc s b) : acc (lex r s) (inr b) := begin induction acb with b H IH, constructor, intros y h, cases h with _ _ _ b' _ h' a, { exact IH _ h' }, { exact aca _ } end lemma lex_wf (ha : well_founded r) (hb : well_founded s) : well_founded (lex r s) := have aca : ∀ a, acc (lex r s) (inl a), from λ a, lex_acc_inl (ha.apply a), ⟨λ x, sum.rec_on x aca (λ b, lex_acc_inr aca (hb.apply b))⟩ end lex end sum open sum namespace function lemma injective.sum_elim {f : α → γ} {g : β → γ} (hf : injective f) (hg : injective g) (hfg : ∀ a b, f a ≠ g b) : injective (sum.elim f g) | (inl x) (inl y) h := congr_arg inl $ hf h | (inl x) (inr y) h := (hfg x y h).elim | (inr x) (inl y) h := (hfg y x h.symm).elim | (inr x) (inr y) h := congr_arg inr $ hg h lemma injective.sum_map {f : α → β} {g : α' → β'} (hf : injective f) (hg : injective g) : injective (sum.map f g) | (inl x) (inl y) h := congr_arg inl $ hf $ inl.inj h | (inr x) (inr y) h := congr_arg inr $ hg $ inr.inj h lemma surjective.sum_map {f : α → β} {g : α' → β'} (hf : surjective f) (hg : surjective g) : surjective (sum.map f g) | (inl y) := let ⟨x, hx⟩ := hf y in ⟨inl x, congr_arg inl hx⟩ | (inr y) := let ⟨x, hx⟩ := hg y in ⟨inr x, congr_arg inr hx⟩ end function /-! ### Ternary sum Abbreviations for the maps from the summands to `α ⊕ β ⊕ γ`. This is useful for pattern-matching. -/ namespace sum3 /-- The map from the first summand into a ternary sum. -/ @[pattern, simp, reducible] def in₀ (a) : α ⊕ β ⊕ γ := inl a /-- The map from the second summand into a ternary sum. -/ @[pattern, simp, reducible] def in₁ (b) : α ⊕ β ⊕ γ := inr $ inl b /-- The map from the third summand into a ternary sum. -/ @[pattern, simp, reducible] def in₂ (c) : α ⊕ β ⊕ γ := inr $ inr c end sum3
3989663e62b33061eff0c25ab44dc1a3ddd0cbd3
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/measure_theory/measure/stieltjes.lean
cddd18465cdfa435788cebaf1ef5288d8457e362
[ "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
16,765
lean
/- Copyright (c) 2021 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Yury Kudryashov, Sébastien Gouëzel -/ import measure_theory.constructions.borel_space /-! # Stieltjes measures on the real line Consider a function `f : ℝ → ℝ` which is monotone and right-continuous. Then one can define a corrresponding measure, giving mass `f b - f a` to the interval `(a, b]`. ## Main definitions * `stieltjes_function` is a structure containing a function from `ℝ → ℝ`, together with the assertions that it is monotone and right-continuous. To `f : stieltjes_function`, one associates a Borel measure `f.measure`. * `f.left_lim x` is the limit of `f` to the left of `x`. * `f.measure_Ioc` asserts that `f.measure (Ioc a b) = of_real (f b - f a)` * `f.measure_Ioo` asserts that `f.measure (Ioo a b) = of_real (f.left_lim b - f a)`. * `f.measure_Icc` and `f.measure_Ico` are analogous. -/ noncomputable theory open classical set filter open ennreal (of_real) open_locale big_operators ennreal nnreal topological_space /-! ### Basic properties of Stieltjes functions -/ /-- Bundled monotone right-continuous real functions, used to construct Stieltjes measures. -/ structure stieltjes_function := (to_fun : ℝ → ℝ) (mono' : monotone to_fun) (right_continuous' : ∀ x, continuous_within_at to_fun (Ici x) x) namespace stieltjes_function instance : has_coe_to_fun stieltjes_function := ⟨_, to_fun⟩ initialize_simps_projections stieltjes_function (to_fun → apply) variable (f : stieltjes_function) lemma mono : monotone f := f.mono' lemma right_continuous (x : ℝ) : continuous_within_at f (Ici x) x := f.right_continuous' x /-- The limit of a Stieltjes function to the left of `x` (it exists by monotonicity). The fact that it is indeed a left limit is asserted in `tendsto_left_lim` -/ @[irreducible] def left_lim (x : ℝ) := Sup (f '' (Iio x)) lemma tendsto_left_lim (x : ℝ) : tendsto f (𝓝[Iio x] x) (𝓝 (f.left_lim x)) := by { rw left_lim, exact f.mono.tendsto_nhds_within_Iio x } lemma left_lim_le {x y : ℝ} (h : x ≤ y) : f.left_lim x ≤ f y := begin apply le_of_tendsto (f.tendsto_left_lim x), filter_upwards [self_mem_nhds_within], assume z hz, exact (f.mono (le_of_lt hz)).trans (f.mono h) end lemma le_left_lim {x y : ℝ} (h : x < y) : f x ≤ f.left_lim y := begin apply ge_of_tendsto (f.tendsto_left_lim y), apply mem_nhds_within_Iio_iff_exists_Ioo_subset.2 ⟨x, h, _⟩, assume z hz, exact f.mono hz.1.le, end lemma left_lim_le_left_lim {x y : ℝ} (h : x ≤ y) : f.left_lim x ≤ f.left_lim y := begin rcases eq_or_lt_of_le h with rfl|hxy, { exact le_rfl }, { exact (f.left_lim_le le_rfl).trans (f.le_left_lim hxy) } end /-- The identity of `ℝ` as a Stieltjes function, used to construct Lebesgue measure. -/ @[simps] protected def id : stieltjes_function := { to_fun := id, mono' := λ x y, id, right_continuous' := λ x, continuous_within_at_id } @[simp] lemma id_left_lim (x : ℝ) : stieltjes_function.id.left_lim x = x := tendsto_nhds_unique (stieltjes_function.id.tendsto_left_lim x) $ (continuous_at_id).tendsto.mono_left nhds_within_le_nhds instance : inhabited stieltjes_function := ⟨stieltjes_function.id⟩ /-! ### The outer measure associated to a Stieltjes function -/ /-- Length of an interval. This is the largest monotone function which correctly measures all intervals. -/ def length (s : set ℝ) : ℝ≥0∞ := ⨅a b (h : s ⊆ Ioc a b), of_real (f b - f a) @[simp] lemma length_empty : f.length ∅ = 0 := nonpos_iff_eq_zero.1 $ infi_le_of_le 0 $ infi_le_of_le 0 $ by simp @[simp] lemma length_Ioc (a b : ℝ) : f.length (Ioc a b) = of_real (f b - f a) := begin refine le_antisymm (infi_le_of_le a $ binfi_le b (subset.refl _)) (le_infi $ λ a', le_infi $ λ b', le_infi $ λ h, ennreal.coe_le_coe.2 _), cases le_or_lt b a with ab ab, { rw real.to_nnreal_of_nonpos (sub_nonpos.2 (f.mono ab)), apply zero_le, }, cases (Ioc_subset_Ioc_iff ab).1 h with h₁ h₂, exact real.to_nnreal_le_to_nnreal (sub_le_sub (f.mono h₁) (f.mono h₂)) end lemma length_mono {s₁ s₂ : set ℝ} (h : s₁ ⊆ s₂) : f.length s₁ ≤ f.length s₂ := infi_le_infi $ λ a, infi_le_infi $ λ b, infi_le_infi2 $ λ h', ⟨subset.trans h h', le_refl _⟩ open measure_theory /-- The Stieltjes outer measure associated to a Stieltjes function. -/ protected def outer : outer_measure ℝ := outer_measure.of_function f.length f.length_empty lemma outer_le_length (s : set ℝ) : f.outer s ≤ f.length s := outer_measure.of_function_le _ /-- If a compact interval `[a, b]` is covered by a union of open interval `(c i, d i)`, then `f b - f a ≤ ∑ f (d i) - f (c i)`. This is an auxiliary technical statement to prove the same statement for half-open intervals, the point of the current statement being that one can use compactness to reduce it to a finite sum, and argue by induction on the size of the covering set. -/ lemma length_subadditive_Icc_Ioo {a b : ℝ} {c d : ℕ → ℝ} (ss : Icc a b ⊆ ⋃ i, Ioo (c i) (d i)) : of_real (f b - f a) ≤ ∑' i, of_real (f (d i) - f (c i)) := begin suffices : ∀ (s:finset ℕ) b (cv : Icc a b ⊆ ⋃ i ∈ (↑s:set ℕ), Ioo (c i) (d i)), (of_real (f b - f a) : ℝ≥0∞) ≤ ∑ i in s, of_real (f (d i) - f (c i)), { rcases is_compact_Icc.elim_finite_subcover_image (λ (i : ℕ) (_ : i ∈ univ), @is_open_Ioo _ _ _ _ (c i) (d i)) (by simpa using ss) with ⟨s, su, hf, hs⟩, have e : (⋃ i ∈ (↑hf.to_finset:set ℕ), Ioo (c i) (d i)) = (⋃ i ∈ s, Ioo (c i) (d i)), by simp only [ext_iff, exists_prop, finset.set_bUnion_coe, mem_Union, forall_const, iff_self, finite.mem_to_finset], rw ennreal.tsum_eq_supr_sum, refine le_trans _ (le_supr _ hf.to_finset), exact this hf.to_finset _ (by simpa only [e]) }, clear ss b, refine λ s, finset.strong_induction_on s (λ s IH b cv, _), cases le_total b a with ab ab, { rw ennreal.of_real_eq_zero.2 (sub_nonpos.2 (f.mono ab)), exact zero_le _, }, have := cv ⟨ab, le_refl _⟩, simp at this, rcases this with ⟨i, is, cb, bd⟩, rw [← finset.insert_erase is] at cv ⊢, rw [finset.coe_insert, bUnion_insert] at cv, rw [finset.sum_insert (finset.not_mem_erase _ _)], refine le_trans _ (add_le_add_left (IH _ (finset.erase_ssubset is) (c i) _) _), { refine le_trans (ennreal.of_real_le_of_real _) ennreal.of_real_add_le, rw sub_add_sub_cancel, exact sub_le_sub_right (f.mono bd.le) _ }, { rintro x ⟨h₁, h₂⟩, refine (cv ⟨h₁, le_trans h₂ (le_of_lt cb)⟩).resolve_left (mt and.left (not_lt_of_le h₂)) } end @[simp] lemma outer_Ioc (a b : ℝ) : f.outer (Ioc a b) = of_real (f b - f a) := begin /- It suffices to show that, if `(a, b]` is covered by sets `s i`, then `f b - f a` is bounded by `∑ f.length (s i) + ε`. The difficulty is that `f.length` is expressed in terms of half-open intervals, while we would like to have a compact interval covered by open intervals to use compactness and finite sums, as provided by `length_subadditive_Icc_Ioo`. The trick is to use the right-continuity of `f`. If `a'` is close enough to `a` on its right, then `[a', b]` is still covered by the sets `s i` and moreover `f b - f a'` is very close to `f b - f a` (up to `ε/2`). Also, by definition one can cover `s i` by a half-closed interval `(p i, q i]` with `f`-length very close to that of `s i` (within a suitably small `ε' i`, say). If one moves `q i` very slightly to the right, then the `f`-length will change very little by right continuity, and we will get an open interval `(p i, q' i)` covering `s i` with `f (q' i) - f (p i)` within `ε' i` of the `f`-length of `s i`. -/ refine le_antisymm (by { rw ← f.length_Ioc, apply outer_le_length }) (le_binfi $ λ s hs, ennreal.le_of_forall_pos_le_add $ λ ε εpos h, _), let δ := ε / 2, have δpos : 0 < (δ : ℝ≥0∞), by simpa using εpos.ne', rcases ennreal.exists_pos_sum_of_encodable δpos.ne' ℕ with ⟨ε', ε'0, hε⟩, obtain ⟨a', ha', aa'⟩ : ∃ a', f a' - f a < δ ∧ a < a', { have A : continuous_within_at (λ r, f r - f a) (Ioi a) a, { refine continuous_within_at.sub _ continuous_within_at_const, exact (f.right_continuous a).mono Ioi_subset_Ici_self }, have B : f a - f a < δ, by rwa [sub_self, nnreal.coe_pos, ← ennreal.coe_pos], exact (((tendsto_order.1 A).2 _ B).and self_mem_nhds_within).exists }, have : ∀ i, ∃ p:ℝ×ℝ, s i ⊆ Ioo p.1 p.2 ∧ (of_real (f p.2 - f p.1) : ℝ≥0∞) < f.length (s i) + ε' i, { intro i, have := (ennreal.lt_add_right ((ennreal.le_tsum i).trans_lt h).ne (ennreal.coe_ne_zero.2 (ε'0 i).ne')), conv at this { to_lhs, rw length }, simp only [infi_lt_iff, exists_prop] at this, rcases this with ⟨p, q', spq, hq'⟩, have : continuous_within_at (λ r, of_real (f r - f p)) (Ioi q') q', { apply ennreal.continuous_of_real.continuous_at.comp_continuous_within_at, refine continuous_within_at.sub _ continuous_within_at_const, exact (f.right_continuous q').mono Ioi_subset_Ici_self }, rcases (((tendsto_order.1 this).2 _ hq').and self_mem_nhds_within).exists with ⟨q, hq, q'q⟩, exact ⟨⟨p, q⟩, spq.trans (Ioc_subset_Ioo_right q'q), hq⟩ }, choose g hg using this, have I_subset : Icc a' b ⊆ ⋃ i, Ioo (g i).1 (g i).2 := calc Icc a' b ⊆ Ioc a b : λ x hx, ⟨aa'.trans_le hx.1, hx.2⟩ ... ⊆ ⋃ i, s i : hs ... ⊆ ⋃ i, Ioo (g i).1 (g i).2 : Union_subset_Union (λ i, (hg i).1), calc of_real (f b - f a) = of_real ((f b - f a') + (f a' - f a)) : by rw sub_add_sub_cancel ... ≤ of_real (f b - f a') + of_real (f a' - f a) : ennreal.of_real_add_le ... ≤ (∑' i, of_real (f (g i).2 - f (g i).1)) + of_real δ : add_le_add (f.length_subadditive_Icc_Ioo I_subset) (ennreal.of_real_le_of_real ha'.le) ... ≤ (∑' i, (f.length (s i) + ε' i)) + δ : add_le_add (ennreal.tsum_le_tsum (λ i, (hg i).2.le)) (by simp only [ennreal.of_real_coe_nnreal, le_rfl]) ... = (∑' i, f.length (s i)) + (∑' i, ε' i) + δ : by rw [ennreal.tsum_add] ... ≤ (∑' i, f.length (s i)) + δ + δ : add_le_add (add_le_add le_rfl hε.le) le_rfl ... = ∑' (i : ℕ), f.length (s i) + ε : by simp [add_assoc, ennreal.add_halves] end lemma measurable_set_Ioi {c : ℝ} : f.outer.caratheodory.measurable_set' (Ioi c) := begin apply outer_measure.of_function_caratheodory (λ t, _), refine le_infi (λ a, le_infi (λ b, le_infi (λ h, _))), refine le_trans (add_le_add (f.length_mono $ inter_subset_inter_left _ h) (f.length_mono $ diff_subset_diff_left h)) _, cases le_total a c with hac hac; cases le_total b c with hbc hbc, { simp only [Ioc_inter_Ioi, f.length_Ioc, hac, sup_eq_max, hbc, le_refl, Ioc_eq_empty, max_eq_right, min_eq_left, Ioc_diff_Ioi, f.length_empty, zero_add, not_lt] }, { simp only [hac, hbc, Ioc_inter_Ioi, Ioc_diff_Ioi, f.length_Ioc, min_eq_right, sup_eq_max, ←ennreal.of_real_add, f.mono hac, f.mono hbc, sub_nonneg, sub_add_sub_cancel, le_refl, max_eq_right] }, { simp only [hbc, le_refl, Ioc_eq_empty, Ioc_inter_Ioi, min_eq_left, Ioc_diff_Ioi, f.length_empty, zero_add, or_true, le_sup_iff, f.length_Ioc, not_lt] }, { simp only [hac, hbc, Ioc_inter_Ioi, Ioc_diff_Ioi, f.length_Ioc, min_eq_right, sup_eq_max, le_refl, Ioc_eq_empty, add_zero, max_eq_left, f.length_empty, not_lt] } end theorem outer_trim : f.outer.trim = f.outer := begin refine le_antisymm (λ s, _) (outer_measure.le_trim _), rw outer_measure.trim_eq_infi, refine le_infi (λ t, le_infi $ λ ht, ennreal.le_of_forall_pos_le_add $ λ ε ε0 h, _), rcases ennreal.exists_pos_sum_of_encodable (ennreal.coe_pos.2 ε0).ne' ℕ with ⟨ε', ε'0, hε⟩, refine le_trans _ (add_le_add_left (le_of_lt hε) _), rw ← ennreal.tsum_add, choose g hg using show ∀ i, ∃ s, t i ⊆ s ∧ measurable_set s ∧ f.outer s ≤ f.length (t i) + of_real (ε' i), { intro i, have := (ennreal.lt_add_right ((ennreal.le_tsum i).trans_lt h).ne (ennreal.coe_pos.2 (ε'0 i)).ne'), conv at this {to_lhs, rw length}, simp only [infi_lt_iff] at this, rcases this with ⟨a, b, h₁, h₂⟩, rw ← f.outer_Ioc at h₂, exact ⟨_, h₁, measurable_set_Ioc, le_of_lt $ by simpa using h₂⟩ }, simp at hg, apply infi_le_of_le (Union g) _, apply infi_le_of_le (subset.trans ht $ Union_subset_Union (λ i, (hg i).1)) _, apply infi_le_of_le (measurable_set.Union (λ i, (hg i).2.1)) _, exact le_trans (f.outer.Union _) (ennreal.tsum_le_tsum $ λ i, (hg i).2.2) end lemma borel_le_measurable : borel ℝ ≤ f.outer.caratheodory := begin rw borel_eq_generate_Ioi, refine measurable_space.generate_from_le _, simp [f.measurable_set_Ioi] { contextual := tt } end /-! ### The measure associated to a Stieltjes function -/ /-- The measure associated to a Stieltjes function, giving mass `f b - f a` to the interval `(a, b]`. -/ @[irreducible] protected def measure : measure ℝ := { to_outer_measure := f.outer, m_Union := λ s hs, f.outer.Union_eq_of_caratheodory $ λ i, f.borel_le_measurable _ (hs i), trimmed := f.outer_trim } @[simp] lemma measure_Ioc (a b : ℝ) : f.measure (Ioc a b) = of_real (f b - f a) := by { rw stieltjes_function.measure, exact f.outer_Ioc a b } @[simp] lemma measure_singleton (a : ℝ) : f.measure {a} = of_real (f a - f.left_lim a) := begin obtain ⟨u, u_mono, u_lt_a, u_lim⟩ : ∃ (u : ℕ → ℝ), strict_mono u ∧ (∀ (n : ℕ), u n < a) ∧ tendsto u at_top (𝓝 a) := exists_seq_strict_mono_tendsto a, have A : {a} = ⋂ n, Ioc (u n) a, { refine subset.antisymm (λ x hx, by simp [mem_singleton_iff.1 hx, u_lt_a]) (λ x hx, _), simp at hx, have : a ≤ x := le_of_tendsto' u_lim (λ n, (hx n).1.le), simp [le_antisymm this (hx 0).2] }, have L1 : tendsto (λ n, f.measure (Ioc (u n) a)) at_top (𝓝 (f.measure {a})), { rw A, refine tendsto_measure_Inter (λ n, measurable_set_Ioc) (λ m n hmn, _) _, { exact Ioc_subset_Ioc (u_mono.monotone hmn) le_rfl }, { exact ⟨0, by simpa only [measure_Ioc] using ennreal.of_real_ne_top⟩ } }, have L2 : tendsto (λ n, f.measure (Ioc (u n) a)) at_top (𝓝 (of_real (f a - f.left_lim a))), { simp only [measure_Ioc], have : tendsto (λ n, f (u n)) at_top (𝓝 (f.left_lim a)), { apply (f.tendsto_left_lim a).comp, exact tendsto_nhds_within_of_tendsto_nhds_of_eventually_within _ u_lim (eventually_of_forall (λ n, u_lt_a n)) }, exact ennreal.continuous_of_real.continuous_at.tendsto.comp (tendsto_const_nhds.sub this) }, exact tendsto_nhds_unique L1 L2 end @[simp] lemma measure_Icc (a b : ℝ) : f.measure (Icc a b) = of_real (f b - f.left_lim a) := begin rcases le_or_lt a b with hab|hab, { have A : disjoint {a} (Ioc a b), by simp, simp [← Icc_union_Ioc_eq_Icc le_rfl hab, -singleton_union, ← ennreal.of_real_add, f.left_lim_le, measure_union A (measurable_set_singleton a) measurable_set_Ioc, f.mono hab] }, { simp only [hab, measure_empty, Icc_eq_empty, not_le], symmetry, simp [ennreal.of_real_eq_zero, f.le_left_lim hab] } end @[simp] lemma measure_Ioo {a b : ℝ} : f.measure (Ioo a b) = of_real (f.left_lim b - f a) := begin rcases le_or_lt b a with hab|hab, { simp only [hab, measure_empty, Ioo_eq_empty, not_lt], symmetry, simp [ennreal.of_real_eq_zero, f.left_lim_le hab] }, { have A : disjoint (Ioo a b) {b}, by simp, have D : f b - f a = (f b - f.left_lim b) + (f.left_lim b - f a), by abel, have := f.measure_Ioc a b, simp only [←Ioo_union_Icc_eq_Ioc hab le_rfl, measure_singleton, measure_union A measurable_set_Ioo (measurable_set_singleton b), Icc_self] at this, rw [D, ennreal.of_real_add, add_comm] at this, { simpa only [ennreal.add_right_inj ennreal.of_real_ne_top] }, { simp only [f.left_lim_le, sub_nonneg] }, { simp only [f.le_left_lim hab, sub_nonneg] } }, end @[simp] lemma measure_Ico (a b : ℝ) : f.measure (Ico a b) = of_real (f.left_lim b - f.left_lim a) := begin rcases le_or_lt b a with hab|hab, { simp only [hab, measure_empty, Ico_eq_empty, not_lt], symmetry, simp [ennreal.of_real_eq_zero, f.left_lim_le_left_lim hab] }, { have A : disjoint {a} (Ioo a b) := by simp, simp [← Icc_union_Ioo_eq_Ico le_rfl hab, -singleton_union, hab.ne, f.left_lim_le, measure_union A (measurable_set_singleton a) measurable_set_Ioo, f.le_left_lim hab, ← ennreal.of_real_add] } end end stieltjes_function
00ac34e3358485da1758f6bf960e7d6c89c270c5
618003631150032a5676f229d13a079ac875ff77
/src/category_theory/comma.lean
b253ab8d82beeaf69fb7bac124845f1328f3a58d
[ "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
22,289
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Johan Commelin, Bhavik Mehta -/ import category_theory.punit import category_theory.reflect_isomorphisms /-! # Comma categories A comma category is a construction in category theory, which builds a category out of two functors with a common codomain. Specifically, for functors `L : A ⥤ T` and `R : B ⥤ T`, an object in `comma L R` is a morphism `hom : L.obj left ⟶ R.obj right` for some objects `left : A` and `right : B`, and a morphism in `comma L R` between `hom : L.obj left ⟶ R.obj right` and `hom' : L.obj left' ⟶ R.obj right'` is a commutative square L.obj left ⟶ L.obj left' | | hom | | hom' ↓ ↓ R.obj right ⟶ R.obj right', where the top and bottom morphism come from morphisms `left ⟶ left'` and `right ⟶ right'`, respectively. Several important constructions are special cases of this construction. * If `L` is the identity functor and `R` is a constant functor, then `comma L R` is the "slice" or "over" category over the object `R` maps to. * Conversely, if `L` is a constant functor and `R` is the identity functor, then `comma L R` is the "coslice" or "under" category under the object `L` maps to. * If `L` and `R` both are the identity functor, then `comma L R` is the arrow category of `T`. ## Main definitions * `comma L R`: the comma category of the functors `L` and `R`. * `over X`: the over category of the object `X`. * `under X`: the under category of the object `X`. * `arrow T`: the arrow category of the category `T`. ## References * https://ncatlab.org/nlab/show/comma+category ## Tags comma, slice, coslice, over, under, arrow -/ namespace category_theory universes v₁ v₂ v₃ u₁ u₂ u₃ -- declare the `v`'s first; see `category_theory.category` for an explanation variables {A : Type u₁} [category.{v₁} A] variables {B : Type u₂} [category.{v₂} B] variables {T : Type u₃} [category.{v₃} T] /-- The objects of the comma category are triples of an object `left : A`, an object `right : B` and a morphism `hom : L.obj left ⟶ R.obj right`. -/ structure comma (L : A ⥤ T) (R : B ⥤ T) : Type (max u₁ u₂ v₃) := (left : A . obviously) (right : B . obviously) (hom : L.obj left ⟶ R.obj right) -- Satisfying the inhabited linter instance comma.inhabited [inhabited T] : inhabited (comma (𝟭 T) (𝟭 T)) := { default := { left := default T, right := default T, hom := 𝟙 (default T) } } variables {L : A ⥤ T} {R : B ⥤ T} /-- A morphism between two objects in the comma category is a commutative square connecting the morphisms coming from the two objects using morphisms in the image of the functors `L` and `R`. -/ @[ext] structure comma_morphism (X Y : comma L R) := (left : X.left ⟶ Y.left . obviously) (right : X.right ⟶ Y.right . obviously) (w' : L.map left ≫ Y.hom = X.hom ≫ R.map right . obviously) -- Satisfying the inhabited linter instance comma_morphism.inhabited [inhabited (comma L R)] : inhabited (comma_morphism (default (comma L R)) (default (comma L R))) := { default := { left := 𝟙 _, right := 𝟙 _ } } restate_axiom comma_morphism.w' attribute [simp] comma_morphism.w instance comma_category : category (comma L R) := { hom := comma_morphism, id := λ X, { left := 𝟙 X.left, right := 𝟙 X.right }, comp := λ X Y Z f g, { left := f.left ≫ g.left, right := f.right ≫ g.right, w' := begin rw [functor.map_comp, category.assoc, g.w, ←category.assoc, f.w, functor.map_comp, category.assoc], end }} namespace comma section variables {X Y Z : comma L R} {f : X ⟶ Y} {g : Y ⟶ Z} @[simp] lemma id_left : ((𝟙 X) : comma_morphism X X).left = 𝟙 X.left := rfl @[simp] lemma id_right : ((𝟙 X) : comma_morphism X X).right = 𝟙 X.right := rfl @[simp] lemma comp_left : (f ≫ g).left = f.left ≫ g.left := rfl @[simp] lemma comp_right : (f ≫ g).right = f.right ≫ g.right := rfl end variables (L) (R) /-- The functor sending an object `X` in the comma category to `X.left`. -/ def fst : comma L R ⥤ A := { obj := λ X, X.left, map := λ _ _ f, f.left } /-- The functor sending an object `X` in the comma category to `X.right`. -/ def snd : comma L R ⥤ B := { obj := λ X, X.right, map := λ _ _ f, f.right } @[simp] lemma fst_obj {X : comma L R} : (fst L R).obj X = X.left := rfl @[simp] lemma snd_obj {X : comma L R} : (snd L R).obj X = X.right := rfl @[simp] lemma fst_map {X Y : comma L R} {f : X ⟶ Y} : (fst L R).map f = f.left := rfl @[simp] lemma snd_map {X Y : comma L R} {f : X ⟶ Y} : (snd L R).map f = f.right := rfl /-- We can interpret the commutative square constituting a morphism in the comma category as a natural transformation between the functors `fst ⋙ L` and `snd ⋙ R` from the comma category to `T`, where the components are given by the morphism that constitutes an object of the comma category. -/ def nat_trans : fst L R ⋙ L ⟶ snd L R ⋙ R := { app := λ X, X.hom } section variables {L₁ L₂ L₃ : A ⥤ T} {R₁ R₂ R₃ : B ⥤ T} /-- A natural transformation `L₁ ⟶ L₂` induces a functor `comma L₂ R ⥤ comma L₁ R`. -/ def map_left (l : L₁ ⟶ L₂) : comma L₂ R ⥤ comma L₁ R := { obj := λ X, { left := X.left, right := X.right, hom := l.app X.left ≫ X.hom }, map := λ X Y f, { left := f.left, right := f.right, w' := by tidy; rw [←category.assoc, l.naturality f.left, category.assoc]; tidy } } section variables {X Y : comma L₂ R} {f : X ⟶ Y} {l : L₁ ⟶ L₂} @[simp] lemma map_left_obj_left : ((map_left R l).obj X).left = X.left := rfl @[simp] lemma map_left_obj_right : ((map_left R l).obj X).right = X.right := rfl @[simp] lemma map_left_obj_hom : ((map_left R l).obj X).hom = l.app X.left ≫ X.hom := rfl @[simp] lemma map_left_map_left : ((map_left R l).map f).left = f.left := rfl @[simp] lemma map_left_map_right : ((map_left R l).map f).right = f.right := rfl end /-- The functor `comma L R ⥤ comma L R` induced by the identity natural transformation on `L` is naturally isomorphic to the identity functor. -/ def map_left_id : map_left R (𝟙 L) ≅ 𝟭 _ := { hom := { app := λ X, { left := 𝟙 _, right := 𝟙 _ } }, inv := { app := λ X, { left := 𝟙 _, right := 𝟙 _ } } } section variables {X : comma L R} @[simp] lemma map_left_id_hom_app_left : (((map_left_id L R).hom).app X).left = 𝟙 (X.left) := rfl @[simp] lemma map_left_id_hom_app_right : (((map_left_id L R).hom).app X).right = 𝟙 (X.right) := rfl @[simp] lemma map_left_id_inv_app_left : (((map_left_id L R).inv).app X).left = 𝟙 (X.left) := rfl @[simp] lemma map_left_id_inv_app_right : (((map_left_id L R).inv).app X).right = 𝟙 (X.right) := rfl end /-- The functor `comma L₁ R ⥤ comma L₃ R` induced by the composition of two natural transformations `l : L₁ ⟶ L₂` and `l' : L₂ ⟶ L₃` is naturally isomorphic to the composition of the two functors induced by these natural transformations. -/ def map_left_comp (l : L₁ ⟶ L₂) (l' : L₂ ⟶ L₃) : (map_left R (l ≫ l')) ≅ (map_left R l') ⋙ (map_left R l) := { hom := { app := λ X, { left := 𝟙 _, right := 𝟙 _ } }, inv := { app := λ X, { left := 𝟙 _, right := 𝟙 _ } } } section variables {X : comma L₃ R} {l : L₁ ⟶ L₂} {l' : L₂ ⟶ L₃} @[simp] lemma map_left_comp_hom_app_left : (((map_left_comp R l l').hom).app X).left = 𝟙 (X.left) := rfl @[simp] lemma map_left_comp_hom_app_right : (((map_left_comp R l l').hom).app X).right = 𝟙 (X.right) := rfl @[simp] lemma map_left_comp_inv_app_left : (((map_left_comp R l l').inv).app X).left = 𝟙 (X.left) := rfl @[simp] lemma map_left_comp_inv_app_right : (((map_left_comp R l l').inv).app X).right = 𝟙 (X.right) := rfl end /-- A natural transformation `R₁ ⟶ R₂` induces a functor `comma L R₁ ⥤ comma L R₂`. -/ def map_right (r : R₁ ⟶ R₂) : comma L R₁ ⥤ comma L R₂ := { obj := λ X, { left := X.left, right := X.right, hom := X.hom ≫ r.app X.right }, map := λ X Y f, { left := f.left, right := f.right, w' := by tidy; rw [←r.naturality f.right, ←category.assoc]; tidy } } section variables {X Y : comma L R₁} {f : X ⟶ Y} {r : R₁ ⟶ R₂} @[simp] lemma map_right_obj_left : ((map_right L r).obj X).left = X.left := rfl @[simp] lemma map_right_obj_right : ((map_right L r).obj X).right = X.right := rfl @[simp] lemma map_right_obj_hom : ((map_right L r).obj X).hom = X.hom ≫ r.app X.right := rfl @[simp] lemma map_right_map_left : ((map_right L r).map f).left = f.left := rfl @[simp] lemma map_right_map_right : ((map_right L r).map f).right = f.right := rfl end /-- The functor `comma L R ⥤ comma L R` induced by the identity natural transformation on `R` is naturally isomorphic to the identity functor. -/ def map_right_id : map_right L (𝟙 R) ≅ 𝟭 _ := { hom := { app := λ X, { left := 𝟙 _, right := 𝟙 _ } }, inv := { app := λ X, { left := 𝟙 _, right := 𝟙 _ } } } section variables {X : comma L R} @[simp] lemma map_right_id_hom_app_left : (((map_right_id L R).hom).app X).left = 𝟙 (X.left) := rfl @[simp] lemma map_right_id_hom_app_right : (((map_right_id L R).hom).app X).right = 𝟙 (X.right) := rfl @[simp] lemma map_right_id_inv_app_left : (((map_right_id L R).inv).app X).left = 𝟙 (X.left) := rfl @[simp] lemma map_right_id_inv_app_right : (((map_right_id L R).inv).app X).right = 𝟙 (X.right) := rfl end /-- The functor `comma L R₁ ⥤ comma L R₃` induced by the composition of the natural transformations `r : R₁ ⟶ R₂` and `r' : R₂ ⟶ R₃` is naturally isomorphic to the composition of the functors induced by these natural transformations. -/ def map_right_comp (r : R₁ ⟶ R₂) (r' : R₂ ⟶ R₃) : (map_right L (r ≫ r')) ≅ (map_right L r) ⋙ (map_right L r') := { hom := { app := λ X, { left := 𝟙 _, right := 𝟙 _ } }, inv := { app := λ X, { left := 𝟙 _, right := 𝟙 _ } } } section variables {X : comma L R₁} {r : R₁ ⟶ R₂} {r' : R₂ ⟶ R₃} @[simp] lemma map_right_comp_hom_app_left : (((map_right_comp L r r').hom).app X).left = 𝟙 (X.left) := rfl @[simp] lemma map_right_comp_hom_app_right : (((map_right_comp L r r').hom).app X).right = 𝟙 (X.right) := rfl @[simp] lemma map_right_comp_inv_app_left : (((map_right_comp L r r').inv).app X).left = 𝟙 (X.left) := rfl @[simp] lemma map_right_comp_inv_app_right : (((map_right_comp L r r').inv).app X).right = 𝟙 (X.right) := rfl end end end comma /-- The over category has as objects arrows in `T` with codomain `X` and as morphisms commutative triangles. -/ @[derive category] def over (X : T) := comma.{v₃ 0 v₃} (𝟭 T) ((functor.const punit).obj X) -- Satisfying the inhabited linter instance over.inhabited [inhabited T] : inhabited (over (default T)) := { default := { left := default T, hom := 𝟙 _ } } namespace over variables {X : T} @[ext] lemma over_morphism.ext {X : T} {U V : over X} {f g : U ⟶ V} (h : f.left = g.left) : f = g := by tidy @[simp] lemma over_right (U : over X) : U.right = punit.star := by tidy @[simp] lemma over_morphism_right {U V : over X} (f : U ⟶ V) : f.right = 𝟙 punit.star := by tidy @[simp] lemma id_left (U : over X) : comma_morphism.left (𝟙 U) = 𝟙 U.left := rfl @[simp] lemma comp_left (a b c : over X) (f : a ⟶ b) (g : b ⟶ c) : (f ≫ g).left = f.left ≫ g.left := rfl @[simp, reassoc] lemma w {A B : over X} (f : A ⟶ B) : f.left ≫ B.hom = A.hom := by have := f.w; tidy /-- To give an object in the over category, it suffices to give a morphism with codomain `X`. -/ def mk {X Y : T} (f : Y ⟶ X) : over X := { left := Y, hom := f } @[simp] lemma mk_left {X Y : T} (f : Y ⟶ X) : (mk f).left = Y := rfl @[simp] lemma mk_hom {X Y : T} (f : Y ⟶ X) : (mk f).hom = f := rfl /-- To give a morphism in the over category, it suffices to give an arrow fitting in a commutative triangle. -/ def hom_mk {U V : over X} (f : U.left ⟶ V.left) (w : f ≫ V.hom = U.hom . obviously) : U ⟶ V := { left := f } @[simp] lemma hom_mk_left {U V : over X} (f : U.left ⟶ V.left) (w : f ≫ V.hom = U.hom) : (hom_mk f).left = f := rfl /-- The forgetful functor mapping an arrow to its domain. -/ def forget : (over X) ⥤ T := comma.fst _ _ @[simp] lemma forget_obj {U : over X} : forget.obj U = U.left := rfl @[simp] lemma forget_map {U V : over X} {f : U ⟶ V} : forget.map f = f.left := rfl /-- A morphism `f : X ⟶ Y` induces a functor `over X ⥤ over Y` in the obvious way. -/ def map {Y : T} (f : X ⟶ Y) : over X ⥤ over Y := comma.map_right _ $ (functor.const punit).map f section variables {Y : T} {f : X ⟶ Y} {U V : over X} {g : U ⟶ V} @[simp] lemma map_obj_left : ((map f).obj U).left = U.left := rfl @[simp] lemma map_obj_hom : ((map f).obj U).hom = U.hom ≫ f := rfl @[simp] lemma map_map_left : ((map f).map g).left = g.left := rfl end instance forget_reflects_iso : reflects_isomorphisms (forget : over X ⥤ T) := { reflects := λ X Y f t, by exactI { inv := over.hom_mk t.inv ((as_iso (forget.map f)).inv_comp_eq.2 (over.w f).symm) } } section iterated_slice variables (f : over X) /-- Given f : Y ⟶ X, this is the obvious functor from (T/X)/f to T/Y -/ @[simps] def iterated_slice_forward : over f ⥤ over f.left := { obj := λ α, over.mk α.hom.left, map := λ α β κ, over.hom_mk κ.left.left (by { rw auto_param_eq, rw ← over.w κ, refl }) } /-- Given f : Y ⟶ X, this is the obvious functor from T/Y to (T/X)/f -/ @[simps] def iterated_slice_backward : over f.left ⥤ over f := { obj := λ g, over.mk (over.hom_mk g.hom (by simp) : over.mk (g.hom ≫ f.hom) ⟶ f), map := λ g h α, over.hom_mk (over.hom_mk α.left (over.w_assoc α f.hom)) (over.over_morphism.ext (over.w α)) } /-- Given f : Y ⟶ X, we have an equivalence between (T/X)/f and T/Y -/ @[simps] def iterated_slice_equiv : over f ≌ over f.left := { functor := iterated_slice_forward f, inverse := iterated_slice_backward f, unit_iso := nat_iso.of_components (λ g, ⟨over.hom_mk (over.hom_mk (𝟙 g.left.left)) (by apply_auto_param), over.hom_mk (over.hom_mk (𝟙 g.left.left)) (by apply_auto_param), by { ext, dsimp, simp }, by { ext, dsimp, simp }⟩) (λ X Y g, by { ext, dsimp, simp }), counit_iso := nat_iso.of_components (λ g, ⟨over.hom_mk (𝟙 g.left) (by apply_auto_param), over.hom_mk (𝟙 g.left) (by apply_auto_param), by { ext, dsimp, simp }, by { ext, dsimp, simp }⟩) (λ X Y g, by { ext, dsimp, simp }) } lemma iterated_slice_forward_forget : iterated_slice_forward f ⋙ forget = forget ⋙ forget := rfl lemma iterated_slice_backward_forget_forget : iterated_slice_backward f ⋙ forget ⋙ forget = forget := rfl end iterated_slice section variables {D : Type u₃} [category.{v₃} D] /-- A functor `F : T ⥤ D` induces a functor `over X ⥤ over (F.obj X)` in the obvious way. -/ def post (F : T ⥤ D) : over X ⥤ over (F.obj X) := { obj := λ Y, mk $ F.map Y.hom, map := λ Y₁ Y₂ f, { left := F.map f.left, w' := by tidy; erw [← F.map_comp, w] } } end end over /-- The under category has as objects arrows with domain `X` and as morphisms commutative triangles. -/ @[derive category] def under (X : T) := comma.{0 v₃ v₃} ((functor.const punit).obj X) (𝟭 T) -- Satisfying the inhabited linter instance under.inhabited [inhabited T] : inhabited (under (default T)) := { default := { right := default T, hom := 𝟙 _ } } namespace under variables {X : T} @[ext] lemma under_morphism.ext {X : T} {U V : under X} {f g : U ⟶ V} (h : f.right = g.right) : f = g := by tidy @[simp] lemma under_left (U : under X) : U.left = punit.star := by tidy @[simp] lemma under_morphism_left {U V : under X} (f : U ⟶ V) : f.left = 𝟙 punit.star := by tidy @[simp] lemma id_right (U : under X) : comma_morphism.right (𝟙 U) = 𝟙 U.right := rfl @[simp] lemma comp_right (a b c : under X) (f : a ⟶ b) (g : b ⟶ c) : (f ≫ g).right = f.right ≫ g.right := rfl @[simp] lemma w {A B : under X} (f : A ⟶ B) : A.hom ≫ f.right = B.hom := by have := f.w; tidy /-- To give an object in the under category, it suffices to give an arrow with domain `X`. -/ def mk {X Y : T} (f : X ⟶ Y) : under X := { right := Y, hom := f } @[simp] lemma mk_right {X Y : T} (f : X ⟶ Y) : (mk f).right = Y := rfl @[simp] lemma mk_hom {X Y : T} (f : X ⟶ Y) : (mk f).hom = f := rfl /-- To give a morphism in the under category, it suffices to give a morphism fitting in a commutative triangle. -/ def hom_mk {U V : under X} (f : U.right ⟶ V.right) (w : U.hom ≫ f = V.hom . obviously) : U ⟶ V := { right := f } @[simp] lemma hom_mk_right {U V : under X} (f : U.right ⟶ V.right) (w : U.hom ≫ f = V.hom) : (hom_mk f).right = f := rfl /-- The forgetful functor mapping an arrow to its domain. -/ def forget : (under X) ⥤ T := comma.snd _ _ @[simp] lemma forget_obj {U : under X} : forget.obj U = U.right := rfl @[simp] lemma forget_map {U V : under X} {f : U ⟶ V} : forget.map f = f.right := rfl /-- A morphism `X ⟶ Y` induces a functor `under Y ⥤ under X` in the obvious way. -/ def map {Y : T} (f : X ⟶ Y) : under Y ⥤ under X := comma.map_left _ $ (functor.const punit).map f section variables {Y : T} {f : X ⟶ Y} {U V : under Y} {g : U ⟶ V} @[simp] lemma map_obj_right : ((map f).obj U).right = U.right := rfl @[simp] lemma map_obj_hom : ((map f).obj U).hom = f ≫ U.hom := rfl @[simp] lemma map_map_right : ((map f).map g).right = g.right := rfl end section variables {D : Type u₃} [category.{v₃} D] /-- A functor `F : T ⥤ D` induces a functor `under X ⥤ under (F.obj X)` in the obvious way. -/ def post {X : T} (F : T ⥤ D) : under X ⥤ under (F.obj X) := { obj := λ Y, mk $ F.map Y.hom, map := λ Y₁ Y₂ f, { right := F.map f.right, w' := by tidy; erw [← F.map_comp, w] } } end end under section variables (T) /-- The arrow category of `T` has as objects all morphisms in `T` and as morphisms commutative squares in `T`. -/ @[derive category] def arrow := comma.{v₃ v₃ v₃} (𝟭 T) (𝟭 T) -- Satisfying the inhabited linter instance arrow.inhabited [inhabited T] : inhabited (arrow T) := { default := show comma (𝟭 T) (𝟭 T), from default (comma (𝟭 T) (𝟭 T)) } end namespace arrow @[simp] lemma id_left (f : arrow T) : comma_morphism.left (𝟙 f) = 𝟙 (f.left) := rfl @[simp] lemma id_right (f : arrow T) : comma_morphism.right (𝟙 f) = 𝟙 (f.right) := rfl /-- An object in the arrow category is simply a morphism in `T`. -/ def mk {X Y : T} (f : X ⟶ Y) : arrow T := ⟨X, Y, f⟩ @[simp] lemma mk_hom {X Y : T} (f : X ⟶ Y) : (mk f).hom = f := rfl /-- A morphism in the arrow category is a commutative square connecting two objects of the arrow category. -/ def hom_mk {f g : arrow T} {u : f.left ⟶ g.left} {v : f.right ⟶ g.right} (w : u ≫ g.hom = f.hom ≫ v) : f ⟶ g := { left := u, right := v, w' := w } @[simp] lemma hom_mk_left {f g : arrow T} {u : f.left ⟶ g.left} {v : f.right ⟶ g.right} (w : u ≫ g.hom = f.hom ≫ v) : (hom_mk w).left = u := rfl @[simp] lemma hom_mk_right {f g : arrow T} {u : f.left ⟶ g.left} {v : f.right ⟶ g.right} (w : u ≫ g.hom = f.hom ≫ v) : (hom_mk w).right = v := rfl /-- We can also build a morphism in the arrow category out of any commutative square in `T`. -/ def hom_mk' {X Y : T} {f : X ⟶ Y} {P Q : T} {g : P ⟶ Q} {u : X ⟶ P} {v : Y ⟶ Q} (w : u ≫ g = f ≫ v) : arrow.mk f ⟶ arrow.mk g := { left := u, right := v, w' := w } @[simp] lemma hom_mk'_left {X Y : T} {f : X ⟶ Y} {P Q : T} {g : P ⟶ Q} {u : X ⟶ P} {v : Y ⟶ Q} (w : u ≫ g = f ≫ v) : (hom_mk' w).left = u := rfl @[simp] lemma hom_mk'_right {X Y : T} {f : X ⟶ Y} {P Q : T} {g : P ⟶ Q} {u : X ⟶ P} {v : Y ⟶ Q} (w : u ≫ g = f ≫ v) : (hom_mk' w).right = v := rfl @[reassoc] lemma w {f g : arrow T} (sq : f ⟶ g) : sq.left ≫ g.hom = f.hom ≫ sq.right := sq.w /-- A lift of a commutative square is a diagonal morphism making the two triangles commute. -/ @[ext] class has_lift {f g : arrow T} (sq : f ⟶ g) := (lift : f.right ⟶ g.left) (fac_left : f.hom ≫ lift = sq.left) (fac_right : lift ≫ g.hom = sq.right) attribute [simp, reassoc] has_lift.fac_left has_lift.fac_right /-- If we have chosen a lift of a commutative square `sq`, we can access it by saying `lift sq`. -/ abbreviation lift {f g : arrow T} (sq : f ⟶ g) [has_lift sq] : f.right ⟶ g.left := has_lift.lift sq lemma lift.fac_left {f g : arrow T} (sq : f ⟶ g) [has_lift sq] : f.hom ≫ lift sq = sq.left := by simp lemma lift.fac_right {f g : arrow T} (sq : f ⟶ g) [has_lift sq] : lift sq ≫ g.hom = sq.right := by simp @[simp, reassoc] lemma lift_mk'_left {X Y P Q : T} {f : X ⟶ Y} {g : P ⟶ Q} {u : X ⟶ P} {v : Y ⟶ Q} (h : u ≫ g = f ≫ v) [has_lift $ arrow.hom_mk' h] : f ≫ lift (arrow.hom_mk' h) = u := by simp only [←arrow.mk_hom f, lift.fac_left, arrow.hom_mk'_left] @[simp, reassoc] lemma lift_mk'_right {X Y P Q : T} {f : X ⟶ Y} {g : P ⟶ Q} {u : X ⟶ P} {v : Y ⟶ Q} (h : u ≫ g = f ≫ v) [has_lift $ arrow.hom_mk' h] : lift (arrow.hom_mk' h) ≫ g = v := by simp only [←arrow.mk_hom g, lift.fac_right, arrow.hom_mk'_right] section instance subsingleton_has_lift_of_epi {f g : arrow T} (sq : f ⟶ g) [epi f.hom] : subsingleton (has_lift sq) := subsingleton.intro $ λ a b, has_lift.ext a b $ (cancel_epi f.hom).1 $ by simp instance subsingleton_has_lift_of_mono {f g : arrow T} (sq : f ⟶ g) [mono g.hom] : subsingleton (has_lift sq) := subsingleton.intro $ λ a b, has_lift.ext a b $ (cancel_mono g.hom).1 $ by simp end end arrow end category_theory
20557620cf26e56d79fe4eade4be37b418095974
2eab05920d6eeb06665e1a6df77b3157354316ad
/src/combinatorics/simple_graph/basic.lean
705afec04d3a7b91d3262526db77de8a368d87f0
[ "Apache-2.0" ]
permissive
ayush1801/mathlib
78949b9f789f488148142221606bf15c02b960d2
ce164e28f262acbb3de6281b3b03660a9f744e3c
refs/heads/master
1,692,886,907,941
1,635,270,866,000
1,635,270,866,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
30,068
lean
/- Copyright (c) 2020 Aaron Anderson, Jalex Stark, Kyle Miller. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson, Jalex Stark, Kyle Miller, Alena Gusakov, Hunter Monroe -/ import data.fintype.basic import data.set.finite import data.sym.sym2 /-! # Simple graphs This module defines simple graphs on a vertex type `V` as an irreflexive symmetric relation. There is a basic API for locally finite graphs and for graphs with finitely many vertices. ## Main definitions * `simple_graph` is a structure for symmetric, irreflexive relations * `neighbor_set` is the `set` of vertices adjacent to a given vertex * `common_neighbors` is the intersection of the neighbor sets of two given vertices * `neighbor_finset` is the `finset` of vertices adjacent to a given vertex, if `neighbor_set` is finite * `incidence_set` is the `set` of edges containing a given vertex * `incidence_finset` is the `finset` of edges containing a given vertex, if `incidence_set` is finite * `homo`, `embedding`, and `iso` for graph homomorphisms, graph embeddings, and graph isomorphisms. Note that a graph embedding is a stronger notion than an injective graph homomorphism, since its image is an induced subgraph. * `boolean_algebra` instance: Under the subgraph relation, `simple_graph` forms a `boolean_algebra`. In other words, this is the lattice of spanning subgraphs of the complete graph. ## Notations * `→g`, `↪g`, and `≃g` for graph homomorphisms, graph embeddings, and graph isomorphisms, respectively. ## Implementation notes * A locally finite graph is one with instances `Π v, fintype (G.neighbor_set v)`. * Given instances `decidable_rel G.adj` and `fintype V`, then the graph is locally finite, too. * Morphisms of graphs are abbreviations for `rel_hom`, `rel_embedding`, and `rel_iso`. To make use of pre-existing simp lemmas, definitions involving morphisms are abbreviations as well. ## Naming Conventions * If the vertex type of a graph is finite, we refer to its cardinality as `card_verts`. ## Todo * Upgrade `simple_graph.boolean_algebra` to a `complete_boolean_algebra`. * This is the simplest notion of an unoriented graph. This should eventually fit into a more complete combinatorics hierarchy which includes multigraphs and directed graphs. We begin with simple graphs in order to start learning what the combinatorics hierarchy should look like. -/ open finset universes u v w /-- A simple graph is an irreflexive symmetric relation `adj` on a vertex type `V`. The relation describes which pairs of vertices are adjacent. There is exactly one edge for every pair of adjacent edges; see `simple_graph.edge_set` for the corresponding edge set. -/ @[ext] structure simple_graph (V : Type u) := (adj : V → V → Prop) (symm : symmetric adj . obviously) (loopless : irreflexive adj . obviously) /-- Construct the simple graph induced by the given relation. It symmetrizes the relation and makes it irreflexive. -/ def simple_graph.from_rel {V : Type u} (r : V → V → Prop) : simple_graph V := { adj := λ a b, (a ≠ b) ∧ (r a b ∨ r b a), symm := λ a b ⟨hn, hr⟩, ⟨hn.symm, hr.symm⟩, loopless := λ a ⟨hn, _⟩, hn rfl } noncomputable instance {V : Type u} [fintype V] : fintype (simple_graph V) := by { classical, exact fintype.of_injective simple_graph.adj simple_graph.ext } @[simp] lemma simple_graph.from_rel_adj {V : Type u} (r : V → V → Prop) (v w : V) : (simple_graph.from_rel r).adj v w ↔ v ≠ w ∧ (r v w ∨ r w v) := iff.rfl /-- The complete graph on a type `V` is the simple graph with all pairs of distinct vertices adjacent. In `mathlib`, this is usually referred to as `⊤`. -/ def complete_graph (V : Type u) : simple_graph V := { adj := ne } /-- The graph with no edges on a given vertex type `V`. `mathlib` prefers the notation `⊥`. -/ def empty_graph (V : Type u) : simple_graph V := { adj := λ i j, false } namespace simple_graph variables {V : Type u} {W : Type v} {X : Type w} (G : simple_graph V) (G' : simple_graph W) @[simp] lemma irrefl {v : V} : ¬G.adj v v := G.loopless v lemma adj_comm (u v : V) : G.adj u v ↔ G.adj v u := ⟨λ x, G.symm x, λ x, G.symm x⟩ @[symm] lemma adj_symm {u v : V} (h : G.adj u v) : G.adj v u := G.symm h lemma ne_of_adj {a b : V} (hab : G.adj a b) : a ≠ b := by { rintro rfl, exact G.irrefl hab } section order /-- The relation that one `simple_graph` is a subgraph of another. Note that this should be spelled `≤`. -/ def is_subgraph (x y : simple_graph V) : Prop := ∀ ⦃v w : V⦄, x.adj v w → y.adj v w instance : has_le (simple_graph V) := ⟨is_subgraph⟩ @[simp] lemma is_subgraph_eq_le : (is_subgraph : simple_graph V → simple_graph V → Prop) = (≤) := rfl /-- The supremum of two graphs `x ⊔ y` has edges where either `x` or `y` have edges. -/ instance : has_sup (simple_graph V) := ⟨λ x y, { adj := x.adj ⊔ y.adj, symm := λ v w h, by rwa [pi.sup_apply, pi.sup_apply, x.adj_comm, y.adj_comm] }⟩ @[simp] lemma sup_adj (x y : simple_graph V) (v w : V) : (x ⊔ y).adj v w ↔ x.adj v w ∨ y.adj v w := iff.rfl /-- The infinum of two graphs `x ⊓ y` has edges where both `x` and `y` have edges. -/ instance : has_inf (simple_graph V) := ⟨λ x y, { adj := x.adj ⊓ y.adj, symm := λ v w h, by rwa [pi.inf_apply, pi.inf_apply, x.adj_comm, y.adj_comm] }⟩ @[simp] lemma inf_adj (x y : simple_graph V) (v w : V) : (x ⊓ y).adj v w ↔ x.adj v w ∧ y.adj v w := iff.rfl /-- We define `Gᶜ` to be the `simple_graph V` such that no two adjacent vertices in `G` are adjacent in the complement, and every nonadjacent pair of vertices is adjacent (still ensuring that vertices are not adjacent to themselves). -/ instance : has_compl (simple_graph V) := ⟨λ G, { adj := λ v w, v ≠ w ∧ ¬G.adj v w, symm := λ v w ⟨hne, _⟩, ⟨hne.symm, by rwa adj_comm⟩, loopless := λ v ⟨hne, _⟩, (hne rfl).elim }⟩ @[simp] lemma compl_adj (G : simple_graph V) (v w : V) : Gᶜ.adj v w ↔ v ≠ w ∧ ¬G.adj v w := iff.rfl /-- The difference of two graphs `x / y` has the edges of `x` with the edges of `y` removed. -/ instance : has_sdiff (simple_graph V) := ⟨λ x y, { adj := x.adj \ y.adj, symm := λ v w h, by change x.adj w v ∧ ¬ y.adj w v; rwa [x.adj_comm, y.adj_comm] }⟩ @[simp] lemma sdiff_adj (x y : simple_graph V) (v w : V) : (x \ y).adj v w ↔ (x.adj v w ∧ ¬ y.adj v w) := iff.rfl instance : boolean_algebra (simple_graph V) := { le := (≤), sup := (⊔), inf := (⊓), compl := has_compl.compl, sdiff := (\), top := complete_graph V, bot := empty_graph V, le_top := λ x v w h, x.ne_of_adj h, bot_le := λ x v w h, h.elim, sup_le := λ x y z hxy hyz v w h, h.cases_on (λ h, hxy h) (λ h, hyz h), sdiff_eq := λ x y, by { ext v w, refine ⟨λ h, ⟨h.1, ⟨_, h.2⟩⟩, λ h, ⟨h.1, h.2.2⟩⟩, rintro rfl, exact x.irrefl h.1 }, sup_inf_sdiff := λ a b, by { ext v w, refine ⟨λ h, _, λ h', _⟩, obtain ⟨ha, _⟩|⟨ha, _⟩ := h; exact ha, by_cases b.adj v w; exact or.inl ⟨h', h⟩ <|> exact or.inr ⟨h', h⟩ }, inf_inf_sdiff := λ a b, by { ext v w, exact ⟨λ ⟨⟨_, hb⟩,⟨_, hb'⟩⟩, hb' hb, λ h, h.elim⟩ }, le_sup_left := λ x y v w h, or.inl h, le_sup_right := λ x y v w h, or.inr h, le_inf := λ x y z hxy hyz v w h, ⟨hxy h, hyz h⟩, le_sup_inf := λ a b c v w h, or.dcases_on h.2 or.inl $ or.dcases_on h.1 (λ h _, or.inl h) $ λ hb hc, or.inr ⟨hb, hc⟩, inf_compl_le_bot := λ a v w h, false.elim $ h.2.2 h.1, top_le_sup_compl := λ a v w ne, by { by_cases a.adj v w, exact or.inl h, exact or.inr ⟨ne, h⟩ }, inf_le_left := λ x y v w h, h.1, inf_le_right := λ x y v w h, h.2, .. partial_order.lift adj ext } @[simp] lemma top_adj (v w : V) : (⊤ : simple_graph V).adj v w ↔ v ≠ w := iff.rfl @[simp] lemma bot_adj (v w : V) : (⊥ : simple_graph V).adj v w ↔ false := iff.rfl @[simp] lemma complete_graph_eq_top (V : Type u) : complete_graph V = ⊤ := rfl @[simp] lemma empty_graph_eq_bot (V : Type u) : empty_graph V = ⊥ := rfl instance (V : Type u) : inhabited (simple_graph V) := ⟨⊤⟩ section decidable variables (V) (H : simple_graph V) [decidable_rel G.adj] [decidable_rel H.adj] instance bot.adj_decidable : decidable_rel (⊥ : simple_graph V).adj := λ v w, decidable.false instance sup.adj_decidable : decidable_rel (G ⊔ H).adj := λ v w, or.decidable instance inf.adj_decidable : decidable_rel (G ⊓ H).adj := λ v w, and.decidable instance sdiff.adj_decidable : decidable_rel (G \ H).adj := λ v w, and.decidable variable [decidable_eq V] instance top.adj_decidable : decidable_rel (⊤ : simple_graph V).adj := λ v w, not.decidable instance compl.adj_decidable : decidable_rel Gᶜ.adj := λ v w, and.decidable end decidable end order /-- `G.neighbor_set v` is the set of vertices adjacent to `v` in `G`. -/ def neighbor_set (v : V) : set V := set_of (G.adj v) instance neighbor_set.mem_decidable (v : V) [decidable_rel G.adj] : decidable_pred (∈ G.neighbor_set v) := by { unfold neighbor_set, apply_instance } /-- The edges of G consist of the unordered pairs of vertices related by `G.adj`. The way `edge_set` is defined is such that `mem_edge_set` is proved by `refl`. (That is, `⟦(v, w)⟧ ∈ G.edge_set` is definitionally equal to `G.adj v w`.) -/ def edge_set : set (sym2 V) := sym2.from_rel G.symm /-- The `incidence_set` is the set of edges incident to a given vertex. -/ def incidence_set (v : V) : set (sym2 V) := {e ∈ G.edge_set | v ∈ e} lemma incidence_set_subset (v : V) : G.incidence_set v ⊆ G.edge_set := λ _ h, h.1 @[simp] lemma mem_edge_set {v w : V} : ⟦(v, w)⟧ ∈ G.edge_set ↔ G.adj v w := iff.rfl /-- Two vertices are adjacent iff there is an edge between them. The condition `v ≠ w` ensures they are different endpoints of the edge, which is necessary since when `v = w` the existential `∃ (e ∈ G.edge_set), v ∈ e ∧ w ∈ e` is satisfied by every edge incident to `v`. -/ lemma adj_iff_exists_edge {v w : V} : G.adj v w ↔ v ≠ w ∧ ∃ (e ∈ G.edge_set), v ∈ e ∧ w ∈ e := begin refine ⟨λ _, ⟨G.ne_of_adj ‹_›, ⟦(v,w)⟧, _⟩, _⟩, { simpa }, { rintro ⟨hne, e, he, hv⟩, rw sym2.elems_iff_eq hne at hv, subst e, rwa mem_edge_set at he } end lemma edge_other_ne {e : sym2 V} (he : e ∈ G.edge_set) {v : V} (h : v ∈ e) : h.other ≠ v := begin erw [← sym2.mem_other_spec h, sym2.eq_swap] at he, exact G.ne_of_adj he, end instance decidable_mem_edge_set [decidable_rel G.adj] : decidable_pred (∈ G.edge_set) := sym2.from_rel.decidable_pred _ instance edges_fintype [decidable_eq V] [fintype V] [decidable_rel G.adj] : fintype G.edge_set := subtype.fintype _ instance decidable_mem_incidence_set [decidable_eq V] [decidable_rel G.adj] (v : V) : decidable_pred (∈ G.incidence_set v) := λ e, and.decidable /-- The `edge_set` of the graph as a `finset`. -/ def edge_finset [decidable_eq V] [fintype V] [decidable_rel G.adj] : finset (sym2 V) := set.to_finset G.edge_set @[simp] lemma mem_edge_finset [decidable_eq V] [fintype V] [decidable_rel G.adj] (e : sym2 V) : e ∈ G.edge_finset ↔ e ∈ G.edge_set := set.mem_to_finset @[simp] lemma edge_set_univ_card [decidable_eq V] [fintype V] [decidable_rel G.adj] : (univ : finset G.edge_set).card = G.edge_finset.card := fintype.card_of_subtype G.edge_finset (mem_edge_finset _) @[simp] lemma mem_neighbor_set (v w : V) : w ∈ G.neighbor_set v ↔ G.adj v w := iff.rfl @[simp] lemma mem_incidence_set (v w : V) : ⟦(v, w)⟧ ∈ G.incidence_set v ↔ G.adj v w := by simp [incidence_set] lemma mem_incidence_iff_neighbor {v w : V} : ⟦(v, w)⟧ ∈ G.incidence_set v ↔ w ∈ G.neighbor_set v := by simp only [mem_incidence_set, mem_neighbor_set] lemma adj_incidence_set_inter {v : V} {e : sym2 V} (he : e ∈ G.edge_set) (h : v ∈ e) : G.incidence_set v ∩ G.incidence_set h.other = {e} := begin ext e', simp only [incidence_set, set.mem_sep_eq, set.mem_inter_eq, set.mem_singleton_iff], split, { intro h', rw ←sym2.mem_other_spec h, exact (sym2.elems_iff_eq (edge_other_ne G he h).symm).mp ⟨h'.1.2, h'.2.2⟩, }, { rintro rfl, use [he, h, he], apply sym2.mem_other_mem, }, end lemma compl_neighbor_set_disjoint (G : simple_graph V) (v : V) : disjoint (G.neighbor_set v) (Gᶜ.neighbor_set v) := begin rw set.disjoint_iff, rintro w ⟨h, h'⟩, rw [mem_neighbor_set, compl_adj] at h', exact h'.2 h, end lemma neighbor_set_union_compl_neighbor_set_eq (G : simple_graph V) (v : V) : G.neighbor_set v ∪ Gᶜ.neighbor_set v = {v}ᶜ := begin ext w, have h := @ne_of_adj _ G, simp_rw [set.mem_union, mem_neighbor_set, compl_adj, set.mem_compl_eq, set.mem_singleton_iff], tauto, end /-- The set of common neighbors between two vertices `v` and `w` in a graph `G` is the intersection of the neighbor sets of `v` and `w`. -/ def common_neighbors (v w : V) : set V := G.neighbor_set v ∩ G.neighbor_set w lemma common_neighbors_eq (v w : V) : G.common_neighbors v w = G.neighbor_set v ∩ G.neighbor_set w := rfl lemma mem_common_neighbors {u v w : V} : u ∈ G.common_neighbors v w ↔ G.adj v u ∧ G.adj w u := by simp [common_neighbors] lemma common_neighbors_symm (v w : V) : G.common_neighbors v w = G.common_neighbors w v := by { rw [common_neighbors, set.inter_comm], refl } lemma not_mem_common_neighbors_left (v w : V) : v ∉ G.common_neighbors v w := λ h, ne_of_adj G h.1 rfl lemma not_mem_common_neighbors_right (v w : V) : w ∉ G.common_neighbors v w := λ h, ne_of_adj G h.2 rfl lemma common_neighbors_subset_neighbor_set (v w : V) : G.common_neighbors v w ⊆ G.neighbor_set v := by simp [common_neighbors] instance decidable_mem_common_neighbors [decidable_rel G.adj] (v w : V) : decidable_pred (∈ G.common_neighbors v w) := λ a, and.decidable section incidence variable [decidable_eq V] /-- Given an edge incident to a particular vertex, get the other vertex on the edge. -/ def other_vertex_of_incident {v : V} {e : sym2 V} (h : e ∈ G.incidence_set v) : V := h.2.other' lemma edge_mem_other_incident_set {v : V} {e : sym2 V} (h : e ∈ G.incidence_set v) : e ∈ G.incidence_set (G.other_vertex_of_incident h) := by { use h.1, simp [other_vertex_of_incident, sym2.mem_other_mem'] } lemma incidence_other_prop {v : V} {e : sym2 V} (h : e ∈ G.incidence_set v) : G.other_vertex_of_incident h ∈ G.neighbor_set v := by { cases h with he hv, rwa [←sym2.mem_other_spec' hv, mem_edge_set] at he } @[simp] lemma incidence_other_neighbor_edge {v w : V} (h : w ∈ G.neighbor_set v) : G.other_vertex_of_incident (G.mem_incidence_iff_neighbor.mpr h) = w := sym2.congr_right.mp (sym2.mem_other_spec' (G.mem_incidence_iff_neighbor.mpr h).right) /-- There is an equivalence between the set of edges incident to a given vertex and the set of vertices adjacent to the vertex. -/ @[simps] def incidence_set_equiv_neighbor_set (v : V) : G.incidence_set v ≃ G.neighbor_set v := { to_fun := λ e, ⟨G.other_vertex_of_incident e.2, G.incidence_other_prop e.2⟩, inv_fun := λ w, ⟨⟦(v, w.1)⟧, G.mem_incidence_iff_neighbor.mpr w.2⟩, left_inv := λ x, by simp [other_vertex_of_incident], right_inv := λ ⟨w, hw⟩, by simp } end incidence section finite_at /-! ## Finiteness at a vertex This section contains definitions and lemmas concerning vertices that have finitely many adjacent vertices. We denote this condition by `fintype (G.neighbor_set v)`. We define `G.neighbor_finset v` to be the `finset` version of `G.neighbor_set v`. Use `neighbor_finset_eq_filter` to rewrite this definition as a `filter`. -/ variables (v : V) [fintype (G.neighbor_set v)] /-- `G.neighbors v` is the `finset` version of `G.adj v` in case `G` is locally finite at `v`. -/ def neighbor_finset : finset V := (G.neighbor_set v).to_finset @[simp] lemma mem_neighbor_finset (w : V) : w ∈ G.neighbor_finset v ↔ G.adj v w := set.mem_to_finset /-- `G.degree v` is the number of vertices adjacent to `v`. -/ def degree : ℕ := (G.neighbor_finset v).card @[simp] lemma card_neighbor_set_eq_degree : fintype.card (G.neighbor_set v) = G.degree v := (set.to_finset_card _).symm lemma degree_pos_iff_exists_adj : 0 < G.degree v ↔ ∃ w, G.adj v w := by simp only [degree, card_pos, finset.nonempty, mem_neighbor_finset] instance incidence_set_fintype [decidable_eq V] : fintype (G.incidence_set v) := fintype.of_equiv (G.neighbor_set v) (G.incidence_set_equiv_neighbor_set v).symm /-- This is the `finset` version of `incidence_set`. -/ def incidence_finset [decidable_eq V] : finset (sym2 V) := (G.incidence_set v).to_finset @[simp] lemma card_incidence_set_eq_degree [decidable_eq V] : fintype.card (G.incidence_set v) = G.degree v := by { rw fintype.card_congr (G.incidence_set_equiv_neighbor_set v), simp } @[simp] lemma mem_incidence_finset [decidable_eq V] (e : sym2 V) : e ∈ G.incidence_finset v ↔ e ∈ G.incidence_set v := set.mem_to_finset end finite_at section locally_finite /-- A graph is locally finite if every vertex has a finite neighbor set. -/ @[reducible] def locally_finite := Π (v : V), fintype (G.neighbor_set v) variable [locally_finite G] /-- A locally finite simple graph is regular of degree `d` if every vertex has degree `d`. -/ def is_regular_of_degree (d : ℕ) : Prop := ∀ (v : V), G.degree v = d lemma is_regular_of_degree_eq {d : ℕ} (h : G.is_regular_of_degree d) (v : V) : G.degree v = d := h v end locally_finite section finite variable [fintype V] instance neighbor_set_fintype [decidable_rel G.adj] (v : V) : fintype (G.neighbor_set v) := @subtype.fintype _ _ (by { simp_rw mem_neighbor_set, apply_instance }) _ lemma neighbor_finset_eq_filter {v : V} [decidable_rel G.adj] : G.neighbor_finset v = finset.univ.filter (G.adj v) := by { ext, simp } @[simp] lemma complete_graph_degree [decidable_eq V] (v : V) : (⊤ : simple_graph V).degree v = fintype.card V - 1 := begin convert univ.card.pred_eq_sub_one, erw [degree, neighbor_finset_eq_filter, filter_ne, card_erase_of_mem (mem_univ v)], end lemma complete_graph_is_regular [decidable_eq V] : (⊤ : simple_graph V).is_regular_of_degree (fintype.card V - 1) := by { intro v, simp } /-- The minimum degree of all vertices (and `0` if there are no vertices). The key properties of this are given in `exists_minimal_degree_vertex`, `min_degree_le_degree` and `le_min_degree_of_forall_le_degree`. -/ def min_degree [decidable_rel G.adj] : ℕ := option.get_or_else (univ.image (λ v, G.degree v)).min 0 /-- There exists a vertex of minimal degree. Note the assumption of being nonempty is necessary, as the lemma implies there exists a vertex. -/ lemma exists_minimal_degree_vertex [decidable_rel G.adj] [nonempty V] : ∃ v, G.min_degree = G.degree v := begin obtain ⟨t, ht : _ = _⟩ := min_of_nonempty (univ_nonempty.image (λ v, G.degree v)), obtain ⟨v, _, rfl⟩ := mem_image.mp (mem_of_min ht), refine ⟨v, by simp [min_degree, ht]⟩, end /-- The minimum degree in the graph is at most the degree of any particular vertex. -/ lemma min_degree_le_degree [decidable_rel G.adj] (v : V) : G.min_degree ≤ G.degree v := begin obtain ⟨t, ht⟩ := finset.min_of_mem (mem_image_of_mem (λ v, G.degree v) (mem_univ v)), have := finset.min_le_of_mem (mem_image_of_mem _ (mem_univ v)) ht, rw option.mem_def at ht, rwa [min_degree, ht, option.get_or_else_some], end /-- In a nonempty graph, if `k` is at most the degree of every vertex, it is at most the minimum degree. Note the assumption that the graph is nonempty is necessary as long as `G.min_degree` is defined to be a natural. -/ lemma le_min_degree_of_forall_le_degree [decidable_rel G.adj] [nonempty V] (k : ℕ) (h : ∀ v, k ≤ G.degree v) : k ≤ G.min_degree := begin rcases G.exists_minimal_degree_vertex with ⟨v, hv⟩, rw hv, apply h end /-- The maximum degree of all vertices (and `0` if there are no vertices). The key properties of this are given in `exists_maximal_degree_vertex`, `degree_le_max_degree` and `max_degree_le_of_forall_degree_le`. -/ def max_degree [decidable_rel G.adj] : ℕ := option.get_or_else (univ.image (λ v, G.degree v)).max 0 /-- There exists a vertex of maximal degree. Note the assumption of being nonempty is necessary, as the lemma implies there exists a vertex. -/ lemma exists_maximal_degree_vertex [decidable_rel G.adj] [nonempty V] : ∃ v, G.max_degree = G.degree v := begin obtain ⟨t, ht⟩ := max_of_nonempty (univ_nonempty.image (λ v, G.degree v)), have ht₂ := mem_of_max ht, simp only [mem_image, mem_univ, exists_prop_of_true] at ht₂, rcases ht₂ with ⟨v, rfl⟩, rw option.mem_def at ht, refine ⟨v, _⟩, rw [max_degree, ht], refl end /-- The maximum degree in the graph is at least the degree of any particular vertex. -/ lemma degree_le_max_degree [decidable_rel G.adj] (v : V) : G.degree v ≤ G.max_degree := begin obtain ⟨t, ht : _ = _⟩ := finset.max_of_mem (mem_image_of_mem (λ v, G.degree v) (mem_univ v)), have := finset.le_max_of_mem (mem_image_of_mem _ (mem_univ v)) ht, rwa [max_degree, ht, option.get_or_else_some], end /-- In a graph, if `k` is at least the degree of every vertex, then it is at least the maximum degree. -/ lemma max_degree_le_of_forall_degree_le [decidable_rel G.adj] (k : ℕ) (h : ∀ v, G.degree v ≤ k) : G.max_degree ≤ k := begin by_cases hV : (univ : finset V).nonempty, { haveI : nonempty V := univ_nonempty_iff.mp hV, obtain ⟨v, hv⟩ := G.exists_maximal_degree_vertex, rw hv, apply h }, { rw not_nonempty_iff_eq_empty at hV, rw [max_degree, hV, image_empty], exact zero_le k }, end lemma degree_lt_card_verts [decidable_rel G.adj] (v : V) : G.degree v < fintype.card V := begin classical, apply finset.card_lt_card, rw finset.ssubset_iff, exact ⟨v, by simp, finset.subset_univ _⟩, end /-- The maximum degree of a nonempty graph is less than the number of vertices. Note that the assumption that `V` is nonempty is necessary, as otherwise this would assert the existence of a natural number less than zero. -/ lemma max_degree_lt_card_verts [decidable_rel G.adj] [nonempty V] : G.max_degree < fintype.card V := begin cases G.exists_maximal_degree_vertex with v hv, rw hv, apply G.degree_lt_card_verts v, end lemma card_common_neighbors_le_degree_left [decidable_rel G.adj] (v w : V) : fintype.card (G.common_neighbors v w) ≤ G.degree v := begin rw [←card_neighbor_set_eq_degree], exact set.card_le_of_subset (set.inter_subset_left _ _), end lemma card_common_neighbors_le_degree_right [decidable_rel G.adj] (v w : V) : fintype.card (G.common_neighbors v w) ≤ G.degree w := begin convert G.card_common_neighbors_le_degree_left w v using 3, apply common_neighbors_symm, end lemma card_common_neighbors_lt_card_verts [decidable_rel G.adj] (v w : V) : fintype.card (G.common_neighbors v w) < fintype.card V := nat.lt_of_le_of_lt (G.card_common_neighbors_le_degree_left _ _) (G.degree_lt_card_verts v) /-- If the condition `G.adj v w` fails, then `card_common_neighbors_le_degree` is the best we can do in general. -/ lemma adj.card_common_neighbors_lt_degree {G : simple_graph V} [decidable_rel G.adj] {v w : V} (h : G.adj v w) : fintype.card (G.common_neighbors v w) < G.degree v := begin classical, erw [←set.to_finset_card], apply finset.card_lt_card, rw finset.ssubset_iff, use w, split, { rw set.mem_to_finset, apply not_mem_common_neighbors_right }, { rw finset.insert_subset, split, { simpa, }, { rw [neighbor_finset, ← set.subset_iff_to_finset_subset], apply common_neighbors_subset_neighbor_set } }, end end finite section maps /-- A graph homomorphism is a map on vertex sets that respects adjacency relations. The notation `G →g G'` represents the type of graph homomorphisms. -/ abbreviation hom := rel_hom G.adj G'.adj /-- A graph embedding is an embedding `f` such that for vertices `v w : V`, `G.adj f(v) f(w) ↔ G.adj v w `. Its image is an induced subgraph of G'. The notation `G ↪g G'` represents the type of graph embeddings. -/ abbreviation embedding := rel_embedding G.adj G'.adj /-- A graph isomorphism is an bijective map on vertex sets that respects adjacency relations. The notation `G ≃g G'` represents the type of graph isomorphisms. -/ abbreviation iso := rel_iso G.adj G'.adj infix ` →g ` : 50 := hom infix ` ↪g ` : 50 := embedding infix ` ≃g ` : 50 := iso namespace hom variables {G G'} (f : G →g G') /-- The identity homomorphism from a graph to itself. -/ abbreviation id : G →g G := rel_hom.id _ lemma map_adj {v w : V} (h : G.adj v w) : G'.adj (f v) (f w) := f.map_rel' h lemma map_mem_edge_set {e : sym2 V} (h : e ∈ G.edge_set) : e.map f ∈ G'.edge_set := quotient.ind (λ e h, sym2.from_rel_prop.mpr (f.map_rel' h)) e h lemma apply_mem_neighbor_set {v w : V} (h : w ∈ G.neighbor_set v) : f w ∈ G'.neighbor_set (f v) := map_adj f h /-- The map between edge sets induced by a homomorphism. The underlying map on edges is given by `sym2.map`. -/ @[simps] def map_edge_set (e : G.edge_set) : G'.edge_set := ⟨sym2.map f e, f.map_mem_edge_set e.property⟩ /-- The map between neighbor sets induced by a homomorphism. -/ @[simps] def map_neighbor_set (v : V) (w : G.neighbor_set v) : G'.neighbor_set (f v) := ⟨f w, f.apply_mem_neighbor_set w.property⟩ lemma map_edge_set.injective (hinj : function.injective f) : function.injective f.map_edge_set := begin rintros ⟨e₁, h₁⟩ ⟨e₂, h₂⟩, dsimp [hom.map_edge_set], repeat { rw subtype.mk_eq_mk }, apply sym2.map.injective hinj, end variable {G'' : simple_graph X} /-- Composition of graph homomorphisms. -/ abbreviation comp (f' : G' →g G'') (f : G →g G') : G →g G'' := f'.comp f @[simp] lemma coe_comp (f' : G' →g G'') (f : G →g G') : ⇑(f'.comp f) = f' ∘ f := rfl end hom namespace embedding variables {G G'} (f : G ↪g G') /-- The identity embedding from a graph to itself. -/ abbreviation refl : G ↪g G := rel_embedding.refl _ /-- An embedding of graphs gives rise to a homomorphism of graphs. -/ abbreviation to_hom : G →g G' := f.to_rel_hom lemma map_adj_iff {v w : V} : G'.adj (f v) (f w) ↔ G.adj v w := f.map_rel_iff lemma map_mem_edge_set_iff {e : sym2 V} : e.map f ∈ G'.edge_set ↔ e ∈ G.edge_set := quotient.ind (λ ⟨v, w⟩, f.map_adj_iff) e lemma apply_mem_neighbor_set_iff {v w : V} : f w ∈ G'.neighbor_set (f v) ↔ w ∈ G.neighbor_set v := map_adj_iff f /-- A graph embedding induces an embedding of edge sets. -/ @[simps] def map_edge_set : G.edge_set ↪ G'.edge_set := { to_fun := hom.map_edge_set f, inj' := hom.map_edge_set.injective f f.inj' } /-- A graph embedding induces an embedding of neighbor sets. -/ @[simps] def map_neighbor_set (v : V) : G.neighbor_set v ↪ G'.neighbor_set (f v) := { to_fun := λ w, ⟨f w, f.apply_mem_neighbor_set_iff.mpr w.2⟩, inj' := begin rintros ⟨w₁, h₁⟩ ⟨w₂, h₂⟩ h, rw subtype.mk_eq_mk at h ⊢, exact f.inj' h, end } variables {G'' : simple_graph X} /-- Composition of graph embeddings. -/ abbreviation comp (f' : G' ↪g G'') (f : G ↪g G') : G ↪g G'' := f.trans f' @[simp] lemma coe_comp (f' : G' ↪g G'') (f : G ↪g G') : ⇑(f'.comp f) = f' ∘ f := rfl end embedding namespace iso variables {G G'} (f : G ≃g G') /-- The identity isomorphism of a graph with itself. -/ abbreviation refl : G ≃g G := rel_iso.refl _ /-- An isomorphism of graphs gives rise to an embedding of graphs. -/ abbreviation to_embedding : G ↪g G' := f.to_rel_embedding /-- An isomorphism of graphs gives rise to a homomorphism of graphs. -/ abbreviation to_hom : G →g G' := f.to_embedding.to_hom /-- The inverse of a graph isomorphism. --/ abbreviation symm : G' ≃g G := f.symm lemma map_adj_iff {v w : V} : G'.adj (f v) (f w) ↔ G.adj v w := f.map_rel_iff lemma map_mem_edge_set_iff {e : sym2 V} : e.map f ∈ G'.edge_set ↔ e ∈ G.edge_set := quotient.ind (λ ⟨v, w⟩, f.map_adj_iff) e lemma apply_mem_neighbor_set_iff {v w : V} : f w ∈ G'.neighbor_set (f v) ↔ w ∈ G.neighbor_set v := map_adj_iff f /-- An isomorphism of graphs induces an equivalence of edge sets. -/ @[simps] def map_edge_set : G.edge_set ≃ G'.edge_set := { to_fun := hom.map_edge_set f, inv_fun := hom.map_edge_set f.symm, left_inv := begin rintro ⟨e, h⟩, simp only [hom.map_edge_set, sym2.map_map, rel_iso.coe_coe_fn, rel_embedding.coe_coe_fn, subtype.mk_eq_mk, subtype.coe_mk, coe_coe], apply congr_fun, convert sym2.map_id, exact funext (λ _, rel_iso.symm_apply_apply _ _), end, right_inv := begin rintro ⟨e, h⟩, simp only [hom.map_edge_set, sym2.map_map, rel_iso.coe_coe_fn, rel_embedding.coe_coe_fn, subtype.mk_eq_mk, subtype.coe_mk, coe_coe], apply congr_fun, convert sym2.map_id, exact funext (λ _, rel_iso.apply_symm_apply _ _), end } /-- A graph isomorphism induces an equivalence of neighbor sets. -/ @[simps] def map_neighbor_set (v : V) : G.neighbor_set v ≃ G'.neighbor_set (f v) := { to_fun := λ w, ⟨f w, f.apply_mem_neighbor_set_iff.mpr w.2⟩, inv_fun := λ w, ⟨f.symm w, begin convert f.symm.apply_mem_neighbor_set_iff.mpr w.2, simp only [rel_iso.symm_apply_apply], end⟩, left_inv := λ w, by simp, right_inv := λ w, by simp } lemma card_eq_of_iso [fintype V] [fintype W] (f : G ≃g G') : fintype.card V = fintype.card W := by convert (fintype.of_equiv_card f.to_equiv).symm variables {G'' : simple_graph X} /-- Composition of graph isomorphisms. -/ abbreviation comp (f' : G' ≃g G'') (f : G ≃g G') : G ≃g G'' := f.trans f' @[simp] lemma coe_comp (f' : G' ≃g G'') (f : G ≃g G') : ⇑(f'.comp f) = f' ∘ f := rfl end iso end maps end simple_graph
1fc975974c9b365b160f3dc0802ca235c382d4d7
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/ring_theory/ideal/local_ring.lean
e43054bcad6173b1f2ed770f0309d6616b07be78
[ "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
9,437
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Chris Hughes, Mario Carneiro -/ import algebra.algebra.basic import algebra.category.CommRing.basic import ring_theory.ideal.operations /-! # Local rings Define local rings as commutative rings having a unique maximal ideal. ## Main definitions * `local_ring`: A predicate on commutative rings, stating that every element `a` is either a unit or `1 - a` is a unit. This is shown to be equivalent to the condition that there exists a unique maximal ideal. * `local_ring.maximal_ideal`: The unique maximal ideal for a local rings. Its carrier set is the set of non units. * `is_local_ring_hom`: A predicate on semiring homomorphisms, requiring that it maps nonunits to nonunits. For local rings, this means that the image of the unique maximal ideal is again contained in the unique maximal ideal. * `local_ring.residue_field`: The quotient of a local ring by its maximal ideal. -/ universes u v w /-- A commutative ring is local if it has a unique maximal ideal. Note that `local_ring` is a predicate. -/ class local_ring (R : Type u) [comm_ring R] extends nontrivial R : Prop := (is_local : ∀ (a : R), (is_unit a) ∨ (is_unit (1 - a))) namespace local_ring variables {R : Type u} [comm_ring R] [local_ring R] lemma is_unit_or_is_unit_one_sub_self (a : R) : (is_unit a) ∨ (is_unit (1 - a)) := is_local a lemma is_unit_of_mem_nonunits_one_sub_self (a : R) (h : (1 - a) ∈ nonunits R) : is_unit a := or_iff_not_imp_right.1 (is_local a) h lemma is_unit_one_sub_self_of_mem_nonunits (a : R) (h : a ∈ nonunits R) : is_unit (1 - a) := or_iff_not_imp_left.1 (is_local a) h lemma nonunits_add {x y} (hx : x ∈ nonunits R) (hy : y ∈ nonunits R) : x + y ∈ nonunits R := begin rintros ⟨u, hu⟩, apply hy, suffices : is_unit ((↑u⁻¹ : R) * y), { rcases this with ⟨s, hs⟩, use u * s, convert congr_arg (λ z, (u : R) * z) hs, rw ← mul_assoc, simp }, rw show (↑u⁻¹ * y) = (1 - ↑u⁻¹ * x), { rw eq_sub_iff_add_eq, replace hu := congr_arg (λ z, (↑u⁻¹ : R) * z) hu.symm, simpa [mul_add, add_comm] using hu }, apply is_unit_one_sub_self_of_mem_nonunits, exact mul_mem_nonunits_right hx end variable (R) /-- The ideal of elements that are not units. -/ def maximal_ideal : ideal R := { carrier := nonunits R, zero_mem' := zero_mem_nonunits.2 $ zero_ne_one, add_mem' := λ x y hx hy, nonunits_add hx hy, smul_mem' := λ a x, mul_mem_nonunits_right } instance maximal_ideal.is_maximal : (maximal_ideal R).is_maximal := begin rw ideal.is_maximal_iff, split, { intro h, apply h, exact is_unit_one }, { intros I x hI hx H, erw not_not at hx, rcases hx with ⟨u,rfl⟩, simpa using I.mul_mem_left ↑u⁻¹ H } end lemma maximal_ideal_unique : ∃! I : ideal R, I.is_maximal := ⟨maximal_ideal R, maximal_ideal.is_maximal R, λ I hI, hI.eq_of_le (maximal_ideal.is_maximal R).1.1 $ λ x hx, hI.1.1 ∘ I.eq_top_of_is_unit_mem hx⟩ variable {R} lemma eq_maximal_ideal {I : ideal R} (hI : I.is_maximal) : I = maximal_ideal R := unique_of_exists_unique (maximal_ideal_unique R) hI $ maximal_ideal.is_maximal R lemma le_maximal_ideal {J : ideal R} (hJ : J ≠ ⊤) : J ≤ maximal_ideal R := begin rcases ideal.exists_le_maximal J hJ with ⟨M, hM1, hM2⟩, rwa ←eq_maximal_ideal hM1 end @[simp] lemma mem_maximal_ideal (x) : x ∈ maximal_ideal R ↔ x ∈ nonunits R := iff.rfl end local_ring variables {R : Type u} {S : Type v} {T : Type w} lemma local_of_nonunits_ideal [comm_ring R] (hnze : (0:R) ≠ 1) (h : ∀ x y ∈ nonunits R, x + y ∈ nonunits R) : local_ring R := { exists_pair_ne := ⟨0, 1, hnze⟩, is_local := λ x, or_iff_not_imp_left.mpr $ λ hx, begin by_contra H, apply h _ _ hx H, simp [-sub_eq_add_neg, add_sub_cancel'_right] end } lemma local_of_unique_max_ideal [comm_ring R] (h : ∃! I : ideal R, I.is_maximal) : local_ring R := local_of_nonunits_ideal (let ⟨I, Imax, _⟩ := h in (λ (H : 0 = 1), Imax.1.1 $ I.eq_top_iff_one.2 $ H ▸ I.zero_mem)) $ λ x y hx hy H, let ⟨I, Imax, Iuniq⟩ := h in let ⟨Ix, Ixmax, Hx⟩ := exists_max_ideal_of_mem_nonunits hx in let ⟨Iy, Iymax, Hy⟩ := exists_max_ideal_of_mem_nonunits hy in have xmemI : x ∈ I, from ((Iuniq Ix Ixmax) ▸ Hx), have ymemI : y ∈ I, from ((Iuniq Iy Iymax) ▸ Hy), Imax.1.1 $ I.eq_top_of_is_unit_mem (I.add_mem xmemI ymemI) H lemma local_of_unique_nonzero_prime (R : Type u) [comm_ring R] (h : ∃! P : ideal R, P ≠ ⊥ ∧ ideal.is_prime P) : local_ring R := local_of_unique_max_ideal begin rcases h with ⟨P, ⟨hPnonzero, hPnot_top, _⟩, hPunique⟩, refine ⟨P, ⟨⟨hPnot_top, _⟩⟩, λ M hM, hPunique _ ⟨_, ideal.is_maximal.is_prime hM⟩⟩, { refine ideal.maximal_of_no_maximal (λ M hPM hM, ne_of_lt hPM _), exact (hPunique _ ⟨ne_bot_of_gt hPM, ideal.is_maximal.is_prime hM⟩).symm }, { rintro rfl, exact hPnot_top (hM.1.2 P (bot_lt_iff_ne_bot.2 hPnonzero)) }, end lemma local_of_surjective [comm_ring R] [local_ring R] [comm_ring S] [nontrivial S] (f : R →+* S) (hf : function.surjective f) : local_ring S := { is_local := begin intros b, obtain ⟨a, rfl⟩ := hf b, apply (local_ring.is_unit_or_is_unit_one_sub_self a).imp f.is_unit_map _, rw [← f.map_one, ← f.map_sub], apply f.is_unit_map, end, .. ‹nontrivial S› } /-- A local ring homomorphism is a homomorphism between local rings such that the image of the maximal ideal of the source is contained within the maximal ideal of the target. -/ class is_local_ring_hom [semiring R] [semiring S] (f : R →+* S) : Prop := (map_nonunit : ∀ a, is_unit (f a) → is_unit a) instance is_local_ring_hom_id (R : Type*) [semiring R] : is_local_ring_hom (ring_hom.id R) := { map_nonunit := λ a, id } @[simp] lemma is_unit_map_iff [semiring R] [semiring S] (f : R →+* S) [is_local_ring_hom f] (a) : is_unit (f a) ↔ is_unit a := ⟨is_local_ring_hom.map_nonunit a, f.is_unit_map⟩ instance is_local_ring_hom_comp [semiring R] [semiring S] [semiring T] (g : S →+* T) (f : R →+* S) [is_local_ring_hom g] [is_local_ring_hom f] : is_local_ring_hom (g.comp f) := { map_nonunit := λ a, is_local_ring_hom.map_nonunit a ∘ is_local_ring_hom.map_nonunit (f a) } instance is_local_ring_hom_equiv [semiring R] [semiring S] (f : R ≃+* S) : is_local_ring_hom f.to_ring_hom := { map_nonunit := λ a ha, begin convert f.symm.to_ring_hom.is_unit_map ha, rw ring_equiv.symm_to_ring_hom_apply_to_ring_hom_apply, end } @[simp] lemma is_unit_of_map_unit [semiring R] [semiring S] (f : R →+* S) [is_local_ring_hom f] (a) (h : is_unit (f a)) : is_unit a := is_local_ring_hom.map_nonunit a h theorem of_irreducible_map [semiring R] [semiring S] (f : R →+* S) [h : is_local_ring_hom f] {x : R} (hfx : irreducible (f x)) : irreducible x := ⟨λ h, hfx.not_unit $ is_unit.map f.to_monoid_hom h, λ p q hx, let ⟨H⟩ := h in or.imp (H p) (H q) $ hfx.is_unit_or_is_unit $ f.map_mul p q ▸ congr_arg f hx⟩ section open category_theory lemma is_local_ring_hom_of_iso {R S : CommRing} (f : R ≅ S) : is_local_ring_hom f.hom := { map_nonunit := λ a ha, begin convert f.inv.is_unit_map ha, rw category_theory.coe_hom_inv_id, end } @[priority 100] -- see Note [lower instance priority] instance is_local_ring_hom_of_is_iso {R S : CommRing} (f : R ⟶ S) [is_iso f] : is_local_ring_hom f := is_local_ring_hom_of_iso (as_iso f) end section open local_ring variables [comm_ring R] [local_ring R] [comm_ring S] [local_ring S] variables (f : R →+* S) [is_local_ring_hom f] lemma map_nonunit (a : R) (h : a ∈ maximal_ideal R) : f a ∈ maximal_ideal S := λ H, h $ is_unit_of_map_unit f a H end namespace local_ring variables [comm_ring R] [local_ring R] [comm_ring S] [local_ring S] variable (R) /-- The residue field of a local ring is the quotient of the ring by its maximal ideal. -/ def residue_field := (maximal_ideal R).quotient noncomputable instance residue_field.field : field (residue_field R) := ideal.quotient.field (maximal_ideal R) noncomputable instance : inhabited (residue_field R) := ⟨37⟩ /-- The quotient map from a local ring to its residue field. -/ def residue : R →+* (residue_field R) := ideal.quotient.mk _ noncomputable instance residue_field.algebra : algebra R (residue_field R) := (residue R).to_algebra namespace residue_field variables {R S} /-- The map on residue fields induced by a local homomorphism between local rings -/ noncomputable def map (f : R →+* S) [is_local_ring_hom f] : residue_field R →+* residue_field S := ideal.quotient.lift (maximal_ideal R) ((ideal.quotient.mk _).comp f) $ λ a ha, begin erw ideal.quotient.eq_zero_iff_mem, exact map_nonunit f a ha end end residue_field variables {R} lemma ker_eq_maximal_ideal {K : Type*} [field K] (φ : R →+* K) (hφ : function.surjective φ) : φ.ker = maximal_ideal R := local_ring.eq_maximal_ideal $ φ.ker_is_maximal_of_surjective hφ end local_ring namespace field variables [field R] open_locale classical @[priority 100] -- see Note [lower instance priority] instance : local_ring R := { is_local := λ a, if h : a = 0 then or.inr (by rw [h, sub_zero]; exact is_unit_one) else or.inl $ is_unit.mk0 a h } end field