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
b5bc5529e9945aa795803585b8877fd8dd3b6a10
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/data/padics/padic_integers.lean
9aec29b62a2fc1e2a14df548c719b0815d12c2ee
[ "Apache-2.0" ]
permissive
ilitzroth/mathlib
ea647e67f1fdfd19a0f7bdc5504e8acec6180011
5254ef14e3465f6504306132fe3ba9cec9ffff16
refs/heads/master
1,680,086,661,182
1,617,715,647,000
1,617,715,647,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
20,163
lean
/- Copyright (c) 2018 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Y. Lewis, Mario Carneiro, Johan Commelin -/ import data.int.modeq import data.zmod.basic import linear_algebra.adic_completion import data.padics.padic_numbers import ring_theory.discrete_valuation_ring import topology.metric_space.cau_seq_filter /-! # p-adic integers This file defines the p-adic integers `ℤ_p` as the subtype of `ℚ_p` with norm `≤ 1`. We show that `ℤ_p` * is complete * is nonarchimedean * is a normed ring * is a local ring * is a discrete valuation ring The relation between `ℤ_[p]` and `zmod p` is established in another file. ## Important definitions * `padic_int` : the type of p-adic numbers ## Notation We introduce the notation `ℤ_[p]` for the p-adic integers. ## Implementation notes Much, but not all, of this file assumes that `p` is prime. This assumption is inferred automatically by taking `[fact (nat.prime p)] as a type class argument. Coercions into `ℤ_p` are set up to work with the `norm_cast` tactic. ## References * [F. Q. Gouêva, *p-adic numbers*][gouvea1997] * [R. Y. Lewis, *A formal proof of Hensel's lemma over the p-adic integers*][lewis2019] * <https://en.wikipedia.org/wiki/P-adic_number> ## Tags p-adic, p adic, padic, p-adic integer -/ open nat padic metric local_ring noncomputable theory open_locale classical /-- The p-adic integers ℤ_p are the p-adic numbers with norm ≤ 1. -/ def padic_int (p : ℕ) [fact p.prime] := {x : ℚ_[p] // ∥x∥ ≤ 1} notation `ℤ_[`p`]` := padic_int p namespace padic_int /-! ### Ring structure and coercion to `ℚ_[p]` -/ variables {p : ℕ} [fact p.prime] instance : has_coe ℤ_[p] ℚ_[p] := ⟨subtype.val⟩ lemma ext {x y : ℤ_[p]} : (x : ℚ_[p]) = y → x = y := subtype.ext_iff_val.2 /-- Addition on ℤ_p is inherited from ℚ_p. -/ instance : has_add ℤ_[p] := ⟨λ ⟨x, hx⟩ ⟨y, hy⟩, ⟨x+y, le_trans (padic_norm_e.nonarchimedean _ _) (max_le_iff.2 ⟨hx,hy⟩)⟩⟩ /-- Multiplication on ℤ_p is inherited from ℚ_p. -/ instance : has_mul ℤ_[p] := ⟨λ ⟨x, hx⟩ ⟨y, hy⟩, ⟨x*y, begin rw padic_norm_e.mul, apply mul_le_one; {assumption <|> apply norm_nonneg} end⟩⟩ /-- Negation on ℤ_p is inherited from ℚ_p. -/ instance : has_neg ℤ_[p] := ⟨λ ⟨x, hx⟩, ⟨-x, by simpa⟩⟩ /-- Subtraction on ℤ_p is inherited from ℚ_p. -/ instance : has_sub ℤ_[p] := ⟨λ ⟨x, hx⟩ ⟨y, hy⟩, ⟨x - y, by { rw sub_eq_add_neg, rw ← norm_neg at hy, exact le_trans (padic_norm_e.nonarchimedean _ _) (max_le_iff.2 ⟨hx, hy⟩) }⟩⟩ /-- Zero on ℤ_p is inherited from ℚ_p. -/ instance : has_zero ℤ_[p] := ⟨⟨0, by norm_num⟩⟩ instance : inhabited ℤ_[p] := ⟨0⟩ /-- One on ℤ_p is inherited from ℚ_p. -/ instance : has_one ℤ_[p] := ⟨⟨1, by norm_num⟩⟩ @[simp] lemma mk_zero {h} : (⟨0, h⟩ : ℤ_[p]) = (0 : ℤ_[p]) := rfl @[simp] lemma val_eq_coe (z : ℤ_[p]) : z.val = z := rfl @[simp, norm_cast] lemma coe_add : ∀ (z1 z2 : ℤ_[p]), ((z1 + z2 : ℤ_[p]) : ℚ_[p]) = z1 + z2 | ⟨_, _⟩ ⟨_, _⟩ := rfl @[simp, norm_cast] lemma coe_mul : ∀ (z1 z2 : ℤ_[p]), ((z1 * z2 : ℤ_[p]) : ℚ_[p]) = z1 * z2 | ⟨_, _⟩ ⟨_, _⟩ := rfl @[simp, norm_cast] lemma coe_neg : ∀ (z1 : ℤ_[p]), ((-z1 : ℤ_[p]) : ℚ_[p]) = -z1 | ⟨_, _⟩ := rfl @[simp, norm_cast] lemma coe_sub : ∀ (z1 z2 : ℤ_[p]), ((z1 - z2 : ℤ_[p]) : ℚ_[p]) = z1 - z2 | ⟨_, _⟩ ⟨_, _⟩ := rfl @[simp, norm_cast] lemma coe_one : ((1 : ℤ_[p]) : ℚ_[p]) = 1 := rfl @[simp, norm_cast] lemma coe_coe : ∀ n : ℕ, ((n : ℤ_[p]) : ℚ_[p]) = n | 0 := rfl | (k+1) := by simp [coe_coe] @[simp, norm_cast] lemma coe_coe_int : ∀ (z : ℤ), ((z : ℤ_[p]) : ℚ_[p]) = z | (int.of_nat n) := by simp | -[1+n] := by simp @[simp, norm_cast] lemma coe_zero : ((0 : ℤ_[p]) : ℚ_[p]) = 0 := rfl instance : ring ℤ_[p] := begin refine { add := (+), mul := (*), neg := has_neg.neg, zero := 0, one := 1, sub := has_sub.sub, sub_eq_add_neg := _, .. }; intros; ext; simp; ring end /-- The coercion from ℤ[p] to ℚ[p] as a ring homomorphism. -/ def coe.ring_hom : ℤ_[p] →+* ℚ_[p] := { to_fun := (coe : ℤ_[p] → ℚ_[p]), map_zero' := rfl, map_one' := rfl, map_mul' := coe_mul, map_add' := coe_add } @[simp, norm_cast] lemma coe_pow (x : ℤ_[p]) (n : ℕ) : (↑(x^n) : ℚ_[p]) = (↑x : ℚ_[p])^n := coe.ring_hom.map_pow x n @[simp] lemma mk_coe : ∀ (k : ℤ_[p]), (⟨k, k.2⟩ : ℤ_[p]) = k | ⟨_, _⟩ := rfl /-- The inverse of a p-adic integer with norm equal to 1 is also a p-adic integer. Otherwise, the inverse is defined to be 0. -/ def inv : ℤ_[p] → ℤ_[p] | ⟨k, _⟩ := if h : ∥k∥ = 1 then ⟨1/k, by simp [h]⟩ else 0 instance : char_zero ℤ_[p] := { cast_injective := λ m n h, cast_injective $ show (m:ℚ_[p]) = n, by { rw subtype.ext_iff at h, norm_cast at h, exact h } } @[simp, norm_cast] lemma coe_int_eq (z1 z2 : ℤ) : (z1 : ℤ_[p]) = z2 ↔ z1 = z2 := suffices (z1 : ℚ_[p]) = z2 ↔ z1 = z2, from iff.trans (by norm_cast) this, by norm_cast /-- A sequence of integers that is Cauchy with respect to the `p`-adic norm converges to a `p`-adic integer. -/ def of_int_seq (seq : ℕ → ℤ) (h : is_cau_seq (padic_norm p) (λ n, seq n)) : ℤ_[p] := ⟨⟦⟨_, h⟩⟧, show ↑(padic_seq.norm _) ≤ (1 : ℝ), begin rw padic_seq.norm, split_ifs with hne; norm_cast, { exact zero_le_one }, { apply padic_norm.of_int } end ⟩ end padic_int namespace padic_int /-! ### Instances We now show that `ℤ_[p]` is a * complete metric space * normed ring * integral domain -/ variables (p : ℕ) [fact p.prime] instance : metric_space ℤ_[p] := subtype.metric_space instance complete_space : complete_space ℤ_[p] := begin delta padic_int, rw [complete_space_iff_is_complete_range uniform_embedding_subtype_coe, subtype.range_coe_subtype], have : is_complete (closed_ball (0 : ℚ_[p]) 1) := is_closed_ball.is_complete, simpa [closed_ball], end instance : has_norm ℤ_[p] := ⟨λ z, ∥(z : ℚ_[p])∥⟩ variables {p} protected lemma mul_comm : ∀ z1 z2 : ℤ_[p], z1*z2 = z2*z1 | ⟨q1, h1⟩ ⟨q2, h2⟩ := show (⟨q1*q2, _⟩ : ℤ_[p]) = ⟨q2*q1, _⟩, by simp [_root_.mul_comm] protected lemma zero_ne_one : (0 : ℤ_[p]) ≠ 1 := show (⟨(0 : ℚ_[p]), _⟩ : ℤ_[p]) ≠ ⟨(1 : ℚ_[p]), _⟩, from mt subtype.ext_iff_val.1 zero_ne_one protected lemma eq_zero_or_eq_zero_of_mul_eq_zero : ∀ (a b : ℤ_[p]), a * b = 0 → a = 0 ∨ b = 0 | ⟨a, ha⟩ ⟨b, hb⟩ := λ h : (⟨a * b, _⟩ : ℤ_[p]) = ⟨0, _⟩, have a * b = 0, from subtype.ext_iff_val.1 h, (mul_eq_zero.1 this).elim (λ h1, or.inl (by simp [h1]; refl)) (λ h2, or.inr (by simp [h2]; refl)) lemma norm_def {z : ℤ_[p]} : ∥z∥ = ∥(z : ℚ_[p])∥ := rfl variables (p) instance : normed_comm_ring ℤ_[p] := { dist_eq := λ ⟨_, _⟩ ⟨_, _⟩, rfl, norm_mul := λ ⟨_, _⟩ ⟨_, _⟩, norm_mul_le _ _, mul_comm := padic_int.mul_comm } instance : norm_one_class ℤ_[p] := ⟨norm_def.trans norm_one⟩ instance is_absolute_value : is_absolute_value (λ z : ℤ_[p], ∥z∥) := { abv_nonneg := norm_nonneg, abv_eq_zero := λ ⟨_, _⟩, by simp [norm_eq_zero], abv_add := λ ⟨_,_⟩ ⟨_, _⟩, norm_add_le _ _, abv_mul := λ _ _, by simp only [norm_def, padic_norm_e.mul, padic_int.coe_mul]} variables {p} instance : integral_domain ℤ_[p] := { eq_zero_or_eq_zero_of_mul_eq_zero := λ x y, padic_int.eq_zero_or_eq_zero_of_mul_eq_zero x y, exists_pair_ne := ⟨0, 1, padic_int.zero_ne_one⟩, .. padic_int.normed_comm_ring p } end padic_int namespace padic_int /-! ### Norm -/ variables {p : ℕ} [fact p.prime] lemma norm_le_one : ∀ z : ℤ_[p], ∥z∥ ≤ 1 | ⟨_, h⟩ := h @[simp] lemma norm_mul (z1 z2 : ℤ_[p]) : ∥z1 * z2∥ = ∥z1∥ * ∥z2∥ := by simp [norm_def] @[simp] lemma norm_pow (z : ℤ_[p]) : ∀ n : ℕ, ∥z^n∥ = ∥z∥^n | 0 := by simp | (k+1) := show ∥z*z^k∥ = ∥z∥*∥z∥^k, by {rw norm_mul, congr, apply norm_pow} theorem nonarchimedean : ∀ (q r : ℤ_[p]), ∥q + r∥ ≤ max (∥q∥) (∥r∥) | ⟨_, _⟩ ⟨_, _⟩ := padic_norm_e.nonarchimedean _ _ theorem norm_add_eq_max_of_ne : ∀ {q r : ℤ_[p]}, ∥q∥ ≠ ∥r∥ → ∥q+r∥ = max (∥q∥) (∥r∥) | ⟨_, _⟩ ⟨_, _⟩ := padic_norm_e.add_eq_max_of_ne lemma norm_eq_of_norm_add_lt_right {z1 z2 : ℤ_[p]} (h : ∥z1 + z2∥ < ∥z2∥) : ∥z1∥ = ∥z2∥ := by_contradiction $ λ hne, not_lt_of_ge (by rw norm_add_eq_max_of_ne hne; apply le_max_right) h lemma norm_eq_of_norm_add_lt_left {z1 z2 : ℤ_[p]} (h : ∥z1 + z2∥ < ∥z1∥) : ∥z1∥ = ∥z2∥ := by_contradiction $ λ hne, not_lt_of_ge (by rw norm_add_eq_max_of_ne hne; apply le_max_left) h @[simp] lemma padic_norm_e_of_padic_int (z : ℤ_[p]) : ∥(↑z : ℚ_[p])∥ = ∥z∥ := by simp [norm_def] lemma norm_int_cast_eq_padic_norm (z : ℤ) : ∥(z : ℤ_[p])∥ = ∥(z : ℚ_[p])∥ := by simp [norm_def] @[simp] lemma norm_eq_padic_norm {q : ℚ_[p]} (hq : ∥q∥ ≤ 1) : @norm ℤ_[p] _ ⟨q, hq⟩ = ∥q∥ := rfl @[simp] lemma norm_p : ∥(p : ℤ_[p])∥ = p⁻¹ := show ∥((p : ℤ_[p]) : ℚ_[p])∥ = p⁻¹, by exact_mod_cast padic_norm_e.norm_p @[simp] lemma norm_p_pow (n : ℕ) : ∥(p : ℤ_[p])^n∥ = p^(-n:ℤ) := show ∥((p^n : ℤ_[p]) : ℚ_[p])∥ = p^(-n:ℤ), by { convert padic_norm_e.norm_p_pow n, simp, } private def cau_seq_to_rat_cau_seq (f : cau_seq ℤ_[p] norm) : cau_seq ℚ_[p] (λ a, ∥a∥) := ⟨ λ n, f n, λ _ hε, by simpa [norm, norm_def] using f.cauchy hε ⟩ variables (p) instance complete : cau_seq.is_complete ℤ_[p] norm := ⟨ λ f, have hqn : ∥cau_seq.lim (cau_seq_to_rat_cau_seq f)∥ ≤ 1, from padic_norm_e_lim_le zero_lt_one (λ _, norm_le_one _), ⟨ ⟨_, hqn⟩, λ ε, by simpa [norm, norm_def] using cau_seq.equiv_lim (cau_seq_to_rat_cau_seq f) ε⟩⟩ end padic_int namespace padic_int variables (p : ℕ) [hp_prime : fact p.prime] include hp_prime lemma exists_pow_neg_lt {ε : ℝ} (hε : 0 < ε) : ∃ (k : ℕ), ↑p ^ -((k : ℕ) : ℤ) < ε := begin obtain ⟨k, hk⟩ := exists_nat_gt ε⁻¹, use k, rw ← inv_lt_inv hε (_root_.fpow_pos_of_pos _ _), { rw [fpow_neg, inv_inv', fpow_coe_nat], apply lt_of_lt_of_le hk, norm_cast, apply le_of_lt, convert nat.lt_pow_self _ _ using 1, exact hp_prime.1.one_lt }, { exact_mod_cast hp_prime.1.pos } end lemma exists_pow_neg_lt_rat {ε : ℚ} (hε : 0 < ε) : ∃ (k : ℕ), ↑p ^ -((k : ℕ) : ℤ) < ε := begin obtain ⟨k, hk⟩ := @exists_pow_neg_lt p _ ε (by exact_mod_cast hε), use k, rw (show (p : ℝ) = (p : ℚ), by simp) at hk, exact_mod_cast hk end variable {p} lemma norm_int_lt_one_iff_dvd (k : ℤ) : ∥(k : ℤ_[p])∥ < 1 ↔ ↑p ∣ k := suffices ∥(k : ℚ_[p])∥ < 1 ↔ ↑p ∣ k, by rwa norm_int_cast_eq_padic_norm, padic_norm_e.norm_int_lt_one_iff_dvd k lemma norm_int_le_pow_iff_dvd {k : ℤ} {n : ℕ} : ∥(k : ℤ_[p])∥ ≤ ((↑p)^(-n : ℤ)) ↔ ↑p^n ∣ k := suffices ∥(k : ℚ_[p])∥ ≤ ((↑p)^(-n : ℤ)) ↔ ↑(p^n) ∣ k, by simpa [norm_int_cast_eq_padic_norm], padic_norm_e.norm_int_le_pow_iff_dvd _ _ /-! ### Valuation on `ℤ_[p]` -/ /-- `padic_int.valuation` lifts the p-adic valuation on `ℚ` to `ℤ_[p]`. -/ def valuation (x : ℤ_[p]) := padic.valuation (x : ℚ_[p]) lemma norm_eq_pow_val {x : ℤ_[p]} (hx : x ≠ 0) : ∥x∥ = p^(-x.valuation) := begin convert padic.norm_eq_pow_val _, contrapose! hx, exact subtype.val_injective hx end @[simp] lemma valuation_zero : valuation (0 : ℤ_[p]) = 0 := padic.valuation_zero @[simp] lemma valuation_one : valuation (1 : ℤ_[p]) = 0 := padic.valuation_one @[simp] lemma valuation_p : valuation (p : ℤ_[p]) = 1 := by simp [valuation, -cast_eq_of_rat_of_nat] lemma valuation_nonneg (x : ℤ_[p]) : 0 ≤ x.valuation := begin by_cases hx : x = 0, { simp [hx] }, have h : (1 : ℝ) < p := by exact_mod_cast hp_prime.1.one_lt, rw [← neg_nonpos, ← (fpow_strict_mono h).le_iff_le], show (p : ℝ) ^ -valuation x ≤ p ^ 0, rw [← norm_eq_pow_val hx], simpa using x.property, end @[simp] lemma valuation_p_pow_mul (n : ℕ) (c : ℤ_[p]) (hc : c ≠ 0) : (↑p ^ n * c).valuation = n + c.valuation := begin have : ∥↑p ^ n * c∥ = ∥(p ^ n : ℤ_[p])∥ * ∥c∥, { exact norm_mul _ _ }, have aux : ↑p ^ n * c ≠ 0, { contrapose! hc, rw mul_eq_zero at hc, cases hc, { refine (hp_prime.1.ne_zero _).elim, exact_mod_cast (pow_eq_zero hc) }, { exact hc } }, rwa [norm_eq_pow_val aux, norm_p_pow, norm_eq_pow_val hc, ← fpow_add, ← neg_add, fpow_inj, neg_inj] at this, { exact_mod_cast hp_prime.1.pos }, { exact_mod_cast hp_prime.1.ne_one }, { exact_mod_cast hp_prime.1.ne_zero }, end section units /-! ### Units of `ℤ_[p]` -/ local attribute [reducible] padic_int lemma mul_inv : ∀ {z : ℤ_[p]}, ∥z∥ = 1 → z * z.inv = 1 | ⟨k, _⟩ h := begin have hk : k ≠ 0, from λ h', @zero_ne_one ℚ_[p] _ _ (by simpa [h'] using h), unfold padic_int.inv, split_ifs, { change (⟨k * (1/k), _⟩ : ℤ_[p]) = 1, simp [hk], refl }, { apply subtype.ext_iff_val.2, simp [mul_inv_cancel hk] } end lemma inv_mul {z : ℤ_[p]} (hz : ∥z∥ = 1) : z.inv * z = 1 := by rw [mul_comm, mul_inv hz] lemma is_unit_iff {z : ℤ_[p]} : is_unit z ↔ ∥z∥ = 1 := ⟨λ h, begin rcases is_unit_iff_dvd_one.1 h with ⟨w, eq⟩, refine le_antisymm (norm_le_one _) _, have := mul_le_mul_of_nonneg_left (norm_le_one w) (norm_nonneg z), rwa [mul_one, ← norm_mul, ← eq, norm_one] at this end, λ h, ⟨⟨z, z.inv, mul_inv h, inv_mul h⟩, rfl⟩⟩ lemma norm_lt_one_add {z1 z2 : ℤ_[p]} (hz1 : ∥z1∥ < 1) (hz2 : ∥z2∥ < 1) : ∥z1 + z2∥ < 1 := lt_of_le_of_lt (nonarchimedean _ _) (max_lt hz1 hz2) lemma norm_lt_one_mul {z1 z2 : ℤ_[p]} (hz2 : ∥z2∥ < 1) : ∥z1 * z2∥ < 1 := calc ∥z1 * z2∥ = ∥z1∥ * ∥z2∥ : by simp ... < 1 : mul_lt_one_of_nonneg_of_lt_one_right (norm_le_one _) (norm_nonneg _) hz2 @[simp] lemma mem_nonunits {z : ℤ_[p]} : z ∈ nonunits ℤ_[p] ↔ ∥z∥ < 1 := by rw lt_iff_le_and_ne; simp [norm_le_one z, nonunits, is_unit_iff] /-- A `p`-adic number `u` with `∥u∥ = 1` is a unit of `ℤ_[p]`. -/ def mk_units {u : ℚ_[p]} (h : ∥u∥ = 1) : units ℤ_[p] := let z : ℤ_[p] := ⟨u, le_of_eq h⟩ in ⟨z, z.inv, mul_inv h, inv_mul h⟩ @[simp] lemma mk_units_eq {u : ℚ_[p]} (h : ∥u∥ = 1) : ((mk_units h : ℤ_[p]) : ℚ_[p]) = u := rfl @[simp] lemma norm_units (u : units ℤ_[p]) : ∥(u : ℤ_[p])∥ = 1 := is_unit_iff.mp $ by simp /-- `unit_coeff hx` is the unit `u` in the unique representation `x = u * p ^ n`. See `unit_coeff_spec`. -/ def unit_coeff {x : ℤ_[p]} (hx : x ≠ 0) : units ℤ_[p] := let u : ℚ_[p] := x*p^(-x.valuation) in have hu : ∥u∥ = 1, by simp [hx, nat.fpow_ne_zero_of_pos (by exact_mod_cast hp_prime.1.pos) x.valuation, norm_eq_pow_val, fpow_neg, inv_mul_cancel, -cast_eq_of_rat_of_nat], mk_units hu @[simp] lemma unit_coeff_coe {x : ℤ_[p]} (hx : x ≠ 0) : (unit_coeff hx : ℚ_[p]) = x * p ^ (-x.valuation) := rfl lemma unit_coeff_spec {x : ℤ_[p]} (hx : x ≠ 0) : x = (unit_coeff hx : ℤ_[p]) * p ^ int.nat_abs (valuation x) := begin apply subtype.coe_injective, push_cast, have repr : (x : ℚ_[p]) = (unit_coeff hx) * p ^ x.valuation, { rw [unit_coeff_coe, mul_assoc, ← fpow_add], { simp }, { exact_mod_cast hp_prime.1.ne_zero } }, convert repr using 2, rw [← fpow_coe_nat, int.nat_abs_of_nonneg (valuation_nonneg x)], end end units section norm_le_iff /-! ### Various characterizations of open unit balls -/ lemma norm_le_pow_iff_le_valuation (x : ℤ_[p]) (hx : x ≠ 0) (n : ℕ) : ∥x∥ ≤ p ^ (-n : ℤ) ↔ ↑n ≤ x.valuation := begin rw norm_eq_pow_val hx, lift x.valuation to ℕ using x.valuation_nonneg with k hk, simp only [int.coe_nat_le, fpow_neg, fpow_coe_nat], have aux : ∀ n : ℕ, 0 < (p ^ n : ℝ), { apply pow_pos, exact_mod_cast hp_prime.1.pos }, rw [inv_le_inv (aux _) (aux _)], have : p ^ n ≤ p ^ k ↔ n ≤ k := (pow_right_strict_mono hp_prime.1.two_le).le_iff_le, rw [← this], norm_cast, end lemma mem_span_pow_iff_le_valuation (x : ℤ_[p]) (hx : x ≠ 0) (n : ℕ) : x ∈ (ideal.span {p ^ n} : ideal ℤ_[p]) ↔ ↑n ≤ x.valuation := begin rw [ideal.mem_span_singleton], split, { rintro ⟨c, rfl⟩, suffices : c ≠ 0, { rw [valuation_p_pow_mul _ _ this, le_add_iff_nonneg_right], apply valuation_nonneg, }, contrapose! hx, rw [hx, mul_zero], }, { rw [unit_coeff_spec hx] { occs := occurrences.pos [2] }, lift x.valuation to ℕ using x.valuation_nonneg with k hk, simp only [int.nat_abs_of_nat, units.is_unit, is_unit.dvd_mul_left, int.coe_nat_le], intro H, obtain ⟨k, rfl⟩ := nat.exists_eq_add_of_le H, simp only [pow_add, dvd_mul_right], } end lemma norm_le_pow_iff_mem_span_pow (x : ℤ_[p]) (n : ℕ) : ∥x∥ ≤ p ^ (-n : ℤ) ↔ x ∈ (ideal.span {p ^ n} : ideal ℤ_[p]) := begin by_cases hx : x = 0, { subst hx, simp only [norm_zero, fpow_neg, fpow_coe_nat, inv_nonneg, iff_true, submodule.zero_mem], exact_mod_cast nat.zero_le _ }, rw [norm_le_pow_iff_le_valuation x hx, mem_span_pow_iff_le_valuation x hx], end lemma norm_le_pow_iff_norm_lt_pow_add_one (x : ℤ_[p]) (n : ℤ) : ∥x∥ ≤ p ^ n ↔ ∥x∥ < p ^ (n + 1) := begin have aux : ∀ n : ℤ, 0 < (p ^ n : ℝ), { apply nat.fpow_pos_of_pos, exact hp_prime.1.pos }, by_cases hx0 : x = 0, { simp [hx0, norm_zero, aux, le_of_lt (aux _)], }, rw norm_eq_pow_val hx0, have h1p : 1 < (p : ℝ), { exact_mod_cast hp_prime.1.one_lt }, have H := fpow_strict_mono h1p, rw [H.le_iff_le, H.lt_iff_lt, int.lt_add_one_iff], end lemma norm_lt_pow_iff_norm_le_pow_sub_one (x : ℤ_[p]) (n : ℤ) : ∥x∥ < p ^ n ↔ ∥x∥ ≤ p ^ (n - 1) := by rw [norm_le_pow_iff_norm_lt_pow_add_one, sub_add_cancel] lemma norm_lt_one_iff_dvd (x : ℤ_[p]) : ∥x∥ < 1 ↔ ↑p ∣ x := begin have := norm_le_pow_iff_mem_span_pow x 1, rw [ideal.mem_span_singleton, pow_one] at this, rw [← this, norm_le_pow_iff_norm_lt_pow_add_one], simp only [fpow_zero, int.coe_nat_zero, int.coe_nat_succ, add_left_neg, zero_add], end @[simp] lemma pow_p_dvd_int_iff (n : ℕ) (a : ℤ) : (p ^ n : ℤ_[p]) ∣ a ↔ ↑p ^ n ∣ a := by rw [← norm_int_le_pow_iff_dvd, norm_le_pow_iff_mem_span_pow, ideal.mem_span_singleton] end norm_le_iff section dvr /-! ### Discrete valuation ring -/ instance : local_ring ℤ_[p] := local_of_nonunits_ideal zero_ne_one $ λ x y, by simp; exact norm_lt_one_add lemma p_nonnunit : (p : ℤ_[p]) ∈ nonunits ℤ_[p] := have (p : ℝ)⁻¹ < 1, from inv_lt_one $ by exact_mod_cast hp_prime.1.one_lt, by simp [this] lemma maximal_ideal_eq_span_p : maximal_ideal ℤ_[p] = ideal.span {p} := begin apply le_antisymm, { intros x hx, rw ideal.mem_span_singleton, simp only [local_ring.mem_maximal_ideal, mem_nonunits] at hx, rwa ← norm_lt_one_iff_dvd, }, { rw [ideal.span_le, set.singleton_subset_iff], exact p_nonnunit } end lemma prime_p : prime (p : ℤ_[p]) := begin rw [← ideal.span_singleton_prime, ← maximal_ideal_eq_span_p], { apply_instance }, { exact_mod_cast hp_prime.1.ne_zero } end lemma irreducible_p : irreducible (p : ℤ_[p]) := irreducible_of_prime prime_p instance : discrete_valuation_ring ℤ_[p] := discrete_valuation_ring.of_has_unit_mul_pow_irreducible_factorization ⟨p, irreducible_p, λ x hx, ⟨x.valuation.nat_abs, unit_coeff hx, by rw [mul_comm, ← unit_coeff_spec hx]⟩⟩ lemma ideal_eq_span_pow_p {s : ideal ℤ_[p]} (hs : s ≠ ⊥) : ∃ n : ℕ, s = ideal.span {p ^ n} := discrete_valuation_ring.ideal_eq_span_pow_irreducible hs irreducible_p end dvr end padic_int
871045ba10c9881bd95aaff32d6f782f908a8f59
6b2a480f27775cba4f3ae191b1c1387a29de586e
/group_rep1/homothetic.lean
356355aff2e0401bf754bb5f1fe027404edb3458
[]
no_license
Or7ando/group_representation
a681de2e19d1930a1e1be573d6735a2f0b8356cb
9b576984f17764ebf26c8caa2a542d248f1b50d2
refs/heads/master
1,662,413,107,324
1,590,302,389,000
1,590,302,389,000
258,130,829
0
1
null
null
null
null
UTF-8
Lean
false
false
1,225
lean
import .group_representation import .morphism import ring_theory.algebra open algebra open linear_map universe variables u v w variables {G : Type u}[group G] {R : Type v}[comm_ring R] {M : Type w} [add_comm_group M] [module R M] namespace homothetic variables (ρ : group_representation G R M) open morphism /- Make an R algebra ? subalgebra of sub.type ! To check -/ def add ( f g : ρ ⟶ ρ ) : ρ ⟶ ρ := { ℓ := f.ℓ +g.ℓ, commute := begin intros k, ext,simp, erw commute_apply,erw commute_apply ρ, exact rfl, end } def spectral (t : R)(f : ρ ⟶ ρ) : ρ ⟶ ρ := { ℓ := t • f.ℓ, commute := begin intros g,ext,simp, erw commute_apply, exact rfl, end } instance has_add_morphism : has_add ( ρ ⟶ ρ ) := { add := add ρ } instance has_scalar_morphism: has_scalar R ( ρ ⟶ ρ ) := { smul := spectral ρ } def id := 𝟙 ρ lemma add_ext ( f g : ρ ⟶ ρ ) : (f+g).ℓ = f.ℓ + g.ℓ := rfl lemma one_ext : (𝟙 ρ ).ℓ =linear_map.id :=rfl lemma smul_ext (t : R)(f : ρ ⟶ ρ) : (t • f).ℓ = t • f.ℓ := rfl def test (t : R)(f : ρ ⟶ ρ) := f + t • 𝟙 ρ end homothetic #check mul_sub_left_distrib
bf7b98ec6138500bd140400b42de8124c6ddd9cf
96338d06deb5f54f351493a71d6ecf6c546089a2
/priv/Lean/Cat.lean
5d00ef5518df80d4549c17fdf972000d2f17e71e
[]
no_license
silky/exe
5f9e4eea772d74852a1a2fac57d8d20588282d2b
e81690d6e16f2a83c105cce446011af6ae905b81
refs/heads/master
1,609,385,766,412
1,472,164,223,000
1,472,164,223,000
66,610,224
1
0
null
1,472,178,919,000
1,472,178,919,000
null
UTF-8
Lean
false
false
6,132
lean
/- Cat -/ import Setoid set_option pp.universes true set_option pp.metavar_args false namespace EXE namespace Cat -- carrier of a category: type of morphisms abbreviation HomType (Ob : Type) : Type := Π(Dom Cod : Ob), SetoidType -- structure of a category section withHom variables {Ob : Type} (Hom : HomType Ob) abbreviation IdType : Type := Π{a : Ob}, Hom a a abbreviation MulType : Type := Π{a b c : Ob}, Hom b c ⥤ Hom a b ⥤ Hom a c end withHom -- axioms of category section withIdMul variables {Ob : Type} {Hom : HomType Ob} variables (Id : IdType Hom) (Mul : MulType Hom) abbreviation UnitLProp : Prop := ∀{a b : Ob}, ∀(f : Hom a b), (Mul Id $ f) ≡(Hom a b)≡ f abbreviation UnitRProp : Prop := ∀{a b : Ob}, ∀(f : Hom a b), (Mul f $ Id) ≡(Hom a b)≡ f abbreviation UnitCProp : Prop := ∀{a : Ob}, (Mul Id $ Id) ≡(Hom a a)≡ Id abbreviation UnitLInvProp : Prop := ∀{a b : Ob}, ∀(f : Hom a b), f ≡(Hom a b)≡ (Mul Id $ f) abbreviation UnitRInvProp : Prop := ∀{a b : Ob}, ∀(f : Hom a b), f ≡(Hom a b)≡ (Mul f $ Id) abbreviation UnitCInvProp : Prop := ∀{a : Ob}, Id ≡(Hom a a)≡ (Mul Id $ Id) abbreviation AssocProp : Prop := ∀{a b c d : Ob}, ∀(f : Hom c d), ∀(g : Hom b c), ∀(h : Hom a b), (Mul (Mul f $ g) $ h) ≡(Hom a d)≡ (Mul f $ (Mul g $ h)) abbreviation AssocInvProp : Prop := ∀{a b c d : Ob}, ∀(f : Hom c d), ∀(g : Hom b c), ∀(h : Hom a b), (Mul f $ (Mul g $ h)) ≡(Hom a d)≡ (Mul (Mul f $ g) $ h) end withIdMul end Cat namespace Setoid -- identity in the category `Setoid` definition Id : Cat.IdType HomSet := λ (A : SetoidType), MkHom /- onEl -/ ( λ (a : A), a) /- onEqu -/ ( λ (a1 a2 : A), λ (e12 : a1 ≡_≡ a2), e12) definition Mul : Cat.MulType HomSet := λ(A B C : SetoidType), MkHom2 (B⥤C) (A⥤B) (A⥤C) /- onElEl -/ ( Setoid.Mul.onElEl ) /- onElEqu -/ ( λ(f : B⥤C), λ(g1 g2 : A⥤B), λ(g12 : g1 ≡(A⥤B)≡ g2), λ(a : A), f (g12 a)) /- onEquEl -/ ( λ(f1 f2 : B⥤C), λ(f12 : f1 ≡(B⥤C)≡ f2), λ(g : A⥤B), λ(a : A), f12 (g a)) definition UnitL : Cat.UnitLProp @Id @Mul := λ(A B : SetoidType), λ(f : A⥤B), λ(a : A), ⊜ definition UnitR : Cat.UnitRProp @Id @Mul := λ(A B : SetoidType), λ(f : A⥤B), λ(a : A), ⊜ definition Assoc : Cat.AssocProp @Mul := λ(A B C D : SetoidType), λ(f : C⥤D), λ(g : B⥤C), λ(h : A⥤B), λ(a : A), ⊜ end Setoid -- objects of 2-category `Cat` record CatType : Type := (Ob : Type) (Hom : Cat.HomType Ob) (Id : Cat.IdType Hom) (Mul : Cat.MulType Hom) (UnitL : Cat.UnitLProp @Id @Mul) (UnitR : Cat.UnitRProp @Id @Mul) (Assoc : Cat.AssocProp @Mul) print CatType abbreviation Cat.MkOb := CatType.mk -- carrier of category attribute CatType.Ob [coercion] notation ` ⟦ ` C ` ⟧ ` := CatType.Ob C notation a ` ⇒` C `⇒ ` b := CatType.Hom C a b notation ` ① ` := CatType.Id _ notation f ` ⊙` C `⊙ ` g := CatType.Mul C f $ g abbreviation CatType.UnitC (C : CatType) : Cat.UnitCProp (@CatType.Id C) (@CatType.Mul C) := λ (X : C), CatType.UnitL C (@CatType.Id C X) abbreviation CatType.UnitLInv (C : CatType) : Cat.UnitLInvProp (@CatType.Id C) (@CatType.Mul C) := λ X Y, λ f, SetoidType.Sym _ (CatType.UnitL C f) abbreviation CatType.UnitRInv (C : CatType) : Cat.UnitRInvProp (@CatType.Id C) (@CatType.Mul C) := λ X Y, λ f, SetoidType.Sym _ (CatType.UnitR C f) abbreviation CatType.UnitCInv (C : CatType) : Cat.UnitCInvProp (@CatType.Id C) (@CatType.Mul C) := λ (X : C), SetoidType.Sym _ (@CatType.UnitC C X) abbreviation CatType.AssocInv (C : CatType) : Cat.AssocInvProp (@CatType.Mul C) := λ X Y Z T, λ f g h, SetoidType.Sym _ (CatType.Assoc C f g h) definition CatType.MulHE (C : CatType) {X Y Z : C} (mYZ : Y ⇒C⇒ Z) {mXY1 mXY2 : X ⇒C⇒ Y}(e12 : mXY1 ≡(X ⇒C⇒ Y)≡ mXY2) : (mYZ ⊙C⊙ mXY1) ≡(X ⇒C⇒ Z)≡ (mYZ ⊙C⊙ mXY2) := (CatType.Mul C $ mYZ) $/ e12 definition CatType.MulEH (C : CatType) {X Y Z : C} {mYZ1 mYZ2 : Y ⇒C⇒ Z}(e12 : mYZ1 ≡(Y ⇒C⇒ Z)≡ mYZ2) (mXY : X ⇒C⇒ Y) : (mYZ1 ⊙C⊙ mXY) ≡(X ⇒C⇒ Z)≡ (mYZ2 ⊙C⊙ mXY) := (CatType.Mul C $/ e12) /$ mXY notation f ` ⊙` C `⊙/ ` geq := CatType.MulHE C f geq notation feq ` /⊙` C `⊙ ` g := CatType.MulEH C feq g -- the category of `Setoid`s definition SetoidCat : CatType := Cat.MkOb SetoidType Setoid.HomSet @Setoid.Id @Setoid.Mul @Setoid.UnitL @Setoid.UnitR @Setoid.Assoc namespace Cat definition FromSet (S : SetoidType) : CatType := let Hom (x y : S) : SetoidType := Setoid.FromType (x ≡S≡ y) in Cat.MkOb /- Ob -/ S /- Hom -/ Hom /- Id -/ ( λ (x : S), SetoidType.Refl S) /-Mul -/ ( λ (x y z : S), Setoid.MkHom2 (Hom y z) (Hom x y) (Hom x z) ( λ (yz : y ≡S≡ z), λ (xy : x ≡S≡ y), SetoidType.Trans S xy yz) ( λ yz xy1 xy2 xyE, true.intro) ( λ yz1 yz2 yzE xy, true.intro)) /- UnitL -/ ( λ x y, λ f, true.intro) /- UnitR -/ ( λ x y, λ f, true.intro) /- Assoc -/ ( λ x y z t, λ f g h, true.intro) end Cat namespace CatType record IsoHom (C : CatType) (A B : C) : Type := (AtoB : A ⇒C⇒ B) (BtoA : B ⇒C⇒ A) (atA : (BtoA ⊙C⊙ AtoB) ≡(A ⇒C⇒ A)≡ ①) (atB : (AtoB ⊙C⊙ BtoA) ≡(B ⇒C⇒ B)≡ ①) abbreviation MkIso {C : CatType} {A B : C} := @IsoHom.mk C A B end CatType notation a ` ⇐` C `⇒ ` b := CatType.IsoHom C a b infix ` ⇔ `:10 := CatType.IsoHom SetoidCat end EXE
5b974c2eaa5118e2a28d6c37949bff90dfc4d887
367134ba5a65885e863bdc4507601606690974c1
/src/tactic/interactive_expr.lean
736819318d928a2ced249a04826c78c7390b4725
[ "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
17,482
lean
/- Copyright (c) 2020 E.W.Ayers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: E.W.Ayers -/ /-! # Widgets used for tactic state and term-mode goal display The vscode extension supports the display of interactive widgets. Default implementation of these widgets are included in the core library. We override them here using `vm_override` so that we can change them quickly without waiting for the next Lean release. The function `widget_override.interactive_expression.mk` renders a single expression as a widget component. Each goal in a tactic state is rendered using the `widget_override.tactic_view_goal` function, a complete tactic state is rendered using `widget_override.tactic_view_component`. Lean itself calls the `widget_override.term_goal_widget` function to render term-mode goals and `widget_override.tactic_state_widget` to render the tactic state in a tactic proof. -/ namespace widget_override open widget open tagged_format open widget.html widget.attr namespace interactive_expression meta instance : has_mem expr.coord expr.address := list.has_mem /-- eformat but without any of the formatting stuff like highlighting, groups etc. -/ meta inductive sf : Type | tag_expr : expr.address → expr → sf → sf | compose : sf → sf → sf | of_string : string → sf | highlight : format.color → sf → sf | block : ℕ → sf → sf /-- Prints a debugging representation of an `sf` object. -/ meta def sf.repr : sf → format | (sf.tag_expr addr e a) := format.group $ format.nest 2 $ "(tag_expr " ++ to_fmt addr ++ format.line ++ "`(" ++ to_fmt e ++ ")" ++ format.line ++ a.repr ++ ")" | (sf.compose a b) := a.repr ++ format.line ++ b.repr | (sf.of_string s) := repr s | (sf.block i a) := "(block " ++ to_fmt i ++ format.line ++ a.repr ++ ")" | (sf.highlight c a) := "(highlight " ++ c.to_string ++ a.repr ++ ")" meta instance : has_to_format sf := ⟨sf.repr⟩ meta instance : has_to_string sf := ⟨λ s, s.repr.to_string⟩ meta instance : has_repr sf := ⟨λ s, s.repr.to_string⟩ /-- Constructs an `sf` from an `eformat` by forgetting grouping, nesting, etc. -/ meta def sf.of_eformat : eformat → sf | (tag ⟨ea,e⟩ m) := sf.tag_expr ea e $ sf.of_eformat m | (group m) := sf.block 0 $ sf.of_eformat m | (nest i m) := sf.block i $ sf.of_eformat m | (highlight c m) := sf.highlight c $ sf.of_eformat m | (of_format f) := sf.of_string $ format.to_string f | (compose x y) := sf.compose (sf.of_eformat x) (sf.of_eformat y) /-- Flattens an `sf`, i.e. merges adjacent `of_string` constructors. -/ meta def sf.flatten : sf → sf | (sf.tag_expr ea e m) := (sf.tag_expr ea e $ sf.flatten m) | (sf.compose x y) := match (sf.flatten x), (sf.flatten y) with | (sf.of_string sx), (sf.of_string sy) := sf.of_string (sx ++ sy) | (sf.of_string sx), (sf.compose (sf.of_string sy) z) := sf.compose (sf.of_string (sx ++ sy)) z | (sf.compose x (sf.of_string sy)), (sf.of_string sz) := sf.compose x (sf.of_string (sy ++ sz)) | (sf.compose x (sf.of_string sy1)), (sf.compose (sf.of_string sy2) z) := sf.compose x (sf.compose (sf.of_string (sy1 ++ sy2)) z) | x, y := sf.compose x y end | (sf.of_string s) := -- replace newline by space sf.of_string (s.to_list.map (λ c, if c = '\n' then ' ' else c)).as_string | (sf.block i (sf.block j a)) := (sf.block (i+j) a).flatten | (sf.block i a) := sf.block i a.flatten | (sf.highlight i a) := sf.highlight i a.flatten private meta def elim_part_apps : sf → expr.address → sf | (sf.tag_expr ea e m) acc := if ∀ c ∈ ea, c = expr.coord.app_fn then elim_part_apps m (acc ++ ea) else sf.tag_expr (acc ++ ea) e (elim_part_apps m []) | (sf.compose a b) acc := (elim_part_apps a acc).compose (elim_part_apps b acc) | (sf.of_string s) _ := sf.of_string s | (sf.block i a) acc := sf.block i $ elim_part_apps a acc | (sf.highlight c a) acc := sf.highlight c $ elim_part_apps a acc /-- Post-process an `sf` object to eliminate tags for partial applications by pushing the `app_fn` as far into the expression as possible. The effect is that clicking on a sub-expression always includes the full argument list in the popup. Consider the expression `id id 0`. We push the `app_fn` for the partial application `id id` inwards and eliminate it. Before: ``` (tag_expr [app_fn] `(id.{1} (nat -> nat) (id.{1} nat)) (tag_expr [app_fn] `(id.{1} (nat -> nat)) "id") "\n" (tag_expr [app_arg] `(id.{1} nat) "id")) "\n" (tag_expr [app_arg] `(has_zero.zero.{0} nat nat.has_zero) "0") ``` After: ``` "id" "\n" (tag_expr [app_fn, app_arg] `(id.{1} nat) "id") "\n" (tag_expr [app_arg] `(has_zero.zero.{0} nat nat.has_zero) "0") ``` -/ meta def sf.elim_part_apps (s : sf) : sf := elim_part_apps s [] /-- The actions accepted by an expression widget. -/ meta inductive action (γ : Type) | on_mouse_enter : subexpr → action | on_mouse_leave_all : action | on_click : subexpr → action | on_tooltip_action : γ → action | on_close_tooltip : action | effect : widget.effect → action /-- Render a 'go to definition' button for a given expression. If there is no definition available, then returns an empty list. -/ meta def goto_def_button {γ} : expr → tactic (list (html (action γ))) | e := (do (expr.const n _) ← pure $ expr.get_app_fn e, env ← tactic.get_env, let file := environment.decl_olean env n, pos ← environment.decl_pos env n, pure $ [h "button" [ cn "pointer ba br3 mr1", on_click (λ _, action.effect $ widget.effect.reveal_position file pos), attr.val "title" "go to definition"] ["↪"]] ) <|> pure [] /-- Due to a bug in the webview browser, we have to reduce the number of spans in the expression. To do this, we collect the attributes from `sf.block` and `sf.highlight` after an expression boundary. -/ meta def get_block_attrs {γ}: sf → tactic (sf × list (attr γ)) | (sf.block i a) := do let s : attr (γ) := style [ ("display", "inline-block"), ("padding-left", "1ch"), ("text-indent", "-1ch"), ("white-space", "pre-wrap"), ("vertical-align", "top") ], (a,rest) ← get_block_attrs a, pure (a, s :: rest) | (sf.highlight c a) := do (a, rest) ← get_block_attrs a, pure (a, (cn c.to_string) :: rest) | a := pure (a,[]) /-- Renders a subexpression as a list of html elements. -/ meta def view {γ} (tooltip_component : tc subexpr (action γ)) (click_address : option expr.address) (select_address : option expr.address) : subexpr → sf → tactic (list (html (action γ))) | ⟨ce, current_address⟩ (sf.tag_expr ea e m) := do let new_address := current_address ++ ea, let select_attrs : list (attr (action γ)) := if some new_address = select_address then [className "highlight"] else [], click_attrs : list (attr (action γ)) ← if some new_address = click_address then do content ← tc.to_html tooltip_component (e, new_address), efmt : string ← format.to_string <$> tactic.pp e, gd_btn ← goto_def_button e, pure [tooltip $ h "div" [] [ h "div" [cn "fr"] (gd_btn ++ [ h "button" [cn "pointer ba br3 mr1", on_click (λ _, action.effect $ widget.effect.copy_text efmt), attr.val "title" "copy expression to clipboard"] ["📋"], h "button" [cn "pointer ba br3", on_click (λ _, action.on_close_tooltip), attr.val "title" "close"] ["×"] ]), content ]] else pure [], (m, block_attrs) ← get_block_attrs m, let as := [className "expr-boundary", key (ea)] ++ select_attrs ++ click_attrs ++ block_attrs, inner ← view (e,new_address) m, pure [h "span" as inner] | ca (sf.compose x y) := pure (++) <*> view ca x <*> view ca y | ca (sf.of_string s) := pure [h "span" [ on_mouse_enter (λ _, action.on_mouse_enter ca), on_click (λ _, action.on_click ca), key s ] [html.of_string s]] | ca b@(sf.block _ _) := do (a, attrs) ← get_block_attrs b, inner ← view ca a, pure [h "span" attrs inner] | ca b@(sf.highlight _ _) := do (a, attrs) ← get_block_attrs b, inner ← view ca a, pure [h "span" attrs inner] /-- Make an interactive expression. -/ meta def mk {γ} (tooltip : tc subexpr γ) : tc expr γ := let tooltip_comp := component.with_should_update (λ (x y : tactic_state × expr × expr.address), x.2.2 ≠ y.2.2) $ component.map_action (action.on_tooltip_action) tooltip in component.filter_map_action (λ _ (a : γ ⊕ widget.effect), sum.cases_on a some (λ _, none)) $ component.with_effects (λ _ (a : γ ⊕ widget.effect), match a with | (sum.inl g) := [] | (sum.inr s) := [s] end ) $ tc.mk_simple (action γ) (option subexpr × option subexpr) (λ e, pure $ (none, none)) (λ e ⟨ca, sa⟩ act, pure $ match act with | (action.on_mouse_enter ⟨e, ea⟩) := ((ca, some (e, ea)), none) | (action.on_mouse_leave_all) := ((ca, none), none) | (action.on_click ⟨e, ea⟩) := if some (e,ea) = ca then ((none, sa), none) else ((some (e, ea), sa), none) | (action.on_tooltip_action g) := ((none, sa), some $ sum.inl g) | (action.on_close_tooltip) := ((none, sa), none) | (action.effect e) := ((ca,sa), some $ sum.inr $ e) end ) (λ e ⟨ca, sa⟩, do m ← sf.of_eformat <$> tactic.pp_tagged e, let m := m.elim_part_apps, let m := m.flatten, let m := m.tag_expr [] e, -- [hack] in pp.cpp I forgot to add an expr-boundary for the root expression. v ← view tooltip_comp (prod.snd <$> ca) (prod.snd <$> sa) ⟨e, []⟩ m, pure $ [ h "span" [ className "expr", key e.hash, on_mouse_leave (λ _, action.on_mouse_leave_all) ] $ v ] ) /-- Render the implicit arguments for an expression in fancy, little pills. -/ meta def implicit_arg_list (tooltip : tc subexpr empty) (e : expr) : tactic $ html empty := do fn ← (mk tooltip) $ expr.get_app_fn e, args ← list.mmap (mk tooltip) $ expr.get_app_args e, pure $ h "div" [style [("display", "flex"), ("flexWrap", "wrap"), ("alignItems", "baseline")]] ( (h "span" [className "bg-blue br3 ma1 ph2 white"] [fn]) :: list.map (λ a, h "span" [className "bg-gray br3 ma1 ph2 white"] [a]) args ) /-- Component for the type tooltip. -/ meta def type_tooltip : tc subexpr empty := tc.stateless (λ ⟨e,ea⟩, do y ← tactic.infer_type e, y_comp ← mk type_tooltip y, implicit_args ← implicit_arg_list type_tooltip e, pure [ h "div" [style [ ("minWidth", "8rem"), -- [note]: textIndent is inherited, and we might -- be in an expression here where textIndent is set ("textIndent", "0")] ] [ h "div" [cn "pl1"] [y_comp], h "hr" [] [], implicit_args ] ] ) end interactive_expression /-- Supported tactic state filters. -/ @[derive decidable_eq] meta inductive filter_type | none | no_instances | only_props /-- Filters a local constant using the given filter. -/ meta def filter_local : filter_type → expr → tactic bool | (filter_type.none) e := pure tt | (filter_type.no_instances) e := do t ← tactic.infer_type e, bnot <$> tactic.is_class t | (filter_type.only_props) e := do t ← tactic.infer_type e, tactic.is_prop t /-- Component for the filter dropdown. -/ meta def filter_component : component filter_type filter_type := component.stateless (λ lf, [ h "label" [] ["filter: "], select [ ⟨filter_type.none, "0", ["no filter"]⟩, ⟨filter_type.no_instances, "1", ["no instances"]⟩, ⟨filter_type.only_props, "2", ["only props"]⟩ ] lf ] ) /-- Converts a name into an html element. -/ meta def html.of_name {α : Type} : name → html α | n := html.of_string $ name.to_string n open tactic /-- Component that shows a type. -/ meta def show_type_component : tc expr empty := tc.stateless (λ x, do y ← infer_type x, y_comp ← interactive_expression.mk interactive_expression.type_tooltip $ y, pure y_comp ) /-- A group of local constants in the context that should be rendered as one line. -/ @[derive decidable_eq] meta structure local_collection := (key : string) (locals : list expr) (type : expr) (value : option expr) /-- Converts a single local constant into a (singleton) `local_collection` -/ meta def to_local_collection (l : expr) : tactic local_collection := tactic.unsafe.type_context.run $ do lctx ← tactic.unsafe.type_context.get_local_context, some ldecl ← pure $ lctx.get_local_decl l.local_uniq_name, pure { key := l.local_uniq_name.repr, locals := [l], type := ldecl.type, value := ldecl.value } /-- Groups consecutive local collections by type -/ meta def group_local_collection : list local_collection → list local_collection | (a :: b :: rest) := if a.type = b.type ∧ a.value = b.value then group_local_collection $ { locals := a.locals ++ b.locals, ..a } :: rest else a :: group_local_collection (b :: rest) | ls := ls /-- Component that displays the main (first) goal. -/ meta def tactic_view_goal {γ} (local_c : tc local_collection γ) (target_c : tc expr γ) : tc filter_type γ := tc.stateless $ λ ft, do g@(expr.mvar u_n pp_n y) ← main_goal, t ← get_tag g, let case_tag : list (html γ) := match interactive.case_tag.parse t with | some t := [h "li" [key "_case"] $ [h "span" [cn "goal-case b"] ["case"]] ++ (t.case_names.bind $ λ n, [" ", n])] | none := [] end, lcs ← local_context, lcs ← list.mfilter (filter_local ft) lcs, lcs ← lcs.mmap $ to_local_collection, let lcs := group_local_collection lcs, lchs ← lcs.mmap (λ lc, do lh ← local_c lc, let ns : list (html γ) := lc.locals.map $ λ n, h "span" [cn "goal-hyp b pr2", key n.local_uniq_name] [html.of_name n.local_pp_name], pure $ h "li" [key lc.key] (ns ++ [": ", h "span" [cn "goal-hyp-type", key "type"] [lh]])), t_comp ← target_c g, pure $ h "ul" [key g.hash, className "list pl0 font-code"] $ case_tag ++ lchs ++ [ h "li" [key u_n] [ h "span" [cn "goal-vdash b"] ["⊢ "], t_comp ]] /-- Actions accepted by the `tactic_view_component`. -/ meta inductive tactic_view_action (γ : Type) | out (a:γ): tactic_view_action | filter (f: filter_type): tactic_view_action /-- The "goals accomplished 🎉" HTML widget. This can be overridden using: ```lean meta def my_new_msg {α : Type} : widget.html α := "my message" attribute [vm_override my_new_msg] widget_override.goals_accomplished_message ``` -/ meta def goals_accomplished_message {α} : html α := h "div" [cn "f5"] ["goals accomplished 🎉"] /-- Component that displays all goals, together with the `$n goals` message. -/ meta def tactic_view_component {γ} (local_c : tc local_collection γ) (target_c : tc expr γ) : tc unit γ := tc.mk_simple (tactic_view_action γ) (filter_type) (λ _, pure $ filter_type.none) (λ ⟨⟩ ft a, match a with | (tactic_view_action.out a) := pure (ft, some a) | (tactic_view_action.filter ft) := pure (ft, none) end) (λ ⟨⟩ ft, do gs ← get_goals, hs ← gs.mmap (λ g, do set_goals [g], flip tc.to_html ft $ tactic_view_goal local_c target_c), set_goals gs, let goal_message : html γ := if gs.length = 0 then goals_accomplished_message else if gs.length = 1 then "1 goal" else html.of_string $ to_string gs.length ++ " goals", let goal_message : html γ := h "strong" [cn "goal-goals"] [goal_message], let goals : html γ := h "ul" [className "list pl0"] $ list.map_with_index (λ i x, h "li" [className $ "lh-copy mt2", key i] [x]) $ (goal_message :: hs), pure [ h "div" [className "fr"] [html.of_component ft $ component.map_action tactic_view_action.filter filter_component], html.map_action tactic_view_action.out goals ]) /-- Component that displays the term-mode goal. -/ meta def tactic_view_term_goal {γ} (local_c : tc local_collection γ) (target_c : tc expr γ) : tc unit γ := tc.stateless $ λ _, do goal ← flip tc.to_html (filter_type.none) $ tactic_view_goal local_c target_c, pure [h "ul" [className "list pl0"] [ h "li" [className "lh-copy"] [h "strong" [cn "goal-goals"] ["expected type:"]], h "li" [className "lh-copy"] [goal]]] /-- Component showing a local collection. -/ meta def show_local_collection_component : tc local_collection empty := tc.stateless (λ lc, do (l::_) ← pure lc.locals, c ← show_type_component l, match lc.value with | some v := do v ← interactive_expression.mk interactive_expression.type_tooltip v, pure [c, " := ", v] | none := pure [c] end) /-- Renders the current tactic state. -/ meta def tactic_render : tc unit empty := component.ignore_action $ tactic_view_component show_local_collection_component show_type_component /-- Component showing the current tactic state. -/ meta def tactic_state_widget : component tactic_state empty := tc.to_component tactic_render /-- Widget used to display term-proof goals. -/ meta def term_goal_widget : component tactic_state empty := (tactic_view_term_goal show_local_collection_component show_type_component).to_component end widget_override attribute [vm_override widget_override.term_goal_widget] widget.term_goal_widget attribute [vm_override widget_override.tactic_state_widget] widget.tactic_state_widget
e2a6ca37ea204a594a2a9055cedc4d2526804aea
6772a11d96d69b3f90d6eeaf7f9accddf2a7691d
/natural_transformation.lean
4a9abe7002cbf7f4bd9534c4609ee98f4c36bf0d
[]
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
6,413
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 open tqft.categories open tqft.categories.functor namespace tqft.categories.natural_transformation structure NaturalTransformation { C D : Category } ( F G : Functor C D ) := (components: Π X : C^.Obj, D^.Hom (F X) (G X)) (naturality: ∀ { X Y : C^.Obj } (f : C^.Hom X Y), D^.compose (F^.onMorphisms f) (components Y) = D^.compose (components X) (G^.onMorphisms f)) -- This defines a coercion so we can write `α X` for `components α X`. instance NaturalTransformation_to_components { C D : Category } { F G : Functor C D } : has_coe_to_fun (NaturalTransformation F G) := { F := λ f, Π X : C^.Obj, D^.Hom (F X) (G X), coe := NaturalTransformation.components } -- TODO can we simplify the next proof, by first using: -- attribute [pointwise] funext -- and then a bit of automation? -- We'll want to be able to prove that two natural transformations are equal if they are componentwise equal. @[pointwise] lemma NaturalTransformations_componentwise_equal { C D : Category } { F G : Functor C D } ( α β : NaturalTransformation F G ) ( w : ∀ X : C^.Obj, α X = β X ) : α = β := begin induction α with αc, induction β with βc, have hc : αc = βc, from funext w, by subst hc end @[reducible] definition IdentityNaturalTransformation { C D : Category } (F : Functor C D) : NaturalTransformation F F := { components := λ X, D^.identity (F X), naturality := ♮ } @[reducible] definition vertical_composition_of_NaturalTransformations { C D : Category } { F G H : Functor C D } ( α : NaturalTransformation F G ) ( β : NaturalTransformation G H ) : NaturalTransformation F H := { components := λ X, D^.compose (α X) (β X), naturality := begin blast, /- this proof was written by a sufficient stupid process that I am confident a computer -- could have done it! -/ rewrite D^.associativity, rewrite - β^.naturality, rewrite - D^.associativity, rewrite α^.naturality, rewrite D^.associativity end } open tqft.categories.functor @[reducible] definition horizontal_composition_of_NaturalTransformations { C D E : Category } { F G : Functor C D } { H I : Functor D E } ( α : NaturalTransformation F G ) ( β : NaturalTransformation H I ) : NaturalTransformation (FunctorComposition F H) (FunctorComposition G I) := { components := λ X : C^.Obj, E^.compose (β (F X)) (I^.onMorphisms (α X)), naturality := begin blast, -- This is obscene! What is the state of automation? -- Ideally we could just say: -- some_tactic [ α^.naturality, β^.naturality, E^.associativity, H^.functoriality ] -- which would search for sequences of rewrites along these equations (and their reverses) -- or even just -- some_other_tactic [ α, β, E, H ] -- which would apply some_tactic using all the equations available as fields on these hypotheses, -- or even just -- some_other_tactic -- which would consider all the available hypotheses. rewrite - β^.naturality, rewrite - β^.naturality, rewrite - E^.associativity, rewrite - H^.functoriality, rewrite α^.naturality, rewrite H^.functoriality, rewrite E^.associativity, rewrite E^.associativity, rewrite β^.naturality end } definition whisker_on_left { C D E : Category } ( F : Functor C D ) { G H : Functor D E } ( α : NaturalTransformation G H ) : NaturalTransformation (FunctorComposition F G) (FunctorComposition F H) := horizontal_composition_of_NaturalTransformations (IdentityNaturalTransformation F) α definition whisker_on_right { C D E : Category } { F G : Functor C D } ( α : NaturalTransformation F G ) ( H : Functor D E ) : NaturalTransformation (FunctorComposition F H) (FunctorComposition G H) := horizontal_composition_of_NaturalTransformations α (IdentityNaturalTransformation H) -- To define a natural isomorphism, we'll define the functor category, and ask for an isomorphism there. -- It's then a lemma that each component is an isomorphism, and vice versa. @[reducible] definition FunctorCategory ( C D : Category ) : Category := { Obj := Functor C D, Hom := λ F G, NaturalTransformation F G, identity := λ F, IdentityNaturalTransformation F, compose := @vertical_composition_of_NaturalTransformations C D, left_identity := ♮, right_identity := ♮, associativity := begin blast, rewrite [ D^.associativity ] end } definition NaturalIsomorphism { C D : Category } ( F G : Functor C D ) := Isomorphism (FunctorCategory C D) F G -- It's a pity we need to separately define this coercion. -- Ideally the coercion from Isomorphism along .morphism would just apply here. -- Somehow we want the definition above to be more transparent? instance NaturalIsomorphism_coercion_to_NaturalTransformation { C D : Category } { F G : Functor C D } : has_coe (NaturalIsomorphism F G) (NaturalTransformation F G) := { coe := Isomorphism.morphism } open NaturalTransformation -- Getting this coercion to work is really painful. We shouldn't have to write -- @components C D F G α X -- below, but rather just: -- α X -- or at least -- α^.components X -- lemma components_of_NaturalIsomorphism_are_isomorphisms { C D : Category } { F G : Functor C D } { α : NaturalIsomorphism F G } { X : C^.Obj } : -- Inverse (@components C D F G α X) := -- { -- inverse := α^.inverse^.components X, -- witness_1 := α^.witness_1, -- TODO we need to evaluate both sides of this equation at X. -- witness_2 := sorry -- } end tqft.categories.natural_transformation
73a924dce6b41e7546600c1b37a70ce4066dbd10
64874bd1010548c7f5a6e3e8902efa63baaff785
/hott/init/types/sigma.hlean
316bb4d5eb6760e3c21b55a0c69ee17fe464e209
[ "Apache-2.0" ]
permissive
tjiaqi/lean
4634d729795c164664d10d093f3545287c76628f
d0ce4cf62f4246b0600c07e074d86e51f2195e30
refs/heads/master
1,622,323,796,480
1,422,643,069,000
1,422,643,069,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
606
hlean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Jeremy Avigad, Floris van Doorn -/ prelude import init.num structure sigma {A : Type} (B : A → Type) := mk :: (pr1 : A) (pr2 : B pr1) notation `Σ` binders `,` r:(scoped P, sigma P) := r namespace sigma notation `pr₁` := pr1 notation `pr₂` := pr2 notation `⟨`:max t:(foldr `,` (e r, mk e r)) `⟩`:0 := t --input ⟨ ⟩ as \< \> namespace ops postfix `.1`:(max+1) := pr1 postfix `.2`:(max+1) := pr2 end ops end sigma
b2ae55022ef4194bb61d7e0831f843c7eaea016a
dc253be9829b840f15d96d986e0c13520b085033
/algebra/free_abelian_group.hlean
d86c1584e34295ef3c5c92cce4b7c4bf01431248
[ "Apache-2.0" ]
permissive
cmu-phil/Spectral
4ce68e5c1ef2a812ffda5260e9f09f41b85ae0ea
3b078f5f1de251637decf04bd3fc8aa01930a6b3
refs/heads/master
1,685,119,195,535
1,684,169,772,000
1,684,169,772,000
46,450,197
42
13
null
1,505,516,767,000
1,447,883,921,000
Lean
UTF-8
Lean
false
false
9,415
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, Egbert Rijke Constructions with groups -/ import algebra.group_theory hit.set_quotient types.list types.sum .free_group open eq algebra is_trunc set_quotient relation sigma sigma.ops prod sum list trunc function equiv trunc_index group pointed namespace group variables {G G' : Group} {g g' h h' k : G} {A B : AbGroup} variables (X : Type*) {Y : Type*} [is_set X] [is_set Y] {l l' : list (X ⊎ X)} /- Free Abelian Group on a pointed set -/ namespace free_ab_group inductive fcg_rel : list (X ⊎ X) → list (X ⊎ X) → Type := | rrefl : Πl, fcg_rel l l | cancel1 : Πx, fcg_rel [inl x, inr x] [] | cancel2 : Πx, fcg_rel [inr x, inl x] [] | cancelpt1 : fcg_rel [inl pt] [] | cancelpt2 : fcg_rel [inr pt] [] | rflip : Πx y, fcg_rel [x, y] [y, x] | resp_append : Π{l₁ l₂ l₃ l₄}, fcg_rel l₁ l₂ → fcg_rel l₃ l₄ → fcg_rel (l₁ ++ l₃) (l₂ ++ l₄) | rtrans : Π{l₁ l₂ l₃}, fcg_rel l₁ l₂ → fcg_rel l₂ l₃ → fcg_rel l₁ l₃ open fcg_rel local abbreviation R [reducible] := fcg_rel attribute fcg_rel.rrefl [refl] attribute fcg_rel.rtrans [trans] definition fcg_carrier [reducible] : Type := set_quotient (λx y, ∥R X x y∥) local abbreviation FG := fcg_carrier definition is_reflexive_R : is_reflexive (λx y, ∥R X x y∥) := begin constructor, intro s, apply tr, unfold R end local attribute is_reflexive_R [instance] variable {X} theorem rel_respect_flip (r : R X l l') : R X (map sum.flip l) (map sum.flip l') := begin induction r with l x x x y l₁ l₂ l₃ l₄ r₁ r₂ IH₁ IH₂ l₁ l₂ l₃ r₁ r₂ IH₁ IH₂, { reflexivity}, { repeat esimp [map], exact cancel2 x}, { repeat esimp [map], exact cancel1 x}, { exact cancelpt2 X }, { exact cancelpt1 X }, { repeat esimp [map], apply fcg_rel.rflip}, { rewrite [+map_append], exact resp_append IH₁ IH₂}, { exact rtrans IH₁ IH₂} end theorem rel_respect_reverse (r : R X l l') : R X (reverse l) (reverse l') := begin induction r with l x x x y l₁ l₂ l₃ l₄ r₁ r₂ IH₁ IH₂ l₁ l₂ l₃ r₁ r₂ IH₁ IH₂, { reflexivity}, { repeat esimp [map], exact cancel2 x}, { repeat esimp [map], exact cancel1 x}, { exact cancelpt1 X }, { exact cancelpt2 X }, { repeat esimp [map], apply fcg_rel.rflip}, { rewrite [+reverse_append], exact resp_append IH₂ IH₁}, { exact rtrans IH₁ IH₂} end theorem rel_cons_concat (l s) : R X (s :: l) (concat s l) := begin induction l with t l IH, { reflexivity}, { rewrite [concat_cons], transitivity (t :: s :: l), { exact resp_append !rflip !rrefl}, { exact resp_append (rrefl [t]) IH}} end definition fcg_one [constructor] : FG X := class_of [] definition fcg_inv [unfold 3] : FG X → FG X := quotient_unary_map (reverse ∘ map sum.flip) (λl l', trunc_functor -1 (rel_respect_reverse ∘ rel_respect_flip)) definition fcg_mul [unfold 3 4] : FG X → FG X → FG X := quotient_binary_map append (λl l', trunc.elim (λr m m', trunc.elim (λs, tr (resp_append r s)))) section local notation 1 := fcg_one local postfix ⁻¹ := fcg_inv local infix * := fcg_mul theorem fcg_mul_assoc (g₁ g₂ g₃ : FG X) : g₁ * g₂ * g₃ = g₁ * (g₂ * g₃) := begin refine set_quotient.rec_prop _ g₁, refine set_quotient.rec_prop _ g₂, refine set_quotient.rec_prop _ g₃, clear g₁ g₂ g₃, intro g₁ g₂ g₃, exact ap class_of !append.assoc end theorem fcg_one_mul (g : FG X) : 1 * g = g := begin refine set_quotient.rec_prop _ g, clear g, intro g, exact ap class_of !append_nil_left end theorem fcg_mul_one (g : FG X) : g * 1 = g := begin refine set_quotient.rec_prop _ g, clear g, intro g, exact ap class_of !append_nil_right end theorem fcg_mul_left_inv (g : FG X) : g⁻¹ * g = 1 := begin refine set_quotient.rec_prop _ g, clear g, intro g, apply eq_of_rel, apply tr, induction g with s l IH, { reflexivity}, { rewrite [▸*, map_cons, reverse_cons, concat_append], refine rtrans _ IH, apply resp_append, reflexivity, change R X ([flip s, s] ++ l) ([] ++ l), apply resp_append, induction s, apply cancel2, apply cancel1, reflexivity} end theorem fcg_mul_comm (g h : FG X) : g * h = h * g := begin refine set_quotient.rec_prop _ g, clear g, intro g, refine set_quotient.rec_prop _ h, clear h, intro h, apply eq_of_rel, apply tr, revert h, induction g with s l IH: intro h, { rewrite [append_nil_left, append_nil_right]}, { rewrite [append_cons,-concat_append], transitivity concat s (l ++ h), apply rel_cons_concat, rewrite [-append_concat], apply IH} end end end free_ab_group open free_ab_group variables (X) definition group_free_ab_group [constructor] : ab_group (fcg_carrier X) := ab_group.mk _ fcg_mul fcg_mul_assoc fcg_one fcg_one_mul fcg_mul_one fcg_inv fcg_mul_left_inv fcg_mul_comm definition free_ab_group [constructor] : AbGroup := AbGroup.mk _ (group_free_ab_group X) /- The universal property of the free commutative group -/ variables {X A} definition free_ab_group_inclusion [constructor] : X →* free_ab_group X := ppi.mk (λ x, class_of [inl x]) (eq_of_rel (tr (fcg_rel.cancelpt1 X))) theorem fgh_helper_respect_fcg_rel (f : X →* A) (r : fcg_rel X l l') : Π(g : A), foldl (fgh_helper f) g l = foldl (fgh_helper f) g l' := begin induction r with l x x x y l₁ l₂ l₃ l₄ r₁ r₂ IH₁ IH₂ l₁ l₂ l₃ r₁ r₂ IH₁ IH₂: intro g, { reflexivity}, { unfold [foldl], apply mul_inv_cancel_right}, { unfold [foldl], apply inv_mul_cancel_right}, { unfold [foldl], rewrite (respect_pt f), apply mul_one }, { unfold [foldl], rewrite [respect_pt f, one_inv], apply mul_one }, { unfold [foldl, fgh_helper], apply mul.right_comm}, { rewrite [+foldl_append, IH₁, IH₂]}, { exact !IH₁ ⬝ !IH₂} end definition free_ab_group_elim [constructor] (f : X →* A) : free_ab_group X →g A := begin fapply homomorphism.mk, { intro g, refine set_quotient.elim _ _ g, { intro l, exact foldl (fgh_helper f) 1 l}, { intro l l' r, esimp at *, refine trunc.rec _ r, clear r, intro r, exact fgh_helper_respect_fcg_rel f r 1}}, { refine set_quotient.rec_prop _, intro l, refine set_quotient.rec_prop _, intro l', esimp, refine !foldl_append ⬝ _, esimp, apply fgh_helper_mul} end definition fn_of_free_ab_group_elim [unfold_full] (φ : free_ab_group X →g A) : X →* A := ppi.mk (φ ∘ free_ab_group_inclusion) begin refine (_ ⬝ @respect_one _ _ _ _ φ (homomorphism.p φ)), apply ap φ, apply eq_of_rel, apply tr, exact (fcg_rel.cancelpt1 X) end definition free_ab_group_elim_unique [constructor] (f : X →* A) (k : free_ab_group X →g A) (H : k ∘ free_ab_group_inclusion ~ f) : k ~ free_ab_group_elim f := begin refine set_quotient.rec_prop _, intro l, esimp, induction l with s l IH, { esimp [foldl], exact to_respect_one k}, { rewrite [foldl_cons, fgh_helper_mul], refine to_respect_mul k (class_of [s]) (class_of l) ⬝ _, rewrite [IH], apply ap (λx, x * _), induction s: rewrite [▸*, one_mul, -H a], apply to_respect_inv } end variables (X A) definition free_ab_group_elim_equiv_fn [constructor] : (free_ab_group X →g A) ≃ (X →* A) := begin fapply equiv.MK, { exact fn_of_free_ab_group_elim}, { exact free_ab_group_elim}, { intro f, apply eq_of_phomotopy, fapply phomotopy.mk, { intro x, esimp, unfold [foldl], apply one_mul }, { apply is_prop.elim } }, { intro k, symmetry, apply homomorphism_eq, apply free_ab_group_elim_unique, reflexivity } end definition free_ab_group_functor (f : X →* Y) : free_ab_group X →g free_ab_group Y := free_ab_group_elim (free_ab_group_inclusion ∘* f) -- set_option pp.all true -- definition free_ab_group.rec {P : free_ab_group X → Type} [H : Πg, is_prop (P g)] -- (h₁ : Πx, P (free_ab_group_inclusion x)) -- (h₂ : P 0) -- (h₃ : Πg h, P g → P h → P (g * h)) -- (h₄ : Πg, P g → P g⁻¹) : -- Πg, P g := -- begin -- refine @set_quotient.rec_prop _ _ _ H _, -- refine @set_quotient.rec_prop _ _ _ (λx, !H) _, -- esimp, intro l, induction l with s l ih, -- exact h₂, -- induction s with v v, -- induction v with i y, -- exact h₃ _ _ (h₁ i y) ih, -- induction v with i y, -- refine h₃ (gqg_map _ _ (class_of [inr ⟨i, y⟩])) _ _ ih, -- refine transport P _ (h₁ i y⁻¹), -- refine _ ⬝ !mul_one, -- refine _ ⬝ ap (mul _) (to_respect_one (dirsum_incl i)), -- apply gqg_eq_of_rel', -- apply tr, esimp, -- refine transport dirsum_rel _ (dirsum_rel.rmk i y⁻¹ y), -- rewrite [mul.left_inv, mul.assoc], -- apply ap (mul _), -- refine _ ⬝ (mul_inv (class_of [inr ⟨i, y⟩]) (ι ⟨i, 1⟩))⁻¹ᵖ, -- refine ap011 mul _ _, -- end end group
7b041e9b8ef3e095ad8cb5084f8600392b98601d
36c7a18fd72e5b57229bd8ba36493daf536a19ce
/tests/lean/run/blast1.lean
103f0f8daa5bda9b7aa75dae2bddb79dfb5d053a
[ "Apache-2.0" ]
permissive
YHVHvx/lean
732bf0fb7a298cd7fe0f15d82f8e248c11db49e9
038369533e0136dd395dc252084d3c1853accbf2
refs/heads/master
1,610,701,080,210
1,449,128,595,000
1,449,128,595,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
55
lean
example (a b : Prop) (Ha : a) (Hb : b) : a := by blast
d394e83e7c53724a093044622d450e50e3df328a
e61a235b8468b03aee0120bf26ec615c045005d2
/src/Init/Lean/Elab/SyntheticMVars.lean
bb1fccdc4985cd8123aa6e92eb15a613e55b0363
[ "Apache-2.0" ]
permissive
SCKelemen/lean4
140dc63a80539f7c61c8e43e1c174d8500ec3230
e10507e6615ddbef73d67b0b6c7f1e4cecdd82bc
refs/heads/master
1,660,973,595,917
1,590,278,033,000
1,590,278,033,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
12,303
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Sebastian Ullrich -/ prelude import Init.Lean.Elab.Term import Init.Lean.Elab.Tactic.Basic namespace Lean namespace Elab namespace Term open Tactic (TacticM evalTactic getUnsolvedGoals) def liftTacticElabM {α} (ref : Syntax) (mvarId : MVarId) (x : TacticM α) : TermElabM α := withMVarContext mvarId $ fun ctx s => let savedSyntheticMVars := s.syntheticMVars; match x { ctx with ref := ref, main := mvarId } { s with goals := [mvarId], syntheticMVars := [] } with | EStateM.Result.error ex newS => EStateM.Result.error (Term.Exception.ex ex) { newS.toTermState with syntheticMVars := savedSyntheticMVars } | EStateM.Result.ok a newS => EStateM.Result.ok a { newS.toTermState with syntheticMVars := savedSyntheticMVars } def ensureAssignmentHasNoMVars (ref : Syntax) (mvarId : MVarId) : TermElabM Unit := do val ← instantiateMVars ref (mkMVar mvarId); when val.hasExprMVar $ throwError ref ("tactic failed, result still contain metavariables" ++ indentExpr val) def runTactic (ref : Syntax) (mvarId : MVarId) (tacticCode : Syntax) : TermElabM Unit := do modify $ fun s => { s with mctx := s.mctx.instantiateMVarDeclMVars mvarId }; remainingGoals ← liftTacticElabM ref mvarId $ do { evalTactic tacticCode; getUnsolvedGoals }; let tailRef := ref.getTailWithPos.getD ref; unless remainingGoals.isEmpty (reportUnsolvedGoals tailRef remainingGoals); ensureAssignmentHasNoMVars tailRef mvarId /-- Auxiliary function used to implement `synthesizeSyntheticMVars`. -/ private def resumeElabTerm (stx : Syntax) (expectedType? : Option Expr) (errToSorry := true) : TermElabM Expr := -- Remark: if `ctx.errToSorry` is already false, then we don't enable it. Recall tactics disable `errToSorry` adaptReader (fun (ctx : Context) => { ctx with errToSorry := ctx.errToSorry && errToSorry }) $ elabTerm stx expectedType? false /-- Try to elaborate `stx` that was postponed by an elaboration method using `Expection.postpone`. It returns `true` if it succeeded, and `false` otherwise. It is used to implement `synthesizeSyntheticMVars`. -/ private def resumePostponed (macroStack : MacroStack) (stx : Syntax) (mvarId : MVarId) (postponeOnError : Bool) : TermElabM Bool := do withMVarContext mvarId $ do s ← get; catch (adaptReader (fun (ctx : Context) => { ctx with macroStack := macroStack }) $ do mvarDecl ← getMVarDecl mvarId; expectedType ← instantiateMVars stx mvarDecl.type; result ← resumeElabTerm stx expectedType (!postponeOnError); /- We must ensure `result` has the expected type because it is the one expected by the method that postponed stx. That is, the method does not have an opportunity to check whether `result` has the expected type or not. -/ result ← ensureHasType stx expectedType result; assignExprMVar mvarId result; pure true) (fun ex => match ex with | Exception.postpone => do set s; pure false | Exception.ex Elab.Exception.unsupportedSyntax => unreachable! | Exception.ex (Elab.Exception.error msg) => if postponeOnError then do set s; pure false else do logMessage msg; pure true) /-- Similar to `synthesizeInstMVarCore`, but makes sure that `instMVar` local context and instances are used. It also logs any error message produced. -/ private def synthesizePendingInstMVar (ref : Syntax) (instMVar : MVarId) : TermElabM Bool := do withMVarContext instMVar $ catch (synthesizeInstMVarCore ref instMVar) (fun ex => match ex with | Exception.ex (Elab.Exception.error errMsg) => do logMessage errMsg; pure true | _ => unreachable!) /-- Similar to `synthesizePendingInstMVar`, but generates type mismatch error message. -/ private def synthesizePendingCoeInstMVar (ref : Syntax) (instMVar : MVarId) (expectedType : Expr) (eType : Expr) (e : Expr) (f? : Option Expr) : TermElabM Bool := do withMVarContext instMVar $ catch (synthesizeInstMVarCore ref instMVar) (fun ex => match ex with | Exception.ex (Elab.Exception.error errMsg) => throwTypeMismatchError ref expectedType eType e f? errMsg.data | _ => unreachable!) /-- Return `true` iff `mvarId` is assigned to a term whose the head is not a metavariable. We use this method to process `SyntheticMVarKind.withDefault`. -/ private def checkWithDefault (ref : Syntax) (mvarId : MVarId) : TermElabM Bool := do val ← instantiateMVars ref (mkMVar mvarId); pure $ !val.getAppFn.isMVar /-- Try to synthesize the given pending synthetic metavariable. -/ private def synthesizeSyntheticMVar (mvarSyntheticDecl : SyntheticMVarDecl) (postponeOnError : Bool) (runTactics : Bool) : TermElabM Bool := match mvarSyntheticDecl.kind with | SyntheticMVarKind.typeClass => synthesizePendingInstMVar mvarSyntheticDecl.ref mvarSyntheticDecl.mvarId | SyntheticMVarKind.coe expectedType eType e f? => synthesizePendingCoeInstMVar mvarSyntheticDecl.ref mvarSyntheticDecl.mvarId expectedType eType e f? -- NOTE: actual processing at `synthesizeSyntheticMVarsAux` | SyntheticMVarKind.withDefault _ => checkWithDefault mvarSyntheticDecl.ref mvarSyntheticDecl.mvarId | SyntheticMVarKind.postponed macroStack => resumePostponed macroStack mvarSyntheticDecl.ref mvarSyntheticDecl.mvarId postponeOnError | SyntheticMVarKind.tactic tacticCode => if runTactics then do runTactic mvarSyntheticDecl.ref mvarSyntheticDecl.mvarId tacticCode; pure true else pure false /-- Try to synthesize the current list of pending synthetic metavariables. Return `true` if at least one of them was synthesized. -/ private def synthesizeSyntheticMVarsStep (postponeOnError : Bool) (runTactics : Bool) : TermElabM Bool := do ctx ← read; traceAtCmdPos `Elab.resuming $ fun _ => fmt "resuming synthetic metavariables, mayPostpone: " ++ fmt ctx.mayPostpone ++ ", postponeOnError: " ++ toString postponeOnError; s ← get; let syntheticMVars := s.syntheticMVars; let numSyntheticMVars := syntheticMVars.length; -- We reset `syntheticMVars` because new synthetic metavariables may be created by `synthesizeSyntheticMVar`. modify $ fun s => { s with syntheticMVars := [] }; -- Recall that `syntheticMVars` is a list where head is the most recent pending synthetic metavariable. -- We use `filterRevM` instead of `filterM` to make sure we process the synthetic metavariables using the order they were created. -- It would not be incorrect to use `filterM`. remainingSyntheticMVars ← syntheticMVars.filterRevM $ fun mvarDecl => do { trace `Elab.postpone mvarDecl.ref $ fun _ => "resuming ?" ++ mvarDecl.mvarId; succeeded ← synthesizeSyntheticMVar mvarDecl postponeOnError runTactics; trace `Elab.postpone mvarDecl.ref $ fun _ => if succeeded then fmt "succeeded" else fmt "not ready yet"; pure $ !succeeded }; -- Merge new synthetic metavariables with `remainingSyntheticMVars`, i.e., metavariables that still couldn't be synthesized modify $ fun s => { s with syntheticMVars := s.syntheticMVars ++ remainingSyntheticMVars }; pure $ numSyntheticMVars != remainingSyntheticMVars.length /-- Apply default value to any pending synthetic metavariable of kind `SyntheticMVarKind.withDefault` -/ private def synthesizeUsingDefault : TermElabM Bool := do s ← get; let len := s.syntheticMVars.length; newSyntheticMVars ← s.syntheticMVars.filterM $ fun mvarDecl => match mvarDecl.kind with | SyntheticMVarKind.withDefault defaultVal => withMVarContext mvarDecl.mvarId $ do val ← instantiateMVars mvarDecl.ref (mkMVar mvarDecl.mvarId); when val.getAppFn.isMVar $ unlessM (isDefEq mvarDecl.ref val defaultVal) $ throwError mvarDecl.ref "failed to assign default value to metavariable"; -- TODO: better error message pure false | _ => pure true; modify $ fun s => { s with syntheticMVars := newSyntheticMVars }; pure $ newSyntheticMVars.length != len /-- Report an error for each synthetic metavariable that could not be resolved. -/ private def reportStuckSyntheticMVars : TermElabM Unit := do s ← get; s.syntheticMVars.forM $ fun mvarSyntheticDecl => match mvarSyntheticDecl.kind with | SyntheticMVarKind.typeClass => withMVarContext mvarSyntheticDecl.mvarId $ do mvarDecl ← getMVarDecl mvarSyntheticDecl.mvarId; logError mvarSyntheticDecl.ref $ "failed to create type class instance for " ++ indentExpr mvarDecl.type | SyntheticMVarKind.coe expectedType eType e f? => withMVarContext mvarSyntheticDecl.mvarId $ do mvarDecl ← getMVarDecl mvarSyntheticDecl.mvarId; throwTypeMismatchError mvarSyntheticDecl.ref expectedType eType e f? (some ("failed to create type class instance for " ++ indentExpr mvarDecl.type)) | _ => unreachable! -- TODO handle other cases. private def getSomeSynthethicMVarsRef : TermElabM Syntax := do s ← get; match s.syntheticMVars.find? $ fun (mvarDecl : SyntheticMVarDecl) => !mvarDecl.ref.getPos.isNone with | some mvarDecl => pure mvarDecl.ref | none => pure Syntax.missing /-- Main loop for `synthesizeSyntheticMVars. It keeps executing `synthesizeSyntheticMVarsStep` while progress is being made. If `mayPostpone == false`, then it applies default values to `SyntheticMVarKind.withDefault` metavariables that are still unresolved, and then tries to resolve metavariables with `mayPostpone == false`. That is, we force them to produce error messages and/or commit to a "best option". If, after that, we still haven't made progress, we report "stuck" errors. -/ private partial def synthesizeSyntheticMVarsAux (mayPostpone := true) : Unit → TermElabM Unit | _ => do let try (x : TermElabM Bool) (k : TermElabM Unit) : TermElabM Unit := condM x (synthesizeSyntheticMVarsAux ()) k; ref ← getSomeSynthethicMVarsRef; withIncRecDepth ref $ do s ← get; unless s.syntheticMVars.isEmpty $ do try (synthesizeSyntheticMVarsStep false false) $ unless mayPostpone $ do /- Resume pending metavariables with "elaboration postponement" disabled. We postpone elaboration errors in this step by setting `postponeOnError := true`. Example: ``` #check let x := ⟨1, 2⟩; Prod.fst x ``` The term `⟨1, 2⟩` can't be elaborated because the expected type is not know. The `x` at `Prod.fst x` is not elaborated because the type of `x` is not known. When we execute the following step with "elaboration postponement" disabled, the elaborator fails at `⟨1, 2⟩` and postpones it, and succeeds at `x` and learns that its type must be of the form `Prod ?α ?β`. Recall that we postponed `x` at `Prod.fst x` because its type it is not known. We the type of `x` may learn later its type and it may contain implicit and/or auto arguments. By disabling postponement, we are essentially giving up the opportunity of learning `x`s type and assume it does not have implict and/or auto arguments. -/ try (withoutPostponing (synthesizeSyntheticMVarsStep true false)) $ try synthesizeUsingDefault $ try (withoutPostponing (synthesizeSyntheticMVarsStep false false)) $ try (synthesizeSyntheticMVarsStep false true) $ reportStuckSyntheticMVars /-- Try to process pending synthetic metavariables. If `mayPostpone == false`, then `syntheticMVars` is `[]` after executing this method. -/ def synthesizeSyntheticMVars (mayPostpone := true) : TermElabM Unit := synthesizeSyntheticMVarsAux mayPostpone () /-- Elaborate `stx`, and make sure all pending synthetic metavariables created while elaborating `stx` are solved. -/ def elabTermAndSynthesize (stx : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do s ← get; let syntheticMVars := s.syntheticMVars; modify $ fun s => { s with syntheticMVars := [] }; finally (do v ← elabTerm stx expectedType?; synthesizeSyntheticMVars false; instantiateMVars stx v) (modify $ fun s => { s with syntheticMVars := s.syntheticMVars ++ syntheticMVars }) end Term end Elab end Lean
b5061de0f28d0ed627a746c9cadcbac16d987ed9
8f0ea954c1cc4f4cda83826954d6186c68fc9536
/library/data/hf.lean
ccdab5c17b5fc1bd080579548dde07fd103ae738
[ "Apache-2.0" ]
permissive
piyush-kurur/lean
fb3cbd339dfa8c70c49559fbea88ac0d3102b8ca
a8db8bc61a0b00379b3d0be8ecaf0d0858dc82ee
refs/heads/master
1,594,387,140,961
1,457,548,608,000
1,457,909,538,000
53,615,930
0
0
null
1,457,642,939,000
1,457,642,939,000
null
UTF-8
Lean
false
false
25,371
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura Hereditarily finite sets: finite sets whose elements are all hereditarily finite sets. Remark: all definitions compute, however the performace is quite poor since we implement this module using a bijection from (finset nat) to nat, and this bijection is implemeted using the Ackermann coding. -/ import data.nat data.finset.equiv data.list open nat binary open - [notation] finset definition hf := nat namespace hf local attribute hf [reducible] protected definition prio : num := num.succ std.priority.default protected definition is_inhabited [instance] : inhabited hf := nat.is_inhabited protected definition has_decidable_eq [instance] : decidable_eq hf := nat.has_decidable_eq definition of_finset (s : finset hf) : hf := @equiv.to_fun _ _ finset_nat_equiv_nat s definition to_finset (h : hf) : finset hf := @equiv.inv _ _ finset_nat_equiv_nat h definition to_nat (h : hf) : nat := h definition of_nat (n : nat) : hf := n lemma to_finset_of_finset (s : finset hf) : to_finset (of_finset s) = s := @equiv.left_inv _ _ finset_nat_equiv_nat s lemma of_finset_to_finset (s : hf) : of_finset (to_finset s) = s := @equiv.right_inv _ _ finset_nat_equiv_nat s lemma to_finset_inj {s₁ s₂ : hf} : to_finset s₁ = to_finset s₂ → s₁ = s₂ := λ h, function.injective_of_left_inverse of_finset_to_finset h lemma of_finset_inj {s₁ s₂ : finset hf} : of_finset s₁ = of_finset s₂ → s₁ = s₂ := λ h, function.injective_of_left_inverse to_finset_of_finset h /- empty -/ definition empty : hf := of_finset (finset.empty) notation `∅` := hf.empty /- insert -/ definition insert (a s : hf) : hf := of_finset (finset.insert a (to_finset s)) /- mem -/ definition mem (a : hf) (s : hf) : Prop := finset.mem a (to_finset s) infix ∈ := mem notation [priority finset.prio] a ∉ b := ¬ mem a b lemma insert_lt_of_not_mem {a s : hf} : a ∉ s → s < insert a s := begin unfold [insert, of_finset, equiv.to_fun, finset_nat_equiv_nat, mem, to_finset, equiv.inv], intro h, rewrite [finset.to_nat_insert h], rewrite [to_nat_of_nat, -zero_add s at {1}], apply add_lt_add_right, apply pow_pos_of_pos _ dec_trivial end lemma insert_lt_insert_of_not_mem_of_not_mem_of_lt {a s₁ s₂ : hf} : a ∉ s₁ → a ∉ s₂ → s₁ < s₂ → insert a s₁ < insert a s₂ := begin unfold [insert, of_finset, equiv.to_fun, finset_nat_equiv_nat, mem, to_finset, equiv.inv], intro h₁ h₂ h₃, rewrite [finset.to_nat_insert h₁], rewrite [finset.to_nat_insert h₂, *to_nat_of_nat], apply add_lt_add_left h₃ end open decidable protected definition decidable_mem [instance] : ∀ a s, decidable (a ∈ s) := λ a s, finset.decidable_mem a (to_finset s) lemma insert_le (a s : hf) : s ≤ insert a s := by_cases (suppose a ∈ s, by rewrite [↑insert, insert_eq_of_mem this, of_finset_to_finset]) (suppose a ∉ s, le_of_lt (insert_lt_of_not_mem this)) lemma not_mem_empty (a : hf) : a ∉ ∅ := begin unfold [mem, empty], rewrite to_finset_of_finset, apply finset.not_mem_empty end lemma mem_insert (a s : hf) : a ∈ insert a s := begin unfold [mem, insert], rewrite to_finset_of_finset, apply finset.mem_insert end lemma mem_insert_of_mem {a s : hf} (b : hf) : a ∈ s → a ∈ insert b s := begin unfold [mem, insert], intros, rewrite to_finset_of_finset, apply finset.mem_insert_of_mem, assumption end lemma eq_or_mem_of_mem_insert {a b s : hf} : a ∈ insert b s → a = b ∨ a ∈ s := begin unfold [mem, insert], rewrite to_finset_of_finset, intros, apply eq_or_mem_of_mem_insert, assumption end theorem mem_of_mem_insert_of_ne {x a : hf} {s : hf} : x ∈ insert a s → x ≠ a → x ∈ s := begin unfold [mem, insert], rewrite to_finset_of_finset, intros, apply mem_of_mem_insert_of_ne, repeat assumption end protected theorem ext {s₁ s₂ : hf} : (∀ a, a ∈ s₁ ↔ a ∈ s₂) → s₁ = s₂ := assume h, have to_finset s₁ = to_finset s₂, from finset.ext h, have of_finset (to_finset s₁) = of_finset (to_finset s₂), by rewrite this, by rewrite [*of_finset_to_finset at this]; exact this theorem insert_eq_of_mem {a : hf} {s : hf} : a ∈ s → insert a s = s := begin unfold mem, intro h, unfold [mem, insert], rewrite (finset.insert_eq_of_mem h), rewrite of_finset_to_finset end protected theorem induction [recursor 4] {P : hf → Prop} (h₁ : P empty) (h₂ : ∀ (a s : hf), a ∉ s → P s → P (insert a s)) (s : hf) : P s := have P (of_finset (to_finset s)), from @finset.induction _ _ _ h₁ (λ a s nain ih, begin unfold [mem, insert] at h₂, rewrite -(to_finset_of_finset s) at nain, have P (insert a (of_finset s)), by exact h₂ a (of_finset s) nain ih, rewrite [↑insert at this, to_finset_of_finset at this], exact this end) (to_finset s), by rewrite of_finset_to_finset at this; exact this lemma insert_le_insert_of_le {a s₁ s₂ : hf} : a ∈ s₁ ∨ a ∉ s₂ → s₁ ≤ s₂ → insert a s₁ ≤ insert a s₂ := suppose a ∈ s₁ ∨ a ∉ s₂, suppose s₁ ≤ s₂, by_cases (suppose s₁ = s₂, by rewrite this) (suppose s₁ ≠ s₂, have s₁ < s₂, from lt_of_le_of_ne `s₁ ≤ s₂` `s₁ ≠ s₂`, by_cases (suppose a ∈ s₁, by_cases (suppose a ∈ s₂, by rewrite [insert_eq_of_mem `a ∈ s₁`, insert_eq_of_mem `a ∈ s₂`]; assumption) (suppose a ∉ s₂, by rewrite [insert_eq_of_mem `a ∈ s₁`]; exact le.trans `s₁ ≤ s₂` !insert_le)) (suppose a ∉ s₁, by_cases (suppose a ∈ s₂, or.elim `a ∈ s₁ ∨ a ∉ s₂` (by contradiction) (by contradiction)) (suppose a ∉ s₂, le_of_lt (insert_lt_insert_of_not_mem_of_not_mem_of_lt `a ∉ s₁` `a ∉ s₂` `s₁ < s₂`)))) /- union -/ definition union (s₁ s₂ : hf) : hf := of_finset (finset.union (to_finset s₁) (to_finset s₂)) infix [priority hf.prio] ∪ := union theorem mem_union_left {a : hf} {s₁ : hf} (s₂ : hf) : a ∈ s₁ → a ∈ s₁ ∪ s₂ := begin unfold mem, intro h, unfold union, rewrite to_finset_of_finset, apply finset.mem_union_left _ h end theorem mem_union_l {a : hf} {s₁ : hf} {s₂ : hf} : a ∈ s₁ → a ∈ s₁ ∪ s₂ := mem_union_left s₂ theorem mem_union_right {a : hf} {s₂ : hf} (s₁ : hf) : a ∈ s₂ → a ∈ s₁ ∪ s₂ := begin unfold mem, intro h, unfold union, rewrite to_finset_of_finset, apply finset.mem_union_right _ h end theorem mem_union_r {a : hf} {s₂ : hf} {s₁ : hf} : a ∈ s₂ → a ∈ s₁ ∪ s₂ := mem_union_right s₁ theorem mem_or_mem_of_mem_union {a : hf} {s₁ s₂ : hf} : a ∈ s₁ ∪ s₂ → a ∈ s₁ ∨ a ∈ s₂ := begin unfold [mem, union], rewrite to_finset_of_finset, intro h, apply finset.mem_or_mem_of_mem_union h end theorem mem_union_iff {a : hf} (s₁ s₂ : hf) : a ∈ s₁ ∪ s₂ ↔ a ∈ s₁ ∨ a ∈ s₂ := iff.intro (λ h, mem_or_mem_of_mem_union h) (λ d, or.elim d (λ i, mem_union_left _ i) (λ i, mem_union_right _ i)) theorem mem_union_eq {a : hf} (s₁ s₂ : hf) : (a ∈ s₁ ∪ s₂) = (a ∈ s₁ ∨ a ∈ s₂) := propext !mem_union_iff theorem union_comm (s₁ s₂ : hf) : s₁ ∪ s₂ = s₂ ∪ s₁ := hf.ext (λ a, by rewrite [*mem_union_eq]; exact or.comm) theorem union_assoc (s₁ s₂ s₃ : hf) : (s₁ ∪ s₂) ∪ s₃ = s₁ ∪ (s₂ ∪ s₃) := hf.ext (λ a, by rewrite [*mem_union_eq]; exact or.assoc) theorem union_left_comm (s₁ s₂ s₃ : hf) : s₁ ∪ (s₂ ∪ s₃) = s₂ ∪ (s₁ ∪ s₃) := !left_comm union_comm union_assoc s₁ s₂ s₃ theorem union_right_comm (s₁ s₂ s₃ : hf) : (s₁ ∪ s₂) ∪ s₃ = (s₁ ∪ s₃) ∪ s₂ := !right_comm union_comm union_assoc s₁ s₂ s₃ theorem union_self (s : hf) : s ∪ s = s := hf.ext (λ a, iff.intro (λ ain, or.elim (mem_or_mem_of_mem_union ain) (λ i, i) (λ i, i)) (λ i, mem_union_left _ i)) theorem union_empty (s : hf) : s ∪ ∅ = s := hf.ext (λ a, iff.intro (suppose a ∈ s ∪ ∅, or.elim (mem_or_mem_of_mem_union this) (λ i, i) (λ i, absurd i !not_mem_empty)) (suppose a ∈ s, mem_union_left _ this)) theorem empty_union (s : hf) : ∅ ∪ s = s := calc ∅ ∪ s = s ∪ ∅ : union_comm ... = s : union_empty /- inter -/ definition inter (s₁ s₂ : hf) : hf := of_finset (finset.inter (to_finset s₁) (to_finset s₂)) infix [priority hf.prio] ∩ := inter theorem mem_of_mem_inter_left {a : hf} {s₁ s₂ : hf} : a ∈ s₁ ∩ s₂ → a ∈ s₁ := begin unfold mem, unfold inter, rewrite to_finset_of_finset, intro h, apply finset.mem_of_mem_inter_left h end theorem mem_of_mem_inter_right {a : hf} {s₁ s₂ : hf} : a ∈ s₁ ∩ s₂ → a ∈ s₂ := begin unfold mem, unfold inter, rewrite to_finset_of_finset, intro h, apply finset.mem_of_mem_inter_right h end theorem mem_inter {a : hf} {s₁ s₂ : hf} : a ∈ s₁ → a ∈ s₂ → a ∈ s₁ ∩ s₂ := begin unfold mem, intro h₁ h₂, unfold inter, rewrite to_finset_of_finset, apply finset.mem_inter h₁ h₂ end theorem mem_inter_iff (a : hf) (s₁ s₂ : hf) : a ∈ s₁ ∩ s₂ ↔ a ∈ s₁ ∧ a ∈ s₂ := iff.intro (λ h, and.intro (mem_of_mem_inter_left h) (mem_of_mem_inter_right h)) (λ h, mem_inter (and.elim_left h) (and.elim_right h)) theorem mem_inter_eq (a : hf) (s₁ s₂ : hf) : (a ∈ s₁ ∩ s₂) = (a ∈ s₁ ∧ a ∈ s₂) := propext !mem_inter_iff theorem inter_comm (s₁ s₂ : hf) : s₁ ∩ s₂ = s₂ ∩ s₁ := hf.ext (λ a, by rewrite [*mem_inter_eq]; exact and.comm) theorem inter_assoc (s₁ s₂ s₃ : hf) : (s₁ ∩ s₂) ∩ s₃ = s₁ ∩ (s₂ ∩ s₃) := hf.ext (λ a, by rewrite [*mem_inter_eq]; exact and.assoc) theorem inter_left_comm (s₁ s₂ s₃ : hf) : s₁ ∩ (s₂ ∩ s₃) = s₂ ∩ (s₁ ∩ s₃) := !left_comm inter_comm inter_assoc s₁ s₂ s₃ theorem inter_right_comm (s₁ s₂ s₃ : hf) : (s₁ ∩ s₂) ∩ s₃ = (s₁ ∩ s₃) ∩ s₂ := !right_comm inter_comm inter_assoc s₁ s₂ s₃ theorem inter_self (s : hf) : s ∩ s = s := hf.ext (λ a, iff.intro (λ h, mem_of_mem_inter_right h) (λ h, mem_inter h h)) theorem inter_empty (s : hf) : s ∩ ∅ = ∅ := hf.ext (λ a, iff.intro (suppose a ∈ s ∩ ∅, absurd (mem_of_mem_inter_right this) !not_mem_empty) (suppose a ∈ ∅, absurd this !not_mem_empty)) theorem empty_inter (s : hf) : ∅ ∩ s = ∅ := calc ∅ ∩ s = s ∩ ∅ : inter_comm ... = ∅ : inter_empty /- card -/ definition card (s : hf) : nat := finset.card (to_finset s) theorem card_empty : card ∅ = 0 := rfl lemma ne_empty_of_card_eq_succ {s : hf} {n : nat} : card s = succ n → s ≠ ∅ := by intros; substvars; contradiction /- erase -/ definition erase (a : hf) (s : hf) : hf := of_finset (erase a (to_finset s)) theorem not_mem_erase (a : hf) (s : hf) : a ∉ erase a s := begin unfold [mem, erase], rewrite to_finset_of_finset, apply finset.not_mem_erase end theorem card_erase_of_mem {a : hf} {s : hf} : a ∈ s → card (erase a s) = pred (card s) := begin unfold mem, intro h, unfold [erase, card], rewrite to_finset_of_finset, apply finset.card_erase_of_mem h end theorem card_erase_of_not_mem {a : hf} {s : hf} : a ∉ s → card (erase a s) = card s := begin unfold [mem], intro h, unfold [erase, card], rewrite to_finset_of_finset, apply finset.card_erase_of_not_mem h end theorem erase_empty (a : hf) : erase a ∅ = ∅ := rfl theorem ne_of_mem_erase {a b : hf} {s : hf} : b ∈ erase a s → b ≠ a := by intro h beqa; subst b; exact absurd h !not_mem_erase theorem mem_of_mem_erase {a b : hf} {s : hf} : b ∈ erase a s → b ∈ s := begin unfold [erase, mem], rewrite to_finset_of_finset, intro h, apply mem_of_mem_erase h end theorem mem_erase_of_ne_of_mem {a b : hf} {s : hf} : a ≠ b → a ∈ s → a ∈ erase b s := begin intro h₁, unfold mem, intro h₂, unfold erase, rewrite to_finset_of_finset, apply mem_erase_of_ne_of_mem h₁ h₂ end theorem mem_erase_iff (a b : hf) (s : hf) : a ∈ erase b s ↔ a ∈ s ∧ a ≠ b := iff.intro (assume H, and.intro (mem_of_mem_erase H) (ne_of_mem_erase H)) (assume H, mem_erase_of_ne_of_mem (and.right H) (and.left H)) theorem mem_erase_eq (a b : hf) (s : hf) : a ∈ erase b s = (a ∈ s ∧ a ≠ b) := propext !mem_erase_iff theorem erase_insert {a : hf} {s : hf} : a ∉ s → erase a (insert a s) = s := begin unfold [mem, erase, insert], intro h, rewrite [to_finset_of_finset, finset.erase_insert h, of_finset_to_finset] end theorem insert_erase {a : hf} {s : hf} : a ∈ s → insert a (erase a s) = s := begin unfold mem, intro h, unfold [insert, erase], rewrite [to_finset_of_finset, finset.insert_erase h, of_finset_to_finset] end /- subset -/ definition subset (s₁ s₂ : hf) : Prop := finset.subset (to_finset s₁) (to_finset s₂) infix [priority hf.prio] ⊆ := subset theorem empty_subset (s : hf) : ∅ ⊆ s := begin unfold [empty, subset], rewrite to_finset_of_finset, apply finset.empty_subset (to_finset s) end theorem subset.refl (s : hf) : s ⊆ s := begin unfold [subset], apply finset.subset.refl (to_finset s) end theorem subset.trans {s₁ s₂ s₃ : hf} : s₁ ⊆ s₂ → s₂ ⊆ s₃ → s₁ ⊆ s₃ := begin unfold [subset], intro h₁ h₂, apply finset.subset.trans h₁ h₂ end theorem mem_of_subset_of_mem {s₁ s₂ : hf} {a : hf} : s₁ ⊆ s₂ → a ∈ s₁ → a ∈ s₂ := begin unfold [subset, mem], intro h₁ h₂, apply finset.mem_of_subset_of_mem h₁ h₂ end theorem subset.antisymm {s₁ s₂ : hf} : s₁ ⊆ s₂ → s₂ ⊆ s₁ → s₁ = s₂ := begin unfold [subset], intro h₁ h₂, apply to_finset_inj (finset.subset.antisymm h₁ h₂) end -- alternative name theorem eq_of_subset_of_subset {s₁ s₂ : hf} (H₁ : s₁ ⊆ s₂) (H₂ : s₂ ⊆ s₁) : s₁ = s₂ := subset.antisymm H₁ H₂ theorem subset_of_forall {s₁ s₂ : hf} : (∀x, x ∈ s₁ → x ∈ s₂) → s₁ ⊆ s₂ := begin unfold [mem, subset], intro h, apply finset.subset_of_forall h end theorem subset_insert (s : hf) (a : hf) : s ⊆ insert a s := begin unfold [subset, insert], rewrite to_finset_of_finset, apply finset.subset_insert (to_finset s) end theorem eq_empty_of_subset_empty {x : hf} (H : x ⊆ ∅) : x = ∅ := subset.antisymm H (empty_subset x) theorem subset_empty_iff (x : hf) : x ⊆ ∅ ↔ x = ∅ := iff.intro eq_empty_of_subset_empty (take xeq, by rewrite xeq; apply subset.refl ∅) theorem erase_subset_erase (a : hf) {s t : hf} : s ⊆ t → erase a s ⊆ erase a t := begin unfold [subset, erase], intro h, rewrite *to_finset_of_finset, apply finset.erase_subset_erase a h end theorem erase_subset (a : hf) (s : hf) : erase a s ⊆ s := begin unfold [subset, erase], rewrite to_finset_of_finset, apply finset.erase_subset a (to_finset s) end theorem erase_eq_of_not_mem {a : hf} {s : hf} : a ∉ s → erase a s = s := begin unfold [mem, erase], intro h, rewrite [finset.erase_eq_of_not_mem h, of_finset_to_finset] end theorem erase_insert_subset (a : hf) (s : hf) : erase a (insert a s) ⊆ s := begin unfold [erase, insert, subset], rewrite [*to_finset_of_finset], apply finset.erase_insert_subset a (to_finset s) end theorem erase_subset_of_subset_insert {a : hf} {s t : hf} (H : s ⊆ insert a t) : erase a s ⊆ t := hf.subset.trans (!hf.erase_subset_erase H) (erase_insert_subset a t) theorem insert_erase_subset (a : hf) (s : hf) : s ⊆ insert a (erase a s) := decidable.by_cases (assume ains : a ∈ s, by rewrite [!insert_erase ains]; apply subset.refl) (assume nains : a ∉ s, suffices s ⊆ insert a s, by rewrite [erase_eq_of_not_mem nains]; assumption, subset_insert s a) theorem insert_subset_insert (a : hf) {s t : hf} : s ⊆ t → insert a s ⊆ insert a t := begin unfold [subset, insert], intro h, rewrite *to_finset_of_finset, apply finset.insert_subset_insert a h end theorem subset_insert_of_erase_subset {s t : hf} {a : hf} (H : erase a s ⊆ t) : s ⊆ insert a t := subset.trans (insert_erase_subset a s) (!insert_subset_insert H) theorem subset_insert_iff (s t : hf) (a : hf) : s ⊆ insert a t ↔ erase a s ⊆ t := iff.intro !erase_subset_of_subset_insert !subset_insert_of_erase_subset theorem le_of_subset {s₁ s₂ : hf} : s₁ ⊆ s₂ → s₁ ≤ s₂ := begin revert s₂, induction s₁ with a s₁ nain ih, take s₂, suppose ∅ ⊆ s₂, !zero_le, take s₂, suppose insert a s₁ ⊆ s₂, have a ∈ s₂, from mem_of_subset_of_mem this !mem_insert, have a ∉ erase a s₂, from !not_mem_erase, have s₁ ⊆ erase a s₂, from subset_of_forall (take x xin, by_cases (suppose x = a, by subst x; contradiction) (suppose x ≠ a, have x ∈ s₂, from mem_of_subset_of_mem `insert a s₁ ⊆ s₂` (mem_insert_of_mem _ `x ∈ s₁`), mem_erase_of_ne_of_mem `x ≠ a` `x ∈ s₂`)), have s₁ ≤ erase a s₂, from ih _ this, have insert a s₁ ≤ insert a (erase a s₂), from insert_le_insert_of_le (or.inr `a ∉ erase a s₂`) this, by rewrite [insert_erase `a ∈ s₂` at this]; exact this end /- image -/ definition image (f : hf → hf) (s : hf) : hf := of_finset (finset.image f (to_finset s)) theorem image_empty (f : hf → hf) : image f ∅ = ∅ := rfl theorem mem_image_of_mem (f : hf → hf) {s : hf} {a : hf} : a ∈ s → f a ∈ image f s := begin unfold [mem, image], intro h, rewrite to_finset_of_finset, apply finset.mem_image_of_mem f h end theorem mem_image {f : hf → hf} {s : hf} {a : hf} {b : hf} (H1 : a ∈ s) (H2 : f a = b) : b ∈ image f s := eq.subst H2 (mem_image_of_mem f H1) theorem exists_of_mem_image {f : hf → hf} {s : hf} {b : hf} : b ∈ image f s → ∃a, a ∈ s ∧ f a = b := begin unfold [mem, image], rewrite to_finset_of_finset, intro h, apply finset.exists_of_mem_image h end theorem mem_image_iff (f : hf → hf) {s : hf} {y : hf} : y ∈ image f s ↔ ∃x, x ∈ s ∧ f x = y := begin unfold [mem, image], rewrite to_finset_of_finset, apply finset.mem_image_iff end theorem mem_image_eq (f : hf → hf) {s : hf} {y : hf} : y ∈ image f s = ∃x, x ∈ s ∧ f x = y := propext (mem_image_iff f) theorem mem_image_of_mem_image_of_subset {f : hf → hf} {s t : hf} {y : hf} (H1 : y ∈ image f s) (H2 : s ⊆ t) : y ∈ image f t := obtain x `x ∈ s` `f x = y`, from exists_of_mem_image H1, have x ∈ t, from mem_of_subset_of_mem H2 `x ∈ s`, show y ∈ image f t, from mem_image `x ∈ t` `f x = y` theorem image_insert (f : hf → hf) (s : hf) (a : hf) : image f (insert a s) = insert (f a) (image f s) := begin unfold [image, insert], rewrite [*to_finset_of_finset, finset.image_insert] end open function lemma image_comp {f : hf → hf} {g : hf → hf} {s : hf} : image (f∘g) s = image f (image g s) := begin unfold image, rewrite [*to_finset_of_finset, finset.image_comp] end lemma image_subset {a b : hf} (f : hf → hf) : a ⊆ b → image f a ⊆ image f b := begin unfold [subset, image], intro h, rewrite *to_finset_of_finset, apply finset.image_subset f h end theorem image_union (f : hf → hf) (s t : hf) : image f (s ∪ t) = image f s ∪ image f t := begin unfold [image, union], rewrite [*to_finset_of_finset, finset.image_union] end /- powerset -/ definition powerset (s : hf) : hf := of_finset (finset.image of_finset (finset.powerset (to_finset s))) prefix [priority hf.prio] `𝒫`:100 := powerset theorem powerset_empty : 𝒫 ∅ = insert ∅ ∅ := rfl theorem powerset_insert {a : hf} {s : hf} : a ∉ s → 𝒫 (insert a s) = 𝒫 s ∪ image (insert a) (𝒫 s) := begin unfold [mem, powerset, insert, union, image], rewrite [*to_finset_of_finset], intro h, have (λ (x : finset hf), of_finset (finset.insert a x)) = (λ (x : finset hf), of_finset (finset.insert a (to_finset (of_finset x)))), from funext (λ x, by rewrite to_finset_of_finset), rewrite [finset.powerset_insert h, finset.image_union, -*finset.image_comp, ↑comp, this] end theorem mem_powerset_iff_subset (s : hf) : ∀ x : hf, x ∈ 𝒫 s ↔ x ⊆ s := begin intro x, unfold [mem, powerset, subset], rewrite [to_finset_of_finset, finset.mem_image_eq], apply iff.intro, suppose (∃ (w : finset hf), finset.mem w (finset.powerset (to_finset s)) ∧ of_finset w = x), obtain w h₁ h₂, from this, begin subst x, rewrite to_finset_of_finset, exact iff.mp !finset.mem_powerset_iff_subset h₁ end, suppose finset.subset (to_finset x) (to_finset s), have finset.mem (to_finset x) (finset.powerset (to_finset s)), from iff.mpr !finset.mem_powerset_iff_subset this, exists.intro (to_finset x) (and.intro this (of_finset_to_finset x)) end theorem subset_of_mem_powerset {s t : hf} (H : s ∈ 𝒫 t) : s ⊆ t := iff.mp (mem_powerset_iff_subset t s) H theorem mem_powerset_of_subset {s t : hf} (H : s ⊆ t) : s ∈ 𝒫 t := iff.mpr (mem_powerset_iff_subset t s) H theorem empty_mem_powerset (s : hf) : ∅ ∈ 𝒫 s := mem_powerset_of_subset (empty_subset s) /- hf as lists -/ open - [notation] list definition of_list (s : list hf) : hf := @equiv.to_fun _ _ list_nat_equiv_nat s definition to_list (h : hf) : list hf := @equiv.inv _ _ list_nat_equiv_nat h lemma to_list_of_list (s : list hf) : to_list (of_list s) = s := @equiv.left_inv _ _ list_nat_equiv_nat s lemma of_list_to_list (s : hf) : of_list (to_list s) = s := @equiv.right_inv _ _ list_nat_equiv_nat s lemma to_list_inj {s₁ s₂ : hf} : to_list s₁ = to_list s₂ → s₁ = s₂ := λ h, function.injective_of_left_inverse of_list_to_list h lemma of_list_inj {s₁ s₂ : list hf} : of_list s₁ = of_list s₂ → s₁ = s₂ := λ h, function.injective_of_left_inverse to_list_of_list h definition nil : hf := of_list list.nil lemma empty_eq_nil : ∅ = nil := rfl definition cons (a l : hf) : hf := of_list (list.cons a (to_list l)) infixr :: := cons lemma cons_ne_nil (a l : hf) : a::l ≠ nil := by contradiction lemma head_eq_of_cons_eq {h₁ h₂ t₁ t₂ : hf} : (h₁::t₁) = (h₂::t₂) → h₁ = h₂ := begin unfold cons, intro h, apply list.head_eq_of_cons_eq (of_list_inj h) end lemma tail_eq_of_cons_eq {h₁ h₂ t₁ t₂ : hf} : (h₁::t₁) = (h₂::t₂) → t₁ = t₂ := begin unfold cons, intro h, apply to_list_inj (list.tail_eq_of_cons_eq (of_list_inj h)) end lemma cons_inj {a : hf} : injective (cons a) := take l₁ l₂, assume Pe, tail_eq_of_cons_eq Pe /- append -/ definition append (l₁ l₂ : hf) : hf := of_list (list.append (to_list l₁) (to_list l₂)) notation l₁ ++ l₂ := append l₁ l₂ theorem append_nil_left [simp] (t : hf) : nil ++ t = t := begin unfold [nil, append], rewrite [to_list_of_list, list.append_nil_left, of_list_to_list] end theorem append_cons [simp] (x s t : hf) : (x::s) ++ t = x::(s ++ t) := begin unfold [cons, append], rewrite [*to_list_of_list, list.append_cons] end theorem append_nil_right [simp] (t : hf) : t ++ nil = t := begin unfold [nil, append], rewrite [to_list_of_list, list.append_nil_right, of_list_to_list] end theorem append.assoc [simp] (s t u : hf) : s ++ t ++ u = s ++ (t ++ u) := begin unfold append, rewrite [*to_list_of_list, list.append.assoc] end /- length -/ definition length (l : hf) : nat := list.length (to_list l) theorem length_nil [simp] : length nil = 0 := begin unfold [length, nil] end theorem length_cons [simp] (x t : hf) : length (x::t) = length t + 1 := begin unfold [length, cons], rewrite to_list_of_list end theorem length_append [simp] (s t : hf) : length (s ++ t) = length s + length t := begin unfold [length, append], rewrite [to_list_of_list, list.length_append] end theorem eq_nil_of_length_eq_zero {l : hf} : length l = 0 → l = nil := begin unfold [length, nil], intro h, rewrite [-list.eq_nil_of_length_eq_zero h, of_list_to_list] end theorem ne_nil_of_length_eq_succ {l : hf} {n : nat} : length l = succ n → l ≠ nil := begin unfold [length, nil], intro h₁ h₂, subst l, rewrite to_list_of_list at h₁, contradiction end /- head and tail -/ definition head (l : hf) : hf := list.head (to_list l) theorem head_cons [simp] (a l : hf) : head (a::l) = a := begin unfold [head, cons], rewrite to_list_of_list end private lemma to_list_ne_list_nil {s : hf} : s ≠ nil → to_list s ≠ list.nil := begin unfold nil, intro h, suppose to_list s = list.nil, by rewrite [-this at h, of_list_to_list at h]; exact absurd rfl h end theorem head_append [simp] (t : hf) {s : hf} : s ≠ nil → head (s ++ t) = head s := begin unfold [nil, head, append], rewrite to_list_of_list, suppose s ≠ of_list list.nil, by rewrite [list.head_append _ (to_list_ne_list_nil this)] end definition tail (l : hf) : hf := of_list (list.tail (to_list l)) theorem tail_nil [simp] : tail nil = nil := begin unfold [tail, nil] end theorem tail_cons [simp] (a l : hf) : tail (a::l) = l := begin unfold [tail, cons], rewrite [to_list_of_list, list.tail_cons, of_list_to_list] end theorem cons_head_tail {l : hf} : l ≠ nil → (head l)::(tail l) = l := begin unfold [nil, head, tail, cons], suppose l ≠ of_list list.nil, by rewrite [to_list_of_list, list.cons_head_tail (to_list_ne_list_nil this), of_list_to_list] end end hf
a3c2e15544404a58d569e4eb1b74507fe788af47
7cef822f3b952965621309e88eadf618da0c8ae9
/src/category_theory/natural_isomorphism.lean
1a09bed47dd8e334d21ac743ca8281a07dec0f66
[ "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
5,516
lean
/- Copyright (c) 2017 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Tim Baumann, Stephen Morgan, Scott Morrison, Floris van Doorn -/ import category_theory.functor_category import category_theory.isomorphism open category_theory universes v₁ v₂ v₃ v₄ u₁ u₂ u₃ u₄ -- declare the `v`'s first; see `category_theory.category` for an explanation namespace category_theory open nat_trans /-- The application of a natural isomorphism to an object. We put this definition in a different namespace, so that we can use α.app -/ @[simp, reducible] def iso.app {C : Type u₁} [category.{v₁} C] {D : Type u₂} [category.{v₂} D] {F G : C ⥤ D} (α : F ≅ G) (X : C) : F.obj X ≅ G.obj X := { hom := α.hom.app X, inv := α.inv.app X, hom_inv_id' := begin rw [← comp_app, iso.hom_inv_id], refl end, inv_hom_id' := begin rw [← comp_app, iso.inv_hom_id], refl end } namespace nat_iso open category_theory.category category_theory.functor variables {C : Type u₁} [𝒞 : category.{v₁} C] {D : Type u₂} [𝒟 : category.{v₂} D] {E : Type u₃} [ℰ : category.{v₃} E] include 𝒞 𝒟 @[simp] lemma trans_app {F G H : C ⥤ D} (α : F ≅ G) (β : G ≅ H) (X : C) : (α ≪≫ β).app X = α.app X ≪≫ β.app X := rfl @[simp] lemma app_hom {F G : C ⥤ D} (α : F ≅ G) (X : C) : (α.app X).hom = α.hom.app X := rfl @[simp] lemma app_inv {F G : C ⥤ D} (α : F ≅ G) (X : C) : (α.app X).inv = α.inv.app X := rfl @[simp] lemma hom_inv_id_app {F G : C ⥤ D} (α : F ≅ G) (X : C) : α.hom.app X ≫ α.inv.app X = 𝟙 (F.obj X) := congr_fun (congr_arg app α.hom_inv_id) X @[simp] lemma inv_hom_id_app {F G : C ⥤ D} (α : F ≅ G) (X : C) : α.inv.app X ≫ α.hom.app X = 𝟙 (G.obj X) := congr_fun (congr_arg app α.inv_hom_id) X variables {F G : C ⥤ D} instance hom_app_is_iso (α : F ≅ G) (X : C) : is_iso (α.hom.app X) := { inv := α.inv.app X, hom_inv_id' := begin rw [←comp_app, iso.hom_inv_id, ←id_app] end, inv_hom_id' := begin rw [←comp_app, iso.inv_hom_id, ←id_app] end } instance inv_app_is_iso (α : F ≅ G) (X : C) : is_iso (α.inv.app X) := { inv := α.hom.app X, hom_inv_id' := begin rw [←comp_app, iso.inv_hom_id, ←id_app] end, inv_hom_id' := begin rw [←comp_app, iso.hom_inv_id, ←id_app] end } @[simp] lemma hom_app_inv_app_id (α : F ≅ G) (X : C) : α.hom.app X ≫ α.inv.app X = 𝟙 _ := begin rw ←comp_app, simp, end @[simp] lemma inv_app_hom_app_id (α : F ≅ G) (X : C) : α.inv.app X ≫ α.hom.app X = 𝟙 _ := begin rw ←comp_app, simp, end variables {X Y : C} @[simp] 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 @[simp] lemma naturality_2 (α : F ≅ G) (f : X ⟶ Y) : (α.hom.app X) ≫ (G.map f) ≫ (α.inv.app Y) = F.map f := begin erw [naturality, ←category.assoc, is_iso.hom_inv_id, category.id_comp] end def is_iso_of_is_iso_app (α : F ⟶ G) [∀ X : C, is_iso (α.app X)] : is_iso α := { inv := { app := λ X, inv (α.app X), naturality' := λ X Y f, begin have h := congr_arg (λ f, inv (α.app X) ≫ (f ≫ inv (α.app Y))) (α.naturality f).symm, simp only [is_iso.inv_hom_id_assoc, is_iso.hom_inv_id, assoc, comp_id, cancel_mono] at h, exact h end } } instance is_iso_of_is_iso_app' (α : F ⟶ G) [H : ∀ X : C, is_iso (nat_trans.app α X)] : is_iso α := @nat_iso.is_iso_of_is_iso_app _ _ _ _ _ _ α H -- TODO can we make this an instance? def is_iso_app_of_is_iso (α : F ⟶ G) [is_iso α] (X) : is_iso (α.app X) := { inv := (inv α).app X, hom_inv_id' := congr_fun (congr_arg nat_trans.app (is_iso.hom_inv_id α)) X, inv_hom_id' := congr_fun (congr_arg nat_trans.app (is_iso.inv_hom_id α)) X } def of_components (app : ∀ X : C, (F.obj X) ≅ (G.obj X)) (naturality : ∀ {X Y : C} (f : X ⟶ Y), (F.map f) ≫ ((app Y).hom) = ((app X).hom) ≫ (G.map f)) : F ≅ G := as_iso { app := λ X, (app X).hom } @[simp] lemma of_components.app (app' : ∀ X : C, (F.obj X) ≅ (G.obj X)) (naturality) (X) : (of_components app' naturality).app X = app' X := by tidy @[simp] lemma of_components.hom_app (app : ∀ X : C, (F.obj X) ≅ (G.obj X)) (naturality) (X) : (of_components app naturality).hom.app X = (app X).hom := rfl @[simp] lemma of_components.inv_app (app : ∀ X : C, (F.obj X) ≅ (G.obj X)) (naturality) (X) : (of_components app naturality).inv.app X = (app X).inv := rfl include ℰ def hcomp {F G : C ⥤ D} {H I : D ⥤ E} (α : F ≅ G) (β : H ≅ I) : F ⋙ H ≅ G ⋙ I := begin refine ⟨α.hom ◫ β.hom, α.inv ◫ β.inv, _, _⟩, { ext, rw [←nat_trans.exchange], simp, refl }, ext, rw [←nat_trans.exchange], simp, refl end omit ℰ -- declare local notation for nat_iso.hcomp localized "infix ` ■ `:80 := category_theory.nat_iso.hcomp" in category end nat_iso namespace functor variables {C : Type u₁} [𝒞 : category.{v₁} C] include 𝒞 def ulift_down_up : ulift_down.{v₁} C ⋙ ulift_up C ≅ 𝟭 (ulift.{u₂} C) := { hom := { app := λ X, @category_struct.id (ulift.{u₂} C) _ X }, inv := { app := λ X, @category_struct.id (ulift.{u₂} C) _ X } } def ulift_up_down : ulift_up.{v₁} C ⋙ ulift_down C ≅ 𝟭 C := { hom := { app := λ X, 𝟙 X }, inv := { app := λ X, 𝟙 X } } end functor end category_theory
18b6cd12e6f235a27200ee910e1cca52e870d7e0
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/library/init/string.lean
b9b536a7327222eabd7506925d0c86313091e7f5
[ "Apache-2.0" ]
permissive
soonhokong/lean-osx
4a954262c780e404c1369d6c06516161d07fcb40
3670278342d2f4faa49d95b46d86642d7875b47c
refs/heads/master
1,611,410,334,552
1,474,425,686,000
1,474,425,686,000
12,043,103
5
1
null
null
null
null
UTF-8
Lean
false
false
1,288
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ prelude import init.char init.list attribute [reducible] definition string := list char namespace string attribute [pattern] definition empty : string := list.nil attribute [pattern] definition str : char → string → string := list.cons definition concat (a b : string) : string := list.append b a end string attribute [instance] definition string.has_append : has_append string := ⟨string.concat⟩ open list private definition utf8_length_aux : nat → nat → string → nat | 0 r (c::s) := let n := char.to_nat c in if n < 0x80 then utf8_length_aux 0 (r+1) s else if 0xC0 ≤ n ∧ n < 0xE0 then utf8_length_aux 1 (r+1) s else if 0xE0 ≤ n ∧ n < 0xF0 then utf8_length_aux 2 (r+1) s else if 0xF0 ≤ n ∧ n < 0xF8 then utf8_length_aux 3 (r+1) s else if 0xF8 ≤ n ∧ n < 0xFC then utf8_length_aux 4 (r+1) s else if 0xFC ≤ n ∧ n < 0xFE then utf8_length_aux 5 (r+1) s else utf8_length_aux 0 (r+1) s | (n+1) r (c::s) := utf8_length_aux n r s | n r [] := r definition utf8_length : string → nat | s := utf8_length_aux 0 0 (reverse s)
ec02164f778f22cd0a721a95b6f8bc48ed189069
75db7e3219bba2fbf41bf5b905f34fcb3c6ca3f2
/hott/types/nat/hott.hlean
bdeaaaee93b45cf5b11ee41c964fd9b3ec05393a
[ "Apache-2.0" ]
permissive
jroesch/lean
30ef0860fa905d35b9ad6f76de1a4f65c9af6871
3de4ec1a6ce9a960feb2a48eeea8b53246fa34f2
refs/heads/master
1,586,090,835,348
1,455,142,203,000
1,455,142,277,000
51,536,958
1
0
null
1,455,215,811,000
1,455,215,811,000
null
UTF-8
Lean
false
false
4,645
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Floris van Doorn Theorems about the natural numbers specific to HoTT -/ import .order open is_trunc unit empty eq equiv algebra namespace nat definition is_hprop_le [instance] (n m : ℕ) : is_hprop (n ≤ m) := begin assert lem : Π{n m : ℕ} (p : n ≤ m) (q : n = m), p = q ▸ le.refl n, { intros, cases p, { assert H' : q = idp, apply is_hset.elim, cases H', reflexivity}, { cases q, exfalso, apply not_succ_le_self a}}, apply is_hprop.mk, intro H1 H2, induction H2, { apply lem}, { cases H1, { exfalso, apply not_succ_le_self a}, { exact ap le.step !v_0}}, end definition is_hprop_lt [instance] (n m : ℕ) : is_hprop (n < m) := !is_hprop_le definition le_equiv_succ_le_succ (n m : ℕ) : (n ≤ m) ≃ (succ n ≤ succ m) := equiv_of_is_hprop succ_le_succ le_of_succ_le_succ definition le_succ_equiv_pred_le (n m : ℕ) : (n ≤ succ m) ≃ (pred n ≤ m) := equiv_of_is_hprop pred_le_pred le_succ_of_pred_le theorem lt_by_cases_lt {a b : ℕ} {P : Type} (H1 : a < b → P) (H2 : a = b → P) (H3 : a > b → P) (H : a < b) : lt.by_cases H1 H2 H3 = H1 H := begin unfold lt.by_cases, induction (lt.trichotomy a b) with H' H', { esimp, exact ap H1 !is_hprop.elim}, { exfalso, cases H' with H' H', apply lt.irrefl, exact H' ▸ H, exact lt.asymm H H'} end theorem lt_by_cases_eq {a b : ℕ} {P : Type} (H1 : a < b → P) (H2 : a = b → P) (H3 : a > b → P) (H : a = b) : lt.by_cases H1 H2 H3 = H2 H := begin unfold lt.by_cases, induction (lt.trichotomy a b) with H' H', { exfalso, apply lt.irrefl, exact H ▸ H'}, { cases H' with H' H', esimp, exact ap H2 !is_hprop.elim, exfalso, apply lt.irrefl, exact H ▸ H'} end theorem lt_by_cases_ge {a b : ℕ} {P : Type} (H1 : a < b → P) (H2 : a = b → P) (H3 : a > b → P) (H : a > b) : lt.by_cases H1 H2 H3 = H3 H := begin unfold lt.by_cases, induction (lt.trichotomy a b) with H' H', { exfalso, exact lt.asymm H H'}, { cases H' with H' H', exfalso, apply lt.irrefl, exact H' ▸ H, esimp, exact ap H3 !is_hprop.elim} end theorem lt_ge_by_cases_lt {n m : ℕ} {P : Type} (H1 : n < m → P) (H2 : n ≥ m → P) (H : n < m) : lt_ge_by_cases H1 H2 = H1 H := by apply lt_by_cases_lt theorem lt_ge_by_cases_ge {n m : ℕ} {P : Type} (H1 : n < m → P) (H2 : n ≥ m → P) (H : n ≥ m) : lt_ge_by_cases H1 H2 = H2 H := begin unfold [lt_ge_by_cases,lt.by_cases], induction (lt.trichotomy n m) with H' H', { exfalso, apply lt.irrefl, exact lt_of_le_of_lt H H'}, { cases H' with H' H'; all_goals (esimp; apply ap H2 !is_hprop.elim)} end theorem lt_ge_by_cases_le {n m : ℕ} {P : Type} {H1 : n ≤ m → P} {H2 : n ≥ m → P} (H : n ≤ m) (Heq : Π(p : n = m), H1 (le_of_eq p) = H2 (le_of_eq p⁻¹)) : lt_ge_by_cases (λH', H1 (le_of_lt H')) H2 = H1 H := begin unfold [lt_ge_by_cases,lt.by_cases], induction (lt.trichotomy n m) with H' H', { esimp, apply ap H1 !is_hprop.elim}, { cases H' with H' H', { esimp, induction H', esimp, symmetry, exact ap H1 !is_hprop.elim ⬝ Heq idp ⬝ ap H2 !is_hprop.elim}, { exfalso, apply lt.irrefl, apply lt_of_le_of_lt H H'}} end protected definition code [reducible] [unfold 1 2] : ℕ → ℕ → Type₀ | code 0 0 := unit | code 0 (succ m) := empty | code (succ n) 0 := empty | code (succ n) (succ m) := code n m protected definition refl : Πn, nat.code n n | refl 0 := star | refl (succ n) := refl n protected definition encode [unfold 3] {n m : ℕ} (p : n = m) : nat.code n m := p ▸ nat.refl n protected definition decode : Π(n m : ℕ), nat.code n m → n = m | decode 0 0 := λc, idp | decode 0 (succ l) := λc, empty.elim c _ | decode (succ k) 0 := λc, empty.elim c _ | decode (succ k) (succ l) := λc, ap succ (decode k l c) definition nat_eq_equiv (n m : ℕ) : (n = m) ≃ nat.code n m := equiv.MK nat.encode !nat.decode begin revert m, induction n, all_goals (intro m;induction m;all_goals intro c), all_goals try contradiction, induction c, reflexivity, xrewrite [↑nat.decode,-tr_compose,v_0], end begin intro p, induction p, esimp, induction n, reflexivity, rewrite [↑nat.decode,↑nat.refl,v_0] end end nat
04cd893bb1ef6a0586e0dc4ba9c5db9ba297cbe4
e07b1aca72e83a272dd59d24c6e0fa246034d774
/src/surreal/ordinal/basic.lean
43f314c4ac84c6eb4c372f5a051b7e03370af7ed
[]
no_license
pedrominicz/learn
637a343bd4f8669d76819ac660a2d2d3e0958710
b79b802a9846c86c21d4b6f3e17af36e7382f0ef
refs/heads/master
1,671,746,990,402
1,670,778,113,000
1,670,778,113,000
265,735,177
1
0
null
null
null
null
UTF-8
Lean
false
false
6,671
lean
import tactic variables {α β : Type} variables {rα : α → α → Prop} {rβ : β → β → Prop} theorem no_infinite_descending_chain_of_wf (H : well_founded rα) : ¬ ∃ f : ℕ → α, ∀ n : ℕ, rα (f n.succ) (f n) := begin rintro ⟨f, hf⟩, cases H.min_mem _ (set.range_nonempty f) with n hn, apply H.not_lt_min, { show f _ ∈ set.range f, simp }, { rw ←hn, exact hf n } end namespace wf_of_no_infinite_descending_chain noncomputable def not_acc_aux {a : α} (ha : ¬ acc rα a) : Σ' b, rα b a ∧ ¬ acc rα b := begin suffices : ∃ b, rα b a ∧ ¬ acc rα b, { exact ⟨classical.some this, classical.some_spec this⟩ }, by_contra h, push_neg at h, exact ha ⟨_, h⟩ end noncomputable def f {a : α} (ha : ¬ acc rα a) : ℕ → Σ' b, ¬ acc rα b := λ n, nat.rec ⟨a, ha⟩ (λ n a, ⟨(not_acc_aux a.snd).fst, (not_acc_aux a.snd).snd.right⟩) n theorem _root_.wf_of_no_infinite_descending_chain : (¬ ∃ f : ℕ → α, ∀ n : ℕ, rα (f n.succ) (f n)) → well_founded rα := begin by_contra h, simp only [not_forall, exists_prop] at h, cases h with h' h, apply h', clear h', have : ¬ ∀ a, acc rα a := h ∘ well_founded.intro, clear h, rename this h, push_neg at h, cases h with a ha, exact ⟨λ n, (f ha n).fst, λ n, (not_acc_aux (f ha n).snd).snd.left⟩ end end wf_of_no_infinite_descending_chain def f {A : set α} (h : Π a : α, a ∈ A → Σ' b : α, b ∈ A ∧ rα b a) {a : α} (ha : a ∈ A) : ℕ → Σ' b, b ∈ A := λ n, nat.rec ⟨a, ha⟩ (λ n a, ⟨(h a.fst a.snd).fst, (h a.fst a.snd).snd.left⟩) n example (H : well_founded rα) {A : set α} : (Π a : α, a ∈ A → Σ' b : α, b ∈ A ∧ rα b a) → A = ∅ := begin intro h, ext a, simp only [set.mem_empty_eq, iff_false], intro ha, apply no_infinite_descending_chain_of_wf H, use λ n, (f h ha n).fst, intro n, suffices : (f h ha n).fst ∈ A ∧ rα (f h ha n.succ).fst (f h ha n).fst, { exact this.right }, induction n with n ih, { exact ⟨ha, (h a ha).snd.right⟩ }, { cases ih with ih₁ ih₂, let b := (h (f h ha n).fst ih₁).fst, let hb : b ∈ A := (h (f h ha n).fst ih₁).snd.left, exact ⟨hb, (h b hb).snd.right⟩ } end theorem set_without_min_eq_empty_of_wf (H : well_founded rα) {A : set α} : (∀ a ∈ A, ∃ b ∈ A, rα b a) → A = ∅ := begin intro h, ext a, rw [set.mem_empty_eq, iff_false], intro ha, rcases h _ (H.min_mem _ _) with ⟨b, hb, hb'⟩, exact H.not_lt_min _ (set.nonempty_of_mem ha) hb hb' end theorem wf_of_set_without_min_eq_empty : (∀ A : set α, (∀ a ∈ A, ∃ b ∈ A, rα b a) → A = ∅) → well_founded rα := begin by_contra h, simp only [exists_prop, not_forall] at h, have := mt (@wf_of_no_infinite_descending_chain _ rα), push_neg at this, cases h with h₁ h₂, specialize this h₂, clear h₂, cases this with f hf, let A := set.range f, suffices : ∀ a, a ∈ A → ∃ b, b ∈ A ∧ rα b a, { specialize h₁ A this, finish }, clear h₁, intros a ha, have : ∃ n, f n = a, { finish }, rcases this with ⟨n, rfl⟩, use f n.succ, finish end example [iα : is_trichotomous α rα] (Hβ : well_founded rβ) {eq : α ≃ β} (h : ∀ a₁ a₂ : α, rα a₁ a₂ → rβ (eq a₁) (eq a₂)) : ∀ b₁ b₂ : β, rβ b₁ b₂ → rα (eq.symm b₁) (eq.symm b₂) := begin intros b₁ b₂ hb, cases eq with to_fun inv_fun left_inv right_inv, change ∀ a, inv_fun (to_fun a) = a at left_inv, change ∀ b, to_fun (inv_fun b) = b at right_inv, change ∀ a₁ a₂, rα a₁ a₂ → rβ (to_fun a₁) (to_fun a₂) at h, change rα (inv_fun b₁) (inv_fun b₂), unfreezingI { rcases iα with ⟨iα⟩ }, rcases iα (inv_fun b₁) (inv_fun b₂) with ha | ha | ha, { assumption }, { exfalso, suffices : b₁ = b₂, { subst this, rename b₁ b, exact (Hβ.is_irrefl.irrefl : ∀ _, ¬ _) b hb }, rw [←right_inv b₁, ha, right_inv] }, { exfalso, specialize h _ _ ha, rw [right_inv, right_inv] at h, apply Hβ.not_gt_of_lt h hb } end inductive ordinal : Type 1 | mk {α : Type} (lt : α → α → Prop) [is_well_order α lt] : ordinal namespace ordinal def equiv : ordinal → ordinal → Prop := begin rintros ⟨α, ltα, iα⟩ ⟨β, ltβ, iβ⟩, exact ∃ eq : α ≃ β, ∀ a₁ a₂ : α, ltα a₁ a₂ ↔ ltβ (eq a₁) (eq a₂) end theorem equiv.refl (α : ordinal) : equiv α α := begin cases α with α ltα iα, use equiv.refl α, simp end theorem equiv.rfl : ∀ {α : ordinal}, equiv α α := equiv.refl theorem equiv.symm {α β : ordinal} : equiv α β → equiv β α := begin cases α with α ltα iα, cases β with β ltβ iβ, rintro ⟨⟨to_fun, inv_fun, left_inv, right_inv⟩, h⟩, change ∀ a, inv_fun (to_fun a) = a at left_inv, change ∀ b, to_fun (inv_fun b) = b at right_inv, change ∀ a₁ a₂, ltα a₁ a₂ ↔ ltβ (to_fun a₁) (to_fun a₂) at h, use ⟨inv_fun, to_fun, right_inv, left_inv⟩, clear iα iβ, change ∀ b₁ b₂, ltβ b₁ b₂ ↔ ltα (inv_fun b₁) (inv_fun b₂), intros b₁ b₂, specialize h (inv_fun b₁) (inv_fun b₂), rw [right_inv, right_inv] at h, symmetry, assumption end theorem equiv.trans {α β γ : ordinal} (h₁ : equiv α β) (h₂ : equiv β γ) : equiv α γ := begin cases α with α ltα iα, cases β with β ltβ iβ, cases γ with γ ltγ iγ, rcases h₁ with ⟨⟨to_fun₁, inv_fun₁, left_inv₁, right_inv₁⟩, h₁⟩, change ∀ a, inv_fun₁ (to_fun₁ a) = a at left_inv₁, change ∀ b, to_fun₁ (inv_fun₁ b) = b at right_inv₁, change ∀ a₁ a₂, ltα a₁ a₂ ↔ ltβ (to_fun₁ a₁) (to_fun₁ a₂) at h₁, rcases h₂ with ⟨⟨to_fun₂, inv_fun₂, left_inv₂, right_inv₂⟩, h₂⟩, change ∀ b, inv_fun₂ (to_fun₂ b) = b at left_inv₂, change ∀ c, to_fun₂ (inv_fun₂ c) = c at right_inv₂, change ∀ b₁ b₂, ltβ b₁ b₂ ↔ ltγ (to_fun₂ b₁) (to_fun₂ b₂) at h₂, change ∃ _, _, use ⟨ λ a, to_fun₂ (to_fun₁ a), λ c, inv_fun₁ (inv_fun₂ c), function.left_inverse.comp left_inv₂ left_inv₁, function.right_inverse.comp right_inv₂ right_inv₁⟩, intros a₁ a₂, change ltα a₁ a₂ ↔ ltγ (to_fun₂ (to_fun₁ a₁)) (to_fun₂ (to_fun₁ a₂)), transitivity, { exact h₁ a₁ a₂ }, { exact h₂ (to_fun₁ a₁) (to_fun₁ a₂) } end instance : setoid ordinal := ⟨equiv, equiv.refl, @equiv.symm, @equiv.trans⟩ end ordinal def Ordinal : Type 1 := quotient ordinal.setoid
3d32715daf4d10b23d7089c3956766da74369996
ea5678cc400c34ff95b661fa26d15024e27ea8cd
/clear_aux_decl.lean
e24fddedcc1f4d55a82aaeb4275127a2bc07e34f
[]
no_license
ChrisHughes24/leanstuff
dca0b5349c3ed893e8792ffbd98cbcadaff20411
9efa85f72efaccd1d540385952a6acc18fce8687
refs/heads/master
1,654,883,241,759
1,652,873,885,000
1,652,873,885,000
134,599,537
1
0
null
null
null
null
UTF-8
Lean
false
false
699
lean
import tactic.basic tactic open tactic #print tactic.local_context #print expr.is_aux_decl #print tactic.clear #print tactic.interactive.clear namespace tactic.interactive meta def clear_aux_decl_aux : list expr → tactic unit | [] := skip | (e::l) := do cond e.is_aux_decl (tactic.clear e) skip, clear_aux_decl_aux l meta def clear_aux_decl : tactic unit := local_context >>= clear_aux_decl_aux end tactic.interactive meta def h : tactic unit := do l ← local_context, trace (l.filter (λ e : expr, e.is_aux_decl)).length example (x y : ℕ) (h₁ : ∃ n : ℕ, n * 1 = 2) (h₂ : 1 + 1 = 2 → x * 1 = y) : x = y := let ⟨n, hn⟩ := h₁ in begin clear_aux_decl, finish end
0a8965ee4465536f8d2fbb4cf2abfdee4e254762
491068d2ad28831e7dade8d6dff871c3e49d9431
/tests/lean/run/imp2.lean
e097a01063202f709e1ab7b5fa42ce769ae3a8f9
[ "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
98
lean
import data.num check (λ {A : Type.{1}} (a : A), a) 10 check (λ {A} a, a) 10 check (λ a, a) 10
403a92263530627739b06e1350ad307205193c88
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/algebra/char_p/basic.lean
6d2fca8033d2e3254cde77dac1cbcca667ebc010
[]
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
12,277
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Kenny Lau, Joey van Langen, Casper Putz -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.fintype.basic import Mathlib.data.nat.choose.default import Mathlib.data.int.modeq import Mathlib.algebra.module.basic import Mathlib.algebra.iterate_hom import Mathlib.group_theory.order_of_element import Mathlib.algebra.group.type_tags import Mathlib.PostPort universes u l u_1 u_2 v namespace Mathlib /-! # Characteristic of semirings -/ /-- The generator of the kernel of the unique homomorphism ℕ → α for a semiring α -/ class char_p (α : Type u) [semiring α] (p : ℕ) where cast_eq_zero_iff : ∀ (x : ℕ), ↑x = 0 ↔ p ∣ x theorem char_p.cast_eq_zero (α : Type u) [semiring α] (p : ℕ) [char_p α p] : ↑p = 0 := iff.mpr (char_p.cast_eq_zero_iff α p p) (dvd_refl p) @[simp] theorem char_p.cast_card_eq_zero (R : Type u_1) [ring R] [fintype R] : ↑(fintype.card R) = 0 := sorry theorem char_p.int_cast_eq_zero_iff (R : Type u) [ring R] (p : ℕ) [char_p R p] (a : ℤ) : ↑a = 0 ↔ ↑p ∣ a := sorry theorem char_p.int_coe_eq_int_coe_iff (R : Type u_1) [ring R] (p : ℕ) [char_p R p] (a : ℤ) (b : ℤ) : ↑a = ↑b ↔ int.modeq (↑p) a b := sorry theorem char_p.eq (α : Type u) [semiring α] {p : ℕ} {q : ℕ} (c1 : char_p α p) (c2 : char_p α q) : p = q := nat.dvd_antisymm (iff.mp (char_p.cast_eq_zero_iff α p q) (char_p.cast_eq_zero α q)) (iff.mp (char_p.cast_eq_zero_iff α q p) (char_p.cast_eq_zero α p)) protected instance char_p.of_char_zero (α : Type u) [semiring α] [char_zero α] : char_p α 0 := char_p.mk fun (x : ℕ) => eq.mpr (id (Eq._oldrec (Eq.refl (↑x = 0 ↔ 0 ∣ x)) (propext zero_dvd_iff))) (eq.mpr (id (Eq._oldrec (Eq.refl (↑x = 0 ↔ x = 0)) (Eq.symm nat.cast_zero))) (eq.mpr (id (Eq._oldrec (Eq.refl (↑x = ↑0 ↔ x = 0)) (propext nat.cast_inj))) (iff.refl (x = 0)))) theorem char_p.exists (α : Type u) [semiring α] : ∃ (p : ℕ), char_p α p := sorry theorem char_p.exists_unique (α : Type u) [semiring α] : exists_unique fun (p : ℕ) => char_p α p := sorry theorem char_p.congr {R : Type u} [semiring R] {p : ℕ} (q : ℕ) [hq : char_p R q] (h : q = p) : char_p R p := h ▸ hq /-- Noncomputable function that outputs the unique characteristic of a semiring. -/ def ring_char (α : Type u) [semiring α] : ℕ := classical.some (char_p.exists_unique α) namespace ring_char theorem spec (R : Type u) [semiring R] (x : ℕ) : ↑x = 0 ↔ ring_char R ∣ x := sorry theorem eq (R : Type u) [semiring R] {p : ℕ} (C : char_p R p) : p = ring_char R := and.right (classical.some_spec (char_p.exists_unique R)) p C protected instance char_p (R : Type u) [semiring R] : char_p R (ring_char R) := char_p.mk (spec R) theorem of_eq {R : Type u} [semiring R] {p : ℕ} (h : ring_char R = p) : char_p R p := char_p.congr (ring_char R) h theorem eq_iff {R : Type u} [semiring R] {p : ℕ} : ring_char R = p ↔ char_p R p := { mp := of_eq, mpr := Eq.symm ∘ eq R } theorem dvd {R : Type u} [semiring R] {x : ℕ} (hx : ↑x = 0) : ring_char R ∣ x := iff.mp (spec R x) hx end ring_char theorem add_pow_char_of_commute (R : Type u) [semiring R] {p : ℕ} [fact (nat.prime p)] [char_p R p] (x : R) (y : R) (h : commute x y) : (x + y) ^ p = x ^ p + y ^ p := sorry theorem add_pow_char_pow_of_commute (R : Type u) [semiring R] {p : ℕ} [fact (nat.prime p)] [char_p R p] {n : ℕ} (x : R) (y : R) (h : commute x y) : (x + y) ^ p ^ n = x ^ p ^ n + y ^ p ^ n := sorry theorem sub_pow_char_of_commute (R : Type u) [ring R] {p : ℕ} [fact (nat.prime p)] [char_p R p] (x : R) (y : R) (h : commute x y) : (x - y) ^ p = x ^ p - y ^ p := sorry theorem sub_pow_char_pow_of_commute (R : Type u) [ring R] {p : ℕ} [fact (nat.prime p)] [char_p R p] {n : ℕ} (x : R) (y : R) (h : commute x y) : (x - y) ^ p ^ n = x ^ p ^ n - y ^ p ^ n := sorry theorem add_pow_char (α : Type u) [comm_semiring α] {p : ℕ} [fact (nat.prime p)] [char_p α p] (x : α) (y : α) : (x + y) ^ p = x ^ p + y ^ p := add_pow_char_of_commute α x y (commute.all x y) theorem add_pow_char_pow (R : Type u) [comm_semiring R] {p : ℕ} [fact (nat.prime p)] [char_p R p] {n : ℕ} (x : R) (y : R) : (x + y) ^ p ^ n = x ^ p ^ n + y ^ p ^ n := add_pow_char_pow_of_commute R x y (commute.all x y) theorem sub_pow_char (α : Type u) [comm_ring α] {p : ℕ} [fact (nat.prime p)] [char_p α p] (x : α) (y : α) : (x - y) ^ p = x ^ p - y ^ p := sub_pow_char_of_commute α x y (commute.all x y) theorem sub_pow_char_pow (R : Type u) [comm_ring R] {p : ℕ} [fact (nat.prime p)] [char_p R p] {n : ℕ} (x : R) (y : R) : (x - y) ^ p ^ n = x ^ p ^ n - y ^ p ^ n := sub_pow_char_pow_of_commute R x y (commute.all x y) theorem eq_iff_modeq_int (R : Type u_1) [ring R] (p : ℕ) [char_p R p] (a : ℤ) (b : ℤ) : ↑a = ↑b ↔ int.modeq (↑p) a b := sorry theorem char_p.neg_one_ne_one (R : Type u_1) [ring R] (p : ℕ) [char_p R p] [fact (bit0 1 < p)] : -1 ≠ 1 := sorry theorem ring_hom.char_p_iff_char_p {K : Type u_1} {L : Type u_2} [field K] [field L] (f : K →+* L) (p : ℕ) : char_p K p ↔ char_p L p := sorry /-- The frobenius map that sends x to x^p -/ def frobenius (R : Type u) [comm_semiring R] (p : ℕ) [fact (nat.prime p)] [char_p R p] : R →+* R := ring_hom.mk (fun (x : R) => x ^ p) sorry sorry sorry (add_pow_char R) theorem frobenius_def {R : Type u} [comm_semiring R] (p : ℕ) [fact (nat.prime p)] [char_p R p] (x : R) : coe_fn (frobenius R p) x = x ^ p := rfl theorem iterate_frobenius {R : Type u} [comm_semiring R] (p : ℕ) [fact (nat.prime p)] [char_p R p] (x : R) (n : ℕ) : nat.iterate (⇑(frobenius R p)) n x = x ^ p ^ n := sorry theorem frobenius_mul {R : Type u} [comm_semiring R] (p : ℕ) [fact (nat.prime p)] [char_p R p] (x : R) (y : R) : coe_fn (frobenius R p) (x * y) = coe_fn (frobenius R p) x * coe_fn (frobenius R p) y := ring_hom.map_mul (frobenius R p) x y theorem frobenius_one {R : Type u} [comm_semiring R] (p : ℕ) [fact (nat.prime p)] [char_p R p] : coe_fn (frobenius R p) 1 = 1 := one_pow p theorem monoid_hom.map_frobenius {R : Type u} [comm_semiring R] {S : Type v} [comm_semiring S] (f : R →* S) (p : ℕ) [fact (nat.prime p)] [char_p R p] [char_p S p] (x : R) : coe_fn f (coe_fn (frobenius R p) x) = coe_fn (frobenius S p) (coe_fn f x) := monoid_hom.map_pow f x p theorem ring_hom.map_frobenius {R : Type u} [comm_semiring R] {S : Type v} [comm_semiring S] (g : R →+* S) (p : ℕ) [fact (nat.prime p)] [char_p R p] [char_p S p] (x : R) : coe_fn g (coe_fn (frobenius R p) x) = coe_fn (frobenius S p) (coe_fn g x) := ring_hom.map_pow g x p theorem monoid_hom.map_iterate_frobenius {R : Type u} [comm_semiring R] {S : Type v} [comm_semiring S] (f : R →* S) (p : ℕ) [fact (nat.prime p)] [char_p R p] [char_p S p] (x : R) (n : ℕ) : coe_fn f (nat.iterate (⇑(frobenius R p)) n x) = nat.iterate (⇑(frobenius S p)) n (coe_fn f x) := function.semiconj.iterate_right (monoid_hom.map_frobenius f p) n x theorem ring_hom.map_iterate_frobenius {R : Type u} [comm_semiring R] {S : Type v} [comm_semiring S] (g : R →+* S) (p : ℕ) [fact (nat.prime p)] [char_p R p] [char_p S p] (x : R) (n : ℕ) : coe_fn g (nat.iterate (⇑(frobenius R p)) n x) = nat.iterate (⇑(frobenius S p)) n (coe_fn g x) := monoid_hom.map_iterate_frobenius (ring_hom.to_monoid_hom g) p x n theorem monoid_hom.iterate_map_frobenius {R : Type u} [comm_semiring R] (x : R) (f : R →* R) (p : ℕ) [fact (nat.prime p)] [char_p R p] (n : ℕ) : nat.iterate (⇑f) n (coe_fn (frobenius R p) x) = coe_fn (frobenius R p) (nat.iterate (⇑f) n x) := monoid_hom.iterate_map_pow f x n p theorem ring_hom.iterate_map_frobenius {R : Type u} [comm_semiring R] (x : R) (f : R →+* R) (p : ℕ) [fact (nat.prime p)] [char_p R p] (n : ℕ) : nat.iterate (⇑f) n (coe_fn (frobenius R p) x) = coe_fn (frobenius R p) (nat.iterate (⇑f) n x) := ring_hom.iterate_map_pow f x n p theorem frobenius_zero (R : Type u) [comm_semiring R] (p : ℕ) [fact (nat.prime p)] [char_p R p] : coe_fn (frobenius R p) 0 = 0 := ring_hom.map_zero (frobenius R p) theorem frobenius_add (R : Type u) [comm_semiring R] (p : ℕ) [fact (nat.prime p)] [char_p R p] (x : R) (y : R) : coe_fn (frobenius R p) (x + y) = coe_fn (frobenius R p) x + coe_fn (frobenius R p) y := ring_hom.map_add (frobenius R p) x y theorem frobenius_nat_cast (R : Type u) [comm_semiring R] (p : ℕ) [fact (nat.prime p)] [char_p R p] (n : ℕ) : coe_fn (frobenius R p) ↑n = ↑n := ring_hom.map_nat_cast (frobenius R p) n theorem frobenius_neg (R : Type u) [comm_ring R] (p : ℕ) [fact (nat.prime p)] [char_p R p] (x : R) : coe_fn (frobenius R p) (-x) = -coe_fn (frobenius R p) x := ring_hom.map_neg (frobenius R p) x theorem frobenius_sub (R : Type u) [comm_ring R] (p : ℕ) [fact (nat.prime p)] [char_p R p] (x : R) (y : R) : coe_fn (frobenius R p) (x - y) = coe_fn (frobenius R p) x - coe_fn (frobenius R p) y := ring_hom.map_sub (frobenius R p) x y theorem frobenius_inj (α : Type u) [comm_ring α] [no_zero_divisors α] (p : ℕ) [fact (nat.prime p)] [char_p α p] : function.injective ⇑(frobenius α p) := sorry namespace char_p theorem char_p_to_char_zero (α : Type u) [ring α] [char_p α 0] : char_zero α := char_zero_of_inj_zero fun (n : ℕ) (h0 : ↑n = 0) => eq_zero_of_zero_dvd (iff.mp (cast_eq_zero_iff α 0 n) h0) theorem cast_eq_mod (α : Type u) [ring α] (p : ℕ) [char_p α p] (k : ℕ) : ↑k = ↑(k % p) := sorry theorem char_ne_zero_of_fintype (α : Type u) [ring α] (p : ℕ) [hc : char_p α p] [fintype α] : p ≠ 0 := fun (h : p = 0) => (fun (this : char_zero α) => absurd nat.cast_injective (not_injective_infinite_fintype coe)) (char_p_to_char_zero α) theorem char_ne_one (α : Type u) [integral_domain α] (p : ℕ) [hc : char_p α p] : p ≠ 1 := sorry theorem char_is_prime_of_two_le (α : Type u) [integral_domain α] (p : ℕ) [hc : char_p α p] (hp : bit0 1 ≤ p) : nat.prime p := sorry theorem char_is_prime_or_zero (α : Type u) [integral_domain α] (p : ℕ) [hc : char_p α p] : nat.prime p ∨ p = 0 := sorry theorem char_is_prime_of_pos (α : Type u) [integral_domain α] (p : ℕ) [h : fact (0 < p)] [char_p α p] : fact (nat.prime p) := or.resolve_right (char_is_prime_or_zero α p) (iff.mp pos_iff_ne_zero h) theorem char_is_prime (α : Type u) [integral_domain α] [fintype α] (p : ℕ) [char_p α p] : nat.prime p := or.resolve_right (char_is_prime_or_zero α p) (char_ne_zero_of_fintype α p) protected instance subsingleton {R : Type u_1} [semiring R] [char_p R 1] : subsingleton R := subsingleton.intro ((fun (this : ∀ (r : R), r = 0) (a b : R) => (fun (this : a = b) => this) (eq.mpr (id (Eq._oldrec (Eq.refl (a = b)) (this a))) (eq.mpr (id (Eq._oldrec (Eq.refl (0 = b)) (this b))) (Eq.refl 0)))) fun (r : R) => Eq.trans (Eq.trans (Eq.trans (eq.mpr (id (Eq._oldrec (Eq.refl (r = 1 * r)) (one_mul r))) (Eq.refl r)) (eq.mpr (id (Eq._oldrec (Eq.refl (1 * r = ↑1 * r)) nat.cast_one)) (Eq.refl (1 * r)))) (eq.mpr (id (Eq._oldrec (Eq.refl (↑1 * r = 0 * r)) (cast_eq_zero R 1))) (Eq.refl (0 * r)))) (eq.mpr (id (Eq._oldrec (Eq.refl (0 * r = 0)) (zero_mul r))) (Eq.refl 0))) theorem false_of_nontrivial_of_char_one {R : Type u_1} [semiring R] [nontrivial R] [char_p R 1] : False := false_of_nontrivial_of_subsingleton R theorem ring_char_ne_one {R : Type u_1} [semiring R] [nontrivial R] : ring_char R ≠ 1 := sorry theorem nontrivial_of_char_ne_one {v : ℕ} (hv : v ≠ 1) {R : Type u_1} [semiring R] [hr : char_p R v] : nontrivial R := sorry end char_p theorem char_p_of_ne_zero (n : ℕ) (R : Type u_1) [comm_ring R] [fintype R] (hn : fintype.card R = n) (hR : ∀ (i : ℕ), i < n → ↑i = 0 → i = 0) : char_p R n := sorry theorem char_p_of_prime_pow_injective (R : Type u_1) [comm_ring R] [fintype R] (p : ℕ) [hp : fact (nat.prime p)] (n : ℕ) (hn : fintype.card R = p ^ n) (hR : ∀ (i : ℕ), i ≤ n → ↑p ^ i = 0 → i = n) : char_p R (p ^ n) := sorry
1ed947bf6852c8869278df27832689ed7d099443
437dc96105f48409c3981d46fb48e57c9ac3a3e4
/src/group_theory/submonoid.lean
69771d98937552d188ecc7dc852a663bc96d603f
[ "Apache-2.0" ]
permissive
dan-c-k/mathlib
08efec79bd7481ee6da9cc44c24a653bff4fbe0d
96efc220f6225bc7a5ed8349900391a33a38cc56
refs/heads/master
1,658,082,847,093
1,589,013,201,000
1,589,013,201,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
50,455
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, Kenny Lau, Johan Commelin, Mario Carneiro, Kevin Buzzard, Amelia Livingston, Yury Kudryashov -/ import algebra.big_operators import algebra.free_monoid import algebra.group.prod import data.equiv.mul_add /-! # Submonoids This file defines multiplicative and additive submonoids, first in an unbundled form (deprecated) and then in a bundled form. We prove submonoids of a monoid form a complete lattice, and results about images and preimages of submonoids under monoid homomorphisms. For the unbundled submonoids, these theorems use unbundled monoid homomorphisms (also deprecated), and the bundled versions use bundled monoid homomorphisms. There are also theorems about the submonoids generated by an element or a subset of a monoid, defined both inductively and as the infimum of the set of submonoids containing a given element/subset. ## Implementation notes Unbundled submonoids will slowly be removed from mathlib. (Bundled) submonoid inclusion is denoted `≤` rather than `⊆`, although `∈` is defined as membership of a submonoid's underlying set. ## Tags submonoid, submonoids, is_submonoid -/ variables {M : Type*} [monoid M] {s : set M} variables {A : Type*} [add_monoid A] {t : set A} /-- `s` is an additive submonoid: a set containing 0 and closed under addition. -/ class is_add_submonoid (s : set A) : Prop := (zero_mem : (0:A) ∈ s) (add_mem {a b} : a ∈ s → b ∈ s → a + b ∈ s) /-- `s` is a submonoid: a set containing 1 and closed under multiplication. -/ @[to_additive is_add_submonoid] class is_submonoid (s : set M) : Prop := (one_mem : (1:M) ∈ s) (mul_mem {a b} : a ∈ s → b ∈ s → a * b ∈ s) lemma additive.is_add_submonoid (s : set M) : ∀ [is_submonoid s], @is_add_submonoid (additive M) _ s | ⟨h₁, h₂⟩ := ⟨h₁, @h₂⟩ theorem additive.is_add_submonoid_iff {s : set M} : @is_add_submonoid (additive M) _ s ↔ is_submonoid s := ⟨λ ⟨h₁, h₂⟩, ⟨h₁, @h₂⟩, λ h, by exactI additive.is_add_submonoid _⟩ lemma multiplicative.is_submonoid (s : set A) : ∀ [is_add_submonoid s], @is_submonoid (multiplicative A) _ s | ⟨h₁, h₂⟩ := ⟨h₁, @h₂⟩ theorem multiplicative.is_submonoid_iff {s : set A} : @is_submonoid (multiplicative A) _ s ↔ is_add_submonoid s := ⟨λ ⟨h₁, h₂⟩, ⟨h₁, @h₂⟩, λ h, by exactI multiplicative.is_submonoid _⟩ /-- The intersection of two submonoids of a monoid `M` is a submonoid of `M`. -/ @[to_additive "The intersection of two `add_submonoid`s of an `add_monoid` `M` is an `add_submonoid` of M."] instance is_submonoid.inter (s₁ s₂ : set M) [is_submonoid s₁] [is_submonoid s₂] : is_submonoid (s₁ ∩ s₂) := { one_mem := ⟨is_submonoid.one_mem, is_submonoid.one_mem⟩, mul_mem := λ x y hx hy, ⟨is_submonoid.mul_mem hx.1 hy.1, is_submonoid.mul_mem hx.2 hy.2⟩ } /-- The intersection of an indexed set of submonoids of a monoid `M` is a submonoid of `M`. -/ @[to_additive "The intersection of an indexed set of `add_submonoid`s of an `add_monoid` `M` is an `add_submonoid` of `M`."] instance is_submonoid.Inter {ι : Sort*} (s : ι → set M) [h : ∀ y : ι, is_submonoid (s y)] : is_submonoid (set.Inter s) := { one_mem := set.mem_Inter.2 $ λ y, is_submonoid.one_mem, mul_mem := λ x₁ x₂ h₁ h₂, set.mem_Inter.2 $ λ y, is_submonoid.mul_mem (set.mem_Inter.1 h₁ y) (set.mem_Inter.1 h₂ y) } /-- The union of an indexed, directed, nonempty set of submonoids of a monoid `M` is a submonoid of `M`. -/ @[to_additive is_add_submonoid_Union_of_directed "The union of an indexed, directed, nonempty set of `add_submonoid`s of an `add_monoid` `M` is an `add_submonoid` of `M`. "] lemma is_submonoid_Union_of_directed {ι : Type*} [hι : nonempty ι] (s : ι → set M) [∀ i, is_submonoid (s i)] (directed : ∀ i j, ∃ k, s i ⊆ s k ∧ s j ⊆ s k) : is_submonoid (⋃i, s i) := { one_mem := let ⟨i⟩ := hι in set.mem_Union.2 ⟨i, is_submonoid.one_mem⟩, mul_mem := λ a b ha hb, let ⟨i, hi⟩ := set.mem_Union.1 ha in let ⟨j, hj⟩ := set.mem_Union.1 hb in let ⟨k, hk⟩ := directed i j in set.mem_Union.2 ⟨k, is_submonoid.mul_mem (hk.1 hi) (hk.2 hj)⟩ } section powers /-- The set of natural number powers `1, x, x², ...` of an element `x` of a monoid. -/ def powers (x : M) : set M := {y | ∃ n:ℕ, x^n = y} /-- The set of natural number multiples `0, x, 2x, ...` of an element `x` of an `add_monoid`. -/ def multiples (x : A) : set A := {y | ∃ n:ℕ, add_monoid.smul n x = y} attribute [to_additive multiples] powers /-- 1 is in the set of natural number powers of an element of a monoid. -/ lemma powers.one_mem {x : M} : (1 : M) ∈ powers x := ⟨0, pow_zero _⟩ /-- 0 is in the set of natural number multiples of an element of an `add_monoid`. -/ lemma multiples.zero_mem {x : A} : (0 : A) ∈ multiples x := ⟨0, add_monoid.zero_smul _⟩ attribute [to_additive] powers.one_mem /-- An element of a monoid is in the set of that element's natural number powers. -/ lemma powers.self_mem {x : M} : x ∈ powers x := ⟨1, pow_one _⟩ /-- An element of an `add_monoid` is in the set of that element's natural number multiples. -/ lemma multiples.self_mem {x : A} : x ∈ multiples x := ⟨1, add_monoid.one_smul _⟩ attribute [to_additive] powers.self_mem /-- The set of natural number powers of an element of a monoid is closed under multiplication. -/ lemma powers.mul_mem {x y z : M} : (y ∈ powers x) → (z ∈ powers x) → (y * z ∈ powers x) := λ ⟨n₁, h₁⟩ ⟨n₂, h₂⟩, ⟨n₁ + n₂, by simp only [pow_add, *]⟩ /-- The set of natural number multiples of an element of an `add_monoid` is closed under addition. -/ lemma multiples.add_mem {x y z : A} : (y ∈ multiples x) → (z ∈ multiples x) → (y + z ∈ multiples x) := @powers.mul_mem (multiplicative A) _ _ _ _ attribute [to_additive] powers.mul_mem /-- The set of natural number powers of an element of a monoid `M` is a submonoid of `M`. -/ @[to_additive is_add_submonoid "The set of natural number multiples of an element of an `add_monoid` `M` is an `add_submonoid` of `M`."] instance powers.is_submonoid (x : M) : is_submonoid (powers x) := { one_mem := powers.one_mem, mul_mem := λ y z, powers.mul_mem } /-- A monoid is a submonoid of itself. -/ @[to_additive is_add_submonoid "An `add_monoid` is an `add_submonoid` of itself."] instance univ.is_submonoid : is_submonoid (@set.univ M) := by split; simp /-- The preimage of a submonoid under a monoid hom is a submonoid of the domain. -/ @[to_additive is_add_submonoid "The preimage of an `add_submonoid` under an `add_monoid` hom is an `add_submonoid` of the domain."] instance preimage.is_submonoid {N : Type*} [monoid N] (f : M → N) [is_monoid_hom f] (s : set N) [is_submonoid s] : is_submonoid (f ⁻¹' s) := { one_mem := show f 1 ∈ s, by rw is_monoid_hom.map_one f; exact is_submonoid.one_mem, mul_mem := λ a b (ha : f a ∈ s) (hb : f b ∈ s), show f (a * b) ∈ s, by rw is_monoid_hom.map_mul f; exact is_submonoid.mul_mem ha hb } /-- The image of a submonoid under a monoid hom is a submonoid of the codomain. -/ @[instance, to_additive is_add_submonoid "The image of an `add_submonoid` under an `add_monoid` hom is an `add_submonoid` of the codomain."] lemma image.is_submonoid {γ : Type*} [monoid γ] (f : M → γ) [is_monoid_hom f] (s : set M) [is_submonoid s] : is_submonoid (f '' s) := { one_mem := ⟨1, is_submonoid.one_mem, is_monoid_hom.map_one f⟩, mul_mem := λ a b ⟨x, hx⟩ ⟨y, hy⟩, ⟨x * y, is_submonoid.mul_mem hx.1 hy.1, by rw [is_monoid_hom.map_mul f, hx.2, hy.2]⟩ } /-- The image of a monoid hom is a submonoid of the codomain. -/ @[to_additive is_add_submonoid "The image of an `add_monoid` hom is an `add_submonoid` of the codomain."] instance range.is_submonoid {γ : Type*} [monoid γ] (f : M → γ) [is_monoid_hom f] : is_submonoid (set.range f) := by rw ← set.image_univ; apply_instance /-- Submonoids are closed under natural powers. -/ lemma is_submonoid.pow_mem {a : M} [is_submonoid s] (h : a ∈ s) : ∀ {n : ℕ}, a ^ n ∈ s | 0 := is_submonoid.one_mem | (n + 1) := is_submonoid.mul_mem h is_submonoid.pow_mem /-- An `add_submonoid` is closed under multiplication by naturals. -/ lemma is_add_submonoid.smul_mem {a : A} [is_add_submonoid t] : ∀ (h : a ∈ t) {n : ℕ}, add_monoid.smul n a ∈ t := @is_submonoid.pow_mem (multiplicative A) _ _ _ (multiplicative.is_submonoid _) attribute [to_additive smul_mem] is_submonoid.pow_mem /-- The set of natural number powers of an element of a submonoid is a subset of the submonoid. -/ lemma is_submonoid.power_subset {a : M} [is_submonoid s] (h : a ∈ s) : powers a ⊆ s := assume x ⟨n, hx⟩, hx ▸ is_submonoid.pow_mem h /-- The set of natural number multiples of an element of an `add_submonoid` is a subset of the `add_submonoid`. -/ lemma is_add_submonoid.multiple_subset {a : A} [is_add_submonoid t] : a ∈ t → multiples a ⊆ t := @is_submonoid.power_subset (multiplicative A) _ _ _ (multiplicative.is_submonoid _) attribute [to_additive multiple_subset] is_submonoid.power_subset end powers namespace is_submonoid /-- The product of a list of elements of a submonoid is an element of the submonoid. -/ @[to_additive "The sum of a list of elements of an `add_submonoid` is an element of the `add_submonoid`."] lemma list_prod_mem [is_submonoid s] : ∀{l : list M}, (∀x∈l, x ∈ s) → l.prod ∈ s | [] h := one_mem | (a::l) h := suffices a * l.prod ∈ s, by simpa, have a ∈ s ∧ (∀x∈l, x ∈ s), by simpa using h, is_submonoid.mul_mem this.1 (list_prod_mem this.2) /-- The product of a multiset of elements of a submonoid of a `comm_monoid` is an element of the submonoid. -/ @[to_additive "The sum of a multiset of elements of an `add_submonoid` of an `add_comm_monoid` is an element of the `add_submonoid`. "] lemma multiset_prod_mem {M} [comm_monoid M] (s : set M) [is_submonoid s] (m : multiset M) : (∀a∈m, a ∈ s) → m.prod ∈ s := begin refine quotient.induction_on m (assume l hl, _), rw [multiset.quot_mk_to_coe, multiset.coe_prod], exact list_prod_mem hl end /-- The product of elements of a submonoid of a `comm_monoid` indexed by a `finset` is an element of the submonoid. -/ @[to_additive "The sum of elements of an `add_submonoid` of an `add_comm_monoid` indexed by a `finset` is an element of the `add_submonoid`."] lemma finset_prod_mem {M A} [comm_monoid M] (s : set M) [is_submonoid s] (f : A → M) : ∀(t : finset A), (∀b∈t, f b ∈ s) → t.prod f ∈ s | ⟨m, hm⟩ hs := begin refine multiset_prod_mem s _ _, simp, rintros a b hb rfl, exact hs _ hb end end is_submonoid -- TODO: modify `subtype_instance` to produce this definition, then use it here -- and for `subtype.group` /-- Submonoids are themselves monoids. -/ @[to_additive add_monoid "An `add_submonoid` is itself an `add_monoid`."] instance subtype.monoid {s : set M} [is_submonoid s] : monoid s := { one := ⟨1, is_submonoid.one_mem⟩, mul := λ x y, ⟨x * y, is_submonoid.mul_mem x.2 y.2⟩, mul_one := λ x, subtype.eq $ mul_one x.1, one_mul := λ x, subtype.eq $ one_mul x.1, mul_assoc := λ x y z, subtype.eq $ mul_assoc x.1 y.1 z.1 } /-- Submonoids of commutative monoids are themselves commutative monoids. -/ @[to_additive add_comm_monoid "An `add_submonoid` of a commutative `add_monoid` is itself a commutative `add_monoid`. "] instance subtype.comm_monoid {M} [comm_monoid M] {s : set M} [is_submonoid s] : comm_monoid s := { mul_comm := λ x y, subtype.eq $ mul_comm x.1 y.1, .. subtype.monoid } /-- Submonoids inherit the 1 of the monoid. -/ @[simp, norm_cast, to_additive "An `add_submonoid` inherits the 0 of the `add_monoid`. "] lemma is_submonoid.coe_one [is_submonoid s] : ((1 : s) : M) = 1 := rfl attribute [norm_cast] is_add_submonoid.coe_zero /-- Submonoids inherit the multiplication of the monoid. -/ @[simp, norm_cast, to_additive "An `add_submonoid` inherits the addition of the `add_monoid`. "] lemma is_submonoid.coe_mul [is_submonoid s] (a b : s) : ((a * b : s) : M) = a * b := rfl attribute [norm_cast] is_add_submonoid.coe_add /-- Submonoids inherit the exponentiation by naturals of the monoid. -/ @[simp, norm_cast] lemma is_submonoid.coe_pow [is_submonoid s] (a : s) (n : ℕ) : ((a ^ n : s) : M) = a ^ n := by induction n; simp [*, pow_succ] /-- An `add_submonoid` inherits the multiplication by naturals of the `add_monoid`. -/ @[simp, norm_cast] lemma is_add_submonoid.smul_coe {A : Type*} [add_monoid A] {s : set A} [is_add_submonoid s] (a : s) (n : ℕ) : ((add_monoid.smul n a : s) : A) = add_monoid.smul n a := by {induction n, refl, simp [*, succ_smul]} attribute [to_additive smul_coe] is_submonoid.coe_pow /-- The natural injection from a submonoid into the monoid is a monoid hom. -/ @[to_additive is_add_monoid_hom "The natural injection from an `add_submonoid` into the `add_monoid` is an `add_monoid` hom. "] instance subtype_val.is_monoid_hom [is_submonoid s] : is_monoid_hom (subtype.val : s → M) := { map_one := rfl, map_mul := λ _ _, rfl } /-- The natural injection from a submonoid into the monoid is a monoid hom. -/ @[to_additive is_add_monoid_hom "The natural injection from an `add_submonoid` into the `add_monoid` is an `add_monoid` hom. "] instance coe.is_monoid_hom [is_submonoid s] : is_monoid_hom (coe : s → M) := subtype_val.is_monoid_hom /-- Given a monoid hom `f : γ → M` whose image is contained in a submonoid `s`, the induced map from `γ` to `s` is a monoid hom. -/ @[to_additive is_add_monoid_hom "Given an `add_monoid` hom `f : γ → M` whose image is contained in an `add_submonoid` s, the induced map from `γ` to `s` is an `add_monoid` hom."] instance subtype_mk.is_monoid_hom {γ : Type*} [monoid γ] [is_submonoid s] (f : γ → M) [is_monoid_hom f] (h : ∀ x, f x ∈ s) : is_monoid_hom (λ x, (⟨f x, h x⟩ : s)) := { map_one := subtype.eq (is_monoid_hom.map_one f), map_mul := λ x y, subtype.eq (is_monoid_hom.map_mul f x y) } /-- Given two submonoids `s` and `t` such that `s ⊆ t`, the natural injection from `s` into `t` is a monoid hom. -/ @[to_additive is_add_monoid_hom "Given two `add_submonoid`s `s` and `t` such that `s ⊆ t`, the natural injection from `s` into `t` is an `add_monoid` hom."] instance set_inclusion.is_monoid_hom (t : set M) [is_submonoid s] [is_submonoid t] (h : s ⊆ t) : is_monoid_hom (set.inclusion h) := subtype_mk.is_monoid_hom _ _ namespace add_monoid /-- The inductively defined membership predicate for the submonoid generated by a subset of a monoid. -/ inductive in_closure (s : set A) : A → Prop | basic {a : A} : a ∈ s → in_closure a | zero : in_closure 0 | add {a b : A} : in_closure a → in_closure b → in_closure (a + b) end add_monoid namespace monoid /-- The inductively defined membership predicate for the `add_submonoid` generated by a subset of an add_monoid. -/ inductive in_closure (s : set M) : M → Prop | basic {a : M} : a ∈ s → in_closure a | one : in_closure 1 | mul {a b : M} : in_closure a → in_closure b → in_closure (a * b) attribute [to_additive] monoid.in_closure attribute [to_additive] monoid.in_closure.one attribute [to_additive] monoid.in_closure.mul /-- The inductively defined submonoid generated by a subset of a monoid. -/ @[to_additive "The inductively defined `add_submonoid` genrated by a subset of an `add_monoid`."] def closure (s : set M) : set M := {a | in_closure s a } @[to_additive is_add_submonoid] instance closure.is_submonoid (s : set M) : is_submonoid (closure s) := { one_mem := in_closure.one, mul_mem := assume a b, in_closure.mul } /-- A subset of a monoid is contained in the submonoid it generates. -/ @[to_additive "A subset of an `add_monoid` is contained in the `add_submonoid` it generates."] theorem subset_closure {s : set M} : s ⊆ closure s := assume a, in_closure.basic /-- The submonoid generated by a set is contained in any submonoid that contains the set. -/ @[to_additive "The `add_submonoid` generated by a set is contained in any `add_submonoid` that contains the set."] theorem closure_subset {s t : set M} [is_submonoid t] (h : s ⊆ t) : closure s ⊆ t := assume a ha, by induction ha; simp [h _, *, is_submonoid.one_mem, is_submonoid.mul_mem] /-- Given subsets `t` and `s` of a monoid `M`, if `s ⊆ t`, the submonoid of `M` generated by `s` is contained in the submonoid generated by `t`. -/ @[to_additive "Given subsets `t` and `s` of an `add_monoid M`, if `s ⊆ t`, the `add_submonoid` of `M` generated by `s` is contained in the `add_submonoid` generated by `t`."] theorem closure_mono {s t : set M} (h : s ⊆ t) : closure s ⊆ closure t := closure_subset $ set.subset.trans h subset_closure /-- The submonoid generated by an element of a monoid equals the set of natural number powers of the element. -/ @[to_additive "The `add_submonoid` generated by an element of an `add_monoid` equals the set of natural number multiples of the element."] theorem closure_singleton {x : M} : closure ({x} : set M) = powers x := set.eq_of_subset_of_subset (closure_subset $ set.singleton_subset_iff.2 $ powers.self_mem) $ is_submonoid.power_subset $ set.singleton_subset_iff.1 $ subset_closure /-- The image under a monoid hom of the submonoid generated by a set equals the submonoid generated by the image of the set under the monoid hom. -/ @[to_additive "The image under an `add_monoid` hom of the `add_submonoid` generated by a set equals the `add_submonoid` generated by the image of the set under the `add_monoid` hom."] lemma image_closure {A : Type*} [monoid A] (f : M → A) [is_monoid_hom f] (s : set M) : f '' closure s = closure (f '' s) := le_antisymm begin rintros _ ⟨x, hx, rfl⟩, apply in_closure.rec_on hx; intros, { solve_by_elim [subset_closure, set.mem_image_of_mem] }, { rw [is_monoid_hom.map_one f], apply is_submonoid.one_mem }, { rw [is_monoid_hom.map_mul f], solve_by_elim [is_submonoid.mul_mem] } end (closure_subset $ set.image_subset _ subset_closure) /-- Given an element `a` of the submonoid of a monoid `M` generated by a set `s`, there exists a list of elements of `s` whose product is `a`. -/ @[to_additive "Given an element `a` of the `add_submonoid` of an `add_monoid M` generated by a set `s`, there exists a list of elements of `s` whose sum is `a`."] theorem exists_list_of_mem_closure {s : set M} {a : M} (h : a ∈ closure s) : (∃l:list M, (∀x∈l, x ∈ s) ∧ l.prod = a) := begin induction h, case in_closure.basic : a ha { existsi ([a]), simp [ha] }, case in_closure.one { existsi ([]), simp }, case in_closure.mul : a b _ _ ha hb { rcases ha with ⟨la, ha, eqa⟩, rcases hb with ⟨lb, hb, eqb⟩, existsi (la ++ lb), simp [eqa.symm, eqb.symm, or_imp_distrib], exact assume a, ⟨ha a, hb a⟩ } end /-- Given sets `s, t` of a commutative monoid `M`, `x ∈ M` is in the submonoid of `M` generated by `s ∪ t` iff there exists an element of the submonoid generated by `s` and an element of the submonoid generated by `t` whose product is `x`. -/ @[to_additive "Given sets `s, t` of a commutative `add_monoid M`, `x ∈ M` is in the `add_submonoid` of `M` generated by `s ∪ t` iff there exists an element of the `add_submonoid` generated by `s` and an element of the `add_submonoid` generated by `t` whose sum is `x`."] theorem mem_closure_union_iff {M : Type*} [comm_monoid M] {s t : set M} {x : M} : x ∈ closure (s ∪ t) ↔ ∃ y ∈ closure s, ∃ z ∈ closure t, y * z = x := ⟨λ hx, let ⟨L, HL1, HL2⟩ := exists_list_of_mem_closure hx in HL2 ▸ list.rec_on L (λ _, ⟨1, is_submonoid.one_mem, 1, is_submonoid.one_mem, mul_one _⟩) (λ hd tl ih HL1, let ⟨y, hy, z, hz, hyzx⟩ := ih (list.forall_mem_of_forall_mem_cons HL1) in or.cases_on (HL1 hd $ list.mem_cons_self _ _) (λ hs, ⟨hd * y, is_submonoid.mul_mem (subset_closure hs) hy, z, hz, by rw [mul_assoc, list.prod_cons, ← hyzx]; refl⟩) (λ ht, ⟨y, hy, z * hd, is_submonoid.mul_mem hz (subset_closure ht), by rw [← mul_assoc, list.prod_cons, ← hyzx, mul_comm hd]; refl⟩)) HL1, λ ⟨y, hy, z, hz, hyzx⟩, hyzx ▸ is_submonoid.mul_mem (closure_mono (set.subset_union_left _ _) hy) (closure_mono (set.subset_union_right _ _) hz)⟩ end monoid /-! ### Bundled submonoids and `add_submonoid`s -/ /-- A submonoid of a monoid `M` is a subset containing 1 and closed under multiplication. -/ structure submonoid (M : Type*) [monoid M] := (carrier : set M) (one_mem' : (1 : M) ∈ carrier) (mul_mem' {a b} : a ∈ carrier → b ∈ carrier → a * b ∈ carrier) /-- An additive submonoid of an additive monoid `M` is a subset containing 0 and closed under addition. -/ structure add_submonoid (M : Type*) [add_monoid M] := (carrier : set M) (zero_mem' : (0 : M) ∈ carrier) (add_mem' {a b} : a ∈ carrier → b ∈ carrier → a + b ∈ carrier) attribute [to_additive add_submonoid] submonoid /-- Create a bundled submonoid from a set `s` and `[is_submonoid s]`. -/ @[to_additive "Create a bundled additive submonoid from a set `s` and `[is_add_submonoid s]`."] def submonoid.of (s : set M) [h : is_submonoid s] : submonoid M := ⟨s, h.1, h.2⟩ /-- Map from submonoids of monoid `M` to `add_submonoid`s of `additive M`. -/ def submonoid.to_add_submonoid {M : Type*} [monoid M] (S : submonoid M) : add_submonoid (additive M) := { carrier := S.carrier, zero_mem' := S.one_mem', add_mem' := S.mul_mem' } /-- Map from `add_submonoid`s of `additive M` to submonoids of `M`. -/ def submonoid.of_add_submonoid {M : Type*} [monoid M] (S : add_submonoid (additive M)) : submonoid M := { carrier := S.carrier, one_mem' := S.zero_mem', mul_mem' := S.add_mem' } /-- Map from `add_submonoid`s of `add_monoid M` to submonoids of `multiplicative M`. -/ def add_submonoid.to_submonoid {M : Type*} [add_monoid M] (S : add_submonoid M) : submonoid (multiplicative M) := { carrier := S.carrier, one_mem' := S.zero_mem', mul_mem' := S.add_mem' } /-- Map from submonoids of `multiplicative M` to `add_submonoid`s of `add_monoid M`. -/ def add_submonoid.of_submonoid {M : Type*} [add_monoid M] (S : submonoid (multiplicative M)) : add_submonoid M := { carrier := S.carrier, zero_mem' := S.one_mem', add_mem' := S.mul_mem' } /-- Submonoids of monoid `M` are isomorphic to additive submonoids of `additive M`. -/ def submonoid.add_submonoid_equiv (M : Type*) [monoid M] : submonoid M ≃ add_submonoid (additive M) := { to_fun := submonoid.to_add_submonoid, inv_fun := submonoid.of_add_submonoid, left_inv := λ x, by cases x; refl, right_inv := λ x, by cases x; refl } namespace submonoid @[to_additive] instance : has_coe (submonoid M) (set M) := ⟨submonoid.carrier⟩ @[to_additive] instance : has_coe_to_sort (submonoid M) := ⟨Type*, λ S, S.carrier⟩ @[to_additive] instance : has_mem M (submonoid M) := ⟨λ m S, m ∈ (S:set M)⟩ @[simp, norm_cast, to_additive] lemma mem_coe {S : submonoid M} {m : M} : m ∈ (S : set M) ↔ m ∈ S := iff.rfl @[simp, norm_cast, to_additive] lemma coe_coe (s : submonoid M) : ↥(s : set M) = s := rfl attribute [norm_cast] add_submonoid.mem_coe add_submonoid.coe_coe @[to_additive] instance is_submonoid (S : submonoid M) : is_submonoid (S : set M) := ⟨S.2, S.3⟩ end submonoid @[to_additive] protected lemma submonoid.exists {s : submonoid M} {p : s → Prop} : (∃ x : s, p x) ↔ ∃ x ∈ s, p ⟨x, ‹x ∈ s›⟩ := set_coe.exists namespace submonoid variables (S : submonoid M) /-- Two submonoids are equal if the underlying subsets are equal. -/ @[to_additive "Two `add_submonoid`s are equal if the underlying subsets are equal."] theorem ext' {S T : submonoid M} (h : (S : set M) = T) : S = T := by cases S; cases T; congr' /-- Two submonoids are equal if and only if the underlying subsets are equal. -/ @[to_additive "Two `add_submonoid`s are equal if and only if the underlying subsets are equal."] protected theorem ext'_iff {S T : submonoid M} : S = T ↔ (S : set M) = T := ⟨λ h, h ▸ rfl, ext'⟩ /-- Two submonoids are equal if they have the same elements. -/ @[ext, to_additive "Two `add_submonoid`s are equal if they have the same elements."] theorem ext {S T : submonoid M} (h : ∀ x, x ∈ S ↔ x ∈ T) : S = T := ext' $ set.ext h attribute [ext] add_submonoid.ext /-- A submonoid contains the monoid's 1. -/ @[to_additive "An `add_submonoid` contains the monoid's 0."] theorem one_mem : (1 : M) ∈ S := S.one_mem' /-- A submonoid is closed under multiplication. -/ @[to_additive "An `add_submonoid` is closed under addition."] theorem mul_mem {x y : M} : x ∈ S → y ∈ S → x * y ∈ S := submonoid.mul_mem' S /-- Product of a list of elements in a submonoid is in the submonoid. -/ @[to_additive "Sum of a list of elements in an `add_submonoid` is in the `add_submonoid`."] lemma list_prod_mem : ∀ {l : list M}, (∀x ∈ l, x ∈ S) → l.prod ∈ S | [] h := S.one_mem | (a::l) h := suffices a * l.prod ∈ S, by rwa [list.prod_cons], have a ∈ S ∧ (∀ x ∈ l, x ∈ S), from list.forall_mem_cons.1 h, S.mul_mem this.1 (list_prod_mem this.2) /-- Product of a multiset of elements in a submonoid of a `comm_monoid` is in the submonoid. -/ @[to_additive "Sum of a multiset of elements in an `add_submonoid` of an `add_comm_monoid` is in the `add_submonoid`."] lemma multiset_prod_mem {M} [comm_monoid M] (S : submonoid M) (m : multiset M) : (∀a ∈ m, a ∈ S) → m.prod ∈ S := begin refine quotient.induction_on m (assume l hl, _), rw [multiset.quot_mk_to_coe, multiset.coe_prod], exact S.list_prod_mem hl end /-- Product of elements of a submonoid of a `comm_monoid` indexed by a `finset` is in the submonoid. -/ @[to_additive "Sum of elements in an `add_submonoid` of an `add_comm_monoid` indexed by a `finset` is in the `add_submonoid`."] lemma prod_mem {M : Type*} [comm_monoid M] (S : submonoid M) {ι : Type*} {t : finset ι} {f : ι → M} (h : ∀c ∈ t, f c ∈ S) : t.prod f ∈ S := S.multiset_prod_mem (t.1.map f) $ λ x hx, let ⟨i, hi, hix⟩ := multiset.mem_map.1 hx in hix ▸ h i hi lemma pow_mem {x : M} (hx : x ∈ S) : ∀ n:ℕ, x^n ∈ S | 0 := S.one_mem | (n+1) := S.mul_mem hx (pow_mem n) /-- A submonoid of a monoid inherits a multiplication. -/ @[to_additive "An `add_submonoid` of an `add_monoid` inherits an addition."] instance has_mul : has_mul S := ⟨λ a b, ⟨a.1 * b.1, S.mul_mem a.2 b.2⟩⟩ /-- A submonoid of a monoid inherits a 1. -/ @[to_additive "An `add_submonoid` of an `add_monoid` inherits a zero."] instance has_one : has_one S := ⟨⟨_, S.one_mem⟩⟩ @[simp, to_additive] lemma coe_mul (x y : S) : (↑(x * y) : M) = ↑x * ↑y := rfl @[simp, to_additive] lemma coe_one : ((1 : S) : M) = 1 := rfl /-- A submonoid of a monoid inherits a monoid structure. -/ @[to_additive to_add_monoid "An `add_submonoid` of an `add_monoid` inherits an `add_monoid` structure."] instance to_monoid {M : Type*} [monoid M] (S : submonoid M) : monoid S := by refine { mul := (*), one := 1, ..}; by simp [mul_assoc] /-- A submonoid of a `comm_monoid` is a `comm_monoid`. -/ @[to_additive to_add_comm_monoid "An `add_submonoid` of an `add_comm_monoid` is an `add_comm_monoid`."] instance to_comm_monoid {M} [comm_monoid M] (S : submonoid M) : comm_monoid S := { mul_comm := λ _ _, subtype.eq $ mul_comm _ _, ..S.to_monoid} /-- The natural monoid hom from a submonoid of monoid `M` to `M`. -/ @[to_additive "The natural monoid hom from an `add_submonoid` of `add_monoid` `M` to `M`."] def subtype : S →* M := ⟨coe, rfl, λ _ _, rfl⟩ @[simp, to_additive] theorem coe_subtype : ⇑S.subtype = coe := rfl @[to_additive] instance : has_le (submonoid M) := ⟨λ S T, ∀ ⦃x⦄, x ∈ S → x ∈ T⟩ @[to_additive] instance : has_lt (submonoid M) := ⟨λ S T, S ≤ T ∧ ¬(T ≤ S)⟩ @[to_additive] lemma le_def {S T : submonoid M} : S ≤ T ↔ ∀ ⦃x : M⦄, x ∈ S → x ∈ T := iff.rfl @[simp, to_additive] lemma coe_subset_coe {S T : submonoid M} : (S : set M) ⊆ T ↔ S ≤ T := iff.rfl @[simp, to_additive] lemma coe_ssubset_coe {S T : submonoid M} : (S : set M) ⊂ T ↔ S < T := iff.rfl /-- The submonoid `M` of the monoid `M`. -/ @[to_additive "The `add_submonoid M` of the `add_monoid M`."] instance : has_top (submonoid M) := ⟨{ carrier := set.univ, one_mem' := set.mem_univ 1, mul_mem' := λ _ _ _ _, set.mem_univ _ }⟩ /-- The trivial submonoid `{1}` of an monoid `M`. -/ @[to_additive "The trivial `add_submonoid` `{0}` of an `add_monoid` `M`."] instance : has_bot (submonoid M) := ⟨{ carrier := {1}, one_mem' := set.mem_singleton 1, mul_mem' := λ a b ha hb, by { simp only [set.mem_singleton_iff] at *, rw [ha, hb, mul_one] }}⟩ @[to_additive] instance : inhabited (submonoid M) := ⟨⊥⟩ @[simp, to_additive] lemma mem_bot {x : M} : x ∈ (⊥ : submonoid M) ↔ x = 1 := set.mem_singleton_iff @[simp, to_additive] lemma mem_top (x : M) : x ∈ (⊤ : submonoid M) := set.mem_univ x @[simp, to_additive] lemma coe_top : ((⊤ : submonoid M) : set M) = set.univ := rfl @[simp, to_additive] lemma coe_bot : ((⊥ : submonoid M) : set M) = {1} := rfl /-- The inf of two submonoids is their intersection. -/ @[to_additive "The inf of two `add_submonoid`s is their intersection."] instance : has_inf (submonoid M) := ⟨λ S₁ S₂, { carrier := S₁ ∩ S₂, one_mem' := ⟨S₁.one_mem, S₂.one_mem⟩, mul_mem' := λ _ _ ⟨hx, hx'⟩ ⟨hy, hy'⟩, ⟨S₁.mul_mem hx hy, S₂.mul_mem hx' hy'⟩ }⟩ @[simp, to_additive] lemma coe_inf (p p' : submonoid M) : ((p ⊓ p' : submonoid M) : set M) = p ∩ p' := rfl @[simp, to_additive] lemma mem_inf {p p' : submonoid M} {x : M} : x ∈ p ⊓ p' ↔ x ∈ p ∧ x ∈ p' := iff.rfl @[to_additive] instance : has_Inf (submonoid M) := ⟨λ s, { carrier := ⋂ t ∈ s, ↑t, one_mem' := set.mem_bInter $ λ i h, i.one_mem, mul_mem' := λ x y hx hy, set.mem_bInter $ λ i h, i.mul_mem (by apply set.mem_bInter_iff.1 hx i h) (by apply set.mem_bInter_iff.1 hy i h) }⟩ @[to_additive] lemma coe_Inf (S : set (submonoid M)) : ((Inf S : submonoid M) : set M) = ⋂ s ∈ S, ↑s := rfl @[to_additive] lemma mem_Inf {S : set (submonoid M)} {x : M} : x ∈ Inf S ↔ ∀ p ∈ S, x ∈ p := set.mem_bInter_iff /-- Submonoids of a monoid form a complete lattice. -/ @[to_additive "The `add_submonoid`s of an `add_monoid` form a complete lattice."] instance : complete_lattice (submonoid M) := { le := (≤), lt := (<), bot := (⊥), bot_le := λ S x hx, (mem_bot.1 hx).symm ▸ S.one_mem, top := (⊤), le_top := λ S x hx, mem_top x, inf := (⊓), Inf := has_Inf.Inf, sup := λ a b, Inf {x | a ≤ x ∧ b ≤ x}, Sup := λ s, Inf {T | ∀ S ∈ s, S ≤ T}, le_sup_left := λ a b, λ x hx, mem_Inf.2 $ λ s hs, hs.1 hx, le_sup_right := λ a b, λ x hx, mem_Inf.2 $ λ s hs, hs.2 hx, sup_le := λ a b c ha hb x hx, mem_Inf.1 hx c ⟨ha, hb⟩, le_inf := λ a b c ha hb x hx, ⟨ha hx, hb hx⟩, inf_le_left := λ a b x, and.left, inf_le_right := λ a b x, and.right, le_Sup := λ s p hs x hx, mem_Inf.2 $ λ t ht, ht p hs hx, Sup_le := λ s p hs x hx, mem_Inf.1 hx p hs, le_Inf := λ s a ha x hx, mem_Inf.2 $ λ t ht, ha t ht hx, Inf_le := λ s a ha x hx, mem_Inf.1 hx _ ha, .. partial_order.lift (coe : submonoid M → set M) (λ a b, ext') (by apply_instance) } /-- The `submonoid` generated by a set. -/ @[to_additive "The `add_submonoid` generated by a set"] def closure (s : set M) : submonoid M := Inf {S | s ⊆ S} @[to_additive] lemma mem_closure {x : M} : x ∈ closure s ↔ ∀ S : submonoid M, s ⊆ S → x ∈ S := mem_Inf /-- The submonoid generated by a set includes the set. -/ @[simp, to_additive "The `add_submonoid` generated by a set includes the set."] lemma subset_closure : s ⊆ closure s := λ x hx, mem_closure.2 $ λ S hS, hS hx variable {S} open set /-- A submonoid `S` includes `closure s` if and only if it includes `s`. -/ @[simp, to_additive "An additive submonoid `S` includes `closure s` if and only if it includes `s`"] lemma closure_le : closure s ≤ S ↔ s ⊆ S := ⟨subset.trans subset_closure, λ h, Inf_le h⟩ /-- Submonoid closure of a set is monotone in its argument: if `s ⊆ t`, then `closure s ≤ closure t`. -/ @[to_additive "Additive submonoid closure of a set is monotone in its argument: if `s ⊆ t`, then `closure s ≤ closure t`"] lemma closure_mono ⦃s t : set M⦄ (h : s ⊆ t) : closure s ≤ closure t := closure_le.2 $ subset.trans h subset_closure @[to_additive] lemma closure_eq_of_le (h₁ : s ⊆ S) (h₂ : S ≤ closure s) : closure s = S := le_antisymm (closure_le.2 h₁) h₂ variable (S) /-- An induction principle for closure membership. If `p` holds for `1` and all elements of `s`, and is preserved under multiplication, then `p` holds for all elements of the closure of `s`. -/ @[to_additive "An induction principle for additive closure membership. If `p` holds for `0` and all elements of `s`, and is preserved under addition, then `p` holds for all elements of the additive closure of `s`."] lemma closure_induction {p : M → Prop} {x} (h : x ∈ closure s) (Hs : ∀ x ∈ s, p x) (H1 : p 1) (Hmul : ∀ x y, p x → p y → p (x * y)) : p x := (@closure_le _ _ _ ⟨p, H1, Hmul⟩).2 Hs h attribute [elab_as_eliminator] submonoid.closure_induction add_submonoid.closure_induction variable (M) /-- `closure` forms a Galois insertion with the coercion to set. -/ @[to_additive "`closure` forms a Galois insertion with the coercion to set."] protected def gi : galois_insertion (@closure M _) coe := { choice := λ s _, closure s, gc := λ s t, closure_le, le_l_u := λ s, subset_closure, choice_eq := λ s h, rfl } variable {M} /-- Closure of a submonoid `S` equals `S`. -/ @[simp, to_additive "Additive closure of an additive submonoid `S` equals `S`"] lemma closure_eq : closure (S : set M) = S := (submonoid.gi M).l_u_eq S @[simp, to_additive] lemma closure_empty : closure (∅ : set M) = ⊥ := (submonoid.gi M).gc.l_bot @[simp, to_additive] lemma closure_univ : closure (univ : set M) = ⊤ := @coe_top M _ ▸ closure_eq ⊤ @[to_additive] lemma closure_union (s t : set M) : closure (s ∪ t) = closure s ⊔ closure t := (submonoid.gi M).gc.l_sup @[to_additive] lemma closure_Union {ι} (s : ι → set M) : closure (⋃ i, s i) = ⨆ i, closure (s i) := (submonoid.gi M).gc.l_supr @[to_additive] lemma mem_supr_of_directed {ι} [hι : nonempty ι] {S : ι → submonoid M} (hS : directed (≤) S) {x : M} : x ∈ (supr S : submonoid M) ↔ ∃ i, x ∈ S i := begin refine ⟨_, λ ⟨i, hi⟩, (le_def.1 $ le_supr S i) hi⟩, suffices : x ∈ closure (⋃ i, (S i : set M)) → ∃ i, x ∈ S i, by simpa only [closure_Union, closure_eq (S _)] using this, refine (λ hx, closure_induction hx (λ _, mem_Union.1) _ _), { exact hι.elim (λ i, ⟨i, (S i).one_mem⟩) }, { rintros x y ⟨i, hi⟩ ⟨j, hj⟩, rcases hS i j with ⟨k, hki, hkj⟩, exact ⟨k, (S k).mul_mem (hki hi) (hkj hj)⟩ } end @[to_additive] lemma mem_Sup_of_directed_on {S : set (submonoid M)} (Sne : S.nonempty) (hS : directed_on (≤) S) {x : M} : x ∈ Sup S ↔ ∃ s ∈ S, x ∈ s := begin haveI : nonempty S := Sne.to_subtype, rw [Sup_eq_supr, supr_subtype', mem_supr_of_directed, subtype.exists], exact (directed_on_iff_directed _).1 hS end variables {N : Type*} [monoid N] {P : Type*} [monoid P] /-- The preimage of a submonoid along a monoid homomorphism is a submonoid. -/ @[to_additive "The preimage of an `add_submonoid` along an `add_monoid` homomorphism is an `add_submonoid`."] def comap (f : M →* N) (S : submonoid N) : submonoid M := { carrier := (f ⁻¹' S), one_mem' := show f 1 ∈ S, by rw f.map_one; exact S.one_mem, mul_mem' := λ a b ha hb, show f (a * b) ∈ S, by rw f.map_mul; exact S.mul_mem ha hb } @[simp, to_additive] lemma coe_comap (S : submonoid N) (f : M →* N) : (S.comap f : set M) = f ⁻¹' S := rfl @[simp, to_additive] lemma mem_comap {S : submonoid N} {f : M →* N} {x : M} : x ∈ S.comap f ↔ f x ∈ S := iff.rfl @[to_additive] lemma comap_comap (S : submonoid P) (g : N →* P) (f : M →* N) : (S.comap g).comap f = S.comap (g.comp f) := rfl /-- The image of a submonoid along a monoid homomorphism is a submonoid. -/ @[to_additive "The image of an `add_submonoid` along an `add_monoid` homomorphism is an `add_submonoid`."] def map (f : M →* N) (S : submonoid M) : submonoid N := { carrier := (f '' S), one_mem' := ⟨1, S.one_mem, f.map_one⟩, mul_mem' := begin rintros _ _ ⟨x, hx, rfl⟩ ⟨y, hy, rfl⟩, exact ⟨x * y, S.mul_mem hx hy, by rw f.map_mul; refl⟩ end } @[simp, to_additive] lemma coe_map (f : M →* N) (S : submonoid M) : (S.map f : set N) = f '' S := rfl @[simp, to_additive] lemma mem_map {f : M →* N} {S : submonoid M} {y : N} : y ∈ S.map f ↔ ∃ x ∈ S, f x = y := mem_image_iff_bex @[to_additive] lemma map_map (g : N →* P) (f : M →* N) : (S.map f).map g = S.map (g.comp f) := ext' $ image_image _ _ _ @[to_additive] lemma map_le_iff_le_comap {f : M →* N} {S : submonoid M} {T : submonoid N} : S.map f ≤ T ↔ S ≤ T.comap f := image_subset_iff @[to_additive] lemma gc_map_comap (f : M →* N) : galois_connection (map f) (comap f) := λ S T, map_le_iff_le_comap @[to_additive] lemma map_sup (S T : submonoid M) (f : M →* N) : (S ⊔ T).map f = S.map f ⊔ T.map f := (gc_map_comap f).l_sup @[to_additive] lemma map_supr {ι : Sort*} (f : M →* N) (s : ι → submonoid M) : (supr s).map f = ⨆ i, (s i).map f := (gc_map_comap f).l_supr @[to_additive] lemma comap_inf (S T : submonoid N) (f : M →* N) : (S ⊓ T).comap f = S.comap f ⊓ T.comap f := (gc_map_comap f).u_inf @[to_additive] lemma comap_infi {ι : Sort*} (f : M →* N) (s : ι → submonoid N) : (infi s).comap f = ⨅ i, (s i).comap f := (gc_map_comap f).u_infi @[simp, to_additive] lemma map_bot (f : M →* N) : (⊥ : submonoid M).map f = ⊥ := (gc_map_comap f).l_bot @[simp, to_additive] lemma comap_top (f : M →* N) : (⊤ : submonoid N).comap f = ⊤ := (gc_map_comap f).u_top /-- Given `submonoid`s `s`, `t` of monoids `M`, `N` respectively, `s × t` as a submonoid of `M × N`. -/ @[to_additive prod "Given `add_submonoid`s `s`, `t` of `add_monoid`s `A`, `B` respectively, `s × t` as an `add_submonoid` of `A × B`."] def prod (s : submonoid M) (t : submonoid N) : submonoid (M × N) := { carrier := (s : set M).prod t, one_mem' := ⟨s.one_mem, t.one_mem⟩, mul_mem' := λ p q hp hq, ⟨s.mul_mem hp.1 hq.1, t.mul_mem hp.2 hq.2⟩ } @[to_additive coe_prod] lemma coe_prod (s : submonoid M) (t : submonoid N) : (s.prod t : set (M × N)) = (s : set M).prod (t : set N) := rfl @[to_additive mem_prod] lemma mem_prod {s : submonoid M} {t : submonoid N} {p : M × N} : p ∈ s.prod t ↔ p.1 ∈ s ∧ p.2 ∈ t := iff.rfl @[to_additive prod_mono] lemma prod_mono : ((≤) ⇒ (≤) ⇒ (≤)) (@prod M _ N _) (@prod M _ N _) := λ s s' hs t t' ht, set.prod_mono hs ht @[to_additive prod_mono_right] lemma prod_mono_right (s : submonoid M) : monotone (λ t : submonoid N, s.prod t) := prod_mono (le_refl s) @[to_additive prod_mono_left] lemma prod_mono_left (t : submonoid N) : monotone (λ s : submonoid M, s.prod t) := λ s₁ s₂ hs, prod_mono hs (le_refl t) @[to_additive prod_top] lemma prod_top (s : submonoid M) : s.prod (⊤ : submonoid N) = s.comap (monoid_hom.fst M N) := ext $ λ x, by simp [mem_prod, monoid_hom.coe_fst] @[to_additive top_prod] lemma top_prod (s : submonoid N) : (⊤ : submonoid M).prod s = s.comap (monoid_hom.snd M N) := ext $ λ x, by simp [mem_prod, monoid_hom.coe_snd] @[simp, to_additive top_prod_top] lemma top_prod_top : (⊤ : submonoid M).prod (⊤ : submonoid N) = ⊤ := (top_prod _).trans $ comap_top _ @[to_additive] lemma bot_prod_bot : (⊥ : submonoid M).prod (⊥ : submonoid N) = ⊥ := ext' $ by simp [coe_prod, prod.one_eq_mk] /-- Product of submonoids is isomorphic to their product as monoids. -/ @[to_additive prod_equiv "Product of additive submonoids is isomorphic to their product as additive monoids"] def prod_equiv (s : submonoid M) (t : submonoid N) : s.prod t ≃* s × t := { map_mul' := λ x y, rfl, .. equiv.set.prod ↑s ↑t } end submonoid namespace monoid_hom variables {N : Type*} {P : Type*} [monoid N] [monoid P] (S : submonoid M) open submonoid /-- The range of a monoid homomorphism is a submonoid. -/ @[to_additive "The range of an `add_monoid_hom` is an `add_submonoid`."] def mrange (f : M →* N) : submonoid N := (⊤ : submonoid M).map f @[simp, to_additive] lemma coe_mrange (f : M →* N) : (f.mrange : set N) = set.range f := set.image_univ @[simp, to_additive] lemma mem_mrange {f : M →* N} {y : N} : y ∈ f.mrange ↔ ∃ x, f x = y := by simp [mrange] @[to_additive] lemma map_mrange (g : N →* P) (f : M →* N) : f.mrange.map g = (g.comp f).mrange := (⊤ : submonoid M).map_map g f /-- Restriction of a monoid hom to a submonoid of the domain. -/ @[to_additive "Restriction of an add_monoid hom to an `add_submonoid` of the domain."] def restrict {N : Type*} [monoid N] (f : M →* N) (S : submonoid M) : S →* N := f.comp S.subtype @[to_additive] lemma restrict_apply {N : Type*} [monoid N] (f : M →* N) (x : S) : f.restrict S x = f x := rfl @[simp, to_additive] lemma restrict_eq {N : Type} [monoid N] (f : M →* N) (x) : f.restrict S x = f x := rfl /-- Restriction of a monoid hom to a submonoid of the codomain. -/ @[to_additive "Restriction of an `add_monoid` hom to an `add_submonoid` of the codomain."] def cod_restrict (f : M →* N) (S : submonoid N) (h : ∀ x, f x ∈ S) : M →* S := { to_fun := λ n, ⟨f n, h n⟩, map_one' := subtype.eq f.map_one, map_mul' := λ x y, subtype.eq (f.map_mul x y) } /-- Restriction of a monoid hom to its range iterpreted as a submonoid. -/ @[to_additive "Restriction of an `add_monoid` hom to its range interpreted as a submonoid."] def range_restrict {N} [monoid N] (f : M →* N) : M →* f.mrange := f.cod_restrict f.mrange $ λ x, ⟨x, submonoid.mem_top x, rfl⟩ @[simp, to_additive] lemma coe_range_restrict {N} [monoid N] (f : M →* N) (x : M) : (f.range_restrict x : N) = f x := rfl @[to_additive] lemma mrange_top_iff_surjective {N} [monoid N] {f : M →* N} : f.mrange = (⊤ : submonoid N) ↔ function.surjective f := submonoid.ext'_iff.trans $ iff.trans (by rw [coe_mrange, coe_top]) set.range_iff_surjective /-- The range of a surjective monoid hom is the whole of the codomain. -/ @[to_additive "The range of a surjective `add_monoid` hom is the whole of the codomain."] lemma mrange_top_of_surjective {N} [monoid N] (f : M →* N) (hf : function.surjective f) : f.mrange = (⊤ : submonoid N) := mrange_top_iff_surjective.2 hf /-- The submonoid of elements `x : M` such that `f x = g x` -/ @[to_additive "The additive submonoid of elements `x : M` such that `f x = g x`"] def eq_mlocus (f g : M →* N) : submonoid M := { carrier := {x | f x = g x}, one_mem' := by rw [set.mem_set_of_eq, f.map_one, g.map_one], mul_mem' := λ x y (hx : _ = _) (hy : _ = _), by simp [*] } /-- If two monoid homomorphisms are equal on a set, then they are equal on its submonoid closure. -/ @[to_additive] lemma eq_on_mclosure {f g : M →* N} {s : set M} (h : set.eq_on f g s) : set.eq_on f g (closure s) := show closure s ≤ f.eq_mlocus g, from closure_le.2 h @[to_additive] lemma eq_of_eq_on_mtop {f g : M →* N} (h : set.eq_on f g (⊤ : submonoid M)) : f = g := ext $ λ x, h trivial @[to_additive] lemma eq_of_eq_on_mdense {s : set M} (hs : closure s = ⊤) {f g : M →* N} (h : s.eq_on f g) : f = g := eq_of_eq_on_mtop $ hs ▸ eq_on_mclosure h @[to_additive] lemma closure_preimage_le (f : M →* N) (s : set N) : closure (f ⁻¹' s) ≤ (closure s).comap f := closure_le.2 $ λ x hx, mem_coe.2 $ mem_comap.2 $ subset_closure hx /-- The image under a monoid hom of the submonoid generated by a set equals the submonoid generated by the image of the set. -/ @[to_additive "The image under an `add_monoid` hom of the `add_submonoid` generated by a set equals the `add_submonoid` generated by the image of the set."] lemma map_mclosure (f : M →* N) (s : set M) : (closure s).map f = closure (f '' s) := le_antisymm (map_le_iff_le_comap.2 $ le_trans (closure_mono $ set.subset_preimage_image _ _) (closure_preimage_le _ _)) (closure_le.2 $ set.image_subset _ subset_closure) end monoid_hom namespace free_monoid variables {α : Type*} open submonoid @[to_additive] theorem closure_range_of : closure (set.range $ @of α) = ⊤ := begin refine eq_top_iff.2 (λ x hx, _), induction x with hd tl ih, { from one_mem _ }, { rw ← of_mul_eq_cons, exact mul_mem _ (subset_closure $ set.mem_range_self _) (ih trivial) } end end free_monoid namespace submonoid variables {N : Type*} [monoid N] open monoid_hom lattice /-- The monoid hom associated to an inclusion of submonoids. -/ @[to_additive "The `add_monoid` hom associated to an inclusion of submonoids."] def inclusion {S T : submonoid M} (h : S ≤ T) : S →* T := S.subtype.cod_restrict _ (λ x, h x.2) @[simp, to_additive] lemma range_subtype (s : submonoid M) : s.subtype.mrange = s := ext' $ (coe_mrange _).trans $ set.range_coe_subtype s lemma closure_singleton_eq (x : M) : closure ({x} : set M) = (powers_hom M x).mrange := closure_eq_of_le (set.singleton_subset_iff.2 ⟨multiplicative.of_add 1, trivial, pow_one x⟩) $ λ x ⟨n, _, hn⟩, hn ▸ pow_mem _ (subset_closure $ set.mem_singleton _) _ /-- The submonoid generated by an element of a monoid equals the set of natural number powers of the element. -/ lemma mem_closure_singleton {x y : M} : y ∈ closure ({x} : set M) ↔ ∃ n:ℕ, x^n=y := by rw [closure_singleton_eq, mem_mrange]; refl @[to_additive] lemma closure_eq_mrange (s : set M) : closure s = (free_monoid.lift s M coe).mrange := by rw [mrange, ← free_monoid.closure_range_of, map_mclosure, ← set.range_comp, free_monoid.lift_comp_of, set.range_coe_subtype] @[to_additive] lemma exists_list_of_mem_closure {s : set M} {x : M} (hx : x ∈ closure s) : ∃ (l : list M) (hl : ∀ y ∈ l, y ∈ s), l.prod = x := begin rw [closure_eq_mrange, mem_mrange] at hx, rcases hx with ⟨l, hx⟩, exact ⟨list.map coe l, λ y hy, let ⟨z, hz, hy⟩ := list.mem_map.1 hy in hy ▸ z.2, hx⟩ end @[to_additive] lemma map_inl (s : submonoid M) : s.map (inl M N) = s.prod ⊥ := ext $ λ p, ⟨λ ⟨x, hx, hp⟩, hp ▸ ⟨hx, set.mem_singleton 1⟩, λ ⟨hps, hp1⟩, ⟨p.1, hps, prod.ext rfl $ (set.eq_of_mem_singleton hp1).symm⟩⟩ @[to_additive] lemma map_inr (s : submonoid N) : s.map (inr M N) = prod ⊥ s := ext $ λ p, ⟨λ ⟨x, hx, hp⟩, hp ▸ ⟨set.mem_singleton 1, hx⟩, λ ⟨hp1, hps⟩, ⟨p.2, hps, prod.ext (set.eq_of_mem_singleton hp1).symm rfl⟩⟩ @[to_additive] lemma range_inl : (inl M N).mrange = prod ⊤ ⊥ := map_inl ⊤ @[to_additive] lemma range_inr : (inr M N).mrange = prod ⊥ ⊤ := map_inr ⊤ @[to_additive] lemma range_inl' : (inl M N).mrange = comap (snd M N) ⊥ := range_inl.trans (top_prod _) @[to_additive] lemma range_inr' : (inr M N).mrange = comap (fst M N) ⊥ := range_inr.trans (prod_top _) @[simp, to_additive] lemma range_fst : (fst M N).mrange = ⊤ := (fst M N).mrange_top_of_surjective $ @prod.fst_surjective _ _ ⟨1⟩ @[simp, to_additive] lemma range_snd : (snd M N).mrange = ⊤ := (snd M N).mrange_top_of_surjective $ @prod.snd_surjective _ _ ⟨1⟩ @[simp, to_additive prod_bot_sup_bot_prod] lemma prod_bot_sup_bot_prod (s : submonoid M) (t : submonoid N) : (s.prod ⊥) ⊔ (prod ⊥ t) = s.prod t := le_antisymm (sup_le (prod_mono_right s bot_le) (prod_mono_left t bot_le)) $ assume p hp, prod.fst_mul_snd p ▸ mul_mem _ ((le_sup_left : s.prod ⊥ ≤ s.prod ⊥ ⊔ prod ⊥ t) ⟨hp.1, set.mem_singleton 1⟩) ((le_sup_right : prod ⊥ t ≤ s.prod ⊥ ⊔ prod ⊥ t) ⟨set.mem_singleton 1, hp.2⟩) @[simp, to_additive] lemma range_inl_sup_range_inr : (inl M N).mrange ⊔ (inr M N).mrange = ⊤ := by simp only [range_inl, range_inr, prod_bot_sup_bot_prod, top_prod_top] end submonoid namespace submonoid variables {N : Type*} [comm_monoid N] open monoid_hom @[to_additive] lemma sup_eq_range (s t : submonoid N) : s ⊔ t = (s.subtype.coprod t.subtype).mrange := by rw [mrange, ← range_inl_sup_range_inr, map_sup, map_mrange, coprod_comp_inl, map_mrange, coprod_comp_inr, range_subtype, range_subtype] @[to_additive] lemma mem_sup {s t : submonoid N} {x : N} : x ∈ s ⊔ t ↔ ∃ (y ∈ s) (z ∈ t), y * z = x := by simp only [sup_eq_range, mem_mrange, coprod_apply, prod.exists, submonoid.exists, coe_subtype, subtype.coe_mk] end submonoid namespace add_submonoid open set lemma smul_mem (S : add_submonoid A) {x : A} (hx : x ∈ S) : ∀ n : ℕ, add_monoid.smul n x ∈ S | 0 := S.zero_mem | (n+1) := S.add_mem hx (smul_mem n) lemma closure_singleton_eq (x : A) : closure ({x} : set A) = (multiples_hom A x).mrange := closure_eq_of_le (set.singleton_subset_iff.2 ⟨1, trivial, add_monoid.one_smul x⟩) $ λ x ⟨n, _, hn⟩, hn ▸ smul_mem _ (subset_closure $ set.mem_singleton _) _ /-- The `add_submonoid` generated by an element of an `add_monoid` equals the set of natural number multiples of the element. -/ lemma mem_closure_singleton {x y : A} : y ∈ closure ({x} : set A) ↔ ∃ n:ℕ, add_monoid.smul n x = y := by rw [closure_singleton_eq, add_monoid_hom.mem_mrange]; refl end add_submonoid namespace mul_equiv variables {S T : submonoid M} /-- Makes the identity isomorphism from a proof two submonoids of a multiplicative monoid are equal. -/ @[to_additive add_submonoid_congr "Makes the identity additive isomorphism from a proof two submonoids of an additive monoid are equal."] def submonoid_congr (h : S = T) : S ≃* T := { map_mul' := λ _ _, rfl, ..equiv.set_congr $ submonoid.ext'_iff.1 h } end mul_equiv
d6820b4d01b7ea3bbc19f62343238ada2e738acc
99b36386640f67a61e85dddccbc0f82edec9bf9c
/src/pushouts.lean
3245b402850700f5982b91e4bb4757e1d8aab0c6
[]
no_license
aymonwuolanne/lean-theorem-proving
1ba46fb89f446b78b7f8f8cb084aad68fadce9a3
701a7873f9f66f2c24962b02450ec90b20935702
refs/heads/master
1,586,068,982,414
1,575,091,205,000
1,575,091,205,000
156,647,753
0
0
null
null
null
null
UTF-8
Lean
false
false
2,083
lean
import category_theory.instances.topological_spaces import category_theory.limits.pullbacks import category_theory.const import topology.continuity open category_theory.instances open category_theory.limits open category_theory.functor open category_theory open sum universe u noncomputable theory variables {X Y Z : Top.{u}} variables (f : X ⟶ Y) (g : X ⟶ Z) -- in the following diagram P is the pushout we wish to construct -- X ⟶ Y -- ↓ ↓ -- Z ⟶ P -- this relation identifies any x and y that are the image of the same -- point in X def r (x : sum Y.α Z.α) (y : sum Y.α Z.α) : Prop := x = y ∨ ∃ a : X.α, inl (f.val a) = x ∧ inr (g.val a) = y def P : Top := { α := quot (r f g), str := by apply_instance} -- inclusion maps from Y and Z into the pushout P def i_Y : Y ⟶ P f g := { val := quot.mk (r f g) ∘ inl, property := continuous.comp continuous_inl continuous_quot_mk } def i_Z : Z ⟶ P f g := { val := quot.mk (r f g) ∘ inr, property := continuous.comp continuous_inr continuous_quot_mk } lemma natural : f ≫ (i_Y f g) = g ≫ (i_Z f g) := subtype.eq begin rw [concrete_category_comp, i_Y, i_Z], dsimp, ext, rw [function.comp.assoc], apply quot.sound, exact or.inr ⟨ x, ⟨ rfl, rfl ⟩ ⟩, end def Top.nat_trans_app (A : walking_span) : (span f g).obj A ⟶ ((const walking_span).obj (P f g)).obj A := match A with | walking_span.zero := f ≫ (i_Y f g) | walking_span.left := i_Y f g | walking_span.right := i_Z f g end def Top.nat_trans : span f g ⟹ (const walking_span).obj (P f g) := { app := Top.nat_trans_app f g, naturality' := sorry } def topcat : category Top := by apply_instance -- cosquare := λ f g, something of type cocone (span f g) -- span f g is a functor from walking_span.{v} to Top -- cocone (F : J ⥤ Top) is a structure taking an object X : Top and -- a natural transformation ι taking F to (const J).obj X -- natural transformations have an app field and a naturality' field instance toppush : @has_pushouts Top topcat := { cosquare := sorry, is_pushout := sorry }
01b08b9f962e5cb3cb2b6795026380138ec2ef41
947b78d97130d56365ae2ec264df196ce769371a
/tests/lean/run/meta1.lean
738be58f53e9b6f0963fe6faf1e9a284a5c1211e
[ "Apache-2.0" ]
permissive
shyamalschandra/lean4
27044812be8698f0c79147615b1d5090b9f4b037
6e7a883b21eaf62831e8111b251dc9b18f40e604
refs/heads/master
1,671,417,126,371
1,601,859,995,000
1,601,860,020,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
5,066
lean
import Lean.Meta new_frontend open Lean open Lean.Meta unsafe def tstInferType (mods : List Name) (e : Expr) : IO Unit := withImportModules (mods.map $ fun m => {module := m}) 0 fun env => do let (type, _, _) ← (inferType e : MetaM _).toIO {} { env := env } {} {}; IO.println (toString e ++ " : " ++ toString type) unsafe def tstWHNF (mods : List Name) (e : Expr) (t := TransparencyMode.default) : IO Unit := withImportModules (mods.map $ fun m => {module := m}) 0 fun env => do let (s, _, _) ← (whnf e : MetaM _).toIO {} { env := env }; IO.println (toString e ++ " ==> " ++ toString s) unsafe def tstIsProp (mods : List Name) (e : Expr) : IO Unit := withImportModules (mods.map $ fun m => {module := m}) 0 fun env => do let (b, _, _) ← (isProp e : MetaM _).toIO {} { env := env }; IO.println (toString e ++ ", isProp: " ++ toString b) def t1 : Expr := let map := mkConst `List.map [levelOne, levelOne]; let nat := mkConst `Nat []; let bool := mkConst `Bool []; mkAppN map #[nat, bool] #eval tstInferType [`Init.Data.List] t1 def t2 : Expr := let prop := mkSort levelZero; mkForall `x BinderInfo.default prop prop #eval tstInferType [`Init.Core] t2 def t3 : Expr := let nat := mkConst `Nat []; let natLe := mkConst `Nat.le []; let zero := mkLit (Literal.natVal 0); let p := mkAppN natLe #[mkBVar 0, zero]; mkForall `x BinderInfo.default nat p #eval tstInferType [`Init.Data.Nat] t3 def t4 : Expr := let nat := mkConst `Nat []; let p := mkAppN (mkConst `Nat.succ []) #[mkBVar 0]; mkLambda `x BinderInfo.default nat p #eval tstInferType [`Init.Core] t4 def t5 : Expr := let add := mkConst `Nat.add []; mkAppN add #[mkLit (Literal.natVal 3), mkLit (Literal.natVal 5)] #eval tstWHNF [`Init.Data.Nat] t5 #eval tstWHNF [`Init.Data.Nat] t5 TransparencyMode.reducible set_option pp.all true #check @List.cons Nat def t6 : Expr := let map := mkConst `List.map [levelOne, levelOne]; let nat := mkConst `Nat []; let add := mkConst `Nat.add []; let f := mkLambda `x BinderInfo.default nat (mkAppN add #[mkBVar 0, mkLit (Literal.natVal 1)]); let cons := mkApp (mkConst `List.cons [levelZero]) nat; let nil := mkApp (mkConst `List.nil [levelZero]) nat; let one := mkLit (Literal.natVal 1); let four := mkLit (Literal.natVal 4); let xs := mkApp (mkApp cons one) (mkApp (mkApp cons four) nil); mkAppN map #[nat, nat, f, xs] #eval tstInferType [`Init.Data.List] t6 #eval tstWHNF [`Init.Data.List] t6 #eval tstInferType [] $ mkSort levelZero #eval tstInferType [`Init.Data.List] $ mkLambda `a BinderInfo.implicit (mkSort levelOne) (mkLambda `x BinderInfo.default (mkBVar 0) (mkLambda `xs BinderInfo.default (mkApp (mkConst `List [levelZero]) (mkBVar 1)) (mkBVar 0))) def t7 : Expr := let nat := mkConst `Nat []; let one := mkLit (Literal.natVal 1); mkLet `x nat one one #eval tstInferType [`Init.Core] $ t7 #eval tstWHNF [`Init.Core] $ t7 def t8 : Expr := let nat := mkConst `Nat []; let one := mkLit (Literal.natVal 1); let add := mkConst `Nat.add []; mkLet `x nat one (mkAppN add #[one, mkBVar 0]) #eval tstInferType [`Init.Core] $ t8 #eval tstWHNF [`Init.Core] $ t8 def t9 : Expr := let nat := mkConst `Nat []; mkLet `a (mkSort levelOne) nat (mkForall `x BinderInfo.default (mkBVar 0) (mkBVar 1)) #eval tstInferType [`Init.Core] $ t9 #eval tstWHNF [`Init.Core] $ t9 #eval tstInferType [`Init.Core] $ mkLit (Literal.natVal 10) #eval tstInferType [`Init.Core] $ mkLit (Literal.strVal "hello") #eval tstInferType [`Init.Core] $ mkMData {} $ mkLit (Literal.natVal 10) #eval tstInferType [`Lean.Util.Trace] (mkProj `Inhabited 0 (mkConst `Lean.TraceState.Inhabited [])) #eval tstInferType [`Lean.Util.Trace] (mkProj `Lean.TraceState 0 (mkProj `Inhabited 0 (mkConst `Lean.TraceState.Inhabited []))) #eval tstWHNF [`Lean.Util.Trace] (mkProj `Inhabited 0 (mkConst `Lean.TraceState.Inhabited [])) #eval tstWHNF [`Lean.Util.Trace] (mkProj `Lean.TraceState 0 (mkProj `Inhabited 0 (mkConst `Lean.TraceState.Inhabited []))) def t10 : Expr := let nat := mkConst `Nat []; let refl := mkApp (mkConst `Eq.refl [levelOne]) nat; mkLambda `a BinderInfo.default nat (mkApp refl (mkBVar 0)) #eval tstInferType [`Init.Core] t10 #eval tstIsProp [`Init.Core] t10 #eval tstIsProp [`Init.Core] (mkAppN (mkConst `And []) #[mkConst `True [], mkConst `True []]) #eval tstIsProp [`Init.Core] (mkConst `And []) -- Example where isPropQuick fails #eval tstIsProp [`Init.Core] (mkAppN (mkConst `id [levelZero]) #[mkSort levelZero, mkAppN (mkConst `And []) #[mkConst `True [], mkConst `True []]]) #eval tstIsProp [`Init.Core] (mkAppN (mkConst `Eq [levelOne]) #[mkConst `Nat [], mkLit (Literal.natVal 0), mkLit (Literal.natVal 1)]) #eval tstIsProp [`Init.Core] $ mkForall `x BinderInfo.default (mkConst `Nat []) (mkAppN (mkConst `Eq [levelOne]) #[mkConst `Nat [], mkBVar 0, mkLit (Literal.natVal 1)]) #eval tstIsProp [`Init.Core] $ mkApp (mkLambda `x BinderInfo.default (mkConst `Nat []) (mkAppN (mkConst `Eq [levelOne]) #[mkConst `Nat [], mkBVar 0, mkLit (Literal.natVal 1)])) (mkLit (Literal.natVal 0))
bbbcc4abf11d3d9587294f4556b8c6878247ae00
737dc4b96c97368cb66b925eeea3ab633ec3d702
/stage0/src/Lean/Meta.lean
2c23fb1ca3d0d0c56e461a8eb4893a93e3b59e26
[ "Apache-2.0" ]
permissive
Bioye97/lean4
1ace34638efd9913dc5991443777b01a08983289
bc3900cbb9adda83eed7e6affeaade7cfd07716d
refs/heads/master
1,690,589,820,211
1,631,051,000,000
1,631,067,598,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,110
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 import Lean.Meta.LevelDefEq import Lean.Meta.WHNF import Lean.Meta.InferType import Lean.Meta.FunInfo import Lean.Meta.ExprDefEq import Lean.Meta.DiscrTree import Lean.Meta.Reduce import Lean.Meta.Instances import Lean.Meta.AbstractMVars import Lean.Meta.SynthInstance import Lean.Meta.AppBuilder import Lean.Meta.Tactic import Lean.Meta.KAbstract import Lean.Meta.RecursorInfo import Lean.Meta.GeneralizeTelescope import Lean.Meta.Match import Lean.Meta.ReduceEval import Lean.Meta.Closure import Lean.Meta.AbstractNestedProofs import Lean.Meta.ForEachExpr import Lean.Meta.Transform import Lean.Meta.PPGoal import Lean.Meta.UnificationHint import Lean.Meta.Inductive import Lean.Meta.SizeOf import Lean.Meta.IndPredBelow import Lean.Meta.Coe import Lean.Meta.SortLocalDecls import Lean.Meta.CollectFVars import Lean.Meta.GeneralizeVars import Lean.Meta.Injective import Lean.Meta.Structure import Lean.Meta.Constructions
e54dd440d7723f8d30a54f11ad5da830d61b6913
a25cc44b447f2fbde61e4b848318762eb892f2bf
/src/subdiv.lean
ac4f3e0b4d12de43dcb5e68457d7b4926844820e
[]
no_license
NeilStrickland/itloc
20f9b9bcaa4d5840f7f32e84108174b294d84b1a
5b13b5b418766d10926b983eb3dd2ac42abf63d8
refs/heads/master
1,592,747,030,159
1,578,138,004,000
1,578,138,004,000
197,470,135
2
0
null
null
null
null
UTF-8
Lean
false
false
19,444
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 poset `P`, we define `subdiv P` to be the poset of finite nonempty chains `s ⊆ P`. Any such `s` has a largest element, and the map `max : (subdiv P) → P` is a morphism of posets. There is an approach to the homotopy theory of finite complexes based on finite posets, and the above map `max` plays a key role in this. -/ import data.list.sort import basic sort_rank universes uP uQ uR uS variables (P : Type uP) [partial_order P] [decidable_eq P] variables (Q : Type uQ) [partial_order Q] [decidable_eq Q] variables (R : Type uR) [partial_order R] [decidable_eq R] variables (S : Type uS) [partial_order S] [decidable_eq S] variable [decidable_rel (has_le.le : P → P → Prop)] variable [decidable_rel (has_le.le : Q → Q → Prop)] variable [decidable_rel (has_le.le : R → R → Prop)] variable [decidable_rel (has_le.le : S → S → Prop)] namespace poset open poset variable {P} /-- Definition of chains LaTeX: defn-subdiv -/ def is_chain (s : finset P) : Prop := ∀ (p ∈ s) (q ∈ s), (p ≤ q ∨ q ≤ p) instance decidable_is_chain (s : finset P) : decidable (is_chain s) := by { unfold is_chain, apply_instance } /-- Definition of simplices as nonempty chains LaTeX: defn-subdiv -/ def is_simplex (s : finset P) : Prop := s ≠ ∅ ∧ (is_chain s) instance decidable_is_simplex (s : finset P) : decidable (is_simplex s) := by { unfold is_simplex, apply_instance } variable (P) /-- Definition of subdiv P as a type LaTeX: defn-subdiv -/ def subdiv := {s : finset P // is_simplex s} /-- Vertices as 0-simplices -/ variable {P} def vertex (p : P) : subdiv P := ⟨ finset.singleton p, begin split, {exact finset.ne_empty_of_mem (finset.mem_singleton_self p)}, {intros x hx y hy, rw [finset.mem_singleton.mp hx, finset.mem_singleton.mp hy], left, exact le_refl p } end⟩ variable (P) namespace subdiv instance : decidable_eq (subdiv P) := by { unfold subdiv, apply_instance } /-- Definition of the partial order on subdiv P LaTeX: defn-subdiv -/ instance : partial_order (subdiv P) := { le := λ s t, s.val ⊆ t.val, le_refl := λ s, (le_refl s.val), le_antisymm := λ s t hst hts, subtype.eq (le_antisymm hst hts), le_trans := λ s t u (hst : s.val ⊆ t.val) (htu : t.val ⊆ u.val) p hs, (htu (hst hs)) } instance decidable_le : decidable_rel (has_le.le : (subdiv P) → (subdiv P) → Prop) := λ s t, by { apply_instance } variable {P} /-- Definition of the dimension of a simplex, as one less than the cardinality. We use the predecessor operation on natural numbers, which sends zero to zero. Because of this, we need a small argument to show that the cardinality is strictly positive and thus equal to one more than the dimension. LaTeX: defn-subdiv -/ def dim (s : subdiv P) : ℕ := s.val.card.pred lemma card_eq (s : subdiv P) : s.val.card = s.dim.succ := begin by_cases h : s.val.card = 0, { exact (s.property.left (finset.card_eq_zero.mp h)).elim }, { replace h := nat.pos_of_ne_zero h, exact (nat.succ_pred_eq_of_pos h).symm } end /-- The dimension function dim : subdiv P → ℕ is monotone. -/ lemma dim_mono : monotone (dim : (subdiv P) → ℕ) := begin intros s t hst, let h := finset.card_le_of_subset hst, rw[card_eq,card_eq] at h, exact nat.le_of_succ_le_succ h end /-- If we have simplices s ≤ t with dim s ≥ dim t then s = t. -/ lemma eq_of_le_of_dim_ge (s t : subdiv P) (hst : s ≤ t) (hd : s.dim ≥ t.dim) : s = t := begin let hc := nat.succ_le_succ hd, rw [← card_eq, ← card_eq] at hc, exact subtype.eq (finset.eq_of_subset_of_card_le hst hc) end /-- This allows us to treat a simplex as a type in its own right. -/ instance : has_coe_to_sort (subdiv P) := ⟨_,λ s, {p : P // p ∈ s.val}⟩ section els variable (s : subdiv P) instance els_decidable_eq : decidable_eq s := by { apply_instance } instance els_fintype : fintype s := by { apply_instance } lemma card_eq' : fintype.card s = s.dim.succ := (fintype.card_coe s.val).trans s.card_eq /-- If s is a simplex, we can treat it as a linearly ordered set. -/ instance els_order : decidable_linear_order s := { le := λ p q,p.val ≤ q.val, le_refl := λ p, ((le_refl (p.val : P)) : p.val ≤ p.val), le_antisymm := λ p q (hpq : p.val ≤ q.val) (hqp : q.val ≤ p.val), subtype.eq (le_antisymm hpq hqp), le_trans := λ p q r (hpq : p.val ≤ q.val) (hqr : q.val ≤ r.val), le_trans hpq hqr, le_total := λ p q,s.property.right p.val p.property q.val q.property, lt := λ p q,p.val < q.val, lt_iff_le_not_le := λ p q, begin change p.val < q.val ↔ p.val ≤ q.val ∧ ¬ q.val ≤ p.val, apply lt_iff_le_not_le, end, decidable_le := λ p q, by { apply_instance } } variable {s} /-- The inclusion of a simplex in the full poset P. -/ def inc : s → P := λ p, p.val /-- The inclusion map is injective. -/ lemma inc_inj (p₀ p₁ : s) : (inc p₀) = (inc p₁) → p₀ = p₁ := subtype.eq /-- The inclusion map is monotone. -/ lemma inc_mono : monotone (inc : s → P) := λ p₀ p₁ hp, hp variable (s) variables {d : ℕ} (e : s.dim = d) /-- If dim s = d, then we have a canonical bijection from s to the set fin d.succ = { 0,1,...,d }. We define rank_equiv s to be a package consisting of this bijection and its inverse. We define seq s and rank s to be auxiliary functions defined in terms of rank_equiv s, and we prove some lemmas about the behaviour of these. -/ def rank_equiv : s ≃ fin d.succ := fintype.rank_equiv (s.card_eq'.trans (congr_arg nat.succ e)) def seq : (fin d.succ) → P := λ i, inc ((rank_equiv s e).inv_fun i) def rank (p : P) (hp : p ∈ s.val) : fin d.succ := (rank_equiv s e).to_fun ⟨p,hp⟩ lemma seq_mem (i : fin d.succ) : seq s e i ∈ s.val := ((rank_equiv s e).inv_fun i).property lemma seq_rank (p : P) (hp : p ∈ s.val) : seq s e (rank s e p hp) = p := congr_arg inc ((rank_equiv s e).left_inv ⟨p,hp⟩) lemma seq_eq (i : fin d.succ) : ((rank_equiv s e).inv_fun i) = ⟨seq s e i,seq_mem s e i⟩ := by { apply subtype.eq, refl } lemma rank_seq (i : fin d.succ) : rank s e (seq s e i) (seq_mem s e i) = i := begin dsimp [rank], rw [← seq_eq, (rank_equiv s e).right_inv] end lemma seq_le (i₀ i₁ : fin d.succ) : i₀ ≤ i₁ ↔ seq s e i₀ ≤ seq s e i₁ := fintype.seq_le (s.card_eq'.trans (congr_arg nat.succ e)) i₀ i₁ lemma seq_lt (i₀ i₁ : fin d.succ) : i₀ < i₁ ↔ seq s e i₀ < seq s e i₁ := fintype.seq_lt (s.card_eq'.trans (congr_arg nat.succ e)) i₀ i₁ variables {P Q} def map (f : poset.hom P Q) : (poset.hom (subdiv P) (subdiv Q)) := begin let sf : subdiv P → subdiv Q := λ s, begin let t0 : finset Q := s.val.image f.val, have : is_simplex t0 := begin split, { rcases finset.exists_mem_of_ne_empty s.property.1 with ⟨p,p_in_s⟩, exact finset.ne_empty_of_mem (finset.mem_image_of_mem f.val p_in_s) }, { intros q₀ hq₀ q₁ hq₁, rcases finset.mem_image.mp hq₀ with ⟨p₀,hp₀,hfp₀⟩, rcases finset.mem_image.mp hq₁ with ⟨p₁,hp₁,hfp₁⟩, rw [← hfp₀, ← hfp₁], rcases s.property.2 p₀ hp₀ p₁ hp₁ with h₀₁ | h₁₀, { left, exact f.property h₀₁ }, { right, exact f.property h₁₀ } } end, exact ⟨t0,this⟩ end, have : monotone sf := λ s₀ s₁ hs, begin change s₀.val.image f.val ⊆ s₁.val.image f.val, intros q hq, rcases finset.mem_image.mp hq with ⟨p,hp,hfp⟩, exact finset.mem_image.mpr ⟨p,hs hp,hfp⟩ end, exact ⟨sf, this⟩ end lemma map_val (f : poset.hom P Q) (s : subdiv P) : ((subdiv.map f).val s).val = s.val.image f.val := rfl section interleave variables [fintype P] {f g : poset.hom P Q} (hfg : f ≤ g) include hfg def interleave : ∀ (r : fin_ranking P) (m : ℕ), hom (subdiv P) (subdiv Q) | ⟨n,r,r_mono⟩ m := ⟨ λ (σ : subdiv P), ⟨ ((σ.val.filter (λ p, 2 * (r p).val < m)).image f) ∪ ((σ.val.filter (λ p, 2 * (r p).val + 1 ≥ m)).image g), begin split, { rcases finset.exists_mem_of_ne_empty σ.property.1 with ⟨p, p_in_σ⟩, by_cases h : 2 * (r p).val < m, { apply @finset.ne_empty_of_mem Q (f p), apply finset.mem_union_left, apply finset.mem_image_of_mem, rw [finset.mem_filter], exact ⟨p_in_σ, h⟩ }, { replace h := le_trans (le_of_not_gt h) (nat.le_succ _), apply @finset.ne_empty_of_mem Q (g p), apply finset.mem_union_right, apply finset.mem_image_of_mem, rw [finset.mem_filter], exact ⟨p_in_σ, h⟩ } }, { intros q₀ h₀ q₁ h₁, rcases finset.mem_union.mp h₀ with h₀ | h₀; rcases finset.mem_union.mp h₁ with h₁ | h₁; rcases finset.mem_image.mp h₀ with ⟨p₀,hf₀,he₀⟩; rcases finset.mem_image.mp h₁ with ⟨p₁,hf₁,he₁⟩; rw [finset.mem_filter] at hf₀ hf₁; rw [← he₀, ← he₁]; let r₀ := (r p₀).val ; let r₁ := (r p₁).val ; rcases σ.property.right p₀ hf₀.1 p₁ hf₁.1 with hpp | hpp; let hfpp := f.property hpp; let hgpp := g.property hpp, { left , exact hfpp }, { right, exact hfpp }, { left , exact le_trans hfpp (hfg p₁) }, { by_cases hrr : r₀ = r₁, { rw [r.injective (fin.eq_of_veq hrr)], left, exact hfg p₁ }, { exfalso, change r₀ ≠ r₁ at hrr, replace hrr : r₁ < r₀ := lt_of_le_of_ne (r_mono hpp) hrr.symm, change r₁ + 1 ≤ r₀ at hrr, have := calc 2 * r₁ + 2 = 2 * (r₁ + 1) : by rw [mul_add, mul_one] ... ≤ 2 * r₀ : nat.mul_le_mul_left 2 hrr ... < m : hf₀.2 ... ≤ 2 * r₁ + 1 : hf₁.2 ... < 2 * r₁ + 2 : nat.lt_succ_self _, exact lt_irrefl _ this } }, { by_cases hrr : r₀ = r₁, { rw [r.injective (fin.eq_of_veq hrr)], right, exact hfg p₁ }, { exfalso, change r₀ ≠ r₁ at hrr, replace hrr : r₀ < r₁ := lt_of_le_of_ne (r_mono hpp) hrr, change r₀ + 1 ≤ r₁ at hrr, have := calc 2 * r₁ < m : hf₁.2 ... ≤ 2 * r₀ + 1 : hf₀.2 ... < 2 * r₀ + 2 : nat.lt_succ_self _ ... = 2 * (r₀ + 1) : by rw [mul_add, mul_one] ... ≤ 2 * r₁ : nat.mul_le_mul_left 2 hrr, exact lt_irrefl _ this } }, { right, exact le_trans hfpp (hfg p₀) }, { left , exact hgpp }, { right, exact hgpp } } end ⟩, begin intros σ₀ σ₁ h_le q hq, rw [finset.mem_union] at hq ⊢, rcases hq with hq | hq; rcases finset.mem_image.mp hq with ⟨p,hm,he⟩; rw [← he]; rw [finset.mem_filter] at hm; replace hm := and.intro (h_le hm.1) hm.2, { left , apply finset.mem_image_of_mem, rw [finset.mem_filter], exact hm }, { right, apply finset.mem_image_of_mem, rw [finset.mem_filter], exact hm } end ⟩ lemma interleave_start : ∀ (r : fin_ranking P), interleave hfg r 0 = subdiv.map g | ⟨n,r,r_mono⟩ := begin ext σ, apply subtype.eq, change _ ∪ _ = σ.val.image g.val, ext q, have : σ.val.filter (λ (p : P), 2 * (r p).val < 0) = ∅ := begin ext p, rw [finset.mem_filter], simp [nat.not_lt_zero, finset.not_mem_empty] end, rw [this, finset.image_empty], have : σ.val.filter (λ (p : P), 2 * (r p).val + 1 ≥ 0) = σ.val := begin ext p, rw [finset.mem_filter], have : _ ≥ 0 := nat.zero_le (2 * (r p).val + 1), simp only [this, and_true] end, rw [this, finset.mem_union], have : (g : P → Q) = g.val := rfl, rw [this], simp [finset.not_mem_empty], end lemma interleave_end : ∀ (r : fin_ranking P) (m : ℕ) (hm : m ≥ 2 * r.card), interleave hfg r m = subdiv.map f | ⟨n,r,r_mono⟩ m hm := begin change m ≥ 2 * n at hm, ext σ, apply subtype.eq, change _ ∪ _ = σ.val.image f.val, ext q, have : σ.val.filter (λ (p : P), 2 * (r p).val < m) = σ.val := begin ext p, rw [finset.mem_filter], have := calc 2 * (r p).val < 2 * n : nat.mul_lt_mul_of_pos_left (r p).is_lt (dec_trivial : 2 > 0) ... ≤ m : hm, simp [this] end, rw [this], have : σ.val.filter (λ (p : P), 2 * (r p).val + 1 ≥ m) = ∅ := begin ext p, rw [finset.mem_filter], have := calc 2 * (r p).val + 1 < 2 * (r p).val + 2 : nat.lt_succ_self _ ... = 2 * ((r p).val + 1) : by rw [mul_add, mul_one] ... ≤ 2 * n : nat.mul_le_mul_left 2 (r p).is_lt ... ≤ m : hm, have : ¬ (_ ≥ m) := not_le_of_gt this, simp only [this, finset.not_mem_empty, and_false] end, rw [this, finset.image_empty, finset.union_empty], have : (f : P → Q) = f.val := rfl, rw [this] end lemma interleave_even_step : ∀ (r : fin_ranking P) (k : ℕ), interleave hfg r (2 * k) ≤ interleave hfg r (2 * k + 1) | ⟨n,r,r_mono⟩ k := begin intros σ q h, change q ∈ _ ∪ _ at h, change q ∈ _ ∪ _, rw [finset.mem_union] at h ⊢, rcases h with h | h; rcases finset.mem_image.mp h with ⟨p,hf,he⟩; rw [finset.mem_filter] at hf; rw [← he], { left, apply finset.mem_image_of_mem, rw [finset.mem_filter], exact ⟨hf.1, lt_trans hf.2 (nat.lt_succ_self _)⟩ }, { right, apply finset.mem_image_of_mem, rw [finset.mem_filter], rcases le_or_gt k (r p).val with hk | hk, { exact ⟨hf.1, nat.succ_le_succ (nat.mul_le_mul_left 2 hk)⟩ }, { exfalso, have := calc 2 * (r p).val + 2 = 2 * ((r p).val + 1) : by rw [mul_add, mul_one] ... ≤ 2 * k : nat.mul_le_mul_left 2 hk ... ≤ 2 * (r p).val + 1 : hf.2 ... < 2 * (r p).val + 2 : nat.lt_succ_self _, exact lt_irrefl _ this } } end lemma interleave_odd_step : ∀ (r : fin_ranking P) (k : ℕ), interleave hfg r (2 * k + 2) ≤ interleave hfg r (2 * k + 1) | ⟨n,r,r_mono⟩ k := begin intros σ q h, change q ∈ _ ∪ _ at h, change q ∈ _ ∪ _, rw [finset.mem_union] at h ⊢, rcases h with h | h; rcases finset.mem_image.mp h with ⟨p,hf,he⟩; rw [finset.mem_filter] at hf; rw [← he], { left, apply finset.mem_image_of_mem, rw [finset.mem_filter], rcases le_or_gt (r p).val k with hk | hk, { have := calc 2 * (r p).val ≤ 2 * k : nat.mul_le_mul_left 2 hk ... < 2 * k + 1 : nat.lt_succ_self _, exact ⟨hf.1, this⟩ }, { exfalso, have := calc 2 * k + 2 = 2 * (k + 1) : by rw [mul_add, mul_one] ... ≤ 2 * (r p).val : nat.mul_le_mul_left 2 hk ... < 2 * k + 2 : hf.2, exact lt_irrefl _ this } }, { right, apply finset.mem_image_of_mem, rw [finset.mem_filter], exact ⟨hf.1, le_trans (le_of_lt (nat.lt_succ_self (2 * k + 1))) hf.2⟩ } end lemma interleave_component (r : fin_ranking P) (m : ℕ) : component (interleave hfg r m) = component (interleave hfg r 0) := zigzag (interleave hfg r) (interleave_even_step hfg r) (interleave_odd_step hfg r) m end interleave def subdiv.mapₕ [fintype P] : π₀ (hom P Q) → π₀ (hom (subdiv P) (subdiv Q)) := π₀.lift (λ f, component (subdiv.map f)) begin intros f g hfg, rcases exists_fin_ranking P with ⟨r⟩, let n := r.card, let c := interleave hfg r, have : c 0 = subdiv.map g := interleave_start hfg r, rw [← this], have : c (2 * n) = subdiv.map f := interleave_end hfg r (2 * n) (le_refl _), rw [← this], apply interleave_component end /-- For a simplex s, we define max s to be the largest element. -/ def max₀ : P := seq s rfl (fin.last s.dim) lemma max₀_mem : s.max₀ ∈ s.val := seq_mem s rfl (fin.last s.dim) lemma le_max₀ (p : P) (hp : p ∈ s.val) : p ≤ s.max₀ := begin rw [← seq_rank s rfl p hp], apply (seq_le s rfl (rank s rfl p hp) (fin.last s.dim)).mp, apply fin.le_last end end els /-- The function max : subdiv P → P is monotone. -/ lemma max₀_mono : monotone (max₀ : subdiv P → P) := λ s t hst, t.le_max₀ s.max₀ (hst s.max₀_mem) variable (P) def max : hom (subdiv P) P := ⟨max₀,max₀_mono⟩ lemma max_mem (s : subdiv P) : max P s ∈ s.val := max₀_mem s lemma le_max (s : subdiv P) (p : P) (hp : p ∈ s.val) : p ≤ max P s := le_max₀ s p hp lemma max_cofinal : cofinalₕ (max P) := begin intro p, let C := comma (max P) p, let c : C := ⟨vertex p,le_refl _⟩, let T := punit.{uP + 1}, let f : hom C T := const C punit.star, let g : hom T C := const T c, have hfg : comp f g = id T := by { ext t, rcases t, refl }, let m₀ : C → C := λ x, begin let τ₀ := x.val.val ∪ finset.singleton p, have h₀ : τ₀ ≠ ∅ := finset.ne_empty_of_mem (finset.mem_union_right _ (finset.mem_singleton_self p)), have h₁ : is_chain τ₀ := λ a ha b hb, begin rcases finset.mem_union.mp ha with hax | hap; rcases finset.mem_union.mp hb with hbx | hbp, { exact x.val.property.2 a hax b hbx }, { left, rw [finset.mem_singleton.mp hbp], exact le_trans (le_max P x.val a hax) x.property }, { right, rw [finset.mem_singleton.mp hap], exact le_trans (le_max P x.val b hbx) x.property }, { left, rw [finset.mem_singleton.mp hbp], rw [finset.mem_singleton.mp hap] } end, let τ : subdiv P := ⟨τ₀,⟨h₀,h₁⟩⟩, have h₂ : max P τ ≤ p := begin rcases finset.mem_union.mp (max_mem P τ) with h | h, { exact le_trans (le_max P x.val _ h) x.property }, { rw [finset.mem_singleton.mp h] } end, exact ⟨τ,h₂⟩ end, have m₀_mono : monotone m₀ := λ x₀ x₁ h, begin change x₀.val.val ⊆ x₁.val.val at h, change x₀.val.val ∪ finset.singleton p ⊆ x₁.val.val ∪ finset.singleton p, intros a ha, rcases finset.mem_union.mp ha with hax | hap, { exact finset.mem_union_left _ (h hax) }, { exact finset.mem_union_right _ hap } end, let m : hom C C := ⟨m₀,m₀_mono⟩, have hm₀ : comp g f ≤ m := λ x a ha, begin change a ∈ finset.singleton p at ha, change a ∈ x.val.val ∪ finset.singleton p, exact finset.mem_union_right _ ha end, have hm₁ : id C ≤ m := λ x a ha, begin change a ∈ x.val.val at ha, change a ∈ x.val.val ∪ finset.singleton p, exact finset.mem_union_left _ ha end, let hgf := (π₀.sound hm₀).trans (π₀.sound hm₁).symm, have e : equivₕ C T := { to_fun := component f, inv_fun := component g, left_inv := hgf, right_inv := congr_arg component hfg }, exact ⟨e⟩ end end subdiv end poset
d65b3a130d0782dc4d26e0ddf7f5a461bd211a5f
9dc8cecdf3c4634764a18254e94d43da07142918
/src/category_theory/limits/shapes/zero_objects.lean
040fc711649d9ea77ac7d90225b3099e3d6e0065
[ "Apache-2.0" ]
permissive
jcommelin/mathlib
d8456447c36c176e14d96d9e76f39841f69d2d9b
ee8279351a2e434c2852345c51b728d22af5a156
refs/heads/master
1,664,782,136,488
1,663,638,983,000
1,663,638,983,000
132,563,656
0
0
Apache-2.0
1,663,599,929,000
1,525,760,539,000
Lean
UTF-8
Lean
false
false
8,285
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Johan Commelin -/ import category_theory.limits.shapes.products import category_theory.limits.shapes.images import category_theory.isomorphism_classes /-! # Zero objects A category "has a zero object" if it has an object which is both initial and terminal. Having a zero object provides zero morphisms, as the unique morphisms factoring through the zero object; see `category_theory.limits.shapes.zero_morphisms`. ## References * [F. Borceux, *Handbook of Categorical Algebra 2*][borceux-vol2] -/ noncomputable theory universes v u v' u' open category_theory open category_theory.category variables {C : Type u} [category.{v} C] variables {D : Type u'} [category.{v'} D] namespace category_theory namespace limits /-- An object `X` in a category is a *zero object* if for every object `Y` there is a unique morphism `to : X → Y` and a unique morphism `from : Y → X`. This is a characteristic predicate for `has_zero_object`. -/ structure is_zero (X : C) : Prop := (unique_to : ∀ Y, nonempty (unique (X ⟶ Y))) (unique_from : ∀ Y, nonempty (unique (Y ⟶ X))) namespace is_zero variables {X Y : C} /-- If `h : is_zero X`, then `h.to Y` is a choice of unique morphism `X → Y`. -/ protected def «to» (h : is_zero X) (Y : C) : X ⟶ Y := @default (X ⟶ Y) $ @unique.inhabited _ $ (h.unique_to Y).some lemma eq_to (h : is_zero X) (f : X ⟶ Y) : f = h.to Y := @unique.eq_default _ (id _) _ lemma to_eq (h : is_zero X) (f : X ⟶ Y) : h.to Y = f := (h.eq_to f).symm /-- If `h : is_zero X`, then `h.from Y` is a choice of unique morphism `Y → X`. -/ protected def «from» (h : is_zero X) (Y : C) : Y ⟶ X := @default (Y ⟶ X) $ @unique.inhabited _ $ (h.unique_from Y).some lemma eq_from (h : is_zero X) (f : Y ⟶ X) : f = h.from Y := @unique.eq_default _ (id _) _ lemma from_eq (h : is_zero X) (f : Y ⟶ X) : h.from Y = f := (h.eq_from f).symm lemma eq_of_src (hX : is_zero X) (f g : X ⟶ Y) : f = g := (hX.eq_to f).trans (hX.eq_to g).symm lemma eq_of_tgt (hX : is_zero X) (f g : Y ⟶ X) : f = g := (hX.eq_from f).trans (hX.eq_from g).symm /-- Any two zero objects are isomorphic. -/ def iso (hX : is_zero X) (hY : is_zero Y) : X ≅ Y := { hom := hX.to Y, inv := hX.from Y, hom_inv_id' := hX.eq_of_src _ _, inv_hom_id' := hY.eq_of_src _ _, } /-- A zero object is in particular initial. -/ protected def is_initial (hX : is_zero X) : is_initial X := @is_initial.of_unique _ _ X $ λ Y, (hX.unique_to Y).some /-- A zero object is in particular terminal. -/ protected def is_terminal (hX : is_zero X) : is_terminal X := @is_terminal.of_unique _ _ X $ λ Y, (hX.unique_from Y).some /-- The (unique) isomorphism between any initial object and the zero object. -/ def iso_is_initial (hX : is_zero X) (hY : is_initial Y) : X ≅ Y := hX.is_initial.unique_up_to_iso hY /-- The (unique) isomorphism between any terminal object and the zero object. -/ def iso_is_terminal (hX : is_zero X) (hY : is_terminal Y) : X ≅ Y := hX.is_terminal.unique_up_to_iso hY lemma of_iso (hY : is_zero Y) (e : X ≅ Y) : is_zero X := begin refine ⟨λ Z, ⟨⟨⟨e.hom ≫ hY.to Z⟩, λ f, _⟩⟩, λ Z, ⟨⟨⟨hY.from Z ≫ e.inv⟩, λ f, _⟩⟩⟩, { rw ← cancel_epi e.inv, apply hY.eq_of_src, }, { rw ← cancel_mono e.hom, apply hY.eq_of_tgt, }, end end is_zero end limits open category_theory.limits lemma iso.is_zero_iff {X Y : C} (e : X ≅ Y) : is_zero X ↔ is_zero Y := ⟨λ h, h.of_iso e.symm, λ h, h.of_iso e⟩ lemma functor.is_zero (F : C ⥤ D) (hF : ∀ X, is_zero (F.obj X)) : is_zero F := begin split; intros G; refine ⟨⟨⟨_⟩, _⟩⟩, { refine { app := λ X, (hF _).to _, naturality' := _ }, intros, exact (hF _).eq_of_src _ _ }, { intro f, ext, apply (hF _).eq_of_src _ _ }, { refine { app := λ X, (hF _).from _, naturality' := _ }, intros, exact (hF _).eq_of_tgt _ _ }, { intro f, ext, apply (hF _).eq_of_tgt _ _ }, end namespace limits variables (C) /-- A category "has a zero object" if it has an object which is both initial and terminal. -/ class has_zero_object : Prop := (zero : ∃ X : C, is_zero X) instance has_zero_object_punit : has_zero_object (discrete punit) := { zero := ⟨⟨⟨⟩⟩, by tidy, by tidy⟩, } section variables [has_zero_object C] /-- Construct a `has_zero C` for a category with a zero object. This can not be a global instance as it will trigger for every `has_zero C` typeclass search. -/ protected def has_zero_object.has_zero : has_zero C := { zero := has_zero_object.zero.some } localized "attribute [instance] category_theory.limits.has_zero_object.has_zero" in zero_object lemma is_zero_zero : is_zero (0 : C) := has_zero_object.zero.some_spec end open_locale zero_object variables {C} lemma is_zero.has_zero_object {X : C} (hX : is_zero X) : has_zero_object C := ⟨⟨X, hX⟩⟩ /-- Every zero object is isomorphic to *the* zero object. -/ def is_zero.iso_zero [has_zero_object C] {X : C} (hX : is_zero X) : X ≅ 0 := hX.iso (is_zero_zero C) lemma is_zero.obj [has_zero_object D] {F : C ⥤ D} (hF : is_zero F) (X : C) : is_zero (F.obj X) := begin let G : C ⥤ D := (category_theory.functor.const C).obj 0, have hG : is_zero G := functor.is_zero _ (λ X, is_zero_zero _), let e : F ≅ G := hF.iso hG, exact (is_zero_zero _).of_iso (e.app X), end namespace has_zero_object variables [has_zero_object C] /-- There is a unique morphism from the zero object to any object `X`. -/ protected def unique_to (X : C) : unique (0 ⟶ X) := ((is_zero_zero C).unique_to X).some /-- There is a unique morphism from any object `X` to the zero object. -/ protected def unique_from (X : C) : unique (X ⟶ 0) := ((is_zero_zero C).unique_from X).some localized "attribute [instance] category_theory.limits.has_zero_object.unique_to" in zero_object localized "attribute [instance] category_theory.limits.has_zero_object.unique_from" in zero_object @[ext] lemma to_zero_ext {X : C} (f g : X ⟶ 0) : f = g := (is_zero_zero C).eq_of_tgt _ _ @[ext] lemma from_zero_ext {X : C} (f g : 0 ⟶ X) : f = g := (is_zero_zero C).eq_of_src _ _ instance (X : C) : subsingleton (X ≅ 0) := by tidy instance {X : C} (f : 0 ⟶ X) : mono f := { right_cancellation := λ Z g h w, by ext, } instance {X : C} (f : X ⟶ 0) : epi f := { left_cancellation := λ Z g h w, by ext, } instance zero_to_zero_is_iso (f : (0 : C) ⟶ 0) : is_iso f := by convert (show is_iso (𝟙 (0 : C)), by apply_instance) /-- A zero object is in particular initial. -/ def zero_is_initial : is_initial (0 : C) := (is_zero_zero C).is_initial /-- A zero object is in particular terminal. -/ def zero_is_terminal : is_terminal (0 : C) := (is_zero_zero C).is_terminal /-- A zero object is in particular initial. -/ @[priority 10] instance has_initial : has_initial C := has_initial_of_unique 0 /-- A zero object is in particular terminal. -/ @[priority 10] instance has_terminal : has_terminal C := has_terminal_of_unique 0 /-- The (unique) isomorphism between any initial object and the zero object. -/ def zero_iso_is_initial {X : C} (t : is_initial X) : 0 ≅ X := zero_is_initial.unique_up_to_iso t /-- The (unique) isomorphism between any terminal object and the zero object. -/ def zero_iso_is_terminal {X : C} (t : is_terminal X) : 0 ≅ X := zero_is_terminal.unique_up_to_iso t /-- The (unique) isomorphism between the chosen initial object and the chosen zero object. -/ def zero_iso_initial [has_initial C] : 0 ≅ ⊥_ C := zero_is_initial.unique_up_to_iso initial_is_initial /-- The (unique) isomorphism between the chosen terminal object and the chosen zero object. -/ def zero_iso_terminal [has_terminal C] : 0 ≅ ⊤_ C := zero_is_terminal.unique_up_to_iso terminal_is_terminal @[priority 100] instance has_strict_initial : initial_mono_class C := initial_mono_class.of_is_initial zero_is_initial (λ X, category_theory.mono _) end has_zero_object end limits open category_theory.limits open_locale zero_object lemma functor.is_zero_iff [has_zero_object D] (F : C ⥤ D) : is_zero F ↔ ∀ X, is_zero (F.obj X) := ⟨λ hF X, hF.obj X, functor.is_zero _⟩ end category_theory
2e0117f8b3fe48e5e9d87e5465cb5555a413171a
6dc0c8ce7a76229dd81e73ed4474f15f88a9e294
/stage0/src/Lean/Meta/Tactic/Induction.lean
e3acf657fc4984a673c556d6ef4a0e38c03c4ead
[ "Apache-2.0" ]
permissive
williamdemeo/lean4
72161c58fe65c3ad955d6a3050bb7d37c04c0d54
6d00fcf1d6d873e195f9220c668ef9c58e9c4a35
refs/heads/master
1,678,305,356,877
1,614,708,995,000
1,614,708,995,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
11,796
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.RecursorInfo import Lean.Meta.SynthInstance import Lean.Meta.Tactic.Util import Lean.Meta.Tactic.Revert import Lean.Meta.Tactic.Intro import Lean.Meta.Tactic.Clear import Lean.Meta.Tactic.FVarSubst namespace Lean.Meta private partial def getTargetArity : Expr → Nat | Expr.mdata _ b _ => getTargetArity b | Expr.forallE _ _ b _ => getTargetArity b + 1 | e => if e.isHeadBetaTarget then getTargetArity e.headBeta else 0 private def addRecParams (mvarId : MVarId) (majorTypeArgs : Array Expr) : List (Option Nat) → Expr → MetaM Expr | [], recursor => pure recursor | some pos :: rest, recursor => if h : pos < majorTypeArgs.size then addRecParams mvarId majorTypeArgs rest (mkApp recursor (majorTypeArgs.get ⟨pos, h⟩)) else throwTacticEx `induction mvarId "ill-formed recursor" | none :: rest, recursor => do let recursorType ← inferType recursor let recursorType ← whnfForall recursorType match recursorType with | Expr.forallE _ d _ _ => do let param ← try synthInstance d catch _ => throwTacticEx `induction mvarId "failed to generate type class instance parameter" addRecParams mvarId majorTypeArgs rest (mkApp recursor param) | _ => throwTacticEx `induction mvarId "ill-formed recursor" structure InductionSubgoal where mvarId : MVarId fields : Array Expr := #[] subst : FVarSubst := {} deriving Inhabited private def getTypeBody (mvarId : MVarId) (type : Expr) (x : Expr) : MetaM Expr := do let type ← whnfForall type match type with | Expr.forallE _ _ b _ => pure $ b.instantiate1 x | _ => throwTacticEx `induction mvarId "ill-formed recursor" structure AltVarNames where explicit : Bool := false -- true if `@` modifier was used varNames : List Name := [] deriving Inhabited private partial def finalize (mvarId : MVarId) (givenNames : Array AltVarNames) (recursorInfo : RecursorInfo) (reverted : Array FVarId) (major : Expr) (indices : Array Expr) (baseSubst : FVarSubst) (recursor : Expr) : MetaM (Array InductionSubgoal) := do let target ← getMVarType mvarId let initialArity := getTargetArity target let recursorType ← inferType recursor let numMinors := recursorInfo.produceMotive.length let rec loop (pos : Nat) (minorIdx : Nat) (recursor recursorType : Expr) (consumedMajor : Bool) (subgoals : Array InductionSubgoal) := do let recursorType ← whnfForall recursorType if recursorType.isForall && pos < recursorInfo.numArgs then if pos == recursorInfo.firstIndexPos then let (recursor, recursorType) ← indices.foldlM (init := (recursor, recursorType)) fun (recursor, recursorType) index => do let recursor := mkApp recursor index let recursorType ← getTypeBody mvarId recursorType index pure (recursor, recursorType) let recursor := mkApp recursor major let recursorType ← getTypeBody mvarId recursorType major loop (pos+1+indices.size) minorIdx recursor recursorType true subgoals else -- consume motive let tag ← getMVarTag mvarId if minorIdx ≥ numMinors then throwTacticEx `induction mvarId "ill-formed recursor" match recursorType with | Expr.forallE n d b c => let d := d.headBeta -- Remark is givenNames is not empty, then user provided explicit alternatives for each minor premise if c.binderInfo.isInstImplicit && givenNames.isEmpty then match (← synthInstance? d) with | some inst => let recursor := mkApp recursor inst let recursorType ← getTypeBody mvarId recursorType inst loop (pos+1) (minorIdx+1) recursor recursorType consumedMajor subgoals | none => do -- Add newSubgoal if type class resolution failed let mvar ← mkFreshExprSyntheticOpaqueMVar d (tag ++ n) let recursor := mkApp recursor mvar let recursorType ← getTypeBody mvarId recursorType mvar loop (pos+1) (minorIdx+1) recursor recursorType consumedMajor (subgoals.push { mvarId := mvar.mvarId! }) else let arity := getTargetArity d if arity < initialArity then throwTacticEx `induction mvarId "ill-formed recursor" let nparams := arity - initialArity -- number of fields due to minor premise let nextra := reverted.size - indices.size - 1 -- extra dependencies that have been reverted let minorGivenNames := if h : minorIdx < givenNames.size then givenNames.get ⟨minorIdx, h⟩ else {} let mvar ← mkFreshExprSyntheticOpaqueMVar d (tag ++ n) let recursor := mkApp recursor mvar let recursorType ← getTypeBody mvarId recursorType mvar -- Try to clear major premise from new goal let mvarId' ← tryClear mvar.mvarId! major.fvarId! let (fields, mvarId') ← introN mvarId' nparams minorGivenNames.varNames (useNamesForExplicitOnly := !minorGivenNames.explicit) let (extra, mvarId') ← introNP mvarId' nextra let subst := reverted.size.fold (init := baseSubst) fun i (subst : FVarSubst) => if i < indices.size + 1 then subst else let revertedFVarId := reverted[i] let newFVarId := extra[i - indices.size - 1] subst.insert revertedFVarId (mkFVar newFVarId) let fields := fields.map mkFVar loop (pos+1) (minorIdx+1) recursor recursorType consumedMajor (subgoals.push { mvarId := mvarId', fields := fields, subst := subst }) | _ => unreachable! else unless consumedMajor do throwTacticEx `induction mvarId "ill-formed recursor" assignExprMVar mvarId recursor pure subgoals loop (recursorInfo.paramsPos.length + 1) 0 recursor recursorType false #[] private def throwUnexpectedMajorType {α} (mvarId : MVarId) (majorType : Expr) : MetaM α := throwTacticEx `induction mvarId m!"unexpected major premise type{indentExpr majorType}" def induction (mvarId : MVarId) (majorFVarId : FVarId) (recursorName : Name) (givenNames : Array AltVarNames := #[]) : MetaM (Array InductionSubgoal) := withMVarContext mvarId do trace[Meta.Tactic.induction]! "initial\n{MessageData.ofGoal mvarId}" checkNotAssigned mvarId `induction let majorLocalDecl ← getLocalDecl majorFVarId let recursorInfo ← mkRecursorInfo recursorName let some majorType ← whnfUntil majorLocalDecl.type recursorInfo.typeName | throwUnexpectedMajorType mvarId majorLocalDecl.type majorType.withApp fun _ majorTypeArgs => do recursorInfo.paramsPos.forM fun paramPos? => do match paramPos? with | none => pure () | some paramPos => if paramPos ≥ majorTypeArgs.size then throwTacticEx `induction mvarId m!"major premise type is ill-formed{indentExpr majorType}" let mctx ← getMCtx let indices ← recursorInfo.indicesPos.toArray.mapM fun idxPos => do if idxPos ≥ majorTypeArgs.size then throwTacticEx `induction mvarId m!"major premise type is ill-formed{indentExpr majorType}" let idx := majorTypeArgs.get! idxPos unless idx.isFVar do throwTacticEx `induction mvarId m!"major premise type index {idx} is not a variable{indentExpr majorType}" majorTypeArgs.size.forM fun i => do let arg := majorTypeArgs[i] if i != idxPos && arg == idx then throwTacticEx `induction mvarId m!"'{idx}' is an index in major premise, but it occurs more than once{indentExpr majorType}" if i < idxPos && mctx.exprDependsOn arg idx.fvarId! then throwTacticEx `induction mvarId m!"'{idx}' is an index in major premise, but it occurs in previous arguments{indentExpr majorType}" -- If arg is also and index and a variable occurring after `idx`, we need to make sure it doesn't depend on `idx`. -- Note that if `arg` is not a variable, we will fail anyway when we visit it. if i > idxPos && recursorInfo.indicesPos.contains i && arg.isFVar then let idxDecl ← getLocalDecl idx.fvarId! if mctx.localDeclDependsOn idxDecl arg.fvarId! then throwTacticEx `induction mvarId m!"'{idx}' is an index in major premise, but it depends on index occurring at position #{i+1}" pure idx let target ← getMVarType mvarId if !recursorInfo.depElim && mctx.exprDependsOn target majorFVarId then throwTacticEx `induction mvarId m!"recursor '{recursorName}' does not support dependent elimination, but conclusion depends on major premise" -- Revert indices and major premise preserving variable order let (reverted, mvarId) ← revert mvarId ((indices.map Expr.fvarId!).push majorFVarId) true -- Re-introduce indices and major let (indices', mvarId) ← introNP mvarId indices.size let (majorFVarId', mvarId) ← intro1P mvarId -- Create FVarSubst with indices let baseSubst := do let mut subst : FVarSubst := {} let mut i := 0 for index in indices do subst := subst.insert index.fvarId! (mkFVar indices'[i]) i := i + 1 pure subst trace[Meta.Tactic.induction]! "after revert&intro\n{MessageData.ofGoal mvarId}" -- Update indices and major let indices := indices'.map mkFVar let majorFVarId := majorFVarId' let major := mkFVar majorFVarId withMVarContext mvarId do let target ← getMVarType mvarId let targetLevel ← getLevel target let targetLevel ← normalizeLevel targetLevel let majorLocalDecl ← getLocalDecl majorFVarId let some majorType ← whnfUntil majorLocalDecl.type recursorInfo.typeName | throwUnexpectedMajorType mvarId majorLocalDecl.type majorType.withApp fun majorTypeFn majorTypeArgs => do match majorTypeFn with | Expr.const majorTypeFnName majorTypeFnLevels _ => do let majorTypeFnLevels := majorTypeFnLevels.toArray let (recursorLevels, foundTargetLevel) ← recursorInfo.univLevelPos.foldlM (init := (#[], false)) fun (recursorLevels, foundTargetLevel) (univPos : RecursorUnivLevelPos) => do match univPos with | RecursorUnivLevelPos.motive => pure (recursorLevels.push targetLevel, true) | RecursorUnivLevelPos.majorType idx => if idx ≥ majorTypeFnLevels.size then throwTacticEx `induction mvarId "ill-formed recursor" pure (recursorLevels.push (majorTypeFnLevels.get! idx), foundTargetLevel) if !foundTargetLevel && !targetLevel.isZero then throwTacticEx `induction mvarId m!"recursor '{recursorName}' can only eliminate into Prop" let recursor := mkConst recursorName recursorLevels.toList let recursor ← addRecParams mvarId majorTypeArgs recursorInfo.paramsPos recursor -- Compute motive let motive := target let motive ← if recursorInfo.depElim then mkLambdaFVars #[major] motive else pure motive let motive ← mkLambdaFVars indices motive let recursor := mkApp recursor motive finalize mvarId givenNames recursorInfo reverted major indices baseSubst recursor | _ => throwTacticEx `induction mvarId "major premise is not of the form (C ...)" builtin_initialize registerTraceClass `Meta.Tactic.induction end Lean.Meta
ac16c4a82bea094a7e1f4378982aa42260a73e3b
947b78d97130d56365ae2ec264df196ce769371a
/tests/lean/run/toExpr.lean
c9824ab329ff82b5994bbd07394b167f071f6924
[ "Apache-2.0" ]
permissive
shyamalschandra/lean4
27044812be8698f0c79147615b1d5090b9f4b037
6e7a883b21eaf62831e8111b251dc9b18f40e604
refs/heads/master
1,671,417,126,371
1,601,859,995,000
1,601,860,020,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
797
lean
import Lean new_frontend open Lean unsafe def test {α : Type} [HasToString α] [ToExpr α] [HasBeq α] (a : α) : CoreM Unit := do let env ← getEnv; let auxName := `_toExpr._test; let decl := Declaration.defnDecl { name := auxName, lparams := [], value := toExpr a, type := toTypeExpr α, hints := ReducibilityHints.abbrev, isUnsafe := false }; IO.println (toExpr a); (match env.addAndCompile {} decl with | Except.error _ => throwError "addDecl failed" | Except.ok env => match env.evalConst α auxName with | Except.error ex => throwError ex | Except.ok b => do IO.println b; «unless» (a == b) $ throwError "toExpr failed"; pure ()) #eval test #[(1, 2), (3, 4)] #eval test ['a', 'b', 'c'] #eval test ("hello", true) #eval test ((), 10)
46c11cddb82d910e68dc52f34af428e4522ce700
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
/stage0/src/Lean/Server/Requests.lean
daba50109997f0ccee365d1d64ef675cd69cc0b9
[ "Apache-2.0" ]
permissive
WojciechKarpiel/lean4
7f89706b8e3c1f942b83a2c91a3a00b05da0e65b
f6e1314fa08293dea66a329e05b6c196a0189163
refs/heads/master
1,686,633,402,214
1,625,821,189,000
1,625,821,258,000
384,640,886
0
0
Apache-2.0
1,625,903,617,000
1,625,903,026,000
null
UTF-8
Lean
false
false
6,451
lean
/- Copyright (c) 2021 Wojciech Nawrocki. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Wojciech Nawrocki, Marc Huisinga -/ import Lean.DeclarationRange import Lean.Data.Json import Lean.Data.Lsp import Lean.Server.FileSource import Lean.Server.FileWorker.Utils /-! We maintain a global map of LSP request handlers. This allows user code such as plugins to register its own handlers, for example to support ITP functionality such as goal state visualization. For details of how to register one, see `registerLspRequestHandler`. -/ namespace Lean.Server.Requests structure RequestError where code : JsonRpc.ErrorCode message : String namespace RequestError open JsonRpc def fileChanged : RequestError := { code := ErrorCode.contentModified message := "File changed." } def methodNotFound (method : String) : RequestError := { code := ErrorCode.methodNotFound message := s!"No request handler found for '{method}'" } instance : Coe IO.Error RequestError where coe e := { code := ErrorCode.internalError message := toString e } def toLspResponseError (id : RequestID) (e : RequestError) : ResponseError Unit := { id := id code := e.code message := e.message } end RequestError structure RequestContext where srcSearchPath : SearchPath docRef : IO.Ref FileWorker.EditableDocument abbrev RequestTask α := Task (Except RequestError α) /-- Workers execute request handlers in this monad. -/ abbrev RequestM := ReaderT RequestContext <| ExceptT RequestError IO namespace RequestM open FileWorker open Snapshots def readDoc : RequestM EditableDocument := fun rc => rc.docRef.get def asTask (t : RequestM α) : RequestM (RequestTask α) := fun rc => do let t ← IO.asTask <| t rc return t.map fun | Except.error e => throwThe RequestError e | Except.ok v => v def mapTask (t : Task α) (f : α → RequestM β) : RequestM (RequestTask β) := fun rc => do let t ← (IO.mapTask · t) fun a => f a rc return t.map fun | Except.error e => throwThe RequestError e | Except.ok v => v def bindTask (t : Task α) (f : α → RequestM (RequestTask β)) : RequestM (RequestTask β) := fun rc => do let t ← IO.bindTask t fun a => do match (← f a rc) with | Except.error e => return Task.pure <| Except.ok <| Except.error e | Except.ok t => return t.map Except.ok return t.map fun | Except.error e => throwThe RequestError e | Except.ok v => v /-- Create a task which waits for a snapshot matching `p`, handles various errors, and if a matching snapshot was found executes `x` with it. If not found, the task executes `notFoundX`. -/ def withWaitFindSnap (doc : EditableDocument) (p : Snapshot → Bool) (notFoundX : RequestM β) (x : Snapshot → RequestM β) : RequestM (RequestTask β) := do let findTask ← doc.cmdSnaps.waitFind? p mapTask findTask fun /- The elaboration task that we're waiting for may be aborted if the file contents change. In that case, we reply with the `fileChanged` error. Thanks to this, the server doesn't get bogged down in requests for an old state of the document. -/ | Except.error FileWorker.ElabTaskError.aborted => throwThe RequestError RequestError.fileChanged | Except.error (FileWorker.ElabTaskError.ioError e) => throwThe IO.Error e | Except.error FileWorker.ElabTaskError.eof => notFoundX | Except.ok none => notFoundX | Except.ok (some snap) => x snap end RequestM /- The global request handlers table. -/ section HandlerTable open Lsp private structure RequestHandler where fileSource : Json → Except RequestError Lsp.DocumentUri handle : Json → RequestM (RequestTask Json) builtin_initialize requestHandlers : IO.Ref (Std.PersistentHashMap String RequestHandler) ← IO.mkRef {} private def parseParams (paramType : Type) [FromJson paramType] (params : Json) : Except RequestError paramType := fromJson? params |>.mapError fun inner => { code := JsonRpc.ErrorCode.parseError message := s!"Cannot parse request params: {params.compress}\n{inner}" } /-- NB: This method may only be called in `initialize`/`builtin_initialize` blocks. A registration consists of: - a type of JSON-parsable request data `paramType` - a `FileSource` instance for it so the system knows where to route requests - a type of JSON-serializable response data `respType` - an actual `handler` which runs in the `RequestM` monad and is expected to produce an asynchronous `RequestTask` which does any waiting/computation A handler task may be cancelled at any time, so it should check the cancellation token when possible to handle this cooperatively. Any exceptions thrown in a request handler will be reported to the client as LSP error responses. -/ def registerLspRequestHandler (method : String) paramType [FromJson paramType] [FileSource paramType] respType [ToJson respType] (handler : paramType → RequestM (RequestTask respType)) : IO Unit := do if !(← IO.initializing) then throw <| IO.userError s!"Failed to register LSP request handler for '{method}': only possible during initialization" if (←requestHandlers.get).contains method then throw <| IO.userError s!"Failed to register LSP request handler for '{method}': already registered" let fileSource := fun j => parseParams paramType j |>.map fun p => Lsp.fileSource p let handle := fun j => do let params ← parseParams paramType j let t ← handler params t.map <| Except.map ToJson.toJson requestHandlers.modify fun rhs => rhs.insert method { fileSource, handle } private def lookupLspRequestHandler (method : String) : IO (Option RequestHandler) := do (← requestHandlers.get).find? method def routeLspRequest (method : String) (params : Json) : IO (Except RequestError DocumentUri) := do match (← lookupLspRequestHandler method) with | none => return Except.error <| RequestError.methodNotFound method | some rh => return rh.fileSource params def handleLspRequest (method : String) (params : Json) : RequestM (RequestTask Json) := do match (← lookupLspRequestHandler method) with | none => throwThe IO.Error <| IO.userError s!"internal server error: request '{method}' routed through watchdog but unknown in worker; are both using the same plugins?" | some rh => rh.handle params end HandlerTable end Lean.Server.Requests
8bf291d3b8cbedbb89a4cebc0efc24cbb5dc5c53
c777c32c8e484e195053731103c5e52af26a25d1
/src/analysis/convolution.lean
c46120ed87890a95a565b2953f0a893ab19a8f1e
[ "Apache-2.0" ]
permissive
kbuzzard/mathlib
2ff9e85dfe2a46f4b291927f983afec17e946eb8
58537299e922f9c77df76cb613910914a479c1f7
refs/heads/master
1,685,313,702,744
1,683,974,212,000
1,683,974,212,000
128,185,277
1
0
null
1,522,920,600,000
1,522,920,600,000
null
UTF-8
Lean
false
false
83,790
lean
/- Copyright (c) 2022 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn -/ import measure_theory.group.integration import measure_theory.group.prod import measure_theory.function.locally_integrable import analysis.calculus.bump_function_inner import measure_theory.integral.interval_integral import analysis.calculus.parametric_integral /-! # Convolution of functions This file defines the convolution on two functions, i.e. `x ↦ ∫ f(t)g(x - t) ∂t`. In the general case, these functions can be vector-valued, and have an arbitrary (additive) group as domain. We use a continuous bilinear operation `L` on these function values as "multiplication". The domain must be equipped with a Haar measure `μ` (though many individual results have weaker conditions on `μ`). For many applications we can take `L = lsmul ℝ ℝ` or `L = mul ℝ ℝ`. We also define `convolution_exists` and `convolution_exists_at` to state that the convolution is well-defined (everywhere or at a single point). These conditions are needed for pointwise computations (e.g. `convolution_exists_at.distrib_add`), but are generally not stong enough for any local (or global) properties of the convolution. For this we need stronger assumptions on `f` and/or `g`, and generally if we impose stronger conditions on one of the functions, we can impose weaker conditions on the other. We have proven many of the properties of the convolution assuming one of these functions has compact support (in which case the other function only needs to be locally integrable). We still need to prove the properties for other pairs of conditions (e.g. both functions are rapidly decreasing) # Design Decisions We use a bilinear map `L` to "multiply" the two functions in the integrand. This generality has several advantages * This allows us to compute the total derivative of the convolution, in case the functions are multivariate. The total derivative is again a convolution, but where the codomains of the functions can be higher-dimensional. See `has_compact_support.has_fderiv_at_convolution_right`. * This allows us to use `@[to_additive]` everywhere (which would not be possible if we would use `mul`/`smul` in the integral, since `@[to_additive]` will incorrectly also try to additivize those definitions). * We need to support the case where at least one of the functions is vector-valued, but if we use `smul` to multiply the functions, that would be an asymmetric definition. # Main Definitions * `convolution f g L μ x = (f ⋆[L, μ] g) x = ∫ t, L (f t) (g (x - t)) ∂μ` is the convolution of `f` and `g` w.r.t. the continuous bilinear map `L` and measure `μ`. * `convolution_exists_at f g x L μ` states that the convolution `(f ⋆[L, μ] g) x` is well-defined (i.e. the integral exists). * `convolution_exists f g L μ` states that the convolution `f ⋆[L, μ] g` is well-defined at each point. # Main Results * `has_compact_support.has_fderiv_at_convolution_right` and `has_compact_support.has_fderiv_at_convolution_left`: we can compute the total derivative of the convolution as a convolution with the total derivative of the right (left) function. * `has_compact_support.cont_diff_convolution_right` and `has_compact_support.cont_diff_convolution_left`: the convolution is `𝒞ⁿ` if one of the functions is `𝒞ⁿ` with compact support and the other function in locally integrable. Versions of these statements for functions depending on a parameter are also given. * `convolution_tendsto_right`: Given a sequence of nonnegative normalized functions whose support tends to a small neighborhood around `0`, the convolution tends to the right argument. This is specialized to bump functions in `cont_diff_bump.convolution_tendsto_right`. # Notation The following notations are localized in the locale `convolution`: * `f ⋆[L, μ] g` for the convolution. Note: you have to use parentheses to apply the convolution to an argument: `(f ⋆[L, μ] g) x`. * `f ⋆[L] g := f ⋆[L, volume] g` * `f ⋆ g := f ⋆[lsmul ℝ ℝ] g` # To do * Existence and (uniform) continuity of the convolution if one of the maps is in `ℒ^p` and the other in `ℒ^q` with `1 / p + 1 / q = 1`. This might require a generalization of `measure_theory.mem_ℒp.smul` where `smul` is generalized to a continuous bilinear map. (see e.g. [Fremlin, *Measure Theory* (volume 2)][fremlin_vol2], 255K) * The convolution is a `ae_strongly_measurable` function (see e.g. [Fremlin, *Measure Theory* (volume 2)][fremlin_vol2], 255I). * Prove properties about the convolution if both functions are rapidly decreasing. * Use `@[to_additive]` everywhere -/ open set function filter measure_theory measure_theory.measure topological_space open continuous_linear_map metric open_locale pointwise topology nnreal filter universes u𝕜 uG uE uE' uE'' uF uF' uF'' uP variables {𝕜 : Type u𝕜} {G : Type uG} {E : Type uE} {E' : Type uE'} {E'' : Type uE''} {F : Type uF} {F' : Type uF'} {F'' : Type uF''} {P : Type uP} variables [normed_add_comm_group E] [normed_add_comm_group E'] [normed_add_comm_group E''] [normed_add_comm_group F] {f f' : G → E} {g g' : G → E'} {x x' : G} {y y' : E} section nontrivially_normed_field variables [nontrivially_normed_field 𝕜] variables [normed_space 𝕜 E] [normed_space 𝕜 E'] [normed_space 𝕜 E''] [normed_space 𝕜 F] variables (L : E →L[𝕜] E' →L[𝕜] F) section no_measurability variables [add_group G] [topological_space G] lemma convolution_integrand_bound_right_of_le_of_subset {C : ℝ} (hC : ∀ i, ‖g i‖ ≤ C) {x t : G} {s u : set G} (hx : x ∈ s) (hu : - tsupport g + s ⊆ u) : ‖L (f t) (g (x - t))‖ ≤ u.indicator (λ t, ‖L‖ * ‖f t‖ * C) t := begin refine le_indicator (λ t ht, _) (λ t ht, _) t, { refine (L.le_op_norm₂ _ _).trans _, apply mul_le_mul_of_nonneg_left (hC _) (mul_nonneg (norm_nonneg _) (norm_nonneg _)) }, { have : x - t ∉ support g, { refine mt (λ hxt, _) ht, apply hu, refine ⟨_, _, set.neg_mem_neg.mpr (subset_closure hxt), hx, _⟩, rw [neg_sub, sub_add_cancel] }, rw [nmem_support.mp this, (L _).map_zero, norm_zero] } end lemma has_compact_support.convolution_integrand_bound_right_of_subset (hcg : has_compact_support g) (hg : continuous g) {x t : G} {s u : set G} (hx : x ∈ s) (hu : - tsupport g + s ⊆ u) : ‖L (f t) (g (x - t))‖ ≤ u.indicator (λ t, ‖L‖ * ‖f t‖ * (⨆ i, ‖g i‖)) t := begin apply convolution_integrand_bound_right_of_le_of_subset _ (λ i, _) hx hu, exact le_csupr (hg.norm.bdd_above_range_of_has_compact_support hcg.norm) _, end lemma has_compact_support.convolution_integrand_bound_right (hcg : has_compact_support g) (hg : continuous g) {x t : G} {s : set G} (hx : x ∈ s) : ‖L (f t) (g (x - t))‖ ≤ (- tsupport g + s).indicator (λ t, ‖L‖ * ‖f t‖ * (⨆ i, ‖g i‖)) t := hcg.convolution_integrand_bound_right_of_subset L hg hx subset.rfl lemma continuous.convolution_integrand_fst [has_continuous_sub G] (hg : continuous g) (t : G) : continuous (λ x, L (f t) (g (x - t))) := L.continuous₂.comp₂ continuous_const $ hg.comp $ continuous_id.sub continuous_const lemma has_compact_support.convolution_integrand_bound_left (hcf : has_compact_support f) (hf : continuous f) {x t : G} {s : set G} (hx : x ∈ s) : ‖L (f (x - t)) (g t)‖ ≤ (- tsupport f + s).indicator (λ t, ‖L‖ * (⨆ i, ‖f i‖) * ‖g t‖) t := by { convert hcf.convolution_integrand_bound_right L.flip hf hx, simp_rw [L.op_norm_flip, mul_right_comm] } end no_measurability section measurability variables [measurable_space G] {μ ν : measure G} /-- The convolution of `f` and `g` exists at `x` when the function `t ↦ L (f t) (g (x - t))` is integrable. There are various conditions on `f` and `g` to prove this. -/ def convolution_exists_at [has_sub G] (f : G → E) (g : G → E') (x : G) (L : E →L[𝕜] E' →L[𝕜] F) (μ : measure G . volume_tac) : Prop := integrable (λ t, L (f t) (g (x - t))) μ /-- The convolution of `f` and `g` exists when the function `t ↦ L (f t) (g (x - t))` is integrable for all `x : G`. There are various conditions on `f` and `g` to prove this. -/ def convolution_exists [has_sub G] (f : G → E) (g : G → E') (L : E →L[𝕜] E' →L[𝕜] F) (μ : measure G . volume_tac) : Prop := ∀ x : G, convolution_exists_at f g x L μ section convolution_exists variables {L} lemma convolution_exists_at.integrable [has_sub G] {x : G} (h : convolution_exists_at f g x L μ) : integrable (λ t, L (f t) (g (x - t))) μ := h variables (L) section group variables [add_group G] lemma measure_theory.ae_strongly_measurable.convolution_integrand' [has_measurable_add₂ G] [has_measurable_neg G] [sigma_finite ν] (hf : ae_strongly_measurable f ν) (hg : ae_strongly_measurable g $ map (λ (p : G × G), p.1 - p.2) (μ.prod ν)) : ae_strongly_measurable (λ p : G × G, L (f p.2) (g (p.1 - p.2))) (μ.prod ν) := L.ae_strongly_measurable_comp₂ hf.snd $ hg.comp_measurable measurable_sub section variables [has_measurable_add G] [has_measurable_neg G] lemma measure_theory.ae_strongly_measurable.convolution_integrand_snd' (hf : ae_strongly_measurable f μ) {x : G} (hg : ae_strongly_measurable g $ map (λ t, x - t) μ) : ae_strongly_measurable (λ t, L (f t) (g (x - t))) μ := L.ae_strongly_measurable_comp₂ hf $ hg.comp_measurable $ measurable_id.const_sub x lemma measure_theory.ae_strongly_measurable.convolution_integrand_swap_snd' {x : G} (hf : ae_strongly_measurable f $ map (λ t, x - t) μ) (hg : ae_strongly_measurable g μ) : ae_strongly_measurable (λ t, L (f (x - t)) (g t)) μ := L.ae_strongly_measurable_comp₂ (hf.comp_measurable $ measurable_id.const_sub x) hg /-- A sufficient condition to prove that `f ⋆[L, μ] g` exists. We assume that `f` is integrable on a set `s` and `g` is bounded and ae strongly measurable on `x₀ - s` (note that both properties hold if `g` is continuous with compact support). -/ lemma bdd_above.convolution_exists_at' {x₀ : G} {s : set G} (hbg : bdd_above ((λ i, ‖g i‖) '' ((λ t, - t + x₀) ⁻¹' s))) (hs : measurable_set s) (h2s : support (λ t, L (f t) (g (x₀ - t))) ⊆ s) (hf : integrable_on f s μ) (hmg : ae_strongly_measurable g $ map (λ t, x₀ - t) (μ.restrict s)) : convolution_exists_at f g x₀ L μ := begin rw [convolution_exists_at, ← integrable_on_iff_integrable_of_support_subset h2s], set s' := (λ t, - t + x₀) ⁻¹' s, have : ∀ᵐ (t : G) ∂(μ.restrict s), ‖L (f t) (g (x₀ - t))‖ ≤ s.indicator (λ t, ‖L‖ * ‖f t‖ * ⨆ i : s', ‖g i‖) t, { refine eventually_of_forall _, refine le_indicator (λ t ht, _) (λ t ht, _), { refine (L.le_op_norm₂ _ _).trans _, refine mul_le_mul_of_nonneg_left (le_csupr_set hbg $ mem_preimage.mpr _) (mul_nonneg (norm_nonneg _) (norm_nonneg _)), rwa [neg_sub, sub_add_cancel] }, { have : t ∉ support (λ t, L (f t) (g (x₀ - t))) := mt (λ h, h2s h) ht, rw [nmem_support.mp this, norm_zero] } }, refine integrable.mono' _ _ this, { rw [integrable_indicator_iff hs], exact ((hf.norm.const_mul _).mul_const _).integrable_on }, { exact hf.ae_strongly_measurable.convolution_integrand_snd' L hmg } end /-- If `‖f‖ *[μ] ‖g‖` exists, then `f *[L, μ] g` exists. -/ lemma convolution_exists_at.of_norm' {x₀ : G} (h : convolution_exists_at (λ x, ‖f x‖) (λ x, ‖g x‖) x₀ (mul ℝ ℝ) μ) (hmf : ae_strongly_measurable f μ) (hmg : ae_strongly_measurable g $ map (λ t, x₀ - t) μ) : convolution_exists_at f g x₀ L μ := begin refine (h.const_mul ‖L‖).mono' (hmf.convolution_integrand_snd' L hmg) (eventually_of_forall $ λ x, _), rw [mul_apply', ← mul_assoc], apply L.le_op_norm₂, end end section left variables [has_measurable_add₂ G] [has_measurable_neg G] [sigma_finite μ] [is_add_right_invariant μ] lemma measure_theory.ae_strongly_measurable.convolution_integrand_snd (hf : ae_strongly_measurable f μ) (hg : ae_strongly_measurable g μ) (x : G) : ae_strongly_measurable (λ t, L (f t) (g (x - t))) μ := hf.convolution_integrand_snd' L $ hg.mono' $ (quasi_measure_preserving_sub_left_of_right_invariant μ x).absolutely_continuous lemma measure_theory.ae_strongly_measurable.convolution_integrand_swap_snd (hf : ae_strongly_measurable f μ) (hg : ae_strongly_measurable g μ) (x : G) : ae_strongly_measurable (λ t, L (f (x - t)) (g t)) μ := (hf.mono' (quasi_measure_preserving_sub_left_of_right_invariant μ x).absolutely_continuous) .convolution_integrand_swap_snd' L hg /-- If `‖f‖ *[μ] ‖g‖` exists, then `f *[L, μ] g` exists. -/ lemma convolution_exists_at.of_norm {x₀ : G} (h : convolution_exists_at (λ x, ‖f x‖) (λ x, ‖g x‖) x₀ (mul ℝ ℝ) μ) (hmf : ae_strongly_measurable f μ) (hmg : ae_strongly_measurable g μ) : convolution_exists_at f g x₀ L μ := h.of_norm' L hmf $ hmg.mono' (quasi_measure_preserving_sub_left_of_right_invariant μ x₀).absolutely_continuous end left section right variables [has_measurable_add₂ G] [has_measurable_neg G] [sigma_finite μ] [is_add_right_invariant μ] [sigma_finite ν] lemma measure_theory.ae_strongly_measurable.convolution_integrand (hf : ae_strongly_measurable f ν) (hg : ae_strongly_measurable g μ) : ae_strongly_measurable (λ p : G × G, L (f p.2) (g (p.1 - p.2))) (μ.prod ν) := hf.convolution_integrand' L $ hg.mono' (quasi_measure_preserving_sub_of_right_invariant μ ν).absolutely_continuous lemma measure_theory.integrable.convolution_integrand (hf : integrable f ν) (hg : integrable g μ) : integrable (λ p : G × G, L (f p.2) (g (p.1 - p.2))) (μ.prod ν) := begin have h_meas : ae_strongly_measurable (λ (p : G × G), L (f p.2) (g (p.1 - p.2))) (μ.prod ν) := hf.ae_strongly_measurable.convolution_integrand L hg.ae_strongly_measurable, have h2_meas : ae_strongly_measurable (λ (y : G), ∫ (x : G), ‖L (f y) (g (x - y))‖ ∂μ) ν := h_meas.prod_swap.norm.integral_prod_right', simp_rw [integrable_prod_iff' h_meas], refine ⟨eventually_of_forall (λ t, (L (f t)).integrable_comp (hg.comp_sub_right t)), _⟩, refine integrable.mono' _ h2_meas (eventually_of_forall $ λ t, (_ : _ ≤ ‖L‖ * ‖f t‖ * ∫ x, ‖g (x - t)‖ ∂μ)), { simp_rw [integral_sub_right_eq_self (λ t, ‖ g t ‖)], exact (hf.norm.const_mul _).mul_const _ }, { simp_rw [← integral_mul_left], rw [real.norm_of_nonneg], { exact integral_mono_of_nonneg (eventually_of_forall $ λ t, norm_nonneg _) ((hg.comp_sub_right t).norm.const_mul _) (eventually_of_forall $ λ t, L.le_op_norm₂ _ _) }, exact integral_nonneg (λ x, norm_nonneg _) } end lemma measure_theory.integrable.ae_convolution_exists (hf : integrable f ν) (hg : integrable g μ) : ∀ᵐ x ∂μ, convolution_exists_at f g x L ν := ((integrable_prod_iff $ hf.ae_strongly_measurable.convolution_integrand L hg.ae_strongly_measurable).mp $ hf.convolution_integrand L hg).1 end right variables [topological_space G] [topological_add_group G] [borel_space G] lemma has_compact_support.convolution_exists_at {x₀ : G} (h : has_compact_support (λ t, L (f t) (g (x₀ - t)))) (hf : locally_integrable f μ) (hg : continuous g) : convolution_exists_at f g x₀ L μ := begin let u := (homeomorph.neg G).trans (homeomorph.add_right x₀), let v := (homeomorph.neg G).trans (homeomorph.add_left x₀), apply ((u.is_compact_preimage.mpr h).bdd_above_image hg.norm.continuous_on).convolution_exists_at' L is_closed_closure.measurable_set subset_closure (hf.integrable_on_is_compact h), have A : ae_strongly_measurable (g ∘ ⇑v) (μ.restrict (tsupport (λ (t : G), (L (f t)) (g (x₀ - t))))), { apply (hg.comp v.continuous).continuous_on.ae_strongly_measurable_of_is_compact h, exact (is_closed_tsupport _).measurable_set }, convert ((v.continuous.measurable.measure_preserving (μ.restrict (tsupport (λ t, L (f t) (g (x₀ - t)))))).ae_strongly_measurable_comp_iff v.to_measurable_equiv.measurable_embedding).1 A, ext x, simp only [homeomorph.neg, sub_eq_add_neg, coe_to_add_units, homeomorph.trans_apply, equiv.neg_apply, equiv.to_fun_as_coe, homeomorph.homeomorph_mk_coe, equiv.coe_fn_mk, homeomorph.coe_add_left], end lemma has_compact_support.convolution_exists_right (hcg : has_compact_support g) (hf : locally_integrable f μ) (hg : continuous g) : convolution_exists f g L μ := begin intro x₀, refine has_compact_support.convolution_exists_at L _ hf hg, refine (hcg.comp_homeomorph (homeomorph.sub_left x₀)).mono _, refine λ t, mt (λ ht : g (x₀ - t) = 0, _), simp_rw [ht, (L _).map_zero] end lemma has_compact_support.convolution_exists_left_of_continuous_right (hcf : has_compact_support f) (hf : locally_integrable f μ) (hg : continuous g) : convolution_exists f g L μ := begin intro x₀, refine has_compact_support.convolution_exists_at L _ hf hg, refine hcf.mono _, refine λ t, mt (λ ht : f t = 0, _), simp_rw [ht, L.map_zero₂] end end group section comm_group variables [add_comm_group G] section measurable_group variables [has_measurable_neg G] [is_add_left_invariant μ] /-- A sufficient condition to prove that `f ⋆[L, μ] g` exists. We assume that the integrand has compact support and `g` is bounded on this support (note that both properties hold if `g` is continuous with compact support). We also require that `f` is integrable on the support of the integrand, and that both functions are strongly measurable. This is a variant of `bdd_above.convolution_exists_at'` in an abelian group with a left-invariant measure. This allows us to state the boundedness and measurability of `g` in a more natural way. -/ lemma bdd_above.convolution_exists_at [has_measurable_add₂ G] [sigma_finite μ] {x₀ : G} {s : set G} (hbg : bdd_above ((λ i, ‖g i‖) '' ((λ t, x₀ - t) ⁻¹' s))) (hs : measurable_set s) (h2s : support (λ t, L (f t) (g (x₀ - t))) ⊆ s) (hf : integrable_on f s μ) (hmg : ae_strongly_measurable g μ) : convolution_exists_at f g x₀ L μ := begin refine bdd_above.convolution_exists_at' L _ hs h2s hf _, { simp_rw [← sub_eq_neg_add, hbg] }, { have : ae_strongly_measurable g (map (λ (t : G), x₀ - t) μ), from hmg.mono' (quasi_measure_preserving_sub_left_of_right_invariant μ x₀).absolutely_continuous, apply this.mono_measure, exact map_mono_of_ae_measurable restrict_le_self (measurable_const.sub measurable_id').ae_measurable } end variables {L} [has_measurable_add G] [is_neg_invariant μ] lemma convolution_exists_at_flip : convolution_exists_at g f x L.flip μ ↔ convolution_exists_at f g x L μ := by simp_rw [convolution_exists_at, ← integrable_comp_sub_left (λ t, L (f t) (g (x - t))) x, sub_sub_cancel, flip_apply] lemma convolution_exists_at.integrable_swap (h : convolution_exists_at f g x L μ) : integrable (λ t, L (f (x - t)) (g t)) μ := by { convert h.comp_sub_left x, simp_rw [sub_sub_self] } lemma convolution_exists_at_iff_integrable_swap : convolution_exists_at f g x L μ ↔ integrable (λ t, L (f (x - t)) (g t)) μ := convolution_exists_at_flip.symm end measurable_group variables [topological_space G] [topological_add_group G] [borel_space G] [is_add_left_invariant μ] [is_neg_invariant μ] lemma has_compact_support.convolution_exists_left (hcf : has_compact_support f) (hf : continuous f) (hg : locally_integrable g μ) : convolution_exists f g L μ := λ x₀, convolution_exists_at_flip.mp $ hcf.convolution_exists_right L.flip hg hf x₀ lemma has_compact_support.convolution_exists_right_of_continuous_left (hcg : has_compact_support g) (hf : continuous f) (hg : locally_integrable g μ) : convolution_exists f g L μ := λ x₀, convolution_exists_at_flip.mp $ hcg.convolution_exists_left_of_continuous_right L.flip hg hf x₀ end comm_group end convolution_exists variables [normed_space ℝ F] [complete_space F] /-- The convolution of two functions `f` and `g` with respect to a continuous bilinear map `L` and measure `μ`. It is defined to be `(f ⋆[L, μ] g) x = ∫ t, L (f t) (g (x - t)) ∂μ`. -/ noncomputable def convolution [has_sub G] (f : G → E) (g : G → E') (L : E →L[𝕜] E' →L[𝕜] F) (μ : measure G . volume_tac) : G → F := λ x, ∫ t, L (f t) (g (x - t)) ∂μ localized "notation (name := convolution) f ` ⋆[`:67 L:67 `, ` μ:67 `] `:0 g:66 := convolution f g L μ" in convolution localized "notation (name := convolution.volume) f ` ⋆[`:67 L:67 `]`:0 g:66 := convolution f g L measure_theory.measure_space.volume" in convolution localized "notation (name := convolution.lsmul) f ` ⋆ `:67 g:66 := convolution f g (continuous_linear_map.lsmul ℝ ℝ) measure_theory.measure_space.volume" in convolution lemma convolution_def [has_sub G] : (f ⋆[L, μ] g) x = ∫ t, L (f t) (g (x - t)) ∂μ := rfl /-- The definition of convolution where the bilinear operator is scalar multiplication. Note: it often helps the elaborator to give the type of the convolution explicitly. -/ lemma convolution_lsmul [has_sub G] {f : G → 𝕜} {g : G → F} : (f ⋆[lsmul 𝕜 𝕜, μ] g : G → F) x = ∫ t, f t • g (x - t) ∂μ := rfl /-- The definition of convolution where the bilinear operator is multiplication. -/ lemma convolution_mul [has_sub G] [normed_space ℝ 𝕜] [complete_space 𝕜] {f : G → 𝕜} {g : G → 𝕜} : (f ⋆[mul 𝕜 𝕜, μ] g) x = ∫ t, f t * g (x - t) ∂μ := rfl section group variables {L} [add_group G] lemma smul_convolution [smul_comm_class ℝ 𝕜 F] {y : 𝕜} : (y • f) ⋆[L, μ] g = y • (f ⋆[L, μ] g) := by { ext, simp only [pi.smul_apply, convolution_def, ← integral_smul, L.map_smul₂] } lemma convolution_smul [smul_comm_class ℝ 𝕜 F] {y : 𝕜} : f ⋆[L, μ] (y • g) = y • (f ⋆[L, μ] g) := by { ext, simp only [pi.smul_apply, convolution_def, ← integral_smul, (L _).map_smul] } @[simp] lemma zero_convolution : 0 ⋆[L, μ] g = 0 := by { ext, simp_rw [convolution_def, pi.zero_apply, L.map_zero₂, integral_zero] } @[simp] lemma convolution_zero : f ⋆[L, μ] 0 = 0 := by { ext, simp_rw [convolution_def, pi.zero_apply, (L _).map_zero, integral_zero] } lemma convolution_exists_at.distrib_add {x : G} (hfg : convolution_exists_at f g x L μ) (hfg' : convolution_exists_at f g' x L μ) : (f ⋆[L, μ] (g + g')) x = (f ⋆[L, μ] g) x + (f ⋆[L, μ] g') x := by simp only [convolution_def, (L _).map_add, pi.add_apply, integral_add hfg hfg'] lemma convolution_exists.distrib_add (hfg : convolution_exists f g L μ) (hfg' : convolution_exists f g' L μ) : f ⋆[L, μ] (g + g') = f ⋆[L, μ] g + f ⋆[L, μ] g' := by { ext, exact (hfg x).distrib_add (hfg' x) } lemma convolution_exists_at.add_distrib {x : G} (hfg : convolution_exists_at f g x L μ) (hfg' : convolution_exists_at f' g x L μ) : ((f + f') ⋆[L, μ] g) x = (f ⋆[L, μ] g) x + (f' ⋆[L, μ] g) x := by simp only [convolution_def, L.map_add₂, pi.add_apply, integral_add hfg hfg'] lemma convolution_exists.add_distrib (hfg : convolution_exists f g L μ) (hfg' : convolution_exists f' g L μ) : (f + f') ⋆[L, μ] g = f ⋆[L, μ] g + f' ⋆[L, μ] g := by { ext, exact (hfg x).add_distrib (hfg' x) } lemma convolution_mono_right {f g g' : G → ℝ} (hfg : convolution_exists_at f g x (lsmul ℝ ℝ) μ) (hfg' : convolution_exists_at f g' x (lsmul ℝ ℝ) μ) (hf : ∀ x, 0 ≤ f x) (hg : ∀ x, g x ≤ g' x) : (f ⋆[lsmul ℝ ℝ, μ] g) x ≤ (f ⋆[lsmul ℝ ℝ, μ] g') x := begin apply integral_mono hfg hfg', simp only [lsmul_apply, algebra.id.smul_eq_mul], assume t, apply mul_le_mul_of_nonneg_left (hg _) (hf _), end lemma convolution_mono_right_of_nonneg {f g g' : G → ℝ} (hfg' : convolution_exists_at f g' x (lsmul ℝ ℝ) μ) (hf : ∀ x, 0 ≤ f x) (hg : ∀ x, g x ≤ g' x) (hg' : ∀ x, 0 ≤ g' x) : (f ⋆[lsmul ℝ ℝ, μ] g) x ≤ (f ⋆[lsmul ℝ ℝ, μ] g') x := begin by_cases H : convolution_exists_at f g x (lsmul ℝ ℝ) μ, { exact convolution_mono_right H hfg' hf hg }, have : (f ⋆[lsmul ℝ ℝ, μ] g) x = 0 := integral_undef H, rw this, exact integral_nonneg (λ y, mul_nonneg (hf y) (hg' (x - y))), end variables (L) lemma convolution_congr [has_measurable_add₂ G] [has_measurable_neg G] [sigma_finite μ] [is_add_right_invariant μ] (h1 : f =ᵐ[μ] f') (h2 : g =ᵐ[μ] g') : f ⋆[L, μ] g = f' ⋆[L, μ] g' := begin ext x, apply integral_congr_ae, exact (h1.prod_mk $ h2.comp_tendsto (quasi_measure_preserving_sub_left_of_right_invariant μ x).tendsto_ae).fun_comp ↿(λ x y, L x y) end lemma support_convolution_subset_swap : support (f ⋆[L, μ] g) ⊆ support g + support f := begin intros x h2x, by_contra hx, apply h2x, simp_rw [set.mem_add, not_exists, not_and_distrib, nmem_support] at hx, rw [convolution_def], convert integral_zero G F, ext t, rcases hx (x - t) t with h|h|h, { rw [h, (L _).map_zero] }, { rw [h, L.map_zero₂] }, { exact (h $ sub_add_cancel x t).elim } end section variables [has_measurable_add₂ G] [has_measurable_neg G] [sigma_finite μ] [is_add_right_invariant μ] lemma measure_theory.integrable.integrable_convolution (hf : integrable f μ) (hg : integrable g μ) : integrable (f ⋆[L, μ] g) μ := (hf.convolution_integrand L hg).integral_prod_left end variables [topological_space G] variables [topological_add_group G] lemma has_compact_support.convolution [t2_space G] (hcf : has_compact_support f) (hcg : has_compact_support g) : has_compact_support (f ⋆[L, μ] g) := is_compact_of_is_closed_subset (hcg.is_compact.add hcf) is_closed_closure $ closure_minimal ((support_convolution_subset_swap L).trans $ add_subset_add subset_closure subset_closure) (hcg.is_compact.add hcf).is_closed variables [borel_space G] [first_countable_topology G] [topological_space P] [first_countable_topology P] /-- The convolution `f * g` is continuous if `f` is locally integrable and `g` is continuous and compactly supported. Version where `g` depends on an additional parameter in a subset `s` of a parameter space `P` (and the compact support `k` is independent of the parameter in `s`), not assuming `t2_space G`. -/ lemma continuous_on_convolution_right_with_param' {g : P → G → E'} {s : set P} {k : set G} (hk : is_compact k) (h'k : is_closed k) (hgs : ∀ p, ∀ x, p ∈ s → x ∉ k → g p x = 0) (hf : locally_integrable f μ) (hg : continuous_on (↿g) (s ×ˢ univ)) : continuous_on (λ (q : P × G), (f ⋆[L, μ] g q.1) q.2) (s ×ˢ univ) := begin assume q₀ hq₀, replace hq₀ : q₀.1 ∈ s, by simpa only [mem_prod, mem_univ, and_true] using hq₀, have A : ∀ p ∈ s, continuous (g p), { assume p hp, apply hg.comp_continuous (continuous_const.prod_mk continuous_id') (λ x, _), simpa only [prod_mk_mem_set_prod_eq, mem_univ, and_true] using hp }, have B : ∀ p ∈ s, tsupport (g p) ⊆ k := λ p hp, closure_minimal (support_subset_iff'.2 (λ z hz, hgs _ _ hp hz)) h'k, /- We find a small neighborhood of `{q₀.1} × k` on which the function is uniformly bounded. This follows from the continuity at all points of the compact set `k`. -/ obtain ⟨w, C, w_open, q₀w, Cnonneg, hw⟩ : ∃ w C, is_open w ∧ q₀.1 ∈ w ∧ 0 ≤ C ∧ ∀ p x, p ∈ w ∩ s → ‖g p x‖ ≤ C, { have A : is_compact ({q₀.1} ×ˢ k), from is_compact_singleton.prod hk, obtain ⟨t, kt, t_open, ht⟩ : ∃ t, {q₀.1} ×ˢ k ⊆ t ∧ is_open t ∧ bounded (↿g '' (t ∩ s ×ˢ univ)), { apply exists_is_open_bounded_image_inter_of_is_compact_of_continuous_on A _ hg, simp only [prod_subset_prod_iff, hq₀, singleton_subset_iff, subset_univ, and_self, true_or] }, obtain ⟨C, Cpos, hC⟩ : ∃ C, 0 < C ∧ (↿g) '' (t ∩ s ×ˢ univ) ⊆ closed_ball (0 : E') C, from ht.subset_ball_lt 0 0, obtain ⟨w, w_open, q₀w, hw⟩ : ∃ w, is_open w ∧ q₀.1 ∈ w ∧ w ×ˢ k ⊆ t, { obtain ⟨w, v, w_open, v_open, hw, hv, hvw⟩ : ∃ (w : set P) (v : set G), is_open w ∧ is_open v ∧ {q₀.fst} ⊆ w ∧ k ⊆ v ∧ w ×ˢ v ⊆ t, from generalized_tube_lemma is_compact_singleton hk t_open kt, exact ⟨w, w_open, singleton_subset_iff.1 hw, subset.trans (set.prod_mono subset.rfl hv) hvw⟩ }, refine ⟨w, C, w_open, q₀w, Cpos.le, _⟩, rintros p x ⟨hp, hps⟩, by_cases hx : x ∈ k, { have H : (p, x) ∈ t, { apply hw, simp only [prod_mk_mem_set_prod_eq, hp, hx, and_true], }, have H' : (p, x) ∈ (s ×ˢ univ : set (P × G)), by simpa only [prod_mk_mem_set_prod_eq, mem_univ, and_true] using hps, have : g p x ∈ closed_ball (0 : E') C, from hC (mem_image_of_mem _ ⟨H, H'⟩), rwa mem_closed_ball_zero_iff at this }, { have : g p x = 0, from hgs _ _ hps hx, rw this, simpa only [norm_zero] using Cpos.le } }, have I1 : ∀ᶠ (q : P × G) in 𝓝[s ×ˢ univ] q₀, ae_strongly_measurable (λ (a : G), L (f a) (g q.1 (q.2 - a))) μ, { filter_upwards [self_mem_nhds_within], rintros ⟨p, x⟩ ⟨hp, hx⟩, refine (has_compact_support.convolution_exists_right L _ hf (A _ hp) _).1, exact is_compact_of_is_closed_subset hk (is_closed_tsupport _) (B p hp) }, let K' := - k + {q₀.2}, have hK' : is_compact K' := hk.neg.add is_compact_singleton, obtain ⟨U, U_open, K'U, hU⟩ : ∃ U, is_open U ∧ K' ⊆ U ∧ integrable_on f U μ, from hf.integrable_on_nhds_is_compact hK', let bound : G → ℝ := indicator U (λ a, ‖L‖ * ‖f a‖ * C), have I2 : ∀ᶠ (q : P × G) in 𝓝[s ×ˢ univ] q₀, ∀ᵐ a ∂μ, ‖L (f a) (g q.1 (q.2 - a))‖ ≤ bound a, { obtain ⟨V, V_mem, hV⟩ : ∃ (V : set G) (H : V ∈ 𝓝 (0 : G)), K' + V ⊆ U, from compact_open_separated_add_right hK' U_open K'U, have : ((w ∩ s) ×ˢ ({q₀.2} + V) : set (P × G)) ∈ 𝓝[s ×ˢ univ] q₀, { conv_rhs { rw [← @prod.mk.eta _ _ q₀, nhds_within_prod_eq, nhds_within_univ] }, refine filter.prod_mem_prod _ (singleton_add_mem_nhds_of_nhds_zero q₀.2 V_mem), exact mem_nhds_within_iff_exists_mem_nhds_inter.2 ⟨w, w_open.mem_nhds q₀w, subset.rfl⟩ }, filter_upwards [this], rintros ⟨p, x⟩ hpx, simp only [prod_mk_mem_set_prod_eq] at hpx, apply eventually_of_forall (λ a, _), apply convolution_integrand_bound_right_of_le_of_subset _ _ hpx.2 _, { assume x, exact hw _ _ hpx.1 }, { rw ← add_assoc, apply subset.trans (add_subset_add_right (add_subset_add_right _)) hV, rw neg_subset_neg, exact B p hpx.1.2 } }, have I3 : integrable bound μ, { rw [integrable_indicator_iff U_open.measurable_set], exact (hU.norm.const_mul _).mul_const _ }, have I4 : ∀ᵐ (a : G) ∂μ, continuous_within_at (λ (q : P × G), L (f a) (g q.1 (q.2 - a))) (s ×ˢ univ) q₀, { apply eventually_of_forall (λ a, _), suffices H : continuous_within_at (λ (q : P × G), (f a, g q.1 (q.2 - a))) (s ×ˢ univ) q₀, from L.continuous₂.continuous_at.comp_continuous_within_at H, apply continuous_within_at_const.prod, change continuous_within_at (λ (q : P × G), ↿g (q.1, q.2 - a)) (s ×ˢ univ) q₀, have : continuous_at (λ (q : P × G), (q.1, q.2 - a)) (q₀.1, q₀.2), from (continuous_fst.prod_mk (continuous_snd.sub continuous_const)).continuous_at, rw ← @prod.mk.eta _ _ q₀, have h'q₀ : (q₀.1, q₀.2 - a) ∈ (s ×ˢ univ : set (P × G)) := ⟨hq₀, mem_univ _⟩, refine continuous_within_at.comp (hg _ h'q₀) this.continuous_within_at _, rintros ⟨q, x⟩ ⟨hq, hx⟩, exact ⟨hq, mem_univ _⟩ }, exact continuous_within_at_of_dominated I1 I2 I3 I4, end /-- The convolution `f * g` is continuous if `f` is locally integrable and `g` is continuous and compactly supported. Version where `g` depends on an additional parameter in a subset `s` of a parameter space `P` (and the compact support `k` is independent of the parameter in `s`). -/ lemma continuous_on_convolution_right_with_param [t2_space G] {g : P → G → E'} {s : set P} {k : set G} (hk : is_compact k) (hgs : ∀ p, ∀ x, p ∈ s → x ∉ k → g p x = 0) (hf : locally_integrable f μ) (hg : continuous_on (↿g) (s ×ˢ univ)) : continuous_on (λ (q : P × G), (f ⋆[L, μ] g q.1) q.2) (s ×ˢ univ) := continuous_on_convolution_right_with_param' L hk hk.is_closed hgs hf hg /-- The convolution `f * g` is continuous if `f` is locally integrable and `g` is continuous and compactly supported. Version where `g` depends on an additional parameter in an open subset `s` of a parameter space `P` (and the compact support `k` is independent of the parameter in `s`), given in terms of compositions with an additional continuous map. Version not assuming `t2_space G`. -/ lemma continuous_on_convolution_right_with_param_comp' {s : set P} {v : P → G} (hv : continuous_on v s) {g : P → G → E'} {k : set G} (hk : is_compact k) (h'k : is_closed k) (hgs : ∀ p, ∀ x, p ∈ s → x ∉ k → g p x = 0) (hf : locally_integrable f μ) (hg : continuous_on (↿g) (s ×ˢ univ)) : continuous_on (λ x, (f ⋆[L, μ] g x) (v x)) s := begin apply (continuous_on_convolution_right_with_param' L hk h'k hgs hf hg).comp (continuous_on_id.prod hv), assume x hx, simp only [hx, prod_mk_mem_set_prod_eq, mem_univ, and_self, id.def], end /-- The convolution `f * g` is continuous if `f` is locally integrable and `g` is continuous and compactly supported. Version where `g` depends on an additional parameter in an open subset `s` of a parameter space `P` (and the compact support `k` is independent of the parameter in `s`), given in terms of compositions with an additional continuous map. -/ lemma continuous_on_convolution_right_with_param_comp [t2_space G] {s : set P} {v : P → G} (hv : continuous_on v s) {g : P → G → E'} {k : set G} (hk : is_compact k) (hgs : ∀ p, ∀ x, p ∈ s → x ∉ k → g p x = 0) (hf : locally_integrable f μ) (hg : continuous_on (↿g) (s ×ˢ univ)) : continuous_on (λ x, (f ⋆[L, μ] g x) (v x)) s := continuous_on_convolution_right_with_param_comp' L hv hk hk.is_closed hgs hf hg /-- The convolution is continuous if one function is locally integrable and the other has compact support and is continuous. -/ lemma has_compact_support.continuous_convolution_right (hcg : has_compact_support g) (hf : locally_integrable f μ) (hg : continuous g) : continuous (f ⋆[L, μ] g) := begin rw continuous_iff_continuous_on_univ, let g' : G → G → E' := λ p q, g q, have : continuous_on (↿g') (univ ×ˢ univ) := (hg.comp continuous_snd).continuous_on, exact continuous_on_convolution_right_with_param_comp' L (continuous_iff_continuous_on_univ.1 continuous_id) hcg (is_closed_tsupport _) (λ p x hp hx, image_eq_zero_of_nmem_tsupport hx) hf this, end /-- The convolution is continuous if one function is integrable and the other is bounded and continuous. -/ lemma bdd_above.continuous_convolution_right_of_integrable [second_countable_topology G] (hbg : bdd_above (range (λ x, ‖g x‖))) (hf : integrable f μ) (hg : continuous g) : continuous (f ⋆[L, μ] g) := begin refine continuous_iff_continuous_at.mpr (λ x₀, _), have : ∀ᶠ x in 𝓝 x₀, ∀ᵐ (t : G) ∂μ, ‖L (f t) (g (x - t))‖ ≤ ‖L‖ * ‖f t‖ * (⨆ i, ‖g i‖), { refine eventually_of_forall (λ x, eventually_of_forall $ λ t, _), refine (L.le_op_norm₂ _ _).trans _, exact mul_le_mul_of_nonneg_left (le_csupr hbg $ x - t) (mul_nonneg (norm_nonneg _) (norm_nonneg _)) }, refine continuous_at_of_dominated _ this _ _, { exact eventually_of_forall (λ x, hf.ae_strongly_measurable.convolution_integrand_snd' L hg.ae_strongly_measurable) }, { exact (hf.norm.const_mul _).mul_const _ }, { exact eventually_of_forall (λ t, (L.continuous₂.comp₂ continuous_const $ hg.comp $ continuous_id.sub $ by apply continuous_const).continuous_at) } end end group section comm_group variables [add_comm_group G] lemma support_convolution_subset : support (f ⋆[L, μ] g) ⊆ support f + support g := (support_convolution_subset_swap L).trans (add_comm _ _).subset variables [is_add_left_invariant μ] [is_neg_invariant μ] section measurable variables [has_measurable_neg G] variables [has_measurable_add G] variable (L) /-- Commutativity of convolution -/ lemma convolution_flip : g ⋆[L.flip, μ] f = f ⋆[L, μ] g := begin ext1 x, simp_rw [convolution_def], rw [← integral_sub_left_eq_self _ μ x], simp_rw [sub_sub_self, flip_apply] end /-- The symmetric definition of convolution. -/ lemma convolution_eq_swap : (f ⋆[L, μ] g) x = ∫ t, L (f (x - t)) (g t) ∂μ := by { rw [← convolution_flip], refl } /-- The symmetric definition of convolution where the bilinear operator is scalar multiplication. -/ lemma convolution_lsmul_swap {f : G → 𝕜} {g : G → F}: (f ⋆[lsmul 𝕜 𝕜, μ] g : G → F) x = ∫ t, f (x - t) • g t ∂μ := convolution_eq_swap _ /-- The symmetric definition of convolution where the bilinear operator is multiplication. -/ lemma convolution_mul_swap [normed_space ℝ 𝕜] [complete_space 𝕜] {f : G → 𝕜} {g : G → 𝕜} : (f ⋆[mul 𝕜 𝕜, μ] g) x = ∫ t, f (x - t) * g t ∂μ := convolution_eq_swap _ /-- The convolution of two even functions is also even. -/ lemma convolution_neg_of_neg_eq (h1 : ∀ᵐ x ∂μ, f (-x) = f x) (h2 : ∀ᵐ x ∂μ, g (-x) = g x) : (f ⋆[L, μ] g) (-x) = (f ⋆[L, μ] g) x := calc ∫ (t : G), (L (f t)) (g (-x - t)) ∂μ = ∫ (t : G), (L (f (-t))) (g (x + t)) ∂μ : begin apply integral_congr_ae, filter_upwards [h1, (eventually_add_left_iff μ x).2 h2] with t ht h't, simp_rw [ht, ← h't, neg_add'], end ... = ∫ (t : G), (L (f t)) (g (x - t)) ∂μ : by { rw ← integral_neg_eq_self, simp only [neg_neg, ← sub_eq_add_neg] } end measurable variables [topological_space G] variables [topological_add_group G] variables [borel_space G] lemma has_compact_support.continuous_convolution_left [first_countable_topology G] (hcf : has_compact_support f) (hf : continuous f) (hg : locally_integrable g μ) : continuous (f ⋆[L, μ] g) := by { rw [← convolution_flip], exact hcf.continuous_convolution_right L.flip hg hf } lemma bdd_above.continuous_convolution_left_of_integrable [second_countable_topology G] (hbf : bdd_above (range (λ x, ‖f x‖))) (hf : continuous f) (hg : integrable g μ) : continuous (f ⋆[L, μ] g) := by { rw [← convolution_flip], exact hbf.continuous_convolution_right_of_integrable L.flip hg hf } end comm_group section normed_add_comm_group variables [seminormed_add_comm_group G] /-- Compute `(f ⋆ g) x₀` if the support of the `f` is within `metric.ball 0 R`, and `g` is constant on `metric.ball x₀ R`. We can simplify the RHS further if we assume `f` is integrable, but also if `L = (•)` or more generally if `L` has a `antilipschitz_with`-condition. -/ lemma convolution_eq_right' {x₀ : G} {R : ℝ} (hf : support f ⊆ ball (0 : G) R) (hg : ∀ x ∈ ball x₀ R, g x = g x₀) : (f ⋆[L, μ] g) x₀ = ∫ t, L (f t) (g x₀) ∂μ := begin have h2 : ∀ t, L (f t) (g (x₀ - t)) = L (f t) (g x₀), { intro t, by_cases ht : t ∈ support f, { have h2t := hf ht, rw [mem_ball_zero_iff] at h2t, specialize hg (x₀ - t), rw [sub_eq_add_neg, add_mem_ball_iff_norm, norm_neg, ← sub_eq_add_neg] at hg, rw [hg h2t] }, { rw [nmem_support] at ht, simp_rw [ht, L.map_zero₂] } }, simp_rw [convolution_def, h2], end variables [borel_space G] [second_countable_topology G] variables [is_add_left_invariant μ] [sigma_finite μ] /-- Approximate `(f ⋆ g) x₀` if the support of the `f` is bounded within a ball, and `g` is near `g x₀` on a ball with the same radius around `x₀`. See `dist_convolution_le` for a special case. We can simplify the second argument of `dist` further if we add some extra type-classes on `E` and `𝕜` or if `L` is scalar multiplication. -/ lemma dist_convolution_le' {x₀ : G} {R ε : ℝ} {z₀ : E'} (hε : 0 ≤ ε) (hif : integrable f μ) (hf : support f ⊆ ball (0 : G) R) (hmg : ae_strongly_measurable g μ) (hg : ∀ x ∈ ball x₀ R, dist (g x) z₀ ≤ ε) : dist ((f ⋆[L, μ] g : G → F) x₀) (∫ t, L (f t) z₀ ∂μ) ≤ ‖L‖ * ∫ x, ‖f x‖ ∂μ * ε := begin have hfg : convolution_exists_at f g x₀ L μ, { refine bdd_above.convolution_exists_at L _ metric.is_open_ball.measurable_set (subset_trans _ hf) hif.integrable_on hmg, swap, { refine λ t, mt (λ ht : f t = 0, _), simp_rw [ht, L.map_zero₂] }, rw [bdd_above_def], refine ⟨‖z₀‖ + ε, _⟩, rintro _ ⟨x, hx, rfl⟩, refine norm_le_norm_add_const_of_dist_le (hg x _), rwa [mem_ball_iff_norm, norm_sub_rev, ← mem_ball_zero_iff] }, have h2 : ∀ t, dist (L (f t) (g (x₀ - t))) (L (f t) z₀) ≤ ‖L (f t)‖ * ε, { intro t, by_cases ht : t ∈ support f, { have h2t := hf ht, rw [mem_ball_zero_iff] at h2t, specialize hg (x₀ - t), rw [sub_eq_add_neg, add_mem_ball_iff_norm, norm_neg, ← sub_eq_add_neg] at hg, refine ((L (f t)).dist_le_op_norm _ _).trans _, exact mul_le_mul_of_nonneg_left (hg h2t) (norm_nonneg _) }, { rw [nmem_support] at ht, simp_rw [ht, L.map_zero₂, L.map_zero, norm_zero, zero_mul, dist_self] } }, simp_rw [convolution_def], simp_rw [dist_eq_norm] at h2 ⊢, rw [← integral_sub hfg.integrable], swap, { exact (L.flip z₀).integrable_comp hif }, refine (norm_integral_le_of_norm_le ((L.integrable_comp hif).norm.mul_const ε) (eventually_of_forall h2)).trans _, rw [integral_mul_right], refine mul_le_mul_of_nonneg_right _ hε, have h3 : ∀ t, ‖L (f t)‖ ≤ ‖L‖ * ‖f t‖, { intros t, exact L.le_op_norm (f t) }, refine (integral_mono (L.integrable_comp hif).norm (hif.norm.const_mul _) h3).trans_eq _, rw [integral_mul_left] end variables [normed_space ℝ E] [normed_space ℝ E'] [complete_space E'] /-- Approximate `f ⋆ g` if the support of the `f` is bounded within a ball, and `g` is near `g x₀` on a ball with the same radius around `x₀`. This is a special case of `dist_convolution_le'` where `L` is `(•)`, `f` has integral 1 and `f` is nonnegative. -/ lemma dist_convolution_le {f : G → ℝ} {x₀ : G} {R ε : ℝ} {z₀ : E'} (hε : 0 ≤ ε) (hf : support f ⊆ ball (0 : G) R) (hnf : ∀ x, 0 ≤ f x) (hintf : ∫ x, f x ∂μ = 1) (hmg : ae_strongly_measurable g μ) (hg : ∀ x ∈ ball x₀ R, dist (g x) z₀ ≤ ε) : dist ((f ⋆[lsmul ℝ ℝ, μ] g : G → E') x₀) z₀ ≤ ε := begin have hif : integrable f μ, { by_contra hif, exact zero_ne_one ((integral_undef hif).symm.trans hintf) }, convert (dist_convolution_le' _ hε hif hf hmg hg).trans _, { simp_rw [lsmul_apply, integral_smul_const, hintf, one_smul] }, { simp_rw [real.norm_of_nonneg (hnf _), hintf, mul_one], exact (mul_le_mul_of_nonneg_right op_norm_lsmul_le hε).trans_eq (one_mul ε) } end /-- `(φ i ⋆ g i) (k i)` tends to `z₀` as `i` tends to some filter `l` if * `φ` is a sequence of nonnegative functions with integral `1` as `i` tends to `l`; * The support of `φ` tends to small neighborhoods around `(0 : G)` as `i` tends to `l`; * `g i` is `mu`-a.e. strongly measurable as `i` tends to `l`; * `g i x` tends to `z₀` as `(i, x)` tends to `l ×ᶠ 𝓝 x₀`; * `k i` tends to `x₀`. See also `cont_diff_bump.convolution_tendsto_right`. -/ lemma convolution_tendsto_right {ι} {g : ι → G → E'} {l : filter ι} {x₀ : G} {z₀ : E'} {φ : ι → G → ℝ} {k : ι → G} (hnφ : ∀ᶠ i in l, ∀ x, 0 ≤ φ i x) (hiφ : ∀ᶠ i in l, ∫ x, φ i x ∂μ = 1) -- todo: we could weaken this to "the integral tends to 1" (hφ : tendsto (λ n, support (φ n)) l (𝓝 0).small_sets) (hmg : ∀ᶠ i in l, ae_strongly_measurable (g i) μ) (hcg : tendsto (uncurry g) (l ×ᶠ 𝓝 x₀) (𝓝 z₀)) (hk : tendsto k l (𝓝 x₀)) : tendsto (λ i : ι, (φ i ⋆[lsmul ℝ ℝ, μ] g i : G → E') (k i)) l (𝓝 z₀) := begin simp_rw [tendsto_small_sets_iff] at hφ, rw [metric.tendsto_nhds] at hcg ⊢, simp_rw [metric.eventually_prod_nhds_iff] at hcg, intros ε hε, have h2ε : 0 < ε / 3 := div_pos hε (by norm_num), obtain ⟨p, hp, δ, hδ, hgδ⟩ := hcg _ h2ε, dsimp only [uncurry] at hgδ, have h2k := hk.eventually (ball_mem_nhds x₀ $ half_pos hδ), have h2φ := (hφ (ball (0 : G) _) $ ball_mem_nhds _ (half_pos hδ)), filter_upwards [hp, h2k, h2φ, hnφ, hiφ, hmg] with i hpi hki hφi hnφi hiφi hmgi, have hgi : dist (g i (k i)) z₀ < ε / 3 := hgδ hpi (hki.trans $ half_lt_self hδ), have h1 : ∀ x' ∈ ball (k i) (δ / 2), dist (g i x') (g i (k i)) ≤ ε / 3 + ε / 3, { intros x' hx', refine (dist_triangle_right _ _ _).trans (add_le_add (hgδ hpi _).le hgi.le), exact ((dist_triangle _ _ _).trans_lt (add_lt_add hx'.out hki)).trans_eq (add_halves δ) }, have := dist_convolution_le (add_pos h2ε h2ε).le hφi hnφi hiφi hmgi h1, refine ((dist_triangle _ _ _).trans_lt (add_lt_add_of_le_of_lt this hgi)).trans_eq _, field_simp, ring_nf end end normed_add_comm_group namespace cont_diff_bump variables {n : ℕ∞} variables [normed_space ℝ E'] variables [normed_add_comm_group G] [normed_space ℝ G] [has_cont_diff_bump G] variables [complete_space E'] variables {a : G} {φ : cont_diff_bump (0 : G)} /-- If `φ` is a bump function, compute `(φ ⋆ g) x₀` if `g` is constant on `metric.ball x₀ φ.R`. -/ lemma convolution_eq_right {x₀ : G} (hg : ∀ x ∈ ball x₀ φ.R, g x = g x₀) : (φ ⋆[lsmul ℝ ℝ, μ] g : G → E') x₀ = integral μ φ • g x₀ := by simp_rw [convolution_eq_right' _ φ.support_eq.subset hg, lsmul_apply, integral_smul_const] variables [borel_space G] variables [is_locally_finite_measure μ] [is_open_pos_measure μ] variables [finite_dimensional ℝ G] /-- If `φ` is a normed bump function, compute `φ ⋆ g` if `g` is constant on `metric.ball x₀ φ.R`. -/ lemma normed_convolution_eq_right {x₀ : G} (hg : ∀ x ∈ ball x₀ φ.R, g x = g x₀) : (φ.normed μ ⋆[lsmul ℝ ℝ, μ] g : G → E') x₀ = g x₀ := by { simp_rw [convolution_eq_right' _ φ.support_normed_eq.subset hg, lsmul_apply], exact integral_normed_smul φ μ (g x₀) } variables [is_add_left_invariant μ] /-- If `φ` is a normed bump function, approximate `(φ ⋆ g) x₀` if `g` is near `g x₀` on a ball with radius `φ.R` around `x₀`. -/ lemma dist_normed_convolution_le {x₀ : G} {ε : ℝ} (hmg : ae_strongly_measurable g μ) (hg : ∀ x ∈ ball x₀ φ.R, dist (g x) (g x₀) ≤ ε) : dist ((φ.normed μ ⋆[lsmul ℝ ℝ, μ] g : G → E') x₀) (g x₀) ≤ ε := dist_convolution_le (by simp_rw [← dist_self (g x₀), hg x₀ (mem_ball_self φ.R_pos)]) φ.support_normed_eq.subset φ.nonneg_normed φ.integral_normed hmg hg /-- `(φ i ⋆ g i) (k i)` tends to `z₀` as `i` tends to some filter `l` if * `φ` is a sequence of normed bump functions such that `(φ i).R` tends to `0` as `i` tends to `l`; * `g i` is `mu`-a.e. strongly measurable as `i` tends to `l`; * `g i x` tends to `z₀` as `(i, x)` tends to `l ×ᶠ 𝓝 x₀`; * `k i` tends to `x₀`. -/ lemma convolution_tendsto_right {ι} {φ : ι → cont_diff_bump (0 : G)} {g : ι → G → E'} {k : ι → G} {x₀ : G} {z₀ : E'} {l : filter ι} (hφ : tendsto (λ i, (φ i).R) l (𝓝 0)) (hig : ∀ᶠ i in l, ae_strongly_measurable (g i) μ) (hcg : tendsto (uncurry g) (l ×ᶠ 𝓝 x₀) (𝓝 z₀)) (hk : tendsto k l (𝓝 x₀)) : tendsto (λ i, ((λ x, (φ i).normed μ x) ⋆[lsmul ℝ ℝ, μ] g i : G → E') (k i)) l (𝓝 z₀) := convolution_tendsto_right (eventually_of_forall $ λ i, (φ i).nonneg_normed) (eventually_of_forall $ λ i, (φ i).integral_normed) (tendsto_support_normed_small_sets hφ) hig hcg hk /-- Special case of `cont_diff_bump.convolution_tendsto_right` where `g` is continuous, and the limit is taken only in the first function. -/ lemma convolution_tendsto_right_of_continuous {ι} {φ : ι → cont_diff_bump (0 : G)} {l : filter ι} (hφ : tendsto (λ i, (φ i).R) l (𝓝 0)) (hg : continuous g) (x₀ : G) : tendsto (λ i, ((λ x, (φ i).normed μ x) ⋆[lsmul ℝ ℝ, μ] g : G → E') x₀) l (𝓝 (g x₀)) := convolution_tendsto_right hφ (eventually_of_forall $ λ _, hg.ae_strongly_measurable) ((hg.tendsto x₀).comp tendsto_snd) tendsto_const_nhds end cont_diff_bump end measurability end nontrivially_normed_field open_locale convolution section is_R_or_C variables [is_R_or_C 𝕜] variables [normed_space 𝕜 E] variables [normed_space 𝕜 E'] variables [normed_space 𝕜 E''] variables [normed_space ℝ F] [normed_space 𝕜 F] variables {n : ℕ∞} variables [complete_space F] variables [measurable_space G] {μ ν : measure G} variables (L : E →L[𝕜] E' →L[𝕜] F) section assoc variables [normed_add_comm_group F'] [normed_space ℝ F'] [normed_space 𝕜 F'] [complete_space F'] variables [normed_add_comm_group F''] [normed_space ℝ F''] [normed_space 𝕜 F''] [complete_space F''] variables {k : G → E''} variables (L₂ : F →L[𝕜] E'' →L[𝕜] F') variables (L₃ : E →L[𝕜] F'' →L[𝕜] F') variables (L₄ : E' →L[𝕜] E'' →L[𝕜] F'') variables [add_group G] variables [sigma_finite μ] [sigma_finite ν] [is_add_right_invariant μ] lemma integral_convolution [has_measurable_add₂ G] [has_measurable_neg G] [normed_space ℝ E] [normed_space ℝ E'] [complete_space E] [complete_space E'] (hf : integrable f ν) (hg : integrable g μ) : ∫ x, (f ⋆[L, ν] g) x ∂μ = L (∫ x, f x ∂ν) (∫ x, g x ∂μ) := begin refine (integral_integral_swap (by apply hf.convolution_integrand L hg)).trans _, simp_rw [integral_comp_comm _ (hg.comp_sub_right _), integral_sub_right_eq_self], exact (L.flip (∫ x, g x ∂μ)).integral_comp_comm hf end variables [has_measurable_add₂ G] [is_add_right_invariant ν] [has_measurable_neg G] /-- Convolution is associative. This has a weak but inconvenient integrability condition. See also `convolution_assoc`. -/ lemma convolution_assoc' (hL : ∀ (x : E) (y : E') (z : E''), L₂ (L x y) z = L₃ x (L₄ y z)) {x₀ : G} (hfg : ∀ᵐ y ∂μ, convolution_exists_at f g y L ν) (hgk : ∀ᵐ x ∂ν, convolution_exists_at g k x L₄ μ) (hi : integrable (uncurry (λ x y, (L₃ (f y)) ((L₄ (g (x - y))) (k (x₀ - x))))) (μ.prod ν)) : ((f ⋆[L, ν] g) ⋆[L₂, μ] k) x₀ = (f ⋆[L₃, ν] (g ⋆[L₄, μ] k)) x₀ := calc ((f ⋆[L, ν] g) ⋆[L₂, μ] k) x₀ = ∫ t, L₂ (∫ s, L (f s) (g (t - s)) ∂ν) (k (x₀ - t)) ∂μ : rfl ... = ∫ t, ∫ s, L₂ (L (f s) (g (t - s))) (k (x₀ - t)) ∂ν ∂μ : integral_congr_ae (hfg.mono $ λ t ht, ((L₂.flip (k (x₀ - t))).integral_comp_comm ht).symm) ... = ∫ t, ∫ s, L₃ (f s) (L₄ (g (t - s)) (k (x₀ - t))) ∂ν ∂μ : by simp_rw hL ... = ∫ s, ∫ t, L₃ (f s) (L₄ (g (t - s)) (k (x₀ - t))) ∂μ ∂ν : by rw [integral_integral_swap hi] ... = ∫ s, ∫ u, L₃ (f s) (L₄ (g u) (k ((x₀ - s) - u))) ∂μ ∂ν : begin congr', ext t, rw [eq_comm, ← integral_sub_right_eq_self _ t], { simp_rw [sub_sub_sub_cancel_right] }, { apply_instance }, end ... = ∫ s, L₃ (f s) (∫ u, L₄ (g u) (k ((x₀ - s) - u)) ∂μ) ∂ν : begin refine integral_congr_ae _, refine ((quasi_measure_preserving_sub_left_of_right_invariant ν x₀).ae hgk).mono (λ t ht, _), exact (L₃ (f t)).integral_comp_comm ht, end ... = (f ⋆[L₃, ν] (g ⋆[L₄, μ] k)) x₀ : rfl /-- Convolution is associative. This requires that * all maps are a.e. strongly measurable w.r.t one of the measures * `f ⋆[L, ν] g` exists almost everywhere * `‖g‖ ⋆[μ] ‖k‖` exists almost everywhere * `‖f‖ ⋆[ν] (‖g‖ ⋆[μ] ‖k‖)` exists at `x₀` -/ lemma convolution_assoc (hL : ∀ (x : E) (y : E') (z : E''), L₂ (L x y) z = L₃ x (L₄ y z)) {x₀ : G} (hf : ae_strongly_measurable f ν) (hg : ae_strongly_measurable g μ) (hk : ae_strongly_measurable k μ) (hfg : ∀ᵐ y ∂μ, convolution_exists_at f g y L ν) (hgk : ∀ᵐ x ∂ν, convolution_exists_at (λ x, ‖g x‖) (λ x, ‖k x‖) x (mul ℝ ℝ) μ) (hfgk : convolution_exists_at (λ x, ‖f x‖) ((λ x, ‖g x‖) ⋆[mul ℝ ℝ, μ] (λ x, ‖k x‖)) x₀ (mul ℝ ℝ) ν) : ((f ⋆[L, ν] g) ⋆[L₂, μ] k) x₀ = (f ⋆[L₃, ν] (g ⋆[L₄, μ] k)) x₀ := begin refine convolution_assoc' L L₂ L₃ L₄ hL hfg (hgk.mono $ λ x hx, hx.of_norm L₄ hg hk) _, /- the following is similar to `integrable.convolution_integrand` -/ have h_meas : ae_strongly_measurable (uncurry (λ x y, L₃ (f y) (L₄ (g x) (k (x₀ - y - x))))) (μ.prod ν), { refine L₃.ae_strongly_measurable_comp₂ hf.snd _, refine L₄.ae_strongly_measurable_comp₂ hg.fst _, refine (hk.mono' _).comp_measurable ((measurable_const.sub measurable_snd).sub measurable_fst), refine quasi_measure_preserving.absolutely_continuous _, refine quasi_measure_preserving.prod_of_left ((measurable_const.sub measurable_snd).sub measurable_fst) (eventually_of_forall $ λ y, _), dsimp only, exact quasi_measure_preserving_sub_left_of_right_invariant μ _ }, have h2_meas : ae_strongly_measurable (λ y, ∫ x, ‖L₃ (f y) (L₄ (g x) (k (x₀ - y - x)))‖ ∂μ) ν := h_meas.prod_swap.norm.integral_prod_right', have h3 : map (λ z : G × G, (z.1 - z.2, z.2)) (μ.prod ν) = μ.prod ν := (measure_preserving_sub_prod μ ν).map_eq, suffices : integrable (uncurry (λ x y, L₃ (f y) (L₄ (g x) (k (x₀ - y - x))))) (μ.prod ν), { rw [← h3] at this, convert this.comp_measurable (measurable_sub.prod_mk measurable_snd), ext ⟨x, y⟩, simp_rw [uncurry, function.comp_apply, sub_sub_sub_cancel_right] }, simp_rw [integrable_prod_iff' h_meas], refine ⟨((quasi_measure_preserving_sub_left_of_right_invariant ν x₀).ae hgk).mono (λ t ht, (L₃ (f t)).integrable_comp $ ht.of_norm L₄ hg hk), _⟩, refine (hfgk.const_mul (‖L₃‖ * ‖L₄‖)).mono' h2_meas (((quasi_measure_preserving_sub_left_of_right_invariant ν x₀).ae hgk).mono $ λ t ht, _), { simp_rw [convolution_def, mul_apply', mul_mul_mul_comm ‖L₃‖ ‖L₄‖, ← integral_mul_left], rw [real.norm_of_nonneg], { refine integral_mono_of_nonneg (eventually_of_forall $ λ t, norm_nonneg _) ((ht.const_mul _).const_mul _) (eventually_of_forall $ λ s, _), refine (L₃.le_op_norm₂ _ _).trans _, refine mul_le_mul_of_nonneg_left _ (mul_nonneg (norm_nonneg _) (norm_nonneg _)), rw [← mul_assoc], apply L₄.le_op_norm₂ }, exact integral_nonneg (λ x, norm_nonneg _) } end end assoc variables [normed_add_comm_group G] [borel_space G] lemma convolution_precompR_apply {g : G → E'' →L[𝕜] E'} (hf : locally_integrable f μ) (hcg : has_compact_support g) (hg : continuous g) (x₀ : G) (x : E'') : (f ⋆[L.precompR E'', μ] g) x₀ x = (f ⋆[L, μ] (λ a, g a x)) x₀ := begin have := hcg.convolution_exists_right (L.precompR E'' : _) hf hg x₀, simp_rw [convolution_def, continuous_linear_map.integral_apply this], refl, end variables [normed_space 𝕜 G] [sigma_finite μ] [is_add_left_invariant μ] /-- Compute the total derivative of `f ⋆ g` if `g` is `C^1` with compact support and `f` is locally integrable. To write down the total derivative as a convolution, we use `continuous_linear_map.precompR`. -/ lemma has_compact_support.has_fderiv_at_convolution_right (hcg : has_compact_support g) (hf : locally_integrable f μ) (hg : cont_diff 𝕜 1 g) (x₀ : G) : has_fderiv_at (f ⋆[L, μ] g) ((f ⋆[L.precompR G, μ] fderiv 𝕜 g) x₀) x₀ := begin rcases hcg.eq_zero_or_finite_dimensional 𝕜 hg.continuous with rfl|fin_dim, { have : fderiv 𝕜 (0 : G → E') = 0, from fderiv_const (0 : E'), simp only [this, convolution_zero, pi.zero_apply], exact has_fderiv_at_const (0 : F) x₀ }, resetI, haveI : proper_space G, from finite_dimensional.proper_is_R_or_C 𝕜 G, set L' := L.precompR G, have h1 : ∀ᶠ x in 𝓝 x₀, ae_strongly_measurable (λ t, L (f t) (g (x - t))) μ := eventually_of_forall (hf.ae_strongly_measurable.convolution_integrand_snd L hg.continuous.ae_strongly_measurable), have h2 : ∀ x, ae_strongly_measurable (λ t, L' (f t) (fderiv 𝕜 g (x - t))) μ, { exact hf.ae_strongly_measurable.convolution_integrand_snd L' (hg.continuous_fderiv le_rfl).ae_strongly_measurable }, have h3 : ∀ x t, has_fderiv_at (λ x, g (x - t)) (fderiv 𝕜 g (x - t)) x, { intros x t, simpa using (hg.differentiable le_rfl).differentiable_at.has_fderiv_at.comp x ((has_fderiv_at_id x).sub (has_fderiv_at_const t x)) }, let K' := - tsupport (fderiv 𝕜 g) + closed_ball x₀ 1, have hK' : is_compact K' := (hcg.fderiv 𝕜).neg.add (is_compact_closed_ball x₀ 1), refine has_fderiv_at_integral_of_dominated_of_fderiv_le zero_lt_one h1 _ (h2 x₀) _ _ _, { exact K'.indicator (λ t, ‖L'‖ * ‖f t‖ * (⨆ x, ‖fderiv 𝕜 g x‖)) }, { exact hcg.convolution_exists_right L hf hg.continuous x₀ }, { refine eventually_of_forall (λ t x hx, _), exact (hcg.fderiv 𝕜).convolution_integrand_bound_right L' (hg.continuous_fderiv le_rfl) (ball_subset_closed_ball hx) }, { rw [integrable_indicator_iff hK'.measurable_set], exact ((hf.integrable_on_is_compact hK').norm.const_mul _).mul_const _ }, { exact eventually_of_forall (λ t x hx, (L _).has_fderiv_at.comp x (h3 x t)) }, end lemma has_compact_support.has_fderiv_at_convolution_left [is_neg_invariant μ] (hcf : has_compact_support f) (hf : cont_diff 𝕜 1 f) (hg : locally_integrable g μ) (x₀ : G) : has_fderiv_at (f ⋆[L, μ] g) ((fderiv 𝕜 f ⋆[L.precompL G, μ] g) x₀) x₀ := begin simp only [← convolution_flip] {single_pass := tt}, exact hcf.has_fderiv_at_convolution_right L.flip hg hf x₀, end end is_R_or_C section real /-! The one-variable case -/ variables [is_R_or_C 𝕜] variables [normed_space 𝕜 E] variables [normed_space 𝕜 E'] variables [normed_space ℝ F] [normed_space 𝕜 F] variables {f₀ : 𝕜 → E} {g₀ : 𝕜 → E'} variables {n : ℕ∞} variables (L : E →L[𝕜] E' →L[𝕜] F) variables [complete_space F] variables {μ : measure 𝕜} variables [is_add_left_invariant μ] [sigma_finite μ] lemma has_compact_support.has_deriv_at_convolution_right (hf : locally_integrable f₀ μ) (hcg : has_compact_support g₀) (hg : cont_diff 𝕜 1 g₀) (x₀ : 𝕜) : has_deriv_at (f₀ ⋆[L, μ] g₀) ((f₀ ⋆[L, μ] deriv g₀) x₀) x₀ := begin convert (hcg.has_fderiv_at_convolution_right L hf hg x₀).has_deriv_at, rw [convolution_precompR_apply L hf (hcg.fderiv 𝕜) (hg.continuous_fderiv le_rfl)], refl, end lemma has_compact_support.has_deriv_at_convolution_left [is_neg_invariant μ] (hcf : has_compact_support f₀) (hf : cont_diff 𝕜 1 f₀) (hg : locally_integrable g₀ μ) (x₀ : 𝕜) : has_deriv_at (f₀ ⋆[L, μ] g₀) ((deriv f₀ ⋆[L, μ] g₀) x₀) x₀ := begin simp only [← convolution_flip] {single_pass := tt}, exact hcf.has_deriv_at_convolution_right L.flip hg hf x₀, end end real section with_param variables [is_R_or_C 𝕜] [normed_space 𝕜 E] [normed_space 𝕜 E'] [normed_space 𝕜 E''] [normed_space ℝ F] [normed_space 𝕜 F] [complete_space F] [measurable_space G] [normed_add_comm_group G] [borel_space G] [normed_space 𝕜 G] [normed_add_comm_group P] [normed_space 𝕜 P] {μ : measure G} (L : E →L[𝕜] E' →L[𝕜] F) /-- The derivative of the convolution `f * g` is given by `f * Dg`, when `f` is locally integrable and `g` is `C^1` and compactly supported. Version where `g` depends on an additional parameter in an open subset `s` of a parameter space `P` (and the compact support `k` is independent of the parameter in `s`). -/ lemma has_fderiv_at_convolution_right_with_param {g : P → G → E'} {s : set P} {k : set G} (hs : is_open s) (hk : is_compact k) (hgs : ∀ p, ∀ x, p ∈ s → x ∉ k → g p x = 0) (hf : locally_integrable f μ) (hg : cont_diff_on 𝕜 1 ↿g (s ×ˢ univ)) (q₀ : P × G) (hq₀ : q₀.1 ∈ s) : has_fderiv_at (λ (q : P × G), (f ⋆[L, μ] g q.1) q.2) ((f ⋆[L.precompR (P × G), μ] (λ (x : G), fderiv 𝕜 ↿g (q₀.1, x))) q₀.2) q₀ := begin let g' := fderiv 𝕜 ↿g, have A : ∀ p ∈ s, continuous (g p), { assume p hp, apply hg.continuous_on.comp_continuous (continuous_const.prod_mk continuous_id') (λ x, _), simpa only [prod_mk_mem_set_prod_eq, mem_univ, and_true] using hp }, have A' : ∀ (q : P × G), q.1 ∈ s → s ×ˢ univ ∈ 𝓝 q, { assume q hq, apply (hs.prod is_open_univ).mem_nhds, simpa only [mem_prod, mem_univ, and_true] using hq }, /- The derivative of `g` vanishes away from `k`. -/ have g'_zero : ∀ p x, p ∈ s → x ∉ k → g' (p, x) = 0, { assume p x hp hx, refine (has_fderiv_at_zero_of_eventually_const 0 _).fderiv, have M2 : kᶜ ∈ 𝓝 x, from is_open.mem_nhds hk.is_closed.is_open_compl hx, have M1 : s ∈ 𝓝 p, from hs.mem_nhds hp, rw nhds_prod_eq, filter_upwards [prod_mem_prod M1 M2], rintros ⟨p, y⟩ ⟨hp, hy⟩, exact hgs p y hp hy }, /- We find a small neighborhood of `{q₀.1} × k` on which the derivative is uniformly bounded. This follows from the continuity at all points of the compact set `k`. -/ obtain ⟨ε, C, εpos, Cnonneg, h₀ε, hε⟩ : ∃ ε C, 0 < ε ∧ 0 ≤ C ∧ ball q₀.1 ε ⊆ s ∧ ∀ p x, ‖p - q₀.1‖ < ε → ‖g' (p, x)‖ ≤ C, { have A : is_compact ({q₀.1} ×ˢ k), from is_compact_singleton.prod hk, obtain ⟨t, kt, t_open, ht⟩ : ∃ t, {q₀.1} ×ˢ k ⊆ t ∧ is_open t ∧ bounded (g' '' t), { have B : continuous_on g' (s ×ˢ univ), from hg.continuous_on_fderiv_of_open (hs.prod is_open_univ) le_rfl, apply exists_is_open_bounded_image_of_is_compact_of_continuous_on A (hs.prod is_open_univ) _ B, simp only [prod_subset_prod_iff, hq₀, singleton_subset_iff, subset_univ, and_self, true_or] }, obtain ⟨ε, εpos, hε, h'ε⟩ : ∃ (ε : ℝ), 0 < ε ∧ thickening ε ({q₀.fst} ×ˢ k) ⊆ t ∧ ball q₀.1 ε ⊆ s, { obtain ⟨ε, εpos, hε⟩ : ∃ (ε : ℝ), 0 < ε ∧ thickening ε ({q₀.fst} ×ˢ k) ⊆ t, from A.exists_thickening_subset_open t_open kt, obtain ⟨δ, δpos, hδ⟩ : ∃ (δ : ℝ) (H : 0 < δ), ball q₀.1 δ ⊆ s, from metric.is_open_iff.1 hs _ hq₀, refine ⟨min ε δ, lt_min εpos δpos, _, _⟩, { exact subset.trans (thickening_mono (min_le_left _ _) _) hε }, { exact subset.trans (ball_subset_ball (min_le_right _ _)) hδ } }, obtain ⟨C, Cpos, hC⟩ : ∃ C, 0 < C ∧ g' '' t ⊆ closed_ball 0 C, from ht.subset_ball_lt 0 0, refine ⟨ε, C, εpos, Cpos.le, h'ε, λ p x hp, _⟩, have hps : p ∈ s, from h'ε (mem_ball_iff_norm.2 hp), by_cases hx : x ∈ k, { have H : (p, x) ∈ t, { apply hε, refine mem_thickening_iff.2 ⟨(q₀.1, x), _, _⟩, { simp only [hx, singleton_prod, mem_image, prod.mk.inj_iff, eq_self_iff_true, true_and, exists_eq_right] }, { rw ← dist_eq_norm at hp, simpa only [prod.dist_eq, εpos, dist_self, max_lt_iff, and_true] using hp } }, have : g' (p, x) ∈ closed_ball (0 : P × G →L[𝕜] E') C, from hC (mem_image_of_mem _ H), rwa mem_closed_ball_zero_iff at this }, { have : g' (p, x) = 0, from g'_zero _ _ hps hx, rw this, simpa only [norm_zero] using Cpos.le } }, /- Now, we wish to apply a theorem on differentiation of integrals. For this, we need to check trivial measurability or integrability assumptions (in `I1`, `I2`, `I3`), as well as a uniform integrability assumption over the derivative (in `I4` and `I5`) and pointwise differentiability in `I6`. -/ have I1 : ∀ᶠ (x : P × G) in 𝓝 q₀, ae_strongly_measurable (λ (a : G), L (f a) (g x.1 (x.2 - a))) μ, { filter_upwards [A' q₀ hq₀], rintros ⟨p, x⟩ ⟨hp, hx⟩, refine (has_compact_support.convolution_exists_right L _ hf (A _ hp) _).1, apply is_compact_of_is_closed_subset hk (is_closed_tsupport _), exact closure_minimal (support_subset_iff'.2 (λ z hz, hgs _ _ hp hz)) hk.is_closed, }, have I2 : integrable (λ (a : G), L (f a) (g q₀.1 (q₀.2 - a))) μ, { have M : has_compact_support (g q₀.1), from has_compact_support.intro hk (λ x hx, hgs q₀.1 x hq₀ hx), apply M.convolution_exists_right L hf (A q₀.1 hq₀) q₀.2 }, have I3 : ae_strongly_measurable (λ (a : G), (L (f a)).comp (g' (q₀.fst, q₀.snd - a))) μ, { have T : has_compact_support (λ y, g' (q₀.1, y)), from has_compact_support.intro hk (λ x hx, g'_zero q₀.1 x hq₀ hx), apply (has_compact_support.convolution_exists_right (L.precompR (P × G) : _) T hf _ q₀.2).1, have : continuous_on g' (s ×ˢ univ), from hg.continuous_on_fderiv_of_open (hs.prod is_open_univ) le_rfl, apply this.comp_continuous (continuous_const.prod_mk continuous_id'), assume x, simpa only [prod_mk_mem_set_prod_eq, mem_univ, and_true] using hq₀ }, set K' := - k + {q₀.2} with K'_def, have hK' : is_compact K' := hk.neg.add is_compact_singleton, obtain ⟨U, U_open, K'U, hU⟩ : ∃ U, is_open U ∧ K' ⊆ U ∧ integrable_on f U μ, from hf.integrable_on_nhds_is_compact hK', obtain ⟨δ, δpos, δε, hδ⟩ : ∃ δ, (0 : ℝ) < δ ∧ δ ≤ ε ∧ K' + ball 0 δ ⊆ U, { obtain ⟨V, V_mem, hV⟩ : ∃ (V : set G) (V_mem : V ∈ 𝓝 (0 : G)), K' + V ⊆ U, from compact_open_separated_add_right hK' U_open K'U, rcases metric.mem_nhds_iff.1 V_mem with ⟨δ, δpos, hδ⟩, refine ⟨min δ ε, lt_min δpos εpos, min_le_right _ _, _⟩, exact (add_subset_add_left ((ball_subset_ball (min_le_left _ _)).trans hδ)).trans hV }, let bound : G → ℝ := indicator U (λ a, ‖L.precompR (P × G)‖ * ‖f a‖ * C), have I4 : ∀ᵐ (a : G) ∂μ, ∀ (x : P × G), dist x q₀ < δ → ‖L.precompR (P × G) (f a) (g' (x.fst, x.snd - a))‖ ≤ bound a, { apply eventually_of_forall, assume a x hx, rw [prod.dist_eq, dist_eq_norm, dist_eq_norm] at hx, have : -tsupport (λ a, g' (x.1, a)) + ball q₀.2 δ ⊆ U, { apply subset.trans _ hδ, rw [K'_def, add_assoc], apply add_subset_add, { rw neg_subset_neg, apply closure_minimal (support_subset_iff'.2 (λ z hz, _)) hk.is_closed, apply g'_zero x.1 z (h₀ε _) hz, rw mem_ball_iff_norm, exact ((le_max_left _ _).trans_lt hx).trans_le δε }, { simp only [add_ball, thickening_singleton, zero_vadd] } }, apply convolution_integrand_bound_right_of_le_of_subset _ _ _ this, { assume y, exact hε _ _ (((le_max_left _ _).trans_lt hx).trans_le δε) }, { rw mem_ball_iff_norm, exact (le_max_right _ _).trans_lt hx } }, have I5 : integrable bound μ, { rw [integrable_indicator_iff U_open.measurable_set], exact (hU.norm.const_mul _).mul_const _ }, have I6 : ∀ᵐ (a : G) ∂μ, ∀ (x : P × G), dist x q₀ < δ → has_fderiv_at (λ (x : P × G), L (f a) (g x.1 (x.2 - a))) ((L (f a)).comp (g' (x.fst, x.snd - a))) x, { apply eventually_of_forall, assume a x hx, apply (L _).has_fderiv_at.comp x, have N : s ×ˢ univ ∈ 𝓝 (x.1, x.2 - a), { apply A', apply h₀ε, rw prod.dist_eq at hx, exact lt_of_lt_of_le (lt_of_le_of_lt (le_max_left _ _) hx) δε }, have Z := ((hg.differentiable_on le_rfl).differentiable_at N).has_fderiv_at, have Z' : has_fderiv_at (λ (x : P × G), (x.1, x.2 - a)) (continuous_linear_map.id 𝕜 (P × G)) x, { have : (λ (x : P × G), (x.1, x.2 - a)) = id - (λ x, (0, a)), { ext x; simp only [pi.sub_apply, id.def, prod.fst_sub, sub_zero, prod.snd_sub] }, simp_rw [this], exact (has_fderiv_at_id x).sub_const (0, a) }, exact Z.comp x Z' }, exact has_fderiv_at_integral_of_dominated_of_fderiv_le δpos I1 I2 I3 I4 I5 I6, end /-- The convolution `f * g` is `C^n` when `f` is locally integrable and `g` is `C^n` and compactly supported. Version where `g` depends on an additional parameter in an open subset `s` of a parameter space `P` (and the compact support `k` is independent of the parameter in `s`). In this version, all the types belong to the same universe (to get an induction working in the proof). Use instead `cont_diff_on_convolution_right_with_param`, which removes this restriction. -/ lemma cont_diff_on_convolution_right_with_param_aux {G : Type uP} {E' : Type uP} {F : Type uP} {P : Type uP} [normed_add_comm_group E'] [normed_add_comm_group F] [normed_space 𝕜 E'] [normed_space ℝ F] [normed_space 𝕜 F] [complete_space F] [measurable_space G] {μ : measure G} [normed_add_comm_group G] [borel_space G] [normed_space 𝕜 G] [normed_add_comm_group P] [normed_space 𝕜 P] {f : G → E} {n : ℕ∞} (L : E →L[𝕜] E' →L[𝕜] F) {g : P → G → E'} {s : set P} {k : set G} (hs : is_open s) (hk : is_compact k) (hgs : ∀ p, ∀ x, p ∈ s → x ∉ k → g p x = 0) (hf : locally_integrable f μ) (hg : cont_diff_on 𝕜 n ↿g (s ×ˢ univ)) : cont_diff_on 𝕜 n (λ (q : P × G), (f ⋆[L, μ] g q.1) q.2) (s ×ˢ univ) := begin /- We have a formula for the derivation of `f * g`, which is of the same form, thanks to `has_fderiv_at_convolution_right_with_param`. Therefore, we can prove the result by induction on `n` (but for this we need the spaces at the different steps of the induction to live in the same universe, which is why we make the assumption in the lemma that all the relevant spaces come from the same universe). -/ unfreezingI { induction n using enat.nat_induction with n ih ih generalizing g E' F }, { rw [cont_diff_on_zero] at hg ⊢, exact continuous_on_convolution_right_with_param L hk hgs hf hg }, { let f' : P → G → (P × G →L[𝕜] F) := λ p a, (f ⋆[L.precompR (P × G), μ] (λ (x : G), fderiv 𝕜 (uncurry g) (p, x))) a, have A : ∀ (q₀ : P × G), q₀.1 ∈ s → has_fderiv_at (λ (q : P × G), (f ⋆[L, μ] g q.1) q.2) (f' q₀.1 q₀.2) q₀, from has_fderiv_at_convolution_right_with_param L hs hk hgs hf hg.one_of_succ, rw cont_diff_on_succ_iff_fderiv_of_open (hs.prod (@is_open_univ G _)) at ⊢ hg, split, { rintros ⟨p, x⟩ ⟨hp, hx⟩, exact (A (p, x) hp).differentiable_at.differentiable_within_at, }, { suffices H : cont_diff_on 𝕜 n ↿f' (s ×ˢ univ), { apply H.congr, rintros ⟨p, x⟩ ⟨hp, hx⟩, exact (A (p, x) hp).fderiv }, have B : ∀ (p : P) (x : G), p ∈ s → x ∉ k → fderiv 𝕜 (uncurry g) (p, x) = 0, { assume p x hp hx, apply (has_fderiv_at_zero_of_eventually_const (0 : E') _).fderiv, have M2 : kᶜ ∈ 𝓝 x, from is_open.mem_nhds hk.is_closed.is_open_compl hx, have M1 : s ∈ 𝓝 p, from hs.mem_nhds hp, rw nhds_prod_eq, filter_upwards [prod_mem_prod M1 M2], rintros ⟨p, y⟩ ⟨hp, hy⟩, exact hgs p y hp hy }, apply ih (L.precompR (P × G) : _) B, convert hg.2, apply funext, rintros ⟨p, x⟩, refl } }, { rw [cont_diff_on_top] at hg ⊢, assume n, exact ih n L hgs (hg n) } end /-- The convolution `f * g` is `C^n` when `f` is locally integrable and `g` is `C^n` and compactly supported. Version where `g` depends on an additional parameter in an open subset `s` of a parameter space `P` (and the compact support `k` is independent of the parameter in `s`). -/ lemma cont_diff_on_convolution_right_with_param {f : G → E} {n : ℕ∞} (L : E →L[𝕜] E' →L[𝕜] F) {g : P → G → E'} {s : set P} {k : set G} (hs : is_open s) (hk : is_compact k) (hgs : ∀ p, ∀ x, p ∈ s → x ∉ k → g p x = 0) (hf : locally_integrable f μ) (hg : cont_diff_on 𝕜 n ↿g (s ×ˢ univ)) : cont_diff_on 𝕜 n (λ (q : P × G), (f ⋆[L, μ] g q.1) q.2) (s ×ˢ univ) := begin /- The result is known when all the universes are the same, from `cont_diff_on_convolution_right_with_param_aux`. We reduce to this situation by pushing everything through `ulift` continuous linear equivalences. -/ let eG : Type (max uG uE' uF uP) := ulift G, borelize eG, let eE' : Type (max uE' uG uF uP) := ulift E', let eF : Type (max uF uG uE' uP) := ulift F, let eP : Type (max uP uG uE' uF) := ulift P, have isoG : eG ≃L[𝕜] G := continuous_linear_equiv.ulift, have isoE' : eE' ≃L[𝕜] E' := continuous_linear_equiv.ulift, have isoF : eF ≃L[𝕜] F := continuous_linear_equiv.ulift, have isoP : eP ≃L[𝕜] P := continuous_linear_equiv.ulift, let ef := f ∘ isoG, let eμ : measure eG := measure.map isoG.symm μ, let eg : eP → eG → eE' := λ ep ex, isoE'.symm (g (isoP ep) (isoG ex)), let eL := continuous_linear_map.comp ((continuous_linear_equiv.arrow_congr isoE' isoF).symm : (E' →L[𝕜] F) →L[𝕜] eE' →L[𝕜] eF) L, let R := (λ (q : eP × eG), (ef ⋆[eL, eμ] eg q.1) q.2), have R_contdiff : cont_diff_on 𝕜 n R ((isoP ⁻¹' s) ×ˢ univ), { have hek : is_compact (isoG ⁻¹' k), from isoG.to_homeomorph.closed_embedding.is_compact_preimage hk, have hes : is_open (isoP ⁻¹' s), from isoP.continuous.is_open_preimage _ hs, refine cont_diff_on_convolution_right_with_param_aux eL hes hek _ _ _, { assume p x hp hx, simp only [comp_app, continuous_linear_equiv.prod_apply, linear_isometry_equiv.coe_coe, continuous_linear_equiv.map_eq_zero_iff], exact hgs _ _ hp hx }, { apply (locally_integrable_map_homeomorph isoG.symm.to_homeomorph).2, convert hf, ext1 x, simp only [ef, continuous_linear_equiv.coe_to_homeomorph, comp_app, continuous_linear_equiv.apply_symm_apply], }, { apply isoE'.symm.cont_diff.comp_cont_diff_on, apply hg.comp ((isoP.prod isoG).cont_diff).cont_diff_on, rintros ⟨p, x⟩ ⟨hp, hx⟩, simpa only [mem_preimage, continuous_linear_equiv.prod_apply, prod_mk_mem_set_prod_eq, mem_univ, and_true] using hp } }, have A : cont_diff_on 𝕜 n (isoF ∘ R ∘ (isoP.prod isoG).symm) (s ×ˢ univ), { apply isoF.cont_diff.comp_cont_diff_on, apply R_contdiff.comp (continuous_linear_equiv.cont_diff _).cont_diff_on, rintros ⟨p, x⟩ ⟨hp, hx⟩, simpa only [mem_preimage, mem_prod, mem_univ, and_true, continuous_linear_equiv.prod_symm, continuous_linear_equiv.prod_apply, continuous_linear_equiv.apply_symm_apply] using hp }, have : isoF ∘ R ∘ (isoP.prod isoG).symm = (λ (q : P × G), (f ⋆[L, μ] g q.1) q.2), { apply funext, rintros ⟨p, x⟩, simp only [R, linear_isometry_equiv.coe_coe, comp_app, continuous_linear_equiv.prod_symm, continuous_linear_equiv.prod_apply], simp only [convolution, eL, coe_comp', continuous_linear_equiv.coe_coe, comp_app, eμ], rw [closed_embedding.integral_map, ← isoF.integral_comp_comm], swap, { exact isoG.symm.to_homeomorph.closed_embedding }, congr' 1, ext1 a, simp only [ef, eg, comp_app, continuous_linear_equiv.apply_symm_apply, coe_comp', continuous_linear_equiv.prod_apply, continuous_linear_equiv.map_sub, continuous_linear_equiv.arrow_congr, continuous_linear_equiv.arrow_congrSL_symm_apply, continuous_linear_equiv.coe_coe, comp_app, continuous_linear_equiv.apply_symm_apply] }, simp_rw [this] at A, exact A, end /-- The convolution `f * g` is `C^n` when `f` is locally integrable and `g` is `C^n` and compactly supported. Version where `g` depends on an additional parameter in an open subset `s` of a parameter space `P` (and the compact support `k` is independent of the parameter in `s`), given in terms of composition with an additional smooth function. -/ lemma cont_diff_on_convolution_right_with_param_comp {n : ℕ∞} (L : E →L[𝕜] E' →L[𝕜] F) {s : set P} {v : P → G} (hv : cont_diff_on 𝕜 n v s) {f : G → E} {g : P → G → E'} {k : set G} (hs : is_open s) (hk : is_compact k) (hgs : ∀ p, ∀ x, p ∈ s → x ∉ k → g p x = 0) (hf : locally_integrable f μ) (hg : cont_diff_on 𝕜 n ↿g (s ×ˢ univ)) : cont_diff_on 𝕜 n (λ x, (f ⋆[L, μ] g x) (v x)) s := begin apply (cont_diff_on_convolution_right_with_param L hs hk hgs hf hg).comp (cont_diff_on_id.prod hv), assume x hx, simp only [hx, mem_preimage, prod_mk_mem_set_prod_eq, mem_univ, and_self, id.def], end /-- The convolution `g * f` is `C^n` when `f` is locally integrable and `g` is `C^n` and compactly supported. Version where `g` depends on an additional parameter in an open subset `s` of a parameter space `P` (and the compact support `k` is independent of the parameter in `s`). -/ lemma cont_diff_on_convolution_left_with_param [μ.is_add_left_invariant] [μ.is_neg_invariant] (L : E' →L[𝕜] E →L[𝕜] F) {f : G → E} {n : ℕ∞} {g : P → G → E'} {s : set P} {k : set G} (hs : is_open s) (hk : is_compact k) (hgs : ∀ p, ∀ x, p ∈ s → x ∉ k → g p x = 0) (hf : locally_integrable f μ) (hg : cont_diff_on 𝕜 n ↿g (s ×ˢ univ)) : cont_diff_on 𝕜 n (λ (q : P × G), (g q.1 ⋆[L, μ] f) q.2) (s ×ˢ univ) := by simpa only [convolution_flip] using cont_diff_on_convolution_right_with_param L.flip hs hk hgs hf hg /-- The convolution `g * f` is `C^n` when `f` is locally integrable and `g` is `C^n` and compactly supported. Version where `g` depends on an additional parameter in an open subset `s` of a parameter space `P` (and the compact support `k` is independent of the parameter in `s`), given in terms of composition with additional smooth functions. -/ lemma cont_diff_on_convolution_left_with_param_comp [μ.is_add_left_invariant] [μ.is_neg_invariant] (L : E' →L[𝕜] E →L[𝕜] F) {s : set P} {n : ℕ∞} {v : P → G} (hv : cont_diff_on 𝕜 n v s) {f : G → E} {g : P → G → E'} {k : set G} (hs : is_open s) (hk : is_compact k) (hgs : ∀ p, ∀ x, p ∈ s → x ∉ k → g p x = 0) (hf : locally_integrable f μ) (hg : cont_diff_on 𝕜 n ↿g (s ×ˢ univ)) : cont_diff_on 𝕜 n (λ x, (g x ⋆[L, μ] f) (v x)) s := begin apply (cont_diff_on_convolution_left_with_param L hs hk hgs hf hg).comp (cont_diff_on_id.prod hv), assume x hx, simp only [hx, mem_preimage, prod_mk_mem_set_prod_eq, mem_univ, and_self, id.def], end lemma has_compact_support.cont_diff_convolution_right {n : ℕ∞} (hcg : has_compact_support g) (hf : locally_integrable f μ) (hg : cont_diff 𝕜 n g) : cont_diff 𝕜 n (f ⋆[L, μ] g) := begin rcases exists_compact_iff_has_compact_support.2 hcg with ⟨k, hk, h'k⟩, rw ← cont_diff_on_univ, exact cont_diff_on_convolution_right_with_param_comp L cont_diff_on_id is_open_univ hk (λ p x hp hx, h'k x hx) hf (hg.comp cont_diff_snd).cont_diff_on, end lemma has_compact_support.cont_diff_convolution_left [μ.is_add_left_invariant] [μ.is_neg_invariant] {n : ℕ∞} (hcf : has_compact_support f) (hf : cont_diff 𝕜 n f) (hg : locally_integrable g μ) : cont_diff 𝕜 n (f ⋆[L, μ] g) := by { rw [← convolution_flip], exact hcf.cont_diff_convolution_right L.flip hg hf } end with_param section nonneg variables [normed_space ℝ E] [normed_space ℝ E'] [normed_space ℝ F] [complete_space F] /-- The forward convolution of two functions `f` and `g` on `ℝ`, with respect to a continuous bilinear map `L` and measure `ν`. It is defined to be the function mapping `x` to `∫ t in 0..x, L (f t) (g (x - t)) ∂ν` if `0 < x`, and 0 otherwise. -/ noncomputable def pos_convolution (f : ℝ → E) (g : ℝ → E') (L : E →L[ℝ] E' →L[ℝ] F) (ν : measure ℝ . volume_tac) : ℝ → F := indicator (Ioi (0:ℝ)) (λ x, ∫ t in 0..x, L (f t) (g (x - t)) ∂ν) lemma pos_convolution_eq_convolution_indicator (f : ℝ → E) (g : ℝ → E') (L : E →L[ℝ] E' →L[ℝ] F) (ν : measure ℝ . volume_tac) [has_no_atoms ν] : pos_convolution f g L ν = convolution (indicator (Ioi 0) f) (indicator (Ioi 0) g) L ν := begin ext1 x, rw [convolution, pos_convolution, indicator], split_ifs, { rw [interval_integral.integral_of_le (le_of_lt h), integral_Ioc_eq_integral_Ioo, ←integral_indicator (measurable_set_Ioo : measurable_set (Ioo 0 x))], congr' 1 with t : 1, have : (t ≤ 0) ∨ (t ∈ Ioo 0 x) ∨ (x ≤ t), { rcases le_or_lt t 0 with h | h, { exact or.inl h }, { rcases lt_or_le t x with h' | h', exacts [or.inr (or.inl ⟨h, h'⟩), or.inr (or.inr h')] } }, rcases this with ht|ht|ht, { rw [indicator_of_not_mem (not_mem_Ioo_of_le ht), indicator_of_not_mem (not_mem_Ioi.mpr ht), continuous_linear_map.map_zero, continuous_linear_map.zero_apply] }, { rw [indicator_of_mem ht, indicator_of_mem (mem_Ioi.mpr ht.1), indicator_of_mem (mem_Ioi.mpr $ sub_pos.mpr ht.2)] }, { rw [indicator_of_not_mem (not_mem_Ioo_of_ge ht), indicator_of_not_mem (not_mem_Ioi.mpr (sub_nonpos_of_le ht)), continuous_linear_map.map_zero] } }, { convert (integral_zero ℝ F).symm, ext1 t, by_cases ht : 0 < t, { rw [indicator_of_not_mem (_ : x - t ∉ Ioi 0), continuous_linear_map.map_zero], rw not_mem_Ioi at h ⊢, exact sub_nonpos.mpr (h.trans ht.le) }, { rw [indicator_of_not_mem (mem_Ioi.not.mpr ht), continuous_linear_map.map_zero, continuous_linear_map.zero_apply] } } end lemma integrable_pos_convolution {f : ℝ → E} {g : ℝ → E'} {μ ν : measure ℝ} [sigma_finite μ] [sigma_finite ν] [is_add_right_invariant μ] [has_no_atoms ν] (hf : integrable_on f (Ioi 0) ν) (hg : integrable_on g (Ioi 0) μ) (L : E →L[ℝ] E' →L[ℝ] F) : integrable (pos_convolution f g L ν) μ := begin rw ←integrable_indicator_iff (measurable_set_Ioi : measurable_set (Ioi (0:ℝ))) at hf hg, rw pos_convolution_eq_convolution_indicator f g L ν, exact (hf.convolution_integrand L hg).integral_prod_left, end /-- The integral over `Ioi 0` of a forward convolution of two functions is equal to the product of their integrals over this set. (Compare `integral_convolution` for the two-sided convolution.) -/ lemma integral_pos_convolution [complete_space E] [complete_space E'] {μ ν : measure ℝ} [sigma_finite μ] [sigma_finite ν] [is_add_right_invariant μ] [has_no_atoms ν] {f : ℝ → E} {g : ℝ → E'} (hf : integrable_on f (Ioi 0) ν) (hg : integrable_on g (Ioi 0) μ) (L : E →L[ℝ] E' →L[ℝ] F) : ∫ x:ℝ in Ioi 0, (∫ t:ℝ in 0..x, L (f t) (g (x - t)) ∂ν) ∂μ = L (∫ x:ℝ in Ioi 0, f x ∂ν) (∫ x:ℝ in Ioi 0, g x ∂μ) := begin rw ←integrable_indicator_iff (measurable_set_Ioi : measurable_set (Ioi (0:ℝ))) at hf hg, simp_rw ←integral_indicator measurable_set_Ioi, convert integral_convolution L hf hg using 2, apply pos_convolution_eq_convolution_indicator, end end nonneg
8726e46168fcf7da8892b04f7e6a232af7f747c1
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/src/Init/Lean/Meta/Tactic/Cases.lean
42508752d796c1dd852f6ddd4121f9b58e3238c6
[ "Apache-2.0" ]
permissive
mhuisi/lean4
28d35a4febc2e251c7f05492e13f3b05d6f9b7af
dda44bc47f3e5d024508060dac2bcb59fd12e4c0
refs/heads/master
1,621,225,489,283
1,585,142,689,000
1,585,142,689,000
250,590,438
0
2
Apache-2.0
1,602,443,220,000
1,585,327,814,000
C
UTF-8
Lean
false
false
11,306
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.Lean.Meta.AppBuilder import Init.Lean.Meta.Tactic.Induction import Init.Lean.Meta.Tactic.Injection import Init.Lean.Meta.Tactic.Assert import Init.Lean.Meta.Tactic.Subst namespace Lean namespace Meta private def mkEqAndProof (lhs rhs : Expr) : MetaM (Expr × Expr) := do lhsType ← inferType lhs; rhsType ← inferType rhs; u ← getLevel lhsType; condM (isDefEq lhsType rhsType) (pure (mkApp3 (mkConst `Eq [u]) lhsType lhs rhs, mkApp2 (mkConst `Eq.refl [u]) lhsType lhs)) (pure (mkApp4 (mkConst `HEq [u]) lhsType lhs rhsType rhs, mkApp2 (mkConst `HEq.refl [u]) lhsType lhs)) private partial def withNewIndexEqsAux {α} (indices newIndices : Array Expr) (k : Array Expr → Array Expr → MetaM α) : Nat → Array Expr → Array Expr → MetaM α | i, newEqs, newRefls => if h : i < indices.size then do let index := indices.get! i; let newIndex := newIndices.get! i; (newEqType, newRefl) ← mkEqAndProof index newIndex; withLocalDecl `h newEqType BinderInfo.default $ fun newEq => do withNewIndexEqsAux (i+1) (newEqs.push newEq) (newRefls.push newRefl) else k newEqs newRefls private def withNewIndexEqs {α} (indices newIndices : Array Expr) (k : Array Expr → Array Expr → MetaM α) : MetaM α := withNewIndexEqsAux indices newIndices k 0 #[] #[] structure GeneralizeIndicesSubgoal := (mvarId : MVarId) (indicesFVarIds : Array FVarId) (fvarId : FVarId) (numEqs : Nat) /-- Given a metavariable `mvarId` representing the ``` Ctx, h : I A j, D |- T ``` where `fvarId` is `h`s id, and the type `I A j` is an inductive datatype where `A` are parameters, and `j` the indices. Generate the goal ``` Ctx, h : I A j, D, j' : J, h' : I A j' |- j == j' -> h == h' -> T ``` Remark: `(j == j' -> h == h')` is a "telescopic" equality. Remark: `j` is sequence of terms, and `j'` a sequence of free variables. The result contains the fields - `mvarId`: the new goal - `indicesFVarIds`: `j'` ids - `fvarId`: `h'` id - `numEqs`: number of equations in the target -/ def generalizeIndices (mvarId : MVarId) (fvarId : FVarId) : MetaM GeneralizeIndicesSubgoal := do withMVarContext mvarId $ do lctx ← getLCtx; localInsts ← getLocalInstances; env ← getEnv; checkNotAssigned mvarId `generalizeIndices; fvarDecl ← getLocalDecl fvarId; type ← whnf fvarDecl.type; type.withApp $ fun f args => matchConst env f (fun _ => throwTacticEx `generalizeIndices mvarId "inductive type expected") $ fun cinfo _ => match cinfo with | ConstantInfo.inductInfo val => do unless (val.nindices > 0) $ throwTacticEx `generalizeIndices mvarId "indexed inductive type expected"; unless (args.size == val.nindices + val.nparams) $ throwTacticEx `generalizeIndices mvarId "ill-formed inductive datatype"; let indices := args.extract (args.size - val.nindices) args.size; let IA := mkAppN f (args.extract 0 val.nparams); -- `I A` IAType ← inferType IA; forallTelescopeReducing IAType $ fun newIndices _ => do let newType := mkAppN IA newIndices; withLocalDecl fvarDecl.userName newType BinderInfo.default $ fun h' => withNewIndexEqs indices newIndices $ fun newEqs newRefls => do (newEqType, newRefl) ← mkEqAndProof fvarDecl.toExpr h'; let newRefls := newRefls.push newRefl; withLocalDecl `h newEqType BinderInfo.default $ fun newEq => do let newEqs := newEqs.push newEq; /- auxType `forall (j' : J) (h' : I A j'), j == j' -> h == h' -> target -/ target ← getMVarType mvarId; tag ← getMVarTag mvarId; auxType ← mkForall newEqs target; auxType ← mkForall #[h'] auxType; auxType ← mkForall newIndices auxType; newMVar ← mkFreshExprMVarAt lctx localInsts auxType tag MetavarKind.syntheticOpaque; /- assign mvarId := newMVar indices h refls -/ assignExprMVar mvarId (mkAppN (mkApp (mkAppN newMVar indices) fvarDecl.toExpr) newRefls); (indicesFVarIds, newMVarId) ← introN newMVar.mvarId! newIndices.size [] false; (fvarId, newMVarId) ← intro1 newMVarId false; pure { mvarId := newMVarId, indicesFVarIds := indicesFVarIds, fvarId := fvarId, numEqs := newEqs.size } | _ => throwTacticEx `generalizeIndices mvarId "inductive type expected" structure CasesSubgoal extends InductionSubgoal := (ctorName : Name) namespace Cases structure Context := (inductiveVal : InductiveVal) (casesOnVal : DefinitionVal) (nminors : Nat := inductiveVal.ctors.length) (majorDecl : LocalDecl) (majorTypeFn : Expr) (majorTypeArgs : Array Expr) (majorTypeIndices : Array Expr := majorTypeArgs.extract (majorTypeArgs.size - inductiveVal.nindices) majorTypeArgs.size) private def mkCasesContext? (majorFVarId : FVarId) : MetaM (Option Context) := do env ← getEnv; if !env.contains `Eq || !env.contains `HEq then pure none else do majorDecl ← getLocalDecl majorFVarId; majorType ← whnf majorDecl.type; majorType.withApp $ fun f args => matchConst env f (fun _ => pure none) $ fun cinfo _ => do match cinfo with | ConstantInfo.inductInfo ival => if args.size != ival.nindices + ival.nparams then pure none else match env.find? (mkNameStr ival.name "casesOn") with | ConstantInfo.defnInfo cval => pure $ some { inductiveVal := ival, casesOnVal := cval, majorDecl := majorDecl, majorTypeFn := f, majorTypeArgs := args } | _ => pure none | _ => pure none /- We say the major premise has independent indices IF 1- its type is *not* an indexed inductive family, OR 2- its type is an indexed inductive family, but all indices are distinct free variables, and all local declarations different from the major and its indices do not depend on the indices. -/ private def hasIndepIndices (ctx : Context) : MetaM Bool := if ctx.majorTypeIndices.isEmpty then pure true else if ctx.majorTypeIndices.any $ fun idx => !idx.isFVar then /- One of the indices is not a free variable. -/ pure false else if ctx.majorTypeIndices.size.any $ fun i => i.any $ fun j => ctx.majorTypeIndices.get! i == ctx.majorTypeIndices.get! j then /- An index ocurrs more than once -/ pure false else do lctx ← getLCtx; mctx ← getMCtx; pure $ lctx.all $ fun decl => decl.fvarId == ctx.majorDecl.fvarId || -- decl is the major ctx.majorTypeIndices.any (fun index => decl.fvarId == index.fvarId!) || -- decl is one of the indices mctx.findLocalDeclDependsOn decl (fun fvarId => ctx.majorTypeIndices.all $ fun idx => idx.fvarId! != fvarId) -- or does not depend on any index private def elimAuxIndices (s₁ : GeneralizeIndicesSubgoal) (s₂ : Array InductionSubgoal) : MetaM (Array InductionSubgoal) := let indicesFVarIds := s₁.indicesFVarIds; s₂.mapM $ fun s => do indicesFVarIds.foldlM (fun s indexFVarId => let indexFVarId' := s.subst.get indexFVarId; (do mvarId ← clear s.mvarId indexFVarId'; pure { mvarId := mvarId, subst := s.subst.erase indexFVarId, .. s }) <|> (pure s)) s private def toCasesSubgoals (s : Array InductionSubgoal) (ctorNames : Array Name) : Array CasesSubgoal := s.mapIdx $ fun i s => { ctorName := ctorNames.get! i, toInductionSubgoal := s } private partial def unifyEqsAux : Nat → CasesSubgoal → MetaM (Option CasesSubgoal) | 0, s => do trace! `Meta.cases ("unifyEqs " ++ MessageData.ofGoal s.mvarId); pure (some s) | n+1, s => do trace! `Meta.cases ("unifyEqs [" ++ toString (n+1) ++ "] " ++ MessageData.ofGoal s.mvarId); (eqFVarId, mvarId) ← intro1 s.mvarId; withMVarContext mvarId $ do eqDecl ← getLocalDecl eqFVarId; match eqDecl.type.heq? with | some (α, a, β, b) => do prf ← mkEqOfHEq (mkFVar eqFVarId); aEqb ← mkEq a b; mvarId ← assert mvarId eqDecl.userName aEqb prf; mvarId ← clear mvarId eqFVarId; unifyEqsAux (n+1) { mvarId := mvarId, .. s } | none => match eqDecl.type.eq? with | some (α, a, b) => let skip : Unit → MetaM (Option CasesSubgoal) := fun _ => do { mvarId ← clear mvarId eqFVarId; unifyEqsAux n { mvarId := mvarId, .. s } }; let substEq (symm : Bool) : MetaM (Option CasesSubgoal) := do { (newSubst, mvarId) ← substCore mvarId eqFVarId false true; unifyEqsAux n { mvarId := mvarId, subst := newSubst.compose s.subst, fields := s.fields.map $ fun fvarId => newSubst.get fvarId, .. s } }; let inj : Unit → MetaM (Option CasesSubgoal) := fun _ => do { r ← injectionCore mvarId eqFVarId; match r with | InjectionResultCore.solved => pure none -- this alternative has been solved | InjectionResultCore.subgoal mvarId numEqs => unifyEqsAux (n+numEqs) { mvarId := mvarId, .. s } }; condM (isDefEq a b) (skip ()) $ do a ← whnf a; b ← whnf b; match a, b with | Expr.fvar aFVarId _, Expr.fvar bFVarId _ => do aDecl ← getLocalDecl aFVarId; bDecl ← getLocalDecl bFVarId; substEq (aDecl.index < bDecl.index) | Expr.fvar _ _, _ => substEq false | _, Expr.fvar _ _ => substEq true | _, _ => inj () | none => throwTacticEx `cases mvarId "equality expected" private def unifyEqs (numEqs : Nat) (subgoals : Array CasesSubgoal) : MetaM (Array CasesSubgoal) := subgoals.foldlM (fun subgoals s => do s? ← unifyEqsAux numEqs s; match s? with | none => pure $ subgoals | some s => pure $ subgoals.push s) #[] def cases (mvarId : MVarId) (majorFVarId : FVarId) (givenNames : Array (List Name) := #[]) (useUnusedNames := false) : MetaM (Array CasesSubgoal) := withMVarContext mvarId $ do checkNotAssigned mvarId `cases; context? ← mkCasesContext? majorFVarId; match context? with | none => throwTacticEx `cases mvarId "not applicable to the given hypothesis" | some ctx => let ctors := ctx.inductiveVal.ctors.toArray; let casesOn := mkCasesOnFor ctx.inductiveVal.name; condM (hasIndepIndices ctx) (do s ← induction mvarId majorFVarId casesOn givenNames useUnusedNames; pure $ toCasesSubgoals s ctors) (do s₁ ← generalizeIndices mvarId majorFVarId; trace! `Meta.cases ("after generalizeIndices" ++ Format.line ++ MessageData.ofGoal s₁.mvarId); s₂ ← induction s₁.mvarId s₁.fvarId casesOn givenNames useUnusedNames; s₂ ← elimAuxIndices s₁ s₂; let s₂ := toCasesSubgoals s₂ ctors; unifyEqs s₁.numEqs s₂) end Cases def cases (mvarId : MVarId) (majorFVarId : FVarId) (givenNames : Array (List Name) := #[]) (useUnusedNames := false) : MetaM (Array CasesSubgoal) := Cases.cases mvarId majorFVarId givenNames useUnusedNames end Meta end Lean
15b9e8b3183938bf13e234fc566171ff31ac6400
b7f22e51856f4989b970961f794f1c435f9b8f78
/library/data/finset/to_set.lean
d4472a5e6f954693a1cf0f36f2fb7476748d2a0d
[ "Apache-2.0" ]
permissive
soonhokong/lean
cb8aa01055ffe2af0fb99a16b4cda8463b882cd1
38607e3eb57f57f77c0ac114ad169e9e4262e24f
refs/heads/master
1,611,187,284,081
1,450,766,737,000
1,476,122,547,000
11,513,992
2
0
null
1,401,763,102,000
1,374,182,235,000
C++
UTF-8
Lean
false
false
4,031
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad Interactions between finset and set. -/ import data.finset.comb data.set.function open nat eq.ops set namespace finset variable {A : Type} variable [deceq : decidable_eq A] definition to_set [coercion] (s : finset A) : set A := λx, x ∈ s abbreviation ts := @to_set A variables (s t : finset A) (x y : A) theorem mem_eq_mem_to_set : x ∈ s = (x ∈ ts s) := rfl definition to_set.inj {s₁ s₂ : finset A} : to_set s₁ = to_set s₂ → s₁ = s₂ := λ h, ext (λ a, iff.of_eq (calc (a ∈ s₁) = (a ∈ ts s₁) : mem_eq_mem_to_set ... = (a ∈ ts s₂) : h ... = (a ∈ s₂) : mem_eq_mem_to_set)) /- operations -/ theorem mem_to_set_empty : (x ∈ ts ∅) = (x ∈ ∅) := rfl theorem to_set_empty : ts ∅ = (@set.empty A) := rfl theorem mem_to_set_univ [h : fintype A] : (x ∈ ts univ) = (x ∈ set.univ) := propext (iff.intro (assume H, trivial) (assume H, !mem_univ)) theorem to_set_univ [h : fintype A] : ts univ = (set.univ : set A) := funext (λ x, !mem_to_set_univ) theorem mem_to_set_upto (x n : ℕ) : x ∈ ts (upto n) = (x ∈ {a | a < n}) := !mem_upto_eq theorem to_set_upto (n : ℕ) : ts (upto n) = {a | a < n} := funext (λ x, !mem_to_set_upto) include deceq theorem mem_to_set_insert : x ∈ insert y s = (x ∈ set.insert y s) := !mem_insert_eq theorem to_set_insert : insert y s = set.insert y s := funext (λ x, !mem_to_set_insert) theorem mem_to_set_union : x ∈ s ∪ t = (x ∈ ts s ∪ ts t) := !mem_union_eq theorem to_set_union : ts (s ∪ t) = ts s ∪ ts t := funext (λ x, !mem_to_set_union) theorem mem_to_set_inter : x ∈ s ∩ t = (x ∈ ts s ∩ ts t) := !mem_inter_eq theorem to_set_inter : ts (s ∩ t) = ts s ∩ ts t := funext (λ x, !mem_to_set_inter) theorem mem_to_set_diff : x ∈ s \ t = (x ∈ ts s \ ts t) := !mem_diff_eq theorem to_set_diff : ts (s \ t) = ts s \ ts t := funext (λ x, !mem_to_set_diff) theorem mem_to_set_sep (p : A → Prop) [h : decidable_pred p] : x ∈ sep p s = (x ∈ set.sep p s) := !finset.mem_sep_eq theorem to_set_sep (p : A → Prop) [h : decidable_pred p] : sep p s = set.sep p s := funext (λ x, !mem_to_set_sep) theorem mem_to_set_image {B : Type} [h : decidable_eq B] (f : A → B) {s : finset A} {y : B} : y ∈ image f s = (y ∈ set.image f s) := !mem_image_eq theorem to_set_image {B : Type} [h : decidable_eq B] (f : A → B) (s : finset A) : image f s = set.image f s := funext (λ x, !mem_to_set_image) /- relations -/ definition decidable_mem_to_set [instance] (x : A) (s : finset A) : decidable (x ∈ ts s) := decidable_of_decidable_of_eq _ !mem_eq_mem_to_set theorem eq_of_to_set_eq_to_set {s t : finset A} (H : to_set s = to_set t) : s = t := ext (take x, by rewrite [mem_eq_mem_to_set s, H]) theorem eq_eq_to_set_eq : (s = t) = (ts s = ts t) := propext (iff.intro (assume H, H ▸ rfl) !eq_of_to_set_eq_to_set) definition decidable_to_set_eq [instance] (s t : finset A) : decidable (ts s = ts t) := decidable_of_decidable_of_eq _ !eq_eq_to_set_eq theorem subset_eq_to_set_subset (s t : finset A) : (s ⊆ t) = (ts s ⊆ ts t) := propext (iff.intro (assume H, take x xs, mem_of_subset_of_mem H xs) (assume H, subset_of_forall H)) definition decidable_to_set_subset (s t : finset A) : decidable (ts s ⊆ ts t) := decidable_of_decidable_of_eq _ !subset_eq_to_set_subset /- bounded quantifiers -/ definition decidable_bounded_forall (s : finset A) (p : A → Prop) [h : decidable_pred p] : decidable (∀₀ x ∈ ts s, p x) := decidable_of_decidable_of_iff _ !all_iff_forall definition decidable_bounded_exists (s : finset A) (p : A → Prop) [h : decidable_pred p] : decidable (∃₀ x ∈ ts s, p x) := decidable_of_decidable_of_iff _ !any_iff_exists /- properties -/ theorem inj_on_to_set {B : Type} [h : decidable_eq B] (f : A → B) (s : finset A) : inj_on f s = inj_on f (ts s) := rfl end finset
b83f5a3cf96ae5085e380ab1df852c9b0af4322e
1a61aba1b67cddccce19532a9596efe44be4285f
/library/data/finset/comb.lean
335800a95bb22b532806626124f7d096e1452691
[ "Apache-2.0" ]
permissive
eigengrau/lean
07986a0f2548688c13ba36231f6cdbee82abf4c6
f8a773be1112015e2d232661ce616d23f12874d0
refs/heads/master
1,610,939,198,566
1,441,352,386,000
1,441,352,494,000
41,903,576
0
0
null
1,441,352,210,000
1,441,352,210,000
null
UTF-8
Lean
false
false
18,878
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura, Jeremy Avigad Combinators for finite sets. -/ import data.finset.basic logic.identities open list quot subtype decidable perm function namespace finset /- image (corresponds to map on list) -/ section image variables {A B : Type} variable [h : decidable_eq B] include h definition image (f : A → B) (s : finset A) : finset B := quot.lift_on s (λ l, to_finset (list.map f (elt_of l))) (λ l₁ l₂ p, quot.sound (perm_erase_dup_of_perm (perm_map _ p))) notation [priority finset.prio] f `'[`:max a `]` := image f a theorem image_empty (f : A → B) : image f ∅ = ∅ := rfl theorem mem_image_of_mem (f : A → B) {s : finset A} {a : A} : a ∈ s → f a ∈ image f s := quot.induction_on s (take l, assume H : a ∈ elt_of l, mem_to_finset (mem_map f H)) theorem mem_image {f : A → B} {s : finset A} {a : A} {b : B} (H1 : a ∈ s) (H2 : f a = b) : b ∈ image f s := eq.subst H2 (mem_image_of_mem f H1) theorem exists_of_mem_image {f : A → B} {s : finset A} {b : B} : b ∈ image f s → ∃a, a ∈ s ∧ f a = b := quot.induction_on s (take l, assume H : b ∈ erase_dup (list.map f (elt_of l)), exists_of_mem_map (mem_of_mem_erase_dup H)) theorem mem_image_iff (f : A → B) {s : finset A} {y : B} : y ∈ image f s ↔ ∃x, x ∈ s ∧ f x = y := iff.intro exists_of_mem_image (assume H, obtain x (H₁ : x ∈ s) (H₂ : f x = y), from H, mem_image H₁ H₂) theorem mem_image_eq (f : A → B) {s : finset A} {y : B} : y ∈ image f s = ∃x, x ∈ s ∧ f x = y := propext (mem_image_iff f) theorem mem_image_of_mem_image_of_subset {f : A → B} {s t : finset A} {y : B} (H1 : y ∈ image f s) (H2 : s ⊆ t) : y ∈ image f t := obtain x (H3: x ∈ s) (H4 : f x = y), from exists_of_mem_image H1, have H5 : x ∈ t, from mem_of_subset_of_mem H2 H3, show y ∈ image f t, from mem_image H5 H4 theorem image_insert [h' : decidable_eq A] (f : A → B) (s : finset A) (a : A) : image f (insert a s) = insert (f a) (image f s) := ext (take y, iff.intro (assume H : y ∈ image f (insert a s), obtain x (H1l : x ∈ insert a s) (H1r :f x = y), from exists_of_mem_image H, have x = a ∨ x ∈ s, from eq_or_mem_of_mem_insert H1l, or.elim this (suppose x = a, have f a = y, from eq.subst this H1r, show y ∈ insert (f a) (image f s), from eq.subst this !mem_insert) (suppose x ∈ s, have f x ∈ image f s, from mem_image_of_mem f this, show y ∈ insert (f a) (image f s), from eq.subst H1r (mem_insert_of_mem _ this))) (suppose y ∈ insert (f a) (image f s), have y = f a ∨ y ∈ image f s, from eq_or_mem_of_mem_insert this, or.elim this (suppose y = f a, have f a ∈ image f (insert a s), from mem_image_of_mem f !mem_insert, show y ∈ image f (insert a s), from eq.subst (eq.symm `y = f a`) this) (suppose y ∈ image f s, show y ∈ image f (insert a s), from mem_image_of_mem_image_of_subset this !subset_insert))) lemma image_compose {C : Type} [deceqC : decidable_eq C] {f : B → C} {g : A → B} {s : finset A} : image (f∘g) s = image f (image g s) := ext (take z, iff.intro (suppose z ∈ image (f∘g) s, obtain x (Hx : x ∈ s) (Hgfx : f (g x) = z), from exists_of_mem_image this, by rewrite -Hgfx; apply mem_image_of_mem _ (mem_image_of_mem _ Hx)) (suppose z ∈ image f (image g s), obtain y (Hy : y ∈ image g s) (Hfy : f y = z), from exists_of_mem_image this, obtain x (Hx : x ∈ s) (Hgx : g x = y), from exists_of_mem_image Hy, mem_image Hx (by esimp; rewrite [Hgx, Hfy]))) lemma image_subset {a b : finset A} (f : A → B) (H : a ⊆ b) : f '[a] ⊆ f '[b] := subset_of_forall (take y, assume Hy : y ∈ f '[a], obtain x (Hx₁ : x ∈ a) (Hx₂ : f x = y), from exists_of_mem_image Hy, mem_image (mem_of_subset_of_mem H Hx₁) Hx₂) theorem image_union [h' : decidable_eq A] (f : A → B) (s t : finset A) : image f (s ∪ t) = image f s ∪ image f t := ext (take y, iff.intro (assume H : y ∈ image f (s ∪ t), obtain x [(xst : x ∈ s ∪ t) (fxy : f x = y)], from exists_of_mem_image H, or.elim (mem_or_mem_of_mem_union xst) (assume xs, mem_union_l (mem_image xs fxy)) (assume xt, mem_union_r (mem_image xt fxy))) (assume H : y ∈ image f s ∪ image f t, or.elim (mem_or_mem_of_mem_union H) (assume yifs : y ∈ image f s, obtain x [(xs : x ∈ s) (fxy : f x = y)], from exists_of_mem_image yifs, mem_image (mem_union_l xs) fxy) (assume yift : y ∈ image f t, obtain x [(xt : x ∈ t) (fxy : f x = y)], from exists_of_mem_image yift, mem_image (mem_union_r xt) fxy))) end image /- separation and set-builder notation -/ section sep variables {A : Type} [deceq : decidable_eq A] include deceq variables (p : A → Prop) [decp : decidable_pred p] (s : finset A) {x : A} include decp definition sep : finset A := quot.lift_on s (λl, to_finset_of_nodup (list.filter p (subtype.elt_of l)) (list.nodup_filter p (subtype.has_property l))) (λ l₁ l₂ u, quot.sound (perm.perm_filter u)) notation [priority finset.prio] `{` binder ∈ s `|` r:(scoped:1 p, sep p s) `}` := r theorem sep_empty : sep p ∅ = ∅ := rfl variables {p s} theorem of_mem_sep : x ∈ sep p s → p x := quot.induction_on s (take l, list.of_mem_filter) theorem mem_of_mem_sep : x ∈ sep p s → x ∈ s := quot.induction_on s (take l, list.mem_of_mem_filter) theorem mem_sep_of_mem {x : A} : x ∈ s → p x → x ∈ sep p s := quot.induction_on s (take l, list.mem_filter_of_mem) variables (p s) theorem mem_sep_iff : x ∈ sep p s ↔ x ∈ s ∧ p x := iff.intro (assume H, and.intro (mem_of_mem_sep H) (of_mem_sep H)) (assume H, mem_sep_of_mem (and.left H) (and.right H)) theorem mem_sep_eq : x ∈ sep p s = (x ∈ s ∧ p x) := propext !mem_sep_iff variable t : finset A theorem mem_sep_union_iff : x ∈ sep p (s ∪ t) ↔ x ∈ sep p s ∨ x ∈ sep p t := by rewrite [*mem_sep_iff, mem_union_iff, and.right_distrib] end sep section variables {A : Type} [deceqA : decidable_eq A] include deceqA theorem eq_sep_of_subset {s t : finset A} (ssubt : s ⊆ t) : s = {x ∈ t | x ∈ s} := ext (take x, iff.intro (suppose x ∈ s, mem_sep_of_mem (mem_of_subset_of_mem ssubt this) this) (suppose x ∈ {x ∈ t | x ∈ s}, of_mem_sep this)) theorem mem_singleton_eq' (x a : A) : x ∈ '{a} = (x = a) := by rewrite [mem_insert_eq, mem_empty_eq, or_false] end /- set difference -/ section diff variables {A : Type} [deceq : decidable_eq A] include deceq definition diff (s t : finset A) : finset A := {x ∈ s | x ∉ t} infix [priority finset.prio] `\`:70 := diff theorem mem_of_mem_diff {s t : finset A} {x : A} (H : x ∈ s \ t) : x ∈ s := mem_of_mem_sep H theorem not_mem_of_mem_diff {s t : finset A} {x : A} (H : x ∈ s \ t) : x ∉ t := of_mem_sep H theorem mem_diff {s t : finset A} {x : A} (H1 : x ∈ s) (H2 : x ∉ t) : x ∈ s \ t := mem_sep_of_mem H1 H2 theorem mem_diff_iff (s t : finset A) (x : A) : x ∈ s \ t ↔ x ∈ s ∧ x ∉ t := iff.intro (assume H, and.intro (mem_of_mem_diff H) (not_mem_of_mem_diff H)) (assume H, mem_diff (and.left H) (and.right H)) theorem mem_diff_eq (s t : finset A) (x : A) : x ∈ s \ t = (x ∈ s ∧ x ∉ t) := propext !mem_diff_iff theorem union_diff_cancel {s t : finset A} (H : s ⊆ t) : s ∪ (t \ s) = t := ext (take x, iff.intro (suppose x ∈ s ∪ (t \ s), or.elim (mem_or_mem_of_mem_union this) (suppose x ∈ s, mem_of_subset_of_mem H this) (suppose x ∈ t \ s, mem_of_mem_diff this)) (suppose x ∈ t, decidable.by_cases (suppose x ∈ s, mem_union_left _ this) (suppose x ∉ s, mem_union_right _ (mem_diff `x ∈ t` this)))) theorem diff_union_cancel {s t : finset A} (H : s ⊆ t) : (t \ s) ∪ s = t := eq.subst !union.comm (!union_diff_cancel H) end diff /- set complement -/ section complement variables {A : Type} [deceqA : decidable_eq A] [h : fintype A] include deceqA h definition complement (s : finset A) : finset A := univ \ s prefix [priority finset.prio] - := complement theorem mem_complement {s : finset A} {x : A} (H : x ∉ s) : x ∈ -s := mem_diff !mem_univ H theorem not_mem_of_mem_complement {s : finset A} {x : A} (H : x ∈ -s) : x ∉ s := not_mem_of_mem_diff H theorem mem_complement_iff (s : finset A) (x : A) : x ∈ -s ↔ x ∉ s := iff.intro not_mem_of_mem_complement mem_complement section open classical theorem union_eq_comp_comp_inter_comp (s t : finset A) : s ∪ t = -(-s ∩ -t) := ext (take x, by rewrite [mem_union_iff, mem_complement_iff, mem_inter_iff, *mem_complement_iff, or_iff_not_and_not]) theorem inter_eq_comp_comp_union_comp (s t : finset A) : s ∩ t = -(-s ∪ -t) := ext (take x, by rewrite [mem_inter_iff, mem_complement_iff, mem_union_iff, *mem_complement_iff, and_iff_not_or_not]) end end complement /- all -/ section all variables {A : Type} definition all (s : finset A) (p : A → Prop) : Prop := quot.lift_on s (λ l, all (elt_of l) p) (λ l₁ l₂ p, foldr_eq_of_perm (λ a₁ a₂ q, propext !and.left_comm) p true) theorem all_empty (p : A → Prop) : all ∅ p = true := rfl theorem of_mem_of_all {p : A → Prop} {a : A} {s : finset A} : a ∈ s → all s p → p a := quot.induction_on s (λ l i h, list.of_mem_of_all i h) theorem forall_of_all {p : A → Prop} {s : finset A} (H : all s p) : ∀{a}, a ∈ s → p a := λ a H', of_mem_of_all H' H theorem all_of_forall {p : A → Prop} {s : finset A} : (∀a, a ∈ s → p a) → all s p := quot.induction_on s (λ l H, list.all_of_forall H) theorem all_iff_forall (p : A → Prop) (s : finset A) : all s p ↔ (∀a, a ∈ s → p a) := iff.intro forall_of_all all_of_forall definition decidable_all [instance] (p : A → Prop) [h : decidable_pred p] (s : finset A) : decidable (all s p) := quot.rec_on_subsingleton s (λ l, list.decidable_all p (elt_of l)) theorem all_implies {p q : A → Prop} {s : finset A} : all s p → (∀ x, p x → q x) → all s q := quot.induction_on s (λ l h₁ h₂, list.all_implies h₁ h₂) variable [h : decidable_eq A] include h theorem all_union {p : A → Prop} {s₁ s₂ : finset A} : all s₁ p → all s₂ p → all (s₁ ∪ s₂) p := quot.induction_on₂ s₁ s₂ (λ l₁ l₂ a₁ a₂, all_union a₁ a₂) theorem all_of_all_union_left {p : A → Prop} {s₁ s₂ : finset A} : all (s₁ ∪ s₂) p → all s₁ p := quot.induction_on₂ s₁ s₂ (λ l₁ l₂ a, list.all_of_all_union_left a) theorem all_of_all_union_right {p : A → Prop} {s₁ s₂ : finset A} : all (s₁ ∪ s₂) p → all s₂ p := quot.induction_on₂ s₁ s₂ (λ l₁ l₂ a, list.all_of_all_union_right a) theorem all_insert_of_all {p : A → Prop} {a : A} {s : finset A} : p a → all s p → all (insert a s) p := quot.induction_on s (λ l h₁ h₂, list.all_insert_of_all h₁ h₂) theorem all_erase_of_all {p : A → Prop} (a : A) {s : finset A}: all s p → all (erase a s) p := quot.induction_on s (λ l h, list.all_erase_of_all a h) theorem all_inter_of_all_left {p : A → Prop} {s₁ : finset A} (s₂ : finset A) : all s₁ p → all (s₁ ∩ s₂) p := quot.induction_on₂ s₁ s₂ (λ l₁ l₂ h, list.all_inter_of_all_left _ h) theorem all_inter_of_all_right {p : A → Prop} {s₁ : finset A} (s₂ : finset A) : all s₂ p → all (s₁ ∩ s₂) p := quot.induction_on₂ s₁ s₂ (λ l₁ l₂ h, list.all_inter_of_all_right _ h) theorem subset_iff_all (s t : finset A) : s ⊆ t ↔ all s (λ x, x ∈ t) := iff.intro (suppose s ⊆ t, all_of_forall (take x, suppose x ∈ s, mem_of_subset_of_mem `s ⊆ t` `x ∈ s`)) (suppose all s (λ x, x ∈ t), subset_of_forall (take x, suppose x ∈ s, of_mem_of_all `x ∈ s` `all s (λ x, x ∈ t)`)) definition decidable_subset [instance] (s t : finset A) : decidable (s ⊆ t) := decidable_of_decidable_of_iff _ (iff.symm !subset_iff_all) end all /- any -/ section any variables {A : Type} definition any (s : finset A) (p : A → Prop) : Prop := quot.lift_on s (λ l, any (elt_of l) p) (λ l₁ l₂ p, foldr_eq_of_perm (λ a₁ a₂ q, propext !or.left_comm) p false) theorem any_empty (p : A → Prop) : any ∅ p = false := rfl theorem exists_of_any {p : A → Prop} {s : finset A} : any s p → ∃a, a ∈ s ∧ p a := quot.induction_on s (λ l H, list.exists_of_any H) theorem any_of_mem {p : A → Prop} {s : finset A} {a : A} : a ∈ s → p a → any s p := quot.induction_on s (λ l H1 H2, list.any_of_mem H1 H2) theorem any_of_exists {p : A → Prop} {s : finset A} (H : ∃a, a ∈ s ∧ p a) : any s p := obtain a H₁ H₂, from H, any_of_mem H₁ H₂ theorem any_iff_exists (p : A → Prop) (s : finset A) : any s p ↔ (∃a, a ∈ s ∧ p a) := iff.intro exists_of_any any_of_exists theorem any_of_insert [h : decidable_eq A] {p : A → Prop} (s : finset A) {a : A} (H : p a) : any (insert a s) p := any_of_mem (mem_insert a s) H theorem any_of_insert_right [h : decidable_eq A] {p : A → Prop} {s : finset A} (a : A) (H : any s p) : any (insert a s) p := obtain b (H₁ : b ∈ s) (H₂ : p b), from exists_of_any H, any_of_mem (mem_insert_of_mem a H₁) H₂ definition decidable_any [instance] (p : A → Prop) [h : decidable_pred p] (s : finset A) : decidable (any s p) := quot.rec_on_subsingleton s (λ l, list.decidable_any p (elt_of l)) end any section product variables {A B : Type} definition product (s₁ : finset A) (s₂ : finset B) : finset (A × B) := quot.lift_on₂ s₁ s₂ (λ l₁ l₂, to_finset_of_nodup (product (elt_of l₁) (elt_of l₂)) (nodup_product (has_property l₁) (has_property l₂))) (λ v₁ v₂ w₁ w₂ p₁ p₂, quot.sound (perm_product p₁ p₂)) infix [priority finset.prio] * := product theorem empty_product (s : finset B) : @empty A * s = ∅ := quot.induction_on s (λ l, rfl) theorem mem_product {a : A} {b : B} {s₁ : finset A} {s₂ : finset B} : a ∈ s₁ → b ∈ s₂ → (a, b) ∈ s₁ * s₂ := quot.induction_on₂ s₁ s₂ (λ l₁ l₂ i₁ i₂, list.mem_product i₁ i₂) theorem mem_of_mem_product_left {a : A} {b : B} {s₁ : finset A} {s₂ : finset B} : (a, b) ∈ s₁ * s₂ → a ∈ s₁ := quot.induction_on₂ s₁ s₂ (λ l₁ l₂ i, list.mem_of_mem_product_left i) theorem mem_of_mem_product_right {a : A} {b : B} {s₁ : finset A} {s₂ : finset B} : (a, b) ∈ s₁ * s₂ → b ∈ s₂ := quot.induction_on₂ s₁ s₂ (λ l₁ l₂ i, list.mem_of_mem_product_right i) theorem product_empty (s : finset A) : s * @empty B = ∅ := ext (λ p, match p with | (a, b) := iff.intro (λ i, absurd (mem_of_mem_product_right i) !not_mem_empty) (λ i, absurd i !not_mem_empty) end) end product /- powerset -/ section powerset variables {A : Type} [deceqA : decidable_eq A] include deceqA section list_powerset open list definition list_powerset : list A → finset (finset A) | [] := '{∅} | (a :: l) := list_powerset l ∪ image (insert a) (list_powerset l) end list_powerset private theorem image_insert_comm (a b : A) (s : finset (finset A)) : image (insert a) (image (insert b) s) = image (insert b) (image (insert a) s) := have aux' : ∀ a b : A, ∀ x : finset A, x ∈ image (insert a) (image (insert b) s) → x ∈ image (insert b) (image (insert a) s), from begin intros [a, b, x, H], cases (exists_of_mem_image H) with [y, Hy], cases Hy with [Hy1, Hy2], cases (exists_of_mem_image Hy1) with [z, Hz], cases Hz with [Hz1, Hz2], substvars, rewrite insert.comm, repeat (apply mem_image_of_mem), assumption end, ext (take x, iff.intro (aux' a b x) (aux' b a x)) theorem list_powerset_eq_list_powerset_of_perm {l₁ l₂ : list A} (p : l₁ ~ l₂) : list_powerset l₁ = list_powerset l₂ := perm.induction_on p rfl (λ x l₁ l₂ p ih, by rewrite [↑list_powerset, ih]) (λ x y l, by rewrite [↑list_powerset, ↑list_powerset, *image_union, image_insert_comm, *union.assoc, union.left_comm (finset.image (finset.insert x) _)]) (λ l₁ l₂ l₃ p₁ p₂ r₁ r₂, eq.trans r₁ r₂) definition powerset (s : finset A) : finset (finset A) := quot.lift_on s (λ l, list_powerset (elt_of l)) (λ l₁ l₂ p, list_powerset_eq_list_powerset_of_perm p) prefix [priority finset.prio] `𝒫`:100 := powerset theorem powerset_empty : 𝒫 (∅ : finset A) = '{∅} := rfl theorem powerset_insert {a : A} {s : finset A} : a ∉ s → 𝒫 (insert a s) = 𝒫 s ∪ image (insert a) (𝒫 s) := quot.induction_on s (λ l, assume H : a ∉ quot.mk l, calc 𝒫 (insert a (quot.mk l)) = list_powerset (list.insert a (elt_of l)) : rfl ... = list_powerset (#list a :: elt_of l) : by rewrite [list.insert_eq_of_not_mem H] ... = 𝒫 (quot.mk l) ∪ image (insert a) (𝒫 (quot.mk l)) : rfl) theorem mem_powerset_iff_subset (s : finset A) : ∀ x, x ∈ 𝒫 s ↔ x ⊆ s := begin induction s with a s nains ih, intro x, rewrite powerset_empty, show x ∈ '{∅} ↔ x ⊆ ∅, by rewrite [mem_singleton_eq', subset_empty_iff], intro x, rewrite [powerset_insert nains, mem_union_iff, ih, mem_image_iff], exact (iff.intro (assume H, or.elim H (suppose x ⊆ s, subset.trans this !subset_insert) (suppose ∃ y, y ∈ 𝒫 s ∧ insert a y = x, obtain y [yps iay], from this, show x ⊆ insert a s, begin rewrite [-iay], apply insert_subset_insert, rewrite -ih, apply yps end)) (assume H : x ⊆ insert a s, assert H' : erase a x ⊆ s, from erase_subset_of_subset_insert H, decidable.by_cases (suppose a ∈ x, or.inr (exists.intro (erase a x) (and.intro (show erase a x ∈ 𝒫 s, by rewrite ih; apply H') (show insert a (erase a x) = x, from insert_erase this)))) (suppose a ∉ x, or.inl (show x ⊆ s, by rewrite [(erase_eq_of_not_mem this) at H']; apply H')))) end theorem subset_of_mem_powerset {s t : finset A} (H : s ∈ 𝒫 t) : s ⊆ t := iff.mp (mem_powerset_iff_subset t s) H theorem mem_powerset_of_subset {s t : finset A} (H : s ⊆ t) : s ∈ 𝒫 t := iff.mpr (mem_powerset_iff_subset t s) H theorem empty_mem_powerset (s : finset A) : ∅ ∈ 𝒫 s := mem_powerset_of_subset (empty_subset s) end powerset end finset
b6f4ec8259d11bc71ccfce2de243f8aff0bcfdfa
9dc8cecdf3c4634764a18254e94d43da07142918
/src/ring_theory/trace.lean
4ec7c28b8cceb4165f06085b5a396d6221210929
[ "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
22,540
lean
/- Copyright (c) 2020 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen -/ import linear_algebra.matrix.bilinear_form import linear_algebra.matrix.charpoly.minpoly import linear_algebra.determinant import linear_algebra.finite_dimensional import linear_algebra.vandermonde import linear_algebra.trace import field_theory.is_alg_closed.algebraic_closure import field_theory.primitive_element import field_theory.galois import ring_theory.power_basis /-! # Trace for (finite) ring extensions. Suppose we have an `R`-algebra `S` with a finite basis. For each `s : S`, the trace of the linear map given by multiplying by `s` gives information about the roots of the minimal polynomial of `s` over `R`. ## Main definitions * `algebra.trace R S x`: the trace of an element `s` of an `R`-algebra `S` * `algebra.trace_form R S`: bilinear form sending `x`, `y` to the trace of `x * y` * `algebra.trace_matrix R b`: the matrix whose `(i j)`-th element is the trace of `b i * b j`. * `algebra.embeddings_matrix A C b : matrix κ (B →ₐ[A] C) C` is the matrix whose `(i, σ)` coefficient is `σ (b i)`. * `algebra.embeddings_matrix_reindex A C b e : matrix κ κ C` is the matrix whose `(i, j)` coefficient is `σⱼ (b i)`, where `σⱼ : B →ₐ[A] C` is the embedding corresponding to `j : κ` given by a bijection `e : κ ≃ (B →ₐ[A] C)`. ## Main results * `trace_algebra_map_of_basis`, `trace_algebra_map`: if `x : K`, then `Tr_{L/K} x = [L : K] x` * `trace_trace_of_basis`, `trace_trace`: `Tr_{L/K} (Tr_{F/L} x) = Tr_{F/K} x` * `trace_eq_sum_roots`: the trace of `x : K(x)` is the sum of all conjugate roots of `x` * `trace_eq_sum_embeddings`: the trace of `x : K(x)` is the sum of all embeddings of `x` into an algebraically closed field * `trace_form_nondegenerate`: the trace form over a separable extension is a nondegenerate bilinear form ## Implementation notes Typically, the trace is defined specifically for finite field extensions. The definition is as general as possible and the assumption that we have fields or that the extension is finite is added to the lemmas as needed. We only define the trace for left multiplication (`algebra.left_mul_matrix`, i.e. `linear_map.mul_left`). For now, the definitions assume `S` is commutative, so the choice doesn't matter anyway. ## References * https://en.wikipedia.org/wiki/Field_trace -/ universes u v w z variables {R S T : Type*} [comm_ring R] [comm_ring S] [comm_ring T] variables [algebra R S] [algebra R T] variables {K L : Type*} [field K] [field L] [algebra K L] variables {ι κ : Type w} [fintype ι] open finite_dimensional open linear_map open matrix open_locale big_operators open_locale matrix namespace algebra variables (b : basis ι R S) variables (R S) /-- The trace of an element `s` of an `R`-algebra is the trace of `(*) s`, as an `R`-linear map. -/ noncomputable def trace : S →ₗ[R] R := (linear_map.trace R S).comp (lmul R S).to_linear_map variables {S} -- Not a `simp` lemma since there are more interesting ways to rewrite `trace R S x`, -- for example `trace_trace` lemma trace_apply (x) : trace R S x = linear_map.trace R S (lmul R S x) := rfl lemma trace_eq_zero_of_not_exists_basis (h : ¬ ∃ (s : finset S), nonempty (basis s R S)) : trace R S = 0 := by { ext s, simp [trace_apply, linear_map.trace, h] } include b variables {R} -- Can't be a `simp` lemma because it depends on a choice of basis lemma trace_eq_matrix_trace [decidable_eq ι] (b : basis ι R S) (s : S) : trace R S s = matrix.trace (algebra.left_mul_matrix b s) := by { rw [trace_apply, linear_map.trace_eq_matrix_trace _ b, ←to_matrix_lmul_eq], refl } /-- If `x` is in the base field `K`, then the trace is `[L : K] * x`. -/ lemma trace_algebra_map_of_basis (x : R) : trace R S (algebra_map R S x) = fintype.card ι • x := begin haveI := classical.dec_eq ι, rw [trace_apply, linear_map.trace_eq_matrix_trace R b, matrix.trace], convert finset.sum_const _, ext i, simp [-coe_lmul_eq_mul], end omit b /-- If `x` is in the base field `K`, then the trace is `[L : K] * x`. (If `L` is not finite-dimensional over `K`, then `trace` and `finrank` return `0`.) -/ @[simp] lemma trace_algebra_map (x : K) : trace K L (algebra_map K L x) = finrank K L • x := begin by_cases H : ∃ (s : finset L), nonempty (basis s K L), { rw [trace_algebra_map_of_basis H.some_spec.some, finrank_eq_card_basis H.some_spec.some] }, { simp [trace_eq_zero_of_not_exists_basis K H, finrank_eq_zero_of_not_exists_basis_finset H] } end lemma trace_trace_of_basis [algebra S T] [is_scalar_tower R S T] {ι κ : Type*} [finite ι] [finite κ] (b : basis ι R S) (c : basis κ S T) (x : T) : trace R S (trace S T x) = trace R T x := begin haveI := classical.dec_eq ι, haveI := classical.dec_eq κ, casesI nonempty_fintype ι, casesI nonempty_fintype κ, rw [trace_eq_matrix_trace (b.smul c), trace_eq_matrix_trace b, trace_eq_matrix_trace c, matrix.trace, matrix.trace, matrix.trace, ← finset.univ_product_univ, finset.sum_product], refine finset.sum_congr rfl (λ i _, _), simp only [alg_hom.map_sum, smul_left_mul_matrix, finset.sum_apply, matrix.diag, -- The unifier is not smart enough to apply this one by itself: finset.sum_apply i _ (λ y, left_mul_matrix b (left_mul_matrix c x y y))] end lemma trace_comp_trace_of_basis [algebra S T] [is_scalar_tower R S T] {ι κ : Type*} [finite ι] [fintype κ] (b : basis ι R S) (c : basis κ S T) : (trace R S).comp ((trace S T).restrict_scalars R) = trace R T := by { ext, rw [linear_map.comp_apply, linear_map.restrict_scalars_apply, trace_trace_of_basis b c] } @[simp] lemma trace_trace [algebra K T] [algebra L T] [is_scalar_tower K L T] [finite_dimensional K L] [finite_dimensional L T] (x : T) : trace K L (trace L T x) = trace K T x := trace_trace_of_basis (basis.of_vector_space K L) (basis.of_vector_space L T) x @[simp] lemma trace_comp_trace [algebra K T] [algebra L T] [is_scalar_tower K L T] [finite_dimensional K L] [finite_dimensional L T] : (trace K L).comp ((trace L T).restrict_scalars K) = trace K T := by { ext, rw [linear_map.comp_apply, linear_map.restrict_scalars_apply, trace_trace] } section trace_form variables (R S) /-- The `trace_form` maps `x y : S` to the trace of `x * y`. It is a symmetric bilinear form and is nondegenerate if the extension is separable. -/ noncomputable def trace_form : bilin_form R S := (linear_map.compr₂ (lmul R S).to_linear_map (trace R S)).to_bilin variables {S} -- This is a nicer lemma than the one produced by `@[simps] def trace_form`. @[simp] lemma trace_form_apply (x y : S) : trace_form R S x y = trace R S (x * y) := rfl lemma trace_form_is_symm : (trace_form R S).is_symm := λ x y, congr_arg (trace R S) (mul_comm _ _) lemma trace_form_to_matrix [decidable_eq ι] (i j) : bilin_form.to_matrix b (trace_form R S) i j = trace R S (b i * b j) := by rw [bilin_form.to_matrix_apply, trace_form_apply] lemma trace_form_to_matrix_power_basis (h : power_basis R S) : bilin_form.to_matrix h.basis (trace_form R S) = of (λ i j, trace R S (h.gen ^ (↑i + ↑j : ℕ))) := by { ext, rw [trace_form_to_matrix, of_apply, pow_add, h.basis_eq_pow, h.basis_eq_pow] } end trace_form end algebra section eq_sum_roots open algebra polynomial variables {F : Type*} [field F] variables [algebra K S] [algebra K F] /-- Given `pb : power_basis K S`, the trace of `pb.gen` is `-(minpoly K pb.gen).next_coeff`. -/ lemma power_basis.trace_gen_eq_next_coeff_minpoly [nontrivial S] (pb : power_basis K S) : algebra.trace K S pb.gen = -(minpoly K pb.gen).next_coeff := begin have d_pos : 0 < pb.dim := power_basis.dim_pos pb, have d_pos' : 0 < (minpoly K pb.gen).nat_degree, { simpa }, haveI : nonempty (fin pb.dim) := ⟨⟨0, d_pos⟩⟩, rw [trace_eq_matrix_trace pb.basis, trace_eq_neg_charpoly_coeff, charpoly_left_mul_matrix, ← pb.nat_degree_minpoly, fintype.card_fin, ← next_coeff_of_pos_nat_degree _ d_pos'] end /-- Given `pb : power_basis K S`, then the trace of `pb.gen` is `((minpoly K pb.gen).map (algebra_map K F)).roots.sum`. -/ lemma power_basis.trace_gen_eq_sum_roots [nontrivial S] (pb : power_basis K S) (hf : (minpoly K pb.gen).splits (algebra_map K F)) : algebra_map K F (trace K S pb.gen) = ((minpoly K pb.gen).map (algebra_map K F)).roots.sum := begin rw [power_basis.trace_gen_eq_next_coeff_minpoly, ring_hom.map_neg, ← next_coeff_map (algebra_map K F).injective, sum_roots_eq_next_coeff_of_monic_of_split ((minpoly.monic (power_basis.is_integral_gen _)).map _) ((splits_id_iff_splits _).2 hf), neg_neg] end namespace intermediate_field.adjoin_simple open intermediate_field lemma trace_gen_eq_zero {x : L} (hx : ¬ is_integral K x) : algebra.trace K K⟮x⟯ (adjoin_simple.gen K x) = 0 := begin rw [trace_eq_zero_of_not_exists_basis, linear_map.zero_apply], contrapose! hx, obtain ⟨s, ⟨b⟩⟩ := hx, refine is_integral_of_mem_of_fg (K⟮x⟯).to_subalgebra _ x _, { exact (submodule.fg_iff_finite_dimensional _).mpr (finite_dimensional.of_fintype_basis b) }, { exact subset_adjoin K _ (set.mem_singleton x) } end lemma trace_gen_eq_sum_roots (x : L) (hf : (minpoly K x).splits (algebra_map K F)) : algebra_map K F (trace K K⟮x⟯ (adjoin_simple.gen K x)) = ((minpoly K x).map (algebra_map K F)).roots.sum := begin have injKxL := (algebra_map K⟮x⟯ L).injective, by_cases hx : is_integral K x, swap, { simp [minpoly.eq_zero hx, trace_gen_eq_zero hx], }, have hx' : is_integral K (adjoin_simple.gen K x), { rwa [← is_integral_algebra_map_iff injKxL, adjoin_simple.algebra_map_gen], apply_instance }, rw [← adjoin.power_basis_gen hx, (adjoin.power_basis hx).trace_gen_eq_sum_roots]; rw [adjoin.power_basis_gen hx, minpoly.eq_of_algebra_map_eq injKxL hx']; try { simp only [adjoin_simple.algebra_map_gen _ _] }, exact hf end end intermediate_field.adjoin_simple open intermediate_field variables (K) lemma trace_eq_trace_adjoin [finite_dimensional K L] (x : L) : algebra.trace K L x = finrank K⟮x⟯ L • trace K K⟮x⟯ (adjoin_simple.gen K x) := begin rw ← @trace_trace _ _ K K⟮x⟯ _ _ _ _ _ _ _ _ x, conv in x { rw ← intermediate_field.adjoin_simple.algebra_map_gen K x }, rw [trace_algebra_map, linear_map.map_smul_of_tower], end variables {K} lemma trace_eq_sum_roots [finite_dimensional K L] {x : L} (hF : (minpoly K x).splits (algebra_map K F)) : algebra_map K F (algebra.trace K L x) = finrank K⟮x⟯ L • ((minpoly K x).map (algebra_map K _)).roots.sum := by rw [trace_eq_trace_adjoin K x, algebra.smul_def, ring_hom.map_mul, ← algebra.smul_def, intermediate_field.adjoin_simple.trace_gen_eq_sum_roots _ hF, is_scalar_tower.algebra_map_smul] end eq_sum_roots variables {F : Type*} [field F] variables [algebra R L] [algebra L F] [algebra R F] [is_scalar_tower R L F] open polynomial lemma algebra.is_integral_trace [finite_dimensional L F] {x : F} (hx : _root_.is_integral R x) : _root_.is_integral R (algebra.trace L F x) := begin have hx' : _root_.is_integral L x := is_integral_of_is_scalar_tower _ hx, rw [← is_integral_algebra_map_iff (algebra_map L (algebraic_closure F)).injective, trace_eq_sum_roots], { refine (is_integral.multiset_sum _).nsmul _, intros y hy, rw mem_roots_map (minpoly.ne_zero hx') at hy, use [minpoly R x, minpoly.monic hx], rw ← aeval_def at ⊢ hy, exact minpoly.aeval_of_is_scalar_tower R x y hy }, { apply is_alg_closed.splits_codomain }, { apply_instance } end section eq_sum_embeddings variables [algebra K F] [is_scalar_tower K L F] open algebra intermediate_field variables (F) (E : Type*) [field E] [algebra K E] lemma trace_eq_sum_embeddings_gen (pb : power_basis K L) (hE : (minpoly K pb.gen).splits (algebra_map K E)) (hfx : (minpoly K pb.gen).separable) : algebra_map K E (algebra.trace K L pb.gen) = (@@finset.univ (power_basis.alg_hom.fintype pb)).sum (λ σ, σ pb.gen) := begin letI := classical.dec_eq E, rw [pb.trace_gen_eq_sum_roots hE, fintype.sum_equiv pb.lift_equiv', finset.sum_mem_multiset, finset.sum_eq_multiset_sum, multiset.to_finset_val, multiset.dedup_eq_self.mpr _, multiset.map_id], { exact nodup_roots ((separable_map _).mpr hfx) }, { intro x, refl }, { intro σ, rw [power_basis.lift_equiv'_apply_coe, id.def] } end variables [is_alg_closed E] lemma sum_embeddings_eq_finrank_mul [finite_dimensional K F] [is_separable K F] (pb : power_basis K L) : ∑ σ : F →ₐ[K] E, σ (algebra_map L F pb.gen) = finrank L F • (@@finset.univ (power_basis.alg_hom.fintype pb)).sum (λ σ : L →ₐ[K] E, σ pb.gen) := begin haveI : finite_dimensional L F := finite_dimensional.right K L F, haveI : is_separable L F := is_separable_tower_top_of_is_separable K L F, letI : fintype (L →ₐ[K] E) := power_basis.alg_hom.fintype pb, letI : ∀ (f : L →ₐ[K] E), fintype (@@alg_hom L F E _ _ _ _ f.to_ring_hom.to_algebra) := _, -- will be solved by unification rw [fintype.sum_equiv alg_hom_equiv_sigma (λ (σ : F →ₐ[K] E), _) (λ σ, σ.1 pb.gen), ← finset.univ_sigma_univ, finset.sum_sigma, ← finset.sum_nsmul], refine finset.sum_congr rfl (λ σ _, _), { letI : algebra L E := σ.to_ring_hom.to_algebra, simp only [finset.sum_const, finset.card_univ], rw alg_hom.card L F E }, { intros σ, simp only [alg_hom_equiv_sigma, equiv.coe_fn_mk, alg_hom.restrict_domain, alg_hom.comp_apply, is_scalar_tower.coe_to_alg_hom'] } end lemma trace_eq_sum_embeddings [finite_dimensional K L] [is_separable K L] {x : L} : algebra_map K E (algebra.trace K L x) = ∑ σ : L →ₐ[K] E, σ x := begin have hx := is_separable.is_integral K x, rw [trace_eq_trace_adjoin K x, algebra.smul_def, ring_hom.map_mul, ← adjoin.power_basis_gen hx, trace_eq_sum_embeddings_gen E (adjoin.power_basis hx) (is_alg_closed.splits_codomain _), ← algebra.smul_def, algebra_map_smul], { exact (sum_embeddings_eq_finrank_mul L E (adjoin.power_basis hx)).symm }, { haveI := is_separable_tower_bot_of_is_separable K K⟮x⟯ L, exact is_separable.separable K _ } end lemma trace_eq_sum_automorphisms (x : L) [finite_dimensional K L] [is_galois K L] : algebra_map K L (algebra.trace K L x) = ∑ (σ : L ≃ₐ[K] L), σ x := begin apply no_zero_smul_divisors.algebra_map_injective L (algebraic_closure L), rw map_sum (algebra_map L (algebraic_closure L)), rw ← fintype.sum_equiv (normal.alg_hom_equiv_aut K (algebraic_closure L) L), { rw ←trace_eq_sum_embeddings (algebraic_closure L), { simp only [algebra_map_eq_smul_one, smul_one_smul] }, { exact is_galois.to_is_separable } }, { intro σ, simp only [normal.alg_hom_equiv_aut, alg_hom.restrict_normal', equiv.coe_fn_mk, alg_equiv.coe_of_bijective, alg_hom.restrict_normal_commutes, id.map_eq_id, ring_hom.id_apply] }, end end eq_sum_embeddings section det_ne_zero namespace algebra variables (A : Type u) {B : Type v} (C : Type z) variables [comm_ring A] [comm_ring B] [algebra A B] [comm_ring C] [algebra A C] open finset /-- Given an `A`-algebra `B` and `b`, an `κ`-indexed family of elements of `B`, we define `trace_matrix A b` as the matrix whose `(i j)`-th element is the trace of `b i * b j`. -/ @[simp] noncomputable def trace_matrix (b : κ → B) : matrix κ κ A | i j := trace_form A B (b i) (b j) lemma trace_matrix_def (b : κ → B) : trace_matrix A b = of (λ i j, trace_form A B (b i) (b j)) := rfl lemma trace_matrix_reindex {κ' : Type*} (b : basis κ A B) (f : κ ≃ κ') : trace_matrix A (b.reindex f) = reindex f f (trace_matrix A b) := by {ext x y, simp} variables {A} lemma trace_matrix_of_matrix_vec_mul [fintype κ] (b : κ → B) (P : matrix κ κ A) : trace_matrix A ((P.map (algebra_map A B)).vec_mul b) = Pᵀ ⬝ (trace_matrix A b) ⬝ P := begin ext α β, rw [trace_matrix, vec_mul, dot_product, vec_mul, dot_product, matrix.mul_apply, bilin_form.sum_left, fintype.sum_congr _ _ (λ (i : κ), @bilin_form.sum_right _ _ _ _ _ _ _ _ (b i * P.map (algebra_map A B) i α) (λ (y : κ), b y * P.map (algebra_map A B) y β)), sum_comm], congr, ext x, rw [matrix.mul_apply, sum_mul], congr, ext y, rw [map_apply, trace_form_apply, mul_comm (b y), ← smul_def], simp only [id.smul_eq_mul, ring_hom.id_apply, map_apply, transpose_apply, linear_map.map_smulₛₗ, trace_form_apply, algebra.smul_mul_assoc], rw [mul_comm (b x), ← smul_def], ring_nf, simp [mul_comm], end lemma trace_matrix_of_matrix_mul_vec [fintype κ] (b : κ → B) (P : matrix κ κ A) : trace_matrix A ((P.map (algebra_map A B)).mul_vec b) = P ⬝ (trace_matrix A b) ⬝ Pᵀ := begin refine add_equiv.injective (transpose_add_equiv _ _ _) _, rw [transpose_add_equiv_apply, transpose_add_equiv_apply, ← vec_mul_transpose, ← transpose_map, trace_matrix_of_matrix_vec_mul, transpose_transpose, transpose_mul, transpose_transpose, transpose_mul] end lemma trace_matrix_of_basis [fintype κ] [decidable_eq κ] (b : basis κ A B) : trace_matrix A b = bilin_form.to_matrix b (trace_form A B) := begin ext i j, rw [trace_matrix, trace_form_apply, trace_form_to_matrix] end lemma trace_matrix_of_basis_mul_vec (b : basis ι A B) (z : B) : (trace_matrix A b).mul_vec (b.equiv_fun z) = (λ i, trace A B (z * (b i))) := begin ext i, rw [← col_apply ((trace_matrix A b).mul_vec (b.equiv_fun z)) i unit.star, col_mul_vec, matrix.mul_apply, trace_matrix_def], simp only [col_apply, trace_form_apply], conv_lhs { congr, skip, funext, rw [mul_comm _ (b.equiv_fun z _), ← smul_eq_mul, of_apply, ← linear_map.map_smul] }, rw [← linear_map.map_sum], congr, conv_lhs { congr, skip, funext, rw [← mul_smul_comm] }, rw [← finset.mul_sum, mul_comm z], congr, rw [b.sum_equiv_fun ] end variable (A) /-- `embeddings_matrix A C b : matrix κ (B →ₐ[A] C) C` is the matrix whose `(i, σ)` coefficient is `σ (b i)`. It is mostly useful for fields when `fintype.card κ = finrank A B` and `C` is algebraically closed. -/ @[simp] def embeddings_matrix (b : κ → B) : matrix κ (B →ₐ[A] C) C | i σ := σ (b i) /-- `embeddings_matrix_reindex A C b e : matrix κ κ C` is the matrix whose `(i, j)` coefficient is `σⱼ (b i)`, where `σⱼ : B →ₐ[A] C` is the embedding corresponding to `j : κ` given by a bijection `e : κ ≃ (B →ₐ[A] C)`. It is mostly useful for fields and `C` is algebraically closed. In this case, in presence of `h : fintype.card κ = finrank A B`, one can take `e := equiv_of_card_eq ((alg_hom.card A B C).trans h.symm)`. -/ def embeddings_matrix_reindex (b : κ → B) (e : κ ≃ (B →ₐ[A] C)) := reindex (equiv.refl κ) e.symm (embeddings_matrix A C b) variable {A} lemma embeddings_matrix_reindex_eq_vandermonde (pb : power_basis A B) (e : fin pb.dim ≃ (B →ₐ[A] C)) : embeddings_matrix_reindex A C pb.basis e = (vandermonde (λ i, e i pb.gen))ᵀ := by { ext i j, simp [embeddings_matrix_reindex, embeddings_matrix] } section field variables (K) {L} (E : Type z) [field E] variables [algebra K E] variables [module.finite K L] [is_separable K L] [is_alg_closed E] variables (b : κ → L) (pb : power_basis K L) lemma trace_matrix_eq_embeddings_matrix_mul_trans : (trace_matrix K b).map (algebra_map K E) = (embeddings_matrix K E b) ⬝ (embeddings_matrix K E b)ᵀ := by { ext i j, simp [trace_eq_sum_embeddings, embeddings_matrix, matrix.mul_apply] } lemma trace_matrix_eq_embeddings_matrix_reindex_mul_trans [fintype κ] (e : κ ≃ (L →ₐ[K] E)) : (trace_matrix K b).map (algebra_map K E) = (embeddings_matrix_reindex K E b e) ⬝ (embeddings_matrix_reindex K E b e)ᵀ := by rw [trace_matrix_eq_embeddings_matrix_mul_trans, embeddings_matrix_reindex, reindex_apply, transpose_submatrix, ← submatrix_mul_transpose_submatrix, ← equiv.coe_refl, equiv.refl_symm] end field end algebra open algebra variables (pb : power_basis K L) lemma det_trace_matrix_ne_zero' [is_separable K L] : det (trace_matrix K pb.basis) ≠ 0 := begin suffices : algebra_map K (algebraic_closure L) (det (trace_matrix K pb.basis)) ≠ 0, { refine mt (λ ht, _) this, rw [ht, ring_hom.map_zero] }, haveI : finite_dimensional K L := pb.finite_dimensional, let e : fin pb.dim ≃ (L →ₐ[K] algebraic_closure L) := (fintype.equiv_fin_of_card_eq _).symm, rw [ring_hom.map_det, ring_hom.map_matrix_apply, trace_matrix_eq_embeddings_matrix_reindex_mul_trans K _ _ e, embeddings_matrix_reindex_eq_vandermonde, det_mul, det_transpose], refine mt mul_self_eq_zero.mp _, { simp only [det_vandermonde, finset.prod_eq_zero_iff, not_exists, sub_eq_zero], intros i _ j hij h, exact (finset.mem_Ioi.mp hij).ne' (e.injective $ pb.alg_hom_ext h) }, { rw [alg_hom.card, pb.finrank] } end lemma det_trace_form_ne_zero [is_separable K L] [decidable_eq ι] (b : basis ι K L) : det (bilin_form.to_matrix b (trace_form K L)) ≠ 0 := begin haveI : finite_dimensional K L := finite_dimensional.of_fintype_basis b, let pb : power_basis K L := field.power_basis_of_finite_of_separable _ _, rw [← bilin_form.to_matrix_mul_basis_to_matrix pb.basis b, ← det_comm' (pb.basis.to_matrix_mul_to_matrix_flip b) _, ← matrix.mul_assoc, det_mul], swap, { apply basis.to_matrix_mul_to_matrix_flip }, refine mul_ne_zero (is_unit_of_mul_eq_one _ ((b.to_matrix pb.basis)ᵀ ⬝ b.to_matrix pb.basis).det _).ne_zero _, { calc (pb.basis.to_matrix b ⬝ (pb.basis.to_matrix b)ᵀ).det * ((b.to_matrix pb.basis)ᵀ ⬝ b.to_matrix pb.basis).det = (pb.basis.to_matrix b ⬝ (b.to_matrix pb.basis ⬝ pb.basis.to_matrix b)ᵀ ⬝ b.to_matrix pb.basis).det : by simp only [← det_mul, matrix.mul_assoc, matrix.transpose_mul] ... = 1 : by simp only [basis.to_matrix_mul_to_matrix_flip, matrix.transpose_one, matrix.mul_one, matrix.det_one] }, simpa only [trace_matrix_of_basis] using det_trace_matrix_ne_zero' pb end variables (K L) theorem trace_form_nondegenerate [finite_dimensional K L] [is_separable K L] : (trace_form K L).nondegenerate := bilin_form.nondegenerate_of_det_ne_zero (trace_form K L) _ (det_trace_form_ne_zero (finite_dimensional.fin_basis K L)) end det_ne_zero
f52339cdbd0d514a2b3abbf4c48f506149b2a6d3
4727251e0cd73359b15b664c3170e5d754078599
/src/group_theory/abelianization.lean
7bf9be76b99aebee10d21b8724b279618ce28eb4
[ "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
7,202
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Michael Howes -/ import group_theory.commutator import group_theory.quotient_group /-! # The abelianization of a group This file defines the commutator and the abelianization of a group. It furthermore prepares for the result that the abelianization is left adjoint to the forgetful functor from abelian groups to groups, which can be found in `algebra/category/Group/adjunctions`. ## Main definitions * `commutator`: defines the commutator of a group `G` as a subgroup of `G`. * `abelianization`: defines the abelianization of a group `G` as the quotient of a group by its commutator subgroup. * `abelianization.map`: lifts a group homomorphism to a homomorphism between the abelianizations * `mul_equiv.abelianization_congr`: Equivalent groups have equivalent abelianizations -/ universes u v w -- Let G be a group. variables (G : Type u) [group G] /-- The commutator subgroup of a group G is the normal subgroup generated by the commutators [p,q]=`p*q*p⁻¹*q⁻¹`. -/ @[derive subgroup.normal] def commutator : subgroup G := ⁅(⊤ : subgroup G), ⊤⁆ lemma commutator_def : commutator G = ⁅(⊤ : subgroup G), ⊤⁆ := rfl lemma commutator_eq_closure : commutator G = subgroup.closure {g | ∃ g₁ g₂ : G, ⁅g₁, g₂⁆ = g} := by simp_rw [commutator, subgroup.commutator_def, subgroup.mem_top, exists_true_left] lemma commutator_eq_normal_closure : commutator G = subgroup.normal_closure {g | ∃ g₁ g₂ : G, ⁅g₁, g₂⁆ = g} := by simp_rw [commutator, subgroup.commutator_def', subgroup.mem_top, exists_true_left] instance commutator_characteristic : (commutator G).characteristic := subgroup.commutator_characteristic ⊤ ⊤ lemma commutator_centralizer_commutator_le_center : ⁅(commutator G).centralizer, (commutator G).centralizer⁆ ≤ subgroup.center G := begin rw [←subgroup.centralizer_top, ←subgroup.commutator_eq_bot_iff_le_centralizer], suffices : ⁅⁅⊤, (commutator G).centralizer⁆, (commutator G).centralizer⁆ = ⊥, { refine subgroup.commutator_commutator_eq_bot_of_rotate _ this, rwa subgroup.commutator_comm (commutator G).centralizer }, rw [subgroup.commutator_comm, subgroup.commutator_eq_bot_iff_le_centralizer], exact set.centralizer_subset (subgroup.commutator_mono le_top le_top), end /-- The abelianization of G is the quotient of G by its commutator subgroup. -/ def abelianization : Type u := G ⧸ (commutator G) namespace abelianization local attribute [instance] quotient_group.left_rel instance : comm_group (abelianization G) := { mul_comm := λ x y, quotient.induction_on₂' x y $ λ a b, quotient.sound' $ subgroup.subset_closure ⟨b⁻¹, subgroup.mem_top b⁻¹, a⁻¹, subgroup.mem_top a⁻¹, by group⟩, .. quotient_group.quotient.group _ } instance : inhabited (abelianization G) := ⟨1⟩ instance [fintype G] [decidable_pred (∈ commutator G)] : fintype (abelianization G) := quotient_group.fintype (commutator G) variable {G} /-- `of` is the canonical projection from G to its abelianization. -/ def of : G →* abelianization G := { to_fun := quotient_group.mk, map_one' := rfl, map_mul' := λ x y, rfl } @[simp] lemma mk_eq_of (a : G) : quot.mk _ a = of a := rfl section lift -- So far we have built Gᵃᵇ and proved it's an abelian group. -- Furthremore we defined the canonical projection `of : G → Gᵃᵇ` -- Let `A` be an abelian group and let `f` be a group homomorphism from `G` to `A`. variables {A : Type v} [comm_group A] (f : G →* A) lemma commutator_subset_ker : commutator G ≤ f.ker := begin rw [commutator_eq_closure, subgroup.closure_le], rintros x ⟨p, q, rfl⟩, simp [monoid_hom.mem_ker, mul_right_comm (f p) (f q), commutator_element_def], end /-- If `f : G → A` is a group homomorphism to an abelian group, then `lift f` is the unique map from the abelianization of a `G` to `A` that factors through `f`. -/ def lift : (G →* A) ≃ (abelianization G →* A) := { to_fun := λ f, quotient_group.lift _ f (λ x h, f.mem_ker.2 $ commutator_subset_ker _ h), inv_fun := λ F, F.comp of, left_inv := λ f, monoid_hom.ext $ λ x, rfl, right_inv := λ F, monoid_hom.ext $ λ x, quotient_group.induction_on x $ λ z, rfl } @[simp] lemma lift.of (x : G) : lift f (of x) = f x := rfl theorem lift.unique (φ : abelianization G →* A) -- hφ : φ agrees with f on the image of G in Gᵃᵇ (hφ : ∀ (x : G), φ (of x) = f x) {x : abelianization G} : φ x = lift f x := quotient_group.induction_on x hφ @[simp] lemma lift_of : lift of = monoid_hom.id (abelianization G) := lift.apply_symm_apply $ monoid_hom.id _ end lift variables {A : Type v} [monoid A] /-- See note [partially-applied ext lemmas]. -/ @[ext] theorem hom_ext (φ ψ : abelianization G →* A) (h : φ.comp of = ψ.comp of) : φ = ψ := monoid_hom.ext $ λ x, quotient_group.induction_on x $ monoid_hom.congr_fun h section map variables {H : Type v} [group H] (f : G →* H) /-- The map operation of the `abelianization` functor -/ def map : abelianization G →* abelianization H := lift (of.comp f) @[simp] lemma map_of (x : G) : map f (of x) = of (f x) := rfl @[simp] lemma map_id : map (monoid_hom.id G) = monoid_hom.id (abelianization G) := hom_ext _ _ rfl @[simp] lemma map_comp {I : Type w} [group I] (g : H →* I) : (map g).comp (map f) = map (g.comp f) := hom_ext _ _ rfl @[simp] lemma map_map_apply {I : Type w} [group I] {g : H →* I} {x : abelianization G}: map g (map f x) = map (g.comp f) x := monoid_hom.congr_fun (map_comp _ _) x end map end abelianization section abelianization_congr variables {G} {H : Type v} [group H] (e : G ≃* H) /-- Equivalent groups have equivalent abelianizations -/ def mul_equiv.abelianization_congr : abelianization G ≃* abelianization H := { to_fun := abelianization.map e.to_monoid_hom, inv_fun := abelianization.map e.symm.to_monoid_hom, left_inv := by { rintros ⟨a⟩, simp }, right_inv := by { rintros ⟨a⟩, simp }, map_mul' := monoid_hom.map_mul _ } @[simp] lemma abelianization_congr_of (x : G) : (e.abelianization_congr) (abelianization.of x) = abelianization.of (e x) := rfl @[simp] lemma abelianization_congr_refl : (mul_equiv.refl G).abelianization_congr = mul_equiv.refl (abelianization G) := mul_equiv.to_monoid_hom_injective abelianization.lift_of @[simp] lemma abelianization_congr_symm : e.abelianization_congr.symm = e.symm.abelianization_congr := rfl @[simp] lemma abelianization_congr_trans {I : Type v} [group I] (e₂ : H ≃* I) : e.abelianization_congr.trans e₂.abelianization_congr = (e.trans e₂).abelianization_congr := mul_equiv.to_monoid_hom_injective (abelianization.hom_ext _ _ rfl) end abelianization_congr /-- An Abelian group is equivalent to its own abelianization. -/ @[simps] def abelianization.equiv_of_comm {H : Type*} [comm_group H] : H ≃* abelianization H := { to_fun := abelianization.of, inv_fun := abelianization.lift (monoid_hom.id H), left_inv := λ a, rfl, right_inv := by { rintros ⟨a⟩, refl, }, .. abelianization.of }
3d0663007bbacb0c1947731a842a53e948eed656
07f5f86b00fed90a419ccda4298d8b795a68f657
/library/init/algebra/field.lean
716775eacb2c73e296f444efb4e40761c3b4a7fb
[ "Apache-2.0" ]
permissive
VBaratham/lean
8ec5c3167b4835cfbcd7f25e2173d61ad9416b3a
450ca5834c1c35318e4b47d553bb9820c1b3eee7
refs/heads/master
1,629,649,471,814
1,512,060,373,000
1,512,060,469,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
18,493
lean
/- Copyright (c) 2014 Robert Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Lewis, Leonardo de Moura Structures with multiplicative and additive components, including division rings and fields. The development is modeled after Isabelle's library. -/ prelude import init.algebra.ring universe u /- Make sure instances defined in this file have lower priority than the ones defined for concrete structures -/ set_option default_priority 100 set_option old_structure_cmd true class division_ring (α : Type u) extends ring α, has_inv α, zero_ne_one_class α := (mul_inv_cancel : ∀ {a : α}, a ≠ 0 → a * a⁻¹ = 1) (inv_mul_cancel : ∀ {a : α}, a ≠ 0 → a⁻¹ * a = 1) variable {α : Type u} section division_ring variables [division_ring α] protected definition algebra.div (a b : α) : α := a * b⁻¹ instance division_ring_has_div [division_ring α] : has_div α := ⟨algebra.div⟩ lemma division_def (a b : α) : a / b = a * b⁻¹ := rfl @[simp] lemma mul_inv_cancel {a : α} (h : a ≠ 0) : a * a⁻¹ = 1 := division_ring.mul_inv_cancel h @[simp] lemma inv_mul_cancel {a : α} (h : a ≠ 0) : a⁻¹ * a = 1 := division_ring.inv_mul_cancel h @[simp] lemma one_div_eq_inv (a : α) : 1 / a = a⁻¹ := one_mul a⁻¹ lemma inv_eq_one_div (a : α) : a⁻¹ = 1 / a := by simp local attribute [simp] division_def mul_comm mul_assoc mul_left_comm mul_inv_cancel inv_mul_cancel lemma div_eq_mul_one_div (a b : α) : a / b = a * (1 / b) := by simp lemma mul_one_div_cancel {a : α} (h : a ≠ 0) : a * (1 / a) = 1 := by simp [h] lemma one_div_mul_cancel {a : α} (h : a ≠ 0) : (1 / a) * a = 1 := by simp [h] lemma div_self {a : α} (h : a ≠ 0) : a / a = 1 := by simp [h] lemma one_div_one : 1 / 1 = (1:α) := div_self (ne.symm zero_ne_one) lemma mul_div_assoc (a b c : α) : (a * b) / c = a * (b / c) := by simp lemma one_div_ne_zero {a : α} (h : a ≠ 0) : 1 / a ≠ 0 := assume : 1 / a = 0, have 0 = (1:α), from eq.symm (by rw [← mul_one_div_cancel h, this, mul_zero]), absurd this zero_ne_one lemma inv_ne_zero {a : α} (h : a ≠ 0) : a⁻¹ ≠ 0 := by rw inv_eq_one_div; exact one_div_ne_zero h lemma one_inv_eq : 1⁻¹ = (1:α) := calc 1⁻¹ = 1 * 1⁻¹ : by rw [one_mul] ... = (1:α) : by simp local attribute [simp] one_inv_eq lemma div_one (a : α) : a / 1 = a := by simp lemma zero_div (a : α) : 0 / a = 0 := by simp -- note: integral domain has a "mul_ne_zero". α commutative division ring is an integral -- domain, but let's not define that class for now. lemma division_ring.mul_ne_zero {a b : α} (ha : a ≠ 0) (hb : b ≠ 0) : a * b ≠ 0 := assume : a * b = 0, have a * 1 = 0, by rw [← mul_one_div_cancel hb, ← mul_assoc, this, zero_mul], have a = 0, by rwa mul_one at this, absurd this ha lemma mul_ne_zero_comm {a b : α} (h : a * b ≠ 0) : b * a ≠ 0 := have h₁ : a ≠ 0, from ne_zero_of_mul_ne_zero_right h, have h₂ : b ≠ 0, from ne_zero_of_mul_ne_zero_left h, division_ring.mul_ne_zero h₂ h₁ lemma eq_one_div_of_mul_eq_one {a b : α} (h : a * b = 1) : b = 1 / a := have a ≠ 0, from assume : a = 0, have 0 = (1:α), by rwa [this, zero_mul] at h, absurd this zero_ne_one, have b = (1 / a) * a * b, by rw [one_div_mul_cancel this, one_mul], show b = 1 / a, by rwa [mul_assoc, h, mul_one] at this lemma eq_one_div_of_mul_eq_one_left {a b : α} (h : b * a = 1) : b = 1 / a := have a ≠ 0, from assume : a = 0, have 0 = (1:α), by rwa [this, mul_zero] at h, absurd this zero_ne_one, by rw [← h, mul_div_assoc, div_self this, mul_one] lemma division_ring.one_div_mul_one_div {a b : α} (ha : a ≠ 0) (hb : b ≠ 0) : (1 / a) * (1 / b) = 1 / (b * a) := have (b * a) * ((1 / a) * (1 / b)) = 1, by rw [mul_assoc, ← mul_assoc a, mul_one_div_cancel ha, one_mul, mul_one_div_cancel hb], eq_one_div_of_mul_eq_one this lemma one_div_neg_one_eq_neg_one : (1:α) / (-1) = -1 := have (-1) * (-1) = (1:α), by rw [neg_mul_neg, one_mul], eq.symm (eq_one_div_of_mul_eq_one this) lemma division_ring.one_div_neg_eq_neg_one_div {a : α} (h : a ≠ 0) : 1 / (- a) = - (1 / a) := have -1 ≠ (0:α), from (assume : -1 = 0, absurd (eq.symm (calc 1 = -(-1) : (neg_neg (1:α)).symm ... = -0 : by rw this ... = (0:α) : neg_zero)) zero_ne_one), calc 1 / (- a) = 1 / ((-1) * a) : by rw neg_eq_neg_one_mul ... = (1 / a) * (1 / (- 1)) : by rw (division_ring.one_div_mul_one_div h this) ... = (1 / a) * (-1) : by rw one_div_neg_one_eq_neg_one ... = - (1 / a) : by rw [mul_neg_eq_neg_mul_symm, mul_one] lemma div_neg_eq_neg_div {a : α} (b : α) (ha : a ≠ 0) : b / (- a) = - (b / a) := calc b / (- a) = b * (1 / (- a)) : by rw [← inv_eq_one_div, division_def] ... = b * -(1 / a) : by rw (division_ring.one_div_neg_eq_neg_one_div ha) ... = -(b * (1 / a)) : by rw neg_mul_eq_mul_neg ... = - (b * a⁻¹) : by rw inv_eq_one_div lemma neg_div (a b : α) : (-b) / a = - (b / a) := by rw [neg_eq_neg_one_mul, mul_div_assoc, ← neg_eq_neg_one_mul] lemma division_ring.neg_div_neg_eq (a : α) {b : α} (hb : b ≠ 0) : (-a) / (-b) = a / b := by rw [(div_neg_eq_neg_div _ hb), neg_div, neg_neg] lemma division_ring.one_div_one_div {a : α} (h : a ≠ 0) : 1 / (1 / a) = a := eq.symm (eq_one_div_of_mul_eq_one_left (mul_one_div_cancel h)) lemma division_ring.inv_inv {a : α} (h : a ≠ 0) : a⁻¹⁻¹ = a := by rw [inv_eq_one_div, inv_eq_one_div, division_ring.one_div_one_div h] lemma division_ring.eq_of_one_div_eq_one_div {a b : α} (ha : a ≠ 0) (hb : b ≠ 0) (h : 1 / a = 1 / b) : a = b := by rw [← division_ring.one_div_one_div ha, h, (division_ring.one_div_one_div hb)] lemma mul_inv_eq {a b : α} (ha : a ≠ 0) (hb : b ≠ 0) : (b * a)⁻¹ = a⁻¹ * b⁻¹ := eq.symm $ calc a⁻¹ * b⁻¹ = (1 / a) * (1 / b) : by simp ... = (1 / (b * a)) : division_ring.one_div_mul_one_div ha hb ... = (b * a)⁻¹ : by simp lemma division_ring.one_div_div {a b : α} (ha : a ≠ 0) (hb : b ≠ 0) : 1 / (a / b) = b / a := by rw [one_div_eq_inv, division_def, mul_inv_eq (inv_ne_zero hb) ha, division_ring.inv_inv hb, division_def] lemma mul_div_cancel (a : α) {b : α} (hb : b ≠ 0) : a * b / b = a := by simp [hb] lemma div_mul_cancel (a : α) {b : α} (hb : b ≠ 0) : a / b * b = a := by simp [hb] lemma div_add_div_same (a b c : α) : a / c + b / c = (a + b) / c := eq.symm $ right_distrib a b (c⁻¹) lemma div_sub_div_same (a b c : α) : (a / c) - (b / c) = (a - b) / c := by rw [sub_eq_add_neg, ← neg_div, div_add_div_same, sub_eq_add_neg] lemma one_div_mul_add_mul_one_div_eq_one_div_add_one_div {a b : α} (ha : a ≠ 0) (hb : b ≠ 0) : (1 / a) * (a + b) * (1 / b) = 1 / a + 1 / b := by rw [(left_distrib (1 / a)), (one_div_mul_cancel ha), right_distrib, one_mul, mul_assoc, (mul_one_div_cancel hb), mul_one, add_comm] lemma one_div_mul_sub_mul_one_div_eq_one_div_add_one_div {a b : α} (ha : a ≠ 0) (hb : b ≠ 0) : (1 / a) * (b - a) * (1 / b) = 1 / a - 1 / b := by rw [(mul_sub_left_distrib (1 / a)), (one_div_mul_cancel ha), mul_sub_right_distrib, one_mul, mul_assoc, (mul_one_div_cancel hb), mul_one] lemma div_eq_one_iff_eq (a : α) {b : α} (hb : b ≠ 0) : a / b = 1 ↔ a = b := iff.intro (assume : a / b = 1, calc a = a / b * b : by simp [hb] ... = 1 * b : by rw this ... = b : by simp) (assume : a = b, by simp [this, hb]) lemma eq_of_div_eq_one (a : α) {b : α} (Hb : b ≠ 0) : a / b = 1 → a = b := iff.mp $ div_eq_one_iff_eq a Hb lemma eq_div_iff_mul_eq (a b : α) {c : α} (hc : c ≠ 0) : a = b / c ↔ a * c = b := iff.intro (assume : a = b / c, by rw [this, (div_mul_cancel _ hc)]) (assume : a * c = b, by rw [← this, mul_div_cancel _ hc]) lemma eq_div_of_mul_eq (a b : α) {c : α} (hc : c ≠ 0) : a * c = b → a = b / c := iff.mpr $ eq_div_iff_mul_eq a b hc lemma mul_eq_of_eq_div (a b: α) {c : α} (hc : c ≠ 0) : a = b / c → a * c = b := iff.mp $ eq_div_iff_mul_eq a b hc lemma add_div_eq_mul_add_div (a b : α) {c : α} (hc : c ≠ 0) : a + b / c = (a * c + b) / c := have (a + b / c) * c = a * c + b, by rw [right_distrib, (div_mul_cancel _ hc)], (iff.mpr (eq_div_iff_mul_eq _ _ hc)) this lemma mul_mul_div (a : α) {c : α} (hc : c ≠ 0) : a = a * c * (1 / c) := by simp [hc] end division_ring class field (α : Type u) extends division_ring α, comm_ring α section field variable [field α] lemma field.one_div_mul_one_div {a b : α} (ha : a ≠ 0) (hb : b ≠ 0) : (1 / a) * (1 / b) = 1 / (a * b) := by rw [(division_ring.one_div_mul_one_div ha hb), mul_comm b] lemma field.div_mul_right {a b : α} (hb : b ≠ 0) (h : a * b ≠ 0) : a / (a * b) = 1 / b := have a ≠ 0, from ne_zero_of_mul_ne_zero_right h, eq.symm (calc 1 / b = a * ((1 / a) * (1 / b)) : by rw [← mul_assoc, mul_one_div_cancel this, one_mul] ... = a * (1 / (b * a)) : by rw (division_ring.one_div_mul_one_div this hb) ... = a * (a * b)⁻¹ : by rw [inv_eq_one_div, mul_comm a b]) lemma field.div_mul_left {a b : α} (ha : a ≠ 0) (h : a * b ≠ 0) : b / (a * b) = 1 / a := have b * a ≠ 0, from mul_ne_zero_comm h, by rw [mul_comm a, (field.div_mul_right ha this)] lemma mul_div_cancel_left {a : α} (b : α) (ha : a ≠ 0) : a * b / a = b := by rw [mul_comm a, (mul_div_cancel _ ha)] lemma mul_div_cancel' (a : α) {b : α} (hb : b ≠ 0) : b * (a / b) = a := by rw [mul_comm, (div_mul_cancel _ hb)] lemma one_div_add_one_div {a b : α} (ha : a ≠ 0) (hb : b ≠ 0) : 1 / a + 1 / b = (a + b) / (a * b) := have a * b ≠ 0, from (division_ring.mul_ne_zero ha hb), by rw [add_comm, ← field.div_mul_left ha this, ← field.div_mul_right hb this, division_def, division_def, division_def, ← right_distrib] lemma field.div_mul_div (a : α) {b : α} (c : α) {d : α} (hb : b ≠ 0) (hd : d ≠ 0) : (a / b) * (c / d) = (a * c) / (b * d) := begin simp [division_def], rw [mul_inv_eq hd hb, mul_comm d⁻¹] end lemma mul_div_mul_left (a : α) {b c : α} (hb : b ≠ 0) (hc : c ≠ 0) : (c * a) / (c * b) = a / b := by rw [← field.div_mul_div _ _ hc hb, div_self hc, one_mul] lemma mul_div_mul_right (a : α) {b c : α} (hb : b ≠ 0) (hc : c ≠ 0) : (a * c) / (b * c) = a / b := by rw [mul_comm a, mul_comm b, mul_div_mul_left _ hb hc] lemma div_mul_eq_mul_div (a b c : α) : (b / c) * a = (b * a) / c := by simp [division_def] lemma field.div_mul_eq_mul_div_comm (a b : α) {c : α} (hc : c ≠ 0) : (b / c) * a = b * (a / c) := by rw [div_mul_eq_mul_div, ← one_mul c, ← field.div_mul_div _ _ (ne.symm zero_ne_one) hc, div_one, one_mul] lemma div_add_div (a : α) {b : α} (c : α) {d : α} (hb : b ≠ 0) (hd : d ≠ 0) : (a / b) + (c / d) = ((a * d) + (b * c)) / (b * d) := by rw [← mul_div_mul_right _ hb hd, ← mul_div_mul_left _ hd hb, div_add_div_same] lemma div_sub_div (a : α) {b : α} (c : α) {d : α} (hb : b ≠ 0) (hd : d ≠ 0) : (a / b) - (c / d) = ((a * d) - (b * c)) / (b * d) := begin simp [sub_eq_add_neg], rw [neg_eq_neg_one_mul, ← mul_div_assoc, div_add_div _ _ hb hd, ← mul_assoc, mul_comm b, mul_assoc, ← neg_eq_neg_one_mul] end lemma mul_eq_mul_of_div_eq_div (a : α) {b : α} (c : α) {d : α} (hb : b ≠ 0) (hd : d ≠ 0) (h : a / b = c / d) : a * d = c * b := by rw [← mul_one (a*d), mul_assoc, mul_comm d, ← mul_assoc, ← div_self hb, ← field.div_mul_eq_mul_div_comm _ _ hb, h, div_mul_eq_mul_div, div_mul_cancel _ hd] lemma field.div_div_eq_mul_div (a : α) {b c : α} (hb : b ≠ 0) (hc : c ≠ 0) : a / (b / c) = (a * c) / b := by rw [div_eq_mul_one_div, division_ring.one_div_div hb hc, ← mul_div_assoc] lemma field.div_div_eq_div_mul (a : α) {b c : α} (hb : b ≠ 0) (hc : c ≠ 0) : (a / b) / c = a / (b * c) := by rw [div_eq_mul_one_div, field.div_mul_div _ _ hb hc, mul_one] lemma field.div_div_div_div_eq (a : α) {b c d : α} (hb : b ≠ 0) (hc : c ≠ 0) (hd : d ≠ 0) : (a / b) / (c / d) = (a * d) / (b * c) := by rw [field.div_div_eq_mul_div _ hc hd, div_mul_eq_mul_div, field.div_div_eq_div_mul _ hb hc] lemma field.div_mul_eq_div_mul_one_div (a : α) {b c : α} (hb : b ≠ 0) (hc : c ≠ 0) : a / (b * c) = (a / b) * (1 / c) := by rw [← field.div_div_eq_div_mul _ hb hc, ← div_eq_mul_one_div] lemma eq_of_mul_eq_mul_of_nonzero_left {a b c : α} (h : a ≠ 0) (h₂ : a * b = a * c) : b = c := by rw [← one_mul b, ← div_self h, div_mul_eq_mul_div, h₂, mul_div_cancel_left _ h] lemma eq_of_mul_eq_mul_of_nonzero_right {a b c : α} (h : c ≠ 0) (h2 : a * c = b * c) : a = b := by rw [← mul_one a, ← div_self h, ← mul_div_assoc, h2, mul_div_cancel _ h] end field class discrete_field (α : Type u) extends field α := (has_decidable_eq : decidable_eq α) (inv_zero : inv zero = zero) attribute [instance] discrete_field.has_decidable_eq section discrete_field variable [discrete_field α] -- many of the lemmas in discrete_field are the same as lemmas in field or division ring, -- but with fewer hypotheses since 0⁻¹ = 0 and equality is decidable. lemma discrete_field.eq_zero_or_eq_zero_of_mul_eq_zero (a b : α) (h : a * b = 0) : a = 0 ∨ b = 0 := decidable.by_cases (assume : a = 0, or.inl this) (assume : a ≠ 0, or.inr (by rw [← one_mul b, ← inv_mul_cancel this, mul_assoc, h, mul_zero])) instance discrete_field.to_integral_domain [s : discrete_field α] : integral_domain α := { eq_zero_or_eq_zero_of_mul_eq_zero := discrete_field.eq_zero_or_eq_zero_of_mul_eq_zero, ..s } lemma inv_zero : 0⁻¹ = (0:α) := discrete_field.inv_zero α lemma one_div_zero : 1 / 0 = (0:α) := calc 1 / 0 = (1:α) * 0⁻¹ : by rw division_def ... = 1 * 0 : by rw inv_zero ... = (0:α) : by rw mul_zero lemma div_zero (a : α) : a / 0 = 0 := by rw [div_eq_mul_one_div, one_div_zero, mul_zero] lemma ne_zero_of_one_div_ne_zero {a : α} (h : 1 / a ≠ 0) : a ≠ 0 := assume ha : a = 0, begin rw [ha, one_div_zero] at h, contradiction end lemma eq_zero_of_one_div_eq_zero {a : α} (h : 1 / a = 0) : a = 0 := decidable.by_cases (assume ha, ha) (assume ha, false.elim ((one_div_ne_zero ha) h)) lemma one_div_mul_one_div' (a b : α) : (1 / a) * (1 / b) = 1 / (b * a) := decidable.by_cases (assume : a = 0, by rw [this, div_zero, zero_mul, mul_zero, div_zero]) (assume ha : a ≠ 0, decidable.by_cases (assume : b = 0, by rw [this, div_zero, mul_zero, zero_mul, div_zero]) (assume : b ≠ 0, division_ring.one_div_mul_one_div ha this)) lemma one_div_neg_eq_neg_one_div (a : α) : 1 / (- a) = - (1 / a) := decidable.by_cases (assume : a = 0, by rw [this, neg_zero, div_zero, neg_zero]) (assume : a ≠ 0, division_ring.one_div_neg_eq_neg_one_div this) lemma neg_div_neg_eq (a b : α) : (-a) / (-b) = a / b := decidable.by_cases (assume hb : b = 0, by rw [hb, neg_zero, div_zero, div_zero]) (assume hb : b ≠ 0, division_ring.neg_div_neg_eq _ hb) lemma one_div_one_div (a : α) : 1 / (1 / a) = a := decidable.by_cases (assume ha : a = 0, by rw [ha, div_zero, div_zero]) (assume ha : a ≠ 0, division_ring.one_div_one_div ha) lemma eq_of_one_div_eq_one_div {a b : α} (h : 1 / a = 1 / b) : a = b := decidable.by_cases (assume ha : a = 0, have hb : b = 0, from eq_zero_of_one_div_eq_zero (by rw [← h, ha, div_zero]), hb.symm ▸ ha) (assume ha : a ≠ 0, have hb : b ≠ 0, from ne_zero_of_one_div_ne_zero (h ▸ (one_div_ne_zero ha)), division_ring.eq_of_one_div_eq_one_div ha hb h) lemma mul_inv' (a b : α) : (b * a)⁻¹ = a⁻¹ * b⁻¹ := decidable.by_cases (assume ha : a = 0, by rw [ha, mul_zero, inv_zero, zero_mul]) (assume ha : a ≠ 0, decidable.by_cases (assume hb : b = 0, by rw [hb, zero_mul, inv_zero, mul_zero]) (assume hb : b ≠ 0, mul_inv_eq ha hb)) -- the following are specifically for fields lemma one_div_mul_one_div (a b : α) : (1 / a) * (1 / b) = 1 / (a * b) := by rw [one_div_mul_one_div', mul_comm b] lemma div_mul_right {a : α} (b : α) (ha : a ≠ 0) : a / (a * b) = 1 / b := decidable.by_cases (assume hb : b = 0, by rw [hb, mul_zero, div_zero, div_zero]) (assume hb : b ≠ 0, field.div_mul_right hb (mul_ne_zero ha hb)) lemma div_mul_left (a : α) {b : α} (hb : b ≠ 0) : b / (a * b) = 1 / a := by rw [mul_comm a, div_mul_right _ hb] lemma div_mul_div (a b c d : α) : (a / b) * (c / d) = (a * c) / (b * d) := decidable.by_cases (assume hb : b = 0, by rw [hb, div_zero, zero_mul, zero_mul, div_zero]) (assume hb : b ≠ 0, decidable.by_cases (assume hd : d = 0, by rw [hd, div_zero, mul_zero, mul_zero, div_zero]) (assume hd : d ≠ 0, field.div_mul_div _ _ hb hd)) lemma mul_div_mul_left' (a b : α) {c : α} (hc : c ≠ 0) : (c * a) / (c * b) = a / b := decidable.by_cases (assume hb : b = 0, by rw [hb, mul_zero, div_zero, div_zero]) (assume hb : b ≠ 0, mul_div_mul_left _ hb hc) lemma mul_div_mul_right' (a b : α) {c : α} (hc : c ≠ 0) : (a * c) / (b * c) = a / b := by rw [mul_comm a, mul_comm b, (mul_div_mul_left' _ _ hc)] lemma div_mul_eq_mul_div_comm (a b c : α) : (b / c) * a = b * (a / c) := decidable.by_cases (assume hc : c = 0, by rw [hc, div_zero, zero_mul, div_zero, mul_zero]) (assume hc : c ≠ 0, field.div_mul_eq_mul_div_comm _ _ hc) lemma one_div_div (a b : α) : 1 / (a / b) = b / a := decidable.by_cases (assume ha : a = 0, by rw [ha, zero_div, div_zero, div_zero]) (assume ha : a ≠ 0, decidable.by_cases (assume hb : b = 0, by rw [hb, div_zero, zero_div, div_zero]) (assume hb : b ≠ 0, division_ring.one_div_div ha hb)) lemma div_div_eq_mul_div (a b c : α) : a / (b / c) = (a * c) / b := by rw [div_eq_mul_one_div, one_div_div, ← mul_div_assoc] lemma div_div_eq_div_mul (a b c : α) : (a / b) / c = a / (b * c) := by rw [div_eq_mul_one_div, div_mul_div, mul_one] lemma div_div_div_div_eq (a b c d : α) : (a / b) / (c / d) = (a * d) / (b * c) := by rw [div_div_eq_mul_div, div_mul_eq_mul_div, div_div_eq_div_mul] lemma div_helper {a : α} (b : α) (h : a ≠ 0) : (1 / (a * b)) * a = 1 / b := by rw [div_mul_eq_mul_div, one_mul, div_mul_right _ h] lemma div_mul_eq_div_mul_one_div (a b c : α) : a / (b * c) = (a / b) * (1 / c) := by rw [← div_div_eq_div_mul, ← div_eq_mul_one_div] end discrete_field
28653adce8fa45cdab7d2bad9fac3353b87a0253
618003631150032a5676f229d13a079ac875ff77
/src/ring_theory/power_series.lean
6fa4eee5a8d9d49a8b745cfb4f17a6d6ee549442
[ "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
57,816
lean
/- Copyright (c) 2019 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Kenny Lau -/ import data.mv_polynomial import ring_theory.ideal_operations import tactic.linarith /-! # Formal power series This file defines (multivariate) formal power series and develops the basic properties of these objects. A formal power series is to a polynomial like an infinite sum is to a finite sum. We provide the natural inclusion from polynomials to formal power series. ## Generalities The file starts with setting up the (semi)ring structure on multivariate power series. `trunc n φ` truncates a formal power series to the polynomial that has the same coefficients as φ, for all m ≤ n, and 0 otherwise. If the constant coefficient of a formal power series is invertible, then this formal power series is invertible. Formal power series over a local ring form a local ring. ## Formal power series in one variable We prove that if the ring of coefficients is an integral domain, then formal power series in one variable form an integral domain. The `order` of a formal power series `φ` is the multiplicity of the variable `X` in `φ`. If the coefficients form an integral domain, then `order` is a valuation (`order_mul`, `order_add_ge`). ## Implementation notes In this file we define multivariate formal power series with variables indexed by `σ` and coefficients in `α` as mv_power_series σ α := (σ →₀ ℕ) → α. Unfortunately there is not yet enough API to show that they are the completion of the ring of multivariate polynomials. However, we provide most of the infrastructure that is needed to do this. Once I-adic completion (topological or algebraic) is available it should not be hard to fill in the details. Formal power series in one variable are defined as power_series α := mv_power_series unit α. This allows us to port a lot of proofs and properties from the multivariate case to the single variable case. However, it means that formal power series are indexed by (unit →₀ ℕ), which is of course canonically isomorphic to ℕ. We then build some glue to treat formal power series as if they are indexed by ℕ. Occasionally this leads to proofs that are uglier than expected. -/ noncomputable theory open_locale classical /-- Multivariate formal power series, where `σ` is the index set of the variables and `α` is the coefficient ring.-/ def mv_power_series (σ : Type*) (α : Type*) := (σ →₀ ℕ) → α namespace mv_power_series open finsupp variables {σ : Type*} {α : Type*} instance [inhabited α] : inhabited (mv_power_series σ α) := ⟨λ _, default _⟩ instance [has_zero α] : has_zero (mv_power_series σ α) := pi.has_zero instance [add_monoid α] : add_monoid (mv_power_series σ α) := pi.add_monoid instance [add_group α] : add_group (mv_power_series σ α) := pi.add_group instance [add_comm_monoid α] : add_comm_monoid (mv_power_series σ α) := pi.add_comm_monoid instance [add_comm_group α] : add_comm_group (mv_power_series σ α) := pi.add_comm_group section add_monoid variables [add_monoid α] variables (α) /-- The `n`th monomial with coefficient `a` as multivariate formal power series.-/ def monomial (n : σ →₀ ℕ) : α →+ mv_power_series σ α := { to_fun := λ a m, if m = n then a else 0, map_zero' := funext $ λ m, by { split_ifs; refl }, map_add' := λ a b, funext $ λ m, show (if m = n then a + b else 0) = (if m = n then a else 0) + (if m = n then b else 0), from if h : m = n then by simp only [if_pos h] else by simp only [if_neg h, add_zero] } /-- The `n`th coefficient of a multivariate formal power series.-/ def coeff (n : σ →₀ ℕ) : (mv_power_series σ α) →+ α := { to_fun := λ φ, φ n, map_zero' := rfl, map_add' := λ _ _, rfl } variables {α} /-- Two multivariate formal power series are equal if all their coefficients are equal.-/ @[ext] lemma ext {φ ψ} (h : ∀ (n : σ →₀ ℕ), coeff α n φ = coeff α n ψ) : φ = ψ := funext h /-- Two multivariate formal power series are equal if and only if all their coefficients are equal.-/ lemma ext_iff {φ ψ : mv_power_series σ α} : φ = ψ ↔ (∀ (n : σ →₀ ℕ), coeff α n φ = coeff α n ψ) := ⟨λ h n, congr_arg (coeff α n) h, ext⟩ lemma coeff_monomial (m n : σ →₀ ℕ) (a : α) : coeff α m (monomial α n a) = if m = n then a else 0 := rfl @[simp] lemma coeff_monomial' (n : σ →₀ ℕ) (a : α) : coeff α n (monomial α n a) = a := if_pos rfl @[simp] lemma coeff_comp_monomial (n : σ →₀ ℕ) : (coeff α n).comp (monomial α n) = add_monoid_hom.id α := add_monoid_hom.ext $ coeff_monomial' n @[simp] lemma coeff_zero (n : σ →₀ ℕ) : coeff α n (0 : mv_power_series σ α) = 0 := rfl end add_monoid section semiring variables [semiring α] (n : σ →₀ ℕ) (φ ψ : mv_power_series σ α) instance : has_one (mv_power_series σ α) := ⟨monomial α (0 : σ →₀ ℕ) 1⟩ lemma coeff_one : coeff α n (1 : mv_power_series σ α) = if n = 0 then 1 else 0 := rfl lemma coeff_zero_one : coeff α (0 : σ →₀ ℕ) 1 = 1 := coeff_monomial' 0 1 instance : has_mul (mv_power_series σ α) := ⟨λ φ ψ n, (finsupp.antidiagonal n).support.sum (λ p, φ p.1 * ψ p.2)⟩ lemma coeff_mul : coeff α n (φ * ψ) = (finsupp.antidiagonal n).support.sum (λ p, coeff α p.1 φ * coeff α p.2 ψ) := rfl protected lemma zero_mul : (0 : mv_power_series σ α) * φ = 0 := ext $ λ n, by simp [coeff_mul] protected lemma mul_zero : φ * 0 = 0 := ext $ λ n, by simp [coeff_mul] protected lemma one_mul : (1 : mv_power_series σ α) * φ = φ := ext $ λ n, begin rw [coeff_mul, finset.sum_eq_single ((0 : σ →₀ ℕ), n)]; simp [mem_antidiagonal_support, coeff_one], show ∀ (i j : σ →₀ ℕ), i + j = n → (i = 0 → j ≠ n) → (if i = 0 then coeff α j φ else 0) = 0, intros i j hij h, rw [if_neg], contrapose! h, simpa [h] using hij, end protected lemma mul_one : φ * 1 = φ := ext $ λ n, begin rw [coeff_mul, finset.sum_eq_single (n, (0 : σ →₀ ℕ))], rotate, { rintros ⟨i, j⟩ hij h, rw [coeff_one, if_neg, mul_zero], rw mem_antidiagonal_support at hij, contrapose! h, simpa [h] using hij }, all_goals { simp [mem_antidiagonal_support, coeff_one] } end protected lemma mul_add (φ₁ φ₂ φ₃ : mv_power_series σ α) : φ₁ * (φ₂ + φ₃) = φ₁ * φ₂ + φ₁ * φ₃ := ext $ λ n, by simp only [coeff_mul, mul_add, finset.sum_add_distrib, add_monoid_hom.map_add] protected lemma add_mul (φ₁ φ₂ φ₃ : mv_power_series σ α) : (φ₁ + φ₂) * φ₃ = φ₁ * φ₃ + φ₂ * φ₃ := ext $ λ n, by simp only [coeff_mul, add_mul, finset.sum_add_distrib, add_monoid_hom.map_add] protected lemma mul_assoc (φ₁ φ₂ φ₃ : mv_power_series σ α) : (φ₁ * φ₂) * φ₃ = φ₁ * (φ₂ * φ₃) := ext $ λ n, begin simp only [coeff_mul], have := @finset.sum_sigma ((σ →₀ ℕ) × (σ →₀ ℕ)) α _ _ (antidiagonal n).support (λ p, (antidiagonal (p.1)).support) (λ x, coeff α x.2.1 φ₁ * coeff α x.2.2 φ₂ * coeff α x.1.2 φ₃), convert this.symm using 1; clear this, { apply finset.sum_congr rfl, intros p hp, exact finset.sum_mul }, have := @finset.sum_sigma ((σ →₀ ℕ) × (σ →₀ ℕ)) α _ _ (antidiagonal n).support (λ p, (antidiagonal (p.2)).support) (λ x, coeff α x.1.1 φ₁ * (coeff α x.2.1 φ₂ * coeff α x.2.2 φ₃)), convert this.symm using 1; clear this, { apply finset.sum_congr rfl, intros p hp, rw finset.mul_sum }, 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_antidiagonal_support] at H ⊢, finish }, { 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_antidiagonal_support, and_imp, prod.mk.inj_iff, add_comm, heq_iff_eq] at H₁ H₂ ⊢, finish }, { rintros ⟨⟨i,j⟩, ⟨k,l⟩⟩ H, refine ⟨⟨(i+k, l), (i, k)⟩, _, _⟩; { simp only [finset.mem_sigma, mem_antidiagonal_support] at H ⊢, finish } } end instance : semiring (mv_power_series σ α) := { mul_one := mv_power_series.mul_one, one_mul := mv_power_series.one_mul, mul_assoc := mv_power_series.mul_assoc, mul_zero := mv_power_series.mul_zero, zero_mul := mv_power_series.zero_mul, left_distrib := mv_power_series.mul_add, right_distrib := mv_power_series.add_mul, .. mv_power_series.has_one, .. mv_power_series.has_mul, .. mv_power_series.add_comm_monoid } end semiring instance [comm_semiring α] : comm_semiring (mv_power_series σ α) := { mul_comm := λ φ ψ, ext $ λ n, finset.sum_bij (λ p hp, p.swap) (λ p hp, swap_mem_antidiagonal_support hp) (λ p hp, mul_comm _ _) (λ p q hp hq H, by simpa using congr_arg prod.swap H) (λ p hp, ⟨p.swap, swap_mem_antidiagonal_support hp, p.swap_swap.symm⟩), .. mv_power_series.semiring } instance [ring α] : ring (mv_power_series σ α) := { .. mv_power_series.semiring, .. mv_power_series.add_comm_group } instance [comm_ring α] : comm_ring (mv_power_series σ α) := { .. mv_power_series.comm_semiring, .. mv_power_series.add_comm_group } section semiring variables [semiring α] lemma monomial_mul_monomial (m n : σ →₀ ℕ) (a b : α) : monomial α m a * monomial α n b = monomial α (m + n) (a * b) := begin ext k, rw [coeff_mul, coeff_monomial], split_ifs with h, { rw [h, finset.sum_eq_single (m,n)], { rw [coeff_monomial', coeff_monomial'] }, { rintros ⟨i,j⟩ hij hne, rw [ne.def, prod.mk.inj_iff, not_and] at hne, by_cases H : i = m, { rw [coeff_monomial j n b, if_neg (hne H), mul_zero] }, { rw [coeff_monomial, if_neg H, zero_mul] } }, { intro H, rw finsupp.mem_antidiagonal_support at H, exfalso, exact H rfl } }, { rw [finset.sum_eq_zero], rintros ⟨i,j⟩ hij, rw finsupp.mem_antidiagonal_support at hij, by_cases H : i = m, { subst i, have : j ≠ n, { rintro rfl, exact h hij.symm }, { rw [coeff_monomial j n b, if_neg this, mul_zero] } }, { rw [coeff_monomial, if_neg H, zero_mul] } } end variables (σ) (α) /-- The constant multivariate formal power series.-/ def C : α →+* mv_power_series σ α := { map_one' := rfl, map_mul' := λ a b, (monomial_mul_monomial 0 0 a b).symm, .. monomial α (0 : σ →₀ ℕ) } variables {σ} {α} @[simp] lemma monomial_zero_eq_C : monomial α (0 : σ →₀ ℕ) = C σ α := rfl lemma monomial_zero_eq_C_apply (a : α) : monomial α (0 : σ →₀ ℕ) a = C σ α a := rfl lemma coeff_C (n : σ →₀ ℕ) (a : α) : coeff α n (C σ α a) = if n = 0 then a else 0 := rfl lemma coeff_zero_C (a : α) : coeff α (0 : σ →₀ℕ) (C σ α a) = a := coeff_monomial' 0 a /-- The variables of the multivariate formal power series ring.-/ def X (s : σ) : mv_power_series σ α := monomial α (single s 1) 1 lemma coeff_X (n : σ →₀ ℕ) (s : σ) : coeff α n (X s : mv_power_series σ α) = if n = (single s 1) then 1 else 0 := rfl lemma coeff_index_single_X (s t : σ) : coeff α (single t 1) (X s : mv_power_series σ α) = if t = s then 1 else 0 := by { simp only [coeff_X, single_left_inj one_ne_zero], split_ifs; refl } @[simp] lemma coeff_index_single_self_X (s : σ) : coeff α (single s 1) (X s : mv_power_series σ α) = 1 := if_pos rfl lemma coeff_zero_X (s : σ) : coeff α (0 : σ →₀ ℕ) (X s : mv_power_series σ α) = 0 := by { rw [coeff_X, if_neg], intro h, exact one_ne_zero (single_eq_zero.mp h.symm) } lemma X_def (s : σ) : X s = monomial α (single s 1) 1 := rfl lemma X_pow_eq (s : σ) (n : ℕ) : (X s : mv_power_series σ α)^n = monomial α (single s n) 1 := begin induction n with n ih, { rw [pow_zero, finsupp.single_zero], refl }, { rw [pow_succ', ih, nat.succ_eq_add_one, finsupp.single_add, X, monomial_mul_monomial, one_mul] } end lemma coeff_X_pow (m : σ →₀ ℕ) (s : σ) (n : ℕ) : coeff α m ((X s : mv_power_series σ α)^n) = if m = single s n then 1 else 0 := by rw [X_pow_eq s n, coeff_monomial] @[simp] lemma coeff_mul_C (n : σ →₀ ℕ) (φ : mv_power_series σ α) (a : α) : coeff α n (φ * (C σ α a)) = (coeff α n φ) * a := begin rw [coeff_mul n φ], rw [finset.sum_eq_single (n,(0 : σ →₀ ℕ))], { rw [coeff_C, if_pos rfl] }, { rintro ⟨i,j⟩ hij hne, rw finsupp.mem_antidiagonal_support at hij, by_cases hj : j = 0, { subst hj, simp at *, contradiction }, { rw [coeff_C, if_neg hj, mul_zero] } }, { intro h, exfalso, apply h, rw finsupp.mem_antidiagonal_support, apply add_zero } end lemma coeff_zero_mul_X (φ : mv_power_series σ α) (s : σ) : coeff α (0 : σ →₀ ℕ) (φ * X s) = 0 := begin rw [coeff_mul _ φ, finset.sum_eq_zero], rintro ⟨i,j⟩ hij, obtain ⟨rfl, rfl⟩ : i = 0 ∧ j = 0, { rw finsupp.mem_antidiagonal_support at hij, simpa using hij }, simp [coeff_zero_X] end variables (σ) (α) /-- The constant coefficient of a formal power series.-/ def constant_coeff : (mv_power_series σ α) →+* α := { to_fun := coeff α (0 : σ →₀ ℕ), map_one' := coeff_zero_one, map_mul' := λ φ ψ, by simp [coeff_mul, support_single_ne_zero], .. coeff α (0 : σ →₀ ℕ) } variables {σ} {α} @[simp] lemma coeff_zero_eq_constant_coeff : coeff α (0 : σ →₀ ℕ) = constant_coeff σ α := rfl lemma coeff_zero_eq_constant_coeff_apply (φ : mv_power_series σ α) : coeff α (0 : σ →₀ ℕ) φ = constant_coeff σ α φ := rfl @[simp] lemma constant_coeff_C (a : α) : constant_coeff σ α (C σ α a) = a := rfl @[simp] lemma constant_coeff_comp_C : (constant_coeff σ α).comp (C σ α) = ring_hom.id α := rfl @[simp] lemma constant_coeff_zero : constant_coeff σ α 0 = 0 := rfl @[simp] lemma constant_coeff_one : constant_coeff σ α 1 = 1 := rfl @[simp] lemma constant_coeff_X (s : σ) : constant_coeff σ α (X s) = 0 := coeff_zero_X s /-- If a multivariate formal power series is invertible, then so is its constant coefficient.-/ lemma is_unit_constant_coeff (φ : mv_power_series σ α) (h : is_unit φ) : is_unit (constant_coeff σ α φ) := h.map' (constant_coeff σ α) instance : semimodule α (mv_power_series σ α) := { smul := λ a φ, C σ α a * φ, one_smul := λ φ, one_mul _, mul_smul := λ a b φ, by simp [ring_hom.map_mul, mul_assoc], smul_add := λ a φ ψ, mul_add _ _ _, smul_zero := λ a, mul_zero _, add_smul := λ a b φ, by simp only [ring_hom.map_add, add_mul], zero_smul := λ φ, by simp only [zero_mul, ring_hom.map_zero] } end semiring instance [ring α] : module α (mv_power_series σ α) := { ..mv_power_series.semimodule } instance [comm_ring α] : algebra α (mv_power_series σ α) := { commutes' := λ _ _, mul_comm _ _, smul_def' := λ c p, rfl, .. C σ α, .. mv_power_series.module } section map variables {β : Type*} {γ : Type*} [semiring α] [semiring β] [semiring γ] variables (f : α →+* β) (g : β →+* γ) variable (σ) /-- The map between multivariate formal power series induced by a map on the coefficients.-/ def map : mv_power_series σ α →+* mv_power_series σ β := { to_fun := λ φ n, f $ coeff α n φ, map_zero' := ext $ λ n, f.map_zero, map_one' := ext $ λ n, show f ((coeff α n) 1) = (coeff β n) 1, by { rw [coeff_one, coeff_one], split_ifs; simp [f.map_one, f.map_zero] }, map_add' := λ φ ψ, ext $ λ n, show f ((coeff α n) (φ + ψ)) = f ((coeff α n) φ) + f ((coeff α n) ψ), by simp, map_mul' := λ φ ψ, ext $ λ n, show f _ = _, begin rw [coeff_mul, ← finset.sum_hom _ f, coeff_mul, finset.sum_congr rfl], rintros ⟨i,j⟩ hij, rw [f.map_mul], refl, end } variable {σ} @[simp] lemma map_id : map σ (ring_hom.id α) = ring_hom.id _ := rfl lemma map_comp : map σ (g.comp f) = (map σ g).comp (map σ f) := rfl @[simp] lemma coeff_map (n : σ →₀ ℕ) (φ : mv_power_series σ α) : coeff β n (map σ f φ) = f (coeff α n φ) := rfl @[simp] lemma constant_coeff_map (φ : mv_power_series σ α) : constant_coeff σ β (map σ f φ) = f (constant_coeff σ α φ) := rfl end map section trunc variables [comm_semiring α] (n : σ →₀ ℕ) -- Auxiliary definition for the truncation function. def trunc_fun (φ : mv_power_series σ α) : mv_polynomial σ α := { support := (n.antidiagonal.support.image prod.fst).filter (λ m, coeff α m φ ≠ 0), to_fun := λ m, if m ≤ n then coeff α m φ else 0, mem_support_to_fun := λ m, begin suffices : m ∈ finset.image prod.fst ((antidiagonal n).support) ↔ m ≤ n, { rw [finset.mem_filter, this], split, { intro h, rw [if_pos h.1], exact h.2 }, { intro h, split_ifs at h with H H, { exact ⟨H, h⟩ }, { exfalso, exact h rfl } } }, rw finset.mem_image, split, { rintros ⟨⟨i,j⟩, h, rfl⟩ s, rw finsupp.mem_antidiagonal_support at h, rw ← h, exact nat.le_add_right _ _ }, { intro h, refine ⟨(m, n-m), _, rfl⟩, rw finsupp.mem_antidiagonal_support, ext s, exact nat.add_sub_of_le (h s) } end } variable (α) /-- The `n`th truncation of a multivariate formal power series to a multivariate polynomial -/ def trunc : mv_power_series σ α →+ mv_polynomial σ α := { to_fun := trunc_fun n, map_zero' := mv_polynomial.ext _ _ $ λ m, by { change ite _ _ _ = _, split_ifs; refl }, map_add' := λ φ ψ, mv_polynomial.ext _ _ $ λ m, begin rw mv_polynomial.coeff_add, change ite _ _ _ = ite _ _ _ + ite _ _ _, split_ifs with H, {refl}, {rw [zero_add]} end } variable {α} lemma coeff_trunc (m : σ →₀ ℕ) (φ : mv_power_series σ α) : mv_polynomial.coeff m (trunc α n φ) = if m ≤ n then coeff α m φ else 0 := rfl @[simp] lemma trunc_one : trunc α n 1 = 1 := mv_polynomial.ext _ _ $ λ m, begin rw [coeff_trunc, coeff_one], split_ifs with H H' H', { subst m, erw mv_polynomial.coeff_C 0, simp }, { symmetry, erw mv_polynomial.coeff_monomial, convert if_neg (ne.elim (ne.symm H')), }, { symmetry, erw mv_polynomial.coeff_monomial, convert if_neg _, intro H', apply H, subst m, intro s, exact nat.zero_le _ } end @[simp] lemma trunc_C (a : α) : trunc α n (C σ α a) = mv_polynomial.C a := mv_polynomial.ext _ _ $ λ m, begin rw [coeff_trunc, coeff_C, mv_polynomial.coeff_C], split_ifs with H; refl <|> try {simp * at *}, exfalso, apply H, subst m, intro s, exact nat.zero_le _ end end trunc section comm_semiring variable [comm_semiring α] lemma X_pow_dvd_iff {s : σ} {n : ℕ} {φ : mv_power_series σ α} : (X s : mv_power_series σ α)^n ∣ φ ↔ ∀ m : σ →₀ ℕ, m s < n → coeff α m φ = 0 := begin split, { rintros ⟨φ, rfl⟩ m h, rw [coeff_mul, finset.sum_eq_zero], rintros ⟨i,j⟩ hij, rw [coeff_X_pow, if_neg, zero_mul], contrapose! h, subst i, rw finsupp.mem_antidiagonal_support at hij, rw [← hij, finsupp.add_apply, finsupp.single_eq_same], exact nat.le_add_right n _ }, { intro h, refine ⟨λ m, coeff α (m + (single s n)) φ, _⟩, ext m, by_cases H : m - single s n + single s n = m, { rw [coeff_mul, finset.sum_eq_single (single s n, m - single s n)], { rw [coeff_X_pow, if_pos rfl, one_mul], simpa using congr_arg (λ (m : σ →₀ ℕ), coeff α m φ) H.symm }, { rintros ⟨i,j⟩ hij hne, rw finsupp.mem_antidiagonal_support at hij, rw coeff_X_pow, split_ifs with hi, { exfalso, apply hne, rw [← hij, ← hi, prod.mk.inj_iff], refine ⟨rfl, _⟩, ext t, simp only [nat.add_sub_cancel_left, finsupp.add_apply, finsupp.nat_sub_apply] }, { exact zero_mul _ } }, { intro hni, exfalso, apply hni, rwa [finsupp.mem_antidiagonal_support, add_comm] } }, { rw [h, coeff_mul, finset.sum_eq_zero], { rintros ⟨i,j⟩ hij, rw finsupp.mem_antidiagonal_support at hij, rw coeff_X_pow, split_ifs with hi, { exfalso, apply H, rw [← hij, hi], ext, simp, cc }, { exact zero_mul _ } }, { classical, contrapose! H, ext t, by_cases hst : s = t, { subst t, simpa using nat.sub_add_cancel H }, { simp [finsupp.single_apply, hst] } } } } end lemma X_dvd_iff {s : σ} {φ : mv_power_series σ α} : (X s : mv_power_series σ α) ∣ φ ↔ ∀ m : σ →₀ ℕ, m s = 0 → coeff α m φ = 0 := begin rw [← pow_one (X s : mv_power_series σ α), X_pow_dvd_iff], split; intros h m hm, { exact h m (hm.symm ▸ zero_lt_one) }, { exact h m (nat.eq_zero_of_le_zero $ nat.le_of_succ_le_succ hm) } end end comm_semiring section ring variables [ring α] /- The inverse of a multivariate formal power series is defined by well-founded recursion on the coeffients of the inverse. -/ /-- Auxiliary definition that unifies the totalised inverse formal power series `(_)⁻¹` and the inverse formal power series that depends on an inverse of the constant coefficient `inv_of_unit`.-/ protected noncomputable def inv.aux (a : α) (φ : mv_power_series σ α) : mv_power_series σ α | n := if n = 0 then a else - a * n.antidiagonal.support.sum (λ (x : (σ →₀ ℕ) × (σ →₀ ℕ)), if h : x.2 < n then coeff α x.1 φ * inv.aux x.2 else 0) using_well_founded { rel_tac := λ _ _, `[exact ⟨_, finsupp.lt_wf σ⟩], dec_tac := tactic.assumption } lemma coeff_inv_aux (n : σ →₀ ℕ) (a : α) (φ : mv_power_series σ α) : coeff α n (inv.aux a φ) = if n = 0 then a else - a * n.antidiagonal.support.sum (λ (x : (σ →₀ ℕ) × (σ →₀ ℕ)), if x.2 < n then coeff α x.1 φ * coeff α x.2 (inv.aux a φ) else 0) := show inv.aux a φ n = _, by { rw inv.aux, refl } /-- A multivariate formal power series is invertible if the constant coefficient is invertible.-/ def inv_of_unit (φ : mv_power_series σ α) (u : units α) : mv_power_series σ α := inv.aux (↑u⁻¹) φ lemma coeff_inv_of_unit (n : σ →₀ ℕ) (φ : mv_power_series σ α) (u : units α) : coeff α n (inv_of_unit φ u) = if n = 0 then ↑u⁻¹ else - ↑u⁻¹ * n.antidiagonal.support.sum (λ (x : (σ →₀ ℕ) × (σ →₀ ℕ)), if x.2 < n then coeff α x.1 φ * coeff α x.2 (inv_of_unit φ u) else 0) := coeff_inv_aux n (↑u⁻¹) φ @[simp] lemma constant_coeff_inv_of_unit (φ : mv_power_series σ α) (u : units α) : constant_coeff σ α (inv_of_unit φ u) = ↑u⁻¹ := by rw [← coeff_zero_eq_constant_coeff_apply, coeff_inv_of_unit, if_pos rfl] lemma mul_inv_of_unit (φ : mv_power_series σ α) (u : units α) (h : constant_coeff σ α φ = u) : φ * inv_of_unit φ u = 1 := ext $ λ n, if H : n = 0 then by { rw H, simp [coeff_mul, support_single_ne_zero, h], } else begin have : ((0 : σ →₀ ℕ), n) ∈ n.antidiagonal.support, { rw [finsupp.mem_antidiagonal_support, zero_add] }, rw [coeff_one, if_neg H, coeff_mul, ← finset.insert_erase this, finset.sum_insert (finset.not_mem_erase _ _), coeff_zero_eq_constant_coeff_apply, h, coeff_inv_of_unit, if_neg H, neg_mul_eq_neg_mul_symm, mul_neg_eq_neg_mul_symm, units.mul_inv_cancel_left, ← finset.insert_erase this, finset.sum_insert (finset.not_mem_erase _ _), finset.insert_erase this, if_neg (not_lt_of_ge $ le_refl _), zero_add, add_comm, ← sub_eq_add_neg, sub_eq_zero, finset.sum_congr rfl], rintros ⟨i,j⟩ hij, rw [finset.mem_erase, finsupp.mem_antidiagonal_support] at hij, cases hij with h₁ h₂, subst n, rw if_pos, suffices : (0 : _) + j < i + j, {simpa}, apply add_lt_add_right, split, { intro s, exact nat.zero_le _ }, { intro H, apply h₁, suffices : i = 0, {simp [this]}, ext1 s, exact nat.eq_zero_of_le_zero (H s) } end end ring section comm_ring variable [comm_ring α] /-- Multivariate formal power series over a local ring form a local ring.-/ lemma is_local_ring (h : is_local_ring α) : is_local_ring (mv_power_series σ α) := begin split, { have H : (0:α) ≠ 1 := ‹is_local_ring α›.1, contrapose! H, simpa using congr_arg (constant_coeff σ α) H }, { intro φ, rcases ‹is_local_ring α›.2 (constant_coeff σ α φ) with ⟨u,h⟩|⟨u,h⟩; [left, right]; { refine is_unit_of_mul_eq_one _ _ (mul_inv_of_unit _ u _), simpa using h.symm } } end -- TODO(jmc): once adic topology lands, show that this is complete end comm_ring section nonzero variables [semiring α] [nonzero α] instance : nonzero (mv_power_series σ α) := { zero_ne_one := assume h, zero_ne_one $ show (0:α) = 1, from congr_arg (constant_coeff σ α) h } lemma X_inj {s t : σ} : (X s : mv_power_series σ α) = X t ↔ s = t := ⟨begin intro h, replace h := congr_arg (coeff α (single s 1)) h, rw [coeff_X, if_pos rfl, coeff_X] at h, split_ifs at h with H, { rw finsupp.single_eq_single_iff at H, cases H, { exact H.1 }, { exfalso, exact one_ne_zero H.1 } }, { exfalso, exact one_ne_zero h } end, congr_arg X⟩ end nonzero section local_ring variables {β : Type*} [local_ring α] [local_ring β] (f : α →+* β) [is_local_ring_hom f] instance : local_ring (mv_power_series σ α) := local_of_is_local_ring $ is_local_ring ⟨zero_ne_one, local_ring.is_local⟩ instance map.is_local_ring_hom : is_local_ring_hom (map σ f) := ⟨begin rintros φ ⟨ψ, h⟩, replace h := congr_arg (constant_coeff σ β) h, rw constant_coeff_map at h, have : is_unit (constant_coeff σ β ↑ψ) := @is_unit_constant_coeff σ β _ (↑ψ) (is_unit_unit ψ), rw h at this, rcases is_unit_of_map_unit f _ this with ⟨c, hc⟩, exact is_unit_of_mul_eq_one φ (inv_of_unit φ c) (mul_inv_of_unit φ c hc.symm) end⟩ end local_ring section field variables [field α] protected def inv (φ : mv_power_series σ α) : mv_power_series σ α := inv.aux (constant_coeff σ α φ)⁻¹ φ instance : has_inv (mv_power_series σ α) := ⟨mv_power_series.inv⟩ lemma coeff_inv (n : σ →₀ ℕ) (φ : mv_power_series σ α) : coeff α n (φ⁻¹) = if n = 0 then (constant_coeff σ α φ)⁻¹ else - (constant_coeff σ α φ)⁻¹ * n.antidiagonal.support.sum (λ (x : (σ →₀ ℕ) × (σ →₀ ℕ)), if x.2 < n then coeff α x.1 φ * coeff α x.2 (φ⁻¹) else 0) := coeff_inv_aux n _ φ @[simp] lemma constant_coeff_inv (φ : mv_power_series σ α) : constant_coeff σ α (φ⁻¹) = (constant_coeff σ α φ)⁻¹ := by rw [← coeff_zero_eq_constant_coeff_apply, coeff_inv, if_pos rfl] lemma inv_eq_zero {φ : mv_power_series σ α} : φ⁻¹ = 0 ↔ constant_coeff σ α φ = 0 := ⟨λ h, by simpa using congr_arg (constant_coeff σ α) h, λ h, ext $ λ n, by { rw coeff_inv, split_ifs; simp only [h, mv_power_series.coeff_zero, zero_mul, inv_zero, neg_zero] }⟩ @[simp, priority 1100] lemma inv_of_unit_eq (φ : mv_power_series σ α) (h : constant_coeff σ α φ ≠ 0) : inv_of_unit φ (units.mk0 _ h) = φ⁻¹ := rfl @[simp] lemma inv_of_unit_eq' (φ : mv_power_series σ α) (u : units α) (h : constant_coeff σ α φ = u) : inv_of_unit φ u = φ⁻¹ := begin rw ← inv_of_unit_eq φ (h.symm ▸ u.coe_ne_zero), congr' 1, rw [units.ext_iff], exact h.symm, end @[simp] protected lemma mul_inv (φ : mv_power_series σ α) (h : constant_coeff σ α φ ≠ 0) : φ * φ⁻¹ = 1 := by rw [← inv_of_unit_eq φ h, mul_inv_of_unit φ (units.mk0 _ h) rfl] @[simp] protected lemma inv_mul (φ : mv_power_series σ α) (h : constant_coeff σ α φ ≠ 0) : φ⁻¹ * φ = 1 := by rw [mul_comm, φ.mul_inv h] end field end mv_power_series namespace mv_polynomial open finsupp variables {σ : Type*} {α : Type*} [comm_semiring α] /-- The natural inclusion from multivariate polynomials into multivariate formal power series.-/ instance coe_to_mv_power_series : has_coe (mv_polynomial σ α) (mv_power_series σ α) := ⟨λ φ n, coeff n φ⟩ @[simp, norm_cast] lemma coeff_coe (φ : mv_polynomial σ α) (n : σ →₀ ℕ) : mv_power_series.coeff α n ↑φ = coeff n φ := rfl @[simp, norm_cast] lemma coe_monomial (n : σ →₀ ℕ) (a : α) : (monomial n a : mv_power_series σ α) = mv_power_series.monomial α n a := mv_power_series.ext $ λ m, begin rw [coeff_coe, coeff_monomial, mv_power_series.coeff_monomial], split_ifs with h₁ h₂; refl <|> subst m; contradiction end @[simp, norm_cast] lemma coe_zero : ((0 : mv_polynomial σ α) : mv_power_series σ α) = 0 := rfl @[simp, norm_cast] lemma coe_one : ((1 : mv_polynomial σ α) : mv_power_series σ α) = 1 := coe_monomial _ _ @[simp, norm_cast] lemma coe_add (φ ψ : mv_polynomial σ α) : ((φ + ψ : mv_polynomial σ α) : mv_power_series σ α) = φ + ψ := rfl @[simp, norm_cast] lemma coe_mul (φ ψ : mv_polynomial σ α) : ((φ * ψ : mv_polynomial σ α) : mv_power_series σ α) = φ * ψ := mv_power_series.ext $ λ n, by simp only [coeff_coe, mv_power_series.coeff_mul, coeff_mul] @[simp, norm_cast] lemma coe_C (a : α) : ((C a : mv_polynomial σ α) : mv_power_series σ α) = mv_power_series.C σ α a := coe_monomial _ _ @[simp, norm_cast] lemma coe_X (s : σ) : ((X s : mv_polynomial σ α) : mv_power_series σ α) = mv_power_series.X s := coe_monomial _ _ namespace coe_to_mv_power_series instance : is_semiring_hom (coe : mv_polynomial σ α → mv_power_series σ α) := { map_zero := coe_zero, map_one := coe_one, map_add := coe_add, map_mul := coe_mul } end coe_to_mv_power_series end mv_polynomial /-- Formal power series over the coefficient ring `α`.-/ def power_series (α : Type*) := mv_power_series unit α namespace power_series open finsupp (single) variable {α : Type*} instance [inhabited α] : inhabited (power_series α) := by delta power_series; apply_instance instance [add_monoid α] : add_monoid (power_series α) := by delta power_series; apply_instance instance [add_group α] : add_group (power_series α) := by delta power_series; apply_instance instance [add_comm_monoid α] : add_comm_monoid (power_series α) := by delta power_series; apply_instance instance [add_comm_group α] : add_comm_group (power_series α) := by delta power_series; apply_instance instance [semiring α] : semiring (power_series α) := by delta power_series; apply_instance instance [comm_semiring α] : comm_semiring (power_series α) := by delta power_series; apply_instance instance [ring α] : ring (power_series α) := by delta power_series; apply_instance instance [comm_ring α] : comm_ring (power_series α) := by delta power_series; apply_instance instance [semiring α] [nonzero α] : nonzero (power_series α) := by delta power_series; apply_instance instance [semiring α] : semimodule α (power_series α) := by delta power_series; apply_instance instance [ring α] : module α (power_series α) := by delta power_series; apply_instance instance [comm_ring α] : algebra α (power_series α) := by delta power_series; apply_instance section add_monoid variables (α) [add_monoid α] /-- The `n`th coefficient of a formal power series.-/ def coeff (n : ℕ) : power_series α →+ α := mv_power_series.coeff α (single () n) /-- The `n`th monomial with coefficient `a` as formal power series.-/ def monomial (n : ℕ) : α →+ power_series α := mv_power_series.monomial α (single () n) variables {α} lemma coeff_def {s : unit →₀ ℕ} {n : ℕ} (h : s () = n) : coeff α n = mv_power_series.coeff α s := by erw [coeff, ← h, ← finsupp.unique_single s] /-- Two formal power series are equal if all their coefficients are equal.-/ @[ext] lemma ext {φ ψ : power_series α} (h : ∀ n, coeff α n φ = coeff α n ψ) : φ = ψ := mv_power_series.ext $ λ n, by { rw ← coeff_def, { apply h }, refl } /-- Two formal power series are equal if all their coefficients are equal.-/ lemma ext_iff {φ ψ : power_series α} : φ = ψ ↔ (∀ n, coeff α n φ = coeff α n ψ) := ⟨λ h n, congr_arg (coeff α n) h, ext⟩ /-- Constructor for formal power series.-/ def mk {α} (f : ℕ → α) : power_series α := λ s, f (s ()) @[simp] lemma coeff_mk (n : ℕ) (f : ℕ → α) : coeff α n (mk f) = f n := congr_arg f finsupp.single_eq_same lemma coeff_monomial (m n : ℕ) (a : α) : coeff α m (monomial α n a) = if m = n then a else 0 := calc coeff α m (monomial α n a) = _ : mv_power_series.coeff_monomial _ _ _ ... = if m = n then a else 0 : by { simp only [finsupp.unique_single_eq_iff], split_ifs; refl } lemma monomial_eq_mk (n : ℕ) (a : α) : monomial α n a = mk (λ m, if m = n then a else 0) := ext $ λ m, by { rw [coeff_monomial, coeff_mk] } @[simp] lemma coeff_monomial' (n : ℕ) (a : α) : coeff α n (monomial α n a) = a := by convert if_pos rfl @[simp] lemma coeff_comp_monomial (n : ℕ) : (coeff α n).comp (monomial α n) = add_monoid_hom.id α := add_monoid_hom.ext $ coeff_monomial' n end add_monoid section semiring variable [semiring α] variable (α) /--The constant coefficient of a formal power series. -/ def constant_coeff : power_series α →+* α := mv_power_series.constant_coeff unit α /-- The constant formal power series.-/ def C : α →+* power_series α := mv_power_series.C unit α variable {α} /-- The variable of the formal power series ring.-/ def X : power_series α := mv_power_series.X () @[simp] lemma coeff_zero_eq_constant_coeff : coeff α 0 = constant_coeff α := begin rw [constant_coeff, ← mv_power_series.coeff_zero_eq_constant_coeff, coeff_def], refl end lemma coeff_zero_eq_constant_coeff_apply (φ : power_series α) : coeff α 0 φ = constant_coeff α φ := by rw [coeff_zero_eq_constant_coeff]; refl @[simp] lemma monomial_zero_eq_C : monomial α 0 = C α := by rw [monomial, finsupp.single_zero, mv_power_series.monomial_zero_eq_C, C] lemma monomial_zero_eq_C_apply (a : α) : monomial α 0 a = C α a := by simp lemma coeff_C (n : ℕ) (a : α) : coeff α n (C α a : power_series α) = if n = 0 then a else 0 := by rw [← monomial_zero_eq_C_apply, coeff_monomial] lemma coeff_zero_C (a : α) : coeff α 0 (C α a) = a := by rw [← monomial_zero_eq_C_apply, coeff_monomial' 0 a] lemma X_eq : (X : power_series α) = monomial α 1 1 := rfl lemma coeff_X (n : ℕ) : coeff α n (X : power_series α) = if n = 1 then 1 else 0 := by rw [X_eq, coeff_monomial] lemma coeff_zero_X : coeff α 0 (X : power_series α) = 0 := by rw [coeff, finsupp.single_zero, X, mv_power_series.coeff_zero_X] @[simp] lemma coeff_one_X : coeff α 1 (X : power_series α) = 1 := by rw [coeff_X, if_pos rfl] lemma X_pow_eq (n : ℕ) : (X : power_series α)^n = monomial α n 1 := mv_power_series.X_pow_eq _ n lemma coeff_X_pow (m n : ℕ) : coeff α m ((X : power_series α)^n) = if m = n then 1 else 0 := by rw [X_pow_eq, coeff_monomial] @[simp] lemma coeff_X_pow_self (n : ℕ) : coeff α n ((X : power_series α)^n) = 1 := by rw [coeff_X_pow, if_pos rfl] @[simp] lemma coeff_one (n : ℕ) : coeff α n (1 : power_series α) = if n = 0 then 1 else 0 := calc coeff α n (1 : power_series α) = _ : mv_power_series.coeff_one _ ... = if n = 0 then 1 else 0 : by { simp only [finsupp.single_eq_zero], split_ifs; refl } lemma coeff_zero_one : coeff α 0 (1 : power_series α) = 1 := coeff_zero_C 1 lemma coeff_mul (n : ℕ) (φ ψ : power_series α) : coeff α n (φ * ψ) = (finset.nat.antidiagonal n).sum (λ p, coeff α p.1 φ * coeff α p.2 ψ) := begin symmetry, apply finset.sum_bij (λ (p : ℕ × ℕ) h, (single () p.1, single () p.2)), { rintros ⟨i,j⟩ hij, rw finset.nat.mem_antidiagonal at hij, rw [finsupp.mem_antidiagonal_support, ← finsupp.single_add, hij], }, { rintros ⟨i,j⟩ hij, refl }, { rintros ⟨i,j⟩ ⟨k,l⟩ hij hkl, simpa only [prod.mk.inj_iff, finsupp.unique_single_eq_iff] using id }, { rintros ⟨f,g⟩ hfg, refine ⟨(f (), g ()), _, _⟩, { rw finsupp.mem_antidiagonal_support at hfg, rw [finset.nat.mem_antidiagonal, ← finsupp.add_apply, hfg, finsupp.single_eq_same] }, { rw prod.mk.inj_iff, dsimp, exact ⟨finsupp.unique_single f, finsupp.unique_single g⟩ } } end @[simp] lemma coeff_mul_C (n : ℕ) (φ : power_series α) (a : α) : coeff α n (φ * (C α a)) = (coeff α n φ) * a := mv_power_series.coeff_mul_C _ φ a @[simp] lemma coeff_succ_mul_X (n : ℕ) (φ : power_series α) : coeff α (n+1) (φ * X) = coeff α n φ := begin rw [coeff_mul _ φ, finset.sum_eq_single (n,1)], { rw [coeff_X, if_pos rfl, mul_one] }, { rintro ⟨i,j⟩ hij hne, by_cases hj : j = 1, { subst hj, simp at *, contradiction }, { simp [coeff_X, hj] } }, { intro h, exfalso, apply h, simp }, end @[simp] lemma constant_coeff_C (a : α) : constant_coeff α (C α a) = a := rfl @[simp] lemma constant_coeff_comp_C : (constant_coeff α).comp (C α) = ring_hom.id α := rfl @[simp] lemma constant_coeff_zero : constant_coeff α 0 = 0 := rfl @[simp] lemma constant_coeff_one : constant_coeff α 1 = 1 := rfl @[simp] lemma constant_coeff_X : constant_coeff α X = 0 := mv_power_series.coeff_zero_X _ lemma coeff_zero_mul_X (φ : power_series α) : coeff α 0 (φ * X) = 0 := by simp /-- If a formal power series is invertible, then so is its constant coefficient.-/ lemma is_unit_constant_coeff (φ : power_series α) (h : is_unit φ) : is_unit (constant_coeff α φ) := mv_power_series.is_unit_constant_coeff φ h section map variables {β : Type*} {γ : Type*} [semiring β] [semiring γ] variables (f : α →+* β) (g : β →+* γ) /-- The map between formal power series induced by a map on the coefficients.-/ def map : power_series α →+* power_series β := mv_power_series.map _ f @[simp] lemma map_id : (map (ring_hom.id α) : power_series α → power_series α) = id := rfl lemma map_comp : map (g.comp f) = (map g).comp (map f) := rfl @[simp] lemma coeff_map (n : ℕ) (φ : power_series α) : coeff β n (map f φ) = f (coeff α n φ) := rfl end map end semiring section comm_semiring variables [comm_semiring α] lemma X_pow_dvd_iff {n : ℕ} {φ : power_series α} : (X : power_series α)^n ∣ φ ↔ ∀ m, m < n → coeff α m φ = 0 := begin convert @mv_power_series.X_pow_dvd_iff unit α _ () n φ, apply propext, classical, split; intros h m hm, { rw finsupp.unique_single m, convert h _ hm }, { apply h, simpa only [finsupp.single_eq_same] using hm } end lemma X_dvd_iff {φ : power_series α} : (X : power_series α) ∣ φ ↔ constant_coeff α φ = 0 := begin rw [← pow_one (X : power_series α), X_pow_dvd_iff, ← coeff_zero_eq_constant_coeff_apply], split; intro h, { exact h 0 zero_lt_one }, { intros m hm, rwa nat.eq_zero_of_le_zero (nat.le_of_succ_le_succ hm) } end section trunc /-- The `n`th truncation of a formal power series to a polynomial -/ def trunc (n : ℕ) (φ : power_series α) : polynomial α := { support := ((finset.nat.antidiagonal n).image prod.fst).filter (λ m, coeff α m φ ≠ 0), to_fun := λ m, if m ≤ n then coeff α m φ else 0, mem_support_to_fun := λ m, begin suffices : m ∈ ((finset.nat.antidiagonal n).image prod.fst) ↔ m ≤ n, { rw [finset.mem_filter, this], split, { intro h, rw [if_pos h.1], exact h.2 }, { intro h, split_ifs at h with H H, { exact ⟨H, h⟩ }, { exfalso, exact h rfl } } }, rw finset.mem_image, split, { rintros ⟨⟨i,j⟩, h, rfl⟩, rw finset.nat.mem_antidiagonal at h, rw ← h, exact nat.le_add_right _ _ }, { intro h, refine ⟨(m, n-m), _, rfl⟩, rw finset.nat.mem_antidiagonal, exact nat.add_sub_of_le h } end } lemma coeff_trunc (m) (n) (φ : power_series α) : polynomial.coeff (trunc n φ) m = if m ≤ n then coeff α m φ else 0 := rfl @[simp] lemma trunc_zero (n) : trunc n (0 : power_series α) = 0 := polynomial.ext $ λ m, begin rw [coeff_trunc, add_monoid_hom.map_zero, polynomial.coeff_zero], split_ifs; refl end @[simp] lemma trunc_one (n) : trunc n (1 : power_series α) = 1 := polynomial.ext $ λ m, begin rw [coeff_trunc, coeff_one], split_ifs with H H' H'; rw [polynomial.coeff_one], { subst m, rw [if_pos rfl] }, { symmetry, exact if_neg (ne.elim (ne.symm H')) }, { symmetry, refine if_neg _, intro H', apply H, subst m, exact nat.zero_le _ } end @[simp] lemma trunc_C (n) (a : α) : trunc n (C α a) = polynomial.C a := polynomial.ext $ λ m, begin rw [coeff_trunc, coeff_C, polynomial.coeff_C], split_ifs with H; refl <|> try {simp * at *} end @[simp] lemma trunc_add (n) (φ ψ : power_series α) : trunc n (φ + ψ) = trunc n φ + trunc n ψ := polynomial.ext $ λ m, begin simp only [coeff_trunc, add_monoid_hom.map_add, polynomial.coeff_add], split_ifs with H, {refl}, {rw [zero_add]} end end trunc end comm_semiring section ring variables [ring α] protected def inv.aux : α → power_series α → power_series α := mv_power_series.inv.aux lemma coeff_inv_aux (n : ℕ) (a : α) (φ : power_series α) : coeff α n (inv.aux a φ) = if n = 0 then a else - a * (finset.nat.antidiagonal n).sum (λ (x : ℕ × ℕ), if x.2 < n then coeff α x.1 φ * coeff α x.2 (inv.aux a φ) else 0) := begin rw [coeff, inv.aux, mv_power_series.coeff_inv_aux], simp only [finsupp.single_eq_zero], split_ifs, {refl}, congr' 1, symmetry, apply finset.sum_bij (λ (p : ℕ × ℕ) h, (single () p.1, single () p.2)), { rintros ⟨i,j⟩ hij, rw finset.nat.mem_antidiagonal at hij, rw [finsupp.mem_antidiagonal_support, ← finsupp.single_add, hij], }, { rintros ⟨i,j⟩ hij, by_cases H : j < n, { rw [if_pos H, if_pos], {refl}, split, { rintro ⟨⟩, simpa [finsupp.single_eq_same] using le_of_lt H }, { intro hh, rw lt_iff_not_ge at H, apply H, simpa [finsupp.single_eq_same] using hh () } }, { rw [if_neg H, if_neg], rintro ⟨h₁, h₂⟩, apply h₂, rintro ⟨⟩, simpa [finsupp.single_eq_same] using not_lt.1 H } }, { rintros ⟨i,j⟩ ⟨k,l⟩ hij hkl, simpa only [prod.mk.inj_iff, finsupp.unique_single_eq_iff] using id }, { rintros ⟨f,g⟩ hfg, refine ⟨(f (), g ()), _, _⟩, { rw finsupp.mem_antidiagonal_support at hfg, rw [finset.nat.mem_antidiagonal, ← finsupp.add_apply, hfg, finsupp.single_eq_same] }, { rw prod.mk.inj_iff, dsimp, exact ⟨finsupp.unique_single f, finsupp.unique_single g⟩ } } end /-- A formal power series is invertible if the constant coefficient is invertible.-/ def inv_of_unit (φ : power_series α) (u : units α) : power_series α := mv_power_series.inv_of_unit φ u lemma coeff_inv_of_unit (n : ℕ) (φ : power_series α) (u : units α) : coeff α n (inv_of_unit φ u) = if n = 0 then ↑u⁻¹ else - ↑u⁻¹ * (finset.nat.antidiagonal n).sum (λ (x : ℕ × ℕ), if x.2 < n then coeff α x.1 φ * coeff α x.2 (inv_of_unit φ u) else 0) := coeff_inv_aux n ↑u⁻¹ φ @[simp] lemma constant_coeff_inv_of_unit (φ : power_series α) (u : units α) : constant_coeff α (inv_of_unit φ u) = ↑u⁻¹ := by rw [← coeff_zero_eq_constant_coeff_apply, coeff_inv_of_unit, if_pos rfl] lemma mul_inv_of_unit (φ : power_series α) (u : units α) (h : constant_coeff α φ = u) : φ * inv_of_unit φ u = 1 := mv_power_series.mul_inv_of_unit φ u $ h end ring section integral_domain variable [integral_domain α] lemma eq_zero_or_eq_zero_of_mul_eq_zero (φ ψ : power_series α) (h : φ * ψ = 0) : φ = 0 ∨ ψ = 0 := begin rw classical.or_iff_not_imp_left, intro H, have ex : ∃ m, coeff α m φ ≠ 0, { contrapose! H, exact ext H }, let P : ℕ → Prop := λ k, coeff α k φ ≠ 0, let m := nat.find ex, have hm₁ : coeff α m φ ≠ 0 := nat.find_spec ex, have hm₂ : ∀ k < m, ¬coeff α k φ ≠ 0 := λ k, nat.find_min ex, ext n, rw (coeff α n).map_zero, apply nat.strong_induction_on n, clear n, intros n ih, replace h := congr_arg (coeff α (m + n)) h, rw [add_monoid_hom.map_zero, coeff_mul, finset.sum_eq_single (m,n)] at h, { replace h := eq_zero_or_eq_zero_of_mul_eq_zero h, rw or_iff_not_imp_left at h, exact h hm₁ }, { rintro ⟨i,j⟩ hij hne, by_cases hj : j < n, { rw [ih j hj, mul_zero] }, by_cases hi : i < m, { specialize hm₂ _ hi, push_neg at hm₂, rw [hm₂, zero_mul] }, rw finset.nat.mem_antidiagonal at hij, push_neg at hi hj, suffices : m < i, { have : m + n < i + j := add_lt_add_of_lt_of_le this hj, exfalso, exact ne_of_lt this hij.symm }, contrapose! hne, have : i = m := le_antisymm hne hi, subst i, clear hi hne, simpa [ne.def, prod.mk.inj_iff] using (add_right_inj m).mp hij }, { contrapose!, intro h, rw finset.nat.mem_antidiagonal } end instance : integral_domain (power_series α) := { eq_zero_or_eq_zero_of_mul_eq_zero := eq_zero_or_eq_zero_of_mul_eq_zero, .. power_series.comm_ring, .. power_series.nonzero } /-- The ideal spanned by the variable in the power series ring over an integral domain is a prime ideal.-/ lemma span_X_is_prime : (ideal.span ({X} : set (power_series α))).is_prime := begin suffices : ideal.span ({X} : set (power_series α)) = (constant_coeff α).ker, { rw this, exact ring_hom.ker_is_prime _ }, apply ideal.ext, intro φ, rw [ring_hom.mem_ker, ideal.mem_span_singleton, X_dvd_iff] end /-- The variable of the power series ring over an integral domain is prime.-/ lemma X_prime : prime (X : power_series α) := begin rw ← ideal.span_singleton_prime, { exact span_X_is_prime }, { intro h, simpa using congr_arg (coeff α 1) h } end end integral_domain section local_ring variables [comm_ring α] lemma is_local_ring (h : is_local_ring α) : is_local_ring (power_series α) := mv_power_series.is_local_ring h end local_ring section local_ring variables {β : Type*} [local_ring α] [local_ring β] (f : α →+* β) [is_local_ring_hom f] instance : local_ring (power_series α) := mv_power_series.local_ring instance map.is_local_ring_hom : is_local_ring_hom (map f) := mv_power_series.map.is_local_ring_hom f end local_ring section field variables [field α] protected def inv : power_series α → power_series α := mv_power_series.inv instance : has_inv (power_series α) := ⟨power_series.inv⟩ lemma inv_eq_inv_aux (φ : power_series α) : φ⁻¹ = inv.aux (constant_coeff α φ)⁻¹ φ := rfl lemma coeff_inv (n) (φ : power_series α) : coeff α n (φ⁻¹) = if n = 0 then (constant_coeff α φ)⁻¹ else - (constant_coeff α φ)⁻¹ * (finset.nat.antidiagonal n).sum (λ (x : ℕ × ℕ), if x.2 < n then coeff α x.1 φ * coeff α x.2 (φ⁻¹) else 0) := by rw [inv_eq_inv_aux, coeff_inv_aux n (constant_coeff α φ)⁻¹ φ] @[simp] lemma constant_coeff_inv (φ : power_series α) : constant_coeff α (φ⁻¹) = (constant_coeff α φ)⁻¹ := mv_power_series.constant_coeff_inv φ lemma inv_eq_zero {φ : power_series α} : φ⁻¹ = 0 ↔ constant_coeff α φ = 0 := mv_power_series.inv_eq_zero @[simp, priority 1100] lemma inv_of_unit_eq (φ : power_series α) (h : constant_coeff α φ ≠ 0) : inv_of_unit φ (units.mk0 _ h) = φ⁻¹ := mv_power_series.inv_of_unit_eq _ _ @[simp] lemma inv_of_unit_eq' (φ : power_series α) (u : units α) (h : constant_coeff α φ = u) : inv_of_unit φ u = φ⁻¹ := mv_power_series.inv_of_unit_eq' φ _ h @[simp] protected lemma mul_inv (φ : power_series α) (h : constant_coeff α φ ≠ 0) : φ * φ⁻¹ = 1 := mv_power_series.mul_inv φ h @[simp] protected lemma inv_mul (φ : power_series α) (h : constant_coeff α φ ≠ 0) : φ⁻¹ * φ = 1 := mv_power_series.inv_mul φ h end field end power_series namespace power_series variable {α : Type*} local attribute [instance, priority 1] classical.prop_decidable noncomputable theory section order_basic open multiplicity variables [comm_semiring α] /-- The order of a formal power series `φ` is the smallest `n : enat` such that `X^n` divides `φ`. The order is `⊤` if and only if `φ = 0`. -/ @[reducible] def order (φ : power_series α) : enat := multiplicity X φ lemma order_finite_of_coeff_ne_zero (φ : power_series α) (h : ∃ n, coeff α n φ ≠ 0) : (order φ).dom := begin cases h with n h, refine ⟨n, _⟩, rw X_pow_dvd_iff, push_neg, exact ⟨n, lt_add_one n, h⟩ end /-- If the order of a formal power series is finite, then the coefficient indexed by the order is nonzero.-/ lemma coeff_order (φ : power_series α) (h : (order φ).dom) : coeff α (φ.order.get h) φ ≠ 0 := begin have H := nat.find_spec h, contrapose! H, rw X_pow_dvd_iff, intros m hm, by_cases Hm : m < nat.find h, { have := nat.find_min h Hm, push_neg at this, rw X_pow_dvd_iff at this, exact this m (lt_add_one m) }, have : m = nat.find h, {linarith}, {rwa this} end /-- If the `n`th coefficient of a formal power series is nonzero, then the order of the power series is less than or equal to `n`.-/ lemma order_le (φ : power_series α) (n : ℕ) (h : coeff α n φ ≠ 0) : order φ ≤ n := begin have h : ¬ X^(n+1) ∣ φ, { rw X_pow_dvd_iff, push_neg, exact ⟨n, lt_add_one n, h⟩ }, have : (order φ).dom := ⟨n, h⟩, rw [← enat.coe_get this, enat.coe_le_coe], refine nat.find_min' this h end /-- The `n`th coefficient of a formal power series is `0` if `n` is strictly smaller than the order of the power series.-/ lemma coeff_of_lt_order (φ : power_series α) (n : ℕ) (h: ↑n < order φ) : coeff α n φ = 0 := by { contrapose! h, exact order_le _ _ h } /-- The `0` power series is the unique power series with infinite order.-/ lemma order_eq_top {φ : power_series α} : φ.order = ⊤ ↔ φ = 0 := begin rw multiplicity.eq_top_iff, split, { intro h, ext n, specialize h (n+1), rw X_pow_dvd_iff at h, exact h n (lt_add_one _) }, { rintros rfl n, exact dvd_zero _ } end /-- The order of the `0` power series is infinite.-/ @[simp] lemma order_zero : order (0 : power_series α) = ⊤ := multiplicity.zero _ /-- The order of a formal power series is at least `n` if the `i`th coefficient is `0` for all `i < n`.-/ lemma order_ge_nat (φ : power_series α) (n : ℕ) (h : ∀ i < n, coeff α i φ = 0) : order φ ≥ n := begin by_contra H, rw not_le at H, have : (order φ).dom := enat.dom_of_le_some (le_of_lt H), rw [← enat.coe_get this, enat.coe_lt_coe] at H, exact coeff_order _ this (h _ H) end /-- The order of a formal power series is at least `n` if the `i`th coefficient is `0` for all `i < n`.-/ lemma order_ge (φ : power_series α) (n : enat) (h : ∀ i : ℕ, ↑i < n → coeff α i φ = 0) : order φ ≥ n := begin induction n using enat.cases_on, { show _ ≤ _, rw [top_le_iff, order_eq_top], ext i, exact h _ (enat.coe_lt_top i) }, { apply order_ge_nat, simpa only [enat.coe_lt_coe] using h } end /-- The order of a formal power series is exactly `n` if the `n`th coefficient is nonzero, and the `i`th coefficient is `0` for all `i < n`.-/ lemma order_eq_nat {φ : power_series α} {n : ℕ} : order φ = n ↔ (coeff α n φ ≠ 0) ∧ (∀ i, i < n → coeff α i φ = 0) := begin simp only [eq_some_iff, X_pow_dvd_iff], push_neg, split, { rintros ⟨h₁, m, hm₁, hm₂⟩, refine ⟨_, h₁⟩, suffices : n = m, { rwa this }, suffices : m ≥ n, { linarith }, contrapose! hm₂, exact h₁ _ hm₂ }, { rintros ⟨h₁, h₂⟩, exact ⟨h₂, n, lt_add_one n, h₁⟩ } end /-- The order of a formal power series is exactly `n` if the `n`th coefficient is nonzero, and the `i`th coefficient is `0` for all `i < n`.-/ lemma order_eq {φ : power_series α} {n : enat} : order φ = n ↔ (∀ i:ℕ, ↑i = n → coeff α i φ ≠ 0) ∧ (∀ i:ℕ, ↑i < n → coeff α i φ = 0) := begin induction n using enat.cases_on, { rw order_eq_top, split, { rintro rfl, split; intros, { exfalso, exact enat.coe_ne_top ‹_› ‹_› }, { exact (coeff _ _).map_zero } }, { rintro ⟨h₁, h₂⟩, ext i, exact h₂ i (enat.coe_lt_top i) } }, { simpa [enat.coe_inj] using order_eq_nat } end /-- The order of the sum of two formal power series is at least the minimum of their orders.-/ lemma order_add_ge (φ ψ : power_series α) : order (φ + ψ) ≥ min (order φ) (order ψ) := multiplicity.min_le_multiplicity_add private lemma order_add_of_order_eq.aux (φ ψ : power_series α) (h : order φ ≠ order ψ) (H : order φ < order ψ) : order (φ + ψ) ≤ order φ ⊓ order ψ := begin suffices : order (φ + ψ) = order φ, { rw [le_inf_iff, this], exact ⟨le_refl _, le_of_lt H⟩ }, { rw order_eq, split, { intros i hi, rw [(coeff _ _).map_add, coeff_of_lt_order ψ i (hi.symm ▸ H), add_zero], exact (order_eq_nat.1 hi.symm).1 }, { intros i hi, rw [(coeff _ _).map_add, coeff_of_lt_order φ i hi, coeff_of_lt_order ψ i (lt_trans hi H), zero_add] } } end /-- The order of the sum of two formal power series is the minimum of their orders if their orders differ.-/ lemma order_add_of_order_eq (φ ψ : power_series α) (h : order φ ≠ order ψ) : order (φ + ψ) = order φ ⊓ order ψ := begin refine le_antisymm _ (order_add_ge _ _), by_cases H₁ : order φ < order ψ, { apply order_add_of_order_eq.aux _ _ h H₁ }, by_cases H₂ : order ψ < order φ, { simpa only [add_comm, inf_comm] using order_add_of_order_eq.aux _ _ h.symm H₂ }, exfalso, exact h (le_antisymm (not_lt.1 H₂) (not_lt.1 H₁)) end /-- The order of the product of two formal power series is at least the sum of their orders.-/ lemma order_mul_ge (φ ψ : power_series α) : order (φ * ψ) ≥ order φ + order ψ := begin apply order_ge, intros n hn, rw [coeff_mul, finset.sum_eq_zero], rintros ⟨i,j⟩ hij, by_cases hi : ↑i < order φ, { rw [coeff_of_lt_order φ i hi, zero_mul] }, by_cases hj : ↑j < order ψ, { rw [coeff_of_lt_order ψ j hj, mul_zero] }, rw not_lt at hi hj, rw finset.nat.mem_antidiagonal at hij, exfalso, apply ne_of_lt (lt_of_lt_of_le hn $ add_le_add' hi hj), rw [← enat.coe_add, hij] end /-- The order of the monomial `a*X^n` is infinite if `a = 0` and `n` otherwise.-/ lemma order_monomial (n : ℕ) (a : α) : order (monomial α n a) = if a = 0 then ⊤ else n := begin split_ifs with h, { rw [h, order_eq_top, add_monoid_hom.map_zero] }, { rw [order_eq], split; intros i hi, { rw [enat.coe_inj] at hi, rwa [hi, coeff_monomial'] }, { rw [enat.coe_lt_coe] at hi, rw [coeff_monomial, if_neg], exact ne_of_lt hi } } end /-- The order of the monomial `a*X^n` is `n` if `a ≠ 0`.-/ lemma order_monomial_of_ne_zero (n : ℕ) (a : α) (h : a ≠ 0) : order (monomial α n a) = n := by rw [order_monomial, if_neg h] end order_basic section order_zero_ne_one variables [comm_semiring α] [nonzero α] /-- The order of the formal power series `1` is `0`.-/ @[simp] lemma order_one : order (1 : power_series α) = 0 := by simpa using order_monomial_of_ne_zero 0 (1:α) one_ne_zero /-- The order of the formal power series `X` is `1`.-/ @[simp] lemma order_X : order (X : power_series α) = 1 := order_monomial_of_ne_zero 1 (1:α) one_ne_zero /-- The order of the formal power series `X^n` is `n`.-/ @[simp] lemma order_X_pow (n : ℕ) : order ((X : power_series α)^n) = n := by { rw [X_pow_eq, order_monomial_of_ne_zero], exact one_ne_zero } end order_zero_ne_one section order_integral_domain variables [integral_domain α] /-- The order of the product of two formal power series over an integral domain is the sum of their orders.-/ lemma order_mul (φ ψ : power_series α) : order (φ * ψ) = order φ + order ψ := multiplicity.mul (X_prime) end order_integral_domain end power_series namespace polynomial open finsupp variables {σ : Type*} {α : Type*} [comm_semiring α] /-- The natural inclusion from polynomials into formal power series.-/ instance coe_to_power_series : has_coe (polynomial α) (power_series α) := ⟨λ φ, power_series.mk $ λ n, coeff φ n⟩ @[simp, norm_cast] lemma coeff_coe (φ : polynomial α) (n) : power_series.coeff α n φ = coeff φ n := congr_arg (coeff φ) (finsupp.single_eq_same) @[simp, norm_cast] lemma coe_monomial (n : ℕ) (a : α) : (monomial n a : power_series α) = power_series.monomial α n a := power_series.ext $ λ m, begin rw [coeff_coe, power_series.coeff_monomial], simp only [@eq_comm _ m n], convert finsupp.single_apply, end @[simp, norm_cast] lemma coe_zero : ((0 : polynomial α) : power_series α) = 0 := rfl @[simp, norm_cast] lemma coe_one : ((1 : polynomial α) : power_series α) = 1 := begin have := coe_monomial 0 (1:α), rwa power_series.monomial_zero_eq_C_apply at this, end @[simp, norm_cast] lemma coe_add (φ ψ : polynomial α) : ((φ + ψ : polynomial α) : power_series α) = φ + ψ := rfl @[simp, norm_cast] lemma coe_mul (φ ψ : polynomial α) : ((φ * ψ : polynomial α) : power_series α) = φ * ψ := power_series.ext $ λ n, by simp only [coeff_coe, power_series.coeff_mul, coeff_mul] @[simp, norm_cast] lemma coe_C (a : α) : ((C a : polynomial α) : power_series α) = power_series.C α a := begin have := coe_monomial 0 a, rwa power_series.monomial_zero_eq_C_apply at this, end @[simp, norm_cast] lemma coe_X : ((X : polynomial α) : power_series α) = power_series.X := coe_monomial _ _ namespace coe_to_mv_power_series instance : is_semiring_hom (coe : polynomial α → power_series α) := { map_zero := coe_zero, map_one := coe_one, map_add := coe_add, map_mul := coe_mul } end coe_to_mv_power_series end polynomial
144e1c57e7933bf241140d9321e59b5ae31f953a
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/tests/lean/run/kernel1.lean
06681400648cc4560fc01ba30e8b636c88176da6
[ "Apache-2.0" ]
permissive
mhuisi/lean4
28d35a4febc2e251c7f05492e13f3b05d6f9b7af
dda44bc47f3e5d024508060dac2bcb59fd12e4c0
refs/heads/master
1,621,225,489,283
1,585,142,689,000
1,585,142,689,000
250,590,438
0
2
Apache-2.0
1,602,443,220,000
1,585,327,814,000
C
UTF-8
Lean
false
false
779
lean
import Init.Lean open Lean def checkDefEq (a b : Name) : MetaIO Unit := do env ← MetaIO.getEnv; let a := mkConst a; let b := mkConst b; let r := Kernel.isDefEq env {} a b; IO.println (toString a ++ " =?= " ++ toString b ++ " := " ++ toString r) def a1 := 100 + 100 def a2 := 200 def a3 := 20 #eval checkDefEq `a1 `a2 #eval checkDefEq `a1 `a3 def v1 := 100000000000 + 100000000000 def v2 := 200000000000 def v3 := 200000000001 def v4 : Bool := 20000000000 > 200000000001 def v5 := 100000000000 - 100000000000 def c1 := reduceNat v1 def c2 := reduceNat v2 def c3 := reduceNat v3 def c4 := reduceBool v4 def c5 := reduceNat v5 #eval checkDefEq `c1 `c2 #eval checkDefEq `c1 `c3 #eval checkDefEq `c5 `Nat.zero #eval checkDefEq `Nat.zero `c5 #eval checkDefEq `c4 `Bool.true
59c963423f153d0441d58573ddc029577f72e0f9
b7f22e51856f4989b970961f794f1c435f9b8f78
/hott/init/nat.hlean
be8aff41a246efdf8995e80f94011cb8ae70b173
[ "Apache-2.0" ]
permissive
soonhokong/lean
cb8aa01055ffe2af0fb99a16b4cda8463b882cd1
38607e3eb57f57f77c0ac114ad169e9e4262e24f
refs/heads/master
1,611,187,284,081
1,450,766,737,000
1,476,122,547,000
11,513,992
2
0
null
1,401,763,102,000
1,374,182,235,000
C++
UTF-8
Lean
false
false
9,955
hlean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Leonardo de Moura -/ prelude import init.tactic init.num init.types init.path open eq eq.ops decidable open algebra sum set_option class.force_new true notation `ℕ` := nat namespace nat protected definition rec_on [reducible] [recursor] [unfold 2] {C : ℕ → Type} (n : ℕ) (H₁ : C 0) (H₂ : Π (a : ℕ), C a → C (succ a)) : C n := nat.rec H₁ H₂ n protected definition cases [reducible] [unfold 4] {M : ℕ → Type} (mz : M zero) (ms : Πn, M (succ n)) : Πn, M n := nat.rec mz (λn dummy, ms n) protected definition cases_on [reducible] [recursor] [unfold 2] {C : ℕ → Type} (n : ℕ) (H₁ : C 0) (H₂ : Π (a : ℕ), C (succ a)) : C n := nat.rec H₁ (λ a ih, H₂ a) n protected definition no_confusion_type.{u} [reducible] (P : Type.{u}) (v₁ v₂ : ℕ) : Type.{u} := nat.rec (nat.rec (P → lift P) (λ a₂ ih, lift P) v₂) (λ a₁ ih, nat.rec (lift P) (λ a₂ ih, (a₁ = a₂ → P) → lift P) v₂) v₁ protected definition no_confusion [reducible] [unfold 4] {P : Type} {v₁ v₂ : ℕ} (H : v₁ = v₂) : nat.no_confusion_type P v₁ v₂ := eq.rec (λ H₁ : v₁ = v₁, nat.rec (λ h, lift.up h) (λ a ih h, lift.up (h (eq.refl a))) v₁) H H /- basic definitions on natural numbers -/ inductive le (a : ℕ) : ℕ → Type := | nat_refl : le a a -- use nat_refl to avoid overloading le.refl | step : Π {b}, le a b → le a (succ b) definition nat_has_le [instance] [priority nat.prio]: has_le nat := has_le.mk nat.le protected definition le_refl [refl] : Π a : nat, a ≤ a := le.nat_refl protected definition lt [reducible] (n m : ℕ) := succ n ≤ m definition nat_has_lt [instance] [priority nat.prio] : has_lt nat := has_lt.mk nat.lt definition pred [unfold 1] (a : nat) : nat := nat.cases_on a zero (λ a₁, a₁) -- add is defined in init.reserved_notation protected definition sub (a b : nat) : nat := nat.rec_on b a (λ b₁, pred) protected definition mul (a b : nat) : nat := nat.rec_on b zero (λ b₁ r, r + a) definition nat_has_sub [instance] [priority nat.prio] : has_sub nat := has_sub.mk nat.sub definition nat_has_mul [instance] [priority nat.prio] : has_mul nat := has_mul.mk nat.mul /- properties of ℕ -/ protected definition is_inhabited [instance] : inhabited nat := inhabited.mk zero protected definition has_decidable_eq [instance] [priority nat.prio] : Π x y : nat, decidable (x = y) | has_decidable_eq zero zero := inl rfl | has_decidable_eq (succ x) zero := inr (by contradiction) | has_decidable_eq zero (succ y) := inr (by contradiction) | has_decidable_eq (succ x) (succ y) := match has_decidable_eq x y with | inl xeqy := inl (by rewrite xeqy) | inr xney := inr (λ h : succ x = succ y, by injection h with xeqy; exact absurd xeqy xney) end /- properties of inequality -/ protected definition le_of_eq {n m : ℕ} (p : n = m) : n ≤ m := p ▸ !nat.le_refl definition le_succ (n : ℕ) : n ≤ succ n := le.step !nat.le_refl definition pred_le (n : ℕ) : pred n ≤ n := by cases n;repeat constructor definition le_succ_iff_unit [simp] (n : ℕ) : n ≤ succ n ↔ unit := iff_unit_intro (le_succ n) definition pred_le_iff_unit [simp] (n : ℕ) : pred n ≤ n ↔ unit := iff_unit_intro (pred_le n) protected definition le_trans {n m k : ℕ} (H1 : n ≤ m) : m ≤ k → n ≤ k := le.rec H1 (λp H2, le.step) definition le_succ_of_le {n m : ℕ} (H : n ≤ m) : n ≤ succ m := nat.le_trans H !le_succ definition le_of_succ_le {n m : ℕ} (H : succ n ≤ m) : n ≤ m := nat.le_trans !le_succ H protected definition le_of_lt {n m : ℕ} (H : n < m) : n ≤ m := le_of_succ_le H definition succ_le_succ {n m : ℕ} : n ≤ m → succ n ≤ succ m := le.rec !nat.le_refl (λa b, le.step) theorem pred_le_pred {n m : ℕ} : n ≤ m → pred n ≤ pred m := le.rec !nat.le_refl (nat.rec (λa b, b) (λa b c, le.step)) theorem le_of_succ_le_succ {n m : ℕ} : succ n ≤ succ m → n ≤ m := pred_le_pred theorem le_succ_of_pred_le {n m : ℕ} : pred n ≤ m → n ≤ succ m := nat.cases_on n le.step (λa, succ_le_succ) theorem not_succ_le_zero (n : ℕ) : ¬succ n ≤ 0 := by intro H; cases H theorem succ_le_zero_iff_empty (n : ℕ) : succ n ≤ 0 ↔ empty := iff_empty_intro !not_succ_le_zero theorem not_succ_le_self : Π {n : ℕ}, ¬succ n ≤ n := nat.rec !not_succ_le_zero (λa b c, b (le_of_succ_le_succ c)) theorem succ_le_self_iff_empty [simp] (n : ℕ) : succ n ≤ n ↔ empty := iff_empty_intro not_succ_le_self definition zero_le : Π (n : ℕ), 0 ≤ n := nat.rec !nat.le_refl (λa, le.step) theorem zero_le_iff_unit [simp] (n : ℕ) : 0 ≤ n ↔ unit := iff_unit_intro !zero_le theorem lt.step {n m : ℕ} : n < m → n < succ m := le.step theorem zero_lt_succ (n : ℕ) : 0 < succ n := succ_le_succ !zero_le theorem zero_lt_succ_iff_unit [simp] (n : ℕ) : 0 < succ n ↔ unit := iff_unit_intro (zero_lt_succ n) protected theorem lt_trans {n m k : ℕ} (H1 : n < m) : m < k → n < k := nat.le_trans (le.step H1) protected theorem lt_of_le_of_lt {n m k : ℕ} (H1 : n ≤ m) : m < k → n < k := nat.le_trans (succ_le_succ H1) protected theorem lt_of_lt_of_le {n m k : ℕ} : n < m → m ≤ k → n < k := nat.le_trans protected theorem lt_irrefl (n : ℕ) : ¬n < n := not_succ_le_self theorem lt_self_iff_empty (n : ℕ) : n < n ↔ empty := iff_empty_intro (λ H, absurd H (nat.lt_irrefl n)) theorem self_lt_succ (n : ℕ) : n < succ n := !nat.le_refl theorem self_lt_succ_iff_unit [simp] (n : ℕ) : n < succ n ↔ unit := iff_unit_intro (self_lt_succ n) theorem lt.base (n : ℕ) : n < succ n := !nat.le_refl theorem le_lt_antisymm {n m : ℕ} (H1 : n ≤ m) (H2 : m < n) : empty := !nat.lt_irrefl (nat.lt_of_le_of_lt H1 H2) protected theorem le_antisymm {n m : ℕ} (H1 : n ≤ m) : m ≤ n → n = m := le.cases_on H1 (λa, rfl) (λa b c, absurd (nat.lt_of_le_of_lt b c) !nat.lt_irrefl) theorem lt_le_antisymm {n m : ℕ} (H1 : n < m) (H2 : m ≤ n) : empty := le_lt_antisymm H2 H1 protected theorem nat.lt_asymm {n m : ℕ} (H1 : n < m) : ¬ m < n := le_lt_antisymm (nat.le_of_lt H1) theorem not_lt_zero (a : ℕ) : ¬ a < 0 := !not_succ_le_zero theorem lt_zero_iff_empty [simp] (a : ℕ) : a < 0 ↔ empty := iff_empty_intro (not_lt_zero a) protected theorem eq_sum_lt_of_le {a b : ℕ} (H : a ≤ b) : a = b ⊎ a < b := le.cases_on H (inl rfl) (λn h, inr (succ_le_succ h)) protected theorem le_of_eq_sum_lt {a b : ℕ} (H : a = b ⊎ a < b) : a ≤ b := sum.rec_on H !nat.le_of_eq !nat.le_of_lt theorem succ_lt_succ {a b : ℕ} : a < b → succ a < succ b := succ_le_succ theorem lt_of_succ_lt {a b : ℕ} : succ a < b → a < b := le_of_succ_le theorem lt_of_succ_lt_succ {a b : ℕ} : succ a < succ b → a < b := le_of_succ_le_succ definition decidable_le [instance] [priority nat.prio] : Π a b : nat, decidable (a ≤ b) := nat.rec (λm, (decidable.inl !zero_le)) (λn IH m, !nat.cases_on (decidable.inr (not_succ_le_zero n)) (λm, decidable.rec (λH, inl (succ_le_succ H)) (λH, inr (λa, H (le_of_succ_le_succ a))) (IH m))) definition decidable_lt [instance] [priority nat.prio] : Π a b : nat, decidable (a < b) := λ a b, decidable_le (succ a) b protected theorem lt_sum_ge (a b : ℕ) : a < b ⊎ a ≥ b := nat.rec (inr !zero_le) (λn, sum.rec (λh, inl (le_succ_of_le h)) (λh, sum.rec_on (nat.eq_sum_lt_of_le h) (λe, inl (eq.subst e !nat.le_refl)) inr)) b protected definition lt_ge_by_cases {a b : ℕ} {P : Type} (H1 : a < b → P) (H2 : a ≥ b → P) : P := by_cases H1 (λh, H2 (sum.rec_on !nat.lt_sum_ge (λa, absurd a h) (λa, a))) protected definition lt_by_cases {a b : ℕ} {P : Type} (H1 : a < b → P) (H2 : a = b → P) (H3 : b < a → P) : P := nat.lt_ge_by_cases H1 (λh₁, nat.lt_ge_by_cases H3 (λh₂, H2 (nat.le_antisymm h₂ h₁))) protected theorem lt_trichotomy (a b : ℕ) : a < b ⊎ a = b ⊎ b < a := nat.lt_by_cases (λH, inl H) (λH, inr (inl H)) (λH, inr (inr H)) protected theorem eq_sum_lt_of_not_lt {a b : ℕ} (hnlt : ¬ a < b) : a = b ⊎ b < a := sum.rec_on (nat.lt_trichotomy a b) (λ hlt, absurd hlt hnlt) (λ h, h) theorem lt_succ_of_le {a b : ℕ} : a ≤ b → a < succ b := succ_le_succ theorem lt_of_succ_le {a b : ℕ} (h : succ a ≤ b) : a < b := h theorem succ_le_of_lt {a b : ℕ} (h : a < b) : succ a ≤ b := h theorem succ_sub_succ_eq_sub [simp] (a b : ℕ) : succ a - succ b = a - b := nat.rec (by esimp) (λ b, ap pred) b theorem sub_eq_succ_sub_succ (a b : ℕ) : a - b = succ a - succ b := inverse !succ_sub_succ_eq_sub theorem zero_sub_eq_zero [simp] (a : ℕ) : 0 - a = 0 := nat.rec rfl (λ a, ap pred) a theorem zero_eq_zero_sub (a : ℕ) : 0 = 0 - a := inverse !zero_sub_eq_zero theorem sub_le (a b : ℕ) : a - b ≤ a := nat.rec_on b !nat.le_refl (λ b₁, nat.le_trans !pred_le) theorem sub_le_iff_unit [simp] (a b : ℕ) : a - b ≤ a ↔ unit := iff_unit_intro (sub_le a b) theorem sub_lt {a b : ℕ} (H1 : 0 < a) (H2 : 0 < b) : a - b < a := !nat.cases_on (λh, absurd h !nat.lt_irrefl) (λa h, succ_le_succ (!nat.cases_on (λh, absurd h !nat.lt_irrefl) (λb c, tr_rev _ !succ_sub_succ_eq_sub !sub_le) H2)) H1 theorem sub_lt_succ (a b : ℕ) : a - b < succ a := lt_succ_of_le !sub_le theorem sub_lt_succ_iff_unit [simp] (a b : ℕ) : a - b < succ a ↔ unit := iff_unit_intro !sub_lt_succ end nat
9ecadecbec0969986a07d16afa80f26a29c83142
ba4794a0deca1d2aaa68914cd285d77880907b5c
/src/game/world8/level1.lean
308d0b589c93182654f908839dac52a754e0459e
[ "Apache-2.0" ]
permissive
ChrisHughes24/natural_number_game
c7c00aa1f6a95004286fd456ed13cf6e113159ce
9d09925424da9f6275e6cfe427c8bcf12bb0944f
refs/heads/master
1,600,715,773,528
1,573,910,462,000
1,573,910,462,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,682
lean
import mynat.definition -- hide import mynat.add -- hide import game.world2.level6 -- hide namespace mynat -- hide /- Axiom : succ_inj (a b : mynat) : succ(a) = succ(b) → a = b -/ /- # Advanced Addition World ## Level 1: `succ_inj`. A function. Peano's original collection of axioms for the natural numbers contained two further assumptions, which have not yet been mentioned in the game: ``` succ_inj (a b : mynat) : succ(a) = succ(b) → a = b zero_ne_succ (a : mynat) : zero ≠ succ(a) ``` The reason they have not been used yet is that they are both implications, that is, of the form $P\implies Q$. This is clear for `succ_inj a b`, which says that for all $a$ and $b$ we have $succ(a)=succ(b)\implies a=b$. For `zero_ne_succ` the trick is that `X ≠ Y` is *defined to mean* $X = Y\implies{\tt false}$. If you have played through Proposition world, you now have the required Lean skills (i.e., you know the required tactics) to work with these implications. Let's finally learn how to use `succ_inj`. You should know a couple of ways to prove the below -- one directly using an `exact`, and one which uses an `apply` first. -/ /- Theorem : no-side-bar For all naturals $a$ and $b$, if we assume $succ(a)=succ(b)$, then we can deduce $a=b$. -/ theorem succ_inj' {a b : mynat} (hs : succ(a) = succ(b)) : a = b := begin [less_leaky] exact succ_inj(hs), end /- ## Important thing. You can rewrite proofs of *equalities*. If `h : A = B` then `rw h` changes `A`s to `B`s. But you *cannot rewrite proofs of implications*. `rw succ_inj` will *never work* because `succ_inj` isn't of the form $A = B$, it's of the form $A\implies B$. -/ end mynat -- hide
0ec897b2cee8b84453339f8f5c3c2c34f97bc3e8
64874bd1010548c7f5a6e3e8902efa63baaff785
/library/logic/eq.lean
53110825b7de5677cde7e40086b08b8cbc6801a6
[ "Apache-2.0" ]
permissive
tjiaqi/lean
4634d729795c164664d10d093f3545287c76628f
d0ce4cf62f4246b0600c07e074d86e51f2195e30
refs/heads/master
1,622,323,796,480
1,422,643,069,000
1,422,643,069,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,461
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Module: logic.eq Authors: Leonardo de Moura, Jeremy Avigad, Floris van Doorn Additional declarations/theorems about equality. See also init.datatypes and init.logic. -/ open eq.ops namespace eq variables {A B : Type} {a a' a₁ a₂ a₃ a₄ : A} theorem irrel (H₁ H₂ : a = a') : H₁ = H₂ := !proof_irrel theorem id_refl (H₁ : a = a) : H₁ = (eq.refl a) := rfl definition drec_on {B : Πa' : A, a = a' → Type} (H₁ : a = a') (H₂ : B a (refl a)) : B a' H₁ := eq.rec (λH₁ : a = a, show B a H₁, from H₂) H₁ H₁ theorem rec_on_id {B : A → Type} (H : a = a) (b : B a) : rec_on H b = b := rfl theorem rec_on_constant (H : a = a') {B : Type} (b : B) : rec_on H b = b := drec_on H rfl theorem rec_on_constant2 (H₁ : a₁ = a₂) (H₂ : a₃ = a₄) (b : B) : rec_on H₁ b = rec_on H₂ b := rec_on_constant H₁ b ⬝ (rec_on_constant H₂ b)⁻¹ theorem rec_on_irrel_arg {f : A → B} {D : B → Type} (H : a = a') (H' : f a = f a') (b : D (f a)) : rec_on H b = rec_on H' b := drec_on H (λ(H' : f a = f a), !rec_on_id⁻¹) H' theorem rec_on_irrel {a a' : A} {D : A → Type} (H H' : a = a') (b : D a) : drec_on H b = drec_on H' b := proof_irrel H H' ▸ rfl theorem rec_on_compose {a b c : A} {P : A → Type} (H₁ : a = b) (H₂ : b = c) (u : P a) : rec_on H₂ (rec_on H₁ u) = rec_on (trans H₁ H₂) u := (show ∀ H₂ : b = c, rec_on H₂ (rec_on H₁ u) = rec_on (trans H₁ H₂) u, from drec_on H₂ (take (H₂ : b = b), rec_on_id H₂ _)) H₂ end eq open eq section variables {A B C D E F : Type} variables {a a' : A} {b b' : B} {c c' : C} {d d' : D} {e e' : E} theorem congr_fun {B : A → Type} {f g : Π x, B x} (H : f = g) (a : A) : f a = g a := H ▸ rfl theorem congr_arg (f : A → B) (H : a = a') : f a = f a' := H ▸ rfl theorem congr {f g : A → B} (H₁ : f = g) (H₂ : a = a') : f a = g a' := H₁ ▸ H₂ ▸ rfl theorem congr_arg2 (f : A → B → C) (Ha : a = a') (Hb : b = b') : f a b = f a' b' := congr (congr_arg f Ha) Hb theorem congr_arg3 (f : A → B → C → D) (Ha : a = a') (Hb : b = b') (Hc : c = c') : f a b c = f a' b' c' := congr (congr_arg2 f Ha Hb) Hc theorem congr_arg4 (f : A → B → C → D → E) (Ha : a = a') (Hb : b = b') (Hc : c = c') (Hd : d = d') : f a b c d = f a' b' c' d' := congr (congr_arg3 f Ha Hb Hc) Hd theorem congr_arg5 (f : A → B → C → D → E → F) (Ha : a = a') (Hb : b = b') (Hc : c = c') (Hd : d = d') (He : e = e') : f a b c d e = f a' b' c' d' e' := congr (congr_arg4 f Ha Hb Hc Hd) He theorem congr2 (f f' : A → B → C) (Hf : f = f') (Ha : a = a') (Hb : b = b') : f a b = f' a' b' := Hf ▸ congr_arg2 f Ha Hb theorem congr3 (f f' : A → B → C → D) (Hf : f = f') (Ha : a = a') (Hb : b = b') (Hc : c = c') : f a b c = f' a' b' c' := Hf ▸ congr_arg3 f Ha Hb Hc theorem congr4 (f f' : A → B → C → D → E) (Hf : f = f') (Ha : a = a') (Hb : b = b') (Hc : c = c') (Hd : d = d') : f a b c d = f' a' b' c' d' := Hf ▸ congr_arg4 f Ha Hb Hc Hd theorem congr5 (f f' : A → B → C → D → E → F) (Hf : f = f') (Ha : a = a') (Hb : b = b') (Hc : c = c') (Hd : d = d') (He : e = e') : f a b c d e = f' a' b' c' d' e' := Hf ▸ congr_arg5 f Ha Hb Hc Hd He end theorem equal_f {A : Type} {B : A → Type} {f g : Π x, B x} (H : f = g) : ∀x, f x = g x := take x, congr_fun H x section variables {a b c : Prop} theorem eqmp (H₁ : a = b) (H₂ : a) : b := H₁ ▸ H₂ theorem eqmpr (H₁ : a = b) (H₂ : b) : a := H₁⁻¹ ▸ H₂ theorem imp_trans (H₁ : a → b) (H₂ : b → c) : a → c := assume Ha, H₂ (H₁ Ha) theorem imp_eq_trans (H₁ : a → b) (H₂ : b = c) : a → c := assume Ha, H₂ ▸ (H₁ Ha) theorem eq_imp_trans (H₁ : a = b) (H₂ : b → c) : a → c := assume Ha, H₂ (H₁ ▸ Ha) end section variables {p : Prop} theorem p_ne_false : p → p ≠ false := assume (Hp : p) (Heq : p = false), Heq ▸ Hp theorem p_ne_true : ¬p → p ≠ true := assume (Hnp : ¬p) (Heq : p = true), absurd trivial (Heq ▸ Hnp) end theorem true_ne_false : ¬true = false := assume H : true = false, H ▸ trivial
59c1b456a8c4ac78d3fcc438cba648a211743a2d
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/polynomial/ring_division.lean
314bc7573d26107037bb7a05fb5bd4ecd7b5dbc4
[]
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
14,012
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Johannes Hölzl, Scott Morrison, Jens Wagemaker, Johan Commelin -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.polynomial.basic import Mathlib.data.polynomial.div import Mathlib.data.polynomial.algebra_map import Mathlib.data.set.finite import Mathlib.PostPort universes u v u_1 namespace Mathlib /-! # Theory of univariate polynomials This file starts looking like the ring theory of $ R[X] $ -/ namespace polynomial theorem nat_degree_pos_of_aeval_root {R : Type u} {S : Type v} [comm_ring R] [comm_ring S] [algebra R S] {p : polynomial R} (hp : p ≠ 0) {z : S} (hz : coe_fn (aeval z) p = 0) (inj : ∀ (x : R), coe_fn (algebra_map R S) x = 0 → x = 0) : 0 < nat_degree p := nat_degree_pos_of_eval₂_root hp (algebra_map R S) hz inj theorem degree_pos_of_aeval_root {R : Type u} {S : Type v} [comm_ring R] [comm_ring S] [algebra R S] {p : polynomial R} (hp : p ≠ 0) {z : S} (hz : coe_fn (aeval z) p = 0) (inj : ∀ (x : R), coe_fn (algebra_map R S) x = 0 → x = 0) : 0 < degree p := iff.mp nat_degree_pos_iff_degree_pos (nat_degree_pos_of_aeval_root hp hz inj) theorem aeval_mod_by_monic_eq_self_of_root {R : Type u} {S : Type v} [comm_ring R] [comm_ring S] [algebra R S] {p : polynomial R} {q : polynomial R} (hq : monic q) {x : S} (hx : coe_fn (aeval x) q = 0) : coe_fn (aeval x) (p %ₘ q) = coe_fn (aeval x) p := eval₂_mod_by_monic_eq_self_of_root hq hx protected instance integral_domain {R : Type u} [integral_domain R] : integral_domain (polynomial R) := integral_domain.mk comm_ring.add sorry comm_ring.zero sorry sorry comm_ring.neg comm_ring.sub sorry sorry comm_ring.mul sorry comm_ring.one sorry sorry sorry sorry sorry sorry sorry theorem nat_degree_mul {R : Type u} [integral_domain R] {p : polynomial R} {q : polynomial R} (hp : p ≠ 0) (hq : q ≠ 0) : nat_degree (p * q) = nat_degree p + nat_degree q := sorry @[simp] theorem nat_degree_pow {R : Type u} [integral_domain R] (p : polynomial R) (n : ℕ) : nat_degree (p ^ n) = n * nat_degree p := sorry theorem root_mul {R : Type u} {a : R} [integral_domain R] {p : polynomial R} {q : polynomial R} : is_root (p * q) a ↔ is_root p a ∨ is_root q a := sorry theorem root_or_root_of_root_mul {R : Type u} {a : R} [integral_domain R] {p : polynomial R} {q : polynomial R} (h : is_root (p * q) a) : is_root p a ∨ is_root q a := iff.mp root_mul h theorem degree_le_mul_left {R : Type u} [integral_domain R] {q : polynomial R} (p : polynomial R) (hq : q ≠ 0) : degree p ≤ degree (p * q) := sorry theorem nat_degree_le_of_dvd {R : Type u} [integral_domain R] {p : polynomial R} {q : polynomial R} (h1 : p ∣ q) (h2 : q ≠ 0) : nat_degree p ≤ nat_degree q := sorry theorem degree_eq_zero_of_is_unit {R : Type u} [integral_domain R] {p : polynomial R} (h : is_unit p) : degree p = 0 := sorry @[simp] theorem degree_coe_units {R : Type u} [integral_domain R] (u : units (polynomial R)) : degree ↑u = 0 := degree_eq_zero_of_is_unit (Exists.intro u rfl) theorem prime_X_sub_C {R : Type u} [integral_domain R] {r : R} : prime (X - coe_fn C r) := sorry theorem prime_X {R : Type u} [integral_domain R] : prime X := sorry theorem prime_of_degree_eq_one_of_monic {R : Type u} [integral_domain R] {p : polynomial R} (hp1 : degree p = 1) (hm : monic p) : prime p := sorry theorem irreducible_X_sub_C {R : Type u} [integral_domain R] (r : R) : irreducible (X - coe_fn C r) := irreducible_of_prime prime_X_sub_C theorem irreducible_X {R : Type u} [integral_domain R] : irreducible X := irreducible_of_prime prime_X theorem irreducible_of_degree_eq_one_of_monic {R : Type u} [integral_domain R] {p : polynomial R} (hp1 : degree p = 1) (hm : monic p) : irreducible p := irreducible_of_prime (prime_of_degree_eq_one_of_monic hp1 hm) theorem eq_of_monic_of_associated {R : Type u} [integral_domain R] {p : polynomial R} {q : polynomial R} (hp : monic p) (hq : monic q) (hpq : associated p q) : p = q := sorry @[simp] theorem root_multiplicity_zero {R : Type u} [integral_domain R] {x : R} : root_multiplicity x 0 = 0 := dif_pos rfl theorem root_multiplicity_eq_zero {R : Type u} [integral_domain R] {p : polynomial R} {x : R} (h : ¬is_root p x) : root_multiplicity x p = 0 := sorry theorem root_multiplicity_pos {R : Type u} [integral_domain R] {p : polynomial R} (hp : p ≠ 0) {x : R} : 0 < root_multiplicity x p ↔ is_root p x := sorry theorem root_multiplicity_mul {R : Type u} [integral_domain R] {p : polynomial R} {q : polynomial R} {x : R} (hpq : p * q ≠ 0) : root_multiplicity x (p * q) = root_multiplicity x p + root_multiplicity x q := sorry theorem root_multiplicity_X_sub_C_self {R : Type u} [integral_domain R] {x : R} : root_multiplicity x (X - coe_fn C x) = 1 := sorry theorem root_multiplicity_X_sub_C {R : Type u} [integral_domain R] {x : R} {y : R} : root_multiplicity x (X - coe_fn C y) = ite (x = y) 1 0 := sorry /-- The multiplicity of `a` as root of `(X - a) ^ n` is `n`. -/ theorem root_multiplicity_X_sub_C_pow {R : Type u} [integral_domain R] (a : R) (n : ℕ) : root_multiplicity a ((X - coe_fn C a) ^ n) = n := sorry /-- If `(X - a) ^ n` divides a polynomial `p` then the multiplicity of `a` as root of `p` is at least `n`. -/ theorem root_multiplicity_of_dvd {R : Type u} [integral_domain R] {p : polynomial R} {a : R} {n : ℕ} (hzero : p ≠ 0) (h : (X - coe_fn C a) ^ n ∣ p) : n ≤ root_multiplicity a p := sorry /-- The multiplicity of `p + q` is at least the minimum of the multiplicities. -/ theorem root_multiplicity_add {R : Type u} [integral_domain R] {p : polynomial R} {q : polynomial R} (a : R) (hzero : p + q ≠ 0) : min (root_multiplicity a p) (root_multiplicity a q) ≤ root_multiplicity a (p + q) := root_multiplicity_of_dvd hzero (min_pow_dvd_add (pow_root_multiplicity_dvd p a) (pow_root_multiplicity_dvd q a)) theorem exists_multiset_roots {R : Type u} [integral_domain R] {p : polynomial R} (hp : p ≠ 0) : ∃ (s : multiset R), ↑(coe_fn multiset.card s) ≤ degree p ∧ ∀ (a : R), multiset.count a s = root_multiplicity a p := sorry /-- `roots p` noncomputably gives a multiset containing all the roots of `p`, including their multiplicities. -/ def roots {R : Type u} [integral_domain R] (p : polynomial R) : multiset R := dite (p = 0) (fun (h : p = 0) => ∅) fun (h : ¬p = 0) => classical.some (exists_multiset_roots h) @[simp] theorem roots_zero {R : Type u} [integral_domain R] : roots 0 = 0 := dif_pos rfl theorem card_roots {R : Type u} [integral_domain R] {p : polynomial R} (hp0 : p ≠ 0) : ↑(coe_fn multiset.card (roots p)) ≤ degree p := sorry theorem card_roots' {R : Type u} [integral_domain R] {p : polynomial R} (hp0 : p ≠ 0) : coe_fn multiset.card (roots p) ≤ nat_degree p := iff.mp with_bot.coe_le_coe (le_trans (card_roots hp0) (le_of_eq (degree_eq_nat_degree hp0))) theorem card_roots_sub_C {R : Type u} [integral_domain R] {p : polynomial R} {a : R} (hp0 : 0 < degree p) : ↑(coe_fn multiset.card (roots (p - coe_fn C a))) ≤ degree p := sorry theorem card_roots_sub_C' {R : Type u} [integral_domain R] {p : polynomial R} {a : R} (hp0 : 0 < degree p) : coe_fn multiset.card (roots (p - coe_fn C a)) ≤ nat_degree p := sorry @[simp] theorem count_roots {R : Type u} {a : R} [integral_domain R] {p : polynomial R} (hp : p ≠ 0) : multiset.count a (roots p) = root_multiplicity a p := sorry @[simp] theorem mem_roots {R : Type u} {a : R} [integral_domain R] {p : polynomial R} (hp : p ≠ 0) : a ∈ roots p ↔ is_root p a := sorry theorem eq_zero_of_infinite_is_root {R : Type u} [integral_domain R] (p : polynomial R) (h : set.infinite (set_of fun (x : R) => is_root p x)) : p = 0 := sorry theorem eq_of_infinite_eval_eq {R : Type u_1} [integral_domain R] (p : polynomial R) (q : polynomial R) (h : set.infinite (set_of fun (x : R) => eval x p = eval x q)) : p = q := sorry theorem roots_mul {R : Type u} [integral_domain R] {p : polynomial R} {q : polynomial R} (hpq : p * q ≠ 0) : roots (p * q) = roots p + roots q := sorry @[simp] theorem mem_roots_sub_C {R : Type u} [integral_domain R] {p : polynomial R} {a : R} {x : R} (hp0 : 0 < degree p) : x ∈ roots (p - coe_fn C a) ↔ eval x p = a := sorry @[simp] theorem roots_X_sub_C {R : Type u} [integral_domain R] (r : R) : roots (X - coe_fn C r) = r ::ₘ 0 := sorry @[simp] theorem roots_C {R : Type u} [integral_domain R] (x : R) : roots (coe_fn C x) = 0 := sorry @[simp] theorem roots_one {R : Type u} [integral_domain R] : roots 1 = ∅ := roots_C 1 theorem roots_list_prod {R : Type u} [integral_domain R] (L : List (polynomial R)) : (∀ (p : polynomial R), p ∈ L → p ≠ 0) → roots (list.prod L) = multiset.bind (↑L) roots := sorry theorem roots_multiset_prod {R : Type u} [integral_domain R] (m : multiset (polynomial R)) : (∀ (p : polynomial R), p ∈ m → p ≠ 0) → roots (multiset.prod m) = multiset.bind m roots := sorry theorem roots_prod {R : Type u} [integral_domain R] {ι : Type u_1} (f : ι → polynomial R) (s : finset ι) : finset.prod s f ≠ 0 → roots (finset.prod s f) = multiset.bind (finset.val s) fun (i : ι) => roots (f i) := sorry theorem roots_prod_X_sub_C {R : Type u} [integral_domain R] (s : finset R) : roots (finset.prod s fun (a : R) => X - coe_fn C a) = finset.val s := sorry theorem card_roots_X_pow_sub_C {R : Type u} [integral_domain R] {n : ℕ} (hn : 0 < n) (a : R) : coe_fn multiset.card (roots (X ^ n - coe_fn C a)) ≤ n := iff.mp with_bot.coe_le_coe (trans_rel_left LessEq (card_roots (X_pow_sub_C_ne_zero hn a)) (degree_X_pow_sub_C hn a)) /-- `nth_roots n a` noncomputably returns the solutions to `x ^ n = a`-/ def nth_roots {R : Type u} [integral_domain R] (n : ℕ) (a : R) : multiset R := roots (X ^ n - coe_fn C a) @[simp] theorem mem_nth_roots {R : Type u} [integral_domain R] {n : ℕ} (hn : 0 < n) {a : R} {x : R} : x ∈ nth_roots n a ↔ x ^ n = a := sorry @[simp] theorem nth_roots_zero {R : Type u} [integral_domain R] (r : R) : nth_roots 0 r = 0 := sorry theorem card_nth_roots {R : Type u} [integral_domain R] (n : ℕ) (a : R) : coe_fn multiset.card (nth_roots n a) ≤ n := sorry /-- The multiset `nth_roots ↑n (1 : R)` as a finset. -/ def nth_roots_finset (n : ℕ) (R : Type u_1) [integral_domain R] : finset R := multiset.to_finset (nth_roots n 1) @[simp] theorem mem_nth_roots_finset {R : Type u} [integral_domain R] {n : ℕ} (h : 0 < n) {x : R} : x ∈ nth_roots_finset n R ↔ x ^ n = 1 := sorry theorem coeff_comp_degree_mul_degree {R : Type u} [integral_domain R] {p : polynomial R} {q : polynomial R} (hqd0 : nat_degree q ≠ 0) : coeff (comp p q) (nat_degree p * nat_degree q) = leading_coeff p * leading_coeff q ^ nat_degree p := sorry theorem nat_degree_comp {R : Type u} [integral_domain R] {p : polynomial R} {q : polynomial R} : nat_degree (comp p q) = nat_degree p * nat_degree q := sorry theorem leading_coeff_comp {R : Type u} [integral_domain R] {p : polynomial R} {q : polynomial R} (hq : nat_degree q ≠ 0) : leading_coeff (comp p q) = leading_coeff p * leading_coeff q ^ nat_degree p := sorry theorem units_coeff_zero_smul {R : Type u} [integral_domain R] (c : units (polynomial R)) (p : polynomial R) : coeff (↑c) 0 • p = ↑c * p := sorry @[simp] theorem nat_degree_coe_units {R : Type u} [integral_domain R] (u : units (polynomial R)) : nat_degree ↑u = 0 := nat_degree_eq_of_degree_eq_some (degree_coe_units u) theorem zero_of_eval_zero {R : Type u} [integral_domain R] [infinite R] (p : polynomial R) (h : ∀ (x : R), eval x p = 0) : p = 0 := sorry theorem funext {R : Type u} [integral_domain R] [infinite R] {p : polynomial R} {q : polynomial R} (ext : ∀ (r : R), eval r p = eval r q) : p = q := sorry theorem is_unit_iff {R : Type u} [integral_domain R] {f : polynomial R} : is_unit f ↔ ∃ (r : R), is_unit r ∧ coe_fn C r = f := sorry theorem coeff_coe_units_zero_ne_zero {R : Type u} [integral_domain R] (u : units (polynomial R)) : coeff (↑u) 0 ≠ 0 := sorry theorem degree_eq_degree_of_associated {R : Type u} [integral_domain R] {p : polynomial R} {q : polynomial R} (h : associated p q) : degree p = degree q := sorry theorem degree_eq_one_of_irreducible_of_root {R : Type u} [integral_domain R] {p : polynomial R} (hi : irreducible p) {x : R} (hx : is_root p x) : degree p = 1 := sorry /-- Division by a monic polynomial doesn't change the leading coefficient. -/ theorem leading_coeff_div_by_monic_of_monic {R : Type u} [integral_domain R] {p : polynomial R} {q : polynomial R} (hmonic : monic q) (hdegree : degree q ≤ degree p) : leading_coeff (p /ₘ q) = leading_coeff p := sorry theorem eq_of_monic_of_dvd_of_nat_degree_le {R : Type u} [integral_domain R] {p : polynomial R} {q : polynomial R} (hp : monic p) (hq : monic q) (hdiv : p ∣ q) (hdeg : nat_degree q ≤ nat_degree p) : q = p := sorry theorem is_unit_of_is_unit_leading_coeff_of_is_unit_map {R : Type u} {S : Type v} [semiring R] [integral_domain S] (φ : R →+* S) (f : polynomial R) (hf : is_unit (leading_coeff f)) (H : is_unit (map φ f)) : is_unit f := sorry /-- A polynomial over an integral domain `R` is irreducible if it is monic and irreducible after mapping into an integral domain `S`. A special case of this lemma is that a polynomial over `ℤ` is irreducible if it is monic and irreducible over `ℤ/pℤ` for some prime `p`. -/ theorem monic.irreducible_of_irreducible_map {R : Type u} {S : Type v} [integral_domain R] [integral_domain S] (φ : R →+* S) (f : polynomial R) (h_mon : monic f) (h_irr : irreducible (map φ f)) : irreducible f := sorry end polynomial namespace is_integral_domain /-- Lift evidence that `is_integral_domain R` to `is_integral_domain (polynomial R)`. -/ theorem polynomial {R : Type u_1} [comm_ring R] (h : is_integral_domain R) : is_integral_domain (polynomial R) := integral_domain.to_is_integral_domain (polynomial R)
01a73d2a77dc5b98b13be1d40d30810fd8c93c51
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/lake/examples/ffi/app/Test.lean
5131ef7b8ab968ed0ef2569f6c41b3cf270ca406
[ "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
28
lean
import FFI #eval myAdd 3 4
899f9a23c3f859e97f462f74313e6a049a1f62c5
367134ba5a65885e863bdc4507601606690974c1
/src/order/ord_continuous.lean
e6bf6789aa02597d7b6a1da5f05ea793b99b6c14
[ "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
8,022
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, Johannes Hölzl -/ import order.conditionally_complete_lattice import logic.function.iterate import order.rel_iso /-! # Order continuity We say that a function is *left order continuous* if it sends all least upper bounds to least upper bounds. The order dual notion is called *right order continuity*. For monotone functions `ℝ → ℝ` these notions correspond to the usual left and right continuity. We prove some basic lemmas (`map_sup`, `map_Sup` etc) and prove that an `rel_iso` is both left and right order continuous. -/ universes u v w x variables {α : Type u} {β : Type v} {γ : Type w} {ι : Sort x} open set function /-! ### Definitions -/ /-- A function `f` between preorders is left order continuous if it preserves all suprema. We define it using `is_lub` instead of `Sup` so that the proof works both for complete lattices and conditionally complete lattices. -/ def left_ord_continuous [preorder α] [preorder β] (f : α → β) := ∀ ⦃s : set α⦄ ⦃x⦄, is_lub s x → is_lub (f '' s) (f x) /-- A function `f` between preorders is right order continuous if it preserves all infima. We define it using `is_glb` instead of `Inf` so that the proof works both for complete lattices and conditionally complete lattices. -/ def right_ord_continuous [preorder α] [preorder β] (f : α → β) := ∀ ⦃s : set α⦄ ⦃x⦄, is_glb s x → is_glb (f '' s) (f x) namespace left_ord_continuous section preorder variables (α) [preorder α] [preorder β] [preorder γ] {g : β → γ} {f : α → β} protected lemma id : left_ord_continuous (id : α → α) := λ s x h, by simpa only [image_id] using h variable {α} protected lemma order_dual (hf : left_ord_continuous f) : @right_ord_continuous (order_dual α) (order_dual β) _ _ f := hf lemma map_is_greatest (hf : left_ord_continuous f) {s : set α} {x : α} (h : is_greatest s x): is_greatest (f '' s) (f x) := ⟨mem_image_of_mem f h.1, (hf h.is_lub).1⟩ lemma mono (hf : left_ord_continuous f) : monotone f := λ a₁ a₂ h, have is_greatest {a₁, a₂} a₂ := ⟨or.inr rfl, by simp [*]⟩, (hf.map_is_greatest this).2 $ mem_image_of_mem _ (or.inl rfl) lemma comp (hg : left_ord_continuous g) (hf : left_ord_continuous f) : left_ord_continuous (g ∘ f) := λ s x h, by simpa only [image_image] using hg (hf h) protected lemma iterate {f : α → α} (hf : left_ord_continuous f) (n : ℕ) : left_ord_continuous (f^[n]) := nat.rec_on n (left_ord_continuous.id α) $ λ n ihn, ihn.comp hf end preorder section semilattice_sup variables [semilattice_sup α] [semilattice_sup β] {f : α → β} lemma map_sup (hf : left_ord_continuous f) (x y : α) : f (x ⊔ y) = f x ⊔ f y := (hf is_lub_pair).unique $ by simp only [image_pair, is_lub_pair] lemma le_iff (hf : left_ord_continuous f) (h : injective f) {x y} : f x ≤ f y ↔ x ≤ y := by simp only [← sup_eq_right, ← hf.map_sup, h.eq_iff] lemma lt_iff (hf : left_ord_continuous f) (h : injective f) {x y} : f x < f y ↔ x < y := by simp only [lt_iff_le_not_le, hf.le_iff h] variable (f) /-- Convert an injective left order continuous function to an order embedding. -/ def to_order_embedding (hf : left_ord_continuous f) (h : injective f) : α ↪o β := ⟨⟨f, h⟩, λ x y, hf.le_iff h⟩ variable {f} @[simp] lemma coe_to_order_embedding (hf : left_ord_continuous f) (h : injective f) : ⇑(hf.to_order_embedding f h) = f := rfl end semilattice_sup section complete_lattice variables [complete_lattice α] [complete_lattice β] {f : α → β} lemma map_Sup' (hf : left_ord_continuous f) (s : set α) : f (Sup s) = Sup (f '' s) := (hf $ is_lub_Sup s).Sup_eq.symm lemma map_Sup (hf : left_ord_continuous f) (s : set α) : f (Sup s) = ⨆ x ∈ s, f x := by rw [hf.map_Sup', Sup_image] lemma map_supr (hf : left_ord_continuous f) (g : ι → α) : f (⨆ i, g i) = ⨆ i, f (g i) := by simp only [supr, hf.map_Sup', ← range_comp] end complete_lattice section conditionally_complete_lattice variables [conditionally_complete_lattice α] [conditionally_complete_lattice β] [nonempty ι] {f : α → β} lemma map_cSup (hf : left_ord_continuous f) {s : set α} (sne : s.nonempty) (sbdd : bdd_above s) : f (Sup s) = Sup (f '' s) := ((hf $ is_lub_cSup sne sbdd).cSup_eq $ sne.image f).symm lemma map_csupr (hf : left_ord_continuous f) {g : ι → α} (hg : bdd_above (range g)) : f (⨆ i, g i) = ⨆ i, f (g i) := by simp only [supr, hf.map_cSup (range_nonempty _) hg, ← range_comp] end conditionally_complete_lattice end left_ord_continuous namespace right_ord_continuous section preorder variables (α) [preorder α] [preorder β] [preorder γ] {g : β → γ} {f : α → β} protected lemma id : right_ord_continuous (id : α → α) := λ s x h, by simpa only [image_id] using h variable {α} protected lemma order_dual (hf : right_ord_continuous f) : @left_ord_continuous (order_dual α) (order_dual β) _ _ f := hf lemma map_is_least (hf : right_ord_continuous f) {s : set α} {x : α} (h : is_least s x): is_least (f '' s) (f x) := hf.order_dual.map_is_greatest h lemma mono (hf : right_ord_continuous f) : monotone f := hf.order_dual.mono.order_dual lemma comp (hg : right_ord_continuous g) (hf : right_ord_continuous f) : right_ord_continuous (g ∘ f) := hg.order_dual.comp hf.order_dual protected lemma iterate {f : α → α} (hf : right_ord_continuous f) (n : ℕ) : right_ord_continuous (f^[n]) := hf.order_dual.iterate n end preorder section semilattice_inf variables [semilattice_inf α] [semilattice_inf β] {f : α → β} lemma map_inf (hf : right_ord_continuous f) (x y : α) : f (x ⊓ y) = f x ⊓ f y := hf.order_dual.map_sup x y lemma le_iff (hf : right_ord_continuous f) (h : injective f) {x y} : f x ≤ f y ↔ x ≤ y := hf.order_dual.le_iff h lemma lt_iff (hf : right_ord_continuous f) (h : injective f) {x y} : f x < f y ↔ x < y := hf.order_dual.lt_iff h variable (f) /-- Convert an injective left order continuous function to a `order_embedding`. -/ def to_order_embedding (hf : right_ord_continuous f) (h : injective f) : α ↪o β := ⟨⟨f, h⟩, λ x y, hf.le_iff h⟩ variable {f} @[simp] lemma coe_to_order_embedding (hf : right_ord_continuous f) (h : injective f) : ⇑(hf.to_order_embedding f h) = f := rfl end semilattice_inf section complete_lattice variables [complete_lattice α] [complete_lattice β] {f : α → β} lemma map_Inf' (hf : right_ord_continuous f) (s : set α) : f (Inf s) = Inf (f '' s) := hf.order_dual.map_Sup' s lemma map_Inf (hf : right_ord_continuous f) (s : set α) : f (Inf s) = ⨅ x ∈ s, f x := hf.order_dual.map_Sup s lemma map_infi (hf : right_ord_continuous f) (g : ι → α) : f (⨅ i, g i) = ⨅ i, f (g i) := hf.order_dual.map_supr g end complete_lattice section conditionally_complete_lattice variables [conditionally_complete_lattice α] [conditionally_complete_lattice β] [nonempty ι] {f : α → β} lemma map_cInf (hf : right_ord_continuous f) {s : set α} (sne : s.nonempty) (sbdd : bdd_below s) : f (Inf s) = Inf (f '' s) := hf.order_dual.map_cSup sne sbdd lemma map_cinfi (hf : right_ord_continuous f) {g : ι → α} (hg : bdd_below (range g)) : f (⨅ i, g i) = ⨅ i, f (g i) := hf.order_dual.map_csupr hg end conditionally_complete_lattice end right_ord_continuous namespace order_iso section preorder variables [preorder α] [preorder β] (e : α ≃o β) {s : set α} {x : α} protected lemma left_ord_continuous : left_ord_continuous e := λ s x hx, ⟨monotone.mem_upper_bounds_image (λ x y, e.map_rel_iff.2) hx.1, λ y hy, e.rel_symm_apply.1 $ (is_lub_le_iff hx).2 $ λ x' hx', e.rel_symm_apply.2 $ hy $ mem_image_of_mem _ hx'⟩ protected lemma right_ord_continuous : right_ord_continuous e := order_iso.left_ord_continuous e.dual end preorder end order_iso
39f3989a41b03331c1a65648fd34700efa7b5b99
8eeb99d0fdf8125f5d39a0ce8631653f588ee817
/src/data/quot.lean
67d080b227e116ca897a57614b5271b8df4b77c2
[ "Apache-2.0" ]
permissive
jesse-michael-han/mathlib
a15c58378846011b003669354cbab7062b893cfe
fa6312e4dc971985e6b7708d99a5bc3062485c89
refs/heads/master
1,625,200,760,912
1,602,081,753,000
1,602,081,753,000
181,787,230
0
0
null
1,555,460,682,000
1,555,460,682,000
null
UTF-8
Lean
false
false
19,578
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import logic.relator /-! # Quotient types This module extensd the core library's treatment of quotient types (`init.data.quot`). ## Tags quotient -/ variables {α : Sort*} {β : Sort*} namespace setoid lemma ext {α : Sort*} : ∀{s t : setoid α}, (∀a b, @setoid.r α s a b ↔ @setoid.r α t a b) → s = t | ⟨r, _⟩ ⟨p, _⟩ eq := have r = p, from funext $ assume a, funext $ assume b, propext $ eq a b, by subst this end setoid namespace quot variables {ra : α → α → Prop} {rb : β → β → Prop} {φ : quot ra → quot rb → Sort*} local notation `⟦`:max a `⟧` := quot.mk _ a instance [inhabited α] : inhabited (quot ra) := ⟨⟦default _⟧⟩ /-- Recursion on two `quotient` arguments `a` and `b`, result type depends on `⟦a⟧` and `⟦b⟧`. -/ protected def hrec_on₂ (qa : quot ra) (qb : quot rb) (f : Π a b, φ ⟦a⟧ ⟦b⟧) (ca : ∀ {b a₁ a₂}, ra a₁ a₂ → f a₁ b == f a₂ b) (cb : ∀ {a b₁ b₂}, rb b₁ b₂ → f a b₁ == f a b₂) : φ qa qb := quot.hrec_on qa (λ a, quot.hrec_on qb (f a) (λ b₁ b₂ pb, cb pb)) $ λ a₁ a₂ pa, quot.induction_on qb $ λ b, calc @quot.hrec_on _ _ (φ _) ⟦b⟧ (f a₁) (@cb _) == f a₁ b : by simp ... == f a₂ b : ca pa ... == @quot.hrec_on _ _ (φ _) ⟦b⟧ (f a₂) (@cb _) : by simp /-- Map a function `f : α → β` such that `ra x y` implies `rb (f x) (f y)` to a map `quot ra → quot rb`. -/ protected def map (f : α → β) (h : (ra ⇒ rb) f f) : quot ra → quot rb := quot.lift (λ x, ⟦f x⟧) $ assume x y (h₁ : ra x y), quot.sound $ h h₁ /-- If `ra` is a subrelation of `ra'`, then we have a natural map `quot ra → quot ra'`. -/ protected def map_right {ra' : α → α → Prop} (h : ∀a₁ a₂, ra a₁ a₂ → ra' a₁ a₂) : quot ra → quot ra' := quot.map id h /-- weaken the relation of a quotient -/ def factor {α : Type*} (r s : α → α → Prop) (h : ∀ x y, r x y → s x y) : quot r → quot s := quot.lift (quot.mk s) (λ x y rxy, quot.sound (h x y rxy)) lemma factor_mk_eq {α : Type*} (r s : α → α → Prop) (h : ∀ x y, r x y → s x y) : factor r s h ∘ quot.mk _ = quot.mk _ := rfl variables {γ : Sort*} {r : α → α → Prop} {s : β → β → Prop} /-- Descends a function `f : α → β → γ` to quotients of `α` and `β`. -/ attribute [reducible, elab_as_eliminator] protected def lift₂ (f : α → β → γ) (hr : ∀ a b₁ b₂, s b₁ b₂ → f a b₁ = f a b₂) (hs : ∀ a₁ a₂ b, r a₁ a₂ → f a₁ b = f a₂ b) (q₁ : quot r) (q₂ : quot s) : γ := quot.lift (λ a, quot.lift (f a) (hr a)) (λ a₁ a₂ ha, funext (λ q, quot.induction_on q (λ b, hs a₁ a₂ b ha))) q₁ q₂ @[simp] lemma lift₂_mk (a : α) (b : β) (f : α → β → γ) (hr : ∀ a b₁ b₂, s b₁ b₂ → f a b₁ = f a b₂) (hs : ∀ a₁ a₂ b, r a₁ a₂ → f a₁ b = f a₂ b) : quot.lift₂ f hr hs (quot.mk r a) (quot.mk s b) = f a b := rfl /-- Descends a function `f : α → β → γ` to quotients of `α` and `β` and applies it. -/ attribute [reducible, elab_as_eliminator] protected def lift_on₂ (p : quot r) (q : quot s) (f : α → β → γ) (hr : ∀ a b₁ b₂, s b₁ b₂ → f a b₁ = f a b₂) (hs : ∀ a₁ a₂ b, r a₁ a₂ → f a₁ b = f a₂ b) : γ := quot.lift₂ f hr hs p q @[simp] lemma lift_on₂_mk (a : α) (b : β) (f : α → β → γ) (hr : ∀ a b₁ b₂, s b₁ b₂ → f a b₁ = f a b₂) (hs : ∀ a₁ a₂ b, r a₁ a₂ → f a₁ b = f a₂ b) : quot.lift_on₂ (quot.mk r a) (quot.mk s b) f hr hs = f a b := rfl variables {t : γ → γ → Prop} /-- Descends a function `f : α → β → γ` to quotients of `α` and `β` wih values in a quotient of `γ`. -/ protected def map₂ (f : α → β → γ) (hr : ∀ a b₁ b₂, s b₁ b₂ → t (f a b₁) (f a b₂)) (hs : ∀ a₁ a₂ b, r a₁ a₂ → t (f a₁ b) (f a₂ b)) (q₁ : quot r) (q₂ : quot s) : quot t := quot.lift₂ (λ a b, quot.mk t $ f a b) (λ a b₁ b₂ hb, quot.sound (hr a b₁ b₂ hb)) (λ a₁ a₂ b ha, quot.sound (hs a₁ a₂ b ha)) q₁ q₂ @[simp] lemma map₂_mk (f : α → β → γ) (hr : ∀ a b₁ b₂, s b₁ b₂ → t (f a b₁) (f a b₂)) (hs : ∀ a₁ a₂ b, r a₁ a₂ → t (f a₁ b) (f a₂ b)) (a : α) (b : β) : quot.map₂ f hr hs (quot.mk r a) (quot.mk s b) = quot.mk t (f a b) := rfl attribute [elab_as_eliminator] protected lemma induction_on₂ {δ : quot r → quot s → Prop} (q₁ : quot r) (q₂ : quot s) (h : ∀ a b, δ (quot.mk r a) (quot.mk s b)) : δ q₁ q₂ := quot.ind (λ a₁, quot.ind (λ a₂, h a₁ a₂) q₂) q₁ attribute [elab_as_eliminator] protected lemma induction_on₃ {δ : quot r → quot s → quot t → Prop} (q₁ : quot r) (q₂ : quot s) (q₃ : quot t) (h : ∀ a b c, δ (quot.mk r a) (quot.mk s b) (quot.mk t c)) : δ q₁ q₂ q₃ := quot.ind (λ a₁, quot.ind (λ a₂, quot.ind (λ a₃, h a₁ a₂ a₃) q₃) q₂) q₁ end quot namespace quotient variables [sa : setoid α] [sb : setoid β] variables {φ : quotient sa → quotient sb → Sort*} instance [inhabited α] : inhabited (quotient sa) := ⟨⟦default _⟧⟩ /-- Induction on two `quotient` arguments `a` and `b`, result type depends on `⟦a⟧` and `⟦b⟧`. -/ protected def hrec_on₂ (qa : quotient sa) (qb : quotient sb) (f : Π a b, φ ⟦a⟧ ⟦b⟧) (c : ∀ a₁ b₁ a₂ b₂, a₁ ≈ a₂ → b₁ ≈ b₂ → f a₁ b₁ == f a₂ b₂) : φ qa qb := quot.hrec_on₂ qa qb f (λ _ _ _ p, c _ _ _ _ p (setoid.refl _)) (λ _ _ _ p, c _ _ _ _ (setoid.refl _) p) /-- Map a function `f : α → β` that sends equivalent elements to equivalent elements to a function `quotient sa → quotient sb`. Useful to define unary operations on quotients. -/ protected def map (f : α → β) (h : ((≈) ⇒ (≈)) f f) : quotient sa → quotient sb := quot.map f h @[simp] lemma map_mk (f : α → β) (h : ((≈) ⇒ (≈)) f f) (x : α) : quotient.map f h (⟦x⟧ : quotient sa) = (⟦f x⟧ : quotient sb) := rfl variables {γ : Sort*} [sc : setoid γ] /-- Map a function `f : α → β → γ` that sends equivalent elements to equivalent elements to a function `f : quotient sa → quotient sb → quotient sc`. Useful to define binary operations on quotients. -/ protected def map₂ (f : α → β → γ) (h : ((≈) ⇒ (≈) ⇒ (≈)) f f) : quotient sa → quotient sb → quotient sc := quotient.lift₂ (λ x y, ⟦f x y⟧) (λ x₁ y₁ x₂ y₂ h₁ h₂, quot.sound $ h h₁ h₂) end quotient lemma quot.eq {α : Type*} {r : α → α → Prop} {x y : α} : quot.mk r x = quot.mk r y ↔ eqv_gen r x y := ⟨quot.exact r, quot.eqv_gen_sound⟩ @[simp] theorem quotient.eq [r : setoid α] {x y : α} : ⟦x⟧ = ⟦y⟧ ↔ x ≈ y := ⟨quotient.exact, quotient.sound⟩ theorem forall_quotient_iff {α : Type*} [r : setoid α] {p : quotient r → Prop} : (∀a:quotient r, p a) ↔ (∀a:α, p ⟦a⟧) := ⟨assume h x, h _, assume h a, a.induction_on h⟩ @[simp] lemma quotient.lift_beta [s : setoid α] (f : α → β) (h : ∀ (a b : α), a ≈ b → f a = f b) (x : α) : quotient.lift f h (quotient.mk x) = f x := rfl @[simp] lemma quotient.lift_on_beta [s : setoid α] (f : α → β) (h : ∀ (a b : α), a ≈ b → f a = f b) (x : α) : quotient.lift_on (quotient.mk x) f h = f x := rfl @[simp] theorem quotient.lift_on_beta₂ {α : Type} {β : Type} [setoid α] (f : α → α → β) (h : ∀ (a₁ a₂ b₁ b₂ : α), a₁ ≈ b₁ → a₂ ≈ b₂ → f a₁ a₂ = f b₁ b₂) (x y : α) : quotient.lift_on₂ (quotient.mk x) (quotient.mk y) f h = f x y := rfl /-- Choose an element of the equivalence class using the axiom of choice. Sound but noncomputable. -/ noncomputable def quot.out {r : α → α → Prop} (q : quot r) : α := classical.some (quot.exists_rep q) /-- Unwrap the VM representation of a quotient to obtain an element of the equivalence class. Computable but unsound. -/ meta def quot.unquot {r : α → α → Prop} : quot r → α := unchecked_cast @[simp] theorem quot.out_eq {r : α → α → Prop} (q : quot r) : quot.mk r q.out = q := classical.some_spec (quot.exists_rep q) /-- Choose an element of the equivalence class using the axiom of choice. Sound but noncomputable. -/ noncomputable def quotient.out [s : setoid α] : quotient s → α := quot.out @[simp] theorem quotient.out_eq [s : setoid α] (q : quotient s) : ⟦q.out⟧ = q := q.out_eq theorem quotient.mk_out [s : setoid α] (a : α) : ⟦a⟧.out ≈ a := quotient.exact (quotient.out_eq _) instance pi_setoid {ι : Sort*} {α : ι → Sort*} [∀ i, setoid (α i)] : setoid (Π i, α i) := { r := λ a b, ∀ i, a i ≈ b i, iseqv := ⟨ λ a i, setoid.refl _, λ a b h i, setoid.symm (h _), λ a b c h₁ h₂ i, setoid.trans (h₁ _) (h₂ _)⟩ } /-- Given a function `f : Π i, quotient (S i)`, returns the class of functions `Π i, α i` sending each `i` to an element of the class `f i`. -/ noncomputable def quotient.choice {ι : Type*} {α : ι → Type*} [S : Π i, setoid (α i)] (f : Π i, quotient (S i)) : @quotient (Π i, α i) (by apply_instance) := ⟦λ i, (f i).out⟧ theorem quotient.choice_eq {ι : Type*} {α : ι → Type*} [Π i, setoid (α i)] (f : Π i, α i) : quotient.choice (λ i, ⟦f i⟧) = ⟦f⟧ := quotient.sound $ λ i, quotient.mk_out _ lemma nonempty_quotient_iff (s : setoid α) : nonempty (quotient s) ↔ nonempty α := ⟨assume ⟨a⟩, quotient.induction_on a nonempty.intro, assume ⟨a⟩, ⟨⟦a⟧⟩⟩ /-- `trunc α` is the quotient of `α` by the always-true relation. This is related to the propositional truncation in HoTT, and is similar in effect to `nonempty α`, but unlike `nonempty α`, `trunc α` is data, so the VM representation is the same as `α`, and so this can be used to maintain computability. -/ def {u} trunc (α : Sort u) : Sort u := @quot α (λ _ _, true) theorem true_equivalence : @equivalence α (λ _ _, true) := ⟨λ _, trivial, λ _ _ _, trivial, λ _ _ _ _ _, trivial⟩ namespace trunc /-- Constructor for `trunc α` -/ def mk (a : α) : trunc α := quot.mk _ a instance [inhabited α] : inhabited (trunc α) := ⟨mk (default _)⟩ /-- Any constant function lifts to a function out of the truncation -/ def lift (f : α → β) (c : ∀ a b : α, f a = f b) : trunc α → β := quot.lift f (λ a b _, c a b) theorem ind {β : trunc α → Prop} : (∀ a : α, β (mk a)) → ∀ q : trunc α, β q := quot.ind protected theorem lift_beta (f : α → β) (c) (a : α) : lift f c (mk a) = f a := rfl /-- Lift a constant function on `q : trunc α`. -/ @[reducible, elab_as_eliminator] protected def lift_on (q : trunc α) (f : α → β) (c : ∀ a b : α, f a = f b) : β := lift f c q @[elab_as_eliminator] protected theorem induction_on {β : trunc α → Prop} (q : trunc α) (h : ∀ a, β (mk a)) : β q := ind h q theorem exists_rep (q : trunc α) : ∃ a : α, mk a = q := quot.exists_rep q attribute [elab_as_eliminator] protected theorem induction_on₂ {C : trunc α → trunc β → Prop} (q₁ : trunc α) (q₂ : trunc β) (h : ∀ a b, C (mk a) (mk b)) : C q₁ q₂ := trunc.induction_on q₁ $ λ a₁, trunc.induction_on q₂ (h a₁) protected theorem eq (a b : trunc α) : a = b := trunc.induction_on₂ a b (λ x y, quot.sound trivial) instance : subsingleton (trunc α) := ⟨trunc.eq⟩ /-- The `bind` operator for the `trunc` monad. -/ def bind (q : trunc α) (f : α → trunc β) : trunc β := trunc.lift_on q f (λ a b, trunc.eq _ _) /-- A function `f : α → β` defines a function `map f : trunc α → trunc β`. -/ def map (f : α → β) (q : trunc α) : trunc β := bind q (trunc.mk ∘ f) instance : monad trunc := { pure := @trunc.mk, bind := @trunc.bind } instance : is_lawful_monad trunc := { id_map := λ α q, trunc.eq _ _, pure_bind := λ α β q f, rfl, bind_assoc := λ α β γ x f g, trunc.eq _ _ } variable {C : trunc α → Sort*} /-- Recursion/induction principle for `trunc`. -/ @[reducible, elab_as_eliminator] protected def rec (f : Π a, C (mk a)) (h : ∀ (a b : α), (eq.rec (f a) (trunc.eq (mk a) (mk b)) : C (mk b)) = f b) (q : trunc α) : C q := quot.rec f (λ a b _, h a b) q /-- A version of `trunc.rec` taking `q : trunc α` as the first argument. -/ @[reducible, elab_as_eliminator] protected def rec_on (q : trunc α) (f : Π a, C (mk a)) (h : ∀ (a b : α), (eq.rec (f a) (trunc.eq (mk a) (mk b)) : C (mk b)) = f b) : C q := trunc.rec f h q /-- A version of `trunc.rec_on` assuming the codomain is a `subsingleton`. -/ @[reducible, elab_as_eliminator] protected def rec_on_subsingleton [∀ a, subsingleton (C (mk a))] (q : trunc α) (f : Π a, C (mk a)) : C q := trunc.rec f (λ a b, subsingleton.elim _ (f b)) q /-- Noncomputably extract a representative of `trunc α` (using the axiom of choice). -/ noncomputable def out : trunc α → α := quot.out @[simp] theorem out_eq (q : trunc α) : mk q.out = q := trunc.eq _ _ end trunc theorem nonempty_of_trunc (q : trunc α) : nonempty α := let ⟨a, _⟩ := q.exists_rep in ⟨a⟩ namespace quotient variables {γ : Sort*} {φ : Sort*} {s₁ : setoid α} {s₂ : setoid β} {s₃ : setoid γ} /- Versions of quotient definitions and lemmas ending in `'` use unification instead of typeclass inference for inferring the `setoid` argument. This is useful when there are several different quotient relations on a type, for example quotient groups, rings and modules -/ /-- A version of `quotient.mk` taking `{s : setoid α}` as an implicit argument instead of an instance argument. -/ protected def mk' (a : α) : quotient s₁ := quot.mk s₁.1 a /-- A version of `quotient.lift_on` taking `{s : setoid α}` as an implicit argument instead of an instance argument. -/ @[elab_as_eliminator, reducible] protected def lift_on' (q : quotient s₁) (f : α → φ) (h : ∀ a b, @setoid.r α s₁ a b → f a = f b) : φ := quotient.lift_on q f h /-- A version of `quotient.lift_on₂` taking `{s₁ : setoid α} {s₂ : setoid β}` as implicit arguments instead of instance arguments. -/ @[elab_as_eliminator, reducible] protected def lift_on₂' (q₁ : quotient s₁) (q₂ : quotient s₂) (f : α → β → γ) (h : ∀ a₁ a₂ b₁ b₂, @setoid.r α s₁ a₁ b₁ → @setoid.r β s₂ a₂ b₂ → f a₁ a₂ = f b₁ b₂) : γ := quotient.lift_on₂ q₁ q₂ f h /-- A version of `quotient.ind` taking `{s : setoid α}` as an implicit argument instead of an instance argument. -/ @[elab_as_eliminator] protected lemma ind' {p : quotient s₁ → Prop} (h : ∀ a, p (quotient.mk' a)) (q : quotient s₁) : p q := quotient.ind h q /-- A version of `quotient.ind₂` taking `{s₁ : setoid α} {s₂ : setoid β}` as implicit arguments instead of instance arguments. -/ @[elab_as_eliminator] protected lemma ind₂' {p : quotient s₁ → quotient s₂ → Prop} (h : ∀ a₁ a₂, p (quotient.mk' a₁) (quotient.mk' a₂)) (q₁ : quotient s₁) (q₂ : quotient s₂) : p q₁ q₂ := quotient.ind₂ h q₁ q₂ /-- A version of `quotient.induction_on` taking `{s : setoid α}` as an implicit argument instead of an instance argument. -/ @[elab_as_eliminator] protected lemma induction_on' {p : quotient s₁ → Prop} (q : quotient s₁) (h : ∀ a, p (quotient.mk' a)) : p q := quotient.induction_on q h /-- A version of `quotient.induction_on₂` taking `{s₁ : setoid α} {s₂ : setoid β}` as implicit arguments instead of instance arguments. -/ @[elab_as_eliminator] protected lemma induction_on₂' {p : quotient s₁ → quotient s₂ → Prop} (q₁ : quotient s₁) (q₂ : quotient s₂) (h : ∀ a₁ a₂, p (quotient.mk' a₁) (quotient.mk' a₂)) : p q₁ q₂ := quotient.induction_on₂ q₁ q₂ h /-- A version of `quotient.induction_on₃` taking `{s₁ : setoid α} {s₂ : setoid β} {s₃ : setoid γ}` as implicit arguments instead of instance arguments. -/ @[elab_as_eliminator] protected lemma induction_on₃' {p : quotient s₁ → quotient s₂ → quotient s₃ → Prop} (q₁ : quotient s₁) (q₂ : quotient s₂) (q₃ : quotient s₃) (h : ∀ a₁ a₂ a₃, p (quotient.mk' a₁) (quotient.mk' a₂) (quotient.mk' a₃)) : p q₁ q₂ q₃ := quotient.induction_on₃ q₁ q₂ q₃ h /-- Recursion on a `quotient` argument `a`, result type depends on `⟦a⟧`. -/ protected def hrec_on' {φ : quotient s₁ → Sort*} (qa : quotient s₁) (f : Π a, φ (quotient.mk' a)) (c : ∀ a₁ a₂, a₁ ≈ a₂ → f a₁ == f a₂) : φ qa := quot.hrec_on qa f c @[simp] lemma hrec_on'_mk' {φ : quotient s₁ → Sort*} (f : Π a, φ (quotient.mk' a)) (c : ∀ a₁ a₂, a₁ ≈ a₂ → f a₁ == f a₂) (x : α) : (quotient.mk' x).hrec_on' f c = f x := rfl /-- Recursion on two `quotient` arguments `a` and `b`, result type depends on `⟦a⟧` and `⟦b⟧`. -/ protected def hrec_on₂' {φ : quotient s₁ → quotient s₂ → Sort*} (qa : quotient s₁) (qb : quotient s₂) (f : ∀ a b, φ (quotient.mk' a) (quotient.mk' b)) (c : ∀ a₁ b₁ a₂ b₂, a₁ ≈ a₂ → b₁ ≈ b₂ → f a₁ b₁ == f a₂ b₂) : φ qa qb := quotient.hrec_on₂ qa qb f c @[simp] lemma hrec_on₂'_mk' {φ : quotient s₁ → quotient s₂ → Sort*} (f : ∀ a b, φ (quotient.mk' a) (quotient.mk' b)) (c : ∀ a₁ b₁ a₂ b₂, a₁ ≈ a₂ → b₁ ≈ b₂ → f a₁ b₁ == f a₂ b₂) (x : α) (qb : quotient s₂) : (quotient.mk' x).hrec_on₂' qb f c = qb.hrec_on' (f x) (λ b₁ b₂, c _ _ _ _ (setoid.refl _)) := rfl /-- Map a function `f : α → β` that sends equivalent elements to equivalent elements to a function `quotient sa → quotient sb`. Useful to define unary operations on quotients. -/ protected def map' (f : α → β) (h : ((≈) ⇒ (≈)) f f) : quotient s₁ → quotient s₂ := quot.map f h @[simp] lemma map'_mk' (f : α → β) (h) (x : α) : (quotient.mk' x : quotient s₁).map' f h = (quotient.mk' (f x) : quotient s₂) := rfl /-- A version of `quotient.map₂` using curly braces and unification. -/ protected def map₂' (f : α → β → γ) (h : ((≈) ⇒ (≈) ⇒ (≈)) f f) : quotient s₁ → quotient s₂ → quotient s₃ := quotient.map₂ f h @[simp] lemma map₂'_mk' (f : α → β → γ) (h) (x : α) : (quotient.mk' x : quotient s₁).map₂' f h = (quotient.map' (f x) (h (setoid.refl x)) : quotient s₂ → quotient s₃) := rfl lemma exact' {a b : α} : (quotient.mk' a : quotient s₁) = quotient.mk' b → @setoid.r _ s₁ a b := quotient.exact lemma sound' {a b : α} : @setoid.r _ s₁ a b → @quotient.mk' α s₁ a = quotient.mk' b := quotient.sound @[simp] protected lemma eq' {a b : α} : @quotient.mk' α s₁ a = quotient.mk' b ↔ @setoid.r _ s₁ a b := quotient.eq /-- A version of `quotient.out` taking `{s₁ : setoid α}` as an implicit argument instead of an instance argument. -/ noncomputable def out' (a : quotient s₁) : α := quotient.out a @[simp] theorem out_eq' (q : quotient s₁) : quotient.mk' q.out' = q := q.out_eq theorem mk_out' (a : α) : @setoid.r α s₁ (quotient.mk' a : quotient s₁).out' a := quotient.exact (quotient.out_eq _) end quotient
9806c468e37eb063b9ead7bfac4e34bf2b4c1c72
57fdc8de88f5ea3bfde4325e6ecd13f93a274ab5
/group_theory/subgroup.lean
c43704f2ecd0badda8418893b9bcfccb68c0d231
[ "Apache-2.0" ]
permissive
louisanu/mathlib
11f56f2d40dc792bc05ee2f78ea37d73e98ecbfe
2bd5e2159d20a8f20d04fc4d382e65eea775ed39
refs/heads/master
1,617,706,993,439
1,523,163,654,000
1,523,163,654,000
124,519,997
0
0
Apache-2.0
1,520,588,283,000
1,520,588,283,000
null
UTF-8
Lean
false
false
9,705
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 -/ import data.finset algebra.big_operators data.equiv data.set data.nat.basic set_theory.cardinal open set function finset universes u v w variables {α : Type u} {β : Type v} {s : set α} {a a₁ a₂ : α} namespace finset open finset lemma mem_range_iff_mem_finset_range_of_mod_eq [decidable_eq α] {f : ℤ → α} {a : α} {n : ℕ} (hn : 0 < n) (h : ∀i, f (i % n) = f i) : a ∈ set.range f ↔ a ∈ (finset.range n).image (λi, f i) := suffices (∃i, f (i % n) = a) ↔ ∃i, i < n ∧ f ↑i = a, by simpa [h], have hn' : 0 < (n : ℤ), from int.coe_nat_lt.mpr hn, iff.intro (assume ⟨i, hi⟩, have 0 ≤ i % ↑n, from int.mod_nonneg _ (ne_of_gt hn'), ⟨int.to_nat (i % n), by rw [←int.coe_nat_lt, int.to_nat_of_nonneg this]; exact ⟨int.mod_lt_of_pos i hn', hi⟩⟩) (assume ⟨i, hi, ha⟩, ⟨i, by rw [int.mod_eq_of_lt (int.coe_zero_le _) (int.coe_nat_lt_coe_nat_of_lt hi), ha]⟩) end finset variables [group α] /-- A subset of a group closed under the group operations. -/ structure is_subgroup (s : set α) : Prop := (one_mem : (1:α) ∈ s) (mul_inv_mem : ∀a∈s, ∀b∈s, a * b⁻¹ ∈ s) def cosets (s : set α) : set (set α) := range (λa, (*) a '' s) namespace is_subgroup lemma inv_mem (hs : is_subgroup s) (h : a ∈ s) : a⁻¹ ∈ s := have 1 * a⁻¹ ∈ s, from hs.mul_inv_mem _ hs.one_mem _ h, by simpa lemma inv_mem_iff (hs : is_subgroup s) : a⁻¹ ∈ s ↔ a ∈ s := iff.intro (assume h, have a⁻¹⁻¹ ∈ s, from hs.inv_mem h, by simpa) hs.inv_mem lemma mul_mem (hs : is_subgroup s) (h₁ : a₁ ∈ s) (h₂ : a₂ ∈ s) : a₁ * a₂ ∈ s := have a₁ * a₂⁻¹⁻¹ ∈ s, from hs.mul_inv_mem _ h₁ _ (hs.inv_mem h₂), by simpa lemma mul_image (hs : is_subgroup s) (a : α) (ha : a ∈ s) : (*) a '' s = s := ext $ assume a', iff.intro (assume ⟨a'', ha'', eq⟩, eq ▸ hs.mul_mem ha ha'') (assume ha', ⟨a⁻¹ * a', hs.mul_mem (hs.inv_mem ha) ha', by simp⟩) lemma injective_mul {a : α} : injective ((*) a) := assume a₁ a₂ h, have a⁻¹ * a * a₁ = a⁻¹ * a * a₂, by rw [mul_assoc, mul_assoc, h], by rwa [inv_mul_self, one_mul, one_mul] at this lemma subgroup_mem_cosets (hs : is_subgroup s) : s ∈ cosets s := ⟨1, hs.mul_image _ hs.one_mem⟩ lemma cosets_disjoint (hs : is_subgroup s) : ∀{s₁ s₂ : set α}, s₁ ∈ cosets s → s₂ ∈ cosets s → ∀{a}, a ∈ s₁ → a ∈ s₂ → s₁ = s₂ | _ _ ⟨b₁, rfl⟩ ⟨b₂, rfl⟩ a ⟨c₁, hc₁, eq₁⟩ ⟨c₂, hc₂, eq₂⟩ := have b_eq : b₁ = b₂ * c₂ * c₁⁻¹, by rw [eq_mul_inv_iff_mul_eq, eq₁, eq₂], have hc : c₂ * c₁⁻¹ ∈ s, from hs.mul_mem hc₂ (hs.inv_mem hc₁), calc (*) b₁ '' s = (*) b₂ '' ((*) (c₂ * c₁⁻¹) '' s) : by rw [←image_comp, (∘), b_eq]; apply image_congr _; simp [mul_assoc] ... = (*) b₂ '' s : by rw [hs.mul_image _ hc] lemma pairwise_cosets_disjoint (hs : is_subgroup s) : pairwise_on (cosets s) disjoint := assume s₁ h₁ s₂ h₂ ne, eq_empty_iff_forall_not_mem.mpr $ assume a ⟨ha₁, ha₂⟩, ne $ hs.cosets_disjoint h₁ h₂ ha₁ ha₂ lemma cosets_equiv_subgroup (hs : is_subgroup s) : ∀{t : set α}, t ∈ cosets s → nonempty (t ≃ s) | _ ⟨a, rfl⟩ := ⟨(equiv.set.image ((*) a) s injective_mul).symm⟩ lemma Union_cosets_eq_univ (hs : is_subgroup s) : ⋃₀ cosets s = univ := eq_univ_of_forall $ assume a, ⟨(*) a '' s, mem_range_self _, ⟨1, hs.one_mem, mul_one _⟩⟩ lemma group_equiv_cosets_times_subgroup (hs : is_subgroup s) : nonempty (α ≃ (cosets s × s)) := ⟨calc α ≃ (@set.univ α) : (equiv.set.univ α).symm ... ≃ (⋃t∈cosets s, t) : by rw [←hs.Union_cosets_eq_univ]; simp ... ≃ (Σt:cosets s, t) : equiv.set.bUnion_eq_sigma_of_disjoint hs.pairwise_cosets_disjoint ... ≃ (Σt:cosets s, s) : equiv.sigma_congr_right $ λ⟨t, ht⟩, classical.choice $ hs.cosets_equiv_subgroup ht ... ≃ (cosets s × s) : equiv.sigma_equiv_prod _ _⟩ end is_subgroup lemma is_subgroup_range_gpow : is_subgroup (range ((^) a : ℤ → α)) := ⟨⟨0, rfl⟩, assume a ⟨i, ha⟩ b ⟨j, hb⟩, ⟨i - j, by simp [gpow_add, gpow_neg, ha.symm, hb.symm]⟩⟩ section finite_group variables [fintype α] [decidable_eq α] lemma exists_gpow_eq_one (a : α) : ∃i≠0, a ^ (i:ℤ) = 1 := have ¬ injective (λi, a ^ i), from not_injective_int_fintype, let ⟨i, j, a_eq, ne⟩ := show ∃(i j : ℤ), a ^ i = a ^ j ∧ i ≠ j, by rw [injective] at this; simpa [classical.not_forall] in have a ^ (i - j) = 1, by simp [gpow_add, gpow_neg, a_eq], ⟨i - j, sub_ne_zero.mpr ne, this⟩ lemma exists_pow_eq_one (a : α) : ∃i≠0, a ^ i = 1 := let ⟨i, hi, eq⟩ := exists_gpow_eq_one a in begin cases i, { exact ⟨i, by simp [int.of_nat_eq_coe, *] at *, eq⟩ }, { exact ⟨i + 1, dec_trivial, inv_eq_one.1 eq⟩ } end /-- `order_of a` is the order of the element, i.e. the `n ≥ 1`, s.t. `a ^ n = 1` -/ def order_of (a : α) : ℕ := nat.find (exists_pow_eq_one a) lemma pow_order_of_eq_one (a : α) : a ^ order_of a = 1 := let ⟨h₁, h₂⟩ := nat.find_spec (exists_pow_eq_one a) in h₂ lemma order_of_ne_zero (a : α) : order_of a ≠ 0 := let ⟨h₁, h₂⟩ := nat.find_spec (exists_pow_eq_one a) in h₁ private lemma pow_injective_aux {n m : ℕ} (a : α) (h : n ≤ m) (hn : n < order_of a) (hm : m < order_of a) (eq : a ^ n = a ^ m) : n = m := decidable.by_contradiction $ assume ne : n ≠ m, have h₁ : m - n ≠ 0, by simp [nat.sub_eq_iff_eq_add h, ne.symm], have h₂ : a ^ (m - n) = 1, by simp [pow_sub _ h, eq], have le : order_of a ≤ m - n, from nat.find_min' (exists_pow_eq_one a) ⟨h₁, h₂⟩, have lt : m - n < order_of a, from (nat.sub_lt_left_iff_lt_add h).mpr $ nat.lt_add_left _ _ _ hm, lt_irrefl _ (lt_of_le_of_lt le lt) lemma pow_injective_of_lt_order_of {n m : ℕ} (a : α) (hn : n < order_of a) (hm : m < order_of a) (eq : a ^ n = a ^ m) : n = m := (le_total n m).elim (assume h, pow_injective_aux a h hn hm eq) (assume h, (pow_injective_aux a h hm hn eq.symm).symm) lemma order_of_le_card_univ : order_of a ≤ fintype.card α := finset.card_le_of_inj_on ((^) a) (assume n _, fintype.complete _) (assume i j, pow_injective_of_lt_order_of a) lemma pow_eq_mod_order_of {n : ℕ} : a ^ n = a ^ (n % order_of a) := calc a ^ n = a ^ (n % order_of a + order_of a * (n / order_of a)) : by rw [nat.mod_add_div] ... = a ^ (n % order_of a) : by simp [pow_add, pow_mul, pow_order_of_eq_one] lemma gpow_eq_mod_order_of {i : ℤ} : a ^ i = a ^ (i % order_of a) := calc a ^ i = a ^ (i % order_of a + order_of a * (i / order_of a)) : by rw [int.mod_add_div] ... = a ^ (i % order_of a) : by simp [gpow_add, gpow_mul, pow_order_of_eq_one] lemma mem_range_gpow_iff_mem_range_order_of {a a' : α} : a' ∈ range ((^) a : ℤ → α) ↔ a' ∈ (finset.range (order_of a)).image ((^) a : ℕ → α) := finset.mem_range_iff_mem_finset_range_of_mod_eq (nat.pos_iff_ne_zero.mpr (order_of_ne_zero a)) (assume i, gpow_eq_mod_order_of.symm) instance decidable_range_gpow : decidable_pred (range ((^) a : ℤ → α)) := assume a', decidable_of_iff' (a' ∈ (finset.range (order_of a)).image ((^) a)) mem_range_gpow_iff_mem_range_order_of section local attribute [instance] set_fintype lemma order_eq_card_range_gpow : order_of a = fintype.card (range ((^) a : ℤ → α)) := begin refine (finset.card_eq_of_bijective _ _ _ _).symm, { exact λn hn, ⟨gpow a n, mem_range_self n⟩ }, { exact assume ⟨_, i, rfl⟩ _, have pos: (0:int) < order_of a, from int.coe_nat_lt.mpr $ nat.pos_iff_ne_zero.mpr $ order_of_ne_zero a, have 0 ≤ i % (order_of a), from int.mod_nonneg _ $ ne_of_gt pos, ⟨int.to_nat (i % order_of a), by rw [← int.coe_nat_lt, int.to_nat_of_nonneg this]; exact ⟨int.mod_lt_of_pos _ pos, subtype.eq gpow_eq_mod_order_of.symm⟩⟩ }, { intros, exact finset.mem_univ _ }, { exact assume i j hi hj eq, pow_injective_of_lt_order_of a hi hj $ by simpa using eq } end section classical local attribute [instance] classical.prop_decidable -- TODO: use cardinal theory, or introduce `card : set α → ℕ` lemma order_of_dvd_card_univ : order_of a ∣ fintype.card α := let s := range $ gpow a in have hs : is_subgroup s, from is_subgroup_range_gpow, let ⟨equiv⟩ := hs.group_equiv_cosets_times_subgroup in have ft_prod : fintype (cosets s × s), from fintype.of_equiv α equiv, have ft_s : fintype s, from @fintype.fintype_prod_right _ _ _ ft_prod ⟨⟨s, hs.subgroup_mem_cosets⟩⟩, have ft_cosets : fintype (cosets s), from @fintype.fintype_prod_left _ _ _ ft_prod ⟨⟨1, hs.one_mem⟩⟩, have ft : fintype (cosets s × s), from @prod.fintype _ _ ft_cosets ft_s, have eq₁ : fintype.card α = @fintype.card _ ft_cosets * @fintype.card _ ft_s, from calc fintype.card α = @fintype.card _ ft_prod : (@fintype.card_eq _ _ _ ft_prod).2 hs.group_equiv_cosets_times_subgroup ... = @fintype.card _ (@prod.fintype _ _ ft_cosets ft_s) : congr_arg (@fintype.card _) $ subsingleton.elim _ _ ... = @fintype.card _ ft_cosets * @fintype.card _ ft_s : @fintype.card_prod _ _ ft_cosets ft_s, have eq₂ : order_of a = @fintype.card _ ft_s, from calc order_of a = _ : order_eq_card_range_gpow ... = _ : congr_arg (@fintype.card _) $ subsingleton.elim _ _, dvd.intro (@fintype.card (cosets s) ft_cosets) $ by rw [eq₁, eq₂, mul_comm] end classical end end finite_group
c0f86debded8004e1130d982e3e406657689ef31
40ad357bbd0d327dd1e3e7f7beb868bd4e5b0a9d
/src/temporal_logic/pair.lean
4ed3cc99fa97f51c2dbc87e8d406c77f4dc53148
[]
no_license
unitb/temporal-logic
9966424f015976d5997a9ffa30cbd77cc3a9cb1c
accec04d1b09ca841be065511c9e206b725b16e9
refs/heads/master
1,633,868,382,769
1,541,072,223,000
1,541,072,223,000
114,790,987
5
3
null
null
null
null
UTF-8
Lean
false
false
2,357
lean
import temporal_logic.basic universe variables u u₀ u₁ u₂ namespace temporal open predicate section pair variables {α : Type u} {β : Type u₀} {γ : Type u₁} {ω : Type u₂} variables (x : tvar α) (y : tvar β) (z : tvar γ) @[tl_simp, simp] lemma pair_model (i : ℕ) : i ⊨ ⦃x,y⦄ = (i ⊨ x,i ⊨ y) := by { cases x, cases y, refl } @[reducible] def pair.fst : var (α × β) α := ⟨ @prod.fst α β ⟩ @[reducible] def pair.snd : var (α × β) β := ⟨ @prod.snd α β ⟩ abbreviation tvar.fst (p : var γ (α × β)) : var γ α := pair.fst!p abbreviation tvar.snd (p : var γ (α × β)) : var γ β := pair.snd!p @[tl_simp, simp] def pair.fst_mk (x : tvar α) (y : tvar β) : pair.fst ! ⦃x,y⦄ = x := by lifted_pred @[tl_simp, simp] def pair.fst_mk' (x : tvar α) (y : tvar β) : ⟨ @prod.fst α β ⟩ ! ⦃x,y⦄ = x := pair.fst_mk _ _ @[tl_simp, simp] def pair.snd_mk (x : tvar α) (y : tvar β) : pair.snd ! ⦃x,y⦄ = y := by lifted_pred @[tl_simp, simp] def pair.snd_mk' (x : tvar α) (y : tvar β) : ⟨ @prod.snd α β ⟩ ! ⦃x,y⦄ = y := by lifted_pred @[tl_simp, simp] def prod.map_left {α β γ} (f : α → β) : α × γ → β × γ | (x,y) := (f x, y) @[tl_simp, simp] def prod.map_right {α β γ} (f : β → γ) : α × β → α × γ | (x,y) := (x,f y) open temporal.prod @[tl_simp, simp] lemma map_right_proj_pair (f : β → γ) : ⟨map_right f⟩ ! ⦃x,y⦄ = ⦃x, ⟨f⟩ ! y⦄ := by ext i ; simp [map_right] with tl_simp @[tl_simp, simp] lemma map_left_proj_pair (f : α → γ) : ⟨map_left f⟩ ! ⦃x,y⦄ = ⦃⟨f⟩ ! x, y⦄ := by ext i ; simp [map_left] with tl_simp @[tl_simp, simp] lemma map_proj_pair (f : α → γ) (g : β → ω) : ⟨prod.map f g⟩ ! ⦃x,y⦄ = ⦃⟨f⟩ ! x,⟨g⟩ ! y⦄ := by ext i ; simp [prod.map] with tl_simp @[tl_simp, simp] lemma eta_pair (w : tvar (α × β)) : ⦃w.fst, w.snd⦄ = w := by ext i ; simp [prod.map] with tl_simp @[tl_simp, simp] lemma next_pair (v₀ : tvar α) (v₁ : tvar β) : ⊙⦃v₀,v₁⦄ = ⦃⊙v₀,⊙v₁⦄ := by lifted_pred [next] @[tl_simp, simp, predicate] lemma to_fun_var_pair (f : tvar α → tvar β) (g : tvar α → tvar γ) (w : tvar α) : to_fun_var (λ w : tvar α, ⦃f w,g w⦄) w = ⦃to_fun_var f w,to_fun_var g w⦄ := by { lifted_pred, simp! } end pair end temporal
55ba4fc90998dadd372ee251b0d55b0fb7f9248c
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/category_theory/Fintype.lean
49fd297aeb31061f243a4efd30895072b290e382
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
4,825
lean
/- Copyright (c) 2020 Adam Topaz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta, Adam Topaz -/ import category_theory.concrete_category.basic import category_theory.full_subcategory import category_theory.skeletal import category_theory.elementwise import data.fintype.card /-! # The category of finite types. We define the category of finite types, denoted `Fintype` as (bundled) types with a `fintype` instance. We also define `Fintype.skeleton`, the standard skeleton of `Fintype` whose objects are `fin n` for `n : ℕ`. We prove that the obvious inclusion functor `Fintype.skeleton ⥤ Fintype` is an equivalence of categories in `Fintype.skeleton.equivalence`. We prove that `Fintype.skeleton` is a skeleton of `Fintype` in `Fintype.is_skeleton`. -/ open_locale classical open category_theory /-- The category of finite types. -/ def Fintype := bundled fintype namespace Fintype instance : has_coe_to_sort Fintype Type* := bundled.has_coe_to_sort /-- Construct a bundled `Fintype` from the underlying type and typeclass. -/ def of (X : Type*) [fintype X] : Fintype := bundled.of X instance : inhabited Fintype := ⟨⟨pempty⟩⟩ instance {X : Fintype} : fintype X := X.2 instance : category Fintype := induced_category.category bundled.α /-- The fully faithful embedding of `Fintype` into the category of types. -/ @[derive [full, faithful], simps] def incl : Fintype ⥤ Type* := induced_functor _ instance concrete_category_Fintype : concrete_category Fintype := ⟨incl⟩ @[simp] lemma id_apply (X : Fintype) (x : X) : (𝟙 X : X → X) x = x := rfl @[simp] lemma comp_apply {X Y Z : Fintype} (f : X ⟶ Y) (g : Y ⟶ Z) (x : X) : (f ≫ g) x = g (f x) := rfl /-- Equivalences between finite types are the same as isomorphisms in `Fintype`. -/ -- See `equiv_equiv_iso` in the root namespace for the analogue in `Type`. @[simps] def equiv_equiv_iso {A B : Fintype} : (A ≃ B) ≃ (A ≅ B) := { to_fun := λ e, { hom := e, inv := e.symm, }, inv_fun := λ i, { to_fun := i.hom, inv_fun := i.inv, left_inv := iso.hom_inv_id_apply i, right_inv := iso.inv_hom_id_apply i, }, left_inv := by tidy, right_inv := by tidy, } universe u /-- The "standard" skeleton for `Fintype`. This is the full subcategory of `Fintype` spanned by objects of the form `ulift (fin n)` for `n : ℕ`. We parameterize the objects of `Fintype.skeleton` directly as `ulift ℕ`, as the type `ulift (fin m) ≃ ulift (fin n)` is nonempty if and only if `n = m`. Specifying universes, `skeleton : Type u` is a small skeletal category equivalent to `Fintype.{u}`. -/ def skeleton : Type u := ulift ℕ namespace skeleton /-- Given any natural number `n`, this creates the associated object of `Fintype.skeleton`. -/ def mk : ℕ → skeleton := ulift.up instance : inhabited skeleton := ⟨mk 0⟩ /-- Given any object of `Fintype.skeleton`, this returns the associated natural number. -/ def len : skeleton → ℕ := ulift.down @[ext] lemma ext (X Y : skeleton) : X.len = Y.len → X = Y := ulift.ext _ _ instance : small_category skeleton.{u} := { hom := λ X Y, ulift.{u} (fin X.len) → ulift.{u} (fin Y.len), id := λ _, id, comp := λ _ _ _ f g, g ∘ f } lemma is_skeletal : skeletal skeleton.{u} := λ X Y ⟨h⟩, ext _ _ $ fin.equiv_iff_eq.mp $ nonempty.intro $ { to_fun := λ x, (h.hom ⟨x⟩).down, inv_fun := λ x, (h.inv ⟨x⟩).down, left_inv := begin intro a, change ulift.down _ = _, rw ulift.up_down, change ((h.hom ≫ h.inv) _).down = _, simpa, end, right_inv := begin intro a, change ulift.down _ = _, rw ulift.up_down, change ((h.inv ≫ h.hom) _).down = _, simpa, end } /-- The canonical fully faithful embedding of `Fintype.skeleton` into `Fintype`. -/ def incl : skeleton.{u} ⥤ Fintype.{u} := { obj := λ X, Fintype.of (ulift (fin X.len)), map := λ _ _ f, f } instance : full incl := { preimage := λ _ _ f, f } instance : faithful incl := {} instance : ess_surj incl := ess_surj.mk $ λ X, let F := fintype.equiv_fin X in ⟨mk (fintype.card X), nonempty.intro { hom := F.symm ∘ ulift.down, inv := ulift.up ∘ F }⟩ noncomputable instance : is_equivalence incl := equivalence.of_fully_faithfully_ess_surj _ /-- The equivalence between `Fintype.skeleton` and `Fintype`. -/ noncomputable def equivalence : skeleton ≌ Fintype := incl.as_equivalence @[simp] lemma incl_mk_nat_card (n : ℕ) : fintype.card (incl.obj (mk n)) = n := begin convert finset.card_fin n, apply fintype.of_equiv_card, end end skeleton /-- `Fintype.skeleton` is a skeleton of `Fintype`. -/ noncomputable def is_skeleton : is_skeleton_of Fintype skeleton skeleton.incl := { skel := skeleton.is_skeletal, eqv := by apply_instance } end Fintype
e173cd25dd8c405936c37bc72eeede57c5948e93
2c096fdfecf64e46ea7bc6ce5521f142b5926864
/tests/lean/derivingRpcEncoding.lean
de5eb9233ff42009359beb9f9aa10636fa581087
[ "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
Kha/lean4
1005785d2c8797ae266a303968848e5f6ce2fe87
b99e11346948023cd6c29d248cd8f3e3fb3474cf
refs/heads/master
1,693,355,498,027
1,669,080,461,000
1,669,113,138,000
184,748,176
0
0
Apache-2.0
1,665,995,520,000
1,556,884,930,000
Lean
UTF-8
Lean
false
false
2,486
lean
import Lean.Server.Rpc.Basic open Lean Server abbrev M := StateM RpcObjectStore def M.run (x : ExceptT String M α) : Except String α := x.run' {} def test (α : Type) [RpcEncodable α] (a : α) := M.run do let json ← rpcEncode a let _a : α ← ofExcept (rpcDecode json (← get)) return json structure FooRef where a : Array Nat deriving Inhabited, TypeName #check instTypeNameFooRef #eval test (WithRpcRef FooRef) default structure FooJson where s : String deriving FromJson, ToJson, Inhabited structure Bar where fooRef : WithRpcRef FooRef fooJson : FooJson deriving RpcEncodable, Inhabited #check instRpcEncodableBar #eval test Bar default structure BarTrans where bar : Bar deriving RpcEncodable, Inhabited #check instRpcEncodableBarTrans #eval test BarTrans default structure Baz where arr : Array String -- non-constant field deriving RpcEncodable, Inhabited #check instRpcEncodableBaz #eval test Baz default structure FooGeneric (α : Type) where a : α b? : Option α deriving RpcEncodable, Inhabited #check @instRpcEncodableFooGeneric #eval test (FooGeneric Nat) default #eval test (FooGeneric Nat) { a := 3, b? := some 42 } inductive BazInductive | baz (arr : Array Bar) deriving RpcEncodable, Inhabited #check @instRpcEncodableBazInductive #eval test BazInductive ⟨#[default, default]⟩ inductive FooInductive (α : Type) where | a : α → WithRpcRef FooRef → FooInductive α | b : (n : Nat) → (a : α) → (m : Nat) → FooInductive α deriving RpcEncodable, Inhabited #check @instRpcEncodableFooInductive #eval test (FooInductive BazInductive) (.a default default) #eval test (FooInductive BazInductive) (.b 42 default default) inductive FooNested (α : Type) where | a : α → Array (FooNested α) → FooNested α deriving RpcEncodable, Inhabited #eval test (FooNested BazInductive) (.a default #[default]) inductive FooParam (n : Nat) where | a : Nat → FooParam n deriving RpcEncodable, Inhabited #check @instRpcEncodableFooParam #eval test (FooParam 10) (.a 42) inductive Unused (α : Type) | a deriving RpcEncodable, Inhabited #check @instRpcEncodableUnused structure NoRpcEncodable #eval test (Unused NoRpcEncodable) default structure UnusedStruct (α : Type) deriving RpcEncodable, Inhabited #check @instRpcEncodableUnusedStruct #eval test (UnusedStruct NoRpcEncodable) default deriving instance Repr, RpcEncodable for Empty #eval rpcDecode (α := Empty) .null {}
65d8d74e7d27e606f6f20080a12f1d2ff74c7af7
02fbe05a45fda5abde7583464416db4366eedfbf
/library/init/data/nat/bitwise.lean
e45188a80df9896c0076914a88d0d084939a43e3
[ "Apache-2.0" ]
permissive
jasonrute/lean
cc12807e11f9ac6b01b8951a8bfb9c2eb35a0154
4be962c167ca442a0ec5e84472d7ff9f5302788f
refs/heads/master
1,672,036,664,637
1,601,642,826,000
1,601,642,826,000
260,777,966
0
0
Apache-2.0
1,588,454,819,000
1,588,454,818,000
null
UTF-8
Lean
false
false
10,112
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro -/ prelude import init.data.nat.lemmas init.meta.well_founded_tactics universe u namespace nat def bodd_div2 : ℕ → bool × ℕ | 0 := (ff, 0) | (succ n) := match bodd_div2 n with | (ff, m) := (tt, m) | (tt, m) := (ff, succ m) end def div2 (n : ℕ) : ℕ := (bodd_div2 n).2 def bodd (n : ℕ) : bool := (bodd_div2 n).1 @[simp] lemma bodd_zero : bodd 0 = ff := rfl @[simp] lemma bodd_one : bodd 1 = tt := rfl @[simp] lemma bodd_two : bodd 2 = ff := rfl @[simp] lemma bodd_succ (n : ℕ) : bodd (succ n) = bnot (bodd n) := by unfold bodd bodd_div2; cases bodd_div2 n; cases fst; refl @[simp] lemma bodd_add (m n : ℕ) : bodd (m + n) = bxor (bodd m) (bodd n) := begin induction n with n IH, { simp, cases bodd m; refl }, { simp [IH], cases bodd m; cases bodd n; refl } end @[simp] lemma bodd_mul (m n : ℕ) : bodd (m * n) = bodd m && bodd n := begin induction n with n IH, { simp, cases bodd m; refl }, { simp [mul_succ, IH], cases bodd m; cases bodd n; refl } end lemma mod_two_of_bodd (n : ℕ) : n % 2 = cond (bodd n) 1 0 := begin have := congr_arg bodd (mod_add_div n 2), simp [bnot] at this, rw [show ∀ b, ff && b = ff, by intros; cases b; refl, show ∀ b, bxor b ff = b, by intros; cases b; refl] at this, rw [← this], cases mod_two_eq_zero_or_one n with h h; rw h; refl end @[simp] lemma div2_zero : div2 0 = 0 := rfl @[simp] lemma div2_one : div2 1 = 0 := rfl @[simp] lemma div2_two : div2 2 = 1 := rfl @[simp] lemma div2_succ (n : ℕ) : div2 (succ n) = cond (bodd n) (succ (div2 n)) (div2 n) := by unfold bodd div2 bodd_div2; cases bodd_div2 n; cases fst; refl local attribute [simp] nat.add_comm nat.add_assoc nat.add_left_comm nat.mul_comm nat.mul_assoc theorem bodd_add_div2 : ∀ n, cond (bodd n) 1 0 + 2 * div2 n = n | 0 := rfl | (succ n) := begin simp, refine eq.trans _ (congr_arg succ (bodd_add_div2 n)), cases bodd n; simp [cond, bnot], { rw [nat.add_comm, nat.zero_add], }, { rw [succ_mul, nat.add_comm 1, nat.zero_add] } end theorem div2_val (n) : div2 n = n / 2 := begin refine eq_of_mul_eq_mul_left dec_trivial (nat.add_left_cancel (eq.trans _ (nat.mod_add_div n 2).symm)), rw [mod_two_of_bodd, bodd_add_div2] end def bit (b : bool) : ℕ → ℕ := cond b bit1 bit0 lemma bit0_val (n : nat) : bit0 n = 2 * n := calc n + n = 0 + n + n : by rw nat.zero_add ... = n * 2 : rfl ... = 2 * n : nat.mul_comm _ _ lemma bit1_val (n : nat) : bit1 n = 2 * n + 1 := congr_arg succ (bit0_val _) lemma bit_val (b n) : bit b n = 2 * n + cond b 1 0 := by { cases b, apply bit0_val, apply bit1_val } lemma bit_decomp (n : nat) : bit (bodd n) (div2 n) = n := (bit_val _ _).trans $ (nat.add_comm _ _).trans $ bodd_add_div2 _ def bit_cases_on {C : nat → Sort u} (n) (h : ∀ b n, C (bit b n)) : C n := by rw [← bit_decomp n]; apply h @[simp] lemma bit_zero : bit ff 0 = 0 := rfl def shiftl' (b : bool) (m : ℕ) : ℕ → ℕ | 0 := m | (n+1) := bit b (shiftl' n) def shiftl : ℕ → ℕ → ℕ := shiftl' ff @[simp] theorem shiftl_zero (m) : shiftl m 0 = m := rfl @[simp] theorem shiftl_succ (m n) : shiftl m (n + 1) = bit0 (shiftl m n) := rfl def shiftr : ℕ → ℕ → ℕ | m 0 := m | m (n+1) := div2 (shiftr m n) def test_bit (m n : ℕ) : bool := bodd (shiftr m n) def binary_rec {C : nat → Sort u} (z : C 0) (f : ∀ b n, C n → C (bit b n)) : Π n, C n | n := if n0 : n = 0 then by rw n0; exact z else let n' := div2 n in have n' < n, begin change div2 n < n, rw div2_val, apply (div_lt_iff_lt_mul _ _ (succ_pos 1)).2, have := nat.mul_lt_mul_of_pos_left (lt_succ_self 1) (lt_of_le_of_ne (zero_le _) (ne.symm n0)), rwa nat.mul_one at this end, by rw [← show bit (bodd n) n' = n, from bit_decomp n]; exact f (bodd n) n' (binary_rec n') def size : ℕ → ℕ := binary_rec 0 (λ_ _, succ) def bits : ℕ → list bool := binary_rec [] (λb _ IH, b :: IH) def bitwise (f : bool → bool → bool) : ℕ → ℕ → ℕ := binary_rec (λn, cond (f ff tt) n 0) (λa m Ia, binary_rec (cond (f tt ff) (bit a m) 0) (λb n _, bit (f a b) (Ia n))) def lor : ℕ → ℕ → ℕ := bitwise bor def land : ℕ → ℕ → ℕ := bitwise band def ldiff : ℕ → ℕ → ℕ := bitwise (λ a b, a && bnot b) def lxor : ℕ → ℕ → ℕ := bitwise bxor @[simp] lemma binary_rec_zero {C : nat → Sort u} (z : C 0) (f : ∀ b n, C n → C (bit b n)) : binary_rec z f 0 = z := by {rw [binary_rec], refl} /- bitwise ops -/ lemma bodd_bit (b n) : bodd (bit b n) = b := by rw bit_val; simp; cases b; cases bodd n; refl lemma div2_bit (b n) : div2 (bit b n) = n := by rw [bit_val, div2_val, nat.add_comm, add_mul_div_left, div_eq_of_lt, nat.zero_add]; cases b; exact dec_trivial lemma shiftl'_add (b m n) : ∀ k, shiftl' b m (n + k) = shiftl' b (shiftl' b m n) k | 0 := rfl | (k+1) := congr_arg (bit b) (shiftl'_add k) lemma shiftl_add : ∀ m n k, shiftl m (n + k) = shiftl (shiftl m n) k := shiftl'_add _ lemma shiftr_add (m n) : ∀ k, shiftr m (n + k) = shiftr (shiftr m n) k | 0 := rfl | (k+1) := congr_arg div2 (shiftr_add k) lemma shiftl'_sub (b m) : ∀ {n k}, k ≤ n → shiftl' b m (n - k) = shiftr (shiftl' b m n) k | n 0 h := rfl | (n+1) (k+1) h := begin simp [shiftl'], rw [nat.add_comm, shiftr_add], simp [shiftr, div2_bit], apply shiftl'_sub (nat.le_of_succ_le_succ h) end lemma shiftl_sub : ∀ m {n k}, k ≤ n → shiftl m (n - k) = shiftr (shiftl m n) k := shiftl'_sub _ @[simp] lemma test_bit_zero (b n) : test_bit (bit b n) 0 = b := bodd_bit _ _ lemma test_bit_succ (m b n) : test_bit (bit b n) (succ m) = test_bit n m := have bodd (shiftr (shiftr (bit b n) 1) m) = bodd (shiftr n m), by dsimp [shiftr]; rw div2_bit, by rw [← shiftr_add, nat.add_comm] at this; exact this lemma binary_rec_eq {C : nat → Sort u} {z : C 0} {f : ∀ b n, C n → C (bit b n)} (h : f ff 0 z = z) (b n) : binary_rec z f (bit b n) = f b n (binary_rec z f n) := begin rw [binary_rec], with_cases { by_cases bit b n = 0 }, case pos : h' { simp [dif_pos h'], generalize : binary_rec._main._pack._proof_1 (bit b n) h' = e, revert e, have bf := bodd_bit b n, have n0 := div2_bit b n, rw h' at bf n0, simp at bf n0, rw [← bf, ← n0, binary_rec_zero], intros, exact h.symm }, case neg : h' { simp [dif_neg h'], generalize : binary_rec._main._pack._proof_2 (bit b n) = e, revert e, rw [bodd_bit, div2_bit], intros, refl} end lemma bitwise_bit_aux {f : bool → bool → bool} (h : f ff ff = ff) : @binary_rec (λ_, ℕ) (cond (f tt ff) (bit ff 0) 0) (λ b n _, bit (f ff b) (cond (f ff tt) n 0)) = λ (n : ℕ), cond (f ff tt) n 0 := begin funext n, apply bit_cases_on n, intros b n, rw [binary_rec_eq], { cases b; try {rw h}; induction fft : f ff tt; simp [cond]; refl }, { rw [h, show cond (f ff tt) 0 0 = 0, by cases f ff tt; refl, show cond (f tt ff) (bit ff 0) 0 = 0, by cases f tt ff; refl]; refl } end @[simp] lemma bitwise_zero_left (f : bool → bool → bool) (n) : bitwise f 0 n = cond (f ff tt) n 0 := by unfold bitwise; rw [binary_rec_zero] @[simp] lemma bitwise_zero_right (f : bool → bool → bool) (h : f ff ff = ff) (m) : bitwise f m 0 = cond (f tt ff) m 0 := by unfold bitwise; apply bit_cases_on m; intros; rw [binary_rec_eq, binary_rec_zero]; exact bitwise_bit_aux h @[simp] lemma bitwise_zero (f : bool → bool → bool) : bitwise f 0 0 = 0 := by rw bitwise_zero_left; cases f ff tt; refl @[simp] lemma bitwise_bit {f : bool → bool → bool} (h : f ff ff = ff) (a m b n) : bitwise f (bit a m) (bit b n) = bit (f a b) (bitwise f m n) := begin unfold bitwise, rw [binary_rec_eq, binary_rec_eq], { induction ftf : f tt ff; dsimp [cond], rw [show f a ff = ff, by cases a; assumption], apply @congr_arg _ _ _ 0 (bit ff), tactic.swap, rw [show f a ff = a, by cases a; assumption], apply congr_arg (bit a), all_goals { apply bit_cases_on m, intros a m, rw [binary_rec_eq, binary_rec_zero], rw [← bitwise_bit_aux h, ftf], refl } }, { exact bitwise_bit_aux h } end theorem bitwise_swap {f : bool → bool → bool} (h : f ff ff = ff) : bitwise (function.swap f) = function.swap (bitwise f) := begin funext m n, revert n, dsimp [function.swap], apply binary_rec _ (λ a m' IH, _) m; intro n, { rw [bitwise_zero_left, bitwise_zero_right], exact h }, apply bit_cases_on n; intros b n', rw [bitwise_bit, bitwise_bit, IH]; exact h end @[simp] lemma lor_bit : ∀ (a m b n), lor (bit a m) (bit b n) = bit (a || b) (lor m n) := bitwise_bit rfl @[simp] lemma land_bit : ∀ (a m b n), land (bit a m) (bit b n) = bit (a && b) (land m n) := bitwise_bit rfl @[simp] lemma ldiff_bit : ∀ (a m b n), ldiff (bit a m) (bit b n) = bit (a && bnot b) (ldiff m n) := bitwise_bit rfl @[simp] lemma lxor_bit : ∀ (a m b n), lxor (bit a m) (bit b n) = bit (bxor a b) (lxor m n) := bitwise_bit rfl @[simp] lemma test_bit_bitwise {f : bool → bool → bool} (h : f ff ff = ff) (m n k) : test_bit (bitwise f m n) k = f (test_bit m k) (test_bit n k) := begin revert m n; induction k with k IH; intros m n; apply bit_cases_on m; intros a m'; apply bit_cases_on n; intros b n'; rw bitwise_bit h, { simp [test_bit_zero] }, { simp [test_bit_succ, IH] } end @[simp] lemma test_bit_lor : ∀ (m n k), test_bit (lor m n) k = test_bit m k || test_bit n k := test_bit_bitwise rfl @[simp] lemma test_bit_land : ∀ (m n k), test_bit (land m n) k = test_bit m k && test_bit n k := test_bit_bitwise rfl @[simp] lemma test_bit_ldiff : ∀ (m n k), test_bit (ldiff m n) k = test_bit m k && bnot (test_bit n k) := test_bit_bitwise rfl @[simp] lemma test_bit_lxor : ∀ (m n k), test_bit (lxor m n) k = bxor (test_bit m k) (test_bit n k) := test_bit_bitwise rfl end nat
a55878a5cb77e3880e6784d799e56c3433e18210
08a8ee10652ba4f8592710ceb654b37e951d9082
/src/hott/init/trunc.lean
db4f04ec0f164e03de60527f45f96f9d0885fc9c
[ "Apache-2.0" ]
permissive
felixwellen/hott3
e9f299c84d30a782a741c40d38741ec024d391fb
8ac87a2699ab94c23ea7984b4a5fbd5a7052575c
refs/heads/master
1,619,972,899,098
1,509,047,351,000
1,518,040,986,000
120,676,559
0
0
null
1,518,040,503,000
1,518,040,503,000
null
UTF-8
Lean
false
false
13,263
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Floris van Doorn Definition of is_trunc (n-truncatedness) Ported from Coq HoTT. -/ import .equiv .pathover .logic universes u v l hott_theory namespace hott open hott.eq nat sigma unit /- Truncation levels -/ inductive trunc_index : Type | minus_two : trunc_index | succ : trunc_index → trunc_index open trunc_index /- notation for trunc_index is -2, -1, 0, 1, ... from 0 and up this comes from the way numerals are parsed in Lean. Any structure with a 0, a 1, and a + have numerals defined in them. -/ notation `ℕ₋₂` := trunc_index -- input using \N-2 instance has_zero_trunc_index : has_zero ℕ₋₂ := has_zero.mk (succ (succ minus_two)) instance has_one_trunc_index : has_one ℕ₋₂ := has_one.mk (succ (succ (succ minus_two))) namespace trunc_index notation `-1` := trunc_index.succ trunc_index.minus_two -- ISSUE: -1 gets printed as -2.+1? notation `-2` := trunc_index.minus_two postfix `.+1`:(max+1) := trunc_index.succ postfix `.+2`:(max+1) := λn, (n .+1 .+1) --addition, where we add two to the result @[hott] def add_plus_two (n m : ℕ₋₂) : ℕ₋₂ := trunc_index.rec_on m n (λ k l, l .+1) infix ` +2+ `:65 := trunc_index.add_plus_two -- addition of trunc_indices, where results smaller than -2 are changed to -2 @[hott] protected def add (n m : ℕ₋₂) : ℕ₋₂ := trunc_index.cases_on m (trunc_index.cases_on n -2 (λn', (trunc_index.cases_on n' -2 id))) (λm', trunc_index.cases_on m' (trunc_index.cases_on n -2 id) (add_plus_two n)) /- we give a weird name to the reflexivity step to avoid overloading le.refl (which can be used if types.trunc is imported) -/ inductive le (a : ℕ₋₂) : ℕ₋₂ → Type | tr_refl : le a | step : Π {b}, le b → le (b.+1) attribute [refl] le.tr_refl end trunc_index local infix ` ≤ ` := trunc_index.le -- TODO(gabriel) instance has_add_trunc_index : has_add ℕ₋₂ := has_add.mk trunc_index.add namespace trunc_index @[hott] def sub_two (n : ℕ) : ℕ₋₂ := nat.rec_on n -2 (λ n k, k.+1) @[hott] def add_two (n : ℕ₋₂) : ℕ := trunc_index.rec_on n nat.zero (λ n k, nat.succ k) postfix `.-2`:(max+1) := sub_two postfix `.-1`:(max+1) := λn, (n .-2 .+1) @[hott] def of_nat (n : ℕ) : ℕ₋₂ := n.-2.+2 instance: has_coe ℕ ℕ₋₂ := ⟨of_nat⟩ @[hott] def succ_le_succ {n m : ℕ₋₂} (H : n ≤ m) : n.+1 ≤ m.+1 := begin induction H, refl, apply le.step; assumption end @[hott] def minus_two_le (n : ℕ₋₂) : -2 ≤ n := begin induction n, refl, apply le.step; assumption end end trunc_index open trunc_index namespace is_trunc -- export [notation] [coercion] trunc_index /- truncated types -/ /- Just as in Coq HoTT we define an internal version of contractibility and is_trunc, but we only use `is_trunc` and `is_contr` -/ structure contr_internal (A : Type u) := (center : A) (center_eq : Π(a : A), center = a) @[hott] def is_trunc_internal (n : ℕ₋₂) : Type u → Type u := trunc_index.rec_on n (λA, contr_internal A) (λn trunc_n A, (Π(x y : A), trunc_n (x = y))) end is_trunc open is_trunc class is_trunc (n : ℕ₋₂) (A : Type u) := (to_internal : is_trunc_internal n A) open nat trunc_index namespace is_trunc notation `is_contr` := is_trunc -2 notation `is_prop` := is_trunc -1 notation `is_set` := is_trunc 0 variables {A : Type u} {B : Type v} @[hott] def is_trunc_succ_intro {A : Type _} {n : ℕ₋₂} (H : ∀x y : A, is_trunc n (x = y)) : is_trunc n.+1 A := is_trunc.mk (λ x y, is_trunc.to_internal _ _) @[hott, instance] def is_trunc_eq (n : ℕ₋₂) [H : is_trunc (n.+1) A] (x y : A) : is_trunc n (x = y) := is_trunc.mk (is_trunc.to_internal (n.+1) A x y) /- contractibility -/ @[hott] def is_contr.mk (center : A) (center_eq : Π(a : A), center = a) : is_contr A := is_trunc.mk (contr_internal.mk center center_eq) @[hott] def center (A : Type _) [H : is_contr A] : A := contr_internal.center (is_trunc.to_internal -2 A) @[hott] def center' {A : Type _} (H : is_contr A) : A := center A @[hott] def center_eq [H : is_contr A] (a : A) : center _ = a := contr_internal.center_eq (is_trunc.to_internal -2 A) a @[hott] def eq_of_is_contr [H : is_contr A] (x y : A) : x = y := (center_eq x)⁻¹ ⬝ (center_eq y) @[hott] def prop_eq_of_is_contr {A : Type _} [H : is_contr A] {x y : A} (p q : x = y) : p = q := have K : ∀ (r : x = y), eq_of_is_contr x y = r, from (λ r, by induction r; apply con.left_inv), (K p)⁻¹ ⬝ K q @[hott] def is_contr_eq {A : Type _} [H : is_contr A] (x y : A) : is_contr (x = y) := is_contr.mk (eq_of_is_contr _ _) (λ p, prop_eq_of_is_contr _ _) /- truncation is upward close -/ -- n-types are also (n+1)-types @[hott, instance] def is_trunc_succ (A : Type _) (n : ℕ₋₂) [H : is_trunc n A] : is_trunc (n.+1) A := begin induction n with n IH generalizing A; apply is_trunc_succ_intro; intros x y, { exact @is_contr_eq A H x y }, { refine @IH _ (@is_trunc_eq _ _ H _ _) , } end --in the proof the type of H is given explicitly to make it available for class inference @[hott] def is_trunc_of_le (A : Type.{l}) {n m : ℕ₋₂} (Hnm : n ≤ m) [Hn : is_trunc n A] : is_trunc m A := begin induction Hnm with m Hnm IH, { exact Hn }, { exact @is_trunc_succ _ _ IH } end @[hott] def is_trunc_of_imp_is_trunc {n : ℕ₋₂} (H : A → is_trunc (n.+1) A) : is_trunc (n.+1) A := @is_trunc_succ_intro _ _ (λx y, @is_trunc_eq _ _ (H x) x y) @[hott] def is_trunc_of_imp_is_trunc_of_le {n : ℕ₋₂} (Hn : -1 ≤ n) (H : A → is_trunc n A) : is_trunc n A := begin induction Hn with n' Hn'; apply is_trunc_of_imp_is_trunc H end -- these must be definitions, because we need them to compute sometimes @[hott] def is_trunc_of_is_contr (A : Type _) (n : ℕ₋₂) [H : is_contr A] : is_trunc n A := trunc_index.rec_on n H (λn H, by apply_instance) @[hott] def is_trunc_succ_of_is_prop (A : Type _) (n : ℕ₋₂) [H : is_prop A] : is_trunc (n.+1) A := is_trunc_of_le A (show -1 ≤ n.+1, from succ_le_succ (minus_two_le n)) @[hott] def is_trunc_succ_succ_of_is_set (A : Type _) (n : ℕ₋₂) [H : is_set A] : is_trunc (n.+2) A := is_trunc_of_le A (show 0 ≤ n.+2, from succ_le_succ (succ_le_succ (minus_two_le n))) /- props -/ @[hott] def is_prop.elim [H : is_prop A] (x y : A) : x = y := by apply center @[hott] def is_prop.elim' (x y : A) (H : is_prop A) : x = y := is_prop.elim x y @[hott] def is_contr_of_inhabited_prop {A : Type _} [H : is_prop A] (x : A) : is_contr A := is_contr.mk x (λy, by apply is_prop.elim) @[hott] def is_prop_of_imp_is_contr {A : Type _} (H : A → is_contr A) : is_prop A := @is_trunc_succ_intro A -2 (λx y, have H2 : is_contr A, from H x, by apply is_contr_eq) @[hott] def is_prop.mk {A : Type _} (H : ∀x y : A, x = y) : is_prop A := is_prop_of_imp_is_contr (λ x, is_contr.mk x (H x)) @[hott] def is_prop_elim_self {A : Type _} {H : is_prop A} (x : A) : is_prop.elim x x = idp := by apply is_prop.elim /- sets -/ @[hott] def is_set.mk (A : Type _) (H : ∀(x y : A) (p q : x = y), p = q) : is_set A := @is_trunc_succ_intro _ _ (λ x y, is_prop.mk (H x y)) @[hott] def is_set.elim [H : is_set A] ⦃x y : A⦄ (p q : x = y) : p = q := by apply is_prop.elim @[hott] def is_set.elim' ⦃x y : A⦄ (p q : x = y) (H : is_set A) : p = q := is_set.elim p q /- instances -/ @[instance, hott] def is_contr_sigma_eq {A : Type u} (a : A) : is_contr (Σ(x : A), a = x) := is_contr.mk (sigma.mk a idp) (λ ⟨b,q⟩, by induction q; refl) @[instance, hott] def is_contr_sigma_eq' {A : Type u} (a : A) : is_contr (Σ(x : A), x = a) := is_contr.mk (sigma.mk a idp) (λ ⟨b,q⟩, by clear _fun_match; induction q; refl) @[hott] def ap_fst_center_eq_sigma_eq {A : Type _} {a x : A} (p : a = x) : ap sigma.fst (center_eq ⟨x, p⟩) = p := by induction p; reflexivity @[hott] def ap_fst_center_eq_sigma_eq' {A : Type _} {a x : A} (p : x = a) : ap sigma.fst (center_eq ⟨x, p⟩) = p⁻¹ := by induction p; reflexivity @[hott] def is_contr_unit : is_contr unit := is_contr.mk star (λp, unit.rec_on p idp) @[hott] def is_prop_empty : is_prop empty := is_prop.mk (λx, by induction x) local attribute [instance] is_contr_unit is_prop_empty @[hott,instance] def is_trunc_unit (n : ℕ₋₂) : is_trunc n unit := by apply is_trunc_of_is_contr @[hott,instance] def is_trunc_empty (n : ℕ₋₂) : is_trunc (n.+1) empty := by apply is_trunc_succ_of_is_prop /- interaction with equivalences -/ section open hott.is_equiv hott.equiv @[hott] def is_contr_is_equiv_closed (f : A → B) [Hf : is_equiv f] [HA: is_contr A] : (is_contr B) := is_contr.mk (f (center A)) (λp, eq_of_eq_inv (center_eq _)) @[hott] def is_contr_equiv_closed (H : A ≃ B) [HA: is_contr A] : is_contr B := is_contr_is_equiv_closed H @[hott] def equiv_of_is_contr_of_is_contr [HA : is_contr A] [HB : is_contr B] : A ≃ B := equiv.mk (λa, center B) (is_equiv.adjointify (λa, center B) (λb, center A) center_eq center_eq) @[hott] def is_trunc_is_equiv_closed (n : ℕ₋₂) (f : A → B) [H : is_equiv f] (HA : is_trunc n A) : is_trunc n B := begin revert A B f H HA, induction n with n IH; intros, { exact is_contr_is_equiv_closed f }, { apply is_trunc_succ_intro, intros, apply IH (ap f⁻¹ᶠ)⁻¹ᶠ, all_goals {apply_instance} } end @[hott] def is_trunc_is_equiv_closed_rev (n : ℕ₋₂) (f : A → B) [H : is_equiv f] (HA : is_trunc n B) : is_trunc n A := is_trunc_is_equiv_closed n f⁻¹ᶠ HA @[hott] def is_trunc_equiv_closed (n : ℕ₋₂) (f : A ≃ B) (HA : is_trunc n A) : is_trunc n B := is_trunc_is_equiv_closed n f HA @[hott] def is_trunc_equiv_closed_rev (n : ℕ₋₂) (f : A ≃ B) (HA : is_trunc n B) : is_trunc n A := is_trunc_is_equiv_closed n f⁻¹ᶠ HA @[hott] def is_equiv_of_is_prop [HA : is_prop A] [HB : is_prop B] (f : A → B) (g : B → A) : is_equiv f := by fapply is_equiv.mk f g; intros; {apply is_prop.elim <|> apply is_set.elim} @[hott] def is_equiv_of_is_contr [HA : is_contr A] [HB : is_contr B] (f : A → B) : is_equiv f := by fapply is_equiv.mk f; intros; {apply center <|> apply is_prop.elim <|> apply is_set.elim} @[hott] def equiv_of_is_prop [HA : is_prop A] [HB : is_prop B] (f : A → B) (g : B → A) : A ≃ B := equiv.mk f (is_equiv_of_is_prop f g) @[hott] def equiv_of_iff_of_is_prop [HA : is_prop A] [HB : is_prop B] (H : A ↔ B) : A ≃ B := equiv_of_is_prop (iff.elim_left H) (iff.elim_right H) /- truncatedness of lift -/ @[hott,instance] def is_trunc_lift (A : Type _) (n : ℕ₋₂) [H : is_trunc n A] : is_trunc n (ulift A) := is_trunc_equiv_closed _ (equiv_lift _) H end /- interaction with the Unit type -/ open equiv /- A contractible type is equivalent to unit. -/ variable (A) @[hott] def equiv_unit_of_is_contr [H : is_contr A] : A ≃ unit := equiv.MK (λ (x : A), ()) (λ (u : unit), center A) (λ (u : unit), unit.rec_on u idp) (λ (x : A), center_eq x) /- interaction with pathovers -/ variable {A} variables {C : A → Type _} {a a₂ : A} (p : a = a₂) (c : C a) (c₂ : C a₂) instance is_trunc_pathover (n : ℕ₋₂) [H : is_trunc (n.+1) (C a)] : is_trunc n (c =[p] c₂) := begin refine @is_trunc_equiv_closed_rev _ _ n _ _, tactic.swap, apply pathover_equiv_eq_tr, apply is_trunc_eq, end @[hott] def is_prop.elimo [H : is_prop (C a)] : c =[p] c₂ := pathover_of_eq_tr (by apply is_prop.elim) @[hott] def is_prop.elimo' (H : is_prop (C a)) : c =[p] c₂ := is_prop.elimo p c c₂ @[hott] def is_prop_elimo_self {A : Type _} (B : A → Type _) {a : A} (b : B a) {H : is_prop (B a)} : @is_prop.elimo A B a a idp b b H = idpo := by apply is_prop.elim variables {p c c₂} @[hott] def is_set.elimo (q q' : c =[p] c₂) [H : is_set (C a)] : q = q' := by apply is_prop.elim -- TODO: port "Truncated morphisms" /- truncated universe -/ end is_trunc structure trunctype (n : ℕ₋₂) := (carrier : Type u) (struct : is_trunc n carrier) @[hott] instance (n): has_coe_to_sort (trunctype n) := { S := Type u, coe := trunctype.carrier } notation n `-Type` := trunctype n hott_theory_cmd "local notation Prop := -1-Type" notation `Set` := 0-Type -- attribute trunctype.carrier [coercion] attribute [instance] trunctype.struct notation `Prop.mk` := @trunctype.mk -1 notation `Set.mk` := @trunctype.mk (-1.+1) @[hott] protected def trunctype.mk' (n : ℕ₋₂) (A : Type _) [H : is_trunc n A] : n-Type := trunctype.mk A H namespace is_trunc @[hott] def tlift {n : ℕ₋₂} (A : trunctype.{u} n) : trunctype.{max u v} n := trunctype.mk (ulift A) (is_trunc_lift _ _) end is_trunc end hott
5f9916deca64524d82797e7f64fff32c0ac22632
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/data/sym2.lean
5c41a2e062a6de92b83e95aa015f60f29b0b7d83
[ "Apache-2.0" ]
permissive
ilitzroth/mathlib
ea647e67f1fdfd19a0f7bdc5504e8acec6180011
5254ef14e3465f6504306132fe3ba9cec9ffff16
refs/heads/master
1,680,086,661,182
1,617,715,647,000
1,617,715,647,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
13,744
lean
/- Copyright (c) 2020 Kyle Miller All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kyle Miller -/ import tactic.linarith import data.sym open function open sym /-! # The symmetric square This file defines the symmetric square, which is `α × α` modulo swapping. This is also known as the type of unordered pairs. More generally, the symmetric square is the second symmetric power (see `data.sym`). The equivalence is `sym2.equiv_sym`. From the point of view that an unordered pair is equivalent to a multiset of cardinality two (see `sym2.equiv_multiset`), there is a `has_mem` instance `sym2.mem`, which is a `Prop`-valued membership test. Given `h : a ∈ z` for `z : sym2 α`, then `h.other` is the other element of the pair, defined using `classical.choice`. If `α` has decidable equality, then `h.other'` computably gives the other element. Recall that an undirected graph (allowing self loops, but no multiple edges) is equivalent to a symmetric relation on the vertex type `α`. Given a symmetric relation on `α`, the corresponding edge set is constructed by `sym2.from_rel`. ## Notation The symmetric square has a setoid instance, so `⟦(a, b)⟧` denotes a term of the symmetric square. ## Tags symmetric square, unordered pairs, symmetric powers -/ universe u variables {α : Type u} namespace sym2 /-- This is the relation capturing the notion of pairs equivalent up to permutations. -/ inductive rel (α : Type u) : (α × α) → (α × α) → Prop | refl (x y : α) : rel (x, y) (x, y) | swap (x y : α) : rel (x, y) (y, x) attribute [refl] rel.refl @[symm] lemma rel.symm {x y : α × α} : rel α x y → rel α y x := by rintro ⟨_, _⟩; constructor @[trans] lemma rel.trans {x y z : α × α} : rel α x y → rel α y z → rel α x z := by { intros a b, cases_matching* rel _ _ _; apply rel.refl <|> apply rel.swap } lemma rel.is_equivalence : equivalence (rel α) := by tidy; apply rel.trans; assumption instance rel.setoid (α : Type u) : setoid (α × α) := ⟨rel α, rel.is_equivalence⟩ end sym2 /-- `sym2 α` is the symmetric square of `α`, which, in other words, is the type of unordered pairs. It is equivalent in a natural way to multisets of cardinality 2 (see `sym2.equiv_multiset`). -/ @[reducible] def sym2 (α : Type u) := quotient (sym2.rel.setoid α) namespace sym2 lemma eq_swap {a b : α} : ⟦(a, b)⟧ = ⟦(b, a)⟧ := by { rw quotient.eq, apply rel.swap } lemma congr_right {a b c : α} : ⟦(a, b)⟧ = ⟦(a, c)⟧ ↔ b = c := by { split; intro h, { rw quotient.eq at h, cases h; refl }, rw h } lemma congr_left {a b c : α} : ⟦(b, a)⟧ = ⟦(c, a)⟧ ↔ b = c := by { split; intro h, { rw quotient.eq at h, cases h; refl }, rw h } /-- The functor `sym2` is functorial, and this function constructs the induced maps. -/ def map {α β : Type*} (f : α → β) : sym2 α → sym2 β := quotient.map (prod.map f f) (by { rintros _ _ h, cases h, { refl }, apply rel.swap }) @[simp] lemma map_id : sym2.map (@id α) = id := by tidy lemma map_comp {α β γ : Type*} {g : β → γ} {f : α → β} : sym2.map (g ∘ f) = sym2.map g ∘ sym2.map f := by tidy @[simp] lemma map_pair_eq {α β : Type*} (f : α → β) (x y : α) : map f ⟦(x, y)⟧ = ⟦(f x, f y)⟧ := by simp [map] section membership /-! ### Declarations about membership -/ /-- This is a predicate that determines whether a given term is a member of a term of the symmetric square. From this point of view, the symmetric square is the subtype of cardinality-two multisets on `α`. -/ def mem (x : α) (z : sym2 α) : Prop := ∃ (y : α), z = ⟦(x, y)⟧ instance : has_mem α (sym2 α) := ⟨mem⟩ lemma mk_has_mem (x y : α) : x ∈ ⟦(x, y)⟧ := ⟨y, rfl⟩ lemma mk_has_mem_right (x y : α) : y ∈ ⟦(x, y)⟧ := by { rw eq_swap, apply mk_has_mem } /-- Given an element of the unordered pair, give the other element using `classical.some`. See also `mem.other'` for the computable version. -/ noncomputable def mem.other {a : α} {z : sym2 α} (h : a ∈ z) : α := classical.some h @[simp] lemma mem_other_spec {a : α} {z : sym2 α} (h : a ∈ z) : ⟦(a, h.other)⟧ = z := by erw ← classical.some_spec h lemma eq_iff {x y z w : α} : ⟦(x, y)⟧ = ⟦(z, w)⟧ ↔ (x = z ∧ y = w) ∨ (x = w ∧ y = z) := begin split; intro h, { rw quotient.eq at h, cases h; tidy }, { cases h; rw [h.1, h.2], rw eq_swap } end @[simp] lemma mem_iff {a b c : α} : a ∈ ⟦(b, c)⟧ ↔ a = b ∨ a = c := { mp := by { rintro ⟨_, h⟩, rw eq_iff at h, tidy }, mpr := by { rintro ⟨_⟩; subst a, { apply mk_has_mem }, apply mk_has_mem_right } } lemma mem_other_mem {a : α} {z : sym2 α} (h : a ∈ z) : h.other ∈ z := by { convert mk_has_mem_right a h.other, rw mem_other_spec h } lemma elems_iff_eq {x y : α} {z : sym2 α} (hne : x ≠ y) : x ∈ z ∧ y ∈ z ↔ z = ⟦(x, y)⟧ := begin split, { refine quotient.rec_on_subsingleton z _, rintros ⟨z₁, z₂⟩ ⟨hx, hy⟩, rw eq_iff, cases mem_iff.mp hx with hx hx; cases mem_iff.mp hy with hy hy; cc }, { rintro rfl, simp }, end @[ext] lemma sym2_ext (z z' : sym2 α) (h : ∀ x, x ∈ z ↔ x ∈ z') : z = z' := begin refine quotient.rec_on_subsingleton z (λ w, _) h, refine quotient.rec_on_subsingleton z' (λ w', _), intro h, cases w with x y, cases w' with x' y', simp only [mem_iff] at h, apply eq_iff.mpr, have hx := h x, have hy := h y, have hx' := h x', have hy' := h y', simp only [true_iff, true_or, eq_self_iff_true, iff_true, or_true] at hx hy hx' hy', cases hx; subst x; cases hy; subst y; cases hx'; try { subst x' }; cases hy'; try { subst y' }; cc, end instance mem.decidable [decidable_eq α] (x : α) (z : sym2 α) : decidable (x ∈ z) := quotient.rec_on_subsingleton z (λ ⟨y₁, y₂⟩, decidable_of_iff' _ mem_iff) end membership /-- A type `α` is naturally included in the diagonal of `α × α`, and this function gives the image of this diagonal in `sym2 α`. -/ def diag (x : α) : sym2 α := ⟦(x, x)⟧ /-- A predicate for testing whether an element of `sym2 α` is on the diagonal. -/ def is_diag (z : sym2 α) : Prop := z ∈ set.range (@diag α) @[simp] lemma diag_is_diag (a : α) : is_diag (diag a) := by use a @[simp] lemma is_diag_iff_proj_eq (z : α × α) : is_diag ⟦z⟧ ↔ z.1 = z.2 := begin cases z with a, split, { rintro ⟨_, h⟩, dsimp only, erw eq_iff at h, rcases h; cc }, { rintro ⟨⟩, use a, refl }, end instance is_diag.decidable_pred (α : Type u) [decidable_eq α] : decidable_pred (@is_diag α) := by { refine λ z, quotient.rec_on_subsingleton z (λ a, _), erw is_diag_iff_proj_eq, apply_instance } lemma mem_other_ne {a : α} {z : sym2 α} (hd : ¬is_diag z) (h : a ∈ z) : h.other ≠ a := begin intro hn, apply hd, have h' := sym2.mem_other_spec h, rw hn at h', rw ←h', simp, end section relations /-! ### Declarations about symmetric relations -/ variables {r : α → α → Prop} /-- Symmetric relations define a set on `sym2 α` by taking all those pairs of elements that are related. -/ def from_rel (sym : symmetric r) : set (sym2 α) := quotient.lift (uncurry r) (by { rintros _ _ ⟨_, _⟩, tidy }) @[simp] lemma from_rel_proj_prop {sym : symmetric r} {z : α × α} : ⟦z⟧ ∈ from_rel sym ↔ r z.1 z.2 := iff.rfl @[simp] lemma from_rel_prop {sym : symmetric r} {a b : α} : ⟦(a, b)⟧ ∈ from_rel sym ↔ r a b := by simp only [from_rel_proj_prop] lemma from_rel_irreflexive {sym : symmetric r} : irreflexive r ↔ ∀ {z}, z ∈ from_rel sym → ¬is_diag z := { mp := by { intros h z hr hd, induction z, erw is_diag_iff_proj_eq at hd, erw from_rel_proj_prop at hr, tidy }, mpr := by { intros h x hr, rw ← @from_rel_prop _ _ sym at hr, exact h hr ⟨x, rfl⟩ }} lemma mem_from_rel_irrefl_other_ne {sym : symmetric r} (irrefl : irreflexive r) {a : α} {z : sym2 α} (hz : z ∈ from_rel sym) (h : a ∈ z) : h.other ≠ a := mem_other_ne (from_rel_irreflexive.mp irrefl hz) h instance from_rel.decidable_pred (sym : symmetric r) [h : decidable_rel r] : decidable_pred (sym2.from_rel sym) := λ z, quotient.rec_on_subsingleton z (λ x, h _ _) end relations section sym_equiv /-! ### Equivalence to the second symmetric power -/ local attribute [instance] vector.perm.is_setoid private def from_vector {α : Type*} : vector α 2 → α × α | ⟨[a, b], h⟩ := (a, b) private lemma perm_card_two_iff {α : Type*} {a₁ b₁ a₂ b₂ : α} : [a₁, b₁].perm [a₂, b₂] ↔ (a₁ = a₂ ∧ b₁ = b₂) ∨ (a₁ = b₂ ∧ b₁ = a₂) := { mp := by { simp [← multiset.coe_eq_coe, ← multiset.cons_coe, multiset.cons_eq_cons]; tidy }, mpr := by { intro h, cases h; rw [h.1, h.2], apply list.perm.swap', refl } } /-- The symmetric square is equivalent to length-2 vectors up to permutations. -/ def sym2_equiv_sym' {α : Type*} : equiv (sym2 α) (sym' α 2) := { to_fun := quotient.map (λ (x : α × α), ⟨[x.1, x.2], rfl⟩) (by { rintros _ _ ⟨_⟩, { refl }, apply list.perm.swap', refl }), inv_fun := quotient.map from_vector (begin rintros ⟨x, hx⟩ ⟨y, hy⟩ h, cases x with _ x, { simpa using hx, }, cases x with _ x, { simpa using hx, }, cases x with _ x, swap, { exfalso, simp at hx, linarith [hx] }, cases y with _ y, { simpa using hy, }, cases y with _ y, { simpa using hy, }, cases y with _ y, swap, { exfalso, simp at hy, linarith [hy] }, rcases perm_card_two_iff.mp h with ⟨rfl,rfl⟩|⟨rfl,rfl⟩, { refl }, apply sym2.rel.swap, end), left_inv := by tidy, right_inv := λ x, begin refine quotient.rec_on_subsingleton x (λ x, _), { cases x with x hx, cases x with _ x, { simpa using hx, }, cases x with _ x, { simpa using hx, }, cases x with _ x, swap, { exfalso, simp at hx, linarith [hx] }, refl }, end } /-- The symmetric square is equivalent to the second symmetric power. -/ def equiv_sym (α : Type*) : sym2 α ≃ sym α 2 := equiv.trans sym2_equiv_sym' sym_equiv_sym'.symm /-- The symmetric square is equivalent to multisets of cardinality two. (This is currently a synonym for `equiv_sym`, but it's provided in case the definition for `sym` changes.) -/ def equiv_multiset (α : Type*) : sym2 α ≃ {s : multiset α // s.card = 2} := equiv_sym α end sym_equiv section decidable /-- An algorithm for computing `sym2.rel`. -/ def rel_bool [decidable_eq α] (x y : α × α) : bool := if x.1 = y.1 then x.2 = y.2 else if x.1 = y.2 then x.2 = y.1 else ff lemma rel_bool_spec [decidable_eq α] (x y : α × α) : ↥(rel_bool x y) ↔ rel α x y := begin cases x with x₁ x₂, cases y with y₁ y₂, dsimp [rel_bool], split_ifs; simp only [false_iff, bool.coe_sort_ff, bool.of_to_bool_iff], rotate 2, { contrapose! h, cases h; cc }, all_goals { subst x₁, split; intro h1, { subst h1; apply sym2.rel.swap }, { cases h1; cc } } end /-- Given `[decidable_eq α]` and `[fintype α]`, the following instance gives `fintype (sym2 α)`. -/ instance (α : Type*) [decidable_eq α] : decidable_rel (sym2.rel α) := λ x y, decidable_of_bool (rel_bool x y) (rel_bool_spec x y) /-- A function that gives the other element of a pair given one of the elements. Used in `mem.other'`. -/ private def pair_other [decidable_eq α] (a : α) (z : α × α) : α := if a = z.1 then z.2 else z.1 /-- Get the other element of the unordered pair using the decidable equality. This is the computable version of `mem.other`. -/ def mem.other' [decidable_eq α] {a : α} {z : sym2 α} (h : a ∈ z) : α := quot.rec (λ x h', pair_other a x) (begin clear h z, intros x y h, ext hy, convert_to pair_other a x = _, { have h' : ∀ {c e h}, @eq.rec _ ⟦x⟧ (λ s, a ∈ s → α) (λ _, pair_other a x) c e h = pair_other a x, { intros _ e _, subst e }, apply h', }, have h' := (rel_bool_spec x y).mpr h, cases x with x₁ x₂, cases y with y₁ y₂, cases mem_iff.mp hy with hy'; subst a; dsimp [rel_bool] at h'; split_ifs at h'; try { rw bool.of_to_bool_iff at h', subst x₁, subst x₂ }; dsimp [pair_other], simp only [ne.symm h_1, if_true, eq_self_iff_true, if_false], exfalso, exact bool.not_ff h', simp only [h_1, if_true, eq_self_iff_true, if_false], exfalso, exact bool.not_ff h', end) z h @[simp] lemma mem_other_spec' [decidable_eq α] {a : α} {z : sym2 α} (h : a ∈ z) : ⟦(a, h.other')⟧ = z := begin induction z, cases z with x y, have h' := mem_iff.mp h, dsimp [mem.other', quot.rec, pair_other], cases h'; subst a, { simp only [if_true, eq_self_iff_true], refl, }, { split_ifs, subst h_1, refl, rw eq_swap, refl, }, refl, end @[simp] lemma other_eq_other' [decidable_eq α] {a : α} {z : sym2 α} (h : a ∈ z) : h.other = h.other' := by rw [←congr_right, mem_other_spec' h, mem_other_spec] lemma mem_other_mem' [decidable_eq α] {a : α} {z : sym2 α} (h : a ∈ z) : h.other' ∈ z := by { rw ←other_eq_other', exact mem_other_mem h } lemma other_invol' [decidable_eq α] {a : α} {z : sym2 α} (ha : a ∈ z) (hb : ha.other' ∈ z): hb.other' = a := begin induction z, cases z with x y, dsimp [mem.other', quot.rec, pair_other] at hb, split_ifs at hb; dsimp [mem.other', quot.rec, pair_other], simp only [h, if_true, eq_self_iff_true], split_ifs, assumption, refl, simp only [h, if_false, if_true, eq_self_iff_true], cases mem_iff.mp ha; cc, refl, end lemma other_invol {a : α} {z : sym2 α} (ha : a ∈ z) (hb : ha.other ∈ z): hb.other = a := begin classical, rw other_eq_other' at hb ⊢, convert other_invol' ha hb, rw other_eq_other', end end decidable end sym2
76db5f8f8ceda6543580bf178bdfccde3093334c
5749d8999a76f3a8fddceca1f6941981e33aaa96
/src/ring_theory/adjoin_root.lean
6eec11df42f42f9f08e7b84359c8457adb73e1aa
[ "Apache-2.0" ]
permissive
jdsalchow/mathlib
13ab43ef0d0515a17e550b16d09bd14b76125276
497e692b946d93906900bb33a51fd243e7649406
refs/heads/master
1,585,819,143,348
1,580,072,892,000
1,580,072,892,000
154,287,128
0
0
Apache-2.0
1,540,281,610,000
1,540,281,609,000
null
UTF-8
Lean
false
false
3,421
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Chris Hughes Adjoining roots of polynomials -/ import data.polynomial ring_theory.principal_ideal_domain noncomputable theory universes u v w variables {α : Type u} {β : Type v} {γ : Type w} open polynomial ideal def adjoin_root [comm_ring α] (f : polynomial α) : Type u := ideal.quotient (span {f} : ideal (polynomial α)) namespace adjoin_root section comm_ring variables [comm_ring α] (f : polynomial α) instance : comm_ring (adjoin_root f) := ideal.quotient.comm_ring _ instance : decidable_eq (adjoin_root f) := classical.dec_eq _ variable {f} def mk : polynomial α → adjoin_root f := ideal.quotient.mk _ def root : adjoin_root f := mk X def of (x : α) : adjoin_root f := mk (C x) instance adjoin_root.has_coe_t : has_coe_t α (adjoin_root f) := ⟨of⟩ instance mk.is_ring_hom : is_ring_hom (mk : polynomial α → adjoin_root f) := ideal.quotient.is_ring_hom_mk _ @[simp] lemma mk_self : (mk f : adjoin_root f) = 0 := quotient.sound' (mem_span_singleton.2 $ by simp) instance : is_ring_hom (coe : α → adjoin_root f) := @is_ring_hom.comp _ _ _ _ C _ _ _ mk mk.is_ring_hom lemma eval₂_root (f : polynomial α) : f.eval₂ coe (root : adjoin_root f) = 0 := quotient.induction_on' (root : adjoin_root f) (λ (g : polynomial α) (hg : mk g = mk X), show finsupp.sum f (λ (e : ℕ) (a : α), mk (C a) * mk g ^ e) = 0, by simp only [hg, (is_semiring_hom.map_pow (mk : polynomial α → adjoin_root f) _ _).symm, (is_ring_hom.map_mul (mk : polynomial α → adjoin_root f)).symm]; rw [finsupp.sum, f.support.sum_hom (mk : polynomial α → adjoin_root f), show finset.sum _ _ = _, from sum_C_mul_X_eq _, mk_self]) (show (root : adjoin_root f) = mk X, from rfl) lemma is_root_root (f : polynomial α) : is_root (f.map coe) (root : adjoin_root f) := by rw [is_root, eval_map, eval₂_root] variables [comm_ring β] def lift (i : α → β) [is_ring_hom i] (x : β) (h : f.eval₂ i x = 0) : (adjoin_root f) → β := ideal.quotient.lift _ (eval₂ i x) $ λ g H, begin simp [mem_span_singleton] at H, cases H with y H, rw [H, eval₂_mul], simp [h] end variables {i : α → β} [is_ring_hom i] {a : β} {h : f.eval₂ i a = 0} @[simp] lemma lift_mk {g : polynomial α} : lift i a h (mk g) = g.eval₂ i a := ideal.quotient.lift_mk @[simp] lemma lift_root : lift i a h root = a := by simp [root, h] @[simp] lemma lift_of {x : α} : lift i a h x = i x := by show lift i a h (ideal.quotient.mk _ (C x)) = i x; convert ideal.quotient.lift_mk; simp instance is_ring_hom_lift : is_ring_hom (lift i a h) := by unfold lift; apply_instance end comm_ring variables [discrete_field α] {f : polynomial α} [irreducible f] instance is_maximal_span : is_maximal (span {f} : ideal (polynomial α)) := principal_ideal_domain.is_maximal_of_irreducible ‹irreducible f› noncomputable instance field : discrete_field (adjoin_root f) := ideal.quotient.field (span {f} : ideal (polynomial α)) lemma coe_injective : function.injective (coe : α → adjoin_root f) := is_ring_hom.injective _ lemma mul_div_root_cancel (f : polynomial α) [irreducible f] : (X - C (root : adjoin_root f)) * (f.map coe / (X - C root)) = f.map coe := mul_div_eq_iff_is_root.2 $ is_root_root _ end adjoin_root
96e6b05c07cd24c8d45aaa94dc4f12fba46fa0af
a7eef317ddec01b9fc6cfbb876fe7ac00f205ac7
/src/category_theory/limits/shapes/finite_products.lean
eb3d92275e50f20a5f66ec9aec3dc59c33a6b936
[ "Apache-2.0" ]
permissive
kmill/mathlib
ea5a007b67ae4e9e18dd50d31d8aa60f650425ee
1a419a9fea7b959317eddd556e1bb9639f4dcc05
refs/heads/master
1,668,578,197,719
1,593,629,163,000
1,593,629,163,000
276,482,939
0
0
null
1,593,637,960,000
1,593,637,959,000
null
UTF-8
Lean
false
false
1,579
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.limits.shapes.finite_limits universes v u open category_theory namespace category_theory.limits variables (C : Type u) [category.{v} C] class has_finite_products := (has_limits_of_shape : Π (J : Type v) [fintype J] [decidable_eq J], has_limits_of_shape (discrete J) C) class has_finite_coproducts := (has_colimits_of_shape : Π (J : Type v) [fintype J] [decidable_eq J], has_colimits_of_shape (discrete J) C) attribute [instance] has_finite_products.has_limits_of_shape has_finite_coproducts.has_colimits_of_shape @[priority 100] -- see Note [lower instance priority] instance has_finite_products_of_has_products [has_products C] : has_finite_products C := { has_limits_of_shape := λ J _, by apply_instance } @[priority 100] -- see Note [lower instance priority] instance has_finite_coproducts_of_has_coproducts [has_coproducts C] : has_finite_coproducts C := { has_colimits_of_shape := λ J _, by apply_instance } @[priority 100] -- see Note [lower instance priority] instance has_finite_products_of_has_finite_limits [has_finite_limits C] : has_finite_products C := { has_limits_of_shape := λ J _ _, by { resetI, apply_instance } } @[priority 100] -- see Note [lower instance priority] instance has_finite_coproducts_of_has_finite_colimits [has_finite_colimits C] : has_finite_coproducts C := { has_colimits_of_shape := λ J _ _, by { resetI, apply_instance } } end category_theory.limits
9c91efa5d4724a5a24df26c15bb7eb20d3b73fc9
32da3d0f92cab08875472ef6cacc1931c2b3eafa
/src/data/real/ennreal.lean
a1262b7d9f1d50d744a1cbadf49500d0da17cc1f
[ "Apache-2.0" ]
permissive
karthiknadig/mathlib
b6073c3748860bfc9a3e55da86afcddba62dc913
33a86cfff12d7f200d0010cd03b95e9b69a6c1a5
refs/heads/master
1,676,389,371,851
1,610,061,127,000
1,610,061,127,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
55,722
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Johannes Hölzl, Yury Kudryashov -/ import data.real.nnreal import data.set.intervals /-! # Extended non-negative reals We define `ennreal := with_no ℝ≥0` to be the type of extended nonnegative real numbers, i.e., the interval `[0, +∞]`. This type is used as the codomain of a `measure_theory.measure`, and of the extended distance `edist` in a `emetric_space`. In this file we define some algebraic operations and a linear order on `ennreal` and prove basic properties of these operations, order, and conversions to/from `ℝ`, `ℝ≥0`, and `ℕ`. ## Main definitions * `ennreal`: the extended nonnegative real numbers `[0, ∞]`; defined as `with_top ℝ≥0`; it is equipped with the following structures: - coercion from `ℝ≥0` defined in the natural way; - the natural structure of a complete dense linear order: `↑p ≤ ↑q ↔ p ≤ q` and `∀ a, a ≤ ∞`; - `a + b` is defined so that `↑p + ↑q = ↑(p + q)` for `(p q : ℝ≥0)` and `a + ∞ = ∞ + a = ∞`; - `a * b` is defined so that `↑p * ↑q = ↑(p * q)` for `(p q : ℝ≥0)`, `0 * ∞ = ∞ * 0 = 0`, and `a * ∞ = ∞ * a = ∞` for `a ≠ 0`; - `a - b` is defined as the minimal `d` such that `a ≤ d + b`; this way we have `↑p - ↑q = ↑(p - q)`, `∞ - ↑p = ∞`, `↑p - ∞ = ∞ - ∞ = 0`; note that there is no negation, only subtraction; - `a⁻¹` is defined as `Inf {b | 1 ≤ a * b}`. This way we have `(↑p)⁻¹ = ↑(p⁻¹)` for `p : ℝ≥0`, `p ≠ 0`, `0⁻¹ = ∞`, and `∞⁻¹ = 0`. - `a / b` is defined as `a * b⁻¹`. The addition and multiplication defined this way together with `0 = ↑0` and `1 = ↑1` turn `ennreal` into a canonically ordered commutative semiring of characteristic zero. * Coercions to/from other types: - coercion `ℝ≥0 → ennreal` is defined as `has_coe`, so one can use `(p : ℝ≥0)` in a context that expects `a : ennreal`, and Lean will apply `coe` automatically; - `ennreal.to_nnreal` sends `↑p` to `p` and `∞` to `0`; - `ennreal.to_real := coe ∘ ennreal.to_nnreal` sends `↑p`, `p : ℝ≥0` to `(↑p : ℝ)` and `∞` to `0`; - `ennreal.of_real := coe ∘ nnreal.of_real` sends `x : ℝ` to `↑⟨max x 0, _⟩` - `ennreal.ne_top_equiv_nnreal` is an equivalence between `{a : ennreal // a ≠ 0}` and `ℝ≥0`. ## Implementation notes We define a `can_lift ennreal ℝ≥0` instance, so one of the ways to prove theorems about an `ennreal` number `a` is to consider the cases `a = ∞` and `a ≠ ∞`, and use the tactic `lift a to ℝ≥0 using ha` in the second case. This instance is even more useful if one already has `ha : a ≠ ∞` in the context, or if we have `(f : α → ennreal) (hf : ∀ x, f x ≠ ∞)`. ## Notations * `ℝ≥0`: type of nonnegative real numbers `[0, ∞)`; defined in `data.real.nnreal`; * `∞`: a localized notation in `ennreal` for `⊤ : ennreal`. -/ noncomputable theory open classical set open_locale classical big_operators nnreal variables {α : Type*} {β : Type*} /-- The extended nonnegative real numbers. This is usually denoted [0, ∞], and is relevant as the codomain of a measure. -/ @[derive canonically_ordered_comm_semiring, derive complete_linear_order, derive densely_ordered, derive nontrivial] def ennreal := with_top ℝ≥0 localized "notation `∞` := (⊤ : ennreal)" in ennreal namespace ennreal variables {a b c d : ennreal} {r p q : ℝ≥0} instance : inhabited ennreal := ⟨0⟩ instance : has_coe ℝ≥0 ennreal := ⟨ option.some ⟩ instance : can_lift ennreal ℝ≥0 := { coe := coe, cond := λ r, r ≠ ∞, prf := λ x hx, ⟨option.get $ option.ne_none_iff_is_some.1 hx, option.some_get _⟩ } @[simp] lemma none_eq_top : (none : ennreal) = ∞ := rfl @[simp] lemma some_eq_coe (a : ℝ≥0) : (some a : ennreal) = (↑a : ennreal) := rfl /-- `to_nnreal x` returns `x` if it is real, otherwise 0. -/ protected def to_nnreal : ennreal → ℝ≥0 | (some r) := r | none := 0 /-- `to_real x` returns `x` if it is real, `0` otherwise. -/ protected def to_real (a : ennreal) : real := coe (a.to_nnreal) /-- `of_real x` returns `x` if it is nonnegative, `0` otherwise. -/ protected def of_real (r : real) : ennreal := coe (nnreal.of_real r) @[simp, norm_cast] lemma to_nnreal_coe : (r : ennreal).to_nnreal = r := rfl @[simp] lemma coe_to_nnreal : ∀{a:ennreal}, a ≠ ∞ → ↑(a.to_nnreal) = a | (some r) h := rfl | none h := (h rfl).elim @[simp] lemma of_real_to_real {a : ennreal} (h : a ≠ ∞) : ennreal.of_real (a.to_real) = a := by simp [ennreal.to_real, ennreal.of_real, h] @[simp] lemma to_real_of_real {r : ℝ} (h : 0 ≤ r) : ennreal.to_real (ennreal.of_real r) = r := by simp [ennreal.to_real, ennreal.of_real, nnreal.coe_of_real _ h] lemma to_real_of_real' {r : ℝ} : ennreal.to_real (ennreal.of_real r) = max r 0 := rfl lemma coe_to_nnreal_le_self : ∀{a:ennreal}, ↑(a.to_nnreal) ≤ a | (some r) := by rw [some_eq_coe, to_nnreal_coe]; exact le_refl _ | none := le_top lemma coe_nnreal_eq (r : ℝ≥0) : (r : ennreal) = ennreal.of_real r := by { rw [ennreal.of_real, nnreal.of_real], cases r with r h, congr, dsimp, rw max_eq_left h } lemma of_real_eq_coe_nnreal {x : ℝ} (h : 0 ≤ x) : ennreal.of_real x = @coe ℝ≥0 ennreal _ (⟨x, h⟩ : ℝ≥0) := by { rw [coe_nnreal_eq], refl } @[simp] lemma of_real_coe_nnreal : ennreal.of_real p = p := (coe_nnreal_eq p).symm @[simp, norm_cast] lemma coe_zero : ↑(0 : ℝ≥0) = (0 : ennreal) := rfl @[simp, norm_cast] lemma coe_one : ↑(1 : ℝ≥0) = (1 : ennreal) := rfl @[simp] lemma to_real_nonneg {a : ennreal} : 0 ≤ a.to_real := by simp [ennreal.to_real] @[simp] lemma top_to_nnreal : ∞.to_nnreal = 0 := rfl @[simp] lemma top_to_real : ∞.to_real = 0 := rfl @[simp] lemma one_to_real : (1 : ennreal).to_real = 1 := rfl @[simp] lemma one_to_nnreal : (1 : ennreal).to_nnreal = 1 := rfl @[simp] lemma coe_to_real (r : ℝ≥0) : (r : ennreal).to_real = r := rfl @[simp] lemma zero_to_nnreal : (0 : ennreal).to_nnreal = 0 := rfl @[simp] lemma zero_to_real : (0 : ennreal).to_real = 0 := rfl @[simp] lemma of_real_zero : ennreal.of_real (0 : ℝ) = 0 := by simp [ennreal.of_real]; refl @[simp] lemma of_real_one : ennreal.of_real (1 : ℝ) = (1 : ennreal) := by simp [ennreal.of_real] lemma of_real_to_real_le {a : ennreal} : ennreal.of_real (a.to_real) ≤ a := if ha : a = ∞ then ha.symm ▸ le_top else le_of_eq (of_real_to_real ha) lemma forall_ennreal {p : ennreal → Prop} : (∀a, p a) ↔ (∀r:ℝ≥0, p r) ∧ p ∞ := ⟨assume h, ⟨assume r, h _, h _⟩, assume ⟨h₁, h₂⟩ a, match a with some r := h₁ _ | none := h₂ end⟩ lemma forall_ne_top {p : ennreal → Prop} : (∀ a ≠ ∞, p a) ↔ ∀ r : ℝ≥0, p r := option.ball_ne_none lemma exists_ne_top {p : ennreal → Prop} : (∃ a ≠ ∞, p a) ↔ ∃ r : ℝ≥0, p r := option.bex_ne_none lemma to_nnreal_eq_zero_iff (x : ennreal) : x.to_nnreal = 0 ↔ x = 0 ∨ x = ∞ := ⟨begin cases x, { simp [none_eq_top] }, { have A : some (0:ℝ≥0) = (0:ennreal) := rfl, simp [ennreal.to_nnreal, A] {contextual := tt} } end, by intro h; cases h; simp [h]⟩ lemma to_real_eq_zero_iff (x : ennreal) : x.to_real = 0 ↔ x = 0 ∨ x = ∞ := by simp [ennreal.to_real, to_nnreal_eq_zero_iff] @[simp] lemma coe_ne_top : (r : ennreal) ≠ ∞ := with_top.coe_ne_top @[simp] lemma top_ne_coe : ∞ ≠ (r : ennreal) := with_top.top_ne_coe @[simp] lemma of_real_ne_top {r : ℝ} : ennreal.of_real r ≠ ∞ := by simp [ennreal.of_real] @[simp] lemma of_real_lt_top {r : ℝ} : ennreal.of_real r < ∞ := lt_top_iff_ne_top.2 of_real_ne_top @[simp] lemma top_ne_of_real {r : ℝ} : ∞ ≠ ennreal.of_real r := by simp [ennreal.of_real] @[simp] lemma zero_ne_top : 0 ≠ ∞ := coe_ne_top @[simp] lemma top_ne_zero : ∞ ≠ 0 := top_ne_coe @[simp] lemma one_ne_top : 1 ≠ ∞ := coe_ne_top @[simp] lemma top_ne_one : ∞ ≠ 1 := top_ne_coe @[simp, norm_cast] lemma coe_eq_coe : (↑r : ennreal) = ↑q ↔ r = q := with_top.coe_eq_coe @[simp, norm_cast] lemma coe_le_coe : (↑r : ennreal) ≤ ↑q ↔ r ≤ q := with_top.coe_le_coe @[simp, norm_cast] lemma coe_lt_coe : (↑r : ennreal) < ↑q ↔ r < q := with_top.coe_lt_coe lemma coe_mono : monotone (coe : ℝ≥0 → ennreal) := λ _ _, coe_le_coe.2 @[simp, norm_cast] lemma coe_eq_zero : (↑r : ennreal) = 0 ↔ r = 0 := coe_eq_coe @[simp, norm_cast] lemma zero_eq_coe : 0 = (↑r : ennreal) ↔ 0 = r := coe_eq_coe @[simp, norm_cast] lemma coe_eq_one : (↑r : ennreal) = 1 ↔ r = 1 := coe_eq_coe @[simp, norm_cast] lemma one_eq_coe : 1 = (↑r : ennreal) ↔ 1 = r := coe_eq_coe @[simp, norm_cast] lemma coe_nonneg : 0 ≤ (↑r : ennreal) ↔ 0 ≤ r := coe_le_coe @[simp, norm_cast] lemma coe_pos : 0 < (↑r : ennreal) ↔ 0 < r := coe_lt_coe @[simp, norm_cast] lemma coe_add : ↑(r + p) = (r + p : ennreal) := with_top.coe_add @[simp, norm_cast] lemma coe_mul : ↑(r * p) = (r * p : ennreal) := with_top.coe_mul @[simp, norm_cast] lemma coe_bit0 : (↑(bit0 r) : ennreal) = bit0 r := coe_add @[simp, norm_cast] lemma coe_bit1 : (↑(bit1 r) : ennreal) = bit1 r := by simp [bit1] lemma coe_two : ((2:ℝ≥0) : ennreal) = 2 := by norm_cast protected lemma zero_lt_one : 0 < (1 : ennreal) := canonically_ordered_semiring.zero_lt_one @[simp] lemma one_lt_two : (1 : ennreal) < 2 := coe_one ▸ coe_two ▸ by exact_mod_cast (@one_lt_two ℕ _ _) @[simp] lemma zero_lt_two : (0:ennreal) < 2 := lt_trans ennreal.zero_lt_one one_lt_two lemma two_ne_zero : (2:ennreal) ≠ 0 := (ne_of_lt zero_lt_two).symm lemma two_ne_top : (2:ennreal) ≠ ∞ := coe_two ▸ coe_ne_top /-- The set of `ennreal` numbers that are not equal to `∞` is equivalent to `ℝ≥0`. -/ def ne_top_equiv_nnreal : {a | a ≠ ∞} ≃ ℝ≥0 := { to_fun := λ x, ennreal.to_nnreal x, inv_fun := λ x, ⟨x, coe_ne_top⟩, left_inv := λ ⟨x, hx⟩, subtype.eq $ coe_to_nnreal hx, right_inv := λ x, to_nnreal_coe } lemma cinfi_ne_top [has_Inf α] (f : ennreal → α) : (⨅ x : {x // x ≠ ∞}, f x) = ⨅ x : ℝ≥0, f x := eq.symm $ infi_congr _ ne_top_equiv_nnreal.symm.surjective $ λ x, rfl lemma infi_ne_top [complete_lattice α] (f : ennreal → α) : (⨅ x ≠ ∞, f x) = ⨅ x : ℝ≥0, f x := by rw [infi_subtype', cinfi_ne_top] lemma csupr_ne_top [has_Sup α] (f : ennreal → α) : (⨆ x : {x // x ≠ ∞}, f x) = ⨆ x : ℝ≥0, f x := @cinfi_ne_top (order_dual α) _ _ lemma supr_ne_top [complete_lattice α] (f : ennreal → α) : (⨆ x ≠ ∞, f x) = ⨆ x : ℝ≥0, f x := @infi_ne_top (order_dual α) _ _ lemma infi_ennreal {α : Type*} [complete_lattice α] {f : ennreal → α} : (⨅ n, f n) = (⨅ n : ℝ≥0, f n) ⊓ f ∞ := le_antisymm (le_inf (le_infi $ assume i, infi_le _ _) (infi_le _ _)) (le_infi $ forall_ennreal.2 ⟨assume r, inf_le_left_of_le $ infi_le _ _, inf_le_right⟩) lemma supr_ennreal {α : Type*} [complete_lattice α] {f : ennreal → α} : (⨆ n, f n) = (⨆ n : ℝ≥0, f n) ⊔ f ∞ := @infi_ennreal (order_dual α) _ _ @[simp] lemma add_top : a + ∞ = ∞ := with_top.add_top @[simp] lemma top_add : ∞ + a = ∞ := with_top.top_add /-- Coercion `ℝ≥0 → ennreal` as a `ring_hom`. -/ def of_nnreal_hom : ℝ≥0 →+* ennreal := ⟨coe, coe_one, λ _ _, coe_mul, coe_zero, λ _ _, coe_add⟩ @[simp] lemma coe_of_nnreal_hom : ⇑of_nnreal_hom = coe := rfl @[simp, norm_cast] lemma coe_indicator {α} (s : set α) (f : α → ℝ≥0) (a : α) : ((s.indicator f a : ℝ≥0) : ennreal) = s.indicator (λ x, f x) a := (of_nnreal_hom : ℝ≥0 →+ ennreal).map_indicator _ _ _ @[simp, norm_cast] lemma coe_pow (n : ℕ) : (↑(r^n) : ennreal) = r^n := of_nnreal_hom.map_pow r n @[simp] lemma add_eq_top : a + b = ∞ ↔ a = ∞ ∨ b = ∞ := with_top.add_eq_top @[simp] lemma add_lt_top : a + b < ∞ ↔ a < ∞ ∧ b < ∞ := with_top.add_lt_top lemma to_nnreal_add {r₁ r₂ : ennreal} (h₁ : r₁ < ∞) (h₂ : r₂ < ∞) : (r₁ + r₂).to_nnreal = r₁.to_nnreal + r₂.to_nnreal := begin rw [← coe_eq_coe, coe_add, coe_to_nnreal, coe_to_nnreal, coe_to_nnreal]; apply @ne_top_of_lt ennreal _ _ ∞, exact h₂, exact h₁, exact add_lt_top.2 ⟨h₁, h₂⟩ end /- rw has trouble with the generic lt_top_iff_ne_top and bot_lt_iff_ne_bot (contrary to erw). This is solved with the next lemmas -/ protected lemma lt_top_iff_ne_top : a < ∞ ↔ a ≠ ∞ := lt_top_iff_ne_top protected lemma bot_lt_iff_ne_bot : 0 < a ↔ a ≠ 0 := bot_lt_iff_ne_bot lemma not_lt_top {x : ennreal} : ¬ x < ∞ ↔ x = ∞ := by rw [lt_top_iff_ne_top, not_not] lemma add_ne_top : a + b ≠ ∞ ↔ a ≠ ∞ ∧ b ≠ ∞ := by simpa only [lt_top_iff_ne_top] using add_lt_top lemma mul_top : a * ∞ = (if a = 0 then 0 else ∞) := begin split_ifs, { simp [h] }, { exact with_top.mul_top h } end lemma top_mul : ∞ * a = (if a = 0 then 0 else ∞) := begin split_ifs, { simp [h] }, { exact with_top.top_mul h } end @[simp] lemma top_mul_top : ∞ * ∞ = ∞ := with_top.top_mul_top lemma top_pow {n:ℕ} (h : 0 < n) : ∞^n = ∞ := nat.le_induction (pow_one _) (λ m hm hm', by rw [pow_succ, hm', top_mul_top]) _ (nat.succ_le_of_lt h) lemma mul_eq_top : a * b = ∞ ↔ (a ≠ 0 ∧ b = ∞) ∨ (a = ∞ ∧ b ≠ 0) := with_top.mul_eq_top_iff lemma mul_lt_top : a < ∞ → b < ∞ → a * b < ∞ := with_top.mul_lt_top lemma mul_ne_top : a ≠ ∞ → b ≠ ∞ → a * b ≠ ∞ := by simpa only [lt_top_iff_ne_top] using mul_lt_top lemma ne_top_of_mul_ne_top_left (h : a * b ≠ ∞) (hb : b ≠ 0) : a ≠ ∞ := by { simp [mul_eq_top, hb, not_or_distrib] at h ⊢, exact h.2 } lemma ne_top_of_mul_ne_top_right (h : a * b ≠ ∞) (ha : a ≠ 0) : b ≠ ∞ := ne_top_of_mul_ne_top_left (by rwa [mul_comm]) ha lemma lt_top_of_mul_lt_top_left (h : a * b < ∞) (hb : b ≠ 0) : a < ∞ := by { rw [ennreal.lt_top_iff_ne_top] at h ⊢, exact ne_top_of_mul_ne_top_left h hb } lemma lt_top_of_mul_lt_top_right (h : a * b < ∞) (ha : a ≠ 0) : b < ∞ := lt_top_of_mul_lt_top_left (by rwa [mul_comm]) ha lemma mul_lt_top_iff {a b : ennreal} : a * b < ∞ ↔ (a < ∞ ∧ b < ∞) ∨ a = 0 ∨ b = 0 := begin split, { intro h, rw [← or_assoc, or_iff_not_imp_right, or_iff_not_imp_right], intros hb ha, exact ⟨lt_top_of_mul_lt_top_left h hb, lt_top_of_mul_lt_top_right h ha⟩ }, { rintro (⟨ha, hb⟩|rfl|rfl); [exact mul_lt_top ha hb, simp, simp] } end @[simp] lemma mul_pos : 0 < a * b ↔ 0 < a ∧ 0 < b := by simp only [zero_lt_iff_ne_zero, ne.def, mul_eq_zero, not_or_distrib] lemma pow_eq_top : ∀ n:ℕ, a^n=∞ → a=∞ | 0 := by simp | (n+1) := λ o, (mul_eq_top.1 o).elim (λ h, pow_eq_top n h.2) and.left lemma pow_ne_top (h : a ≠ ∞) {n:ℕ} : a^n ≠ ∞ := mt (pow_eq_top n) h lemma pow_lt_top : a < ∞ → ∀ n:ℕ, a^n < ∞ := by simpa only [lt_top_iff_ne_top] using pow_ne_top @[simp, norm_cast] lemma coe_finset_sum {s : finset α} {f : α → ℝ≥0} : ↑(∑ a in s, f a) = (∑ a in s, f a : ennreal) := of_nnreal_hom.map_sum f s @[simp, norm_cast] lemma coe_finset_prod {s : finset α} {f : α → ℝ≥0} : ↑(∏ a in s, f a) = ((∏ a in s, f a) : ennreal) := of_nnreal_hom.map_prod f s section order @[simp] lemma bot_eq_zero : (⊥ : ennreal) = 0 := rfl @[simp] lemma coe_lt_top : coe r < ∞ := with_top.coe_lt_top r @[simp] lemma not_top_le_coe : ¬ ∞ ≤ ↑r := with_top.not_top_le_coe r lemma zero_lt_coe_iff : 0 < (↑p : ennreal) ↔ 0 < p := coe_lt_coe @[simp, norm_cast] lemma one_le_coe_iff : (1:ennreal) ≤ ↑r ↔ 1 ≤ r := coe_le_coe @[simp, norm_cast] lemma coe_le_one_iff : ↑r ≤ (1:ennreal) ↔ r ≤ 1 := coe_le_coe @[simp, norm_cast] lemma coe_lt_one_iff : (↑p : ennreal) < 1 ↔ p < 1 := coe_lt_coe @[simp, norm_cast] lemma one_lt_coe_iff : 1 < (↑p : ennreal) ↔ 1 < p := coe_lt_coe @[simp, norm_cast] lemma coe_nat (n : nat) : ((n : ℝ≥0) : ennreal) = n := with_top.coe_nat n @[simp] lemma nat_ne_top (n : nat) : (n : ennreal) ≠ ∞ := with_top.nat_ne_top n @[simp] lemma top_ne_nat (n : nat) : ∞ ≠ n := with_top.top_ne_nat n @[simp] lemma one_lt_top : 1 < ∞ := coe_lt_top lemma le_coe_iff : a ≤ ↑r ↔ (∃p:ℝ≥0, a = p ∧ p ≤ r) := with_top.le_coe_iff lemma coe_le_iff : ↑r ≤ a ↔ (∀p:ℝ≥0, a = p → r ≤ p) := with_top.coe_le_iff lemma lt_iff_exists_coe : a < b ↔ (∃p:ℝ≥0, a = p ∧ ↑p < b) := with_top.lt_iff_exists_coe @[simp, norm_cast] lemma coe_finset_sup {s : finset α} {f : α → ℝ≥0} : ↑(s.sup f) = s.sup (λ x, (f x : ennreal)) := finset.comp_sup_eq_sup_comp_of_is_total _ coe_mono rfl lemma pow_le_pow {n m : ℕ} (ha : 1 ≤ a) (h : n ≤ m) : a ^ n ≤ a ^ m := begin cases a, { cases m, { rw eq_bot_iff.mpr h, exact le_refl _ }, { rw [none_eq_top, top_pow (nat.succ_pos m)], exact le_top } }, { rw [some_eq_coe, ← coe_pow, ← coe_pow, coe_le_coe], exact pow_le_pow (by simpa using ha) h } end @[simp] lemma max_eq_zero_iff : max a b = 0 ↔ a = 0 ∧ b = 0 := by simp only [le_zero_iff_eq.symm, max_le_iff] @[simp] lemma max_zero_left : max 0 a = a := max_eq_right (zero_le a) @[simp] lemma max_zero_right : max a 0 = a := max_eq_left (zero_le a) -- TODO: why this is not a `rfl`? There is some hidden diamond here. @[simp] lemma sup_eq_max : a ⊔ b = max a b := eq_of_forall_ge_iff $ λ c, sup_le_iff.trans max_le_iff.symm protected lemma pow_pos : 0 < a → ∀ n : ℕ, 0 < a^n := canonically_ordered_semiring.pow_pos protected lemma pow_ne_zero : a ≠ 0 → ∀ n : ℕ, a^n ≠ 0 := by simpa only [zero_lt_iff_ne_zero] using ennreal.pow_pos @[simp] lemma not_lt_zero : ¬ a < 0 := by simp lemma add_lt_add_iff_left : a < ∞ → (a + c < a + b ↔ c < b) := with_top.add_lt_add_iff_left lemma add_lt_add_iff_right : a < ∞ → (c + a < b + a ↔ c < b) := with_top.add_lt_add_iff_right lemma lt_add_right (ha : a < ∞) (hb : 0 < b) : a < a + b := by rwa [← add_lt_add_iff_left ha, add_zero] at hb lemma le_of_forall_epsilon_le : ∀{a b : ennreal}, (∀ε:ℝ≥0, 0 < ε → b < ∞ → a ≤ b + ε) → a ≤ b | a none h := le_top | none (some a) h := have ∞ ≤ ↑a + ↑(1:ℝ≥0), from h 1 zero_lt_one coe_lt_top, by rw [← coe_add] at this; exact (not_top_le_coe this).elim | (some a) (some b) h := by simp only [none_eq_top, some_eq_coe, coe_add.symm, coe_le_coe, coe_lt_top, true_implies_iff] at *; exact nnreal.le_of_forall_epsilon_le h lemma lt_iff_exists_rat_btwn : a < b ↔ (∃q:ℚ, 0 ≤ q ∧ a < nnreal.of_real q ∧ (nnreal.of_real q:ennreal) < b) := ⟨λ h, begin rcases lt_iff_exists_coe.1 h with ⟨p, rfl, _⟩, rcases exists_between h with ⟨c, pc, cb⟩, rcases lt_iff_exists_coe.1 cb with ⟨r, rfl, _⟩, rcases (nnreal.lt_iff_exists_rat_btwn _ _).1 (coe_lt_coe.1 pc) with ⟨q, hq0, pq, qr⟩, exact ⟨q, hq0, coe_lt_coe.2 pq, lt_trans (coe_lt_coe.2 qr) cb⟩ end, λ ⟨q, q0, qa, qb⟩, lt_trans qa qb⟩ lemma lt_iff_exists_real_btwn : a < b ↔ (∃r:ℝ, 0 ≤ r ∧ a < ennreal.of_real r ∧ (ennreal.of_real r:ennreal) < b) := ⟨λ h, let ⟨q, q0, aq, qb⟩ := ennreal.lt_iff_exists_rat_btwn.1 h in ⟨q, rat.cast_nonneg.2 q0, aq, qb⟩, λ ⟨q, q0, qa, qb⟩, lt_trans qa qb⟩ lemma lt_iff_exists_nnreal_btwn : a < b ↔ (∃r:ℝ≥0, a < r ∧ (r : ennreal) < b) := with_top.lt_iff_exists_coe_btwn lemma lt_iff_exists_add_pos_lt : a < b ↔ (∃ r : ℝ≥0, 0 < r ∧ a + r < b) := begin refine ⟨λ hab, _, λ ⟨r, rpos, hr⟩, lt_of_le_of_lt (le_add_right (le_refl _)) hr⟩, cases a, { simpa using hab }, rcases lt_iff_exists_real_btwn.1 hab with ⟨c, c_nonneg, ac, cb⟩, let d : ℝ≥0 := ⟨c, c_nonneg⟩, have ad : a < d, { rw of_real_eq_coe_nnreal c_nonneg at ac, exact coe_lt_coe.1 ac }, refine ⟨d-a, nnreal.sub_pos.2 ad, _⟩, rw [some_eq_coe, ← coe_add], convert cb, have : nnreal.of_real c = d, by { rw [← nnreal.coe_eq, nnreal.coe_of_real _ c_nonneg], refl }, rw [add_comm, this], exact nnreal.sub_add_cancel_of_le (le_of_lt ad) end lemma coe_nat_lt_coe {n : ℕ} : (n : ennreal) < r ↔ ↑n < r := ennreal.coe_nat n ▸ coe_lt_coe lemma coe_lt_coe_nat {n : ℕ} : (r : ennreal) < n ↔ r < n := ennreal.coe_nat n ▸ coe_lt_coe @[norm_cast] lemma coe_nat_lt_coe_nat {m n : ℕ} : (m : ennreal) < n ↔ m < n := ennreal.coe_nat n ▸ coe_nat_lt_coe.trans nat.cast_lt lemma coe_nat_ne_top {n : ℕ} : (n : ennreal) ≠ ∞ := ennreal.coe_nat n ▸ coe_ne_top lemma coe_nat_mono : strict_mono (coe : ℕ → ennreal) := λ _ _, coe_nat_lt_coe_nat.2 @[norm_cast] lemma coe_nat_le_coe_nat {m n : ℕ} : (m : ennreal) ≤ n ↔ m ≤ n := coe_nat_mono.le_iff_le instance : char_zero ennreal := ⟨coe_nat_mono.injective⟩ protected lemma exists_nat_gt {r : ennreal} (h : r ≠ ∞) : ∃n:ℕ, r < n := begin lift r to ℝ≥0 using h, rcases exists_nat_gt r with ⟨n, hn⟩, exact ⟨n, coe_lt_coe_nat.2 hn⟩, end lemma add_lt_add (ac : a < c) (bd : b < d) : a + b < c + d := begin lift a to ℝ≥0 using ne_top_of_lt ac, lift b to ℝ≥0 using ne_top_of_lt bd, cases c, { simp }, cases d, { simp }, simp only [← coe_add, some_eq_coe, coe_lt_coe] at *, exact add_lt_add ac bd end @[norm_cast] lemma coe_min : ((min r p:ℝ≥0):ennreal) = min r p := coe_mono.map_min @[norm_cast] lemma coe_max : ((max r p:ℝ≥0):ennreal) = max r p := coe_mono.map_max lemma le_of_top_imp_top_of_to_nnreal_le {a b : ennreal} (h : a = ⊤ → b = ⊤) (h_nnreal : a ≠ ⊤ → b ≠ ⊤ → a.to_nnreal ≤ b.to_nnreal) : a ≤ b := begin by_cases ha : a = ⊤, { rw h ha, exact le_top, }, by_cases hb : b = ⊤, { rw hb, exact le_top, }, rw [←coe_to_nnreal hb, ←coe_to_nnreal ha, coe_le_coe], exact h_nnreal ha hb, end end order section complete_lattice lemma coe_Sup {s : set ℝ≥0} : bdd_above s → (↑(Sup s) : ennreal) = (⨆a∈s, ↑a) := with_top.coe_Sup lemma coe_Inf {s : set ℝ≥0} : s.nonempty → (↑(Inf s) : ennreal) = (⨅a∈s, ↑a) := with_top.coe_Inf @[simp] lemma top_mem_upper_bounds {s : set ennreal} : ∞ ∈ upper_bounds s := assume x hx, le_top lemma coe_mem_upper_bounds {s : set ℝ≥0} : ↑r ∈ upper_bounds ((coe : ℝ≥0 → ennreal) '' s) ↔ r ∈ upper_bounds s := by simp [upper_bounds, ball_image_iff, -mem_image, *] {contextual := tt} end complete_lattice section mul lemma mul_le_mul : a ≤ b → c ≤ d → a * c ≤ b * d := canonically_ordered_semiring.mul_le_mul lemma mul_lt_mul (ac : a < c) (bd : b < d) : a * b < c * d := begin rcases lt_iff_exists_nnreal_btwn.1 ac with ⟨a', aa', a'c⟩, lift a to ℝ≥0 using ne_top_of_lt aa', rcases lt_iff_exists_nnreal_btwn.1 bd with ⟨b', bb', b'd⟩, lift b to ℝ≥0 using ne_top_of_lt bb', norm_cast at *, calc ↑(a * b) < ↑(a' * b') : coe_lt_coe.2 (mul_lt_mul' aa'.le bb' (zero_le _) ((zero_le a).trans_lt aa')) ... = ↑a' * ↑b' : coe_mul ... ≤ c * d : mul_le_mul a'c.le b'd.le end lemma mul_left_mono : monotone ((*) a) := λ b c, mul_le_mul (le_refl a) lemma mul_right_mono : monotone (λ x, x * a) := λ b c h, mul_le_mul h (le_refl a) lemma max_mul : max a b * c = max (a * c) (b * c) := mul_right_mono.map_max lemma mul_max : a * max b c = max (a * b) (a * c) := mul_left_mono.map_max lemma mul_eq_mul_left : a ≠ 0 → a ≠ ∞ → (a * b = a * c ↔ b = c) := begin cases a; cases b; cases c; simp [none_eq_top, some_eq_coe, mul_top, top_mul, -coe_mul, coe_mul.symm, nnreal.mul_eq_mul_left] {contextual := tt}, end lemma mul_eq_mul_right : c ≠ 0 → c ≠ ∞ → (a * c = b * c ↔ a = b) := mul_comm c a ▸ mul_comm c b ▸ mul_eq_mul_left lemma mul_le_mul_left : a ≠ 0 → a ≠ ∞ → (a * b ≤ a * c ↔ b ≤ c) := begin cases a; cases b; cases c; simp [none_eq_top, some_eq_coe, mul_top, top_mul, -coe_mul, coe_mul.symm] {contextual := tt}, assume h, exact mul_le_mul_left (zero_lt_iff_ne_zero.2 h) end lemma mul_le_mul_right : c ≠ 0 → c ≠ ∞ → (a * c ≤ b * c ↔ a ≤ b) := mul_comm c a ▸ mul_comm c b ▸ mul_le_mul_left lemma mul_lt_mul_left : a ≠ 0 → a ≠ ∞ → (a * b < a * c ↔ b < c) := λ h0 ht, by simp only [mul_le_mul_left h0 ht, lt_iff_le_not_le] lemma mul_lt_mul_right : c ≠ 0 → c ≠ ∞ → (a * c < b * c ↔ a < b) := mul_comm c a ▸ mul_comm c b ▸ mul_lt_mul_left end mul section sub instance : has_sub ennreal := ⟨λa b, Inf {d | a ≤ d + b}⟩ @[norm_cast] lemma coe_sub : ↑(p - r) = (↑p:ennreal) - r := le_antisymm (le_Inf $ assume b (hb : ↑p ≤ b + r), coe_le_iff.2 $ by rintros d rfl; rwa [← coe_add, coe_le_coe, ← nnreal.sub_le_iff_le_add] at hb) (Inf_le $ show (↑p : ennreal) ≤ ↑(p - r) + ↑r, by rw [← coe_add, coe_le_coe, ← nnreal.sub_le_iff_le_add]) @[simp] lemma top_sub_coe : ∞ - ↑r = ∞ := top_unique $ le_Inf $ by simp [add_eq_top] @[simp] lemma sub_eq_zero_of_le (h : a ≤ b) : a - b = 0 := le_antisymm (Inf_le $ le_add_left h) (zero_le _) @[simp] lemma sub_self : a - a = 0 := sub_eq_zero_of_le $ le_refl _ @[simp] lemma zero_sub : 0 - a = 0 := le_antisymm (Inf_le $ zero_le $ 0 + a) (zero_le _) @[simp] lemma sub_infty : a - ∞ = 0 := le_antisymm (Inf_le $ by simp) (zero_le _) lemma sub_le_sub (h₁ : a ≤ b) (h₂ : d ≤ c) : a - c ≤ b - d := Inf_le_Inf $ assume e (h : b ≤ e + d), calc a ≤ b : h₁ ... ≤ e + d : h ... ≤ e + c : add_le_add (le_refl _) h₂ @[simp] lemma add_sub_self : ∀{a b : ennreal}, b < ∞ → (a + b) - b = a | a none := by simp [none_eq_top] | none (some b) := by simp [none_eq_top, some_eq_coe] | (some a) (some b) := by simp [some_eq_coe]; rw [← coe_add, ← coe_sub, coe_eq_coe, nnreal.add_sub_cancel] @[simp] lemma add_sub_self' (h : a < ∞) : (a + b) - a = b := by rw [add_comm, add_sub_self h] lemma add_right_inj (h : a < ∞) : a + b = a + c ↔ b = c := ⟨λ e, by simpa [h] using congr_arg (λ x, x - a) e, congr_arg _⟩ lemma add_left_inj (h : a < ∞) : b + a = c + a ↔ b = c := by rw [add_comm, add_comm c, add_right_inj h] @[simp] lemma sub_add_cancel_of_le : ∀{a b : ennreal}, b ≤ a → (a - b) + b = a := begin simp [forall_ennreal, le_coe_iff, -add_comm] {contextual := tt}, rintros r p x rfl h, rw [← coe_sub, ← coe_add, nnreal.sub_add_cancel_of_le h] end @[simp] lemma add_sub_cancel_of_le (h : b ≤ a) : b + (a - b) = a := by rwa [add_comm, sub_add_cancel_of_le] lemma sub_add_self_eq_max : (a - b) + b = max a b := match le_total a b with | or.inl h := by simp [h, max_eq_right] | or.inr h := by simp [h, max_eq_left] end lemma le_sub_add_self : a ≤ (a - b) + b := by { rw sub_add_self_eq_max, exact le_max_left a b } @[simp] protected lemma sub_le_iff_le_add : a - b ≤ c ↔ a ≤ c + b := iff.intro (assume h : a - b ≤ c, calc a ≤ (a - b) + b : le_sub_add_self ... ≤ c + b : add_le_add_right h _) (assume h : a ≤ c + b, calc a - b ≤ (c + b) - b : sub_le_sub h (le_refl _) ... ≤ c : Inf_le (le_refl (c + b))) protected lemma sub_le_iff_le_add' : a - b ≤ c ↔ a ≤ b + c := add_comm c b ▸ ennreal.sub_le_iff_le_add lemma sub_eq_of_add_eq : b ≠ ∞ → a + b = c → c - b = a := λ hb hc, hc ▸ add_sub_self (lt_top_iff_ne_top.2 hb) protected lemma sub_le_of_sub_le (h : a - b ≤ c) : a - c ≤ b := ennreal.sub_le_iff_le_add.2 $ by { rw add_comm, exact ennreal.sub_le_iff_le_add.1 h } protected lemma sub_lt_sub_self : a ≠ ∞ → a ≠ 0 → 0 < b → a - b < a := match a, b with | none, _ := by { have := none_eq_top, assume h, contradiction } | (some a), none := by {intros, simp only [none_eq_top, sub_infty, zero_lt_iff_ne_zero], assumption} | (some a), (some b) := begin simp only [some_eq_coe, coe_sub.symm, coe_pos, coe_eq_zero, coe_lt_coe, ne.def], assume h₁ h₂, apply nnreal.sub_lt_self, exact zero_lt_iff_ne_zero.2 h₂ end end @[simp] lemma sub_eq_zero_iff_le : a - b = 0 ↔ a ≤ b := by simpa [-ennreal.sub_le_iff_le_add] using @ennreal.sub_le_iff_le_add a b 0 @[simp] lemma zero_lt_sub_iff_lt : 0 < a - b ↔ b < a := by simpa [ennreal.bot_lt_iff_ne_bot, -sub_eq_zero_iff_le] using not_iff_not.2 (@sub_eq_zero_iff_le a b) lemma lt_sub_iff_add_lt : a < b - c ↔ a + c < b := begin cases a, { simp }, cases c, { simp }, cases b, { simp only [true_iff, coe_lt_top, some_eq_coe, top_sub_coe, none_eq_top, ← coe_add] }, simp only [some_eq_coe], rw [← coe_add, ← coe_sub, coe_lt_coe, coe_lt_coe, nnreal.lt_sub_iff_add_lt], end lemma sub_le_self (a b : ennreal) : a - b ≤ a := ennreal.sub_le_iff_le_add.2 $ le_add_right (le_refl a) @[simp] lemma sub_zero : a - 0 = a := eq.trans (add_zero (a - 0)).symm $ by simp /-- A version of triangle inequality for difference as a "distance". -/ lemma sub_le_sub_add_sub : a - c ≤ a - b + (b - c) := ennreal.sub_le_iff_le_add.2 $ calc a ≤ a - b + b : le_sub_add_self ... ≤ a - b + ((b - c) + c) : add_le_add_left le_sub_add_self _ ... = a - b + (b - c) + c : (add_assoc _ _ _).symm lemma sub_sub_cancel (h : a < ∞) (h2 : b ≤ a) : a - (a - b) = b := by rw [← add_left_inj (lt_of_le_of_lt (sub_le_self _ _) h), sub_add_cancel_of_le (sub_le_self _ _), add_sub_cancel_of_le h2] lemma sub_right_inj {a b c : ennreal} (ha : a < ∞) (hb : b ≤ a) (hc : c ≤ a) : a - b = a - c ↔ b = c := iff.intro begin assume h, have : a - (a - b) = a - (a - c), rw h, rw [sub_sub_cancel ha hb, sub_sub_cancel ha hc] at this, exact this end (λ h, by rw h) lemma sub_mul (h : 0 < b → b < a → c ≠ ∞) : (a - b) * c = a * c - b * c := begin cases le_or_lt a b with hab hab, { simp [hab, mul_right_mono hab] }, symmetry, cases eq_or_lt_of_le (zero_le b) with hb hb, { subst b, simp }, apply sub_eq_of_add_eq, { exact mul_ne_top (ne_top_of_lt hab) (h hb hab) }, rw [← add_mul, sub_add_cancel_of_le (le_of_lt hab)] end lemma mul_sub (h : 0 < c → c < b → a ≠ ∞) : a * (b - c) = a * b - a * c := by { simp only [mul_comm a], exact sub_mul h } lemma sub_mul_ge : a * c - b * c ≤ (a - b) * c := begin -- with `0 < b → b < a → c ≠ ∞` Lean names the first variable `a` by_cases h : ∀ (hb : 0 < b), b < a → c ≠ ∞, { rw [sub_mul h], exact le_refl _ }, { push_neg at h, rcases h with ⟨hb, hba, hc⟩, subst c, simp only [mul_top, if_neg (ne_of_gt hb), if_neg (ne_of_gt $ lt_trans hb hba), sub_self, zero_le] } end end sub section sum open finset /-- A product of finite numbers is still finite -/ lemma prod_lt_top {s : finset α} {f : α → ennreal} (h : ∀a∈s, f a < ∞) : (∏ a in s, f a) < ∞ := with_top.prod_lt_top h /-- A sum of finite numbers is still finite -/ lemma sum_lt_top {s : finset α} {f : α → ennreal} : (∀a∈s, f a < ∞) → ∑ a in s, f a < ∞ := with_top.sum_lt_top /-- A sum of finite numbers is still finite -/ lemma sum_lt_top_iff {s : finset α} {f : α → ennreal} : ∑ a in s, f a < ∞ ↔ (∀a∈s, f a < ∞) := with_top.sum_lt_top_iff /-- A sum of numbers is infinite iff one of them is infinite -/ lemma sum_eq_top_iff {s : finset α} {f : α → ennreal} : (∑ x in s, f x) = ∞ ↔ (∃a∈s, f a = ∞) := with_top.sum_eq_top_iff /-- seeing `ennreal` as `ℝ≥0` does not change their sum, unless one of the `ennreal` is infinity -/ lemma to_nnreal_sum {s : finset α} {f : α → ennreal} (hf : ∀a∈s, f a < ∞) : ennreal.to_nnreal (∑ a in s, f a) = ∑ a in s, ennreal.to_nnreal (f a) := begin rw [← coe_eq_coe, coe_to_nnreal, coe_finset_sum, sum_congr], { refl }, { intros x hx, exact (coe_to_nnreal (hf x hx).ne).symm }, { exact (sum_lt_top hf).ne } end /-- seeing `ennreal` as `real` does not change their sum, unless one of the `ennreal` is infinity -/ lemma to_real_sum {s : finset α} {f : α → ennreal} (hf : ∀a∈s, f a < ∞) : ennreal.to_real (∑ a in s, f a) = ∑ a in s, ennreal.to_real (f a) := by { rw [ennreal.to_real, to_nnreal_sum hf, nnreal.coe_sum], refl } end sum section interval variables {x y z : ennreal} {ε ε₁ ε₂ : ennreal} {s : set ennreal} protected lemma Ico_eq_Iio : (Ico 0 y) = (Iio y) := ext $ assume a, iff.intro (assume ⟨_, hx⟩, hx) (assume hx, ⟨zero_le _, hx⟩) lemma mem_Iio_self_add : x ≠ ∞ → 0 < ε → x ∈ Iio (x + ε) := assume xt ε0, lt_add_right (by rwa lt_top_iff_ne_top) ε0 lemma not_mem_Ioo_self_sub : x = 0 → x ∉ Ioo (x - ε) y := assume x0, by simp [x0] lemma mem_Ioo_self_sub_add : x ≠ ∞ → x ≠ 0 → 0 < ε₁ → 0 < ε₂ → x ∈ Ioo (x - ε₁) (x + ε₂) := assume xt x0 ε0 ε0', ⟨ennreal.sub_lt_sub_self xt x0 ε0, lt_add_right (by rwa [lt_top_iff_ne_top]) ε0'⟩ end interval section bit @[simp] lemma bit0_inj : bit0 a = bit0 b ↔ a = b := ⟨λh, begin rcases (lt_trichotomy a b) with h₁| h₂| h₃, { exact (absurd h (ne_of_lt (add_lt_add h₁ h₁))) }, { exact h₂ }, { exact (absurd h.symm (ne_of_lt (add_lt_add h₃ h₃))) } end, λh, congr_arg _ h⟩ @[simp] lemma bit0_eq_zero_iff : bit0 a = 0 ↔ a = 0 := by simpa only [bit0_zero] using @bit0_inj a 0 @[simp] lemma bit0_eq_top_iff : bit0 a = ∞ ↔ a = ∞ := by rw [bit0, add_eq_top, or_self] @[simp] lemma bit1_inj : bit1 a = bit1 b ↔ a = b := ⟨λh, begin unfold bit1 at h, rwa [add_left_inj, bit0_inj] at h, simp [lt_top_iff_ne_top] end, λh, congr_arg _ h⟩ @[simp] lemma bit1_ne_zero : bit1 a ≠ 0 := by unfold bit1; simp @[simp] lemma bit1_eq_one_iff : bit1 a = 1 ↔ a = 0 := by simpa only [bit1_zero] using @bit1_inj a 0 @[simp] lemma bit1_eq_top_iff : bit1 a = ∞ ↔ a = ∞ := by unfold bit1; rw add_eq_top; simp end bit section inv instance : has_inv ennreal := ⟨λa, Inf {b | 1 ≤ a * b}⟩ instance : has_div ennreal := ⟨λa b, a * b⁻¹⟩ lemma div_def : a / b = a * b⁻¹ := rfl lemma mul_div_assoc : (a * b) / c = a * (b / c) := mul_assoc _ _ _ @[simp] lemma inv_zero : (0 : ennreal)⁻¹ = ∞ := show Inf {b : ennreal | 1 ≤ 0 * b} = ∞, by simp; refl @[simp] lemma inv_top : ∞⁻¹ = 0 := bot_unique $ le_of_forall_le_of_dense $ λ a (h : a > 0), Inf_le $ by simp [*, ne_of_gt h, top_mul] @[simp, norm_cast] lemma coe_inv (hr : r ≠ 0) : (↑r⁻¹ : ennreal) = (↑r)⁻¹ := le_antisymm (le_Inf $ assume b (hb : 1 ≤ ↑r * b), coe_le_iff.2 $ by rintros b rfl; rwa [← coe_mul, ← coe_one, coe_le_coe, ← nnreal.inv_le hr] at hb) (Inf_le $ by simp; rw [← coe_mul, nnreal.mul_inv_cancel hr]; exact le_refl 1) lemma coe_inv_le : (↑r⁻¹ : ennreal) ≤ (↑r)⁻¹ := if hr : r = 0 then by simp only [hr, nnreal.inv_zero, inv_zero, coe_zero, zero_le] else by simp only [coe_inv hr, le_refl] @[norm_cast] lemma coe_inv_two : ((2⁻¹:ℝ≥0):ennreal) = 2⁻¹ := by rw [coe_inv (ne_of_gt _root_.zero_lt_two), coe_two] @[simp, norm_cast] lemma coe_div (hr : r ≠ 0) : (↑(p / r) : ennreal) = p / r := show ↑(p * r⁻¹) = ↑p * (↑r)⁻¹, by rw [coe_mul, coe_inv hr] @[simp] lemma inv_one : (1:ennreal)⁻¹ = 1 := by simpa only [coe_inv one_ne_zero, coe_one] using coe_eq_coe.2 nnreal.inv_one @[simp] lemma div_one {a : ennreal} : a / 1 = a := by simp [ennreal.div_def] protected lemma inv_pow {n : ℕ} : (a^n)⁻¹ = (a⁻¹)^n := begin by_cases a = 0; cases a; cases n; simp [*, none_eq_top, some_eq_coe, zero_pow, top_pow, nat.zero_lt_succ] at *, rw [← coe_inv h, ← coe_pow, ← coe_inv, nnreal.inv_pow, coe_pow], rw [← ne.def] at h, rw [← zero_lt_iff_ne_zero] at *, apply pow_pos h end @[simp] lemma inv_inv : (a⁻¹)⁻¹ = a := by by_cases a = 0; cases a; simp [*, none_eq_top, some_eq_coe, -coe_inv, (coe_inv _).symm] at * lemma inv_involutive : function.involutive (λ a:ennreal, a⁻¹) := λ a, ennreal.inv_inv lemma inv_bijective : function.bijective (λ a:ennreal, a⁻¹) := ennreal.inv_involutive.bijective @[simp] lemma inv_eq_inv : a⁻¹ = b⁻¹ ↔ a = b := inv_bijective.1.eq_iff @[simp] lemma inv_eq_top : a⁻¹ = ∞ ↔ a = 0 := inv_zero ▸ inv_eq_inv lemma inv_ne_top : a⁻¹ ≠ ∞ ↔ a ≠ 0 := by simp @[simp] lemma inv_lt_top {x : ennreal} : x⁻¹ < ∞ ↔ 0 < x := by { simp only [lt_top_iff_ne_top, inv_ne_top, zero_lt_iff_ne_zero] } lemma div_lt_top {x y : ennreal} (h1 : x < ∞) (h2 : 0 < y) : x / y < ∞ := mul_lt_top h1 (inv_lt_top.mpr h2) @[simp] lemma inv_eq_zero : a⁻¹ = 0 ↔ a = ∞ := inv_top ▸ inv_eq_inv lemma inv_ne_zero : a⁻¹ ≠ 0 ↔ a ≠ ∞ := by simp @[simp] lemma inv_pos : 0 < a⁻¹ ↔ a ≠ ∞ := zero_lt_iff_ne_zero.trans inv_ne_zero @[simp] lemma inv_lt_inv : a⁻¹ < b⁻¹ ↔ b < a := begin cases a; cases b; simp only [some_eq_coe, none_eq_top, inv_top], { simp only [lt_irrefl] }, { exact inv_pos.trans lt_top_iff_ne_top.symm }, { simp only [not_lt_zero, not_top_lt] }, { cases eq_or_lt_of_le (zero_le a) with ha ha; cases eq_or_lt_of_le (zero_le b) with hb hb, { subst a, subst b, simp }, { subst a, simp }, { subst b, simp [zero_lt_iff_ne_zero, lt_top_iff_ne_top, inv_ne_top] }, { rw [← coe_inv (ne_of_gt ha), ← coe_inv (ne_of_gt hb), coe_lt_coe, coe_lt_coe], simp only [nnreal.coe_lt_coe.symm] at *, exact inv_lt_inv ha hb } } end lemma inv_lt_iff_inv_lt : a⁻¹ < b ↔ b⁻¹ < a := by simpa only [inv_inv] using @inv_lt_inv a b⁻¹ lemma lt_inv_iff_lt_inv : a < b⁻¹ ↔ b < a⁻¹ := by simpa only [inv_inv] using @inv_lt_inv a⁻¹ b @[simp, priority 1100] -- higher than le_inv_iff_mul_le lemma inv_le_inv : a⁻¹ ≤ b⁻¹ ↔ b ≤ a := by simp only [le_iff_lt_or_eq, inv_lt_inv, inv_eq_inv, eq_comm] lemma inv_le_iff_inv_le : a⁻¹ ≤ b ↔ b⁻¹ ≤ a := by simpa only [inv_inv] using @inv_le_inv a b⁻¹ lemma le_inv_iff_le_inv : a ≤ b⁻¹ ↔ b ≤ a⁻¹ := by simpa only [inv_inv] using @inv_le_inv a⁻¹ b @[simp] lemma inv_lt_one : a⁻¹ < 1 ↔ 1 < a := inv_lt_iff_inv_lt.trans $ by rw [inv_one] @[simp] lemma div_top : a / ∞ = 0 := by simp only [div_def, inv_top, mul_zero] @[simp] lemma top_div_coe : ∞ / p = ∞ := by simp [div_def, top_mul] lemma top_div_of_ne_top (h : a ≠ ∞) : ∞ / a = ∞ := by { lift a to ℝ≥0 using h, exact top_div_coe } lemma top_div_of_lt_top (h : a < ∞) : ∞ / a = ∞ := top_div_of_ne_top h.ne lemma top_div : ∞ / a = if a = ∞ then 0 else ∞ := by by_cases a = ∞; simp [top_div_of_ne_top, *] @[simp] lemma zero_div : 0 / a = 0 := zero_mul a⁻¹ lemma div_eq_top : a / b = ∞ ↔ (a ≠ 0 ∧ b = 0) ∨ (a = ∞ ∧ b ≠ ∞) := by simp [ennreal.div_def, ennreal.mul_eq_top] lemma le_div_iff_mul_le (h0 : b ≠ 0 ∨ c ≠ 0) (ht : b ≠ ∞ ∨ c ≠ ∞) : a ≤ c / b ↔ a * b ≤ c := begin cases b, { simp at ht, split, { assume ha, simp at ha, simp [ha] }, { contrapose, assume ha, simp at ha, have : a * ∞ = ∞, by simp [ennreal.mul_eq_top, ha], simp [this, ht] } }, by_cases hb : b ≠ 0, { have : (b : ennreal) ≠ 0, by simp [hb], rw [← ennreal.mul_le_mul_left this coe_ne_top], suffices : ↑b * a ≤ (↑b * ↑b⁻¹) * c ↔ a * ↑b ≤ c, { simpa [some_eq_coe, div_def, hb, mul_left_comm, mul_comm, mul_assoc] }, rw [← coe_mul, nnreal.mul_inv_cancel hb, coe_one, one_mul, mul_comm] }, { simp at hb, simp [hb] at h0, have : c / 0 = ∞, by simp [div_eq_top, h0], simp [hb, this] } end lemma div_le_iff_le_mul (hb0 : b ≠ 0 ∨ c ≠ ∞) (hbt : b ≠ ∞ ∨ c ≠ 0) : a / b ≤ c ↔ a ≤ c * b := begin suffices : a * b⁻¹ ≤ c ↔ a ≤ c / b⁻¹, by simpa [div_def], apply (le_div_iff_mul_le _ _).symm, simpa [inv_ne_zero] using hbt, simpa [inv_ne_zero] using hb0 end lemma div_le_of_le_mul (h : a ≤ b * c) : a / c ≤ b := begin by_cases h0 : c = 0, { have : a = 0, by simpa [h0] using h, simp [*] }, by_cases hinf : c = ∞, by simp [hinf], exact (div_le_iff_le_mul (or.inl h0) (or.inl hinf)).2 h end protected lemma div_lt_iff (h0 : b ≠ 0 ∨ c ≠ 0) (ht : b ≠ ∞ ∨ c ≠ ∞) : c / b < a ↔ c < a * b := lt_iff_lt_of_le_iff_le $ le_div_iff_mul_le h0 ht lemma mul_lt_of_lt_div (h : a < b / c) : a * c < b := by { contrapose! h, exact ennreal.div_le_of_le_mul h } lemma inv_le_iff_le_mul : (b = ∞ → a ≠ 0) → (a = ∞ → b ≠ 0) → (a⁻¹ ≤ b ↔ 1 ≤ a * b) := begin cases a; cases b; simp [none_eq_top, some_eq_coe, mul_top, top_mul] {contextual := tt}, by_cases a = 0; simp [*, -coe_mul, coe_mul.symm, -coe_inv, (coe_inv _).symm, nnreal.inv_le] end @[simp] lemma le_inv_iff_mul_le : a ≤ b⁻¹ ↔ a * b ≤ 1 := begin cases b, { by_cases a = 0; simp [*, none_eq_top, mul_top] }, by_cases b = 0; simp [*, some_eq_coe, le_div_iff_mul_le], suffices : a ≤ 1 / b ↔ a * b ≤ 1, { simpa [div_def, h] }, exact le_div_iff_mul_le (or.inl (mt coe_eq_coe.1 h)) (or.inl coe_ne_top) end lemma mul_inv_cancel (h0 : a ≠ 0) (ht : a ≠ ∞) : a * a⁻¹ = 1 := begin lift a to ℝ≥0 using ht, norm_cast at h0, norm_cast, exact nnreal.mul_inv_cancel h0 end lemma inv_mul_cancel (h0 : a ≠ 0) (ht : a ≠ ∞) : a⁻¹ * a = 1 := mul_comm a a⁻¹ ▸ mul_inv_cancel h0 ht lemma mul_le_iff_le_inv {a b r : ennreal} (hr₀ : r ≠ 0) (hr₁ : r ≠ ∞) : (r * a ≤ b ↔ a ≤ r⁻¹ * b) := by rw [← @ennreal.mul_le_mul_left _ a _ hr₀ hr₁, ← mul_assoc, mul_inv_cancel hr₀ hr₁, one_mul] lemma le_of_forall_nnreal_lt {x y : ennreal} (h : ∀ r : ℝ≥0, ↑r < x → ↑r ≤ y) : x ≤ y := begin refine le_of_forall_ge_of_dense (λ r hr, _), lift r to ℝ≥0 using ne_top_of_lt hr, exact h r hr end lemma div_add_div_same {a b c : ennreal} : a / c + b / c = (a + b) / c := eq.symm $ right_distrib a b (c⁻¹) lemma div_self (h0 : a ≠ 0) (hI : a ≠ ∞) : a / a = 1 := mul_inv_cancel h0 hI lemma mul_div_cancel (h0 : a ≠ 0) (hI : a ≠ ∞) : (b / a) * a = b := by rw [div_def, mul_assoc, inv_mul_cancel h0 hI, mul_one] lemma mul_div_cancel' (h0 : a ≠ 0) (hI : a ≠ ∞) : a * (b / a) = b := by rw [mul_comm, mul_div_cancel h0 hI] lemma inv_two_add_inv_two : (2:ennreal)⁻¹ + 2⁻¹ = 1 := by rw [← two_mul, ← div_def, div_self two_ne_zero two_ne_top] lemma add_halves (a : ennreal) : a / 2 + a / 2 = a := by rw [div_def, ← mul_add, inv_two_add_inv_two, mul_one] @[simp] lemma div_zero_iff : a / b = 0 ↔ a = 0 ∨ b = ∞ := by simp [div_def, mul_eq_zero] @[simp] lemma div_pos_iff : 0 < a / b ↔ a ≠ 0 ∧ b ≠ ∞ := by simp [zero_lt_iff_ne_zero, not_or_distrib] lemma half_pos {a : ennreal} (h : 0 < a) : 0 < a / 2 := by simp [ne_of_gt h] lemma one_half_lt_one : (2⁻¹:ennreal) < 1 := inv_lt_one.2 $ one_lt_two lemma half_lt_self {a : ennreal} (hz : a ≠ 0) (ht : a ≠ ∞) : a / 2 < a := begin lift a to ℝ≥0 using ht, have h : (2 : ennreal) = ((2 : ℝ≥0) : ennreal), from rfl, have h' : (2 : ℝ≥0) ≠ 0, from _root_.two_ne_zero', rw [h, ← coe_div h', coe_lt_coe], -- `norm_cast` fails to apply `coe_div` norm_cast at hz, exact nnreal.half_lt_self hz end lemma sub_half (h : a ≠ ∞) : a - a / 2 = a / 2 := begin lift a to ℝ≥0 using h, exact sub_eq_of_add_eq (mul_ne_top coe_ne_top $ by simp) (add_halves a) end lemma one_sub_inv_two : (1:ennreal) - 2⁻¹ = 2⁻¹ := by simpa only [div_def, one_mul] using sub_half one_ne_top lemma exists_inv_nat_lt {a : ennreal} (h : a ≠ 0) : ∃n:ℕ, (n:ennreal)⁻¹ < a := @inv_inv a ▸ by simp only [inv_lt_inv, ennreal.exists_nat_gt (inv_ne_top.2 h)] lemma exists_nat_pos_mul_gt (ha : a ≠ 0) (hb : b ≠ ∞) : ∃ n > 0, b < (n : ℕ) * a := begin have : b / a ≠ ∞, from mul_ne_top hb (inv_ne_top.2 ha), refine (ennreal.exists_nat_gt this).imp (λ n hn, _), have : 0 < (n : ennreal), from (zero_le _).trans_lt hn, refine ⟨coe_nat_lt_coe_nat.1 this, _⟩, rwa [← ennreal.div_lt_iff (or.inl ha) (or.inr hb)] end lemma exists_nat_mul_gt (ha : a ≠ 0) (hb : b ≠ ∞) : ∃ n : ℕ, b < n * a := (exists_nat_pos_mul_gt ha hb).imp $ λ n, Exists.snd lemma exists_nat_pos_inv_mul_lt (ha : a ≠ ∞) (hb : b ≠ 0) : ∃ n > 0, ((n : ℕ) : ennreal)⁻¹ * a < b := begin rcases exists_nat_pos_mul_gt hb ha with ⟨n, npos, hn⟩, have : (n : ennreal) ≠ 0 := nat.cast_ne_zero.2 npos.lt.ne', use [n, npos], rwa [← one_mul b, ← inv_mul_cancel this coe_nat_ne_top, mul_assoc, mul_lt_mul_left (inv_ne_zero.2 coe_nat_ne_top) (inv_ne_top.2 this)] end lemma exists_nnreal_pos_mul_lt (ha : a ≠ ∞) (hb : b ≠ 0) : ∃ n > 0, ↑(n : ℝ≥0) * a < b := begin rcases exists_nat_pos_inv_mul_lt ha hb with ⟨n, npos : 0 < n, hn⟩, use (n : ℝ≥0)⁻¹, simp [*, npos.ne', zero_lt_one] end end inv section real lemma to_real_add (ha : a ≠ ∞) (hb : b ≠ ∞) : (a+b).to_real = a.to_real + b.to_real := begin lift a to ℝ≥0 using ha, lift b to ℝ≥0 using hb, refl end lemma to_real_add_le : (a+b).to_real ≤ a.to_real + b.to_real := if ha : a = ∞ then by simp only [ha, top_add, top_to_real, zero_add, to_real_nonneg] else if hb : b = ∞ then by simp only [hb, add_top, top_to_real, add_zero, to_real_nonneg] else le_of_eq (to_real_add ha hb) lemma of_real_add {p q : ℝ} (hp : 0 ≤ p) (hq : 0 ≤ q) : ennreal.of_real (p + q) = ennreal.of_real p + ennreal.of_real q := by rw [ennreal.of_real, ennreal.of_real, ennreal.of_real, ← coe_add, coe_eq_coe, nnreal.of_real_add hp hq] lemma of_real_add_le {p q : ℝ} : ennreal.of_real (p + q) ≤ ennreal.of_real p + ennreal.of_real q := coe_le_coe.2 nnreal.of_real_add_le @[simp] lemma to_real_le_to_real (ha : a ≠ ∞) (hb : b ≠ ∞) : a.to_real ≤ b.to_real ↔ a ≤ b := begin lift a to ℝ≥0 using ha, lift b to ℝ≥0 using hb, norm_cast end @[simp] lemma to_real_lt_to_real (ha : a ≠ ∞) (hb : b ≠ ∞) : a.to_real < b.to_real ↔ a < b := begin lift a to ℝ≥0 using ha, lift b to ℝ≥0 using hb, norm_cast end lemma to_real_max (hr : a ≠ ∞) (hp : b ≠ ∞) : ennreal.to_real (max a b) = max (ennreal.to_real a) (ennreal.to_real b) := (le_total a b).elim (λ h, by simp only [h, (ennreal.to_real_le_to_real hr hp).2 h, max_eq_right]) (λ h, by simp only [h, (ennreal.to_real_le_to_real hp hr).2 h, max_eq_left]) lemma to_nnreal_pos_iff : 0 < a.to_nnreal ↔ (0 < a ∧ a ≠ ∞) := begin cases a, { simp [none_eq_top] }, { simp [some_eq_coe] } end lemma to_real_pos_iff : 0 < a.to_real ↔ (0 < a ∧ a ≠ ∞):= (nnreal.coe_pos).trans to_nnreal_pos_iff lemma of_real_le_of_real {p q : ℝ} (h : p ≤ q) : ennreal.of_real p ≤ ennreal.of_real q := by simp [ennreal.of_real, nnreal.of_real_le_of_real h] lemma of_real_le_of_le_to_real {a : ℝ} {b : ennreal} (h : a ≤ ennreal.to_real b) : ennreal.of_real a ≤ b := (of_real_le_of_real h).trans of_real_to_real_le @[simp] lemma of_real_le_of_real_iff {p q : ℝ} (h : 0 ≤ q) : ennreal.of_real p ≤ ennreal.of_real q ↔ p ≤ q := by rw [ennreal.of_real, ennreal.of_real, coe_le_coe, nnreal.of_real_le_of_real_iff h] @[simp] lemma of_real_lt_of_real_iff {p q : ℝ} (h : 0 < q) : ennreal.of_real p < ennreal.of_real q ↔ p < q := by rw [ennreal.of_real, ennreal.of_real, coe_lt_coe, nnreal.of_real_lt_of_real_iff h] lemma of_real_lt_of_real_iff_of_nonneg {p q : ℝ} (hp : 0 ≤ p) : ennreal.of_real p < ennreal.of_real q ↔ p < q := by rw [ennreal.of_real, ennreal.of_real, coe_lt_coe, nnreal.of_real_lt_of_real_iff_of_nonneg hp] @[simp] lemma of_real_pos {p : ℝ} : 0 < ennreal.of_real p ↔ 0 < p := by simp [ennreal.of_real] @[simp] lemma of_real_eq_zero {p : ℝ} : ennreal.of_real p = 0 ↔ p ≤ 0 := by simp [ennreal.of_real] lemma of_real_le_iff_le_to_real {a : ℝ} {b : ennreal} (hb : b ≠ ∞) : ennreal.of_real a ≤ b ↔ a ≤ ennreal.to_real b := begin lift b to ℝ≥0 using hb, simpa [ennreal.of_real, ennreal.to_real] using nnreal.of_real_le_iff_le_coe end lemma of_real_lt_iff_lt_to_real {a : ℝ} {b : ennreal} (ha : 0 ≤ a) (hb : b ≠ ∞) : ennreal.of_real a < b ↔ a < ennreal.to_real b := begin lift b to ℝ≥0 using hb, simpa [ennreal.of_real, ennreal.to_real] using nnreal.of_real_lt_iff_lt_coe ha end lemma le_of_real_iff_to_real_le {a : ennreal} {b : ℝ} (ha : a ≠ ∞) (hb : 0 ≤ b) : a ≤ ennreal.of_real b ↔ ennreal.to_real a ≤ b := begin lift a to ℝ≥0 using ha, simpa [ennreal.of_real, ennreal.to_real] using nnreal.le_of_real_iff_coe_le hb end lemma to_real_le_of_le_of_real {a : ennreal} {b : ℝ} (hb : 0 ≤ b) (h : a ≤ ennreal.of_real b) : ennreal.to_real a ≤ b := have ha : a ≠ ∞, from ne_top_of_le_ne_top of_real_ne_top h, (le_of_real_iff_to_real_le ha hb).1 h lemma lt_of_real_iff_to_real_lt {a : ennreal} {b : ℝ} (ha : a ≠ ∞) : a < ennreal.of_real b ↔ ennreal.to_real a < b := begin lift a to ℝ≥0 using ha, simpa [ennreal.of_real, ennreal.to_real] using nnreal.lt_of_real_iff_coe_lt end lemma of_real_mul {p q : ℝ} (hp : 0 ≤ p) : ennreal.of_real (p * q) = (ennreal.of_real p) * (ennreal.of_real q) := by { simp only [ennreal.of_real, coe_mul.symm, coe_eq_coe], exact nnreal.of_real_mul hp } lemma of_real_inv_of_pos {x : ℝ} (hx : 0 < x) : (ennreal.of_real x)⁻¹ = ennreal.of_real x⁻¹ := by rw [ennreal.of_real, ennreal.of_real, ←@coe_inv (nnreal.of_real x) (by simp [hx]), coe_eq_coe, nnreal.of_real_inv.symm] lemma of_real_div_of_pos {x y : ℝ} (hy : 0 < y) : ennreal.of_real (x / y) = ennreal.of_real x / ennreal.of_real y := by rw [div_def, of_real_inv_of_pos hy, mul_comm, ←of_real_mul (inv_nonneg.mpr (le_of_lt hy)), div_eq_mul_inv, mul_comm] lemma to_real_of_real_mul (c : ℝ) (a : ennreal) (h : 0 ≤ c) : ennreal.to_real ((ennreal.of_real c) * a) = c * ennreal.to_real a := begin cases a, { simp only [none_eq_top, ennreal.to_real, top_to_nnreal, nnreal.coe_zero, mul_zero, mul_top], by_cases h' : c ≤ 0, { rw [if_pos], { simp }, { convert of_real_zero, exact le_antisymm h' h } }, { rw [if_neg], refl, rw [of_real_eq_zero], assumption } }, { simp only [ennreal.to_real, ennreal.to_nnreal], simp only [some_eq_coe, ennreal.of_real, coe_mul.symm, to_nnreal_coe, nnreal.coe_mul], congr, apply nnreal.coe_of_real, exact h } end @[simp] lemma to_nnreal_mul_top (a : ennreal) : ennreal.to_nnreal (a * ∞) = 0 := begin by_cases h : a = 0, { rw [h, zero_mul, zero_to_nnreal] }, { rw [mul_top, if_neg h, top_to_nnreal] } end @[simp] lemma to_nnreal_top_mul (a : ennreal) : ennreal.to_nnreal (∞ * a) = 0 := by rw [mul_comm, to_nnreal_mul_top] @[simp] lemma to_real_mul_top (a : ennreal) : ennreal.to_real (a * ∞) = 0 := by rw [ennreal.to_real, to_nnreal_mul_top, nnreal.coe_zero] @[simp] lemma to_real_top_mul (a : ennreal) : ennreal.to_real (∞ * a) = 0 := by { rw mul_comm, exact to_real_mul_top _ } lemma to_real_eq_to_real (ha : a < ∞) (hb : b < ∞) : ennreal.to_real a = ennreal.to_real b ↔ a = b := begin lift a to ℝ≥0 using ha.ne, lift b to ℝ≥0 using hb.ne, simp only [coe_eq_coe, nnreal.coe_eq, coe_to_real], end /-- `ennreal.to_nnreal` as a `monoid_hom`. -/ def to_nnreal_hom : ennreal →* ℝ≥0 := { to_fun := ennreal.to_nnreal, map_one' := to_nnreal_coe, map_mul' := by rintro (_|x) (_|y); simp only [← coe_mul, none_eq_top, some_eq_coe, to_nnreal_top_mul, to_nnreal_mul_top, top_to_nnreal, mul_zero, zero_mul, to_nnreal_coe] } lemma to_nnreal_mul {a b : ennreal}: (a * b).to_nnreal = a.to_nnreal * b.to_nnreal := to_nnreal_hom.map_mul a b lemma to_nnreal_pow (a : ennreal) (n : ℕ) : (a ^ n).to_nnreal = a.to_nnreal ^ n := to_nnreal_hom.map_pow a n lemma to_nnreal_prod {ι : Type*} {s : finset ι} {f : ι → ennreal} : (∏ i in s, f i).to_nnreal = ∏ i in s, (f i).to_nnreal := to_nnreal_hom.map_prod _ _ /-- `ennreal.to_real` as a `monoid_hom`. -/ def to_real_hom : ennreal →* ℝ := (nnreal.to_real_hom : ℝ≥0 →* ℝ).comp to_nnreal_hom lemma to_real_mul : (a * b).to_real = a.to_real * b.to_real := to_real_hom.map_mul a b lemma to_real_pow (a : ennreal) (n : ℕ) : (a ^ n).to_real = a.to_real ^ n := to_real_hom.map_pow a n lemma to_real_prod {ι : Type*} {s : finset ι} {f : ι → ennreal} : (∏ i in s, f i).to_real = ∏ i in s, (f i).to_real := to_real_hom.map_prod _ _ end real section infi variables {ι : Sort*} {f g : ι → ennreal} lemma infi_add : infi f + a = ⨅i, f i + a := le_antisymm (le_infi $ assume i, add_le_add (infi_le _ _) $ le_refl _) (ennreal.sub_le_iff_le_add.1 $ le_infi $ assume i, ennreal.sub_le_iff_le_add.2 $ infi_le _ _) lemma supr_sub : (⨆i, f i) - a = (⨆i, f i - a) := le_antisymm (ennreal.sub_le_iff_le_add.2 $ supr_le $ assume i, ennreal.sub_le_iff_le_add.1 $ le_supr _ i) (supr_le $ assume i, ennreal.sub_le_sub (le_supr _ _) (le_refl a)) lemma sub_infi : a - (⨅i, f i) = (⨆i, a - f i) := begin refine (eq_of_forall_ge_iff $ λ c, _), rw [ennreal.sub_le_iff_le_add, add_comm, infi_add], simp [ennreal.sub_le_iff_le_add, sub_eq_add_neg, add_comm], end lemma Inf_add {s : set ennreal} : Inf s + a = ⨅b∈s, b + a := by simp [Inf_eq_infi, infi_add] lemma add_infi {a : ennreal} : a + infi f = ⨅b, a + f b := by rw [add_comm, infi_add]; simp [add_comm] lemma infi_add_infi (h : ∀i j, ∃k, f k + g k ≤ f i + g j) : infi f + infi g = (⨅a, f a + g a) := suffices (⨅a, f a + g a) ≤ infi f + infi g, from le_antisymm (le_infi $ assume a, add_le_add (infi_le _ _) (infi_le _ _)) this, calc (⨅a, f a + g a) ≤ (⨅ a a', f a + g a') : le_infi $ assume a, le_infi $ assume a', let ⟨k, h⟩ := h a a' in infi_le_of_le k h ... ≤ infi f + infi g : by simp [add_infi, infi_add, -add_comm, -le_infi_iff]; exact le_refl _ lemma infi_sum {f : ι → α → ennreal} {s : finset α} [nonempty ι] (h : ∀(t : finset α) (i j : ι), ∃k, ∀a∈t, f k a ≤ f i a ∧ f k a ≤ f j a) : (⨅i, ∑ a in s, f i a) = ∑ a in s, ⨅i, f i a := finset.induction_on s (by simp) $ assume a s ha ih, have ∀ (i j : ι), ∃ (k : ι), f k a + ∑ b in s, f k b ≤ f i a + ∑ b in s, f j b, from assume i j, let ⟨k, hk⟩ := h (insert a s) i j in ⟨k, add_le_add (hk a (finset.mem_insert_self _ _)).left $ finset.sum_le_sum $ assume a ha, (hk _ $ finset.mem_insert_of_mem ha).right⟩, by simp [ha, ih.symm, infi_add_infi this] lemma infi_mul {ι} [nonempty ι] {f : ι → ennreal} {x : ennreal} (h : x ≠ ∞) : infi f * x = ⨅i, f i * x := begin by_cases h2 : x = 0, simp only [h2, mul_zero, infi_const], refine le_antisymm (le_infi $ λ i, mul_right_mono $ infi_le _ _) ((div_le_iff_le_mul (or.inl h2) $ or.inl h).mp $ le_infi $ λ i, (div_le_iff_le_mul (or.inl h2) $ or.inl h).mpr $ infi_le _ _) end lemma mul_infi {ι} [nonempty ι] {f : ι → ennreal} {x : ennreal} (h : x ≠ ∞) : x * infi f = ⨅i, x * f i := by { rw [mul_comm, infi_mul h], simp only [mul_comm], assumption } /-! `supr_mul`, `mul_supr` and variants are in `topology.instances.ennreal`. -/ end infi section supr lemma supr_coe_nat : (⨆n:ℕ, (n : ennreal)) = ∞ := (supr_eq_top _).2 $ assume b hb, ennreal.exists_nat_gt (lt_top_iff_ne_top.1 hb) end supr /-- `le_of_add_le_add_left` is normally applicable to `ordered_cancel_add_comm_monoid`, but it holds in `ennreal` with the additional assumption that `a < ∞`. -/ lemma le_of_add_le_add_left {a b c : ennreal} : a < ∞ → a + b ≤ a + c → b ≤ c := by cases a; cases b; cases c; simp [← ennreal.coe_add, ennreal.coe_le_coe] end ennreal
812e81c13d22e3f193eca85adf6685d08c4ed1c8
77c5b91fae1b966ddd1db969ba37b6f0e4901e88
/src/tactic/lint/misc.lean
80ec3ca59662eb2dbc9c283f2d7f9f70c529029b
[ "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
16,417
lean
/- Copyright (c) 2020 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Robert Y. Lewis -/ import tactic.lint.basic /-! # Various linters This file defines several small linters: - `ge_or_gt` checks that `>` and `≥` do not occur in the statement of theorems. - `dup_namespace` checks that no declaration has a duplicated namespace such as `list.list.monad`. - `unused_arguments` checks that definitions and theorems do not have unused arguments. - `doc_blame` checks that every definition has a documentation string. - `doc_blame_thm` checks that every theorem has a documentation string (not enabled by default). - `def_lemma` checks that a declaration is a lemma iff its type is a proposition. - `check_type` checks that the statement of a declaration is well-typed. - `check_univs` checks that there are no bad `max u v` universe levels. - `syn_taut` checks that declarations are not syntactic tautologies. -/ open tactic expr /-! ## Linter against use of `>`/`≥` -/ /-- The names of `≥` and `>`, mostly disallowed in lemma statements -/ private meta def illegal_ge_gt : list name := [`gt, `ge] set_option eqn_compiler.max_steps 20000 /-- Checks whether `≥` and `>` occurs in an illegal way in the expression. The main ways we legally use these orderings are: - `f (≥)` - `∃ x ≥ t, b`. This corresponds to the expression `@Exists α (fun (x : α), (@Exists (x > t) (λ (H : x > t), b)))` This function returns `tt` when it finds `ge`/`gt`, except in the following patterns (which are the same for `gt`): - `f (@ge _ _)` - `f (&0 ≥ y) (λ x : t, b)` - `λ H : &0 ≥ t, b` Here `&0` is the 0-th de Bruijn variable. -/ private meta def contains_illegal_ge_gt : expr → bool | (const nm us) := if nm ∈ illegal_ge_gt then tt else ff | (app f e@(app (app (const nm us) tp) tc)) := contains_illegal_ge_gt f || if nm ∈ illegal_ge_gt then ff else contains_illegal_ge_gt e | (app (app custom_binder (app (app (app (app (const nm us) tp) tc) (var 0)) t)) e@(lam var_name bi var_type body)) := contains_illegal_ge_gt e || if nm ∈ illegal_ge_gt then ff else contains_illegal_ge_gt e | (app f x) := contains_illegal_ge_gt f || contains_illegal_ge_gt x | (lam `H bi type@(app (app (app (app (const nm us) tp) tc) (var 0)) t) body) := contains_illegal_ge_gt body || if nm ∈ illegal_ge_gt then ff else contains_illegal_ge_gt type | (lam var_name bi var_type body) := contains_illegal_ge_gt var_type || contains_illegal_ge_gt body | (pi `H bi type@(app (app (app (app (const nm us) tp) tc) (var 0)) t) body) := contains_illegal_ge_gt body || if nm ∈ illegal_ge_gt then ff else contains_illegal_ge_gt type | (pi var_name bi var_type body) := contains_illegal_ge_gt var_type || contains_illegal_ge_gt body | (elet var_name type assignment body) := contains_illegal_ge_gt type || contains_illegal_ge_gt assignment || contains_illegal_ge_gt body | _ := ff /-- Checks whether a `>`/`≥` is used in the statement of `d`. It first does a quick check to see if there is any `≥` or `>` in the statement, and then does a slower check whether the occurrences of `≥` and `>` are allowed. Currently it checks only the conclusion of the declaration, to eliminate false positive from binders such as `∀ ε > 0, ...` -/ private meta def ge_or_gt_in_statement (d : declaration) : tactic (option string) := return $ if d.type.contains_constant (λ n, n ∈ illegal_ge_gt) && contains_illegal_ge_gt d.type then some "the type contains ≥/>. Use ≤/< instead." else none -- TODO: the commented out code also checks for classicality in statements, but needs fixing -- TODO: this probably needs to also check whether the argument is a variable or @eq <var> _ _ -- meta def illegal_constants_in_statement (d : declaration) : tactic (option string) := -- return $ if d.type.contains_constant (λ n, (n.get_prefix = `classical ∧ -- n.last ∈ ["prop_decidable", "dec", "dec_rel", "dec_eq"]) ∨ n ∈ [`gt, `ge]) -- then -- let illegal1 := [`classical.prop_decidable, `classical.dec, `classical.dec_rel, -- `classical.dec_eq], -- illegal2 := [`gt, `ge], -- occur1 := illegal1.filter (λ n, d.type.contains_constant (eq n)), -- occur2 := illegal2.filter (λ n, d.type.contains_constant (eq n)) in -- some $ sformat!"the type contains the following declarations: {occur1 ++ occur2}." ++ -- (if occur1 = [] then "" else " Add decidability type-class arguments instead.") ++ -- (if occur2 = [] then "" else " Use ≤/< instead.") -- else none /-- A linter for checking whether illegal constants (≥, >) appear in a declaration's type. -/ @[linter] meta def linter.ge_or_gt : linter := { test := ge_or_gt_in_statement, auto_decls := ff, no_errors_found := "Not using ≥/> in declarations.", errors_found := "The following declarations use ≥/>, probably in a way where we would prefer to use ≤/< instead. See note [nolint_ge] for more information.", is_fast := ff } /-- Currently, the linter forbids the use of `>` and `≥` in definitions and statements, as they cause problems in rewrites. They are still allowed in statements such as `bounded (≥)` or `∀ ε > 0` or `⨆ n ≥ m`, and the linter allows that. If you write a pattern where you bind two or more variables, like `∃ n m > 0`, the linter will flag this as illegal, but it is also allowed. In this case, add the line ``` @[nolint ge_or_gt] -- see Note [nolint_ge] ``` -/ library_note "nolint_ge" /-! ## Linter for duplicate namespaces -/ /-- Checks whether a declaration has a namespace twice consecutively in its name -/ private meta def dup_namespace (d : declaration) : tactic (option string) := is_instance d.to_name >>= λ is_inst, return $ let nm := d.to_name.components in if nm.chain' (≠) ∨ is_inst then none else let s := (nm.find $ λ n, nm.count n ≥ 2).iget.to_string in some $ "The namespace `" ++ s ++ "` is duplicated in the name" /-- A linter for checking whether a declaration has a namespace twice consecutively in its name. -/ @[linter] meta def linter.dup_namespace : linter := { test := dup_namespace, auto_decls := ff, no_errors_found := "No declarations have a duplicate namespace.", errors_found := "DUPLICATED NAMESPACES IN NAME:" } /-! ## Linter for unused arguments -/ /-- Auxiliary definition for `check_unused_arguments` -/ private 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 ∧ ¬ is_pi e then l 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). Checks both the type and the value of `d` for whether the argument is used (in rare cases an argument is used in the type but not in the value). We return [] if the declaration was automatically generated. We print arguments that are larger than the arity of the type of the declaration (without unfolding definitions). -/ 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 let l2 := check_unused_arguments_aux [] 1 d.type.pi_arity d.type in (l.filter $ λ n, n ∈ l2).reverse /-- Check for unused arguments, and print them with their position, variable name, type and whether the argument is a duplicate. See also `check_unused_arguments`. This tactic additionally filters out all unused arguments of type `parse _`. -/ private meta def unused_arguments (d : declaration) : tactic (option string) := do let ns := check_unused_arguments d, if ¬ ns.is_some then return none else do let ns := ns.iget, (ds, _) ← get_pi_binders d.type, let ns := ns.map (λ n, (n, (ds.nth $ n - 1).iget)), let ns := ns.filter (λ x, x.2.type.get_app_fn ≠ const `interactive.parse []), if ns = [] then return none else do ds' ← ds.mmap pp, ns ← ns.mmap (λ ⟨n, b⟩, (λ s, to_fmt "argument " ++ to_fmt n ++ ": " ++ s ++ (if ds.countp (λ b', b.type = b'.type) ≥ 2 then " (duplicate)" else "")) <$> pp b), return $ some $ ns.to_string_aux tt /-- A linter object for checking for unused arguments. This is in the default linter set. -/ @[linter] meta def linter.unused_arguments : linter := { test := unused_arguments, auto_decls := ff, no_errors_found := "No unused arguments.", errors_found := "UNUSED ARGUMENTS." } attribute [nolint unused_arguments] imp_intro /-! ## Linter for documentation strings -/ /-- Reports definitions and constants that are missing doc strings -/ private meta def doc_blame_report_defn : declaration → tactic (option string) | (declaration.defn n _ _ _ _ _) := doc_string n >> return none <|> return "def missing doc string" | (declaration.cnst n _ _ _) := doc_string n >> return none <|> return "constant missing doc string" | _ := return none /-- Reports definitions and constants that are missing doc strings -/ private meta def doc_blame_report_thm : declaration → tactic (option string) | (declaration.thm n _ _ _) := doc_string n >> return none <|> return "theorem missing doc string" | _ := return none /-- A linter for checking definition doc strings -/ @[linter] meta def linter.doc_blame : linter := { test := λ d, mcond (bnot <$> has_attribute' `instance d.to_name) (doc_blame_report_defn d) (return none), auto_decls := ff, no_errors_found := "No definitions are missing documentation.", errors_found := "DEFINITIONS ARE MISSING DOCUMENTATION STRINGS:" } /-- A linter for checking theorem doc strings. This is not in the default linter set. -/ meta def linter.doc_blame_thm : linter := { test := doc_blame_report_thm, auto_decls := ff, no_errors_found := "No theorems are missing documentation.", errors_found := "THEOREMS ARE MISSING DOCUMENTATION STRINGS:", is_fast := ff } /-! ## Linter for correct usage of `lemma`/`def` -/ /-- Checks whether the correct declaration constructor (definition or theorem) by comparing it to its sort. Instances will not be printed. This test is not very quick: maybe we can speed-up testing that something is a proposition? This takes almost all of the execution time. -/ private meta def incorrect_def_lemma (d : declaration) : tactic (option string) := if d.is_constant ∨ d.is_axiom then return none else do is_instance_d ← is_instance d.to_name, if is_instance_d then return none else do -- the following seems to be a little quicker than `is_prop d.type`. expr.sort n ← infer_type d.type, is_pattern ← has_attribute' `pattern d.to_name, return $ if d.is_theorem ↔ n = level.zero then none else if d.is_theorem then "is a lemma/theorem, should be a def" else if is_pattern then none -- declarations with `@[pattern]` are allowed to be a `def`. else "is a def, should be a lemma/theorem" /-- A linter for checking whether the correct declaration constructor (definition or theorem) has been used. -/ @[linter] meta def linter.def_lemma : linter := { test := incorrect_def_lemma, auto_decls := ff, no_errors_found := "All declarations correctly marked as def/lemma.", errors_found := "INCORRECT DEF/LEMMA:" } attribute [nolint def_lemma] classical.dec classical.dec_pred classical.dec_rel classical.dec_eq /-! ## Linter that checks whether declarations are well-typed -/ /-- Checks whether the statement of a declaration is well-typed. -/ meta def check_type (d : declaration) : tactic (option string) := (type_check d.type >> return none) <|> return "The statement doesn't type-check" /-- A linter for missing checking whether statements of declarations are well-typed. -/ @[linter] meta def linter.check_type : linter := { test := check_type, auto_decls := ff, no_errors_found := "The statements of all declarations type-check with default reducibility settings.", errors_found := "THE STATEMENTS OF THE FOLLOWING DECLARATIONS DO NOT TYPE-CHECK. Some definitions in the statement are marked `@[irreducible]`, which means that the statement " ++ "is now ill-formed. It is likely that these definitions were locally marked as `@[reducible]` " ++ "or `@[semireducible]`. This can especially cause problems with type class inference or " ++ "`@[simps]`.", is_fast := tt } /-! ## Linter for universe parameters -/ open native /-- The good parameters are the parameters that occur somewhere in the `rb_set` as a singleton or (recursively) with only other good parameters. All other parameters in the `rb_set` are bad. -/ meta def bad_params : rb_set (list name) → list name | l := let good_levels : name_set := l.fold mk_name_set $ λ us prev, if us.length = 1 then prev.insert us.head else prev in if good_levels.empty then l.fold [] list.union else bad_params $ rb_set.of_list $ l.to_list.map $ λ us, us.filter $ λ nm, !good_levels.contains nm /-- Checks whether all universe levels `u` in `d` are "good". This means that `u` either occurs in a `level` of `d` by itself, or (recursively) with only other good levels. When this fails, usually this means that there is a level `max u v`, where neither `u` nor `v` occur by themselves in a level. It is ok if *one* of `u` or `v` never occurs alone. For example, `(α : Type u) (β : Type (max u v))` is a occasionally useful method of saying that `β` lives in a higher universe level than `α`. -/ meta def check_univs (d : declaration) : tactic (option string) := do let l := d.type.univ_params_grouped.union d.value.univ_params_grouped, let bad := bad_params l, if bad.empty then return none else return $ some $ "universes " ++ to_string bad ++ " only occur together." /-- A linter for checking that there are no bad `max u v` universe levels. -/ @[linter] meta def linter.check_univs : linter := { test := check_univs, auto_decls := tt, no_errors_found := "All declarations have good universe levels.", errors_found := "THE STATEMENTS OF THE FOLLOWING DECLARATIONS HAVE BAD UNIVERSE LEVELS. " ++ "This usually means that there is a `max u v` in the declaration where neither `u` nor `v` " ++ "occur by themselves. Solution: Find the type (or type bundled with data) that has this " ++ "universe argument and provide the universe level explicitly. If this happens in an implicit " ++ "argument of the declaration, a better solution is to move this argument to a `variables` " ++ "command (where the universe level can be kept implicit). Note: if the linter flags an automatically generated declaration `xyz._proof_i`, it means that the universe problem is with `xyz` itself (even if the linter doesn't flag `xyz`)", is_fast := tt } /-! ## Linter for syntactic tautologies -/ /-- Checks whether a lemma is a declaration of the form `∀ a b ... z, e₁ = e₂` where `e₁` and `e₂` are identical exprs. We call declarations of this form syntactic tautologies. Such lemmas are (mostly) useless and sometimes introduced unintentionally when proving basic facts with rfl when elaboration results in a different term than the user intended. -/ meta def syn_taut (d : declaration) : tactic (option string) := (do (el, er) ← d.type.pi_codomain.is_eq, guardb (el =ₐ er), return $ some "LHS equals RHS syntactically") <|> return none /-- A linter for checking that declarations aren't syntactic tautologies. -/ @[linter] meta def linter.syn_taut : linter := { test := syn_taut, auto_decls := ff, -- many false positives with this enabled no_errors_found := "No declarations are syntactic tautologies.", errors_found := "THE FOLLOWING DECLARATIONS ARE SYNTACTIC TAUTOLOGIES. " ++ "This usually means that they are of the form `∀ a b ... z, e₁ = e₂` where `e₁` and `e₂` are " ++ "identical expressions. We call declarations of this form syntactic tautologies. " ++ "Such lemmas are (mostly) useless and sometimes introduced unintentionally when proving " ++ "basic facts using `rfl`, when elaboration results in a different term than the user intended. " ++ "You should check that the declaration really says what you think it does.", is_fast := tt } attribute [nolint syn_taut] rfl
1c39e61f9b77b95976e1f4487c990484f621c28f
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/combinatorics/pigeonhole.lean
c2c782c521927e3ea51ffb31baa8a2dbe5c554a7
[ "Apache-2.0" ]
permissive
ilitzroth/mathlib
ea647e67f1fdfd19a0f7bdc5504e8acec6180011
5254ef14e3465f6504306132fe3ba9cec9ffff16
refs/heads/master
1,680,086,661,182
1,617,715,647,000
1,617,715,647,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
19,412
lean
/- Copyright (c) 2020 Kyle Miller. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kyle Miller, Yury Kudryashov -/ import data.set.finite import data.nat.modeq import algebra.big_operators.order /-! # Pigeonhole principles Given pigeons (possibly infinitely many) in pigeonholes, the pigeonhole principle states that, if there are more pigeons than pigeonholes, then there is a pigeonhole with two or more pigeons. There are a few variations on this statement, and the conclusion can be made stronger depending on how many pigeons you know you might have. The basic statements of the pigeonhole principle appear in the following locations: * `data.finset.basic` has `finset.exists_ne_map_eq_of_card_lt_of_maps_to` * `data.fintype.basic` has `fintype.exists_ne_map_eq_of_card_lt` * `data.fintype.basic` has `fintype.exists_ne_map_eq_of_infinite` * `data.fintype.basic` has `fintype.exists_infinite_fiber` * `data.set.finite` has `set.infinite.exists_ne_map_eq_of_maps_to` This module gives access to these pigeonhole principles along with 20 more. The versions vary by: * using a function between `fintype`s or a function between possibly infinite types restricted to `finset`s; * counting pigeons by a general weight function (`∑ x in s, w x`) or by heads (`finset.card s`); * using strict or non-strict inequalities; * establishing upper or lower estimate on the number (or the total weight) of the pigeons in one pigeonhole; * in case when we count pigeons by some weight function `w` and consider a function `f` between `finset`s `s` and `t`, we can either assume that each pigeon is in one of the pigeonholes (`∀ x ∈ s, f x ∈ t`), or assume that for `y ∉ t`, the total weight of the pigeons in this pigeonhole `∑ x in s.filter (λ x, f x = y), w x` is nonpositive or nonnegative depending on the inequality we are proving. Lemma names follow `mathlib` convention (e.g., `finset.exists_lt_sum_fiber_of_maps_to_of_nsmul_lt_sum`); "pigeonhole principle" is mentioned in the docstrings instead of the names. ## See also * `ordinal.infinite_pigeonhole`: pigeonhole principle for cardinals, formulated using cofinality; * `measure_theory.exists_nonempty_inter_of_measure_univ_lt_tsum_measure`, `measure_theory.exists_nonempty_inter_of_measure_univ_lt_sum_measure`: pigeonhole principle in a measure space. ## Tags pigeonhole principle -/ universes u v w variables {α : Type u} {β : Type v} {M : Type w} [linear_ordered_cancel_add_comm_monoid M] [decidable_eq β] open_locale big_operators namespace finset variables {s : finset α} {t : finset β} {f : α → β} {w : α → M} {b : M} {n : ℕ} /-! ### The pigeonhole principles on `finset`s, pigeons counted by weight In this section we prove the following version of the pigeonhole principle: if the total weight of a finite set of pigeons is greater than `n •ℕ b`, and they are sorted into `n` pigeonholes, then for some pigeonhole, the total weight of the pigeons in this pigeonhole is greateer than `b`, and a few variations of this theorem. The principle is formalized in the following way, see `finset.exists_lt_sum_fiber_of_maps_to_of_nsmul_lt_sum`: if `f : α → β` is a function which maps all elements of `s : finset α` to `t : finset β` and `card t •ℕ b < ∑ x in s, w x`, where `w : α → M` is a weight function taking values in a `linear_ordered_cancel_add_comm_monoid`, then for some `y ∈ t`, the sum of the weights of all `x ∈ s` such that `f x = y` is greater than `b`. There are a few bits we can change in this theorem: * reverse all inequalities, with obvious adjustments to the name; * replace the assumption `∀ a ∈ s, f a ∈ t` with `∀ y ∉ t, (∑ x in s.filter (λ x, f x = y), w x) ≤ 0`, and replace `of_maps_to` with `of_sum_fiber_nonpos` in the name; * use non-strict inequalities assuming `t` is nonempty. We can do all these variations independently, so we have eight versions of the theorem. -/ /-! #### Strict inequality versions -/ /-- The pigeonhole principle for finitely many pigeons counted by weight, strict inequality version: if the total weight of a finite set of pigeons is greater than `n •ℕ b`, and they are sorted into `n` pigeonholes, then for some pigeonhole, the total weight of the pigeons in this pigeonhole is greater than `b`. -/ lemma exists_lt_sum_fiber_of_maps_to_of_nsmul_lt_sum (hf : ∀ a ∈ s, f a ∈ t) (hb : t.card •ℕ b < ∑ x in s, w x) : ∃ y ∈ t, b < ∑ x in s.filter (λ x, f x = y), w x := exists_lt_of_sum_lt $ by simpa only [sum_fiberwise_of_maps_to hf, sum_const] /-- The pigeonhole principle for finitely many pigeons counted by weight, strict inequality version: if the total weight of a finite set of pigeons is less than `n •ℕ b`, and they are sorted into `n` pigeonholes, then for some pigeonhole, the total weight of the pigeons in this pigeonhole is less than `b`. -/ lemma exists_sum_fiber_lt_of_maps_to_of_sum_lt_nsmul (hf : ∀ a ∈ s, f a ∈ t) (hb : (∑ x in s, w x) < t.card •ℕ b) : ∃ y ∈ t, (∑ x in s.filter (λ x, f x = y), w x) < b := @exists_lt_sum_fiber_of_maps_to_of_nsmul_lt_sum α β (order_dual M) _ _ _ _ _ _ _ hf hb /-- The pigeonhole principle for finitely many pigeons counted by weight, strict inequality version: if the total weight of a finite set of pigeons is greater than `n •ℕ b`, they are sorted into some pigeonholes, and for all but `n` pigeonholes the total weight of the pigeons there is nonpositive, then for at least one of these `n` pigeonholes, the total weight of the pigeons in this pigeonhole is greater than `b`. -/ lemma exists_lt_sum_fiber_of_sum_fiber_nonpos_of_nsmul_lt_sum (ht : ∀ y ∉ t, (∑ x in s.filter (λ x, f x = y), w x) ≤ 0) (hb : t.card •ℕ b < ∑ x in s, w x) : ∃ y ∈ t, b < ∑ x in s.filter (λ x, f x = y), w x := exists_lt_of_sum_lt $ calc (∑ y in t, b) < ∑ x in s, w x : by simpa ... ≤ ∑ y in t, ∑ x in s.filter (λ x, f x = y), w x : sum_le_sum_fiberwise_of_sum_fiber_nonpos ht /-- The pigeonhole principle for finitely many pigeons counted by weight, strict inequality version: if the total weight of a finite set of pigeons is less than `n •ℕ b`, they are sorted into some pigeonholes, and for all but `n` pigeonholes the total weight of the pigeons there is nonnegative, then for at least one of these `n` pigeonholes, the total weight of the pigeons in this pigeonhole is less than `b`. -/ lemma exists_sum_fiber_lt_of_sum_fiber_nonneg_of_sum_lt_nsmul (ht : ∀ y ∉ t, (0:M) ≤ ∑ x in s.filter (λ x, f x = y), w x) (hb : (∑ x in s, w x) < t.card •ℕ b) : ∃ y ∈ t, (∑ x in s.filter (λ x, f x = y), w x) < b := @exists_lt_sum_fiber_of_sum_fiber_nonpos_of_nsmul_lt_sum α β (order_dual M) _ _ _ _ _ _ _ ht hb /-! #### Non-strict inequality versions -/ /-- The pigeonhole principle for finitely many pigeons counted by weight, non-strict inequality version: if the total weight of a finite set of pigeons is greater than or equal to `n •ℕ b`, and they are sorted into `n > 0` pigeonholes, then for some pigeonhole, the total weight of the pigeons in this pigeonhole is greater than or equal to `b`. -/ lemma exists_le_sum_fiber_of_maps_to_of_nsmul_le_sum (hf : ∀ a ∈ s, f a ∈ t) (ht : t.nonempty) (hb : t.card •ℕ b ≤ ∑ x in s, w x) : ∃ y ∈ t, b ≤ ∑ x in s.filter (λ x, f x = y), w x := exists_le_of_sum_le ht $ by simpa only [sum_fiberwise_of_maps_to hf, sum_const] /-- The pigeonhole principle for finitely many pigeons counted by weight, non-strict inequality version: if the total weight of a finite set of pigeons is less than or equal to `n •ℕ b`, and they are sorted into `n > 0` pigeonholes, then for some pigeonhole, the total weight of the pigeons in this pigeonhole is less than or equal to `b`. -/ lemma exists_sum_fiber_le_of_maps_to_of_sum_le_nsmul (hf : ∀ a ∈ s, f a ∈ t) (ht : t.nonempty) (hb : (∑ x in s, w x) ≤ t.card •ℕ b) : ∃ y ∈ t, (∑ x in s.filter (λ x, f x = y), w x) ≤ b := @exists_le_sum_fiber_of_maps_to_of_nsmul_le_sum α β (order_dual M) _ _ _ _ _ _ _ hf ht hb /-- The pigeonhole principle for finitely many pigeons counted by weight, non-strict inequality version: if the total weight of a finite set of pigeons is greater than or equal to `n •ℕ b`, they are sorted into some pigeonholes, and for all but `n > 0` pigeonholes the total weight of the pigeons there is nonpositive, then for at least one of these `n` pigeonholes, the total weight of the pigeons in this pigeonhole is greater than or equal to `b`. -/ lemma exists_le_sum_fiber_of_sum_fiber_nonpos_of_nsmul_le_sum (hf : ∀ y ∉ t, (∑ x in s.filter (λ x, f x = y), w x) ≤ 0) (ht : t.nonempty) (hb : t.card •ℕ b ≤ ∑ x in s, w x) : ∃ y ∈ t, b ≤ ∑ x in s.filter (λ x, f x = y), w x := exists_le_of_sum_le ht $ calc (∑ y in t, b) ≤ ∑ x in s, w x : by simpa ... ≤ ∑ y in t, ∑ x in s.filter (λ x, f x = y), w x : sum_le_sum_fiberwise_of_sum_fiber_nonpos hf /-- The pigeonhole principle for finitely many pigeons counted by weight, non-strict inequality version: if the total weight of a finite set of pigeons is less than or equal to `n •ℕ b`, they are sorted into some pigeonholes, and for all but `n > 0` pigeonholes the total weight of the pigeons there is nonnegative, then for at least one of these `n` pigeonholes, the total weight of the pigeons in this pigeonhole is less than or equal to `b`. -/ lemma exists_sum_fiber_le_of_sum_fiber_nonneg_of_sum_le_nsmul (hf : ∀ y ∉ t, (0:M) ≤ ∑ x in s.filter (λ x, f x = y), w x) (ht : t.nonempty) (hb : (∑ x in s, w x) ≤ t.card •ℕ b) : ∃ y ∈ t, (∑ x in s.filter (λ x, f x = y), w x) ≤ b := @exists_le_sum_fiber_of_sum_fiber_nonpos_of_nsmul_le_sum α β (order_dual M) _ _ _ _ _ _ _ hf ht hb /-! ### The pigeonhole principles on `finset`s, pigeons counted by heads In this section we formalize a few versions of the following pigeonhole principle: there is a pigeonhole with at least as many pigeons as the ceiling of the average number of pigeons across all pigeonholes. First, we can use strict or non-strict inequalities. While the versions with non-strict inequalities are weaker than those with strict inequalities, sometimes it might be more convenient to apply the weaker version. Second, we can either state that there exists a pigeonhole with at least `n` pigeons, or state that there exists a pigeonhole with at most `n` pigeons. In the latter case we do not need the assumption `∀ a ∈ s, f a ∈ t`. So, we prove four theorems: `finset.exists_lt_card_fiber_of_maps_to_of_mul_lt_card`, `finset.exists_le_card_fiber_of_maps_to_of_mul_le_card`, `finset.exists_card_fiber_lt_of_card_lt_mul`, and `finset.exists_card_fiber_le_of_card_le_mul`. -/ /-- The pigeonhole principle for finitely many pigeons counted by heads: there is a pigeonhole with at least as many pigeons as the ceiling of the average number of pigeons across all pigeonholes. ("The maximum is at least the mean" specialized to integers.) More formally, given a function between finite sets `s` and `t` and a natural number `n` such that `card t * n < card s`, there exists `y ∈ t` such that its preimage in `s` has more than `n` elements. -/ lemma exists_lt_card_fiber_of_mul_lt_card_of_maps_to (hf : ∀ a ∈ s, f a ∈ t) (hn : t.card * n < s.card) : ∃ y ∈ t, n < (s.filter (λ x, f x = y)).card := begin simp only [card_eq_sum_ones], apply exists_lt_sum_fiber_of_maps_to_of_nsmul_lt_sum hf, simpa end /-- The pigeonhole principle for finitely many pigeons counted by heads: there is a pigeonhole with at most as many pigeons as the floor of the average number of pigeons across all pigeonholes. ("The minimum is at most the mean" specialized to integers.) More formally, given a function `f`, a finite sets `s` in its domain, a finite set `t` in its codomain, and a natural number `n` such that `card s < card t * n`, there exists `y ∈ t` such that its preimage in `s` has less than `n` elements. -/ lemma exists_card_fiber_lt_of_card_lt_mul (hn : s.card < t.card * n) : ∃ y ∈ t, (s.filter (λ x, f x = y)).card < n:= begin simp only [card_eq_sum_ones], apply exists_sum_fiber_lt_of_sum_fiber_nonneg_of_sum_lt_nsmul (λ _ _, nat.zero_le _), simpa end /-- The pigeonhole principle for finitely many pigeons counted by heads: given a function between finite sets `s` and `t` and a natural number `n` such that `card t * n ≤ card s`, there exists `y ∈ t` such that its preimage in `s` has at least `n` elements. See also `finset.exists_lt_card_fiber_of_mul_lt_card_of_maps_to` for a stronger statement. -/ lemma exists_le_card_fiber_of_mul_le_card_of_maps_to (hf : ∀ a ∈ s, f a ∈ t) (ht : t.nonempty) (hn : t.card * n ≤ s.card) : ∃ y ∈ t, n ≤ (s.filter (λ x, f x = y)).card := begin simp only [card_eq_sum_ones], apply exists_le_sum_fiber_of_maps_to_of_nsmul_le_sum hf ht, simpa end /-- The pigeonhole principle for finitely many pigeons counted by heads: given a function `f`, a finite sets `s` in its domain, a finite set `t` in its codomain, and a natural number `n` such that `card s ≤ card t * n`, there exists `y ∈ t` such that its preimage in `s` has no more than `n` elements. See also `finset.exists_card_fiber_lt_of_card_lt_mul` for a stronger statement. -/ lemma exists_card_fiber_le_of_card_le_mul (ht : t.nonempty) (hn : s.card ≤ t.card * n) : ∃ y ∈ t, (s.filter (λ x, f x = y)).card ≤ n:= begin simp only [card_eq_sum_ones], apply exists_sum_fiber_le_of_sum_fiber_nonneg_of_sum_le_nsmul (λ _ _, nat.zero_le _) ht, simpa end end finset namespace fintype open finset variables [fintype α] [fintype β] (f : α → β) {w : α → M} {b : M} {n : ℕ} /-! ### The pigeonhole principles on `fintypes`s, pigeons counted by weight In this section we specialize theorems from the previous section to the special case of functions between `fintype`s and `s = univ`, `t = univ`. In this case the assumption `∀ x ∈ s, f x ∈ t` always holds, so we have four theorems instead of eight. -/ /-- The pigeonhole principle for finitely many pigeons of different weights, strict inequality version: there is a pigeonhole with the total weight of pigeons in it greater than `b` provided that the total number of pigeonholes times `b` is less than the total weight of all pigeons. -/ lemma exists_lt_sum_fiber_of_nsmul_lt_sum (hb : card β •ℕ b < ∑ x, w x) : ∃ y, b < ∑ x in univ.filter (λ x, f x = y), w x := let ⟨y, _, hy⟩ := exists_lt_sum_fiber_of_maps_to_of_nsmul_lt_sum (λ _ _, mem_univ _) hb in ⟨y, hy⟩ /-- The pigeonhole principle for finitely many pigeons of different weights, non-strict inequality version: there is a pigeonhole with the total weight of pigeons in it greater than or equal to `b` provided that the total number of pigeonholes times `b` is less than or equal to the total weight of all pigeons. -/ lemma exists_le_sum_fiber_of_nsmul_le_sum [nonempty β] (hb : card β •ℕ b ≤ ∑ x, w x) : ∃ y, b ≤ ∑ x in univ.filter (λ x, f x = y), w x := let ⟨y, _, hy⟩ := exists_le_sum_fiber_of_maps_to_of_nsmul_le_sum (λ _ _, mem_univ _) univ_nonempty hb in ⟨y, hy⟩ /-- The pigeonhole principle for finitely many pigeons of different weights, strict inequality version: there is a pigeonhole with the total weight of pigeons in it less than `b` provided that the total number of pigeonholes times `b` is greater than the total weight of all pigeons. -/ lemma exists_sum_fiber_lt_of_sum_lt_nsmul (hb : (∑ x, w x) < card β •ℕ b) : ∃ y, (∑ x in univ.filter (λ x, f x = y), w x) < b := @exists_lt_sum_fiber_of_nsmul_lt_sum α β (order_dual M) _ _ _ _ _ w b hb /-- The pigeonhole principle for finitely many pigeons of different weights, non-strict inequality version: there is a pigeonhole with the total weight of pigeons in it less than or equal to `b` provided that the total number of pigeonholes times `b` is greater than or equal to the total weight of all pigeons. -/ lemma exists_sum_fiber_le_of_sum_le_nsmul [nonempty β] (hb : (∑ x, w x) ≤ card β •ℕ b) : ∃ y, (∑ x in univ.filter (λ x, f x = y), w x) ≤ b := @exists_le_sum_fiber_of_nsmul_le_sum α β (order_dual M) _ _ _ _ _ w b _ hb /-- The strong pigeonhole principle for finitely many pigeons and pigeonholes. There is a pigeonhole with at least as many pigeons as the ceiling of the average number of pigeons across all pigeonholes. ("The maximum is at least the mean" specialized to integers.) More formally, given a function `f` between finite types `α` and `β` and a number `n` such that `card β * n < card α`, there exists an element `y : β` such that its preimage has more than `n` elements. -/ lemma exists_lt_card_fiber_of_mul_lt_card (hn : card β * n < card α) : ∃ y : β, n < (univ.filter (λ x, f x = y)).card := let ⟨y, _, h⟩ := exists_lt_card_fiber_of_mul_lt_card_of_maps_to (λ _ _, mem_univ _) hn in ⟨y, h⟩ /-- The strong pigeonhole principle for finitely many pigeons and pigeonholes. There is a pigeonhole with at most as many pigeons as the floor of the average number of pigeons across all pigeonholes. ("The minimum is at most the mean" specialized to integers.) More formally, given a function `f` between finite types `α` and `β` and a number `n` such that `card α < card β * n`, there exists an element `y : β` such that its preimage has less than `n` elements. -/ lemma exists_card_fiber_lt_of_card_lt_mul (hn : card α < card β * n) : ∃ y : β, (univ.filter (λ x, f x = y)).card < n := let ⟨y, _, h⟩ := exists_card_fiber_lt_of_card_lt_mul hn in ⟨y, h⟩ /-- The strong pigeonhole principle for finitely many pigeons and pigeonholes. Given a function `f` between finite types `α` and `β` and a number `n` such that `card β * n ≤ card α`, there exists an element `y : β` such that its preimage has at least `n` elements. See also `fintype.exists_lt_card_fiber_of_mul_lt_card` for a stronger statement. -/ lemma exists_le_card_fiber_of_mul_le_card [nonempty β] (hn : card β * n ≤ card α) : ∃ y : β, n ≤ (univ.filter (λ x, f x = y)).card := let ⟨y, _, h⟩ := exists_le_card_fiber_of_mul_le_card_of_maps_to (λ _ _, mem_univ _) univ_nonempty hn in ⟨y, h⟩ /-- The strong pigeonhole principle for finitely many pigeons and pigeonholes. Given a function `f` between finite types `α` and `β` and a number `n` such that `card α ≤ card β * n`, there exists an element `y : β` such that its preimage has at most `n` elements. See also `fintype.exists_card_fiber_lt_of_card_lt_mul` for a stronger statement. -/ lemma exists_card_fiber_le_of_card_le_mul [nonempty β] (hn : card α ≤ card β * n) : ∃ y : β, (univ.filter (λ x, f x = y)).card ≤ n := let ⟨y, _, h⟩ := exists_card_fiber_le_of_card_le_mul univ_nonempty hn in ⟨y, h⟩ end fintype namespace nat open set /-- If `s` is an infinite set of natural numbers and `k > 0`, then `s` contains two elements `m < n` that are equal mod `k`. -/ theorem exists_lt_modeq_of_infinite {s : set ℕ} (hs : s.infinite) {k : ℕ} (hk : 0 < k) : ∃ (m ∈ s) (n ∈ s), m < n ∧ m ≡ n [MOD k] := hs.exists_lt_map_eq_of_maps_to (λ n _, show n % k ∈ Iio k, from nat.mod_lt n hk) $ finite_lt_nat k end nat
608f03849f5e2517c42fcd240c766fa86e3592b8
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/algebra/quadratic_discriminant.lean
4d6ca65afec5dd4a72a26c41eb022fb120122384
[ "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
6,848
lean
/- Copyright (c) 2019 Zhouhang Zhou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Zhouhang Zhou -/ import tactic.linarith /-! # Quadratic discriminants and roots of a quadratic This file defines the discriminant of a quadratic and gives the solution to a quadratic equation. ## Main definition The discriminant of a quadratic `a*x*x + b*x + c` is `b*b - 4*a*c`. ## Main statements • Roots of a quadratic can be written as `(-b + s) / (2 * a)` or `(-b - s) / (2 * a)`, where `s` is the square root of the discriminant. • If the discriminant has no square root, then the corresponding quadratic has no root. • If a quadratic is always non-negative, then its discriminant is non-positive. ## Tags polynomial, quadratic, discriminant, root -/ variables {α : Type*} section lemmas variables [linear_ordered_field α] {a b c : α} lemma exists_le_mul_self : ∀ a : α, ∃ x : α, a ≤ x * x := begin classical, -- TODO: otherwise linarith performance sucks assume a, cases le_total 1 a with ha ha, { use a, exact le_mul_of_ge_one_left (by linarith) ha }, { use 1, linarith } end lemma exists_lt_mul_self : ∀ a : α, ∃ x : α, a < x * x := begin classical, -- todo: otherwise linarith performance sucks assume a, rcases (exists_le_mul_self a) with ⟨x, hx⟩, cases le_total 0 x with hx' hx', { use (x + 1), have : (x+1)*(x+1) = x*x + 2*x + 1, {ring}, exact lt_of_le_of_lt hx (by rw this; linarith) }, { use (x - 1), have : (x-1)*(x-1) = x*x - 2*x + 1, {ring}, exact lt_of_le_of_lt hx (by rw this; linarith) } end end lemmas variables [linear_ordered_field α] {a b c x : α} /-- Discriminant of a quadratic -/ def discrim [ring α] (a b c : α) : α := b^2 - 4 * a * c /-- A quadratic has roots if and only if its discriminant equals some square. -/ lemma quadratic_eq_zero_iff_discrim_eq_square (ha : a ≠ 0) : ∀ x : α, a * x * x + b * x + c = 0 ↔ discrim a b c = (2 * a * x + b)^2 := by classical; exact -- TODO: otherwise linarith performance sucks assume x, iff.intro (assume h, calc discrim a b c = 4*a*(a*x*x + b*x + c) + b*b - 4*a*c : by rw [h, discrim]; ring ... = (2*a*x + b)^2 : by ring) (assume h, have ha : 2*2*a ≠ 0 := mul_ne_zero (mul_ne_zero two_ne_zero two_ne_zero) ha, mul_left_cancel' ha $ calc 2 * 2 * a * (a * x * x + b * x + c) = (2*a*x + b)^2 - (b^2 - 4*a*c) : by ring ... = 0 : by { rw [← h, discrim], ring } ... = 2*2*a*0 : by ring) /-- Roots of a quadratic -/ lemma quadratic_eq_zero_iff (ha : a ≠ 0) {s : α} (h : discrim a b c = s * s) : ∀ x : α, a * x * x + b * x + c = 0 ↔ x = (-b + s) / (2 * a) ∨ x = (-b - s) / (2 * a) := assume x, begin classical, -- TODO: otherwise linarith performance sucks rw [quadratic_eq_zero_iff_discrim_eq_square ha, h, pow_two, mul_self_eq_mul_self_iff], have ne : 2 * a ≠ 0 := mul_ne_zero two_ne_zero ha, have : x = 2 * a * x / (2 * a) := (mul_div_cancel_left x ne).symm, have h₁ : 2 * a * ((-b + s) / (2 * a)) = -b + s := mul_div_cancel' _ ne, have h₂ : 2 * a * ((-b - s) / (2 * a)) = -b - s := mul_div_cancel' _ ne, split, { intro h', rcases h', { left, rw h', simpa [add_comm] }, { right, rw h', simpa [add_comm, sub_eq_add_neg] } }, { intro h', rcases h', { left, rw [h', h₁], ring }, { right, rw [h', h₂], ring } } end /-- A quadratic has roots if its discriminant has square roots -/ lemma exist_quadratic_eq_zero (ha : a ≠ 0) (h : ∃ s, discrim a b c = s * s) : ∃ x, a * x * x + b * x + c = 0 := begin rcases h with ⟨s, hs⟩, use (-b + s) / (2 * a), rw quadratic_eq_zero_iff ha hs, simp end /-- Root of a quadratic when its discriminant equals zero -/ lemma quadratic_eq_zero_iff_of_discrim_eq_zero (ha : a ≠ 0) (h : discrim a b c = 0) : ∀ x : α, a * x * x + b * x + c = 0 ↔ x = -b / (2 * a) := assume x, begin classical, -- TODO: otherwise linarith performance sucks have : discrim a b c = 0 * 0 := eq.trans h (by ring), rw quadratic_eq_zero_iff ha this, simp end /-- A quadratic has no root if its discriminant has no square root. -/ lemma quadratic_ne_zero_of_discrim_ne_square (ha : a ≠ 0) (h : ∀ s : α, discrim a b c ≠ s * s) : ∀ (x : α), a * x * x + b * x + c ≠ 0 := begin assume x h', rw [quadratic_eq_zero_iff_discrim_eq_square ha, pow_two] at h', have := h _, contradiction end /-- If a polynomial of degree 2 is always nonnegative, then its discriminant is nonpositive -/ lemma discriminant_le_zero {a b c : α} (h : ∀ x : α, 0 ≤ a*x*x + b*x + c) : discrim a b c ≤ 0 := by classical; exact -- TODO: otherwise linarith performance sucks have hc : 0 ≤ c, by { have := h 0, linarith }, begin rw [discrim, pow_two], cases lt_trichotomy a 0 with ha ha, -- if a < 0 cases classical.em (b = 0) with hb hb, { rw hb at *, rcases exists_lt_mul_self (-c/a) with ⟨x, hx⟩, have := mul_lt_mul_of_neg_left hx ha, rw [mul_div_cancel' _ (ne_of_lt ha), ← mul_assoc] at this, have h₂ := h x, linarith }, { cases classical.em (c = 0) with hc' hc', { rw hc' at *, have : -(a*-b*-b + b*-b + 0) = (1-a)*(b*b), {ring}, have h := h (-b), rw [← neg_nonpos, this] at h, have : b * b ≤ 0 := nonpos_of_mul_nonpos_left h (by linarith), linarith }, { have h := h (-c/b), have : a*(-c/b)*(-c/b) + b*(-c/b) + c = a*((c/b)*(c/b)), { rw mul_div_cancel' _ hb, ring }, rw this at h, have : 0 ≤ a := nonneg_of_mul_nonneg_right h (mul_self_pos $ div_ne_zero hc' hb), linarith [ha] } }, cases ha with ha ha, -- if a = 0 cases classical.em (b = 0) with hb hb, { rw [ha, hb], linarith }, { have := h ((-c-1)/b), rw [ha, mul_div_cancel' _ hb] at this, linarith }, -- if a > 0 have := calc 4*a* (a*(-(b/a)*(1/2))*(-(b/a)*(1/2)) + b*(-(b/a)*(1/2)) + c) = (a*(b/a)) * (a*(b/a)) - 2*(a*(b/a))*b + 4*a*c : by ring ... = -(b*b - 4*a*c) : by { simp only [mul_div_cancel' b (ne_of_gt ha)], ring }, have ha' : 0 ≤ 4*a, {linarith}, have h := (mul_nonneg ha' (h (-(b/a) * (1/2)))), rw this at h, rwa ← neg_nonneg end /-- If a polynomial of degree 2 is always positive, then its discriminant is negative, at least when the coefficient of the quadratic term is nonzero. -/ lemma discriminant_lt_zero {a b c : α} (ha : a ≠ 0) (h : ∀ x : α, 0 < a*x*x + b*x + c) : discrim a b c < 0 := begin classical, -- TODO: otherwise linarith performance sucks have : ∀ x : α, 0 ≤ a*x*x + b*x + c := assume x, le_of_lt (h x), refine lt_of_le_of_ne (discriminant_le_zero this) _, assume h', have := h (-b / (2 * a)), have : a * (-b / (2 * a)) * (-b / (2 * a)) + b * (-b / (2 * a)) + c = 0, { rw [quadratic_eq_zero_iff_of_discrim_eq_zero ha h' (-b / (2 * a))] }, linarith end
d97974d73aa15adcbb0725f855e3d996c9af3491
6ae186a0c6ab366b39397ec9250541c9d5aeb023
/src/category_theory/functor/isomorphism.lean
8fa2af6b07d6c15699f7d8e8effe308ddcab20a9
[]
no_license
ThanhPhamPhuong/lean-category-theory
0d5c4fe1137866b4fe29ec2753d99aa0d0667881
968a29fe7c0b20e10d8a27e120aca8ddc184e1ea
refs/heads/master
1,587,206,682,489
1,544,045,056,000
1,544,045,056,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
603
lean
-- Copyright (c) 2018 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Scott Morrison import category_theory.functor import category_theory.isomorphism open category_theory namespace category_theory universes u₁ v₁ u₂ v₂ variables {C : Type u₁} [category.{u₁ v₁} C] {D : Type u₂} [category.{u₂ v₂} D] class reflects_isos (F : C ⥤ D) := (reflects : Π {X Y : C} (f : X ⟶ Y) (w : is_iso (F.map f)), is_iso f) -- TODO -- instance (F : C ⥤ D) [faithful F] : reflects_isos F := sorry end category_theory
33b23e84c64489d776933d6825e83dddfe99fc23
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/order/max.lean
01aa6e0e063d57d4d98beaa438791b9a83eb921c
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
12,628
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Yury Kudryashov, Yaël Dillies -/ import order.synonym /-! # Minimal/maximal and bottom/top elements > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines predicates for elements to be minimal/maximal or bottom/top and typeclasses saying that there are no such elements. ## Predicates * `is_bot`: An element is *bottom* if all elements are greater than it. * `is_top`: An element is *top* if all elements are less than it. * `is_min`: An element is *minimal* if no element is strictly less than it. * `is_max`: An element is *maximal* if no element is strictly greater than it. See also `is_bot_iff_is_min` and `is_top_iff_is_max` for the equivalences in a (co)directed order. ## Typeclasses * `no_bot_order`: An order without bottom elements. * `no_top_order`: An order without top elements. * `no_min_order`: An order without minimal elements. * `no_max_order`: An order without maximal elements. -/ open order_dual variables {ι α β : Type*} {π : ι → Type*} /-- Order without bottom elements. -/ class no_bot_order (α : Type*) [has_le α] : Prop := (exists_not_ge (a : α) : ∃ b, ¬ a ≤ b) /-- Order without top elements. -/ class no_top_order (α : Type*) [has_le α] : Prop := (exists_not_le (a : α) : ∃ b, ¬ b ≤ a) /-- Order without minimal elements. Sometimes called coinitial or dense. -/ class no_min_order (α : Type*) [has_lt α] : Prop := (exists_lt (a : α) : ∃ b, b < a) /-- Order without maximal elements. Sometimes called cofinal. -/ class no_max_order (α : Type*) [has_lt α] : Prop := (exists_gt (a : α) : ∃ b, a < b) export no_bot_order (exists_not_ge) export no_top_order (exists_not_le) export no_min_order (exists_lt) export no_max_order (exists_gt) instance nonempty_lt [has_lt α] [no_min_order α] (a : α) : nonempty {x // x < a} := nonempty_subtype.2 (exists_lt a) instance nonempty_gt [has_lt α] [no_max_order α] (a : α) : nonempty {x // a < x} := nonempty_subtype.2 (exists_gt a) instance order_dual.no_bot_order (α : Type*) [has_le α] [no_top_order α] : no_bot_order αᵒᵈ := ⟨λ a, @exists_not_le α _ _ a⟩ instance order_dual.no_top_order (α : Type*) [has_le α] [no_bot_order α] : no_top_order αᵒᵈ := ⟨λ a, @exists_not_ge α _ _ a⟩ instance order_dual.no_min_order (α : Type*) [has_lt α] [no_max_order α] : no_min_order αᵒᵈ := ⟨λ a, @exists_gt α _ _ a⟩ instance order_dual.no_max_order (α : Type*) [has_lt α] [no_min_order α] : no_max_order αᵒᵈ := ⟨λ a, @exists_lt α _ _ a⟩ instance no_max_order_of_left [preorder α] [preorder β] [no_max_order α] : no_max_order (α × β) := ⟨λ ⟨a, b⟩, by { obtain ⟨c, h⟩ := exists_gt a, exact ⟨(c, b), prod.mk_lt_mk_iff_left.2 h⟩ }⟩ instance no_max_order_of_right [preorder α] [preorder β] [no_max_order β] : no_max_order (α × β) := ⟨λ ⟨a, b⟩, by { obtain ⟨c, h⟩ := exists_gt b, exact ⟨(a, c), prod.mk_lt_mk_iff_right.2 h⟩ }⟩ instance no_min_order_of_left [preorder α] [preorder β] [no_min_order α] : no_min_order (α × β) := ⟨λ ⟨a, b⟩, by { obtain ⟨c, h⟩ := exists_lt a, exact ⟨(c, b), prod.mk_lt_mk_iff_left.2 h⟩ }⟩ instance no_min_order_of_right [preorder α] [preorder β] [no_min_order β] : no_min_order (α × β) := ⟨λ ⟨a, b⟩, by { obtain ⟨c, h⟩ := exists_lt b, exact ⟨(a, c), prod.mk_lt_mk_iff_right.2 h⟩ }⟩ instance [nonempty ι] [Π i, preorder (π i)] [Π i, no_max_order (π i)] : no_max_order (Π i, π i) := ⟨λ a, begin classical, obtain ⟨b, hb⟩ := exists_gt (a $ classical.arbitrary _), exact ⟨_, lt_update_self_iff.2 hb⟩, end⟩ instance [nonempty ι] [Π i, preorder (π i)] [Π i, no_min_order (π i)] : no_min_order (Π i, π i) := ⟨λ a, begin classical, obtain ⟨b, hb⟩ := exists_lt (a $ classical.arbitrary _), exact ⟨_, update_lt_self_iff.2 hb⟩, end⟩ @[priority 100] -- See note [lower instance priority] instance no_min_order.to_no_bot_order (α : Type*) [preorder α] [no_min_order α] : no_bot_order α := ⟨λ a, (exists_lt a).imp $ λ _, not_le_of_lt⟩ @[priority 100] -- See note [lower instance priority] instance no_max_order.to_no_top_order (α : Type*) [preorder α] [no_max_order α] : no_top_order α := ⟨λ a, (exists_gt a).imp $ λ _, not_le_of_lt⟩ lemma no_bot_order.to_no_min_order (α : Type*) [linear_order α] [no_bot_order α] : no_min_order α := { exists_lt := by { convert λ a : α, exists_not_ge a, simp_rw not_le, } } lemma no_top_order.to_no_max_order (α : Type*) [linear_order α] [no_top_order α] : no_max_order α := { exists_gt := by { convert λ a : α, exists_not_le a, simp_rw not_le, } } lemma no_bot_order_iff_no_min_order (α : Type*) [linear_order α] : no_bot_order α ↔ no_min_order α := ⟨λ h, by { haveI := h, exact no_bot_order.to_no_min_order α }, λ h, by { haveI := h, exact no_min_order.to_no_bot_order α }⟩ lemma no_top_order_iff_no_max_order (α : Type*) [linear_order α] : no_top_order α ↔ no_max_order α := ⟨λ h, by { haveI := h, exact no_top_order.to_no_max_order α }, λ h, by { haveI := h, exact no_max_order.to_no_top_order α }⟩ theorem no_min_order.not_acc [has_lt α] [no_min_order α] (a : α) : ¬ acc (<) a := λ h, acc.rec_on h $ λ x _, (exists_lt x).rec_on theorem no_max_order.not_acc [has_lt α] [no_max_order α] (a : α) : ¬ acc (>) a := λ h, acc.rec_on h $ λ x _, (exists_gt x).rec_on section has_le variables [has_le α] {a b : α} /-- `a : α` is a bottom element of `α` if it is less than or equal to any other element of `α`. This predicate is roughly an unbundled version of `order_bot`, except that a preorder may have several bottom elements. When `α` is linear, this is useful to make a case disjunction on `no_min_order α` within a proof. -/ def is_bot (a : α) : Prop := ∀ b, a ≤ b /-- `a : α` is a top element of `α` if it is greater than or equal to any other element of `α`. This predicate is roughly an unbundled version of `order_bot`, except that a preorder may have several top elements. When `α` is linear, this is useful to make a case disjunction on `no_max_order α` within a proof. -/ def is_top (a : α) : Prop := ∀ b, b ≤ a /-- `a` is a minimal element of `α` if no element is strictly less than it. We spell it without `<` to avoid having to convert between `≤` and `<`. Instead, `is_min_iff_forall_not_lt` does the conversion. -/ def is_min (a : α) : Prop := ∀ ⦃b⦄, b ≤ a → a ≤ b /-- `a` is a maximal element of `α` if no element is strictly greater than it. We spell it without `<` to avoid having to convert between `≤` and `<`. Instead, `is_max_iff_forall_not_lt` does the conversion. -/ def is_max (a : α) : Prop := ∀ ⦃b⦄, a ≤ b → b ≤ a @[simp] lemma not_is_bot [no_bot_order α] (a : α) : ¬is_bot a := λ h, let ⟨b, hb⟩ := exists_not_ge a in hb $ h _ @[simp] lemma not_is_top [no_top_order α] (a : α) : ¬is_top a := λ h, let ⟨b, hb⟩ := exists_not_le a in hb $ h _ protected lemma is_bot.is_min (h : is_bot a) : is_min a := λ b _, h b protected lemma is_top.is_max (h : is_top a) : is_max a := λ b _, h b @[simp] lemma is_bot_to_dual_iff : is_bot (to_dual a) ↔ is_top a := iff.rfl @[simp] lemma is_top_to_dual_iff : is_top (to_dual a) ↔ is_bot a := iff.rfl @[simp] lemma is_min_to_dual_iff : is_min (to_dual a) ↔ is_max a := iff.rfl @[simp] lemma is_max_to_dual_iff : is_max (to_dual a) ↔ is_min a := iff.rfl @[simp] lemma is_bot_of_dual_iff {a : αᵒᵈ} : is_bot (of_dual a) ↔ is_top a := iff.rfl @[simp] lemma is_top_of_dual_iff {a : αᵒᵈ} : is_top (of_dual a) ↔ is_bot a := iff.rfl @[simp] lemma is_min_of_dual_iff {a : αᵒᵈ} : is_min (of_dual a) ↔ is_max a := iff.rfl @[simp] lemma is_max_of_dual_iff {a : αᵒᵈ} : is_max (of_dual a) ↔ is_min a := iff.rfl alias is_bot_to_dual_iff ↔ _ is_top.to_dual alias is_top_to_dual_iff ↔ _ is_bot.to_dual alias is_min_to_dual_iff ↔ _ is_max.to_dual alias is_max_to_dual_iff ↔ _ is_min.to_dual alias is_bot_of_dual_iff ↔ _ is_top.of_dual alias is_top_of_dual_iff ↔ _ is_bot.of_dual alias is_min_of_dual_iff ↔ _ is_max.of_dual alias is_max_of_dual_iff ↔ _ is_min.of_dual end has_le section preorder variables [preorder α] {a b : α} lemma is_bot.mono (ha : is_bot a) (h : b ≤ a) : is_bot b := λ c, h.trans $ ha _ lemma is_top.mono (ha : is_top a) (h : a ≤ b) : is_top b := λ c, (ha _).trans h lemma is_min.mono (ha : is_min a) (h : b ≤ a) : is_min b := λ c hc, h.trans $ ha $ hc.trans h lemma is_max.mono (ha : is_max a) (h : a ≤ b) : is_max b := λ c hc, (ha $ h.trans hc).trans h lemma is_min.not_lt (h : is_min a) : ¬ b < a := λ hb, hb.not_le $ h hb.le lemma is_max.not_lt (h : is_max a) : ¬ a < b := λ hb, hb.not_le $ h hb.le @[simp] lemma not_is_min_of_lt (h : b < a) : ¬ is_min a := λ ha, ha.not_lt h @[simp] lemma not_is_max_of_lt (h : a < b) : ¬ is_max a := λ ha, ha.not_lt h alias not_is_min_of_lt ← has_lt.lt.not_is_min alias not_is_max_of_lt ← has_lt.lt.not_is_max lemma is_min_iff_forall_not_lt : is_min a ↔ ∀ b, ¬ b < a := ⟨λ h _, h.not_lt, λ h b hba, of_not_not $ λ hab, h _ $ hba.lt_of_not_le hab⟩ lemma is_max_iff_forall_not_lt : is_max a ↔ ∀ b, ¬ a < b := ⟨λ h _, h.not_lt, λ h b hba, of_not_not $ λ hab, h _ $ hba.lt_of_not_le hab⟩ @[simp] lemma not_is_min_iff : ¬ is_min a ↔ ∃ b, b < a := by simp_rw [lt_iff_le_not_le, is_min, not_forall, exists_prop] @[simp] lemma not_is_max_iff : ¬ is_max a ↔ ∃ b, a < b := by simp_rw [lt_iff_le_not_le, is_max, not_forall, exists_prop] @[simp] lemma not_is_min [no_min_order α] (a : α) : ¬ is_min a := not_is_min_iff.2 $ exists_lt a @[simp] lemma not_is_max [no_max_order α] (a : α) : ¬ is_max a := not_is_max_iff.2 $ exists_gt a namespace subsingleton variable [subsingleton α] protected lemma is_bot (a : α) : is_bot a := λ _, (subsingleton.elim _ _).le protected lemma is_top (a : α) : is_top a := λ _, (subsingleton.elim _ _).le protected lemma is_min (a : α) : is_min a := (subsingleton.is_bot _).is_min protected lemma is_max (a : α) : is_max a := (subsingleton.is_top _).is_max end subsingleton end preorder section partial_order variables [partial_order α] {a b : α} protected lemma is_min.eq_of_le (ha : is_min a) (h : b ≤ a) : b = a := h.antisymm $ ha h protected lemma is_min.eq_of_ge (ha : is_min a) (h : b ≤ a) : a = b := h.antisymm' $ ha h protected lemma is_max.eq_of_le (ha : is_max a) (h : a ≤ b) : a = b := h.antisymm $ ha h protected lemma is_max.eq_of_ge (ha : is_max a) (h : a ≤ b) : b = a := h.antisymm' $ ha h end partial_order section prod variables [preorder α] [preorder β] {a a₁ a₂ : α} {b b₁ b₂ : β} {x y : α × β} lemma is_bot.prod_mk (ha : is_bot a) (hb : is_bot b) : is_bot (a, b) := λ c, ⟨ha _, hb _⟩ lemma is_top.prod_mk (ha : is_top a) (hb : is_top b) : is_top (a, b) := λ c, ⟨ha _, hb _⟩ lemma is_min.prod_mk (ha : is_min a) (hb : is_min b) : is_min (a, b) := λ c hc, ⟨ha hc.1, hb hc.2⟩ lemma is_max.prod_mk (ha : is_max a) (hb : is_max b) : is_max (a, b) := λ c hc, ⟨ha hc.1, hb hc.2⟩ lemma is_bot.fst (hx : is_bot x) : is_bot x.1 := λ c, (hx (c, x.2)).1 lemma is_bot.snd (hx : is_bot x) : is_bot x.2 := λ c, (hx (x.1, c)).2 lemma is_top.fst (hx : is_top x) : is_top x.1 := λ c, (hx (c, x.2)).1 lemma is_top.snd (hx : is_top x) : is_top x.2 := λ c, (hx (x.1, c)).2 lemma is_min.fst (hx : is_min x) : is_min x.1 := λ c hc, (hx $ show (c, x.2) ≤ x, from (and_iff_left le_rfl).2 hc).1 lemma is_min.snd (hx : is_min x) : is_min x.2 := λ c hc, (hx $ show (x.1, c) ≤ x, from (and_iff_right le_rfl).2 hc).2 lemma is_max.fst (hx : is_max x) : is_max x.1 := λ c hc, (hx $ show x ≤ (c, x.2), from (and_iff_left le_rfl).2 hc).1 lemma is_max.snd (hx : is_max x) : is_max x.2 := λ c hc, (hx $ show x ≤ (x.1, c), from (and_iff_right le_rfl).2 hc).2 lemma prod.is_bot_iff : is_bot x ↔ is_bot x.1 ∧ is_bot x.2 := ⟨λ hx, ⟨hx.fst, hx.snd⟩, λ h, h.1.prod_mk h.2⟩ lemma prod.is_top_iff : is_top x ↔ is_top x.1 ∧ is_top x.2 := ⟨λ hx, ⟨hx.fst, hx.snd⟩, λ h, h.1.prod_mk h.2⟩ lemma prod.is_min_iff : is_min x ↔ is_min x.1 ∧ is_min x.2 := ⟨λ hx, ⟨hx.fst, hx.snd⟩, λ h, h.1.prod_mk h.2⟩ lemma prod.is_max_iff : is_max x ↔ is_max x.1 ∧ is_max x.2 := ⟨λ hx, ⟨hx.fst, hx.snd⟩, λ h, h.1.prod_mk h.2⟩ end prod
b0ddfbb40cc0cde0578066c5a37bb05e659cabd1
35960c5b117752aca7e3e7767c0b393e4dbd72a7
/src/tactics.lean
7d1c4b27b7de486c8cc5ef7f8a6d4fc131b0247d
[ "Apache-2.0" ]
permissive
spl/tts
461dc76b83df8db47e4660d0941dc97e6d4fd7d1
b65298fea68ce47c8ed3ba3dbce71c1a20dd3481
refs/heads/master
1,541,049,198,347
1,537,967,023,000
1,537,967,029,000
119,653,145
1
0
null
null
null
null
UTF-8
Lean
false
false
1,020
lean
import tactic.basic meta def name.update_suffix : name → (string → string) → name | name.anonymous _ := name.anonymous | (name.mk_string s p) f := name.mk_string (f s) p | (name.mk_numeral n p) _ := name.mk_numeral n p namespace tactic --------------------------------------------------------------- namespace interactive ---------------------------------------------------------- open interactive open interactive.types meta def note_all_applied (p : parse texpr) : tactic unit := do e ← to_expr p, et ← infer_type e, guard et.is_pi <|> fail format!"'note_all_applied' expects a function, got '{et}'", ctx ← local_context, ctx.for_each $ λ h, do ht ← infer_type h, tactic.try $ do unify ht et.binding_domain, note (h.local_pp_name.update_suffix (++ "'")) none (e.mk_app [h]) end /- namespace -/ interactive ------------------------------------------------ end /- namespace -/ tactic -----------------------------------------------------
d0ff6ce570a7bb2e9c7abc7ffc06d5d415a17244
fe208a542cea7b2d6d7ff79f94d535f6d11d814a
/src/Logic/Q6a_term_solution.lean
5353c94cecbd378fdafd9f6b77f570ffc2d82f0a
[]
no_license
ImperialCollegeLondon/M1F_room_342_questions
c4b98b14113fe900a7f388762269305faff73e63
63de9a6ab9c27a433039dd5530bc9b10b1d227f7
refs/heads/master
1,585,807,312,561
1,545,232,972,000
1,545,232,972,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
712
lean
inductive fml | atom (i : ℕ) | imp (a b : fml) | not (a : fml) open fml infixr ` →' `:50 := imp -- right associative prefix `¬' `:40 := fml.not inductive prf : fml → Type | axk (p q) : prf (p →' q →' p) | axs (p q r) : prf $ (p →' q →' r) →' (p →' q) →' (p →' r) | axX (p q) : prf $ ((¬' q) →' (¬' p)) →' p →' q | mp {p q} : prf (p →' q) → prf p → prf q -- bracket change open prf -- example usage: lemma p_of_p_of_p_of_q (p q : fml) : prf $ (p →' q) →' (p →' p) := begin apply mp (axs p q p), exact (axk p q) end lemma Q6a (p : fml) : prf $ p →' p := mp (p_of_p_of_p_of_q _ (p →' p)) $ axk p p theorem Q6b (p : fml) : prf $ p →' ¬' ¬' p := sorry
3ceac997e2f8e8bec5e232dfcc8119ead51007db
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Compiler/LCNF/BaseTypes.lean
662b98853d9fa0e691f3244bcc14359847aacf69
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
1,216
lean
/- Copyright (c) 2022 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Compiler.LCNF.CompilerM import Lean.Compiler.LCNF.Types namespace Lean.Compiler.LCNF /-- State for the environment extension used to save the LCNF base phase type for declarations that do not have code associated with them. Example: constructors, inductive types, foreign functions. -/ structure BaseTypeExtState where /-- The LCNF type for the `base` phase. -/ base : PHashMap Name Expr := {} deriving Inhabited builtin_initialize baseTypeExt : EnvExtension BaseTypeExtState ← registerEnvExtension (pure {}) def getOtherDeclBaseType (declName : Name) (us : List Level) : CoreM Expr := do let info ← getConstInfo declName let type ← match baseTypeExt.getState (← getEnv) |>.base.find? declName with | some type => pure type | none => let type ← Meta.MetaM.run' <| toLCNFType info.type modifyEnv fun env => baseTypeExt.modifyState env fun s => { s with base := s.base.insert declName type } pure type return type.instantiateLevelParamsNoCache info.levelParams us end Lean.Compiler.LCNF
5c9ff06b621e3a0e410cff4611f81ddc19ffbfb6
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/08_Building_Theories_and_Proofs.org.28.lean
f9e3382949dfab74f726ab0f02b47eb3780f92f1
[]
no_license
cjmazey/lean-tutorial
ba559a49f82aa6c5848b9bf17b7389bf7f4ba645
381f61c9fcac56d01d959ae0fa6e376f2c4e3b34
refs/heads/master
1,610,286,098,832
1,447,124,923,000
1,447,124,923,000
43,082,433
0
0
null
null
null
null
UTF-8
Lean
false
false
34
lean
import standard print metaclasses
597c6a7125c0913c3fabfbde5f955b0b07012ac3
d4df7c538bbc0b06771d7b7a6f46fbadebb8c5eb
/src/identity_t.lean
278619cb84769568ee4be8d89264614a38390b9e
[]
no_license
breakerzirconia/LeanTransformers
11bb924b59ac589d0c6b39586d27cccc8f9e939c
3c52441b8990bab7d8cf1817df6e04f657a14e1c
refs/heads/main
1,682,610,526,027
1,620,477,129,000
1,620,477,129,000
365,507,838
0
0
null
null
null
null
UTF-8
Lean
false
false
1,883
lean
import comonad_transformers.comonad import comonad_transformers.comonad_trans import monad_transformers.monad_trans ---------------------------- -- Definition + instances -- ---------------------------- structure IdentityT (m : Type → Type) (a : Type) := (run : m a) open IdentityT instance {m : Type → Type} [functor m] : functor (IdentityT m) := { map := λ α β f idntt, mk $ f <$> idntt.run } instance {m : Type → Type} [has_pure m] : has_pure (IdentityT m) := { pure := λ α a, mk $ pure a } instance {m : Type → Type} [has_seq m] : has_seq (IdentityT m) := { seq := λ α β idnttab idntta, mk $ idnttab.run <*> idntta.run } instance {m : Type → Type} [applicative m] : applicative (IdentityT m) := {} instance {m : Type → Type} [has_bind m] : has_bind (IdentityT m) := { bind := λ α β idntt f, mk $ do a ← idntt.run, (f a).run } instance {m : Type → Type} [monad m] : monad (IdentityT m) := {} instance {m : Type → Type} [has_orelse m] : has_orelse (IdentityT m) := { orelse := λ α idntt1 idntt2, mk $ idntt1.run <|> idntt2.run } instance {m : Type → Type} [alternative m] : alternative (IdentityT m) := { failure := λ α, mk failure } protected def IdentityT_lift {m : Type → Type} [monad m] {a : Type} : m a → IdentityT m a := λ ma, mk $ ma instance : monad_trans IdentityT := ⟨@IdentityT_lift⟩ instance {w : Type → Type} [has_extract w] : has_extract (IdentityT w) := { extract := λ α idntt, *idntt.run } instance {w : Type → Type} [has_extend w] : has_extend (IdentityT w) := { extend := λ α β f idntt, mk $ (<<=) _ _ (f ∘ mk) idntt.run } instance {w : Type → Type} [comonad w] : comonad (IdentityT w) := {} protected def IdentityT_lower {w : Type → Type} [comonad w] {a : Type} : IdentityT w a → w a := λ idntt, idntt.run instance : comonad_trans IdentityT := ⟨@IdentityT_lower⟩
db036391c2bd86693fca8981a78d91c64d8bf9be
097294e9b80f0d9893ac160b9c7219aa135b51b9
/answers/exam1_prep_key.lean
f56eb86cb6bc3551aeaaf3d177c44598013929bb
[]
no_license
AbigailCastro17/CS2102-Discrete-Math
cf296251be9418ce90206f5e66bde9163e21abf9
d741e4d2d6a9b2e0c8380e51706218b8f608cee4
refs/heads/main
1,682,891,087,358
1,621,401,341,000
1,621,401,341,000
368,749,959
0
0
null
null
null
null
UTF-8
Lean
false
false
7,186
lean
/- Note: on this exam, you are meant to use built-in Lean types on all problems. You won't need to use our dm_ versions. Those we developed just so you understand how these types are defined and how they work. -/ /- 1. Product types A. Use Lean's "structure" mechanism to define an inductive product type, called employee, with a constructor, mk, that takes four arguments: (name : string), (id : nat), (salary : nat), and (active : bool). -/ structure employee : Type := mk :: (name : string) (id : nat) (salary : nat) (active : bool) /- B. Define e1 to be an active employee named John Smith with id 123 and a salary of 50. -/ def e1 := employee.mk "John Smith" 123 50 tt #eval e1.salary /- C. Write a function called update_salary that takes an value of the employee type and a natural number representing a new salary for that employee and that returns a new employee object just like the given one but with the salary field updated to the given value. -/ def update_salary : employee → ℕ → employee | (employee.mk n i _ a) r := (employee.mk n i r a) /- D. Use #reduce or #eval to evaluate an expression in which you use this function to "raise Mr. Smith's salary to 60." -/ #eval update_salary e1 60 -- Lean has issues here /- 2. Sum types Define an inductive type called rock_paper_scissors with three values, called "rock", "paper", and "scissors". Then writen a function called next, that takes a value of this type and returns a value of this type according to the following rules: given rock, return paper; given paper return scissors; given scissors, return rock. -/ inductive rock_paper_scissors : Type | rock : rock_paper_scissors | paper | scissors open rock_paper_scissors -- not required def next : rock_paper_scissors → rock_paper_scissors | rock := paper | paper := scissors | scissors := rock /- 3. Inductive definitions Define a type called nested_doll, where a value of this type is either "solid_doll" or "shell" applied to a smaller value of this same type. Then write a function, depth, that takes an object of this type and that returns the number of shells it has. The solid doll has zero shells around it, of course. -/ inductive nested_doll : Type | solid_doll | shell_doll (n : nested_doll) open nested_doll def d0 := nested_doll.solid_doll def d1 := shell_doll d0 def d2 := shell_doll d1 -- ad infinitum def depth : nested_doll → ℕ | solid_doll := 0 | (shell_doll d) := 1 + depth d #eval depth d2 /- 4. Polymorphic types and functions We have represented ordered pairs as values of type prod S T, where S and T are type parameters. An object of this type can be said to have two fields, fst of type S and snd of type T. Define an analogous type, called three_tuple S T U, where S, T, and U are type arguments, and where an object of this type has three fields, fst: S, snd : T, and thd : U. Then write a function, rotate_left, that takes a value of this type and returns a new value of this type in which the field values are all rotated on position to the left. So, the first element becomes the third in the result, the second becomes the first, and the third becomes the second. Test your function. -/ structure three_tuple (S T U : Type) : Type := mk :: (fst : S) (snd : T) (thd : U) -- implicit args best here but not required def rotate_left {S T U : Type}: three_tuple S T U → three_tuple T U S | x := three_tuple.mk x.snd x.thd x.fst -- destructuring in lieu of projection also works def rotate_left' {S T U : Type}: three_tuple S T U → three_tuple T U S | (three_tuple.mk s t u) := three_tuple.mk t u s def rotate_left'' {S T U : Type} (x : three_tuple S T U) := match x with | (three_tuple.mk s t u) := three_tuple.mk t u s end #reduce rotate_left (three_tuple.mk ff 5 tt) #reduce rotate_left' (three_tuple.mk ff 5 tt) /- 5. Sequences (lists) / recursion A. Write a function, contains_zero, that takes a value of type "list nat" and that returns true if any value in the list is zero and otherwise false . An empty list has no zero values so the function should return false in this case. Do not use if..then..else; use pattern matching within one of the cases to solve this problem. -/ def contains_zero : list ℕ → bool | [] := ff | (h :: t) := match h with | 0 := tt | _ := contains_zero t end def contains_zero'' : list ℕ → bool | list.nil := ff | (list.cons h t) := match h with | 0 := tt | _ := contains_zero t end -- we'll also take this answer def contains_zero' : list ℕ → bool | [] := ff | (0 :: t) := tt | (_ :: t) := contains_zero t -- This answer show Lean's list notations /- B. Write a function, inc_values, that takes a value of type "list nat" and that returns a list just like the given one but which each value incremented by one. So for example, given a list, [1, 2, 3], inc_values will return [2, 3, 4]. -/ def inc_values : list ℕ → list ℕ | [] := [] | (h :: t) := ((h + 1) :: (inc_values t)) /- inc_values [1, 2, 3] 2 :: (inc_values [2, 3]) 2 :: (3 :: (inc_values [3])) 2 :: 3 :: 4 :: inc_values [] 2 :: 3 :: 4 :: nil [2, 3, 4] -/ #eval inc_values [1, 2, 3] /- 6. Binary trees / recursion A. Define a type called binary_tree_nat. Its values will represent binary trees of natural numbers. Such a tree is either "empty" or it is a "node" containing a natural number and two smaller binary_tree_nat values. -/ inductive binary_tree_nat : Type | empty | node (n : ℕ) (left : binary_tree_nat) (right : binary_tree_nat) /- B. Then define a function that takes a binary_tree_nat value as an argument and that returns the sum of all of the natural numbers in the tree. An empty tree contains no natural numbers, so the result must be zero in this case. -/ def tree_sum : binary_tree_nat → ℕ | binary_tree_nat.empty := 0 | (binary_tree_nat.node n l r) := n + tree_sum l + tree_sum r /- 7. Partial functions. A partial function is a function that is not defined for all values of its argument type. Yet all function definitions in Lean must be total. To represent a partial function as a total funtion in Lean, we use the option type. We define a function that always returns an option, and so is total, but the result is in one of two forms: either "some result" when the result of the underlying partial function is defined, or "none" when it's not. We have implemented a predecessor function, pred : ℕ → ℕ, that's a little "funky": when applied to zero, it returns zero, even though it could be argued that the predecessor of zero (in the natural numbers) should be defined to be undefined. Implement a version of pred, let's call it pred_partial, that for any non-zero argument, n, returns "some result" where "result" is the predecessor of n, but that when applied to zero returns "none", to flag that the function is not defined for zero. Write the function pred_partial and test it for zero and non-zero argument values. -/ def pred_partial : ℕ → option ℕ | 0 := none | (nat.succ n') := some n'
839ca231f158de9d2a215e511bcf7bf7240d7cca
ee8cdbabf07f77e7be63a449b8483ce308d37218
/lean/src/valid/mathd-algebra-149.lean
77adcd850b5d73c43a998e84c0fa9221e5b97db4
[ "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
417
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.finset.basic open_locale big_operators example (f : ℝ → ℝ) (h₀ : ∀ x < -5, f x = x ^ 2 + 5) (h₁ : ∀ x ≥ -5, f x = 3 * x -8) (h₂ : fintype (f⁻¹' {10})): ∑ k in (f⁻¹' {10}).to_finset, k = 6 := begin sorry end
5d183ce78a37bde6dd64f85977108c408044b9d7
a45212b1526d532e6e83c44ddca6a05795113ddc
/src/group_theory/free_group.lean
ddfd29d8738f3491403507f5354f6366ef74b568
[ "Apache-2.0" ]
permissive
fpvandoorn/mathlib
b21ab4068db079cbb8590b58fda9cc4bc1f35df4
b3433a51ea8bc07c4159c1073838fc0ee9b8f227
refs/heads/master
1,624,791,089,608
1,556,715,231,000
1,556,715,231,000
165,722,980
5
0
Apache-2.0
1,552,657,455,000
1,547,494,646,000
Lean
UTF-8
Lean
false
false
30,833
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau Free groups as a quotient over the reduction relation `a * x * x⁻¹ * b = a * b`. First we introduce the one step reduction relation `free_group.red.step`: w * x * x⁻¹ * v ~> w * v its reflexive transitive closure: `free_group.red.trans` and proof that its join is an equivalence relation. Then we introduce `free_group α` as a quotient over `free_group.red.step`. -/ import logic.relation import algebra.group algebra.group_power import data.fintype data.list.basic import group_theory.subgroup open relation universes u v w variables {α : Type u} local attribute [simp] list.append_eq_has_append namespace free_group variables {L L₁ L₂ L₃ L₄ : list (α × bool)} /-- Reduction step: `w * x * x⁻¹ * v ~> w * v` -/ inductive red.step : list (α × bool) → list (α × bool) → Prop | bnot {L₁ L₂ x b} : red.step (L₁ ++ (x, b) :: (x, bnot b) :: L₂) (L₁ ++ L₂) attribute [simp] red.step.bnot /-- Reflexive-transitive closure of red.step -/ def red : list (α × bool) → list (α × bool) → Prop := refl_trans_gen red.step @[refl] lemma red.refl : red L L := refl_trans_gen.refl @[trans] lemma red.trans : red L₁ L₂ → red L₂ L₃ → red L₁ L₃ := refl_trans_gen.trans namespace red /-- Predicate asserting that word `w₁` can be reduced to `w₂` in one step, i.e. there are words `w₃ w₄` and letter `x` such that `w₁ = w₃xx⁻¹w₄` and `w₂ = w₃w₄` -/ theorem step.length : ∀ {L₁ L₂ : list (α × bool)}, step L₁ L₂ → L₂.length + 2 = L₁.length | _ _ (@red.step.bnot _ L1 L2 x b) := by rw [list.length_append, list.length_append]; refl @[simp] lemma step.bnot_rev {x b} : step (L₁ ++ (x, bnot b) :: (x, b) :: L₂) (L₁ ++ L₂) := by cases b; from step.bnot @[simp] lemma step.cons_bnot {x b} : red.step ((x, b) :: (x, bnot b) :: L) L := @step.bnot _ [] _ _ _ @[simp] lemma step.cons_bnot_rev {x b} : red.step ((x, bnot b) :: (x, b) :: L) L := @red.step.bnot_rev _ [] _ _ _ theorem step.append_left : ∀ {L₁ L₂ L₃ : list (α × bool)}, step L₂ L₃ → step (L₁ ++ L₂) (L₁ ++ L₃) | _ _ _ red.step.bnot := by rw [← list.append_assoc, ← list.append_assoc]; constructor theorem step.cons {x} (H : red.step L₁ L₂) : red.step (x :: L₁) (x :: L₂) := @step.append_left _ [x] _ _ H theorem step.append_right : ∀ {L₁ L₂ L₃ : list (α × bool)}, step L₁ L₂ → step (L₁ ++ L₃) (L₂ ++ L₃) | _ _ _ red.step.bnot := by simp lemma not_step_nil : ¬ step [] L := begin generalize h' : [] = L', assume h, cases h with L₁ L₂, simp [list.nil_eq_append_iff] at h', contradiction end lemma step.cons_left_iff {a : α} {b : bool} : step ((a, b) :: L₁) L₂ ↔ (∃L, step L₁ L ∧ L₂ = (a, b) :: L) ∨ (L₁ = (a, bnot b)::L₂) := begin split, { generalize hL : ((a, b) :: L₁ : list _) = L, assume h, rcases h with ⟨_ | ⟨p, s'⟩, e, a', b'⟩, { simp at hL, simp [*] }, { simp at hL, rcases hL with ⟨rfl, rfl⟩, refine or.inl ⟨s' ++ e, step.bnot, _⟩, simp } }, { assume h, rcases h with ⟨L, h, rfl⟩ | rfl, { exact step.cons h }, { exact step.cons_bnot } } end lemma not_step_singleton : ∀ {p : α × bool}, ¬ step [p] L | (a, b) := by simp [step.cons_left_iff, not_step_nil] lemma step.cons_cons_iff : ∀{p : α × bool}, step (p :: L₁) (p :: L₂) ↔ step L₁ L₂ := by simp [step.cons_left_iff, iff_def, or_imp_distrib] {contextual := tt} lemma step.append_left_iff : ∀L, step (L ++ L₁) (L ++ L₂) ↔ step L₁ L₂ | [] := by simp | (p :: l) := by simp [step.append_left_iff l, step.cons_cons_iff] private theorem step.diamond_aux : ∀ {L₁ L₂ L₃ L₄ : list (α × bool)} {x1 b1 x2 b2}, L₁ ++ (x1, b1) :: (x1, bnot b1) :: L₂ = L₃ ++ (x2, b2) :: (x2, bnot b2) :: L₄ → L₁ ++ L₂ = L₃ ++ L₄ ∨ ∃ L₅, red.step (L₁ ++ L₂) L₅ ∧ red.step (L₃ ++ L₄) L₅ | [] _ [] _ _ _ _ _ H := by injections; subst_vars; simp | [] _ [(x3,b3)] _ _ _ _ _ H := by injections; subst_vars; simp | [(x3,b3)] _ [] _ _ _ _ _ H := by injections; subst_vars; simp | [] _ ((x3,b3)::(x4,b4)::tl) _ _ _ _ _ H := by injections; subst_vars; simp; right; exact ⟨_, red.step.bnot, red.step.cons_bnot⟩ | ((x3,b3)::(x4,b4)::tl) _ [] _ _ _ _ _ H := by injections; subst_vars; simp; right; exact ⟨_, red.step.cons_bnot, red.step.bnot⟩ | ((x3,b3)::tl) _ ((x4,b4)::tl2) _ _ _ _ _ H := let ⟨H1, H2⟩ := list.cons.inj H in match step.diamond_aux H2 with | or.inl H3 := or.inl $ by simp [H1, H3] | or.inr ⟨L₅, H3, H4⟩ := or.inr ⟨_, step.cons H3, by simpa [H1] using step.cons H4⟩ end theorem step.diamond : ∀ {L₁ L₂ L₃ L₄ : list (α × bool)}, red.step L₁ L₃ → red.step L₂ L₄ → L₁ = L₂ → L₃ = L₄ ∨ ∃ L₅, red.step L₃ L₅ ∧ red.step L₄ L₅ | _ _ _ _ red.step.bnot red.step.bnot H := step.diamond_aux H lemma step.to_red : step L₁ L₂ → red L₁ L₂ := refl_trans_gen.single /-- Church-Rosser theorem for word reduction: If `w1 w2 w3` are words such that `w1` reduces to `w2` and `w3` respectively, then there is a word `w4` such that `w2` and `w3` reduce to `w4` respectively. -/ theorem church_rosser : red L₁ L₂ → red L₁ L₃ → join red L₂ L₃ := relation.church_rosser (assume a b c hab hac, match b, c, red.step.diamond hab hac rfl with | b, _, or.inl rfl := ⟨b, by refl, by refl⟩ | b, c, or.inr ⟨d, hbd, hcd⟩ := ⟨d, refl_gen.single hbd, hcd.to_red⟩ end) lemma cons_cons {p} : red L₁ L₂ → red (p :: L₁) (p :: L₂) := refl_trans_gen_lift (list.cons p) (assume a b, step.cons) lemma cons_cons_iff (p) : red (p :: L₁) (p :: L₂) ↔ red L₁ L₂ := iff.intro begin generalize eq₁ : (p :: L₁ : list _) = LL₁, generalize eq₂ : (p :: L₂ : list _) = LL₂, assume h, induction h using relation.refl_trans_gen.head_induction_on with L₁ L₂ h₁₂ h ih generalizing L₁ L₂, { subst_vars, cases eq₂, constructor }, { subst_vars, cases p with a b, rw [step.cons_left_iff] at h₁₂, rcases h₁₂ with ⟨L, h₁₂, rfl⟩ | rfl, { exact (ih rfl rfl).head h₁₂ }, { exact (cons_cons h).tail step.cons_bnot_rev } } end cons_cons lemma append_append_left_iff : ∀L, red (L ++ L₁) (L ++ L₂) ↔ red L₁ L₂ | [] := iff.refl _ | (p :: L) := by simp [append_append_left_iff L, cons_cons_iff] lemma append_append (h₁ : red L₁ L₃) (h₂ : red L₂ L₄) : red (L₁ ++ L₂) (L₃ ++ L₄) := (refl_trans_gen_lift (λL, L ++ L₂) (assume a b, step.append_right) h₁).trans ((append_append_left_iff _).2 h₂) lemma to_append_iff : red L (L₁ ++ L₂) ↔ (∃L₃ L₄, L = L₃ ++ L₄ ∧ red L₃ L₁ ∧ red L₄ L₂) := iff.intro begin generalize eq : L₁ ++ L₂ = L₁₂, assume h, induction h with L' L₁₂ hLL' h ih generalizing L₁ L₂, { exact ⟨_, _, eq.symm, by refl, by refl⟩ }, { cases h with s e a b, rcases list.append_eq_append_iff.1 eq with ⟨s', rfl, rfl⟩ | ⟨e', rfl, rfl⟩, { have : L₁ ++ (s' ++ ((a, b) :: (a, bnot b) :: e)) = (L₁ ++ s') ++ ((a, b) :: (a, bnot b) :: e), { simp }, rcases ih this with ⟨w₁, w₂, rfl, h₁, h₂⟩, exact ⟨w₁, w₂, rfl, h₁, h₂.tail step.bnot⟩ }, { have : (s ++ ((a, b) :: (a, bnot b) :: e')) ++ L₂ = s ++ ((a, b) :: (a, bnot b) :: (e' ++ L₂)), { simp }, rcases ih this with ⟨w₁, w₂, rfl, h₁, h₂⟩, exact ⟨w₁, w₂, rfl, h₁.tail step.bnot, h₂⟩ }, } end (assume ⟨L₃, L₄, eq, h₃, h₄⟩, eq.symm ▸ append_append h₃ h₄) /-- The empty word `[]` only reduces to itself. -/ theorem nil_iff : red [] L ↔ L = [] := refl_trans_gen_iff_eq (assume l, red.not_step_nil) /-- A letter only reduces to itself. -/ theorem singleton_iff {x} : red [x] L₁ ↔ L₁ = [x] := refl_trans_gen_iff_eq (assume l, not_step_singleton) /-- If `x` is a letter and `w` is a word such that `xw` reduces to the empty word, then `w` reduces to `x⁻¹` -/ theorem cons_nil_iff_singleton {x b} : red ((x, b) :: L) [] ↔ red L [(x, bnot b)] := iff.intro (assume h, have h₁ : red ((x, bnot b) :: (x, b) :: L) [(x, bnot b)], from cons_cons h, have h₂ : red ((x, bnot b) :: (x, b) :: L) L, from refl_trans_gen.single step.cons_bnot_rev, let ⟨L', h₁, h₂⟩ := church_rosser h₁ h₂ in by rw [singleton_iff] at h₁; subst L'; assumption) (assume h, (cons_cons h).tail step.cons_bnot) theorem red_iff_irreducible {x1 b1 x2 b2} (h : (x1, b1) ≠ (x2, b2)) : red [(x1, bnot b1), (x2, b2)] L ↔ L = [(x1, bnot b1), (x2, b2)] := begin apply refl_trans_gen_iff_eq, generalize eq : [(x1, bnot b1), (x2, b2)] = L', assume L h', cases h', simp [list.cons_eq_append_iff, list.nil_eq_append_iff] at eq, rcases eq with ⟨rfl, ⟨rfl, rfl⟩, ⟨rfl, rfl⟩, rfl⟩, subst_vars, simp at h, contradiction end /-- If `x` and `y` are distinct letters and `w₁ w₂` are words such that `xw₁` reduces to `yw₂`, then `w₁` reduces to `x⁻¹yw₂`. -/ theorem inv_of_red_of_ne {x1 b1 x2 b2} (H1 : (x1, b1) ≠ (x2, b2)) (H2 : red ((x1, b1) :: L₁) ((x2, b2) :: L₂)) : red L₁ ((x1, bnot b1) :: (x2, b2) :: L₂) := begin have : red ((x1, b1) :: L₁) ([(x2, b2)] ++ L₂), from H2, rcases to_append_iff.1 this with ⟨_ | ⟨p, L₃⟩, L₄, eq, h₁, h₂⟩, { simp [nil_iff] at h₁, contradiction }, { cases eq, show red (L₃ ++ L₄) ([(x1, bnot b1), (x2, b2)] ++ L₂), apply append_append _ h₂, have h₁ : red ((x1, bnot b1) :: (x1, b1) :: L₃) [(x1, bnot b1), (x2, b2)], { exact cons_cons h₁ }, have h₂ : red ((x1, bnot b1) :: (x1, b1) :: L₃) L₃, { exact step.cons_bnot_rev.to_red }, rcases church_rosser h₁ h₂ with ⟨L', h₁, h₂⟩, rw [red_iff_irreducible H1] at h₁, rwa [h₁] at h₂ } end theorem step.sublist (H : red.step L₁ L₂) : L₂ <+ L₁ := by cases H; simp; constructor; constructor; refl /-- If `w₁ w₂` are words such that `w₁` reduces to `w₂`, then `w₂` is a sublist of `w₁`. -/ theorem sublist : red L₁ L₂ → L₂ <+ L₁ := refl_trans_gen_of_transitive_reflexive (λl, list.sublist.refl l) (λa b c hab hbc, list.sublist.trans hbc hab) (λa b, red.step.sublist) theorem sizeof_of_step : ∀ {L₁ L₂ : list (α × bool)}, step L₁ L₂ → L₂.sizeof < L₁.sizeof | _ _ (@step.bnot _ L1 L2 x b) := begin induction L1 with hd tl ih, case list.nil { dsimp [list.sizeof], have H : 1 + sizeof (x, b) + (1 + sizeof (x, bnot b) + list.sizeof L2) = (list.sizeof L2 + 1) + (sizeof (x, b) + sizeof (x, bnot b) + 1), { ac_refl }, rw H, exact nat.le_add_right _ _ }, case list.cons { dsimp [list.sizeof], exact nat.add_lt_add_left ih _ } end theorem length (h : red L₁ L₂) : ∃ n, L₁.length = L₂.length + 2 * n := begin induction h with L₂ L₃ h₁₂ h₂₃ ih, { exact ⟨0, rfl⟩ }, { rcases ih with ⟨n, eq⟩, existsi (1 + n), simp [mul_add, eq, (step.length h₂₃).symm] } end theorem antisymm (h₁₂ : red L₁ L₂) : red L₂ L₁ → L₁ = L₂ := match L₁, h₁₂.cases_head with | _, or.inl rfl := assume h, rfl | L₁, or.inr ⟨L₃, h₁₃, h₃₂⟩ := assume h₂₁, let ⟨n, eq⟩ := length (h₃₂.trans h₂₁) in have list.length L₃ + 0 = list.length L₃ + (2 * n + 2), by simpa [(step.length h₁₃).symm, add_comm, add_assoc] using eq, (nat.no_confusion $ nat.add_left_cancel this) end end red theorem equivalence_join_red : equivalence (join (@red α)) := equivalence_join_refl_trans_gen $ assume a b c hab hac, (match b, c, red.step.diamond hab hac rfl with | b, _, or.inl rfl := ⟨b, by refl, by refl⟩ | b, c, or.inr ⟨d, hbd, hcd⟩ := ⟨d, refl_gen.single hbd, refl_trans_gen.single hcd⟩ end) theorem join_red_of_step (h : red.step L₁ L₂) : join red L₁ L₂ := join_of_single reflexive_refl_trans_gen h.to_red theorem eqv_gen_step_iff_join_red : eqv_gen red.step L₁ L₂ ↔ join red L₁ L₂ := iff.intro (assume h, have eqv_gen (join red) L₁ L₂ := eqv_gen_mono (assume a b, join_red_of_step) h, (eqv_gen_iff_of_equivalence $ equivalence_join_red).1 this) (join_of_equivalence (eqv_gen.is_equivalence _) $ assume a b, refl_trans_gen_of_equivalence (eqv_gen.is_equivalence _) eqv_gen.rel) end free_group /-- The free group over a type, i.e. the words formed by the elements of the type and their formal inverses, quotient by one step reduction. -/ def free_group (α : Type u) : Type u := quot $ @free_group.red.step α namespace free_group variables {α} {L L₁ L₂ L₃ L₄ : list (α × bool)} def mk (L) : free_group α := quot.mk red.step L @[simp] lemma quot_mk_eq_mk : quot.mk red.step L = mk L := rfl @[simp] lemma quot_lift_mk (β : Type v) (f : list (α × bool) → β) (H : ∀ L₁ L₂, red.step L₁ L₂ → f L₁ = f L₂) : quot.lift f H (mk L) = f L := rfl @[simp] lemma quot_lift_on_mk (β : Type v) (f : list (α × bool) → β) (H : ∀ L₁ L₂, red.step L₁ L₂ → f L₁ = f L₂) : quot.lift_on (mk L) f H = f L := rfl instance : has_one (free_group α) := ⟨mk []⟩ lemma one_eq_mk : (1 : free_group α) = mk [] := rfl instance : has_mul (free_group α) := ⟨λ x y, quot.lift_on x (λ L₁, quot.lift_on y (λ L₂, mk $ L₁ ++ L₂) (λ L₂ L₃ H, quot.sound $ red.step.append_left H)) (λ L₁ L₂ H, quot.induction_on y $ λ L₃, quot.sound $ red.step.append_right H)⟩ @[simp] lemma mul_mk : mk L₁ * mk L₂ = mk (L₁ ++ L₂) := rfl instance : has_inv (free_group α) := ⟨λx, quot.lift_on x (λ L, mk (L.map $ λ x : α × bool, (x.1, bnot x.2)).reverse) (assume a b h, quot.sound $ by cases h; simp)⟩ @[simp] lemma inv_mk : (mk L)⁻¹ = mk (L.map $ λ x : α × bool, (x.1, bnot x.2)).reverse := rfl instance : group (free_group α) := { mul := (*), one := 1, inv := has_inv.inv, mul_assoc := by rintros ⟨L₁⟩ ⟨L₂⟩ ⟨L₃⟩; simp, one_mul := by rintros ⟨L⟩; refl, mul_one := by rintros ⟨L⟩; simp [one_eq_mk], mul_left_inv := by rintros ⟨L⟩; exact (list.rec_on L rfl $ λ ⟨x, b⟩ tl ih, eq.trans (quot.sound $ by simp [one_eq_mk]) ih) } /-- `of x` is the canonical injection from the type to the free group over that type by sending each element to the equivalence class of the letter that is the element. -/ def of (x : α) : free_group α := mk [(x, tt)] theorem red.exact : mk L₁ = mk L₂ ↔ join red L₁ L₂ := calc (mk L₁ = mk L₂) ↔ eqv_gen red.step L₁ L₂ : iff.intro (quot.exact _) quot.eqv_gen_sound ... ↔ join red L₁ L₂ : eqv_gen_step_iff_join_red /-- The canonical injection from the type to the free group is an injection. -/ theorem of.inj {x y : α} (H : of x = of y) : x = y := let ⟨L₁, hx, hy⟩ := red.exact.1 H in by simp [red.singleton_iff] at hx hy; cc section to_group variables {β : Type v} [group β] (f : α → β) {x y : free_group α} def to_group.aux : list (α × bool) → β := λ L, list.prod $ L.map $ λ x, cond x.2 (f x.1) (f x.1)⁻¹ theorem red.step.to_group {f : α → β} (H : red.step L₁ L₂) : to_group.aux f L₁ = to_group.aux f L₂ := by cases H with _ _ _ b; cases b; simp [to_group.aux] /-- If `β` is a group, then any function from `α` to `β` extends uniquely to a group homomorphism from the free group over `α` to `β` -/ def to_group : free_group α → β := quot.lift (to_group.aux f) $ λ L₁ L₂ H, red.step.to_group H variable {f} @[simp] lemma to_group.mk : to_group f (mk L) = list.prod (L.map $ λ x, cond x.2 (f x.1) (f x.1)⁻¹) := rfl @[simp] lemma to_group.of {x} : to_group f (of x) = f x := one_mul _ instance to_group.is_group_hom : is_group_hom (to_group f) := ⟨by rintros ⟨L₁⟩ ⟨L₂⟩; simp⟩ @[simp] lemma to_group.mul : to_group f (x * y) = to_group f x * to_group f y := is_group_hom.map_mul _ _ _ @[simp] lemma to_group.one : to_group f 1 = 1 := is_group_hom.map_one _ @[simp] lemma to_group.inv : to_group f x⁻¹ = (to_group f x)⁻¹ := is_group_hom.map_inv _ _ theorem to_group.unique (g : free_group α → β) [is_group_hom g] (hg : ∀ x, g (of x) = f x) : ∀{x}, g x = to_group f x := by rintros ⟨L⟩; exact list.rec_on L (is_group_hom.map_one g) (λ ⟨x, b⟩ t (ih : g (mk t) = _), bool.rec_on b (show g ((of x)⁻¹ * mk t) = to_group f (mk ((x, ff) :: t)), by simp [is_group_hom.map_mul g, is_group_hom.map_inv g, hg, ih, to_group, to_group.aux]) (show g (of x * mk t) = to_group f (mk ((x, tt) :: t)), by simp [is_group_hom.map_mul g, is_group_hom.map_inv g, hg, ih, to_group, to_group.aux])) theorem to_group.of_eq (x : free_group α) : to_group of x = x := eq.symm $ to_group.unique id (λ x, rfl) theorem to_group.range_subset {s : set β} [is_subgroup s] (H : set.range f ⊆ s) : set.range (to_group f) ⊆ s := by rintros _ ⟨⟨L⟩, rfl⟩; exact list.rec_on L (is_submonoid.one_mem s) (λ ⟨x, b⟩ tl ih, bool.rec_on b (by simp at ih ⊢; from is_submonoid.mul_mem (is_subgroup.inv_mem $ H ⟨x, rfl⟩) ih) (by simp at ih ⊢; from is_submonoid.mul_mem (H ⟨x, rfl⟩) ih)) theorem to_group.range_eq_closure : set.range (to_group f) = group.closure (set.range f) := set.subset.antisymm (to_group.range_subset group.subset_closure) (group.closure_subset $ λ y ⟨x, hx⟩, ⟨of x, by simpa⟩) end to_group section map variables {β : Type v} (f : α → β) {x y : free_group α} def map.aux (L : list (α × bool)) : list (β × bool) := L.map $ λ x, (f x.1, x.2) /-- Any function from `α` to `β` extends uniquely to a group homomorphism from the free group ver `α` to the free group over `β`. -/ def map (x : free_group α) : free_group β := x.lift_on (λ L, mk $ map.aux f L) $ λ L₁ L₂ H, quot.sound $ by cases H; simp [map.aux] instance map.is_group_hom : is_group_hom (map f) := ⟨by rintros ⟨L₁⟩ ⟨L₂⟩; simp [map, map.aux]⟩ variable {f} @[simp] lemma map.mk : map f (mk L) = mk (L.map (λ x, (f x.1, x.2))) := rfl @[simp] lemma map.id : map id x = x := have H1 : (λ (x : α × bool), x) = id := rfl, by rcases x with ⟨L⟩; simp [H1] @[simp] lemma map.id' : map (λ z, z) x = x := map.id theorem map.comp {γ : Type w} {f : α → β} {g : β → γ} {x} : map g (map f x) = map (g ∘ f) x := by rcases x with ⟨L⟩; simp @[simp] lemma map.of {x} : map f (of x) = of (f x) := rfl @[simp] lemma map.mul : map f (x * y) = map f x * map f y := is_group_hom.map_mul _ x y @[simp] lemma map.one : map f 1 = 1 := is_group_hom.map_one _ @[simp] lemma map.inv : map f x⁻¹ = (map f x)⁻¹ := is_group_hom.map_inv _ x theorem map.unique (g : free_group α → free_group β) [is_group_hom g] (hg : ∀ x, g (of x) = of (f x)) : ∀{x}, g x = map f x := by rintros ⟨L⟩; exact list.rec_on L (is_group_hom.map_one g) (λ ⟨x, b⟩ t (ih : g (mk t) = map f (mk t)), bool.rec_on b (show g ((of x)⁻¹ * mk t) = map f ((of x)⁻¹ * mk t), by simp [is_group_hom.map_mul g, is_group_hom.map_inv g, hg, ih]) (show g (of x * mk t) = map f (of x * mk t), by simp [is_group_hom.map_mul g, hg, ih])) /-- Equivalent types give rise to equivalent free groups. -/ def free_group_congr {α β} (e : α ≃ β) : free_group α ≃ free_group β := ⟨map e, map e.symm, λ x, by simp [function.comp, map.comp], λ x, by simp [function.comp, map.comp]⟩ theorem map_eq_to_group : map f x = to_group (of ∘ f) x := eq.symm $ map.unique _ $ λ x, by simp end map section prod variables [group α] (x y : free_group α) /-- If `α` is a group, then any function from `α` to `α` extends uniquely to a homomorphism from the free group over `α` to `α`. This is the multiplicative version of `sum`. -/ def prod : α := to_group id x variables {x y} @[simp] lemma prod_mk : prod (mk L) = list.prod (L.map $ λ x, cond x.2 x.1 x.1⁻¹) := rfl @[simp] lemma prod.of {x : α} : prod (of x) = x := to_group.of instance prod.is_group_hom : is_group_hom (@prod α _) := to_group.is_group_hom @[simp] lemma prod.mul : prod (x * y) = prod x * prod y := to_group.mul @[simp] lemma prod.one : prod (1:free_group α) = 1 := to_group.one @[simp] lemma prod.inv : prod x⁻¹ = (prod x)⁻¹ := to_group.inv lemma prod.unique (g : free_group α → α) [is_group_hom g] (hg : ∀ x, g (of x) = x) {x} : g x = prod x := to_group.unique g hg end prod theorem to_group_eq_prod_map {β : Type v} [group β] {f : α → β} {x} : to_group f x = prod (map f x) := eq.symm $ to_group.unique (prod ∘ map f) $ λ _, by simp section sum variables [add_group α] (x y : free_group α) /-- If `α` is a group, then any function from `α` to `α` extends uniquely to a homomorphism from the free group over `α` to `α`. This is the additive version of `prod`. -/ def sum : α := @prod (multiplicative _) _ x variables {x y} @[simp] lemma sum_mk : sum (mk L) = list.sum (L.map $ λ x, cond x.2 x.1 (-x.1)) := rfl @[simp] lemma sum.of {x : α} : sum (of x) = x := prod.of instance sum.is_group_hom : is_group_hom (@sum α _) := prod.is_group_hom @[simp] lemma sum.sum : sum (x * y) = sum x + sum y := prod.mul @[simp] lemma sum.one : sum (1:free_group α) = 0 := prod.one @[simp] lemma sum.inv : sum x⁻¹ = -sum x := prod.inv end sum def free_group_empty_equiv_unit : free_group empty ≃ unit := { to_fun := λ _, (), inv_fun := λ _, 1, left_inv := by rintros ⟨_ | ⟨⟨⟨⟩, _⟩, _⟩⟩; refl, right_inv := λ ⟨⟩, rfl } def free_group_unit_equiv_int : free_group unit ≃ int := { to_fun := λ x, sum $ map (λ _, 1) x, inv_fun := λ x, of () ^ x, left_inv := by rintros ⟨L⟩; exact list.rec_on L rfl (λ ⟨⟨⟩, b⟩ tl ih, by cases b; simp [gpow_add] at ih ⊢; rw ih; refl), right_inv := λ x, int.induction_on x (by simp) (λ i ih, by simp at ih; simp [gpow_add, ih]) (λ i ih, by simp at ih; simp [gpow_add, ih]) } section category variables {β : Type u} instance : monad free_group.{u} := { pure := λ α, of, map := λ α β, map, bind := λ α β x f, to_group f x } @[elab_as_eliminator] protected theorem induction_on {C : free_group α → Prop} (z : free_group α) (C1 : C 1) (Cp : ∀ x, C $ pure x) (Ci : ∀ x, C (pure x) → C (pure x)⁻¹) (Cm : ∀ x y, C x → C y → C (x * y)) : C z := quot.induction_on z $ λ L, list.rec_on L C1 $ λ ⟨x, b⟩ tl ih, bool.rec_on b (Cm _ _ (Ci _ $ Cp x) ih) (Cm _ _ (Cp x) ih) @[simp] lemma map_pure (f : α → β) (x : α) : f <$> (pure x : free_group α) = pure (f x) := map.of @[simp] lemma map_one (f : α → β) : f <$> (1 : free_group α) = 1 := map.one @[simp] lemma map_mul (f : α → β) (x y : free_group α) : f <$> (x * y) = f <$> x * f <$> y := map.mul @[simp] lemma map_inv (f : α → β) (x : free_group α) : f <$> (x⁻¹) = (f <$> x)⁻¹ := map.inv @[simp] lemma pure_bind (f : α → free_group β) (x) : pure x >>= f = f x := to_group.of @[simp] lemma one_bind (f : α → free_group β) : 1 >>= f = 1 := @@to_group.one _ f @[simp] lemma mul_bind (f : α → free_group β) (x y : free_group α) : x * y >>= f = (x >>= f) * (y >>= f) := to_group.mul @[simp] lemma inv_bind (f : α → free_group β) (x : free_group α) : x⁻¹ >>= f = (x >>= f)⁻¹ := to_group.inv instance : is_lawful_monad free_group.{u} := { id_map := λ α x, free_group.induction_on x (map_one id) (λ x, map_pure id x) (λ x ih, by rw [map_inv, ih]) (λ x y ihx ihy, by rw [map_mul, ihx, ihy]), pure_bind := λ α β x f, pure_bind f x, bind_assoc := λ α β γ x f g, free_group.induction_on x (by iterate 3 { rw one_bind }) (λ x, by iterate 2 { rw pure_bind }) (λ x ih, by iterate 3 { rw inv_bind }; rw ih) (λ x y ihx ihy, by iterate 3 { rw mul_bind }; rw [ihx, ihy]), bind_pure_comp_eq_map := λ α β f x, free_group.induction_on x (by rw [one_bind, map_one]) (λ x, by rw [pure_bind, map_pure]) (λ x ih, by rw [inv_bind, map_inv, ih]) (λ x y ihx ihy, by rw [mul_bind, map_mul, ihx, ihy]) } end category section reduce variable [decidable_eq α] /-- The maximal reduction of a word. It is computable iff `α` has decidable equality. -/ def reduce (L : list (α × bool)) : list (α × bool) := list.rec_on L [] $ λ hd1 tl1 ih, list.cases_on ih [hd1] $ λ hd2 tl2, if hd1.1 = hd2.1 ∧ hd1.2 = bnot hd2.2 then tl2 else hd1 :: hd2 :: tl2 @[simp] lemma reduce.cons (x) : reduce (x :: L) = list.cases_on (reduce L) [x] (λ hd tl, if x.1 = hd.1 ∧ x.2 = bnot hd.2 then tl else x :: hd :: tl) := rfl /-- The first theorem that characterises the function `reduce`: a word reduces to its maximal reduction. -/ theorem reduce.red : red L (reduce L) := begin induction L with hd1 tl1 ih, case list.nil { constructor }, case list.cons { dsimp, revert ih, generalize htl : reduce tl1 = TL, intro ih, cases TL with hd2 tl2, case list.nil { exact red.cons_cons ih }, case list.cons { dsimp, by_cases h : hd1.fst = hd2.fst ∧ hd1.snd = bnot (hd2.snd), { rw [if_pos h], transitivity, { exact red.cons_cons ih }, { cases hd1, cases hd2, cases h, dsimp at *, subst_vars, exact red.step.cons_bnot_rev.to_red } }, { rw [if_neg h], exact red.cons_cons ih } } } end theorem reduce.not {p : Prop} : ∀ {L₁ L₂ L₃ : list (α × bool)} {x b}, reduce L₁ = L₂ ++ (x, b) :: (x, bnot b) :: L₃ → p | [] L2 L3 _ _ := λ h, by cases L2; injections | ((x,b)::L1) L2 L3 x' b' := begin dsimp, cases r : reduce L1, { dsimp, intro h, have := congr_arg list.length h, simp [-add_comm] at this, exact absurd this dec_trivial }, cases hd with y c, by_cases x = y ∧ b = bnot c; simp [h]; intro H, { rw H at r, exact @reduce.not L1 ((y,c)::L2) L3 x' b' r }, rcases L2 with _|⟨a, L2⟩, { injections, subst_vars, simp at h, cc }, { refine @reduce.not L1 L2 L3 x' b' _, injection H with _ H, rw [r, H], refl } end /-- The second theorem that characterises the function `reduce`: the maximal reduction of a word only reduces to itself. -/ theorem reduce.min (H : red (reduce L₁) L₂) : reduce L₁ = L₂ := begin induction H with L1 L' L2 H1 H2 ih, { refl }, { cases H1 with L4 L5 x b, exact reduce.not H2 } end /-- `reduce` is idempotent, i.e. the maximal reduction of the maximal reduction of a word is the maximal reduction of the word. -/ theorem reduce.idem : reduce (reduce L) = reduce L := eq.symm $ reduce.min reduce.red theorem reduce.step.eq (H : red.step L₁ L₂) : reduce L₁ = reduce L₂ := let ⟨L₃, HR13, HR23⟩ := red.church_rosser reduce.red (reduce.red.head H) in (reduce.min HR13).trans (reduce.min HR23).symm /-- If a word reduces to another word, then they have a common maximal reduction. -/ theorem reduce.eq_of_red (H : red L₁ L₂) : reduce L₁ = reduce L₂ := let ⟨L₃, HR13, HR23⟩ := red.church_rosser reduce.red (red.trans H reduce.red) in (reduce.min HR13).trans (reduce.min HR23).symm /-- If two words correspond to the same element in the free group, then they have a common maximal reduction. This is the proof that the function that sends an element of the free group to its maximal reduction is well-defined. -/ theorem reduce.sound (H : mk L₁ = mk L₂) : reduce L₁ = reduce L₂ := let ⟨L₃, H13, H23⟩ := red.exact.1 H in (reduce.eq_of_red H13).trans (reduce.eq_of_red H23).symm /-- If two words have a common maximal reduction, then they correspond to the same element in the free group. -/ theorem reduce.exact (H : reduce L₁ = reduce L₂) : mk L₁ = mk L₂ := red.exact.2 ⟨reduce L₂, H ▸ reduce.red, reduce.red⟩ /-- A word and its maximal reduction correspond to the same element of the free group. -/ theorem reduce.self : mk (reduce L) = mk L := reduce.exact reduce.idem /-- If words `w₁ w₂` are such that `w₁` reduces to `w₂`, then `w₂` reduces to the maximal reduction of `w₁`. -/ theorem reduce.rev (H : red L₁ L₂) : red L₂ (reduce L₁) := (reduce.eq_of_red H).symm ▸ reduce.red /-- The function that sends an element of the free group to its maximal reduction. -/ def to_word : free_group α → list (α × bool) := quot.lift reduce $ λ L₁ L₂ H, reduce.step.eq H def to_word.mk : ∀{x : free_group α}, mk (to_word x) = x := by rintros ⟨L⟩; exact reduce.self def to_word.inj : ∀(x y : free_group α), to_word x = to_word y → x = y := by rintros ⟨L₁⟩ ⟨L₂⟩; exact reduce.exact /-- Constructive Church-Rosser theorem (compare `church_rosser`). -/ def reduce.church_rosser (H12 : red L₁ L₂) (H13 : red L₁ L₃) : { L₄ // red L₂ L₄ ∧ red L₃ L₄ } := ⟨reduce L₁, reduce.rev H12, reduce.rev H13⟩ instance : decidable_eq (free_group α) := function.injective.decidable_eq to_word.inj instance red.decidable_rel : decidable_rel (@red α) | [] [] := is_true red.refl | [] (hd2::tl2) := is_false $ λ H, list.no_confusion (red.nil_iff.1 H) | ((x,b)::tl) [] := match red.decidable_rel tl [(x, bnot b)] with | is_true H := is_true $ red.trans (red.cons_cons H) $ (@red.step.bnot _ [] [] _ _).to_red | is_false H := is_false $ λ H2, H $ red.cons_nil_iff_singleton.1 H2 end | ((x1,b1)::tl1) ((x2,b2)::tl2) := if h : (x1, b1) = (x2, b2) then match red.decidable_rel tl1 tl2 with | is_true H := is_true $ h ▸ red.cons_cons H | is_false H := is_false $ λ H2, H $ h ▸ (red.cons_cons_iff _).1 $ H2 end else match red.decidable_rel tl1 ((x1,bnot b1)::(x2,b2)::tl2) with | is_true H := is_true $ (red.cons_cons H).tail red.step.cons_bnot | is_false H := is_false $ λ H2, H $ red.inv_of_red_of_ne h H2 end /-- A list containing every word that `w₁` reduces to. -/ def red.enum (L₁ : list (α × bool)) : list (list (α × bool)) := list.filter (λ L₂, red L₁ L₂) (list.sublists L₁) theorem red.enum.sound (H : L₂ ∈ red.enum L₁) : red L₁ L₂ := list.of_mem_filter H theorem red.enum.complete (H : red L₁ L₂) : L₂ ∈ red.enum L₁ := list.mem_filter_of_mem (list.mem_sublists.2 $ red.sublist H) H instance : fintype { L₂ // red L₁ L₂ } := fintype.subtype (list.to_finset $ red.enum L₁) $ λ L₂, ⟨λ H, red.enum.sound $ list.mem_to_finset.1 H, λ H, list.mem_to_finset.2 $ red.enum.complete H⟩ end reduce end free_group
aa9b6655c2a881dc3c58ea0fd4bad2006bb6862f
2c096fdfecf64e46ea7bc6ce5521f142b5926864
/src/Lean/MetavarContext.lean
37ad643c03e8dd9a66b14ce2a419fb9f647e0766
[ "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
Kha/lean4
1005785d2c8797ae266a303968848e5f6ce2fe87
b99e11346948023cd6c29d248cd8f3e3fb3474cf
refs/heads/master
1,693,355,498,027
1,669,080,461,000
1,669,113,138,000
184,748,176
0
0
Apache-2.0
1,665,995,520,000
1,556,884,930,000
Lean
UTF-8
Lean
false
false
63,836
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Util.MonadCache import Lean.LocalContext namespace Lean /-! The metavariable context stores metavariable declarations and their assignments. It is used in the elaborator, tactic framework, unifier (aka `isDefEq`), and type class resolution (TC). First, we list all the requirements imposed by these modules. - We may invoke TC while executing `isDefEq`. We need this feature to be able to solve unification problems such as: ``` f ?a (ringAdd ?s) ?x ?y =?= f Int intAdd n m ``` where `(?a : Type) (?s : Ring ?a) (?x ?y : ?a)` During `isDefEq` (i.e., unification), it will need to solve the constrain ``` ringAdd ?s =?= intAdd ``` We say `ringAdd ?s` is stuck because it cannot be reduced until we synthesize the term `?s : Ring ?a` using TC. This can be done since we have assigned `?a := Int` when solving `?a =?= Int`. - TC uses `isDefEq`, and `isDefEq` may create TC problems as shown above. Thus, we may have nested TC problems. - `isDefEq` extends the local context when going inside binders. Thus, the local context for nested TC may be an extension of the local context for outer TC. - TC should not assign metavariables created by the elaborator, simp, tactic framework, and outer TC problems. Reason: TC commits to the first solution it finds. Consider the TC problem `Coe Nat ?x`, where `?x` is a metavariable created by the caller. There are many solutions to this problem (e.g., `?x := Int`, `?x := Real`, ...), and it doesn’t make sense to commit to the first one since TC does not know the constraints the caller may impose on `?x` after the TC problem is solved. Remark: we claim it is not feasible to make the whole system backtrackable, and allow the caller to backtrack back to TC and ask it for another solution if the first one found did not work. We claim it would be too inefficient. - TC metavariables should not leak outside of TC. Reason: we want to get rid of them after we synthesize the instance. - `simp` invokes `isDefEq` for matching the left-hand-side of equations to terms in our goal. Thus, it may invoke TC indirectly. - In Lean3, we didn’t have to create a fresh pattern for trying to match the left-hand-side of equations when executing `simp`. We had a mechanism called "tmp" metavariables. It avoided this overhead, but it created many problems since `simp` may indirectly call TC which may recursively call TC. Moreover, we may want to allow TC to invoke tactics in the future. Thus, when `simp` invokes `isDefEq`, it may indirectly invoke a tactic and `simp` itself. The Lean3 approach assumed that metavariables were short-lived, this is not true in Lean4, and to some extent was also not true in Lean3 since `simp`, in principle, could trigger an arbitrary number of nested TC problems. - Here are some possible call stack traces we could have in Lean3 (and Lean4). ``` Elaborator (-> TC -> isDefEq)+ Elaborator -> isDefEq (-> TC -> isDefEq)* Elaborator -> simp -> isDefEq (-> TC -> isDefEq)* ``` In Lean4, TC may also invoke tactics in the future. - In Lean3 and Lean4, TC metavariables are not really short-lived. We solve an arbitrary number of unification problems, and we may have nested TC invocations. - TC metavariables do not share the same local context even in the same invocation. In the C++ and Lean implementations we use a trick to ensure they do: https://github.com/leanprover/lean/blob/92826917a252a6092cffaf5fc5f1acb1f8cef379/src/library/type_context.cpp#L3583-L3594 - Metavariables may be natural, synthetic or syntheticOpaque. a) Natural metavariables may be assigned by unification (i.e., `isDefEq`). b) Synthetic metavariables may still be assigned by unification, but whenever possible `isDefEq` will avoid the assignment. For example, if we have the unification constraint `?m =?= ?n`, where `?m` is synthetic, but `?n` is not, `isDefEq` solves it by using the assignment `?n := ?m`. We use synthetic metavariables for type class resolution. Any module that creates synthetic metavariables, must also check whether they have been assigned by `isDefEq`, and then still synthesize them, and check whether the synthesized result is compatible with the one assigned by `isDefEq`. c) SyntheticOpaque metavariables are never assigned by `isDefEq`. That is, the constraint `?n =?= Nat.succ Nat.zero` always fail if `?n` is a syntheticOpaque metavariable. This kind of metavariable is created by tactics such as `intro`. Reason: in the tactic framework, subgoals as represented as metavariables, and a subgoal `?n` is considered as solved whenever the metavariable is assigned. This distinction was not precise in Lean3 and produced counterintuitive behavior. For example, the following hack was added in Lean3 to work around one of these issues: https://github.com/leanprover/lean/blob/92826917a252a6092cffaf5fc5f1acb1f8cef379/src/library/type_context.cpp#L2751 - When creating lambda/forall expressions, we need to convert/abstract free variables and convert them to bound variables. Now, suppose we a trying to create a lambda/forall expression by abstracting free variable `xs` and a term `t[?m]` which contains a metavariable `?m`, and the local context of `?m` contains `xs`. The term ``` fun xs => t[?m] ``` will be ill-formed if we later assign a term `s` to `?m`, and `s` contains free variables in `xs`. We address this issue by changing the free variable abstraction procedure. We consider two cases: `?m` is natural, `?m` is synthetic. Assume the type of `?m` is `A[xs]`. Then, in both cases we create an auxiliary metavariable `?n` with type `forall xs => A[xs]`, and local context := local context of `?m` - `xs`. In both cases, we produce the term `fun xs => t[?n xs]` 1- If `?m` is natural or synthetic, then we assign `?m := ?n xs`, and we produce the term `fun xs => t[?n xs]` 2- If `?m` is syntheticOpaque, then we mark `?n` as a syntheticOpaque variable. However, `?n` is managed by the metavariable context itself. We say we have a "delayed assignment" `?n xs := ?m`. That is, after a term `s` is assigned to `?m`, and `s` does not contain metavariables, we replace any occurrence `?n ts` with `s[xs := ts]`. Gruesome details: - When we create the type `forall xs => A` for `?n`, we may encounter the same issue if `A` contains metavariables. So, the process above is recursive. We claim it terminates because we keep creating new metavariables with smaller local contexts. - Suppose, we have `t[?m]` and we want to create a let-expression by abstracting a let-decl free variable `x`, and the local context of `?m` contains `x`. Similarly to the previous case ``` let x : T := v; t[?m] ``` will be ill-formed if we later assign a term `s` to `?m`, and `s` contains free variable `x`. Again, assume the type of `?m` is `A[x]`. 1- If `?m` is natural or synthetic, then we create `?n : (let x : T := v; A[x])` with and local context := local context of `?m` - `x`, we assign `?m := ?n`, and produce the term `let x : T := v; t[?n]`. That is, we are just making sure `?n` must never be assigned to a term containing `x`. 2- If `?m` is syntheticOpaque, we create a fresh syntheticOpaque `?n` with type `?n : T -> (let x : T := v; A[x])` and local context := local context of `?m` - `x`, create the delayed assignment `?n #[x] := ?m`, and produce the term `let x : T := v; t[?n x]`. Now suppose we assign `s` to `?m`. We do not assign the term `fun (x : T) => s` to `?n`, since `fun (x : T) => s` may not even be type correct. Instead, we just replace applications `?n r` with `s[x/r]`. The term `r` may not necessarily be a bound variable. For example, a tactic may have reduced `let x : T := v; t[?n x]` into `t[?n v]`. We are essentially using the pair "delayed assignment + application" to implement a delayed substitution. - We use TC for implementing coercions. Both Joe Hendrix and Reid Barton reported a nasty limitation. In Lean3, TC will not be used if there are metavariables in the TC problem. For example, the elaborator will not try to synthesize `Coe Nat ?x`. This is good, but this constraint is too strict for problems such as `Coe (Vector Bool ?n) (BV ?n)`. The coercion exists independently of `?n`. Thus, during TC, we want `isDefEq` to throw an exception instead of return `false` whenever it tries to assign a metavariable owned by its caller. The idea is to sign to the caller that it cannot solve the TC problem at this point, and more information is needed. That is, the caller must make progress an assign its metavariables before trying to invoke TC again. In Lean4, we are using a simpler design for the `MetavarContext`. - No distinction between temporary and regular metavariables. - Metavariables have a `depth` Nat field. - MetavarContext also has a `depth` field. - We bump the `MetavarContext` depth when we create a nested problem. Example: Elaborator (depth = 0) -> Simplifier matcher (depth = 1) -> TC (level = 2) -> TC (level = 3) -> ... - When `MetavarContext` is at depth N, `isDefEq` does not assign variables from `depth < N`. - Metavariables from depth N+1 must be fully assigned before we return to level N. - New design even allows us to invoke tactics from TC. * Main concern We don't have tmp metavariables anymore in Lean4. Thus, before trying to match the left-hand-side of an equation in `simp`. We first must bump the level of the `MetavarContext`, create fresh metavariables, then create a new pattern by replacing the free variable on the left-hand-side with these metavariables. We are hoping to minimize this overhead by - Using better indexing data structures in `simp`. They should reduce the number of time `simp` must invoke `isDefEq`. - Implementing `isDefEqApprox` which ignores metavariables and returns only `false` or `undef`. It is a quick filter that allows us to fail quickly and avoid the creation of new fresh metavariables, and a new pattern. - Adding built-in support for arithmetic, Logical connectives, etc. Thus, we avoid a bunch of lemmas in the simp set. - Adding support for AC-rewriting. In Lean3, users use AC lemmas as rewriting rules for "sorting" terms. This is inefficient, requires a quadratic number of rewrite steps, and does not preserve the structure of the goal. The temporary metavariables were also used in the "app builder" module used in Lean3. The app builder uses `isDefEq`. So, it could, in principle, invoke an arbitrary number of nested TC problems. However, in Lean3, all app builder uses are controlled. That is, it is mainly used to synthesize implicit arguments using very simple unification and/or non-nested TC. So, if the "app builder" becomes a bottleneck without tmp metavars, we may solve the issue by implementing `isDefEqCheap` that never invokes TC and uses tmp metavars. -/ /-- `LocalInstance` represents a local typeclass instance registered by and for the elaborator. It stores the name of the typeclass in `className`, and the concrete typeclass instance in `fvar`. Note that the kernel does not care about this information, since typeclasses are entirely eliminated during elaboration. -/ structure LocalInstance where className : Name fvar : Expr deriving Inhabited abbrev LocalInstances := Array LocalInstance instance : BEq LocalInstance where beq i₁ i₂ := i₁.fvar == i₂.fvar /-- Remove local instance with the given `fvarId`. Do nothing if `localInsts` does not contain any free variable with id `fvarId`. -/ def LocalInstances.erase (localInsts : LocalInstances) (fvarId : FVarId) : LocalInstances := match localInsts.findIdx? (fun inst => inst.fvar.fvarId! == fvarId) with | some idx => localInsts.eraseIdx idx | _ => localInsts /-- A kind for the metavariable that determines its unification behaviour. For more information see the large comment at the beginning of this file. -/ inductive MetavarKind where /-- Normal unification behaviour -/ | natural /-- `isDefEq` avoids assignment -/ | synthetic /-- Never assigned by isDefEq -/ | syntheticOpaque deriving Inhabited, Repr def MetavarKind.isSyntheticOpaque : MetavarKind → Bool | MetavarKind.syntheticOpaque => true | _ => false def MetavarKind.isNatural : MetavarKind → Bool | MetavarKind.natural => true | _ => false /-- Information about a metavariable. -/ structure MetavarDecl where /-- A user-friendly name for the metavariable. If anonymous then there is no such name. -/ userName : Name := Name.anonymous /-- The local context containing the free variables that the mvar is permitted to depend upon. -/ lctx : LocalContext /-- The type of the metavarible, in the given `lctx`. -/ type : Expr /-- The nesting depth of this metavariable. We do not want unification subproblems to influence the results of parent problems. The depth keeps track of this information and ensures that unification subproblems cannot leak information out, by unifying based on depth. -/ depth : Nat localInstances : LocalInstances kind : MetavarKind /-- See comment at `CheckAssignment` `Meta/ExprDefEq.lean` -/ numScopeArgs : Nat := 0 /-- We use this field to track how old a metavariable is. It is set using a counter at `MetavarContext` -/ index : Nat deriving Inhabited /-- A delayed assignment for a metavariable `?m`. It represents an assignment of the form `?m := (fun fvars => (mkMVar mvarIdPending))`. `mvarIdPending` is a `syntheticOpaque` metavariable that has not been synthesized yet. The delayed assignment becomes a real one as soon as `mvarIdPending` has been fully synthesized. `fvars` are variables in the `mvarIdPending` local context. See the comment below `assignDelayedMVar ` for the rationale of delayed assignments. Recall that we use a locally nameless approach when dealing with binders. Suppose we are trying to synthesize `?n` in the expression `e`, in the context of `(fun x => e)`. The metavariable `?n` might depend on the bound variable `x`. However, since we are locally nameless, the bound variable `x` is in fact represented by some free variable `fvar_x`. Thus, when we exit the scope, we must rebind the value of `fvar_x` in `?n` to the de-bruijn index of the bound variable `x`. -/ structure DelayedMetavarAssignment where fvars : Array Expr mvarIdPending : MVarId /-- The metavariable context is a set of metavariable declarations and their assignments. For more information on specifics see the comment in the file that `MetavarContext` is defined in. -/ structure MetavarContext where /-- Depth is used to control whether an mvar can be assigned in unification. -/ depth : Nat := 0 /-- Counter for setting the field `index` at `MetavarDecl` -/ mvarCounter : Nat := 0 lDepth : PersistentHashMap LMVarId Nat := {} /-- Metavariable declarations. -/ decls : PersistentHashMap MVarId MetavarDecl := {} /-- Index mapping user-friendly names to ids. -/ userNames : PersistentHashMap Name MVarId := {} /-- Assignment table for universe level metavariables.-/ lAssignment : PersistentHashMap LMVarId Level := {} /-- Assignment table for expression metavariables.-/ eAssignment : PersistentHashMap MVarId Expr := {} /-- Assignment table for delayed abstraction metavariables. For more information about delayed abstraction, see the docstring for `DelayedMetavarAssignment`. -/ dAssignment : PersistentHashMap MVarId DelayedMetavarAssignment := {} /-- A monad with a stateful metavariable context, defining `getMCtx` and `modifyMCtx`. -/ class MonadMCtx (m : Type → Type) where getMCtx : m MetavarContext modifyMCtx : (MetavarContext → MetavarContext) → m Unit export MonadMCtx (getMCtx modifyMCtx) @[always_inline] instance (m n) [MonadLift m n] [MonadMCtx m] : MonadMCtx n where getMCtx := liftM (getMCtx : m _) modifyMCtx := fun f => liftM (modifyMCtx f : m _) abbrev setMCtx [MonadMCtx m] (mctx : MetavarContext) : m Unit := modifyMCtx fun _ => mctx abbrev getLevelMVarAssignment? [Monad m] [MonadMCtx m] (mvarId : LMVarId) : m (Option Level) := return (← getMCtx).lAssignment.find? mvarId def MetavarContext.getExprAssignmentCore? (m : MetavarContext) (mvarId : MVarId) : Option Expr := m.eAssignment.find? mvarId def getExprMVarAssignment? [Monad m] [MonadMCtx m] (mvarId : MVarId) : m (Option Expr) := return (← getMCtx).getExprAssignmentCore? mvarId def getDelayedMVarAssignment? [Monad m] [MonadMCtx m] (mvarId : MVarId) : m (Option DelayedMetavarAssignment) := return (← getMCtx).dAssignment.find? mvarId /-- Given a sequence of delayed assignments ``` mvarId₁ := mvarId₂ ...; ... mvarIdₙ := mvarId_root ... -- where `mvarId_root` is not delayed assigned ``` in `mctx`, `getDelayedRoot mctx mvarId₁` return `mvarId_root`. If `mvarId₁` is not delayed assigned then return `mvarId₁` -/ partial def getDelayedMVarRoot [Monad m] [MonadMCtx m] (mvarId : MVarId) : m MVarId := do match (← getDelayedMVarAssignment? mvarId) with | some d => getDelayedMVarRoot d.mvarIdPending | none => return mvarId def isLevelMVarAssigned [Monad m] [MonadMCtx m] (mvarId : LMVarId) : m Bool := return (← getMCtx).lAssignment.contains mvarId /-- Return `true` if the give metavariable is already assigned. -/ def _root_.Lean.MVarId.isAssigned [Monad m] [MonadMCtx m] (mvarId : MVarId) : m Bool := return (← getMCtx).eAssignment.contains mvarId @[deprecated MVarId.isAssigned] def isExprMVarAssigned [Monad m] [MonadMCtx m] (mvarId : MVarId) : m Bool := do mvarId.isAssigned def _root_.Lean.MVarId.isDelayedAssigned [Monad m] [MonadMCtx m] (mvarId : MVarId) : m Bool := return (← getMCtx).dAssignment.contains mvarId @[deprecated MVarId.isDelayedAssigned] def isMVarDelayedAssigned [Monad m] [MonadMCtx m] (mvarId : MVarId) : m Bool := do mvarId.isDelayedAssigned def isLevelMVarAssignable [Monad m] [MonadMCtx m] (mvarId : LMVarId) : m Bool := do let mctx ← getMCtx match mctx.lDepth.find? mvarId with | some d => return d == mctx.depth | _ => panic! "unknown universe metavariable" def MetavarContext.getDecl (mctx : MetavarContext) (mvarId : MVarId) : MetavarDecl := match mctx.decls.find? mvarId with | some decl => decl | none => panic! "unknown metavariable" def _root_.Lean.MVarId.isAssignable [Monad m] [MonadMCtx m] (mvarId : MVarId) : m Bool := do let mctx ← getMCtx let decl := mctx.getDecl mvarId return decl.depth == mctx.depth @[deprecated MVarId.isAssignable] def isExprMVarAssignable [Monad m] [MonadMCtx m] (mvarId : MVarId) : m Bool := do mvarId.isAssignable /-- Return true iff the given level contains an assigned metavariable. -/ def hasAssignedLevelMVar [Monad m] [MonadMCtx m] : Level → m Bool | .succ lvl => pure lvl.hasMVar <&&> hasAssignedLevelMVar lvl | .max lvl₁ lvl₂ => (pure lvl₁.hasMVar <&&> hasAssignedLevelMVar lvl₁) <||> (pure lvl₂.hasMVar <&&> hasAssignedLevelMVar lvl₂) | .imax lvl₁ lvl₂ => (pure lvl₁.hasMVar <&&> hasAssignedLevelMVar lvl₁) <||> (pure lvl₂.hasMVar <&&> hasAssignedLevelMVar lvl₂) | .mvar mvarId => isLevelMVarAssigned mvarId | .zero => pure false | .param _ => pure false /-- Return `true` iff expression contains assigned (level/expr) metavariables or delayed assigned mvars -/ def hasAssignedMVar [Monad m] [MonadMCtx m] : Expr → m Bool | .const _ lvls => lvls.anyM hasAssignedLevelMVar | .sort lvl => hasAssignedLevelMVar lvl | .app f a => (pure f.hasMVar <&&> hasAssignedMVar f) <||> (pure a.hasMVar <&&> hasAssignedMVar a) | .letE _ t v b _ => (pure t.hasMVar <&&> hasAssignedMVar t) <||> (pure v.hasMVar <&&> hasAssignedMVar v) <||> (pure b.hasMVar <&&> hasAssignedMVar b) | .forallE _ d b _ => (pure d.hasMVar <&&> hasAssignedMVar d) <||> (pure b.hasMVar <&&> hasAssignedMVar b) | .lam _ d b _ => (pure d.hasMVar <&&> hasAssignedMVar d) <||> (pure b.hasMVar <&&> hasAssignedMVar b) | .fvar _ => return false | .bvar _ => return false | .lit _ => return false | .mdata _ e => pure e.hasMVar <&&> hasAssignedMVar e | .proj _ _ e => pure e.hasMVar <&&> hasAssignedMVar e | .mvar mvarId => mvarId.isAssigned <||> mvarId.isDelayedAssigned /-- Return true iff the given level contains a metavariable that can be assigned. -/ def hasAssignableLevelMVar [Monad m] [MonadMCtx m] : Level → m Bool | .succ lvl => pure lvl.hasMVar <&&> hasAssignableLevelMVar lvl | .max lvl₁ lvl₂ => (pure lvl₁.hasMVar <&&> hasAssignableLevelMVar lvl₁) <||> (pure lvl₂.hasMVar <&&> hasAssignableLevelMVar lvl₂) | .imax lvl₁ lvl₂ => (pure lvl₁.hasMVar <&&> hasAssignableLevelMVar lvl₁) <||> (pure lvl₂.hasMVar <&&> hasAssignableLevelMVar lvl₂) | .mvar mvarId => isLevelMVarAssignable mvarId | .zero => return false | .param _ => return false /-- Return `true` iff expression contains a metavariable that can be assigned. -/ def hasAssignableMVar [Monad m] [MonadMCtx m] : Expr → m Bool | .const _ lvls => lvls.anyM hasAssignableLevelMVar | .sort lvl => hasAssignableLevelMVar lvl | .app f a => (pure f.hasMVar <&&> hasAssignableMVar f) <||> (pure a.hasMVar <&&> hasAssignableMVar a) | .letE _ t v b _ => (pure t.hasMVar <&&> hasAssignableMVar t) <||> (pure v.hasMVar <&&> hasAssignableMVar v) <||> (pure b.hasMVar <&&> hasAssignableMVar b) | .forallE _ d b _ => (pure d.hasMVar <&&> hasAssignableMVar d) <||> (pure b.hasMVar <&&> hasAssignableMVar b) | .lam _ d b _ => (pure d.hasMVar <&&> hasAssignableMVar d) <||> (pure b.hasMVar <&&> hasAssignableMVar b) | .fvar _ => return false | .bvar _ => return false | .lit _ => return false | .mdata _ e => pure e.hasMVar <&&> hasAssignableMVar e | .proj _ _ e => pure e.hasMVar <&&> hasAssignableMVar e | .mvar mvarId => mvarId.isAssignable /-- Add `mvarId := u` to the universe metavariable assignment. This method does not check whether `mvarId` is already assigned, nor it checks whether a cycle is being introduced. This is a low-level API, and it is safer to use `isLevelDefEq (mkLevelMVar mvarId) u`. -/ def assignLevelMVar [MonadMCtx m] (mvarId : LMVarId) (val : Level) : m Unit := modifyMCtx fun m => { m with lAssignment := m.lAssignment.insert mvarId val } /-- Add `mvarId := x` to the metavariable assignment. This method does not check whether `mvarId` is already assigned, nor it checks whether a cycle is being introduced, or whether the expression has the right type. This is a low-level API, and it is safer to use `isDefEq (mkMVar mvarId) x`. -/ def _root_.Lean.MVarId.assign [MonadMCtx m] (mvarId : MVarId) (val : Expr) : m Unit := modifyMCtx fun m => { m with eAssignment := m.eAssignment.insert mvarId val } @[deprecated MVarId.assign] def assignExprMVar [MonadMCtx m] (mvarId : MVarId) (val : Expr) : m Unit := mvarId.assign val def assignDelayedMVar [MonadMCtx m] (mvarId : MVarId) (fvars : Array Expr) (mvarIdPending : MVarId) : m Unit := modifyMCtx fun m => { m with dAssignment := m.dAssignment.insert mvarId { fvars, mvarIdPending } } /-! Notes on artificial eta-expanded terms due to metavariables. We try avoid synthetic terms such as `((fun x y => t) a b)` in the output produced by the elaborator. This kind of term may be generated when instantiating metavariable assignments. This module tries to avoid their generation because they often introduce unnecessary dependencies and may affect automation. When elaborating terms, we use metavariables to represent "holes". Each hole has a context which includes all free variables that may be used to "fill" the hole. Suppose, we create a metavariable (hole) `?m : Nat` in a context containing `(x : Nat) (y : Nat) (b : Bool)`, then we can assign terms such as `x + y` to `?m` since `x` and `y` are in the context used to create `?m`. Now, suppose we have the term `?m + 1` and we want to create the lambda expression `fun x => ?m + 1`. This term is not correct since we may assign to `?m` a term containing `x`. We address this issue by create a synthetic metavariable `?n : Nat → Nat` and adding the delayed assignment `?n #[x] := ?m`, and the term `fun x => ?n x + 1`. When we later assign a term `t[x]` to `?m`, `fun x => t[x]` is assigned to `?n`, and if we substitute it at `fun x => ?n x + 1`, we produce `fun x => ((fun x => t[x]) x) + 1`. To avoid this term eta-expanded term, we apply beta-reduction when instantiating metavariable assignments in this module. This operation is performed at `instantiateExprMVars`, `elimMVarDeps`, and `levelMVarToParam`. -/ partial def instantiateLevelMVars [Monad m] [MonadMCtx m] : Level → m Level | lvl@(Level.succ lvl₁) => return Level.updateSucc! lvl (← instantiateLevelMVars lvl₁) | lvl@(Level.max lvl₁ lvl₂) => return Level.updateMax! lvl (← instantiateLevelMVars lvl₁) (← instantiateLevelMVars lvl₂) | lvl@(Level.imax lvl₁ lvl₂) => return Level.updateIMax! lvl (← instantiateLevelMVars lvl₁) (← instantiateLevelMVars lvl₂) | lvl@(Level.mvar mvarId) => do match (← getLevelMVarAssignment? mvarId) with | some newLvl => if !newLvl.hasMVar then pure newLvl else do let newLvl' ← instantiateLevelMVars newLvl assignLevelMVar mvarId newLvl' pure newLvl' | none => pure lvl | lvl => pure lvl /-- instantiateExprMVars main function -/ partial def instantiateExprMVars [Monad m] [MonadMCtx m] [STWorld ω m] [MonadLiftT (ST ω) m] (e : Expr) : MonadCacheT ExprStructEq Expr m Expr := if !e.hasMVar then pure e else checkCache { val := e : ExprStructEq } fun _ => do match e with | .proj _ _ s => return e.updateProj! (← instantiateExprMVars s) | .forallE _ d b _ => return e.updateForallE! (← instantiateExprMVars d) (← instantiateExprMVars b) | .lam _ d b _ => return e.updateLambdaE! (← instantiateExprMVars d) (← instantiateExprMVars b) | .letE _ t v b _ => return e.updateLet! (← instantiateExprMVars t) (← instantiateExprMVars v) (← instantiateExprMVars b) | .const _ lvls => return e.updateConst! (← lvls.mapM instantiateLevelMVars) | .sort lvl => return e.updateSort! (← instantiateLevelMVars lvl) | .mdata _ b => return e.updateMData! (← instantiateExprMVars b) | .app .. => e.withApp fun f args => do let instArgs (f : Expr) : MonadCacheT ExprStructEq Expr m Expr := do let args ← args.mapM instantiateExprMVars pure (mkAppN f args) let instApp : MonadCacheT ExprStructEq Expr m Expr := do let wasMVar := f.isMVar let f ← instantiateExprMVars f if wasMVar && f.isLambda then /- Some of the arguments in args are irrelevant after we beta reduce. -/ instantiateExprMVars (f.betaRev args.reverse) else instArgs f match f with | .mvar mvarId => match (← getDelayedMVarAssignment? mvarId) with | none => instApp | some { fvars, mvarIdPending } => /- Apply "delayed substitution" (i.e., delayed assignment + application). That is, `f` is some metavariable `?m`, that is delayed assigned to `val`. If after instantiating `val`, we obtain `newVal`, and `newVal` does not contain metavariables, we replace the free variables `fvars` in `newVal` with the first `fvars.size` elements of `args`. -/ if fvars.size > args.size then /- We don't have sufficient arguments for instantiating the free variables `fvars`. This can only happy if a tactic or elaboration function is not implemented correctly. We decided to not use `panic!` here and report it as an error in the frontend when we are checking for unassigned metavariables in an elaborated term. -/ instArgs f else let newVal ← instantiateExprMVars (mkMVar mvarIdPending) if newVal.hasExprMVar then instArgs f else do let args ← args.mapM instantiateExprMVars /- Example: suppose we have `?m t1 t2 t3` That is, `f := ?m` and `args := #[t1, t2, t3]` Morever, `?m` is delayed assigned `?m #[x, y] := f x y` where, `fvars := #[x, y]` and `newVal := f x y`. After abstracting `newVal`, we have `f (Expr.bvar 0) (Expr.bvar 1)`. After `instantiaterRevRange 0 2 args`, we have `f t1 t2`. After `mkAppRange 2 3`, we have `f t1 t2 t3` -/ let newVal := newVal.abstract fvars let result := newVal.instantiateRevRange 0 fvars.size args let result := mkAppRange result fvars.size args.size args pure result | _ => instApp | e@(.mvar mvarId) => checkCache { val := e : ExprStructEq } fun _ => do match (← getExprMVarAssignment? mvarId) with | some newE => do let newE' ← instantiateExprMVars newE mvarId.assign newE' pure newE' | none => pure e | e => pure e instance : MonadMCtx (StateRefT MetavarContext (ST ω)) where getMCtx := get modifyMCtx := modify def instantiateMVarsCore (mctx : MetavarContext) (e : Expr) : Expr × MetavarContext := let instantiate {ω} (e : Expr) : (MonadCacheT ExprStructEq Expr <| StateRefT MetavarContext (ST ω)) Expr := instantiateExprMVars e runST fun _ => instantiate e |>.run |>.run mctx def instantiateMVars [Monad m] [MonadMCtx m] (e : Expr) : m Expr := do if !e.hasMVar then return e else let (r, mctx) := instantiateMVarsCore (← getMCtx) e modifyMCtx fun _ => mctx return r def instantiateLCtxMVars [Monad m] [MonadMCtx m] (lctx : LocalContext) : m LocalContext := lctx.foldlM (init := {}) fun lctx ldecl => do match ldecl with | .cdecl _ fvarId userName type bi k => let type ← instantiateMVars type return lctx.mkLocalDecl fvarId userName type bi k | .ldecl _ fvarId userName type value nonDep k => let type ← instantiateMVars type let value ← instantiateMVars value return lctx.mkLetDecl fvarId userName type value nonDep k def instantiateMVarDeclMVars [Monad m] [MonadMCtx m] (mvarId : MVarId) : m Unit := do let mvarDecl := (← getMCtx).getDecl mvarId let lctx ← instantiateLCtxMVars mvarDecl.lctx let type ← instantiateMVars mvarDecl.type modifyMCtx fun mctx => { mctx with decls := mctx.decls.insert mvarId { mvarDecl with lctx, type } } def instantiateLocalDeclMVars [Monad m] [MonadMCtx m] (localDecl : LocalDecl) : m LocalDecl := do match localDecl with | .cdecl idx id n type bi k => return .cdecl idx id n (← instantiateMVars type) bi k | .ldecl idx id n type val nonDep k => return .ldecl idx id n (← instantiateMVars type) (← instantiateMVars val) nonDep k namespace DependsOn structure State where visited : ExprSet := {} mctx : MetavarContext private abbrev M := StateM State instance : MonadMCtx M where getMCtx := return (← get).mctx modifyMCtx f := modify fun s => { s with mctx := f s.mctx } private def shouldVisit (e : Expr) : M Bool := do if !e.hasMVar && !e.hasFVar then return false else if (← get).visited.contains e then return false else modify fun s => { s with visited := s.visited.insert e } return true @[specialize] private partial def dep (pf : FVarId → Bool) (pm : MVarId → Bool) (e : Expr) : M Bool := let rec visit (e : Expr) : M Bool := do if !(← shouldVisit e) then pure false else visitMain e, visitApp : Expr → M Bool | .app f a .. => visitApp f <||> visit a | e => visit e, visitMain : Expr → M Bool | .proj _ _ s => visit s | .forallE _ d b _ => visit d <||> visit b | .lam _ d b _ => visit d <||> visit b | .letE _ t v b _ => visit t <||> visit v <||> visit b | .mdata _ b => visit b | e@(.app ..) => do let f := e.getAppFn if f.isMVar then let e' ← instantiateMVars e if e'.getAppFn != f then visitMain e' else if pm f.mvarId! then return true else visitApp e else visitApp e | .mvar mvarId => do match (← getExprMVarAssignment? mvarId) with | some a => visit a | none => if pm mvarId then return true else let lctx := (← getMCtx).getDecl mvarId |>.lctx return lctx.any fun decl => pf decl.fvarId | .fvar fvarId => return pf fvarId | _ => pure false visit e @[inline] partial def main (pf : FVarId → Bool) (pm : MVarId → Bool) (e : Expr) : M Bool := if !e.hasFVar && !e.hasMVar then pure false else dep pf pm e end DependsOn /-- Return `true` iff `e` depends on a free variable `x` s.t. `pf x` is `true`, or an unassigned metavariable `?m` s.t. `pm ?m` is true. For each metavariable `?m` (that does not satisfy `pm` occurring in `x` 1- If `?m := t`, then we visit `t` looking for `x` 2- If `?m` is unassigned, then we consider the worst case and check whether `x` is in the local context of `?m`. This case is a "may dependency". That is, we may assign a term `t` to `?m` s.t. `t` contains `x`. -/ @[inline] def findExprDependsOn [Monad m] [MonadMCtx m] (e : Expr) (pf : FVarId → Bool := fun _ => false) (pm : MVarId → Bool := fun _ => false) : m Bool := do let (result, { mctx, .. }) := DependsOn.main pf pm e |>.run { mctx := (← getMCtx) } setMCtx mctx return result /-- Similar to `findExprDependsOn`, but checks the expressions in the given local declaration depends on a free variable `x` s.t. `pf x` is `true` or an unassigned metavariable `?m` s.t. `pm ?m` is true. -/ @[inline] def findLocalDeclDependsOn [Monad m] [MonadMCtx m] (localDecl : LocalDecl) (pf : FVarId → Bool := fun _ => false) (pm : MVarId → Bool := fun _ => false) : m Bool := do match localDecl with | .cdecl (type := t) .. => findExprDependsOn t pf pm | .ldecl (type := t) (value := v) .. => let (result, { mctx, .. }) := (DependsOn.main pf pm t <||> DependsOn.main pf pm v).run { mctx := (← getMCtx) } setMCtx mctx return result def exprDependsOn [Monad m] [MonadMCtx m] (e : Expr) (fvarId : FVarId) : m Bool := findExprDependsOn e (fvarId == ·) /-- Return true iff `e` depends on the free variable `fvarId` -/ def dependsOn [Monad m] [MonadMCtx m] (e : Expr) (fvarId : FVarId) : m Bool := exprDependsOn e fvarId /-- Return true iff `e` depends on the free variable `fvarId` -/ def localDeclDependsOn [Monad m] [MonadMCtx m] (localDecl : LocalDecl) (fvarId : FVarId) : m Bool := findLocalDeclDependsOn localDecl (fvarId == ·) /-- Similar to `exprDependsOn`, but `x` can be a free variable or an unassigned metavariable. -/ def exprDependsOn' [Monad m] [MonadMCtx m] (e : Expr) (x : Expr) : m Bool := if x.isFVar then findExprDependsOn e (x.fvarId! == ·) else if x.isMVar then findExprDependsOn e (pm := (x.mvarId! == ·)) else return false /-- Similar to `localDeclDependsOn`, but `x` can be a free variable or an unassigned metavariable. -/ def localDeclDependsOn' [Monad m] [MonadMCtx m] (localDecl : LocalDecl) (x : Expr) : m Bool := if x.isFVar then findLocalDeclDependsOn localDecl (x.fvarId! == ·) else if x.isMVar then findLocalDeclDependsOn localDecl (pm := (x.mvarId! == ·)) else return false /-- Return true iff `e` depends on a free variable `x` s.t. `pf x`, or an unassigned metavariable `?m` s.t. `pm ?m` is true. -/ def dependsOnPred [Monad m] [MonadMCtx m] (e : Expr) (pf : FVarId → Bool := fun _ => false) (pm : MVarId → Bool := fun _ => false) : m Bool := findExprDependsOn e pf pm /-- Return true iff the local declaration `localDecl` depends on a free variable `x` s.t. `pf x`, an unassigned metavariable `?m` s.t. `pm ?m` is true. -/ def localDeclDependsOnPred [Monad m] [MonadMCtx m] (localDecl : LocalDecl) (pf : FVarId → Bool := fun _ => false) (pm : MVarId → Bool := fun _ => false) : m Bool := do findLocalDeclDependsOn localDecl pf pm namespace MetavarContext instance : Inhabited MetavarContext := ⟨{}⟩ @[export lean_mk_metavar_ctx] def mkMetavarContext : Unit → MetavarContext := fun _ => {} /-- Low level API for adding/declaring metavariable declarations. It is used to implement actions in the monads `MetaM`, `ElabM` and `TacticM`. It should not be used directly since the argument `(mvarId : MVarId)` is assumed to be "unique". -/ def addExprMVarDecl (mctx : MetavarContext) (mvarId : MVarId) (userName : Name) (lctx : LocalContext) (localInstances : LocalInstances) (type : Expr) (kind : MetavarKind := MetavarKind.natural) (numScopeArgs : Nat := 0) : MetavarContext := { mctx with mvarCounter := mctx.mvarCounter + 1 decls := mctx.decls.insert mvarId { depth := mctx.depth index := mctx.mvarCounter userName lctx localInstances type kind numScopeArgs } userNames := if userName.isAnonymous then mctx.userNames else mctx.userNames.insert userName mvarId } def addExprMVarDeclExp (mctx : MetavarContext) (mvarId : MVarId) (userName : Name) (lctx : LocalContext) (localInstances : LocalInstances) (type : Expr) (kind : MetavarKind) : MetavarContext := addExprMVarDecl mctx mvarId userName lctx localInstances type kind /-- Low level API for adding/declaring universe level metavariable declarations. It is used to implement actions in the monads `MetaM`, `ElabM` and `TacticM`. It should not be used directly since the argument `(mvarId : MVarId)` is assumed to be "unique". -/ def addLevelMVarDecl (mctx : MetavarContext) (mvarId : LMVarId) : MetavarContext := { mctx with lDepth := mctx.lDepth.insert mvarId mctx.depth } def findDecl? (mctx : MetavarContext) (mvarId : MVarId) : Option MetavarDecl := mctx.decls.find? mvarId def findUserName? (mctx : MetavarContext) (userName : Name) : Option MVarId := mctx.userNames.find? userName def setMVarKind (mctx : MetavarContext) (mvarId : MVarId) (kind : MetavarKind) : MetavarContext := let decl := mctx.getDecl mvarId { mctx with decls := mctx.decls.insert mvarId { decl with kind := kind } } /-- Set the metavariable user facing name. -/ def setMVarUserName (mctx : MetavarContext) (mvarId : MVarId) (userName : Name) : MetavarContext := let decl := mctx.getDecl mvarId { mctx with decls := mctx.decls.insert mvarId { decl with userName := userName } userNames := let userNames := mctx.userNames.erase decl.userName if userName.isAnonymous then userNames else userNames.insert userName mvarId } /-- Low-level version of `setMVarUserName`. It does not update the table `userNames`. Thus, `findUserName?` cannot see the modification. It is meant for `mkForallFVars'` where we temporarily set the user facing name of metavariables to get more meaningful binder names. -/ def setMVarUserNameTemporarily (mctx : MetavarContext) (mvarId : MVarId) (userName : Name) : MetavarContext := let decl := mctx.getDecl mvarId { mctx with decls := mctx.decls.insert mvarId { decl with userName := userName } } /-- Update the type of the given metavariable. This function assumes the new type is definitionally equal to the current one -/ def setMVarType (mctx : MetavarContext) (mvarId : MVarId) (type : Expr) : MetavarContext := let decl := mctx.getDecl mvarId { mctx with decls := mctx.decls.insert mvarId { decl with type := type } } def findLevelDepth? (mctx : MetavarContext) (mvarId : LMVarId) : Option Nat := mctx.lDepth.find? mvarId def getLevelDepth (mctx : MetavarContext) (mvarId : LMVarId) : Nat := match mctx.findLevelDepth? mvarId with | some d => d | none => panic! "unknown metavariable" def isAnonymousMVar (mctx : MetavarContext) (mvarId : MVarId) : Bool := match mctx.findDecl? mvarId with | none => false | some mvarDecl => mvarDecl.userName.isAnonymous def incDepth (mctx : MetavarContext) : MetavarContext := { mctx with depth := mctx.depth + 1 } instance : MonadMCtx (StateRefT MetavarContext (ST ω)) where getMCtx := get modifyMCtx := modify namespace MkBinding inductive Exception where | revertFailure (mctx : MetavarContext) (lctx : LocalContext) (toRevert : Array Expr) (varName : String) instance : ToString Exception where toString | Exception.revertFailure _ lctx toRevert varName => "failed to revert " ++ toString (toRevert.map (fun x => "'" ++ toString (lctx.getFVar! x).userName ++ "'")) ++ ", '" ++ toString varName ++ "' depends on them, and it is an auxiliary declaration created by the elaborator" ++ " (possible solution: use tactic 'clear' to remove '" ++ toString varName ++ "' from local context)" /-- `MkBinding` and `elimMVarDepsAux` are mutually recursive, but `cache` is only used at `elimMVarDepsAux`. We use a single state object for convenience. We have a `NameGenerator` because we need to generate fresh auxiliary metavariables. -/ structure State where mctx : MetavarContext nextMacroScope : MacroScope ngen : NameGenerator cache : HashMap ExprStructEq Expr := {} structure Context where mainModule : Name preserveOrder : Bool /-- When creating binders for abstracted metavariables, we use the following `BinderInfo`. -/ binderInfoForMVars : BinderInfo := BinderInfo.implicit /-- Set of unassigned metavariables being abstracted. -/ mvarIdsToAbstract : MVarIdSet := {} abbrev MCore := EStateM Exception State abbrev M := ReaderT Context MCore instance : MonadMCtx M where getMCtx := return (← get).mctx modifyMCtx f := modify fun s => { s with mctx := f s.mctx } private def mkFreshBinderName (n : Name := `x) : M Name := do let fresh ← modifyGet fun s => (s.nextMacroScope, { s with nextMacroScope := s.nextMacroScope + 1 }) return addMacroScope (← read).mainModule n fresh def preserveOrder : M Bool := return (← read).preserveOrder instance : MonadHashMapCacheAdapter ExprStructEq Expr M where getCache := do let s ← get; pure s.cache modifyCache := fun f => modify fun s => { s with cache := f s.cache } /-- Return the local declaration of the free variable `x` in `xs` with the smallest index -/ private def getLocalDeclWithSmallestIdx (lctx : LocalContext) (xs : Array Expr) : LocalDecl := Id.run do let mut d : LocalDecl := lctx.getFVar! xs[0]! for x in xs[1:] do if x.isFVar then let curr := lctx.getFVar! x if curr.index < d.index then d := curr return d /-- Given `toRevert` an array of free variables s.t. `lctx` contains their declarations, return a new array of free variables that contains `toRevert` and all free variables in `lctx` that may depend on `toRevert`. Remark: the result is sorted by `LocalDecl` indices. Remark: We used to throw an `Exception.revertFailure` exception when an auxiliary declaration had to be reversed. Recall that auxiliary declarations are created when compiling (mutually) recursive definitions. The `revertFailure` due to auxiliary declaration dependency was originally introduced in Lean3 to address issue https://github.com/leanprover/lean/issues/1258. In Lean4, this solution is not satisfactory because all definitions/theorems are potentially recursive. So, even an simple (incomplete) definition such as ``` variables {α : Type} in def f (a : α) : List α := _ ``` would trigger the `Exception.revertFailure` exception. In the definition above, the elaborator creates the auxiliary definition `f : {α : Type} → List α`. The `_` is elaborated as a new fresh variable `?m` that contains `α : Type`, `a : α`, and `f : α → List α` in its context, When we try to create the lambda `fun {α : Type} (a : α) => ?m`, we first need to create an auxiliary `?n` which do not contain `α` and `a` in its context. That is, we create the metavariable `?n : {α : Type} → (a : α) → (f : α → List α) → List α`, add the delayed assignment `?n #[α, a, f] := ?m α a f`, and create the lambda `fun {α : Type} (a : α) => ?n α a f`. See `elimMVarDeps` for more information. If we kept using the Lean3 approach, we would get the `Exception.revertFailure` exception because we are reverting the auxiliary definition `f`. Note that https://github.com/leanprover/lean/issues/1258 is not an issue in Lean4 because we have changed how we compile recursive definitions. -/ def collectForwardDeps (lctx : LocalContext) (toRevert : Array Expr) : M (Array Expr) := do if toRevert.size == 0 then pure toRevert else if (← preserveOrder) then -- Make sure toRevert[j] does not depend on toRevert[i] for j > i toRevert.size.forM fun i => do let fvar := toRevert[i]! i.forM fun j => do let prevFVar := toRevert[j]! let prevDecl := lctx.getFVar! prevFVar if (← localDeclDependsOn prevDecl fvar.fvarId!) then throw (Exception.revertFailure (← getMCtx) lctx toRevert prevDecl.userName.toString) let newToRevert := if (← preserveOrder) then toRevert else Array.mkEmpty toRevert.size let firstDeclToVisit := getLocalDeclWithSmallestIdx lctx toRevert let initSize := newToRevert.size lctx.foldlM (init := newToRevert) (start := firstDeclToVisit.index) fun (newToRevert : Array Expr) decl => do if initSize.any fun i => decl.fvarId == newToRevert[i]!.fvarId! then return newToRevert else if toRevert.any fun x => decl.fvarId == x.fvarId! then return newToRevert.push decl.toExpr else if (← findLocalDeclDependsOn decl (newToRevert.any fun x => x.fvarId! == ·)) then return newToRevert.push decl.toExpr else return newToRevert /-- Create a new `LocalContext` by removing the free variables in `toRevert` from `lctx`. We use this function when we create auxiliary metavariables at `elimMVarDepsAux`. -/ def reduceLocalContext (lctx : LocalContext) (toRevert : Array Expr) : LocalContext := toRevert.foldr (init := lctx) fun x lctx => if x.isFVar then lctx.erase x.fvarId! else lctx /-- Return free variables in `xs` that are in the local context `lctx` -/ private def getInScope (lctx : LocalContext) (xs : Array Expr) : Array Expr := xs.foldl (init := #[]) fun scope x => if !x.isFVar then scope else if lctx.contains x.fvarId! then scope.push x else scope /-- Execute `x` with an empty cache, and then restore the original cache. -/ @[inline] private def withFreshCache (x : M α) : M α := do let cache ← modifyGet fun s => (s.cache, { s with cache := {} }) let a ← x modify fun s => { s with cache := cache } pure a /-- Create an application `mvar ys` where `ys` are the free variables. See "Gruesome details" in the beginning of the file for understanding how let-decl free variables are handled. -/ private def mkMVarApp (lctx : LocalContext) (mvar : Expr) (xs : Array Expr) (kind : MetavarKind) : Expr := xs.foldl (init := mvar) fun e x => if !x.isFVar then e else match kind with | MetavarKind.syntheticOpaque => mkApp e x | _ => if (lctx.getFVar! x).isLet then e else mkApp e x mutual private partial def visit (xs : Array Expr) (e : Expr) : M Expr := if !e.hasMVar then pure e else checkCache { val := e : ExprStructEq } fun _ => elim xs e private partial def elim (xs : Array Expr) (e : Expr) : M Expr := match e with | .proj _ _ s => return e.updateProj! (← visit xs s) | .forallE _ d b _ => return e.updateForallE! (← visit xs d) (← visit xs b) | .lam _ d b _ => return e.updateLambdaE! (← visit xs d) (← visit xs b) | .letE _ t v b _ => return e.updateLet! (← visit xs t) (← visit xs v) (← visit xs b) | .mdata _ b => return e.updateMData! (← visit xs b) | .app .. => e.withApp fun f args => elimApp xs f args | .mvar _ => elimApp xs e #[] | e => return e private partial def mkAuxMVarType (lctx : LocalContext) (xs : Array Expr) (kind : MetavarKind) (e : Expr) : M Expr := do let e ← abstractRangeAux xs xs.size e xs.size.foldRevM (init := e) fun i e => do let x := xs[i]! if x.isFVar then match lctx.getFVar! x with | LocalDecl.cdecl _ _ n type bi _ => let type := type.headBeta let type ← abstractRangeAux xs i type return Lean.mkForall n bi type e | LocalDecl.ldecl _ _ n type value nonDep _ => let type := type.headBeta let type ← abstractRangeAux xs i type let value ← abstractRangeAux xs i value let e := mkLet n type value e nonDep match kind with | MetavarKind.syntheticOpaque => -- See "Gruesome details" section in the beginning of the file let e := e.liftLooseBVars 0 1 return mkForall n BinderInfo.default type e | _ => pure e else let mvarDecl := (← get).mctx.getDecl x.mvarId! let type := mvarDecl.type.headBeta let type ← abstractRangeAux xs i type let id ← if mvarDecl.userName.isAnonymous then mkFreshBinderName else pure mvarDecl.userName return Lean.mkForall id (← read).binderInfoForMVars type e where abstractRangeAux (xs : Array Expr) (i : Nat) (e : Expr) : M Expr := do let e ← elim xs e pure (e.abstractRange i xs) private partial def elimMVar (xs : Array Expr) (mvarId : MVarId) (args : Array Expr) : M (Expr × Array Expr) := do let mvarDecl := (← getMCtx).getDecl mvarId let mvarLCtx := mvarDecl.lctx let toRevert := getInScope mvarLCtx xs if toRevert.size == 0 then let args ← args.mapM (visit xs) return (mkAppN (mkMVar mvarId) args, #[]) else /- `newMVarKind` is the kind for the new auxiliary metavariable. There is an alternative approach where we use ``` let newMVarKind := if !mctx.isExprAssignable mvarId || mvarDecl.isSyntheticOpaque then MetavarKind.syntheticOpaque else MetavarKind.natural ``` In this approach, we use the natural kind for the new auxiliary metavariable if the original metavariable is synthetic and assignable. Since we mainly use synthetic metavariables for pending type class (TC) resolution problems, this approach may minimize the number of TC resolution problems that may need to be resolved. A potential disadvantage is that `isDefEq` will not eagerly use `synthPending` for natural metavariables. That being said, we should try this approach as soon as we have an extensive test suite. -/ let newMVarKind := if !(← mvarId.isAssignable) then MetavarKind.syntheticOpaque else mvarDecl.kind let args ← args.mapM (visit xs) let toRevert ← collectForwardDeps mvarLCtx toRevert let newMVarLCtx := reduceLocalContext mvarLCtx toRevert -- Note that `toRevert` only contains free variables since it is the result of `getInScope` let newLocalInsts := mvarDecl.localInstances.filter fun inst => toRevert.all fun x => inst.fvar != x -- Remark: we must reset the before processing `mkAuxMVarType` because `toRevert` may not be equal to `xs` let newMVarType ← withFreshCache do mkAuxMVarType mvarLCtx toRevert newMVarKind mvarDecl.type let newMVarId := { name := (← get).ngen.curr } let newMVar := mkMVar newMVarId let result := mkMVarApp mvarLCtx newMVar toRevert newMVarKind let numScopeArgs := mvarDecl.numScopeArgs + result.getAppNumArgs modify fun s => { s with mctx := s.mctx.addExprMVarDecl newMVarId Name.anonymous newMVarLCtx newLocalInsts newMVarType newMVarKind numScopeArgs, ngen := s.ngen.next } if !mvarDecl.kind.isSyntheticOpaque then mvarId.assign result else /- If `mvarId` is the lhs of a delayed assignment `?m #[x_1, ... x_n] := ?mvarPending`, then `nestedFVars` is `#[x_1, ..., x_n]`. In this case, `newMVarId` is also `syntheticOpaque` and we add the delayed assignment delayed assignment ``` ?newMVar #[y_1, ..., y_m, x_1, ... x_n] := ?m ``` where `#[y_1, ..., y_m]` is `toRevert` after `collectForwardDeps`. -/ let (mvarIdPending, nestedFVars) ← match (← getDelayedMVarAssignment? mvarId) with | none => pure (mvarId, #[]) | some { fvars, mvarIdPending } => pure (mvarIdPending, fvars) assignDelayedMVar newMVarId (toRevert ++ nestedFVars) mvarIdPending return (mkAppN result args, toRevert) private partial def elimApp (xs : Array Expr) (f : Expr) (args : Array Expr) : M Expr := do match f with | Expr.mvar mvarId => match (← getExprMVarAssignment? mvarId) with | some newF => if newF.isLambda then let args ← args.mapM (visit xs) elim xs <| newF.betaRev args.reverse else elimApp xs newF args | none => if (← read).mvarIdsToAbstract.contains mvarId then return mkAppN f (← args.mapM (visit xs)) else return (← elimMVar xs mvarId args).1 | _ => return mkAppN (← visit xs f) (← args.mapM (visit xs)) end partial def elimMVarDeps (xs : Array Expr) (e : Expr) : M Expr := if !e.hasMVar then return e else withFreshCache do elim xs e partial def revert (xs : Array Expr) (mvarId : MVarId) : M (Expr × Array Expr) := withFreshCache do elimMVar xs mvarId #[] /-- Similar to `Expr.abstractRange`, but handles metavariables correctly. It uses `elimMVarDeps` to ensure `e` and the type of the free variables `xs` do not contain a metavariable `?m` s.t. local context of `?m` contains a free variable in `xs`. `elimMVarDeps` is defined later in this file. -/ @[inline] def abstractRange (xs : Array Expr) (i : Nat) (e : Expr) : M Expr := do let e ← elimMVarDeps xs e pure (e.abstractRange i xs) /-- Similar to `LocalContext.mkBinding`, but handles metavariables correctly. If `usedOnly == false` then `forall` and `lambda` expressions are created only for used variables. If `usedLetOnly == false` then `let` expressions are created only for used (let-) variables. -/ @[specialize] def mkBinding (isLambda : Bool) (lctx : LocalContext) (xs : Array Expr) (e : Expr) (usedOnly : Bool) (usedLetOnly : Bool) : M (Expr × Nat) := do let e ← abstractRange xs xs.size e xs.size.foldRevM (init := (e, 0)) fun i (e, num) => do let x := xs[i]! if x.isFVar then match lctx.getFVar! x with | LocalDecl.cdecl _ _ n type bi _ => if !usedOnly || e.hasLooseBVar 0 then let type := type.headBeta; let type ← abstractRange xs i type if isLambda then return (Lean.mkLambda n bi type e, num + 1) else return (Lean.mkForall n bi type e, num + 1) else return (e.lowerLooseBVars 1 1, num) | LocalDecl.ldecl _ _ n type value nonDep _ => if !usedLetOnly || e.hasLooseBVar 0 then let type ← abstractRange xs i type let value ← abstractRange xs i value return (mkLet n type value e nonDep, num + 1) else return (e.lowerLooseBVars 1 1, num) else let mvarDecl := (← get).mctx.getDecl x.mvarId! let type := mvarDecl.type.headBeta let type ← abstractRange xs i type let id ← if mvarDecl.userName.isAnonymous then mkFreshBinderName else pure mvarDecl.userName if isLambda then return (Lean.mkLambda id (← read).binderInfoForMVars type e, num + 1) else return (Lean.mkForall id (← read).binderInfoForMVars type e, num + 1) end MkBinding structure MkBindingM.Context where mainModule : Name lctx : LocalContext abbrev MkBindingM := ReaderT MkBindingM.Context MkBinding.MCore def elimMVarDeps (xs : Array Expr) (e : Expr) (preserveOrder : Bool) : MkBindingM Expr := fun ctx => MkBinding.elimMVarDeps xs e { preserveOrder, mainModule := ctx.mainModule } def revert (xs : Array Expr) (mvarId : MVarId) (preserveOrder : Bool) : MkBindingM (Expr × Array Expr) := fun ctx => MkBinding.revert xs mvarId { preserveOrder, mainModule := ctx.mainModule } def mkBinding (isLambda : Bool) (xs : Array Expr) (e : Expr) (usedOnly : Bool := false) (usedLetOnly : Bool := true) (binderInfoForMVars := BinderInfo.implicit) : MkBindingM (Expr × Nat) := fun ctx => let mvarIdsToAbstract := xs.foldl (init := {}) fun s x => if x.isMVar then s.insert x.mvarId! else s MkBinding.mkBinding isLambda ctx.lctx xs e usedOnly usedLetOnly { preserveOrder := false, binderInfoForMVars, mvarIdsToAbstract, mainModule := ctx.mainModule } @[inline] def mkLambda (xs : Array Expr) (e : Expr) (usedOnly : Bool := false) (usedLetOnly : Bool := true) (binderInfoForMVars := BinderInfo.implicit) : MkBindingM Expr := return (← mkBinding (isLambda := true) xs e usedOnly usedLetOnly binderInfoForMVars).1 @[inline] def mkForall (xs : Array Expr) (e : Expr) (usedOnly : Bool := false) (usedLetOnly : Bool := true) (binderInfoForMVars := BinderInfo.implicit) : MkBindingM Expr := return (← mkBinding (isLambda := false) xs e usedOnly usedLetOnly binderInfoForMVars).1 @[inline] def abstractRange (e : Expr) (n : Nat) (xs : Array Expr) : MkBindingM Expr := fun ctx => MkBinding.abstractRange xs n e { preserveOrder := false, mainModule := ctx.mainModule } @[inline] def collectForwardDeps (toRevert : Array Expr) (preserveOrder : Bool) : MkBindingM (Array Expr) := fun ctx => MkBinding.collectForwardDeps ctx.lctx toRevert { preserveOrder, mainModule := ctx.mainModule } /-- `isWellFormed mctx lctx e` return true if - All locals in `e` are declared in `lctx` - All metavariables `?m` in `e` have a local context which is a subprefix of `lctx` or are assigned, and the assignment is well-formed. -/ partial def isWellFormed [Monad m] [MonadMCtx m] (lctx : LocalContext) : Expr → m Bool | .mdata _ e => isWellFormed lctx e | .proj _ _ e => isWellFormed lctx e | e@(.app f a) => pure (!e.hasExprMVar && !e.hasFVar) <||> (isWellFormed lctx f <&&> isWellFormed lctx a) | e@(.lam _ d b _) => pure (!e.hasExprMVar && !e.hasFVar) <||> (isWellFormed lctx d <&&> isWellFormed lctx b) | e@(.forallE _ d b _) => pure (!e.hasExprMVar && !e.hasFVar) <||> (isWellFormed lctx d <&&> isWellFormed lctx b) | e@(.letE _ t v b _) => pure (!e.hasExprMVar && !e.hasFVar) <||> (isWellFormed lctx t <&&> isWellFormed lctx v <&&> isWellFormed lctx b) | .const .. => return true | .bvar .. => return true | .sort .. => return true | .lit .. => return true | .mvar mvarId => do let mvarDecl := (← getMCtx).getDecl mvarId; if mvarDecl.lctx.isSubPrefixOf lctx then return true else match (← getExprMVarAssignment? mvarId) with | none => return false | some v => isWellFormed lctx v | .fvar fvarId => return lctx.contains fvarId namespace LevelMVarToParam structure Context where paramNamePrefix : Name alreadyUsedPred : Name → Bool except : LMVarId → Bool structure State where mctx : MetavarContext paramNames : Array Name := #[] nextParamIdx : Nat cache : HashMap ExprStructEq Expr := {} abbrev M := ReaderT Context <| StateM State instance : MonadMCtx M where getMCtx := return (← get).mctx modifyMCtx f := modify fun s => { s with mctx := f s.mctx } instance : MonadCache ExprStructEq Expr M where findCached? e := return (← get).cache.find? e cache e v := modify fun s => { s with cache := s.cache.insert e v } partial def mkParamName : M Name := do let ctx ← read let s ← get let newParamName := ctx.paramNamePrefix.appendIndexAfter s.nextParamIdx if ctx.alreadyUsedPred newParamName then modify fun s => { s with nextParamIdx := s.nextParamIdx + 1 } mkParamName else do modify fun s => { s with nextParamIdx := s.nextParamIdx + 1, paramNames := s.paramNames.push newParamName } pure newParamName partial def visitLevel (u : Level) : M Level := do match u with | .succ v => return u.updateSucc! (← visitLevel v) | .max v₁ v₂ => return u.updateMax! (← visitLevel v₁) (← visitLevel v₂) | .imax v₁ v₂ => return u.updateIMax! (← visitLevel v₁) (← visitLevel v₂) | .zero => return u | .param .. => return u | .mvar mvarId => match (← getLevelMVarAssignment? mvarId) with | some v => visitLevel v | none => if (← read).except mvarId then return u else let p ← mkParamName let p := mkLevelParam p assignLevelMVar mvarId p return p partial def main (e : Expr) : M Expr := if !e.hasMVar then return e else checkCache { val := e : ExprStructEq } fun _ => do match e with | .proj _ _ s => return e.updateProj! (← main s) | .forallE _ d b _ => return e.updateForallE! (← main d) (← main b) | .lam _ d b _ => return e.updateLambdaE! (← main d) (← main b) | .letE _ t v b _ => return e.updateLet! (← main t) (← main v) (← main b) | .app .. => e.withApp fun f args => visitApp f args | .mdata _ b => return e.updateMData! (← main b) | .const _ us => return e.updateConst! (← us.mapM visitLevel) | .sort u => return e.updateSort! (← visitLevel u) | .mvar .. => visitApp e #[] | e => return e where visitApp (f : Expr) (args : Array Expr) : M Expr := do match f with | .mvar mvarId .. => match (← getExprMVarAssignment? mvarId) with | some v => return (← visitApp v args).headBeta | none => return mkAppN f (← args.mapM main) | _ => return mkAppN (← main f) (← args.mapM main) end LevelMVarToParam structure UnivMVarParamResult where mctx : MetavarContext newParamNames : Array Name nextParamIdx : Nat expr : Expr def levelMVarToParam (mctx : MetavarContext) (alreadyUsedPred : Name → Bool) (except : LMVarId → Bool) (e : Expr) (paramNamePrefix : Name := `u) (nextParamIdx : Nat := 1) : UnivMVarParamResult := let (e, s) := LevelMVarToParam.main e { except, paramNamePrefix, alreadyUsedPred } { mctx, nextParamIdx } { mctx := s.mctx newParamNames := s.paramNames nextParamIdx := s.nextParamIdx expr := e } def getExprAssignmentDomain (mctx : MetavarContext) : Array MVarId := mctx.eAssignment.foldl (init := #[]) fun a mvarId _ => Array.push a mvarId end MetavarContext end Lean
4a47818eac8985dcb7736a4970ed888a08b92c44
4727251e0cd73359b15b664c3170e5d754078599
/src/linear_algebra/matrix/trace.lean
f4953a34463cce5cfac26adc500f94c25385f360
[ "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
4,475
lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Patrick Massot, Casper Putz, Anne Baanen -/ import data.matrix.basic /-! # Trace of a matrix This file defines the trace of a matrix, the map sending a matrix to the sum of its diagonal entries. See also `linear_algebra.trace` for the trace of an endomorphism. ## Tags matrix, trace, diagonal -/ open_locale big_operators matrix namespace matrix variables {ι m n p : Type*} {α R S : Type*} variables [fintype m] [fintype n] [fintype p] section add_comm_monoid variables [add_comm_monoid R] /-- The trace of a square matrix. For more bundled versions, see: * `matrix.trace_add_monoid_hom` * `matrix.trace_linear_map` -/ def trace (A : matrix n n R) : R := ∑ i, diag A i variables (n R) @[simp] lemma trace_zero : trace (0 : matrix n n R) = 0 := (finset.sum_const (0 : R)).trans $ smul_zero _ variables {n R} @[simp] lemma trace_add (A B : matrix n n R) : trace (A + B) = trace A + trace B := finset.sum_add_distrib @[simp] lemma trace_smul [monoid α] [distrib_mul_action α R] (r : α) (A : matrix n n R) : trace (r • A) = r • trace A := finset.smul_sum.symm @[simp] lemma trace_transpose (A : matrix n n R) : trace Aᵀ = trace A := rfl @[simp] lemma trace_conj_transpose [star_add_monoid R] (A : matrix n n R) : trace Aᴴ = star (trace A) := (star_sum _ _).symm variables (n α R) /-- `matrix.trace` as an `add_monoid_hom` -/ @[simps] def trace_add_monoid_hom : matrix n n R →+ R := { to_fun := trace, map_zero' := trace_zero n R, map_add' := trace_add } /-- `matrix.trace` as a `linear_map` -/ @[simps] def trace_linear_map [semiring α] [module α R] : matrix n n R →ₗ[α] R := { to_fun := trace, map_add' := trace_add, map_smul' := trace_smul } variables {n α R} @[simp] lemma trace_list_sum (l : list (matrix n n R)) : trace l.sum = (l.map trace).sum := map_list_sum (trace_add_monoid_hom n R) l @[simp] lemma trace_multiset_sum (s : multiset (matrix n n R)) : trace s.sum = (s.map trace).sum := map_multiset_sum (trace_add_monoid_hom n R) s @[simp] lemma trace_sum (s : finset ι) (f : ι → matrix n n R) : trace (∑ i in s, f i) = ∑ i in s, trace (f i) := map_sum (trace_add_monoid_hom n R) f s end add_comm_monoid section add_comm_group variables [add_comm_group R] @[simp] lemma trace_sub (A B : matrix n n R) : trace (A - B) = trace A - trace B := finset.sum_sub_distrib @[simp] lemma trace_neg (A : matrix n n R) : trace (-A) = -trace A := finset.sum_neg_distrib end add_comm_group section one variables [decidable_eq n] [add_comm_monoid R] [has_one R] @[simp] lemma trace_one : trace (1 : matrix n n R) = fintype.card n := by simp_rw [trace, diag_one, pi.one_def, finset.sum_const, nsmul_one, finset.card_univ] end one section mul @[simp] lemma trace_transpose_mul [add_comm_monoid R] [has_mul R] (A : matrix m n R) (B : matrix n m R) : trace (Aᵀ ⬝ Bᵀ) = trace (A ⬝ B) := finset.sum_comm lemma trace_mul_comm [add_comm_monoid R] [comm_semigroup R] (A : matrix m n R) (B : matrix n m R) : trace (A ⬝ B) = trace (B ⬝ A) := by rw [←trace_transpose, ←trace_transpose_mul, transpose_mul] lemma trace_mul_cycle [non_unital_comm_semiring R] (A : matrix m n R) (B : matrix n p R) (C : matrix p m R) : trace (A ⬝ B ⬝ C) = trace (C ⬝ A ⬝ B) := by rw [trace_mul_comm, matrix.mul_assoc] lemma trace_mul_cycle' [non_unital_comm_semiring R] (A : matrix m n R) (B : matrix n p R) (C : matrix p m R) : trace (A ⬝ (B ⬝ C)) = trace (C ⬝ (A ⬝ B)) := by rw [←matrix.mul_assoc, trace_mul_comm] @[simp] lemma trace_col_mul_row [non_unital_non_assoc_semiring R] (a b : n → R) : trace (col a ⬝ row b) = dot_product a b := by simp [dot_product, trace] end mul section fin variables [add_comm_monoid R] /-! ### Special cases for `fin n` While `simp [fin.sum_univ_succ]` can prove these, we include them for convenience and consistency with `matrix.det_fin_two` etc. -/ @[simp] lemma trace_fin_zero (A : matrix (fin 0) (fin 0) R) : trace A = 0 := rfl lemma trace_fin_one (A : matrix (fin 1) (fin 1) R) : trace A = A 0 0 := add_zero _ lemma trace_fin_two (A : matrix (fin 2) (fin 2) R) : trace A = A 0 0 + A 1 1 := congr_arg ((+) _) (add_zero (A 1 1)) lemma trace_fin_three (A : matrix (fin 3) (fin 3) R) : trace A = A 0 0 + A 1 1 + A 2 2 := by { rw [← add_zero (A 2 2), add_assoc], refl } end fin end matrix
188e952491cefad787fe72e0dae378752a57a75e
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/mv_polynomial/monad.lean
a1c339505d3ece9c54760088a0733ddfb9f54c7c
[]
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
17,949
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 Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.mv_polynomial.rename import Mathlib.PostPort universes u_1 u_2 u_3 u_4 u_5 namespace Mathlib /-! # Monad operations on `mv_polynomial` This file defines two monadic operations on `mv_polynomial`. Given `p : mv_polynomial σ R`, * `mv_polynomial.bind₁` and `mv_polynomial.join₁` operate on the variable type `σ`. * `mv_polynomial.bind₂` and `mv_polynomial.join₂` operate on the coefficient type `R`. - `mv_polynomial.bind₁ f φ` with `f : σ → mv_polynomial τ R` and `φ : mv_polynomial σ R`, is the polynomial `φ(f 1, ..., f i, ...) : mv_polynomial τ R`. - `mv_polynomial.join₁ φ` with `φ : mv_polynomial (mv_polynomial σ R) R` collapses `φ` to a `mv_polynomial σ R`, by evaluating `φ` under the map `X f ↦ f` for `f : mv_polynomial σ R`. In other words, if you have a polynomial `φ` in a set of variables indexed by a polynomial ring, you evaluate the polynomial in these indexing polynomials. - `mv_polynomial.bind₂ f φ` with `f : R →+* mv_polynomial σ S` and `φ : mv_polynomial σ R` is the `mv_polynomial σ S` obtained from `φ` by mapping the coefficients of `φ` through `f` and considering the resulting polynomial as polynomial expression in `mv_polynomial σ R`. - `mv_polynomial.join₂ φ` with `φ : mv_polynomial σ (mv_polynomial σ R)` collapses `φ` to a `mv_polynomial σ R`, by considering `φ` as polynomial expression in `mv_polynomial σ R`. These operations themselves have algebraic structure: `mv_polynomial.bind₁` and `mv_polynomial.join₁` are algebra homs and `mv_polynomial.bind₂` and `mv_polynomial.join₂` are ring homs. They interact in convenient ways with `mv_polynomial.rename`, `mv_polynomial.map`, `mv_polynomial.vars`, and other polynomial operations. Indeed, `mv_polynomial.rename` is the "map" operation for the (`bind₁`, `join₁`) pair, whereas `mv_polynomial.map` is the "map" operation for the other pair. ## Implementation notes We add an `is_lawful_monad` instance for the (`bind₁`, `join₁`) pair. The second pair cannot be instantiated as a `monad`, since it is not a monad in `Type` but in `CommRing` (or rather `CommSemiRing`). -/ namespace mv_polynomial /-- `bind₁` is the "left hand side" bind operation on `mv_polynomial`, operating on the variable type. Given a polynomial `p : mv_polynomial σ R` and a map `f : σ → mv_polynomial τ R` taking variables in `p` to polynomials in the variable type `τ`, `bind₁ f p` replaces each variable in `p` with its value under `f`, producing a new polynomial in `τ`. The coefficient type remains the same. This operation is an algebra hom. -/ def bind₁ {σ : Type u_1} {τ : Type u_2} {R : Type u_3} [comm_semiring R] (f : σ → mv_polynomial τ R) : alg_hom R (mv_polynomial σ R) (mv_polynomial τ R) := aeval f /-- `bind₂` is the "right hand side" bind operation on `mv_polynomial`, operating on the coefficient type. Given a polynomial `p : mv_polynomial σ R` and a map `f : R → mv_polynomial σ S` taking coefficients in `p` to polynomials over a new ring `S`, `bind₂ f p` replaces each coefficient in `p` with its value under `f`, producing a new polynomial over `S`. The variable type remains the same. This operation is a ring hom. -/ def bind₂ {σ : Type u_1} {R : Type u_3} {S : Type u_4} [comm_semiring R] [comm_semiring S] (f : R →+* mv_polynomial σ S) : mv_polynomial σ R →+* mv_polynomial σ S := eval₂_hom f X /-- `join₁` is the monadic join operation corresponding to `mv_polynomial.bind₁`. Given a polynomial `p` with coefficients in `R` whose variables are polynomials in `σ` with coefficients in `R`, `join₁ p` collapses `p` to a polynomial with variables in `σ` and coefficients in `R`. This operation is an algebra hom. -/ def join₁ {σ : Type u_1} {R : Type u_3} [comm_semiring R] : alg_hom R (mv_polynomial (mv_polynomial σ R) R) (mv_polynomial σ R) := aeval id /-- `join₂` is the monadic join operation corresponding to `mv_polynomial.bind₂`. Given a polynomial `p` with variables in `σ` whose coefficients are polynomials in `σ` with coefficients in `R`, `join₂ p` collapses `p` to a polynomial with variables in `σ` and coefficients in `R`. This operation is a ring hom. -/ def join₂ {σ : Type u_1} {R : Type u_3} [comm_semiring R] : mv_polynomial σ (mv_polynomial σ R) →+* mv_polynomial σ R := eval₂_hom (ring_hom.id (mv_polynomial σ R)) X @[simp] theorem aeval_eq_bind₁ {σ : Type u_1} {τ : Type u_2} {R : Type u_3} [comm_semiring R] (f : σ → mv_polynomial τ R) : aeval f = bind₁ f := rfl @[simp] theorem eval₂_hom_C_eq_bind₁ {σ : Type u_1} {τ : Type u_2} {R : Type u_3} [comm_semiring R] (f : σ → mv_polynomial τ R) : eval₂_hom C f = ↑(bind₁ f) := rfl @[simp] theorem eval₂_hom_eq_bind₂ {σ : Type u_1} {R : Type u_3} {S : Type u_4} [comm_semiring R] [comm_semiring S] (f : R →+* mv_polynomial σ S) : eval₂_hom f X = bind₂ f := rfl @[simp] theorem aeval_id_eq_join₁ (σ : Type u_1) (R : Type u_3) [comm_semiring R] : aeval id = join₁ := rfl theorem eval₂_hom_C_id_eq_join₁ (σ : Type u_1) (R : Type u_3) [comm_semiring R] (φ : mv_polynomial (mv_polynomial σ R) R) : coe_fn (eval₂_hom C id) φ = coe_fn join₁ φ := rfl @[simp] theorem eval₂_hom_id_X_eq_join₂ (σ : Type u_1) (R : Type u_3) [comm_semiring R] : eval₂_hom (ring_hom.id (mv_polynomial σ R)) X = join₂ := rfl -- In this file, we don't want to use these simp lemmas, -- because we first need to show how these new definitions interact -- and the proofs fall back on unfolding the definitions and call simp afterwards @[simp] theorem bind₁_X_right {σ : Type u_1} {τ : Type u_2} {R : Type u_3} [comm_semiring R] (f : σ → mv_polynomial τ R) (i : σ) : coe_fn (bind₁ f) (X i) = f i := aeval_X f i @[simp] theorem bind₂_X_right {σ : Type u_1} {R : Type u_3} {S : Type u_4} [comm_semiring R] [comm_semiring S] (f : R →+* mv_polynomial σ S) (i : σ) : coe_fn (bind₂ f) (X i) = X i := eval₂_hom_X' f X i @[simp] theorem bind₁_X_left {σ : Type u_1} {R : Type u_3} [comm_semiring R] : bind₁ X = alg_hom.id R (mv_polynomial σ R) := sorry theorem aeval_X_left {σ : Type u_1} {R : Type u_3} [comm_semiring R] : aeval X = alg_hom.id R (mv_polynomial σ R) := eq.mpr (id (Eq._oldrec (Eq.refl (aeval X = alg_hom.id R (mv_polynomial σ R))) (aeval_eq_bind₁ X))) (eq.mpr (id (Eq._oldrec (Eq.refl (bind₁ X = alg_hom.id R (mv_polynomial σ R))) bind₁_X_left)) (Eq.refl (alg_hom.id R (mv_polynomial σ R)))) theorem aeval_X_left_apply {σ : Type u_1} {R : Type u_3} [comm_semiring R] (φ : mv_polynomial σ R) : coe_fn (aeval X) φ = φ := sorry @[simp] theorem bind₁_C_right {σ : Type u_1} {τ : Type u_2} {R : Type u_3} [comm_semiring R] (f : σ → mv_polynomial τ R) (x : R) : coe_fn (bind₁ f) (coe_fn C x) = coe_fn C x := sorry @[simp] theorem bind₂_C_right {σ : Type u_1} {R : Type u_3} {S : Type u_4} [comm_semiring R] [comm_semiring S] (f : R →+* mv_polynomial σ S) (r : R) : coe_fn (bind₂ f) (coe_fn C r) = coe_fn f r := eval₂_hom_C f X r @[simp] theorem bind₂_C_left {σ : Type u_1} {R : Type u_3} [comm_semiring R] : bind₂ C = ring_hom.id (mv_polynomial σ R) := sorry @[simp] theorem bind₂_comp_C {σ : Type u_1} {R : Type u_3} {S : Type u_4} [comm_semiring R] [comm_semiring S] (f : R →+* mv_polynomial σ S) : ring_hom.comp (bind₂ f) C = f := ring_hom.ext (bind₂_C_right f) @[simp] theorem join₂_map {σ : Type u_1} {R : Type u_3} {S : Type u_4} [comm_semiring R] [comm_semiring S] (f : R →+* mv_polynomial σ S) (φ : mv_polynomial σ R) : coe_fn join₂ (coe_fn (map f) φ) = coe_fn (bind₂ f) φ := sorry @[simp] theorem join₂_comp_map {σ : Type u_1} {R : Type u_3} {S : Type u_4} [comm_semiring R] [comm_semiring S] (f : R →+* mv_polynomial σ S) : ring_hom.comp join₂ (map f) = bind₂ f := ring_hom.ext (join₂_map f) theorem aeval_id_rename {σ : Type u_1} {τ : Type u_2} {R : Type u_3} [comm_semiring R] (f : σ → mv_polynomial τ R) (p : mv_polynomial σ R) : coe_fn (aeval id) (coe_fn (rename f) p) = coe_fn (aeval f) p := eq.mpr (id (Eq._oldrec (Eq.refl (coe_fn (aeval id) (coe_fn (rename f) p) = coe_fn (aeval f) p)) (aeval_rename f id p))) (eq.mpr (id (Eq._oldrec (Eq.refl (coe_fn (aeval (id ∘ f)) p = coe_fn (aeval f) p)) (function.comp.left_id f))) (Eq.refl (coe_fn (aeval f) p))) @[simp] theorem join₁_rename {σ : Type u_1} {τ : Type u_2} {R : Type u_3} [comm_semiring R] (f : σ → mv_polynomial τ R) (φ : mv_polynomial σ R) : coe_fn join₁ (coe_fn (rename f) φ) = coe_fn (bind₁ f) φ := aeval_id_rename f φ @[simp] theorem bind₁_id {σ : Type u_1} {R : Type u_3} [comm_semiring R] : bind₁ id = join₁ := rfl @[simp] theorem bind₂_id {σ : Type u_1} {R : Type u_3} [comm_semiring R] : bind₂ (ring_hom.id (mv_polynomial σ R)) = join₂ := rfl theorem bind₁_bind₁ {σ : Type u_1} {τ : Type u_2} {R : Type u_3} [comm_semiring R] {υ : Type u_4} (f : σ → mv_polynomial τ R) (g : τ → mv_polynomial υ R) (φ : mv_polynomial σ R) : coe_fn (bind₁ g) (coe_fn (bind₁ f) φ) = coe_fn (bind₁ fun (i : σ) => coe_fn (bind₁ g) (f i)) φ := sorry theorem bind₁_comp_bind₁ {σ : Type u_1} {τ : Type u_2} {R : Type u_3} [comm_semiring R] {υ : Type u_4} (f : σ → mv_polynomial τ R) (g : τ → mv_polynomial υ R) : alg_hom.comp (bind₁ g) (bind₁ f) = bind₁ fun (i : σ) => coe_fn (bind₁ g) (f i) := alg_hom_ext fun (i : σ) => bind₁_bind₁ (fun (n : σ) => f n) (fun (n : τ) => g n) (X i) theorem bind₂_comp_bind₂ {σ : Type u_1} {R : Type u_3} {S : Type u_4} {T : Type u_5} [comm_semiring R] [comm_semiring S] [comm_semiring T] (f : R →+* mv_polynomial σ S) (g : S →+* mv_polynomial σ T) : ring_hom.comp (bind₂ g) (bind₂ f) = bind₂ (ring_hom.comp (bind₂ g) f) := sorry theorem bind₂_bind₂ {σ : Type u_1} {R : Type u_3} {S : Type u_4} {T : Type u_5} [comm_semiring R] [comm_semiring S] [comm_semiring T] (f : R →+* mv_polynomial σ S) (g : S →+* mv_polynomial σ T) (φ : mv_polynomial σ R) : coe_fn (bind₂ g) (coe_fn (bind₂ f) φ) = coe_fn (bind₂ (ring_hom.comp (bind₂ g) f)) φ := ring_hom.congr_fun (bind₂_comp_bind₂ f g) φ theorem rename_comp_bind₁ {σ : Type u_1} {τ : Type u_2} {R : Type u_3} [comm_semiring R] {υ : Type u_4} (f : σ → mv_polynomial τ R) (g : τ → υ) : alg_hom.comp (rename g) (bind₁ f) = bind₁ fun (i : σ) => coe_fn (rename g) (f i) := sorry theorem rename_bind₁ {σ : Type u_1} {τ : Type u_2} {R : Type u_3} [comm_semiring R] {υ : Type u_4} (f : σ → mv_polynomial τ R) (g : τ → υ) (φ : mv_polynomial σ R) : coe_fn (rename g) (coe_fn (bind₁ f) φ) = coe_fn (bind₁ fun (i : σ) => coe_fn (rename g) (f i)) φ := alg_hom.congr_fun (rename_comp_bind₁ f g) φ theorem map_bind₂ {σ : Type u_1} {R : Type u_3} {S : Type u_4} {T : Type u_5} [comm_semiring R] [comm_semiring S] [comm_semiring T] (f : R →+* mv_polynomial σ S) (g : S →+* T) (φ : mv_polynomial σ R) : coe_fn (map g) (coe_fn (bind₂ f) φ) = coe_fn (bind₂ (ring_hom.comp (map g) f)) φ := sorry theorem bind₁_comp_rename {σ : Type u_1} {τ : Type u_2} {R : Type u_3} [comm_semiring R] {υ : Type u_4} (f : τ → mv_polynomial υ R) (g : σ → τ) : alg_hom.comp (bind₁ f) (rename g) = bind₁ (f ∘ g) := sorry theorem bind₁_rename {σ : Type u_1} {τ : Type u_2} {R : Type u_3} [comm_semiring R] {υ : Type u_4} (f : τ → mv_polynomial υ R) (g : σ → τ) (φ : mv_polynomial σ R) : coe_fn (bind₁ f) (coe_fn (rename g) φ) = coe_fn (bind₁ (f ∘ g)) φ := alg_hom.congr_fun (bind₁_comp_rename f g) φ theorem bind₂_map {σ : Type u_1} {R : Type u_3} {S : Type u_4} {T : Type u_5} [comm_semiring R] [comm_semiring S] [comm_semiring T] (f : S →+* mv_polynomial σ T) (g : R →+* S) (φ : mv_polynomial σ R) : coe_fn (bind₂ f) (coe_fn (map g) φ) = coe_fn (bind₂ (ring_hom.comp f g)) φ := sorry @[simp] theorem map_comp_C {σ : Type u_1} {R : Type u_3} {S : Type u_4} [comm_semiring R] [comm_semiring S] (f : R →+* S) : ring_hom.comp (map f) C = ring_hom.comp C f := ring_hom.ext fun (x : R) => map_C f x -- mixing the two monad structures theorem hom_bind₁ {σ : Type u_1} {τ : Type u_2} {R : Type u_3} {S : Type u_4} [comm_semiring R] [comm_semiring S] (f : mv_polynomial τ R →+* S) (g : σ → mv_polynomial τ R) (φ : mv_polynomial σ R) : coe_fn f (coe_fn (bind₁ g) φ) = coe_fn (eval₂_hom (ring_hom.comp f C) fun (i : σ) => coe_fn f (g i)) φ := sorry theorem map_bind₁ {σ : Type u_1} {τ : Type u_2} {R : Type u_3} {S : Type u_4} [comm_semiring R] [comm_semiring S] (f : R →+* S) (g : σ → mv_polynomial τ R) (φ : mv_polynomial σ R) : coe_fn (map f) (coe_fn (bind₁ g) φ) = coe_fn (bind₁ fun (i : σ) => coe_fn (map f) (g i)) (coe_fn (map f) φ) := sorry @[simp] theorem eval₂_hom_comp_C {σ : Type u_1} {R : Type u_3} {S : Type u_4} [comm_semiring R] [comm_semiring S] (f : R →+* S) (g : σ → S) : ring_hom.comp (eval₂_hom f g) C = f := ring_hom.ext fun (r : R) => eval₂_C f g r theorem eval₂_hom_bind₁ {σ : Type u_1} {τ : Type u_2} {R : Type u_3} {S : Type u_4} [comm_semiring R] [comm_semiring S] (f : R →+* S) (g : τ → S) (h : σ → mv_polynomial τ R) (φ : mv_polynomial σ R) : coe_fn (eval₂_hom f g) (coe_fn (bind₁ h) φ) = coe_fn (eval₂_hom f fun (i : σ) => coe_fn (eval₂_hom f g) (h i)) φ := sorry theorem aeval_bind₁ {σ : Type u_1} {τ : Type u_2} {R : Type u_3} {S : Type u_4} [comm_semiring R] [comm_semiring S] [algebra R S] (f : τ → S) (g : σ → mv_polynomial τ R) (φ : mv_polynomial σ R) : coe_fn (aeval f) (coe_fn (bind₁ g) φ) = coe_fn (aeval fun (i : σ) => coe_fn (aeval f) (g i)) φ := eval₂_hom_bind₁ (algebra_map R S) (fun (n : τ) => f n) g φ theorem aeval_comp_bind₁ {σ : Type u_1} {τ : Type u_2} {R : Type u_3} {S : Type u_4} [comm_semiring R] [comm_semiring S] [algebra R S] (f : τ → S) (g : σ → mv_polynomial τ R) : alg_hom.comp (aeval f) (bind₁ g) = aeval fun (i : σ) => coe_fn (aeval f) (g i) := alg_hom_ext fun (i : σ) => aeval_bind₁ (fun (n : τ) => f n) (fun (n : σ) => g n) (X i) theorem eval₂_hom_comp_bind₂ {σ : Type u_1} {R : Type u_3} {S : Type u_4} {T : Type u_5} [comm_semiring R] [comm_semiring S] [comm_semiring T] (f : S →+* T) (g : σ → T) (h : R →+* mv_polynomial σ S) : ring_hom.comp (eval₂_hom f g) (bind₂ h) = eval₂_hom (ring_hom.comp (eval₂_hom f g) h) g := sorry theorem eval₂_hom_bind₂ {σ : Type u_1} {R : Type u_3} {S : Type u_4} {T : Type u_5} [comm_semiring R] [comm_semiring S] [comm_semiring T] (f : S →+* T) (g : σ → T) (h : R →+* mv_polynomial σ S) (φ : mv_polynomial σ R) : coe_fn (eval₂_hom f g) (coe_fn (bind₂ h) φ) = coe_fn (eval₂_hom (ring_hom.comp (eval₂_hom f g) h) g) φ := ring_hom.congr_fun (eval₂_hom_comp_bind₂ f g h) φ theorem aeval_bind₂ {σ : Type u_1} {R : Type u_3} {S : Type u_4} {T : Type u_5} [comm_semiring R] [comm_semiring S] [comm_semiring T] [algebra S T] (f : σ → T) (g : R →+* mv_polynomial σ S) (φ : mv_polynomial σ R) : coe_fn (aeval f) (coe_fn (bind₂ g) φ) = coe_fn (eval₂_hom (ring_hom.comp (↑(aeval f)) g) f) φ := eval₂_hom_bind₂ (algebra_map S T) (fun (n : σ) => f n) g φ theorem eval₂_hom_C_left {σ : Type u_1} {τ : Type u_2} {R : Type u_3} [comm_semiring R] (f : σ → mv_polynomial τ R) : eval₂_hom C f = ↑(bind₁ f) := rfl theorem bind₁_monomial {σ : Type u_1} {τ : Type u_2} {R : Type u_3} [comm_semiring R] (f : σ → mv_polynomial τ R) (d : σ →₀ ℕ) (r : R) : coe_fn (bind₁ f) (monomial d r) = coe_fn C r * finset.prod (finsupp.support d) fun (i : σ) => f i ^ coe_fn d i := sorry theorem bind₂_monomial {σ : Type u_1} {R : Type u_3} {S : Type u_4} [comm_semiring R] [comm_semiring S] (f : R →+* mv_polynomial σ S) (d : σ →₀ ℕ) (r : R) : coe_fn (bind₂ f) (monomial d r) = coe_fn f r * monomial d 1 := sorry @[simp] theorem bind₂_monomial_one {σ : Type u_1} {R : Type u_3} {S : Type u_4} [comm_semiring R] [comm_semiring S] (f : R →+* mv_polynomial σ S) (d : σ →₀ ℕ) : coe_fn (bind₂ f) (monomial d 1) = monomial d 1 := sorry protected instance monad {R : Type u_3} [comm_semiring R] : Monad fun (σ : Type u_1) => mv_polynomial σ R := sorry protected instance is_lawful_functor {R : Type u_3} [comm_semiring R] : is_lawful_functor fun (σ : Type u_1) => mv_polynomial σ R := is_lawful_functor.mk (fun (α : Type u_1) (x : mv_polynomial α R) => eq.mpr (id (Eq.trans ((fun (a a_1 : mv_polynomial α R) (e_1 : a = a_1) (ᾰ ᾰ_1 : mv_polynomial α R) (e_2 : ᾰ = ᾰ_1) => congr (congr_arg Eq e_1) e_2) (id <$> x) x (rename_id x) x x (Eq.refl x)) (propext (eq_self_iff_true x)))) trivial) fun (α β γ : Type u_1) (g : α → β) (h : β → γ) (x : mv_polynomial α R) => eq.mpr (id (Eq.trans ((fun (a a_1 : mv_polynomial γ R) (e_1 : a = a_1) (ᾰ ᾰ_1 : mv_polynomial γ R) (e_2 : ᾰ = ᾰ_1) => congr (congr_arg Eq e_1) e_2) ((h ∘ g) <$> x) (coe_fn (rename (h ∘ g)) x) (Eq.refl (coe_fn (rename (h ∘ g)) x)) (h <$> g <$> x) (coe_fn (rename (h ∘ g)) x) (rename_rename g h x)) (propext (eq_self_iff_true (coe_fn (rename (h ∘ g)) x))))) trivial protected instance is_lawful_monad {R : Type u_3} [comm_semiring R] : is_lawful_monad fun (σ : Type u_1) => mv_polynomial σ R := sorry
1b1d4b66b2a9d536c1258a1820c65edec53a83df
e9dbaaae490bc072444e3021634bf73664003760
/src/Problems/2003/IMO_2003_P3.lean
02cdd8e38d2ad9299b0b3be0e37b75dcbb5740cf
[ "Apache-2.0" ]
permissive
liaofei1128/geometry
566d8bfe095ce0c0113d36df90635306c60e975b
3dd128e4eec8008764bb94e18b932f9ffd66e6b3
refs/heads/master
1,678,996,510,399
1,581,454,543,000
1,583,337,839,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
335
lean
import Geo.Geo.Core namespace Geo open Analytic Polygon def IMO_2003_P3 : Prop := ∀ (hex : Polygon 6), convex hex → (hex.oppoSides rfl).allP (λ ⟨s₁, s₂⟩ => let midpDist := dist s₁.midp s₂.midp; let sumLengths := ulen s₁ + ulen s₂; midpDist = (Real.sqrt 3) / 2 * sumLengths ) → hex.angles.allEq end Geo
5d43ea2c42ad22bb28f13391a76d5ec4915ee871
5e3548e65f2c037cb94cd5524c90c623fbd6d46a
/AMC_2021_A_25.lean
86b54df9c7e2428ada2b41049d43f43844168ec0
[]
no_license
ahayat16/lean_exos
d4f08c30adb601a06511a71b5ffb4d22d12ef77f
682f2552d5b04a8c8eb9e4ab15f875a91b03845c
refs/heads/main
1,693,101,073,585
1,636,479,336,000
1,636,479,336,000
415,000,441
0
0
null
null
null
null
UTF-8
Lean
false
false
229
lean
import data.complex.basic import number_theory.divisors theorem AMC_2021_A_25 (N:ℕ)(f:ℕ → ℝ)(h:∀(n:ℕ), f n = (finset.card (nat.divisors n))/(n^(1/3)))(hN:∀(n:ℕ),n≠N → (f N > f n)): N=2520 := begin sorry end
6670375493f7950e69d81025d7c94a097fa13aab
9dd3f3912f7321eb58ee9aa8f21778ad6221f87c
/tests/lean/run/simplifier_custom_relations.lean
0590d0234db571f5ec0a315ec116df911f478b18
[ "Apache-2.0" ]
permissive
bre7k30/lean
de893411bcfa7b3c5572e61b9e1c52951b310aa4
5a924699d076dab1bd5af23a8f910b433e598d7a
refs/heads/master
1,610,900,145,817
1,488,006,845,000
1,488,006,845,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
987
lean
open tactic constants (A : Type) (rel : A → A → Prop) (rel.refl : ∀ a, rel a a) (rel.symm : ∀ a b, rel a b → rel b a) (rel.trans : ∀ a b c, rel a b → rel b c → rel a c) attribute [refl] rel.refl attribute [symm] rel.symm attribute [trans] rel.trans constants (x y z : A) (f g h : A → A) (H₁ : rel (f x) (g y)) (H₂ : rel (h (g y)) z) (Hf : ∀ (a b : A), rel a b → rel (f a) (f b)) (Hg : ∀ (a b : A), rel a b → rel (g a) (g b)) (Hh : ∀ (a b : A), rel a b → rel (h a) (h b)) attribute [simp] H₁ H₂ attribute [congr] Hf Hg Hh print [simp] default print [congr] default meta definition relsimp_core (e : expr) : tactic (expr × expr) := do S ← simp_lemmas.mk_default, e_type ← infer_type e >>= whnf, simplify_core {} S `rel e example : rel (h (f x)) z := by do e₁ ← to_expr `(h (f x)), (e₁', pf) ← relsimp_core e₁, exact pf
339213f5ce4b698cbc7742cbb8c67d8335d298df
367134ba5a65885e863bdc4507601606690974c1
/src/group_theory/sylow.lean
5a4a5bd49790d3837e4ec978640002334098fead
[ "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
13,251
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 group_theory.group_action import group_theory.quotient_group import group_theory.order_of_element import data.zmod.basic import data.fintype.card import data.list.rotate /-! # Sylow theorems The Sylow theorems are the following results for every finite group `G` and every prime number `p`. * There exists a Sylow `p`-subgroup of `G`. * All Sylow `p`-subgroups of `G` are conjugate to each other. * Let `nₚ` be the number of Sylow `p`-subgroups of `G`, then `nₚ` divides the index of the Sylow `p`-subgroup, `nₚ ≡ 1 [MOD p]`, and `nₚ` is equal to the index of the normalizer of the Sylow `p`-subgroup in `G`. In this file, currently only the first of these results is proven. ## Main statements * `exists_prime_order_of_dvd_card`: For every prime `p` dividing the order of `G` there exists an element of order `p` in `G`. This is known as Cauchy`s theorem. * `exists_subgroup_card_pow_prime`: A generalisation of the first of the Sylow theorems: For every prime power `pⁿ` dividing `G`, there exists a subgroup of `G` of order `pⁿ`. ## TODO * Prove the second and third of the Sylow theorems. * Sylow theorems for infinite groups -/ open equiv fintype finset mul_action function open equiv.perm subgroup list quotient_group open_locale big_operators universes u v w variables {G : Type u} {α : Type v} {β : Type w} [group G] local attribute [instance, priority 10] subtype.fintype set_fintype classical.prop_decidable namespace mul_action variables [mul_action G α] lemma mem_fixed_points_iff_card_orbit_eq_one {a : α} [fintype (orbit G a)] : a ∈ fixed_points G α ↔ card (orbit G a) = 1 := begin rw [fintype.card_eq_one_iff, mem_fixed_points], split, { exact λ h, ⟨⟨a, mem_orbit_self _⟩, λ ⟨b, ⟨x, hx⟩⟩, subtype.eq $ by simp [h x, hx.symm]⟩ }, { assume h x, rcases h with ⟨⟨z, hz⟩, hz₁⟩, exact calc x • a = z : subtype.mk.inj (hz₁ ⟨x • a, mem_orbit _ _⟩) ... = a : (subtype.mk.inj (hz₁ ⟨a, mem_orbit_self _⟩)).symm } end lemma card_modeq_card_fixed_points [fintype α] [fintype G] [fintype (fixed_points G α)] (p : ℕ) {n : ℕ} [hp : fact p.prime] (h : card G = p ^ n) : card α ≡ card (fixed_points G α) [MOD p] := calc card α = card (Σ y : quotient (orbit_rel G α), {x // quotient.mk' x = y}) : card_congr (sigma_preimage_equiv (@quotient.mk' _ (orbit_rel G α))).symm ... = ∑ a : quotient (orbit_rel G α), card {x // quotient.mk' x = a} : card_sigma _ ... ≡ ∑ a : fixed_points G α, 1 [MOD p] : begin rw [← zmod.eq_iff_modeq_nat p, sum_nat_cast, sum_nat_cast], refine eq.symm (sum_bij_ne_zero (λ a _ _, quotient.mk' a.1) (λ _ _ _, mem_univ _) (λ a₁ a₂ _ _ _ _ h, subtype.eq ((mem_fixed_points' α).1 a₂.2 a₁.1 (quotient.exact' h))) (λ b, _) (λ a ha _, by rw [← mem_fixed_points_iff_card_orbit_eq_one.1 a.2]; simp only [quotient.eq']; congr)), { refine quotient.induction_on' b (λ b _ hb, _), have : card (orbit G b) ∣ p ^ n, { rw [← h, fintype.card_congr (orbit_equiv_quotient_stabilizer G b)], exact card_quotient_dvd_card _ }, rcases (nat.dvd_prime_pow hp).1 this with ⟨k, _, hk⟩, have hb' :¬ p ^ 1 ∣ p ^ k, { rw [pow_one, ← hk, ← nat.modeq.modeq_zero_iff, ← zmod.eq_iff_modeq_nat, nat.cast_zero, ← ne.def], exact eq.mpr (by simp only [quotient.eq']; congr) hb }, have : k = 0 := nat.le_zero_iff.1 (nat.le_of_lt_succ (lt_of_not_ge (mt (pow_dvd_pow p) hb'))), refine ⟨⟨b, mem_fixed_points_iff_card_orbit_eq_one.2 $ by rw [hk, this, pow_zero]⟩, mem_univ _, _, rfl⟩, rw [nat.cast_one], exact one_ne_zero } end ... = _ : by simp; refl end mul_action lemma quotient_group.card_preimage_mk [fintype G] (s : subgroup G) (t : set (quotient s)) : fintype.card (quotient_group.mk ⁻¹' t) = fintype.card s * fintype.card t := by rw [← fintype.card_prod, fintype.card_congr (preimage_mk_equiv_subgroup_times_set _ _)] namespace sylow /-- Given a vector `v` of length `n`, make a vector of length `n+1` whose product is `1`, by consing the the inverse of the product of `v`. -/ def mk_vector_prod_eq_one (n : ℕ) (v : vector G n) : vector G (n+1) := v.to_list.prod⁻¹ ::ᵥ v lemma mk_vector_prod_eq_one_injective (n : ℕ) : injective (@mk_vector_prod_eq_one G _ n) := λ ⟨v, _⟩ ⟨w, _⟩ h, subtype.eq (show v = w, by injection h with h; injection h) /-- The type of vectors with terms from `G`, length `n`, and product equal to `1:G`. -/ def vectors_prod_eq_one (G : Type*) [group G] (n : ℕ) : set (vector G n) := {v | v.to_list.prod = 1} lemma mem_vectors_prod_eq_one {n : ℕ} (v : vector G n) : v ∈ vectors_prod_eq_one G n ↔ v.to_list.prod = 1 := iff.rfl lemma mem_vectors_prod_eq_one_iff {n : ℕ} (v : vector G (n + 1)) : v ∈ vectors_prod_eq_one G (n + 1) ↔ v ∈ set.range (@mk_vector_prod_eq_one G _ n) := ⟨λ (h : v.to_list.prod = 1), ⟨v.tail, begin unfold mk_vector_prod_eq_one, conv {to_rhs, rw ← vector.cons_head_tail v}, suffices : (v.tail.to_list.prod)⁻¹ = v.head, { rw this }, rw [← mul_left_inj v.tail.to_list.prod, inv_mul_self, ← list.prod_cons, ← vector.to_list_cons, vector.cons_head_tail, h] end⟩, λ ⟨w, hw⟩, by rw [mem_vectors_prod_eq_one, ← hw, mk_vector_prod_eq_one, vector.to_list_cons, list.prod_cons, inv_mul_self]⟩ /-- The rotation action of `zmod n` (viewed as multiplicative group) on `vectors_prod_eq_one G n`, where `G` is a multiplicative group. -/ def rotate_vectors_prod_eq_one (G : Type*) [group G] (n : ℕ) (m : multiplicative (zmod n)) (v : vectors_prod_eq_one G n) : vectors_prod_eq_one G n := ⟨⟨v.1.to_list.rotate m.val, by simp⟩, prod_rotate_eq_one_of_prod_eq_one v.2 _⟩ instance rotate_vectors_prod_eq_one.mul_action (n : ℕ) [fact (0 < n)] : mul_action (multiplicative (zmod n)) (vectors_prod_eq_one G n) := { smul := (rotate_vectors_prod_eq_one G n), one_smul := begin intro v, apply subtype.eq, apply vector.eq _ _, show rotate _ (0 : zmod n).val = _, rw zmod.val_zero, exact rotate_zero v.1.to_list end, mul_smul := λ a b ⟨⟨v, hv₁⟩, hv₂⟩, subtype.eq $ vector.eq _ _ $ show v.rotate ((a + b : zmod n).val) = list.rotate (list.rotate v (b.val)) (a.val), by rw [zmod.val_add, rotate_rotate, ← rotate_mod _ (b.val + a.val), add_comm, hv₁] } lemma one_mem_vectors_prod_eq_one (n : ℕ) : vector.repeat (1 : G) n ∈ vectors_prod_eq_one G n := by simp [vector.repeat, vectors_prod_eq_one] lemma one_mem_fixed_points_rotate (n : ℕ) [fact (0 < n)] : (⟨vector.repeat (1 : G) n, one_mem_vectors_prod_eq_one n⟩ : vectors_prod_eq_one G n) ∈ fixed_points (multiplicative (zmod n)) (vectors_prod_eq_one G n) := λ m, subtype.eq $ vector.eq _ _ $ rotate_eq_self_iff_eq_repeat.2 ⟨(1 : G), show list.repeat (1 : G) n = list.repeat 1 (list.repeat (1 : G) n).length, by simp⟩ _ /-- Cauchy's theorem -/ lemma exists_prime_order_of_dvd_card [fintype G] (p : ℕ) [hp : fact p.prime] (hdvd : p ∣ card G) : ∃ x : G, order_of x = p := let n : ℕ+ := ⟨p - 1, nat.sub_pos_of_lt hp.one_lt⟩ in have hn : p = n + 1 := nat.succ_sub hp.pos, have hcard : card (vectors_prod_eq_one G (n + 1)) = card G ^ (n : ℕ), by rw [set.ext mem_vectors_prod_eq_one_iff, set.card_range_of_injective (mk_vector_prod_eq_one_injective _), card_vector], have hzmod : fintype.card (multiplicative (zmod p)) = p ^ 1, by { rw pow_one p, exact zmod.card p }, have hmodeq : _ = _ := @mul_action.card_modeq_card_fixed_points (multiplicative (zmod p)) (vectors_prod_eq_one G p) _ _ _ _ _ _ 1 hp hzmod, have hdvdcard : p ∣ fintype.card (vectors_prod_eq_one G (n + 1)) := calc p ∣ card G ^ 1 : by rwa pow_one ... ∣ card G ^ (n : ℕ) : pow_dvd_pow _ n.2 ... = card (vectors_prod_eq_one G (n + 1)) : hcard.symm, have hdvdcard₂ : p ∣ card (fixed_points (multiplicative (zmod p)) (vectors_prod_eq_one G p)), by { rw nat.dvd_iff_mod_eq_zero at hdvdcard ⊢, rwa [← hn, hmodeq] at hdvdcard }, have hcard_pos : 0 < card (fixed_points (multiplicative (zmod p)) (vectors_prod_eq_one G p)) := fintype.card_pos_iff.2 ⟨⟨⟨vector.repeat 1 p, one_mem_vectors_prod_eq_one _⟩, one_mem_fixed_points_rotate _⟩⟩, have hlt : 1 < card (fixed_points (multiplicative (zmod p)) (vectors_prod_eq_one G p)) := calc (1 : ℕ) < p : hp.one_lt ... ≤ _ : nat.le_of_dvd hcard_pos hdvdcard₂, let ⟨⟨⟨⟨x, hx₁⟩, hx₂⟩, hx₃⟩, hx₄⟩ := fintype.exists_ne_of_one_lt_card hlt ⟨_, one_mem_fixed_points_rotate p⟩ in have hx : x ≠ list.repeat (1 : G) p, from λ h, by simpa [h, vector.repeat] using hx₄, have ∃ a, x = list.repeat a x.length := by exactI rotate_eq_self_iff_eq_repeat.1 (λ n, have list.rotate x (n : zmod p).val = x := subtype.mk.inj (subtype.mk.inj (hx₃ (n : zmod p))), by rwa [zmod.val_nat_cast, ← hx₁, rotate_mod] at this), let ⟨a, ha⟩ := this in ⟨a, have hx1 : x.prod = 1 := hx₂, have ha1: a ≠ 1, from λ h, hx (ha.symm ▸ h ▸ hx₁ ▸ rfl), have a ^ p = 1, by rwa [ha, list.prod_repeat, hx₁] at hx1, (hp.2 _ (order_of_dvd_of_pow_eq_one this)).resolve_left (λ h, ha1 (order_of_eq_one_iff.1 h))⟩ open subgroup submonoid is_group_hom mul_action lemma mem_fixed_points_mul_left_cosets_iff_mem_normalizer {H : subgroup G} [fintype ((H : set G) : Type u)] {x : G} : (x : quotient H) ∈ fixed_points H (quotient H) ↔ x ∈ normalizer H := ⟨λ hx, have ha : ∀ {y : quotient H}, y ∈ orbit H (x : quotient H) → y = x, from λ _, ((mem_fixed_points' _).1 hx _), (inv_mem_iff _).1 (@mem_normalizer_fintype _ _ _ _inst_2 _ (λ n (hn : n ∈ H), have (n⁻¹ * x)⁻¹ * x ∈ H := quotient_group.eq.1 (ha (mem_orbit _ ⟨n⁻¹, H.inv_mem hn⟩)), show _ ∈ H, by {rw [mul_inv_rev, inv_inv] at this, convert this, rw inv_inv} )), λ (hx : ∀ (n : G), n ∈ H ↔ x * n * x⁻¹ ∈ H), (mem_fixed_points' _).2 $ λ y, quotient.induction_on' y $ λ y hy, quotient_group.eq.2 (let ⟨⟨b, hb₁⟩, hb₂⟩ := hy in have hb₂ : (b * x)⁻¹ * y ∈ H := quotient_group.eq.1 hb₂, (inv_mem_iff H).1 $ (hx _).2 $ (mul_mem_cancel_left H (H.inv_mem hb₁)).1 $ by rw hx at hb₂; simpa [mul_inv_rev, mul_assoc] using hb₂)⟩ def fixed_points_mul_left_cosets_equiv_quotient (H : subgroup G) [fintype (H : set G)] : fixed_points H (quotient H) ≃ quotient (subgroup.comap ((normalizer H).subtype : normalizer H →* G) H) := @subtype_quotient_equiv_quotient_subtype G (normalizer H : set G) (id _) (id _) (fixed_points _ _) (λ a, (@mem_fixed_points_mul_left_cosets_iff_mem_normalizer _ _ _ _inst_2 _).symm) (by intros; refl) /-- The first of the Sylow theorems. -/ theorem exists_subgroup_card_pow_prime [fintype G] (p : ℕ) : ∀ {n : ℕ} [hp : fact p.prime] (hdvd : p ^ n ∣ card G), ∃ H : subgroup G, fintype.card H = p ^ n | 0 := λ _ _, ⟨(⊥ : subgroup G), by convert card_trivial⟩ | (n+1) := λ hp hdvd, let ⟨H, hH2⟩ := @exists_subgroup_card_pow_prime _ hp (dvd.trans (pow_dvd_pow _ (nat.le_succ _)) hdvd) in let ⟨s, hs⟩ := exists_eq_mul_left_of_dvd hdvd in have hcard : card (quotient H) = s * p := (nat.mul_left_inj (show card H > 0, from fintype.card_pos_iff.2 ⟨⟨1, H.one_mem⟩⟩)).1 (by rwa [← card_eq_card_quotient_mul_card_subgroup H, hH2, hs, pow_succ', mul_assoc, mul_comm p]), have hm : s * p % p = card (quotient (subgroup.comap ((normalizer H).subtype : normalizer H →* G) H)) % p := card_congr (fixed_points_mul_left_cosets_equiv_quotient H) ▸ hcard ▸ @card_modeq_card_fixed_points _ _ _ _ _ _ _ p _ hp hH2, have hm' : p ∣ card (quotient (subgroup.comap ((normalizer H).subtype : normalizer H →* G) H)) := nat.dvd_of_mod_eq_zero (by rwa [nat.mod_eq_zero_of_dvd (dvd_mul_left _ _), eq_comm] at hm), let ⟨x, hx⟩ := @exists_prime_order_of_dvd_card _ (quotient_group.quotient.group _) _ _ hp hm' in have hequiv : H ≃ (subgroup.comap ((normalizer H).subtype : normalizer H →* G) H) := ⟨λ a, ⟨⟨a.1, le_normalizer a.2⟩, a.2⟩, λ a, ⟨a.1.1, a.2⟩, λ ⟨_, _⟩, rfl, λ ⟨⟨_, _⟩, _⟩, rfl⟩, -- begin proof of ∃ H : subgroup G, fintype.card H = p ^ n ⟨subgroup.map ((normalizer H).subtype) (subgroup.comap (quotient_group.mk' (comap H.normalizer.subtype H)) (gpowers x)), begin show card ↥(map H.normalizer.subtype (comap (mk' (comap H.normalizer.subtype H)) (subgroup.gpowers x))) = p ^ (n + 1), suffices : card ↥(subtype.val '' ((subgroup.comap (mk' (comap H.normalizer.subtype H)) (gpowers x)) : set (↥(H.normalizer)))) = p^(n+1), { convert this using 2 }, rw [set.card_image_of_injective (subgroup.comap (mk' (comap H.normalizer.subtype H)) (gpowers x) : set (H.normalizer)) subtype.val_injective, pow_succ', ← hH2, fintype.card_congr hequiv, ← hx, order_eq_card_gpowers, ← fintype.card_prod], exact @fintype.card_congr _ _ (id _) (id _) (preimage_mk_equiv_subgroup_times_set _ _) end⟩ end sylow
5f4e499a5803db03abac24d28b74707f2b94c7a2
63abd62053d479eae5abf4951554e1064a4c45b4
/src/data/seq/computation.lean
0b8a0754940ddff2b4d3889c8543ce97dfdfe27c
[ "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
37,543
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro Coinductive formalization of unbounded computations. -/ import data.stream import tactic.basic universes u v w /- coinductive computation (α : Type u) : Type u | return : α → computation α | think : computation α → computation α -/ /-- `computation α` is the type of unbounded computations returning `α`. An element of `computation α` is an infinite sequence of `option α` such that if `f n = some a` for some `n` then it is constantly `some a` after that. -/ def computation (α : Type u) : Type u := { f : stream (option α) // ∀ {n a}, f n = some a → f (n+1) = some a } namespace computation variables {α : Type u} {β : Type v} {γ : Type w} -- constructors /-- `return a` is the computation that immediately terminates with result `a`. -/ def return (a : α) : computation α := ⟨stream.const (some a), λn a', id⟩ instance : has_coe_t α (computation α) := ⟨return⟩ -- note [use has_coe_t] /-- `think c` is the computation that delays for one "tick" and then performs computation `c`. -/ def think (c : computation α) : computation α := ⟨none :: c.1, λn a h, by {cases n with n, contradiction, exact c.2 h}⟩ /-- `thinkN c n` is the computation that delays for `n` ticks and then performs computation `c`. -/ def thinkN (c : computation α) : ℕ → computation α | 0 := c | (n+1) := think (thinkN n) -- check for immediate result /-- `head c` is the first step of computation, either `some a` if `c = return a` or `none` if `c = think c'`. -/ def head (c : computation α) : option α := c.1.head -- one step of computation /-- `tail c` is the remainder of computation, either `c` if `c = return a` or `c'` if `c = think c'`. -/ def tail (c : computation α) : computation α := ⟨c.1.tail, λ n a, let t := c.2 in t⟩ /-- `empty α` is the computation that never returns, an infinite sequence of `think`s. -/ def empty (α) : computation α := ⟨stream.const none, λn a', id⟩ instance : inhabited (computation α) := ⟨empty _⟩ /-- `run_for c n` evaluates `c` for `n` steps and returns the result, or `none` if it did not terminate after `n` steps. -/ def run_for : computation α → ℕ → option α := subtype.val /-- `destruct c` is the destructor for `computation α` as a coinductive type. It returns `inl a` if `c = return a` and `inr c'` if `c = think c'`. -/ def destruct (c : computation α) : α ⊕ computation α := match c.1 0 with | none := sum.inr (tail c) | some a := sum.inl a end /-- `run c` is an unsound meta function that runs `c` to completion, possibly resulting in an infinite loop in the VM. -/ meta def run : computation α → α | c := match destruct c with | sum.inl a := a | sum.inr ca := run ca end theorem destruct_eq_ret {s : computation α} {a : α} : destruct s = sum.inl a → s = return a := begin dsimp [destruct], induction f0 : s.1 0; intro h, { contradiction }, { apply subtype.eq, funext n, induction n with n IH, { injection h with h', rwa h' at f0 }, { exact s.2 IH } } end theorem destruct_eq_think {s : computation α} {s'} : destruct s = sum.inr s' → s = think s' := begin dsimp [destruct], induction f0 : s.1 0 with a'; intro h, { injection h with h', rw ←h', cases s with f al, apply subtype.eq, dsimp [think, tail], rw ←f0, exact (stream.eta f).symm }, { contradiction } end @[simp] theorem destruct_ret (a : α) : destruct (return a) = sum.inl a := rfl @[simp] theorem destruct_think : ∀ s : computation α, destruct (think s) = sum.inr s | ⟨f, al⟩ := rfl @[simp] theorem destruct_empty : destruct (empty α) = sum.inr (empty α) := rfl @[simp] theorem head_ret (a : α) : head (return a) = some a := rfl @[simp] theorem head_think (s : computation α) : head (think s) = none := rfl @[simp] theorem head_empty : head (empty α) = none := rfl @[simp] theorem tail_ret (a : α) : tail (return a) = return a := rfl @[simp] theorem tail_think (s : computation α) : tail (think s) = s := by cases s with f al; apply subtype.eq; dsimp [tail, think]; rw [stream.tail_cons] @[simp] theorem tail_empty : tail (empty α) = empty α := rfl theorem think_empty : empty α = think (empty α) := destruct_eq_think destruct_empty def cases_on {C : computation α → Sort v} (s : computation α) (h1 : ∀ a, C (return a)) (h2 : ∀ s, C (think s)) : C s := begin induction H : destruct s with v v, { rw destruct_eq_ret H, apply h1 }, { cases v with a s', rw destruct_eq_think H, apply h2 } end def corec.F (f : β → α ⊕ β) : α ⊕ β → option α × (α ⊕ β) | (sum.inl a) := (some a, sum.inl a) | (sum.inr b) := (match f b with | sum.inl a := some a | sum.inr b' := none end, f b) /-- `corec f b` is the corecursor for `computation α` as a coinductive type. If `f b = inl a` then `corec f b = return a`, and if `f b = inl b'` then `corec f b = think (corec f b')`. -/ def corec (f : β → α ⊕ β) (b : β) : computation α := begin refine ⟨stream.corec' (corec.F f) (sum.inr b), λn a' h, _⟩, rw stream.corec'_eq, change stream.corec' (corec.F f) (corec.F f (sum.inr b)).2 n = some a', revert h, generalize : sum.inr b = o, revert o, induction n with n IH; intro o, { change (corec.F f o).1 = some a' → (corec.F f (corec.F f o).2).1 = some a', cases o with a b; intro h, { exact h }, dsimp [corec.F] at h, dsimp [corec.F], cases f b with a b', { exact h }, { contradiction } }, { rw [stream.corec'_eq (corec.F f) (corec.F f o).2, stream.corec'_eq (corec.F f) o], exact IH (corec.F f o).2 } end /-- left map of `⊕` -/ def lmap (f : α → β) : α ⊕ γ → β ⊕ γ | (sum.inl a) := sum.inl (f a) | (sum.inr b) := sum.inr b /-- right map of `⊕` -/ def rmap (f : β → γ) : α ⊕ β → α ⊕ γ | (sum.inl a) := sum.inl a | (sum.inr b) := sum.inr (f b) attribute [simp] lmap rmap @[simp] lemma corec_eq (f : β → α ⊕ β) (b : β) : destruct (corec f b) = rmap (corec f) (f b) := begin dsimp [corec, destruct], change stream.corec' (corec.F f) (sum.inr b) 0 with corec.F._match_1 (f b), induction h : f b with a b', { refl }, dsimp [corec.F, destruct], apply congr_arg, apply subtype.eq, dsimp [corec, tail], rw [stream.corec'_eq, stream.tail_cons], dsimp [corec.F], rw h end section bisim variable (R : computation α → computation α → Prop) local infix ~ := R def bisim_o : α ⊕ computation α → α ⊕ computation α → Prop | (sum.inl a) (sum.inl a') := a = a' | (sum.inr s) (sum.inr s') := R s s' | _ _ := false attribute [simp] bisim_o def is_bisimulation := ∀ ⦃s₁ s₂⦄, s₁ ~ s₂ → bisim_o R (destruct s₁) (destruct s₂) -- If two computations are bisimilar, then they are equal theorem eq_of_bisim (bisim : is_bisimulation R) {s₁ s₂} (r : s₁ ~ s₂) : s₁ = s₂ := begin apply subtype.eq, apply stream.eq_of_bisim (λx y, ∃ s s' : computation α, s.1 = x ∧ s'.1 = y ∧ R s s'), dsimp [stream.is_bisimulation], intros t₁ t₂ e, exact match t₁, t₂, e with ._, ._, ⟨s, s', rfl, rfl, r⟩ := suffices head s = head s' ∧ R (tail s) (tail s'), from and.imp id (λr, ⟨tail s, tail s', by cases s; refl, by cases s'; refl, r⟩) this, begin have := bisim r, revert r this, apply cases_on s _ _; intros; apply cases_on s' _ _; intros; intros r this, { constructor, dsimp at this, rw this, assumption }, { rw [destruct_ret, destruct_think] at this, exact false.elim this }, { rw [destruct_ret, destruct_think] at this, exact false.elim this }, { simp at this, simp [*] } end end, exact ⟨s₁, s₂, rfl, rfl, r⟩ end end bisim -- It's more of a stretch to use ∈ for this relation, but it -- asserts that the computation limits to the given value. protected def mem (a : α) (s : computation α) := some a ∈ s.1 instance : has_mem α (computation α) := ⟨computation.mem⟩ theorem le_stable (s : computation α) {a m n} (h : m ≤ n) : s.1 m = some a → s.1 n = some a := by {cases s with f al, induction h with n h IH, exacts [id, λ h2, al (IH h2)]} theorem mem_unique : relator.left_unique ((∈) : α → computation α → Prop) := λa s b ⟨m, ha⟩ ⟨n, hb⟩, by injection (le_stable s (le_max_left m n) ha.symm).symm.trans (le_stable s (le_max_right m n) hb.symm) /-- `terminates s` asserts that the computation `s` eventually terminates with some value. -/ @[class] def terminates (s : computation α) : Prop := ∃ a, a ∈ s theorem terminates_of_mem {s : computation α} {a : α} : a ∈ s → terminates s := exists.intro a theorem terminates_def (s : computation α) : terminates s ↔ ∃ n, (s.1 n).is_some := ⟨λ⟨a, n, h⟩, ⟨n, by {dsimp [stream.nth] at h, rw ←h, exact rfl}⟩, λ⟨n, h⟩, ⟨option.get h, n, (option.eq_some_of_is_some h).symm⟩⟩ theorem ret_mem (a : α) : a ∈ return a := exists.intro 0 rfl theorem eq_of_ret_mem {a a' : α} (h : a' ∈ return a) : a' = a := mem_unique h (ret_mem _) instance ret_terminates (a : α) : terminates (return a) := terminates_of_mem (ret_mem _) theorem think_mem {s : computation α} {a} : a ∈ s → a ∈ think s | ⟨n, h⟩ := ⟨n+1, h⟩ instance think_terminates (s : computation α) : ∀ [terminates s], terminates (think s) | ⟨a, n, h⟩ := ⟨a, n+1, h⟩ theorem of_think_mem {s : computation α} {a} : a ∈ think s → a ∈ s | ⟨n, h⟩ := by {cases n with n', contradiction, exact ⟨n', h⟩} theorem of_think_terminates {s : computation α} : terminates (think s) → terminates s | ⟨a, h⟩ := ⟨a, of_think_mem h⟩ theorem not_mem_empty (a : α) : a ∉ empty α := λ ⟨n, h⟩, by clear _fun_match; contradiction theorem not_terminates_empty : ¬ terminates (empty α) := λ ⟨a, h⟩, not_mem_empty a h theorem eq_empty_of_not_terminates {s} (H : ¬ terminates s) : s = empty α := begin apply subtype.eq, funext n, induction h : s.val n, {refl}, refine absurd _ H, exact ⟨_, _, h.symm⟩ end theorem thinkN_mem {s : computation α} {a} : ∀ n, a ∈ thinkN s n ↔ a ∈ s | 0 := iff.rfl | (n+1) := iff.trans ⟨of_think_mem, think_mem⟩ (thinkN_mem n) instance thinkN_terminates (s : computation α) : ∀ [terminates s] n, terminates (thinkN s n) | ⟨a, h⟩ n := ⟨a, (thinkN_mem n).2 h⟩ theorem of_thinkN_terminates (s : computation α) (n) : terminates (thinkN s n) → terminates s | ⟨a, h⟩ := ⟨a, (thinkN_mem _).1 h⟩ /-- `promises s a`, or `s ~> a`, asserts that although the computation `s` may not terminate, if it does, then the result is `a`. -/ def promises (s : computation α) (a : α) : Prop := ∀ ⦃a'⦄, a' ∈ s → a = a' infix ` ~> `:50 := promises theorem mem_promises {s : computation α} {a : α} : a ∈ s → s ~> a := λ h a', mem_unique h theorem empty_promises (a : α) : empty α ~> a := λ a' h, absurd h (not_mem_empty _) section get variables (s : computation α) [h : terminates s] include s h /-- `length s` gets the number of steps of a terminating computation -/ def length : ℕ := nat.find ((terminates_def _).1 h) /-- `get s` returns the result of a terminating computation -/ def get : α := option.get (nat.find_spec $ (terminates_def _).1 h) theorem get_mem : get s ∈ s := exists.intro (length s) (option.eq_some_of_is_some _).symm theorem get_eq_of_mem {a} : a ∈ s → get s = a := mem_unique (get_mem _) theorem mem_of_get_eq {a} : get s = a → a ∈ s := by intro h; rw ←h; apply get_mem @[simp] theorem get_think : get (think s) = get s := get_eq_of_mem _ $ let ⟨n, h⟩ := get_mem s in ⟨n+1, h⟩ @[simp] theorem get_thinkN (n) : get (thinkN s n) = get s := get_eq_of_mem _ $ (thinkN_mem _).2 (get_mem _) theorem get_promises : s ~> get s := λ a, get_eq_of_mem _ theorem mem_of_promises {a} (p : s ~> a) : a ∈ s := by { casesI h with a' h, rw p h, exact h } theorem get_eq_of_promises {a} : s ~> a → get s = a := get_eq_of_mem _ ∘ mem_of_promises _ end get /-- `results s a n` completely characterizes a terminating computation: it asserts that `s` terminates after exactly `n` steps, with result `a`. -/ def results (s : computation α) (a : α) (n : ℕ) := ∃ (h : a ∈ s), @length _ s (terminates_of_mem h) = n theorem results_of_terminates (s : computation α) [T : terminates s] : results s (get s) (length s) := ⟨get_mem _, rfl⟩ theorem results_of_terminates' (s : computation α) [T : terminates s] {a} (h : a ∈ s) : results s a (length s) := by rw ←get_eq_of_mem _ h; apply results_of_terminates theorem results.mem {s : computation α} {a n} : results s a n → a ∈ s | ⟨m, _⟩ := m theorem results.terminates {s : computation α} {a n} (h : results s a n) : terminates s := terminates_of_mem h.mem theorem results.length {s : computation α} {a n} [T : terminates s] : results s a n → length s = n | ⟨_, h⟩ := h theorem results.val_unique {s : computation α} {a b m n} (h1 : results s a m) (h2 : results s b n) : a = b := mem_unique h1.mem h2.mem theorem results.len_unique {s : computation α} {a b m n} (h1 : results s a m) (h2 : results s b n) : m = n := by haveI := h1.terminates; haveI := h2.terminates; rw [←h1.length, h2.length] theorem exists_results_of_mem {s : computation α} {a} (h : a ∈ s) : ∃ n, results s a n := by haveI := terminates_of_mem h; exact ⟨_, results_of_terminates' s h⟩ @[simp] theorem get_ret (a : α) : get (return a) = a := get_eq_of_mem _ ⟨0, rfl⟩ @[simp] theorem length_ret (a : α) : length (return a) = 0 := let h := computation.ret_terminates a in nat.eq_zero_of_le_zero $ nat.find_min' ((terminates_def (return a)).1 h) rfl theorem results_ret (a : α) : results (return a) a 0 := ⟨_, length_ret _⟩ @[simp] theorem length_think (s : computation α) [h : terminates s] : length (think s) = length s + 1 := begin apply le_antisymm, { exact nat.find_min' _ (nat.find_spec ((terminates_def _).1 h)) }, { have : (option.is_some ((think s).val (length (think s))) : Prop) := nat.find_spec ((terminates_def _).1 s.think_terminates), cases length (think s) with n, { contradiction }, { apply nat.succ_le_succ, apply nat.find_min', apply this } } end theorem results_think {s : computation α} {a n} (h : results s a n) : results (think s) a (n + 1) := by haveI := h.terminates; exact ⟨think_mem h.mem, by rw [length_think, h.length]⟩ theorem of_results_think {s : computation α} {a n} (h : results (think s) a n) : ∃ m, results s a m ∧ n = m + 1 := begin haveI := of_think_terminates h.terminates, have := results_of_terminates' _ (of_think_mem h.mem), exact ⟨_, this, results.len_unique h (results_think this)⟩, end @[simp] theorem results_think_iff {s : computation α} {a n} : results (think s) a (n + 1) ↔ results s a n := ⟨λ h, let ⟨n', r, e⟩ := of_results_think h in by injection e with h'; rwa h', results_think⟩ theorem results_thinkN {s : computation α} {a m} : ∀ n, results s a m → results (thinkN s n) a (m + n) | 0 h := h | (n+1) h := results_think (results_thinkN n h) theorem results_thinkN_ret (a : α) (n) : results (thinkN (return a) n) a n := by have := results_thinkN n (results_ret a); rwa nat.zero_add at this @[simp] theorem length_thinkN (s : computation α) [h : terminates s] (n) : length (thinkN s n) = length s + n := (results_thinkN n (results_of_terminates _)).length theorem eq_thinkN {s : computation α} {a n} (h : results s a n) : s = thinkN (return a) n := begin revert s, induction n with n IH; intro s; apply cases_on s (λ a', _) (λ s, _); intro h, { rw ←eq_of_ret_mem h.mem, refl }, { cases of_results_think h with n h, cases h, contradiction }, { have := h.len_unique (results_ret _), contradiction }, { rw IH (results_think_iff.1 h), refl } end theorem eq_thinkN' (s : computation α) [h : terminates s] : s = thinkN (return (get s)) (length s) := eq_thinkN (results_of_terminates _) def mem_rec_on {C : computation α → Sort v} {a s} (M : a ∈ s) (h1 : C (return a)) (h2 : ∀ s, C s → C (think s)) : C s := begin haveI T := terminates_of_mem M, rw [eq_thinkN' s, get_eq_of_mem s M], generalize : length s = n, induction n with n IH, exacts [h1, h2 _ IH] end def terminates_rec_on {C : computation α → Sort v} (s) [terminates s] (h1 : ∀ a, C (return a)) (h2 : ∀ s, C s → C (think s)) : C s := mem_rec_on (get_mem s) (h1 _) h2 /-- Map a function on the result of a computation. -/ def map (f : α → β) : computation α → computation β | ⟨s, al⟩ := ⟨s.map (λo, option.cases_on o none (some ∘ f)), λn b, begin dsimp [stream.map, stream.nth], induction e : s n with a; intro h, { contradiction }, { rw [al e, ←h] } end⟩ def bind.G : β ⊕ computation β → β ⊕ computation α ⊕ computation β | (sum.inl b) := sum.inl b | (sum.inr cb') := sum.inr $ sum.inr cb' def bind.F (f : α → computation β) : computation α ⊕ computation β → β ⊕ computation α ⊕ computation β | (sum.inl ca) := match destruct ca with | sum.inl a := bind.G $ destruct (f a) | sum.inr ca' := sum.inr $ sum.inl ca' end | (sum.inr cb) := bind.G $ destruct cb /-- Compose two computations into a monadic `bind` operation. -/ def bind (c : computation α) (f : α → computation β) : computation β := corec (bind.F f) (sum.inl c) instance : has_bind computation := ⟨@bind⟩ theorem has_bind_eq_bind {β} (c : computation α) (f : α → computation β) : c >>= f = bind c f := rfl /-- Flatten a computation of computations into a single computation. -/ def join (c : computation (computation α)) : computation α := c >>= id @[simp] theorem map_ret (f : α → β) (a) : map f (return a) = return (f a) := rfl @[simp] theorem map_think (f : α → β) : ∀ s, map f (think s) = think (map f s) | ⟨s, al⟩ := by apply subtype.eq; dsimp [think, map]; rw stream.map_cons @[simp] theorem destruct_map (f : α → β) (s) : destruct (map f s) = lmap f (rmap (map f) (destruct s)) := by apply s.cases_on; intro; simp @[simp] theorem map_id : ∀ (s : computation α), map id s = s | ⟨f, al⟩ := begin apply subtype.eq; simp [map, function.comp], have e : (@option.rec α (λ_, option α) none some) = id, { ext ⟨⟩; refl }, simp [e, stream.map_id] end theorem map_comp (f : α → β) (g : β → γ) : ∀ (s : computation α), map (g ∘ f) s = map g (map f s) | ⟨s, al⟩ := begin apply subtype.eq; dsimp [map], rw stream.map_map, apply congr_arg (λ f : _ → option γ, stream.map f s), ext ⟨⟩; refl end @[simp] theorem ret_bind (a) (f : α → computation β) : bind (return a) f = f a := begin apply eq_of_bisim (λc₁ c₂, c₁ = bind (return a) f ∧ c₂ = f a ∨ c₁ = corec (bind.F f) (sum.inr c₂)), { intros c₁ c₂ h, exact match c₁, c₂, h with | ._, ._, or.inl ⟨rfl, rfl⟩ := begin simp [bind, bind.F], cases destruct (f a) with b cb; simp [bind.G] end | ._, c, or.inr rfl := begin simp [bind.F], cases destruct c with b cb; simp [bind.G] end end }, { simp } end @[simp] theorem think_bind (c) (f : α → computation β) : bind (think c) f = think (bind c f) := destruct_eq_think $ by simp [bind, bind.F] @[simp] theorem bind_ret (f : α → β) (s) : bind s (return ∘ f) = map f s := begin apply eq_of_bisim (λc₁ c₂, c₁ = c₂ ∨ ∃ s, c₁ = bind s (return ∘ f) ∧ c₂ = map f s), { intros c₁ c₂ h, exact match c₁, c₂, h with | _, _, or.inl (eq.refl c) := begin cases destruct c with b cb; simp end | _, _, or.inr ⟨s, rfl, rfl⟩ := begin apply cases_on s; intros s; simp, exact or.inr ⟨s, rfl, rfl⟩ end end }, { exact or.inr ⟨s, rfl, rfl⟩ } end @[simp] theorem bind_ret' (s : computation α) : bind s return = s := by rw bind_ret; change (λ x : α, x) with @id α; rw map_id @[simp] theorem bind_assoc (s : computation α) (f : α → computation β) (g : β → computation γ) : bind (bind s f) g = bind s (λ (x : α), bind (f x) g) := begin apply eq_of_bisim (λc₁ c₂, c₁ = c₂ ∨ ∃ s, c₁ = bind (bind s f) g ∧ c₂ = bind s (λ (x : α), bind (f x) g)), { intros c₁ c₂ h, exact match c₁, c₂, h with | _, _, or.inl (eq.refl c) := by cases destruct c with b cb; simp | ._, ._, or.inr ⟨s, rfl, rfl⟩ := begin apply cases_on s; intros s; simp, { generalize : f s = fs, apply cases_on fs; intros t; simp, { cases destruct (g t) with b cb; simp } }, { exact or.inr ⟨s, rfl, rfl⟩ } end end }, { exact or.inr ⟨s, rfl, rfl⟩ } end theorem results_bind {s : computation α} {f : α → computation β} {a b m n} (h1 : results s a m) (h2 : results (f a) b n) : results (bind s f) b (n + m) := begin have := h1.mem, revert m, apply mem_rec_on this _ (λ s IH, _); intros m h1, { rw [ret_bind], rw h1.len_unique (results_ret _), exact h2 }, { rw [think_bind], cases of_results_think h1 with m' h, cases h with h1 e, rw e, exact results_think (IH h1) } end theorem mem_bind {s : computation α} {f : α → computation β} {a b} (h1 : a ∈ s) (h2 : b ∈ f a) : b ∈ bind s f := let ⟨m, h1⟩ := exists_results_of_mem h1, ⟨n, h2⟩ := exists_results_of_mem h2 in (results_bind h1 h2).mem instance terminates_bind (s : computation α) (f : α → computation β) [terminates s] [terminates (f (get s))] : terminates (bind s f) := terminates_of_mem (mem_bind (get_mem s) (get_mem (f (get s)))) @[simp] theorem get_bind (s : computation α) (f : α → computation β) [terminates s] [terminates (f (get s))] : get (bind s f) = get (f (get s)) := get_eq_of_mem _ (mem_bind (get_mem s) (get_mem (f (get s)))) @[simp] theorem length_bind (s : computation α) (f : α → computation β) [T1 : terminates s] [T2 : terminates (f (get s))] : length (bind s f) = length (f (get s)) + length s := (results_of_terminates _).len_unique $ results_bind (results_of_terminates _) (results_of_terminates _) theorem of_results_bind {s : computation α} {f : α → computation β} {b k} : results (bind s f) b k → ∃ a m n, results s a m ∧ results (f a) b n ∧ k = n + m := begin induction k with n IH generalizing s; apply cases_on s (λ a, _) (λ s', _); intro e, { simp [thinkN] at e, refine ⟨a, _, _, results_ret _, e, rfl⟩ }, { have := congr_arg head (eq_thinkN e), contradiction }, { simp at e, refine ⟨a, _, n+1, results_ret _, e, rfl⟩ }, { simp at e, exact let ⟨a, m, n', h1, h2, e'⟩ := IH e in by rw e'; exact ⟨a, m.succ, n', results_think h1, h2, rfl⟩ } end theorem exists_of_mem_bind {s : computation α} {f : α → computation β} {b} (h : b ∈ bind s f) : ∃ a ∈ s, b ∈ f a := let ⟨k, h⟩ := exists_results_of_mem h, ⟨a, m, n, h1, h2, e⟩ := of_results_bind h in ⟨a, h1.mem, h2.mem⟩ theorem bind_promises {s : computation α} {f : α → computation β} {a b} (h1 : s ~> a) (h2 : f a ~> b) : bind s f ~> b := λ b' bB, begin rcases exists_of_mem_bind bB with ⟨a', a's, ba'⟩, rw ←h1 a's at ba', exact h2 ba' end instance : monad computation := { map := @map, pure := @return, bind := @bind } instance : is_lawful_monad computation := { id_map := @map_id, bind_pure_comp_eq_map := @bind_ret, pure_bind := @ret_bind, bind_assoc := @bind_assoc } theorem has_map_eq_map {β} (f : α → β) (c : computation α) : f <$> c = map f c := rfl @[simp] theorem return_def (a) : (_root_.return a : computation α) = return a := rfl @[simp] theorem map_ret' {α β} : ∀ (f : α → β) (a), f <$> return a = return (f a) := map_ret @[simp] theorem map_think' {α β} : ∀ (f : α → β) s, f <$> think s = think (f <$> s) := map_think theorem mem_map (f : α → β) {a} {s : computation α} (m : a ∈ s) : f a ∈ map f s := by rw ←bind_ret; apply mem_bind m; apply ret_mem theorem exists_of_mem_map {f : α → β} {b : β} {s : computation α} (h : b ∈ map f s) : ∃ a, a ∈ s ∧ f a = b := by rw ←bind_ret at h; exact let ⟨a, as, fb⟩ := exists_of_mem_bind h in ⟨a, as, mem_unique (ret_mem _) fb⟩ instance terminates_map (f : α → β) (s : computation α) [terminates s] : terminates (map f s) := by rw ←bind_ret; apply_instance theorem terminates_map_iff (f : α → β) (s : computation α) : terminates (map f s) ↔ terminates s := ⟨λ⟨a, h⟩, let ⟨b, h1, _⟩ := exists_of_mem_map h in ⟨_, h1⟩, @computation.terminates_map _ _ _ _⟩ -- Parallel computation /-- `c₁ <|> c₂` calculates `c₁` and `c₂` simultaneously, returning the first one that gives a result. -/ def orelse (c₁ c₂ : computation α) : computation α := @computation.corec α (computation α × computation α) (λ⟨c₁, c₂⟩, match destruct c₁ with | sum.inl a := sum.inl a | sum.inr c₁' := match destruct c₂ with | sum.inl a := sum.inl a | sum.inr c₂' := sum.inr (c₁', c₂') end end) (c₁, c₂) instance : alternative computation := { orelse := @orelse, failure := @empty, ..computation.monad } @[simp] theorem ret_orelse (a : α) (c₂ : computation α) : (return a <|> c₂) = return a := destruct_eq_ret $ by unfold has_orelse.orelse; simp [orelse] @[simp] theorem orelse_ret (c₁ : computation α) (a : α) : (think c₁ <|> return a) = return a := destruct_eq_ret $ by unfold has_orelse.orelse; simp [orelse] @[simp] theorem orelse_think (c₁ c₂ : computation α) : (think c₁ <|> think c₂) = think (c₁ <|> c₂) := destruct_eq_think $ by unfold has_orelse.orelse; simp [orelse] @[simp] theorem empty_orelse (c) : (empty α <|> c) = c := begin apply eq_of_bisim (λc₁ c₂, (empty α <|> c₂) = c₁) _ rfl, intros s' s h, rw ←h, apply cases_on s; intros s; rw think_empty; simp, rw ←think_empty, end @[simp] theorem orelse_empty (c : computation α) : (c <|> empty α) = c := begin apply eq_of_bisim (λc₁ c₂, (c₂ <|> empty α) = c₁) _ rfl, intros s' s h, rw ←h, apply cases_on s; intros s; rw think_empty; simp, rw←think_empty, end /-- `c₁ ~ c₂` asserts that `c₁` and `c₂` either both terminate with the same result, or both loop forever. -/ def equiv (c₁ c₂ : computation α) : Prop := ∀ a, a ∈ c₁ ↔ a ∈ c₂ infix ~ := equiv @[refl] theorem equiv.refl (s : computation α) : s ~ s := λ_, iff.rfl @[symm] theorem equiv.symm {s t : computation α} : s ~ t → t ~ s := λh a, (h a).symm @[trans] theorem equiv.trans {s t u : computation α} : s ~ t → t ~ u → s ~ u := λh1 h2 a, (h1 a).trans (h2 a) theorem equiv.equivalence : equivalence (@equiv α) := ⟨@equiv.refl _, @equiv.symm _, @equiv.trans _⟩ theorem equiv_of_mem {s t : computation α} {a} (h1 : a ∈ s) (h2 : a ∈ t) : s ~ t := λa', ⟨λma, by rw mem_unique ma h1; exact h2, λma, by rw mem_unique ma h2; exact h1⟩ theorem terminates_congr {c₁ c₂ : computation α} (h : c₁ ~ c₂) : terminates c₁ ↔ terminates c₂ := exists_congr h theorem promises_congr {c₁ c₂ : computation α} (h : c₁ ~ c₂) (a) : c₁ ~> a ↔ c₂ ~> a := forall_congr (λa', imp_congr (h a') iff.rfl) theorem get_equiv {c₁ c₂ : computation α} (h : c₁ ~ c₂) [terminates c₁] [terminates c₂] : get c₁ = get c₂ := get_eq_of_mem _ $ (h _).2 $ get_mem _ theorem think_equiv (s : computation α) : think s ~ s := λ a, ⟨of_think_mem, think_mem⟩ theorem thinkN_equiv (s : computation α) (n) : thinkN s n ~ s := λ a, thinkN_mem n theorem bind_congr {s1 s2 : computation α} {f1 f2 : α → computation β} (h1 : s1 ~ s2) (h2 : ∀ a, f1 a ~ f2 a) : bind s1 f1 ~ bind s2 f2 := λ b, ⟨λh, let ⟨a, ha, hb⟩ := exists_of_mem_bind h in mem_bind ((h1 a).1 ha) ((h2 a b).1 hb), λh, let ⟨a, ha, hb⟩ := exists_of_mem_bind h in mem_bind ((h1 a).2 ha) ((h2 a b).2 hb)⟩ theorem equiv_ret_of_mem {s : computation α} {a} (h : a ∈ s) : s ~ return a := equiv_of_mem h (ret_mem _) /-- `lift_rel R ca cb` is a generalization of `equiv` to relations other than equality. It asserts that if `ca` terminates with `a`, then `cb` terminates with some `b` such that `R a b`, and if `cb` terminates with `b` then `ca` terminates with some `a` such that `R a b`. -/ def lift_rel (R : α → β → Prop) (ca : computation α) (cb : computation β) : Prop := (∀ {a}, a ∈ ca → ∃ {b}, b ∈ cb ∧ R a b) ∧ ∀ {b}, b ∈ cb → ∃ {a}, a ∈ ca ∧ R a b theorem lift_rel.swap (R : α → β → Prop) (ca : computation α) (cb : computation β) : lift_rel (function.swap R) cb ca ↔ lift_rel R ca cb := and_comm _ _ theorem lift_eq_iff_equiv (c₁ c₂ : computation α) : lift_rel (=) c₁ c₂ ↔ c₁ ~ c₂ := ⟨λ⟨h1, h2⟩ a, ⟨λ a1, let ⟨b, b2, ab⟩ := h1 a1 in by rwa ab, λ a2, let ⟨b, b1, ab⟩ := h2 a2 in by rwa ←ab⟩, λe, ⟨λ a a1, ⟨a, (e _).1 a1, rfl⟩, λ a a2, ⟨a, (e _).2 a2, rfl⟩⟩⟩ theorem lift_rel.refl (R : α → α → Prop) (H : reflexive R) : reflexive (lift_rel R) := λ s, ⟨λ a as, ⟨a, as, H a⟩, λ b bs, ⟨b, bs, H b⟩⟩ theorem lift_rel.symm (R : α → α → Prop) (H : symmetric R) : symmetric (lift_rel R) := λ s1 s2 ⟨l, r⟩, ⟨λ a a2, let ⟨b, b1, ab⟩ := r a2 in ⟨b, b1, H ab⟩, λ a a1, let ⟨b, b2, ab⟩ := l a1 in ⟨b, b2, H ab⟩⟩ theorem lift_rel.trans (R : α → α → Prop) (H : transitive R) : transitive (lift_rel R) := λ s1 s2 s3 ⟨l1, r1⟩ ⟨l2, r2⟩, ⟨λ a a1, let ⟨b, b2, ab⟩ := l1 a1, ⟨c, c3, bc⟩ := l2 b2 in ⟨c, c3, H ab bc⟩, λ c c3, let ⟨b, b2, bc⟩ := r2 c3, ⟨a, a1, ab⟩ := r1 b2 in ⟨a, a1, H ab bc⟩⟩ theorem lift_rel.equiv (R : α → α → Prop) : equivalence R → equivalence (lift_rel R) | ⟨refl, symm, trans⟩ := ⟨lift_rel.refl R refl, lift_rel.symm R symm, lift_rel.trans R trans⟩ theorem lift_rel.imp {R S : α → β → Prop} (H : ∀ {a b}, R a b → S a b) (s t) : lift_rel R s t → lift_rel S s t | ⟨l, r⟩ := ⟨λ a as, let ⟨b, bt, ab⟩ := l as in ⟨b, bt, H ab⟩, λ b bt, let ⟨a, as, ab⟩ := r bt in ⟨a, as, H ab⟩⟩ theorem terminates_of_lift_rel {R : α → β → Prop} {s t} : lift_rel R s t → (terminates s ↔ terminates t) | ⟨l, r⟩ := ⟨λ ⟨a, as⟩, let ⟨b, bt, ab⟩ := l as in ⟨b, bt⟩, λ ⟨b, bt⟩, let ⟨a, as, ab⟩ := r bt in ⟨a, as⟩⟩ theorem rel_of_lift_rel {R : α → β → Prop} {ca cb} : lift_rel R ca cb → ∀ {a b}, a ∈ ca → b ∈ cb → R a b | ⟨l, r⟩ a b ma mb := let ⟨b', mb', ab'⟩ := l ma in by rw mem_unique mb mb'; exact ab' theorem lift_rel_of_mem {R : α → β → Prop} {a b ca cb} (ma : a ∈ ca) (mb : b ∈ cb) (ab : R a b) : lift_rel R ca cb := ⟨λ a' ma', by rw mem_unique ma' ma; exact ⟨b, mb, ab⟩, λ b' mb', by rw mem_unique mb' mb; exact ⟨a, ma, ab⟩⟩ theorem exists_of_lift_rel_left {R : α → β → Prop} {ca cb} (H : lift_rel R ca cb) {a} (h : a ∈ ca) : ∃ {b}, b ∈ cb ∧ R a b := H.left h theorem exists_of_lift_rel_right {R : α → β → Prop} {ca cb} (H : lift_rel R ca cb) {b} (h : b ∈ cb) : ∃ {a}, a ∈ ca ∧ R a b := H.right h theorem lift_rel_def {R : α → β → Prop} {ca cb} : lift_rel R ca cb ↔ (terminates ca ↔ terminates cb) ∧ ∀ {a b}, a ∈ ca → b ∈ cb → R a b := ⟨λh, ⟨terminates_of_lift_rel h, λ a b ma mb, let ⟨b', mb', ab⟩ := h.left ma in by rwa mem_unique mb mb'⟩, λ⟨l, r⟩, ⟨λ a ma, let ⟨b, mb⟩ := l.1 ⟨_, ma⟩ in ⟨b, mb, r ma mb⟩, λ b mb, let ⟨a, ma⟩ := l.2 ⟨_, mb⟩ in ⟨a, ma, r ma mb⟩⟩⟩ theorem lift_rel_bind {δ} (R : α → β → Prop) (S : γ → δ → Prop) {s1 : computation α} {s2 : computation β} {f1 : α → computation γ} {f2 : β → computation δ} (h1 : lift_rel R s1 s2) (h2 : ∀ {a b}, R a b → lift_rel S (f1 a) (f2 b)) : lift_rel S (bind s1 f1) (bind s2 f2) := let ⟨l1, r1⟩ := h1 in ⟨λ c cB, let ⟨a, a1, c₁⟩ := exists_of_mem_bind cB, ⟨b, b2, ab⟩ := l1 a1, ⟨l2, r2⟩ := h2 ab, ⟨d, d2, cd⟩ := l2 c₁ in ⟨_, mem_bind b2 d2, cd⟩, λ d dB, let ⟨b, b1, d1⟩ := exists_of_mem_bind dB, ⟨a, a2, ab⟩ := r1 b1, ⟨l2, r2⟩ := h2 ab, ⟨c, c₂, cd⟩ := r2 d1 in ⟨_, mem_bind a2 c₂, cd⟩⟩ @[simp] theorem lift_rel_return_left (R : α → β → Prop) (a : α) (cb : computation β) : lift_rel R (return a) cb ↔ ∃ {b}, b ∈ cb ∧ R a b := ⟨λ⟨l, r⟩, l (ret_mem _), λ⟨b, mb, ab⟩, ⟨λ a' ma', by rw eq_of_ret_mem ma'; exact ⟨b, mb, ab⟩, λ b' mb', ⟨_, ret_mem _, by rw mem_unique mb' mb; exact ab⟩⟩⟩ @[simp] theorem lift_rel_return_right (R : α → β → Prop) (ca : computation α) (b : β) : lift_rel R ca (return b) ↔ ∃ {a}, a ∈ ca ∧ R a b := by rw [lift_rel.swap, lift_rel_return_left] @[simp] theorem lift_rel_return (R : α → β → Prop) (a : α) (b : β) : lift_rel R (return a) (return b) ↔ R a b := by rw [lift_rel_return_left]; exact ⟨λ⟨b', mb', ab'⟩, by rwa eq_of_ret_mem mb' at ab', λab, ⟨_, ret_mem _, ab⟩⟩ @[simp] theorem lift_rel_think_left (R : α → β → Prop) (ca : computation α) (cb : computation β) : lift_rel R (think ca) cb ↔ lift_rel R ca cb := and_congr (forall_congr $ λb, imp_congr ⟨of_think_mem, think_mem⟩ iff.rfl) (forall_congr $ λb, imp_congr iff.rfl $ exists_congr $ λ b, and_congr ⟨of_think_mem, think_mem⟩ iff.rfl) @[simp] theorem lift_rel_think_right (R : α → β → Prop) (ca : computation α) (cb : computation β) : lift_rel R ca (think cb) ↔ lift_rel R ca cb := by rw [←lift_rel.swap R, ←lift_rel.swap R]; apply lift_rel_think_left theorem lift_rel_mem_cases {R : α → β → Prop} {ca cb} (Ha : ∀ a ∈ ca, lift_rel R ca cb) (Hb : ∀ b ∈ cb, lift_rel R ca cb) : lift_rel R ca cb := ⟨λ a ma, (Ha _ ma).left ma, λ b mb, (Hb _ mb).right mb⟩ theorem lift_rel_congr {R : α → β → Prop} {ca ca' : computation α} {cb cb' : computation β} (ha : ca ~ ca') (hb : cb ~ cb') : lift_rel R ca cb ↔ lift_rel R ca' cb' := and_congr (forall_congr $ λ a, imp_congr (ha _) $ exists_congr $ λ b, and_congr (hb _) iff.rfl) (forall_congr $ λ b, imp_congr (hb _) $ exists_congr $ λ a, and_congr (ha _) iff.rfl) theorem lift_rel_map {δ} (R : α → β → Prop) (S : γ → δ → Prop) {s1 : computation α} {s2 : computation β} {f1 : α → γ} {f2 : β → δ} (h1 : lift_rel R s1 s2) (h2 : ∀ {a b}, R a b → S (f1 a) (f2 b)) : lift_rel S (map f1 s1) (map f2 s2) := by rw [←bind_ret, ←bind_ret]; apply lift_rel_bind _ _ h1; simp; exact @h2 theorem map_congr (R : α → α → Prop) (S : β → β → Prop) {s1 s2 : computation α} {f : α → β} (h1 : s1 ~ s2) : map f s1 ~ map f s2 := by rw [←lift_eq_iff_equiv]; exact lift_rel_map eq _ ((lift_eq_iff_equiv _ _).2 h1) (λ a b, congr_arg _) def lift_rel_aux (R : α → β → Prop) (C : computation α → computation β → Prop) : α ⊕ computation α → β ⊕ computation β → Prop | (sum.inl a) (sum.inl b) := R a b | (sum.inl a) (sum.inr cb) := ∃ {b}, b ∈ cb ∧ R a b | (sum.inr ca) (sum.inl b) := ∃ {a}, a ∈ ca ∧ R a b | (sum.inr ca) (sum.inr cb) := C ca cb attribute [simp] lift_rel_aux @[simp] lemma lift_rel_aux.ret_left (R : α → β → Prop) (C : computation α → computation β → Prop) (a cb) : lift_rel_aux R C (sum.inl a) (destruct cb) ↔ ∃ {b}, b ∈ cb ∧ R a b := begin apply cb.cases_on (λ b, _) (λ cb, _), { exact ⟨λ h, ⟨_, ret_mem _, h⟩, λ ⟨b', mb, h⟩, by rw [mem_unique (ret_mem _) mb]; exact h⟩ }, { rw [destruct_think], exact ⟨λ ⟨b, h, r⟩, ⟨b, think_mem h, r⟩, λ ⟨b, h, r⟩, ⟨b, of_think_mem h, r⟩⟩ } end theorem lift_rel_aux.swap (R : α → β → Prop) (C) (a b) : lift_rel_aux (function.swap R) (function.swap C) b a = lift_rel_aux R C a b := by cases a with a ca; cases b with b cb; simp only [lift_rel_aux] @[simp] lemma lift_rel_aux.ret_right (R : α → β → Prop) (C : computation α → computation β → Prop) (b ca) : lift_rel_aux R C (destruct ca) (sum.inl b) ↔ ∃ {a}, a ∈ ca ∧ R a b := by rw [←lift_rel_aux.swap, lift_rel_aux.ret_left] theorem lift_rel_rec.lem {R : α → β → Prop} (C : computation α → computation β → Prop) (H : ∀ {ca cb}, C ca cb → lift_rel_aux R C (destruct ca) (destruct cb)) (ca cb) (Hc : C ca cb) (a) (ha : a ∈ ca) : lift_rel R ca cb := begin revert cb, refine mem_rec_on ha _ (λ ca' IH, _); intros cb Hc; have h := H Hc, { simp at h, simp [h] }, { have h := H Hc, simp, revert h, apply cb.cases_on (λ b, _) (λ cb', _); intro h; simp at h; simp [h], exact IH _ h } end theorem lift_rel_rec {R : α → β → Prop} (C : computation α → computation β → Prop) (H : ∀ {ca cb}, C ca cb → lift_rel_aux R C (destruct ca) (destruct cb)) (ca cb) (Hc : C ca cb) : lift_rel R ca cb := lift_rel_mem_cases (lift_rel_rec.lem C @H ca cb Hc) (λ b hb, (lift_rel.swap _ _ _).2 $ lift_rel_rec.lem (function.swap C) (λ cb ca h, cast (lift_rel_aux.swap _ _ _ _).symm $ H h) cb ca Hc b hb) end computation
1d37d8c2fe30273ddc1256f0dcde3187eeab2d41
5749d8999a76f3a8fddceca1f6941981e33aaa96
/src/data/finsupp.lean
76d8b513e3d8a1ab7900564cfd1d03ea7fdf95f1
[ "Apache-2.0" ]
permissive
jdsalchow/mathlib
13ab43ef0d0515a17e550b16d09bd14b76125276
497e692b946d93906900bb33a51fd243e7649406
refs/heads/master
1,585,819,143,348
1,580,072,892,000
1,580,072,892,000
154,287,128
0
0
Apache-2.0
1,540,281,610,000
1,540,281,609,000
null
UTF-8
Lean
false
false
61,700
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl Type of functions with finite support. Functions with finite support provide the basis for the following concrete instances: * ℕ →₀ α: Polynomials (where α is a ring) * (σ →₀ ℕ) →₀ α: Multivariate Polynomials (again α is a ring, and σ are variable names) * α →₀ ℕ: Multisets * α →₀ ℤ: Abelian groups freely generated by α * β →₀ α: Linear combinations over β where α is the scalar ring Most of the theory assumes that the range is a commutative monoid. This gives us the big sum operator as a powerful way to construct `finsupp` elements. A general advice is to not use α →₀ β directly, as the type class setup might not be fitting. The best is to define a copy and select the instances best suited. -/ import data.finset data.set.finite algebra.big_operators algebra.module noncomputable theory open_locale classical open finset variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {ι : Type*} {α₁ : Type*} {α₂ : Type*} {β₁ : Type*} {β₂ : Type*} /-- `finsupp α β`, denoted `α →₀ β`, is the type of functions `f : α → β` such that `f x = 0` for all but finitely many `x`. -/ structure finsupp (α : Type*) (β : Type*) [has_zero β] := (support : finset α) (to_fun : α → β) (mem_support_to_fun : ∀a, a ∈ support ↔ to_fun a ≠ 0) infixr ` →₀ `:25 := finsupp namespace finsupp section basic variable [has_zero β] instance : has_coe_to_fun (α →₀ β) := ⟨λ_, α → β, finsupp.to_fun⟩ instance : has_zero (α →₀ β) := ⟨⟨∅, (λ_, 0), λ _, ⟨false.elim, λ H, H rfl⟩⟩⟩ @[simp] lemma zero_apply {a : α} : (0 : α →₀ β) a = 0 := rfl @[simp] lemma support_zero : (0 : α →₀ β).support = ∅ := rfl instance : inhabited (α →₀ β) := ⟨0⟩ @[simp] lemma mem_support_iff {f : α →₀ β} : ∀{a:α}, a ∈ f.support ↔ f a ≠ 0 := f.mem_support_to_fun lemma not_mem_support_iff {f : α →₀ β} {a} : a ∉ f.support ↔ f a = 0 := not_iff_comm.1 mem_support_iff.symm @[ext] lemma ext : ∀{f g : α →₀ β}, (∀a, f a = g a) → f = g | ⟨s, f, hf⟩ ⟨t, g, hg⟩ h := begin have : f = g, { funext a, exact h a }, subst this, have : s = t, { ext a, exact (hf a).trans (hg a).symm }, subst this end lemma ext_iff {f g : α →₀ β} : f = g ↔ (∀a:α, f a = g a) := ⟨by rintros rfl a; refl, ext⟩ @[simp] lemma support_eq_empty {f : α →₀ β} : f.support = ∅ ↔ f = 0 := ⟨assume h, ext $ assume a, by_contradiction $ λ H, (finset.ext.1 h a).1 $ mem_support_iff.2 H, by rintro rfl; refl⟩ instance finsupp.decidable_eq [decidable_eq α] [decidable_eq β] : decidable_eq (α →₀ β) := assume f g, decidable_of_iff (f.support = g.support ∧ (∀a∈f.support, f a = g a)) ⟨assume ⟨h₁, h₂⟩, ext $ assume a, if h : a ∈ f.support then h₂ a h else have hf : f a = 0, by rwa [mem_support_iff, not_not] at h, have hg : g a = 0, by rwa [h₁, mem_support_iff, not_not] at h, by rw [hf, hg], by rintro rfl; exact ⟨rfl, λ _ _, rfl⟩⟩ lemma finite_supp (f : α →₀ β) : set.finite {a | f a ≠ 0} := ⟨fintype.of_finset f.support (λ _, mem_support_iff)⟩ lemma support_subset_iff {s : set α} {f : α →₀ β} : ↑f.support ⊆ s ↔ (∀a∉s, f a = 0) := by simp only [set.subset_def, mem_coe, mem_support_iff]; exact forall_congr (assume a, @not_imp_comm _ _ (classical.dec _) (classical.dec _)) def equiv_fun_on_fintype [fintype α] : (α →₀ β) ≃ (α → β) := ⟨λf a, f a, λf, mk (finset.univ.filter $ λa, f a ≠ 0) f (by simp), begin intro f, ext a, refl end, begin intro f, ext a, refl end⟩ end basic section single variables [has_zero β] {a a' : α} {b : β} /-- `single a b` is the finitely supported function which has value `b` at `a` and zero otherwise. -/ def single (a : α) (b : β) : α →₀ β := ⟨if b = 0 then ∅ else finset.singleton a, λ a', if a = a' then b else 0, λ a', begin by_cases hb : b = 0; by_cases a = a'; simp only [hb, h, if_pos, if_false, mem_singleton], { exact ⟨false.elim, λ H, H rfl⟩ }, { exact ⟨false.elim, λ H, H rfl⟩ }, { exact ⟨λ _, hb, λ _, rfl⟩ }, { exact ⟨λ H _, h H.symm, λ H, (H rfl).elim⟩ } end⟩ lemma single_apply : (single a b : α →₀ β) a' = if a = a' then b else 0 := rfl @[simp] lemma single_eq_same : (single a b : α →₀ β) a = b := if_pos rfl @[simp] lemma single_eq_of_ne (h : a ≠ a') : (single a b : α →₀ β) a' = 0 := if_neg h @[simp] lemma single_zero : (single a 0 : α →₀ β) = 0 := ext $ assume a', begin by_cases h : a = a', { rw [h, single_eq_same, zero_apply] }, { rw [single_eq_of_ne h, zero_apply] } end lemma support_single_ne_zero (hb : b ≠ 0) : (single a b).support = {a} := if_neg hb lemma support_single_subset : (single a b).support ⊆ {a} := show ite _ _ _ ⊆ _, by split_ifs; [exact empty_subset _, exact subset.refl _] lemma injective_single (a : α) : function.injective (single a : β → α →₀ β) := assume b₁ b₂ eq, have (single a b₁ : α →₀ β) a = (single a b₂ : α →₀ β) a, by rw eq, by rwa [single_eq_same, single_eq_same] at this lemma single_eq_single_iff (a₁ a₂ : α) (b₁ b₂ : β) : single a₁ b₁ = single a₂ b₂ ↔ ((a₁ = a₂ ∧ b₁ = b₂) ∨ (b₁ = 0 ∧ b₂ = 0)) := begin split, { assume eq, by_cases a₁ = a₂, { refine or.inl ⟨h, _⟩, rwa [h, (injective_single a₂).eq_iff] at eq }, { rw [finsupp.ext_iff] at eq, have h₁ := eq a₁, have h₂ := eq a₂, simp only [single_eq_same, single_eq_of_ne h, single_eq_of_ne (ne.symm h)] at h₁ h₂, exact or.inr ⟨h₁, h₂.symm⟩ } }, { rintros (⟨rfl, rfl⟩ | ⟨rfl, rfl⟩), { refl }, { rw [single_zero, single_zero] } } end lemma single_right_inj (h : b ≠ 0) : single a b = single a' b ↔ a = a' := ⟨λ H, by simpa [h, single_eq_single_iff] using H, λ H, by rw [H]⟩ lemma single_eq_zero : single a b = 0 ↔ b = 0 := ⟨λ h, by { rw ext_iff at h, simpa only [finsupp.single_eq_same, finsupp.zero_apply] using h a }, λ h, by rw [h, single_zero]⟩ lemma single_swap {α β : Type*} [has_zero β] (a₁ a₂ : α) (b : β) : (single a₁ b : α → β) a₂ = (single a₂ b : α → β) a₁ := by simp [single_apply]; ac_refl lemma unique_single [unique α] (x : α →₀ β) : x = single (default α) (x (default α)) := by ext i; simp [unique.eq_default i] @[simp] lemma unique_single_eq_iff [unique α] {b' : β} : single a b = single a' b' ↔ b = b' := begin rw [single_eq_single_iff], split, { rintros (⟨_, rfl⟩ | ⟨rfl, rfl⟩); refl }, { intro h, left, exact ⟨subsingleton.elim _ _, h⟩ } end end single section on_finset variables [has_zero β] /-- `on_finset s f hf` is the finsupp function representing `f` restricted to the set `s`. The function needs to be 0 outside of `s`. Use this when the set needs filtered anyway, otherwise often better set representation is available. -/ def on_finset (s : finset α) (f : α → β) (hf : ∀a, f a ≠ 0 → a ∈ s) : α →₀ β := ⟨s.filter (λa, f a ≠ 0), f, assume a, classical.by_cases (assume h : f a = 0, by rw mem_filter; exact ⟨and.right, λ H, (H h).elim⟩) (assume h : f a ≠ 0, by rw mem_filter; simp only [iff_true_intro h, hf a h, true_and])⟩ @[simp] lemma on_finset_apply {s : finset α} {f : α → β} {hf a} : (on_finset s f hf : α →₀ β) a = f a := rfl @[simp] lemma support_on_finset_subset {s : finset α} {f : α → β} {hf} : (on_finset s f hf).support ⊆ s := filter_subset _ end on_finset section map_range variables [has_zero β₁] [has_zero β₂] /-- The composition of `f : β₁ → β₂` and `g : α →₀ β₁` is `map_range f hf g : α →₀ β₂`, well defined when `f 0 = 0`. -/ def map_range (f : β₁ → β₂) (hf : f 0 = 0) (g : α →₀ β₁) : α →₀ β₂ := on_finset g.support (f ∘ g) $ assume a, by rw [mem_support_iff, not_imp_not]; exact λ H, (congr_arg f H).trans hf @[simp] lemma map_range_apply {f : β₁ → β₂} {hf : f 0 = 0} {g : α →₀ β₁} {a : α} : map_range f hf g a = f (g a) := rfl @[simp] lemma map_range_zero {f : β₁ → β₂} {hf : f 0 = 0} : map_range f hf (0 : α →₀ β₁) = 0 := finsupp.ext $ λ a, by simp [hf] lemma support_map_range {f : β₁ → β₂} {hf : f 0 = 0} {g : α →₀ β₁} : (map_range f hf g).support ⊆ g.support := support_on_finset_subset @[simp] lemma map_range_single {f : β₁ → β₂} {hf : f 0 = 0} {a : α} {b : β₁} : map_range f hf (single a b) = single a (f b) := finsupp.ext $ λ a', show f (ite _ _ _) = ite _ _ _, by split_ifs; [refl, exact hf] end map_range section emb_domain variables [has_zero β] /-- Given `f : α₁ ↪ α₂` and `v : α₁ →₀ β`, `emb_domain f v : α₂ →₀ β` is the finitely supported function whose value at `f a : α₂` is `v a`. For a `b : α₂` outside the range of `f` it is zero. -/ def emb_domain (f : α₁ ↪ α₂) (v : α₁ →₀ β) : α₂ →₀ β := begin refine ⟨v.support.map f, λa₂, if h : a₂ ∈ v.support.map f then v (v.support.choose (λa₁, f a₁ = a₂) _) else 0, _⟩, { rcases finset.mem_map.1 h with ⟨a, ha, rfl⟩, exact exists_unique.intro a ⟨ha, rfl⟩ (assume b ⟨_, hb⟩, f.inj hb) }, { assume a₂, split_ifs, { simp [h], rw [← finsupp.not_mem_support_iff, not_not], apply finset.choose_mem }, { simp [h] } } end lemma support_emb_domain (f : α₁ ↪ α₂) (v : α₁ →₀ β) : (emb_domain f v).support = v.support.map f := rfl lemma emb_domain_zero (f : α₁ ↪ α₂) : (emb_domain f 0 : α₂ →₀ β) = 0 := rfl lemma emb_domain_apply (f : α₁ ↪ α₂) (v : α₁ →₀ β) (a : α₁) : emb_domain f v (f a) = v a := begin change dite _ _ _ = _, split_ifs; rw [finset.mem_map' f] at h, { refine congr_arg (v : α₁ → β) (f.inj' _), exact finset.choose_property (λa₁, f a₁ = f a) _ _ }, { exact (finsupp.not_mem_support_iff.1 h).symm } end lemma emb_domain_notin_range (f : α₁ ↪ α₂) (v : α₁ →₀ β) (a : α₂) (h : a ∉ set.range f) : emb_domain f v a = 0 := begin refine dif_neg (mt (assume h, _) h), rcases finset.mem_map.1 h with ⟨a, h, rfl⟩, exact set.mem_range_self a end lemma emb_domain_inj {f : α₁ ↪ α₂} {l₁ l₂ : α₁ →₀ β} : emb_domain f l₁ = emb_domain f l₂ ↔ l₁ = l₂ := ⟨λ h, finsupp.ext $ λ a, by simpa [emb_domain_apply] using finsupp.ext_iff.1 h (f a), λ h, by rw h⟩ lemma emb_domain_map_range {β₁ β₂ : Type*} [has_zero β₁] [has_zero β₂] (f : α₁ ↪ α₂) (g : β₁ → β₂) (p : α₁ →₀ β₁) (hg : g 0 = 0) : emb_domain f (map_range g hg p) = map_range g hg (emb_domain f p) := begin ext a, by_cases a ∈ set.range f, { rcases h with ⟨a', rfl⟩, rw [map_range_apply, emb_domain_apply, emb_domain_apply, map_range_apply] }, { rw [map_range_apply, emb_domain_notin_range, emb_domain_notin_range, ← hg]; assumption } end lemma single_of_emb_domain_single (l : α₁ →₀ β) (f : α₁ ↪ α₂) (a : α₂) (b : β) (hb : b ≠ 0) (h : l.emb_domain f = finsupp.single a b) : ∃ x, l = finsupp.single x b ∧ f x = a := begin have h_map_support : finset.map f (l.support) = finset.singleton a, by rw [←finsupp.support_emb_domain, h, finsupp.support_single_ne_zero hb]; refl, have ha : a ∈ finset.map f (l.support), by simp [h_map_support], rcases finset.mem_map.1 ha with ⟨c, hc₁, hc₂⟩, use c, split, { ext d, rw [← finsupp.emb_domain_apply f l, h], by_cases h_cases : c = d, { simp [h_cases.symm, hc₂] }, { rw [finsupp.single_apply, finsupp.single_apply, if_neg, if_neg h_cases], by_contra hfd, exact h_cases (f.inj (hc₂.trans hfd)) } }, { exact hc₂ } end end emb_domain section zip_with variables [has_zero β] [has_zero β₁] [has_zero β₂] /-- `zip_with f hf g₁ g₂` is the finitely supported function satisfying `zip_with f hf g₁ g₂ a = f (g₁ a) (g₂ a)`, and well defined when `f 0 0 = 0`. -/ def zip_with (f : β₁ → β₂ → β) (hf : f 0 0 = 0) (g₁ : α →₀ β₁) (g₂ : α →₀ β₂) : (α →₀ β) := on_finset (g₁.support ∪ g₂.support) (λa, f (g₁ a) (g₂ a)) $ λ a H, begin simp only [mem_union, mem_support_iff, ne], rw [← not_and_distrib], rintro ⟨h₁, h₂⟩, rw [h₁, h₂] at H, exact H hf end @[simp] lemma zip_with_apply {f : β₁ → β₂ → β} {hf : f 0 0 = 0} {g₁ : α →₀ β₁} {g₂ : α →₀ β₂} {a : α} : zip_with f hf g₁ g₂ a = f (g₁ a) (g₂ a) := rfl lemma support_zip_with {f : β₁ → β₂ → β} {hf : f 0 0 = 0} {g₁ : α →₀ β₁} {g₂ : α →₀ β₂} : (zip_with f hf g₁ g₂).support ⊆ g₁.support ∪ g₂.support := support_on_finset_subset end zip_with section erase def erase [has_zero β] (a : α) (f : α →₀ β) : α →₀ β := ⟨f.support.erase a, (λa', if a' = a then 0 else f a'), assume a', by rw [mem_erase, mem_support_iff]; split_ifs; [exact ⟨λ H _, H.1 h, λ H, (H rfl).elim⟩, exact and_iff_right h]⟩ @[simp] lemma support_erase [has_zero β] {a : α} {f : α →₀ β} : (f.erase a).support = f.support.erase a := rfl @[simp] lemma erase_same [has_zero β] {a : α} {f : α →₀ β} : (f.erase a) a = 0 := if_pos rfl @[simp] lemma erase_ne [has_zero β] {a a' : α} {f : α →₀ β} (h : a' ≠ a) : (f.erase a) a' = f a' := if_neg h end erase -- [to_additive sum] for finsupp.prod doesn't work, the equation lemmas are not generated /-- `sum f g` is the sum of `g a (f a)` over the support of `f`. -/ def sum [has_zero β] [add_comm_monoid γ] (f : α →₀ β) (g : α → β → γ) : γ := f.support.sum (λa, g a (f a)) /-- `prod f g` is the product of `g a (f a)` over the support of `f`. -/ @[to_additive] def prod [has_zero β] [comm_monoid γ] (f : α →₀ β) (g : α → β → γ) : γ := f.support.prod (λa, g a (f a)) @[to_additive] lemma prod_map_range_index [has_zero β₁] [has_zero β₂] [comm_monoid γ] {f : β₁ → β₂} {hf : f 0 = 0} {g : α →₀ β₁} {h : α → β₂ → γ} (h0 : ∀a, h a 0 = 1) : (map_range f hf g).prod h = g.prod (λa b, h a (f b)) := finset.prod_subset support_map_range $ λ _ _ H, by rw [not_mem_support_iff.1 H, h0] @[to_additive] lemma prod_zero_index [add_comm_monoid β] [comm_monoid γ] {h : α → β → γ} : (0 : α →₀ β).prod h = 1 := rfl section nat_sub instance nat_sub : has_sub (α →₀ ℕ) := ⟨zip_with (λ m n, m - n) (nat.sub_zero 0)⟩ @[simp] lemma nat_sub_apply {g₁ g₂ : α →₀ ℕ} {a : α} : (g₁ - g₂) a = g₁ a - g₂ a := rfl end nat_sub section add_monoid variables [add_monoid β] @[to_additive] lemma prod_single_index [comm_monoid γ] {a : α} {b : β} {h : α → β → γ} (h_zero : h a 0 = 1) : (single a b).prod h = h a b := begin by_cases h : b = 0, { simp only [h, h_zero, single_zero]; refl }, { simp only [finsupp.prod, support_single_ne_zero h, insert_empty_eq_singleton, prod_singleton, single_eq_same] } end instance : has_add (α →₀ β) := ⟨zip_with (+) (add_zero 0)⟩ @[simp] lemma add_apply {g₁ g₂ : α →₀ β} {a : α} : (g₁ + g₂) a = g₁ a + g₂ a := rfl lemma support_add {g₁ g₂ : α →₀ β} : (g₁ + g₂).support ⊆ g₁.support ∪ g₂.support := support_zip_with lemma support_add_eq {g₁ g₂ : α →₀ β} (h : disjoint g₁.support g₂.support) : (g₁ + g₂).support = g₁.support ∪ g₂.support := le_antisymm support_zip_with $ assume a ha, (finset.mem_union.1 ha).elim (assume ha, have a ∉ g₂.support, from disjoint_left.1 h ha, by simp only [mem_support_iff, not_not] at *; simpa only [add_apply, this, add_zero]) (assume ha, have a ∉ g₁.support, from disjoint_right.1 h ha, by simp only [mem_support_iff, not_not] at *; simpa only [add_apply, this, zero_add]) @[simp] lemma single_add {a : α} {b₁ b₂ : β} : single a (b₁ + b₂) = single a b₁ + single a b₂ := ext $ assume a', begin by_cases h : a = a', { rw [h, add_apply, single_eq_same, single_eq_same, single_eq_same] }, { rw [add_apply, single_eq_of_ne h, single_eq_of_ne h, single_eq_of_ne h, zero_add] } end instance : add_monoid (α →₀ β) := { add_monoid . zero := 0, add := (+), add_assoc := assume ⟨s, f, hf⟩ ⟨t, g, hg⟩ ⟨u, h, hh⟩, ext $ assume a, add_assoc _ _ _, zero_add := assume ⟨s, f, hf⟩, ext $ assume a, zero_add _, add_zero := assume ⟨s, f, hf⟩, ext $ assume a, add_zero _ } instance (a : α) : is_add_monoid_hom (λ g : α →₀ β, g a) := { map_add := λ _ _, add_apply, map_zero := zero_apply } lemma single_add_erase {a : α} {f : α →₀ β} : single a (f a) + f.erase a = f := ext $ λ a', if h : a = a' then by subst h; simp only [add_apply, single_eq_same, erase_same, add_zero] else by simp only [add_apply, single_eq_of_ne h, zero_add, erase_ne (ne.symm h)] lemma erase_add_single {a : α} {f : α →₀ β} : f.erase a + single a (f a) = f := ext $ λ a', if h : a = a' then by subst h; simp only [add_apply, single_eq_same, erase_same, zero_add] else by simp only [add_apply, single_eq_of_ne h, add_zero, erase_ne (ne.symm h)] @[elab_as_eliminator] protected theorem induction {p : (α →₀ β) → Prop} (f : α →₀ β) (h0 : p 0) (ha : ∀a b (f : α →₀ β), a ∉ f.support → b ≠ 0 → p f → p (single a b + f)) : p f := suffices ∀s (f : α →₀ β), f.support = s → p f, from this _ _ rfl, assume s, finset.induction_on s (λ f hf, by rwa [support_eq_empty.1 hf]) $ assume a s has ih f hf, suffices p (single a (f a) + f.erase a), by rwa [single_add_erase] at this, begin apply ha, { rw [support_erase, mem_erase], exact λ H, H.1 rfl }, { rw [← mem_support_iff, hf], exact mem_insert_self _ _ }, { apply ih _ _, rw [support_erase, hf, finset.erase_insert has] } end lemma induction₂ {p : (α →₀ β) → Prop} (f : α →₀ β) (h0 : p 0) (ha : ∀a b (f : α →₀ β), a ∉ f.support → b ≠ 0 → p f → p (f + single a b)) : p f := suffices ∀s (f : α →₀ β), f.support = s → p f, from this _ _ rfl, assume s, finset.induction_on s (λ f hf, by rwa [support_eq_empty.1 hf]) $ assume a s has ih f hf, suffices p (f.erase a + single a (f a)), by rwa [erase_add_single] at this, begin apply ha, { rw [support_erase, mem_erase], exact λ H, H.1 rfl }, { rw [← mem_support_iff, hf], exact mem_insert_self _ _ }, { apply ih _ _, rw [support_erase, hf, finset.erase_insert has] } end lemma map_range_add [add_monoid β₁] [add_monoid β₂] {f : β₁ → β₂} {hf : f 0 = 0} (hf' : ∀ x y, f (x + y) = f x + f y) (v₁ v₂ : α →₀ β₁) : map_range f hf (v₁ + v₂) = map_range f hf v₁ + map_range f hf v₂ := finsupp.ext $ λ a, by simp [hf'] end add_monoid instance [add_comm_monoid β] : add_comm_monoid (α →₀ β) := { add_comm := assume ⟨s, f, _⟩ ⟨t, g, _⟩, ext $ assume a, add_comm _ _, .. finsupp.add_monoid } instance [add_group β] : add_group (α →₀ β) := { neg := map_range (has_neg.neg) neg_zero, add_left_neg := assume ⟨s, f, _⟩, ext $ assume x, add_left_neg _, .. finsupp.add_monoid } lemma single_multiset_sum [add_comm_monoid β] (s : multiset β) (a : α) : single a s.sum = (s.map (single a)).sum := multiset.induction_on s single_zero $ λ a s ih, by rw [multiset.sum_cons, single_add, ih, multiset.map_cons, multiset.sum_cons] lemma single_finset_sum [add_comm_monoid β] (s : finset γ) (f : γ → β) (a : α) : single a (s.sum f) = s.sum (λb, single a (f b)) := begin transitivity, apply single_multiset_sum, rw [multiset.map_map], refl end lemma single_sum [has_zero γ] [add_comm_monoid β] (s : δ →₀ γ) (f : δ → γ → β) (a : α) : single a (s.sum f) = s.sum (λd c, single a (f d c)) := single_finset_sum _ _ _ @[to_additive] lemma prod_neg_index [add_group β] [comm_monoid γ] {g : α →₀ β} {h : α → β → γ} (h0 : ∀a, h a 0 = 1) : (-g).prod h = g.prod (λa b, h a (- b)) := prod_map_range_index h0 @[simp] lemma neg_apply [add_group β] {g : α →₀ β} {a : α} : (- g) a = - g a := rfl @[simp] lemma sub_apply [add_group β] {g₁ g₂ : α →₀ β} {a : α} : (g₁ - g₂) a = g₁ a - g₂ a := rfl @[simp] lemma support_neg [add_group β] {f : α →₀ β} : support (-f) = support f := finset.subset.antisymm support_map_range (calc support f = support (- (- f)) : congr_arg support (neg_neg _).symm ... ⊆ support (- f) : support_map_range) instance [add_comm_group β] : add_comm_group (α →₀ β) := { add_comm := add_comm, ..finsupp.add_group } @[simp] lemma sum_apply [has_zero β₁] [add_comm_monoid β] {f : α₁ →₀ β₁} {g : α₁ → β₁ → α →₀ β} {a₂ : α} : (f.sum g) a₂ = f.sum (λa₁ b, g a₁ b a₂) := (f.support.sum_hom (λf : α →₀ β, f a₂)).symm lemma support_sum [has_zero β₁] [add_comm_monoid β] {f : α₁ →₀ β₁} {g : α₁ → β₁ → (α →₀ β)} : (f.sum g).support ⊆ f.support.bind (λa, (g a (f a)).support) := have ∀a₁ : α, f.sum (λ (a : α₁) (b : β₁), (g a b) a₁) ≠ 0 → (∃ (a : α₁), f a ≠ 0 ∧ ¬ (g a (f a)) a₁ = 0), from assume a₁ h, let ⟨a, ha, ne⟩ := finset.exists_ne_zero_of_sum_ne_zero h in ⟨a, mem_support_iff.mp ha, ne⟩, by simpa only [finset.subset_iff, mem_support_iff, finset.mem_bind, sum_apply, exists_prop] using this @[simp] lemma sum_zero [add_comm_monoid β] [add_comm_monoid γ] {f : α →₀ β} : f.sum (λa b, (0 : γ)) = 0 := finset.sum_const_zero @[simp] lemma sum_add [add_comm_monoid β] [add_comm_monoid γ] {f : α →₀ β} {h₁ h₂ : α → β → γ} : f.sum (λa b, h₁ a b + h₂ a b) = f.sum h₁ + f.sum h₂ := finset.sum_add_distrib @[simp] lemma sum_neg [add_comm_monoid β] [add_comm_group γ] {f : α →₀ β} {h : α → β → γ} : f.sum (λa b, - h a b) = - f.sum h := f.support.sum_hom (@has_neg.neg γ _) @[simp] lemma sum_sub [add_comm_monoid β] [add_comm_group γ] {f : α →₀ β} {h₁ h₂ : α → β → γ} : f.sum (λa b, h₁ a b - h₂ a b) = f.sum h₁ - f.sum h₂ := by rw [sub_eq_add_neg, ←sum_neg, ←sum_add]; refl @[simp] lemma sum_single [add_comm_monoid β] (f : α →₀ β) : f.sum single = f := have ∀a:α, f.sum (λa' b, ite (a' = a) b 0) = ({a} : finset α).sum (λa', ite (a' = a) (f a') 0), begin intro a, by_cases h : a ∈ f.support, { have : (finset.singleton a : finset α) ⊆ f.support, { simpa only [finset.subset_iff, mem_singleton, forall_eq] }, refine (finset.sum_subset this (λ _ _ H, _)).symm, exact if_neg (mt mem_singleton.2 H) }, { transitivity (f.support.sum (λa, (0 : β))), { refine (finset.sum_congr rfl $ λ a' ha', if_neg _), rintro rfl, exact h ha' }, { rw [sum_const_zero, insert_empty_eq_singleton, sum_singleton, if_pos rfl, not_mem_support_iff.1 h] } } end, ext $ assume a, by simp only [sum_apply, single_apply, this, insert_empty_eq_singleton, sum_singleton, if_pos] @[to_additive] lemma prod_add_index [add_comm_monoid β] [comm_monoid γ] {f g : α →₀ β} {h : α → β → γ} (h_zero : ∀a, h a 0 = 1) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂) : (f + g).prod h = f.prod h * g.prod h := have f_eq : (f.support ∪ g.support).prod (λa, h a (f a)) = f.prod h, from (finset.prod_subset (finset.subset_union_left _ _) $ by intros _ _ H; rw [not_mem_support_iff.1 H, h_zero]).symm, have g_eq : (f.support ∪ g.support).prod (λa, h a (g a)) = g.prod h, from (finset.prod_subset (finset.subset_union_right _ _) $ by intros _ _ H; rw [not_mem_support_iff.1 H, h_zero]).symm, calc (f + g).support.prod (λa, h a ((f + g) a)) = (f.support ∪ g.support).prod (λa, h a ((f + g) a)) : finset.prod_subset support_add $ by intros _ _ H; rw [not_mem_support_iff.1 H, h_zero] ... = (f.support ∪ g.support).prod (λa, h a (f a)) * (f.support ∪ g.support).prod (λa, h a (g a)) : by simp only [add_apply, h_add, finset.prod_mul_distrib] ... = _ : by rw [f_eq, g_eq] lemma sum_sub_index [add_comm_group β] [add_comm_group γ] {f g : α →₀ β} {h : α → β → γ} (h_sub : ∀a b₁ b₂, h a (b₁ - b₂) = h a b₁ - h a b₂) : (f - g).sum h = f.sum h - g.sum h := have h_zero : ∀a, h a 0 = 0, from assume a, have h a (0 - 0) = h a 0 - h a 0, from h_sub a 0 0, by simpa only [sub_self] using this, have h_neg : ∀a b, h a (- b) = - h a b, from assume a b, have h a (0 - b) = h a 0 - h a b, from h_sub a 0 b, by simpa only [h_zero, zero_sub] using this, have h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ + h a b₂, from assume a b₁ b₂, have h a (b₁ - (- b₂)) = h a b₁ - h a (- b₂), from h_sub a b₁ (-b₂), by simpa only [h_neg, sub_neg_eq_add] using this, calc (f - g).sum h = (f + - g).sum h : rfl ... = f.sum h + - g.sum h : by simp only [sum_add_index h_zero h_add, sum_neg_index h_zero, h_neg, sum_neg] ... = f.sum h - g.sum h : rfl @[to_additive] lemma prod_finset_sum_index [add_comm_monoid β] [comm_monoid γ] {s : finset ι} {g : ι → α →₀ β} {h : α → β → γ} (h_zero : ∀a, h a 0 = 1) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂) : s.prod (λi, (g i).prod h) = (s.sum g).prod h := finset.induction_on s rfl $ λ a s has ih, by rw [prod_insert has, ih, sum_insert has, prod_add_index h_zero h_add] @[to_additive] lemma prod_sum_index [add_comm_monoid β₁] [add_comm_monoid β] [comm_monoid γ] {f : α₁ →₀ β₁} {g : α₁ → β₁ → α →₀ β} {h : α → β → γ} (h_zero : ∀a, h a 0 = 1) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂) : (f.sum g).prod h = f.prod (λa b, (g a b).prod h) := (prod_finset_sum_index h_zero h_add).symm lemma multiset_sum_sum_index [add_comm_monoid β] [add_comm_monoid γ] (f : multiset (α →₀ β)) (h : α → β → γ) (h₀ : ∀a, h a 0 = 0) (h₁ : ∀ (a : α) (b₁ b₂ : β), h a (b₁ + b₂) = h a b₁ + h a b₂) : (f.sum.sum h) = (f.map $ λg:α →₀ β, g.sum h).sum := multiset.induction_on f rfl $ assume a s ih, by rw [multiset.sum_cons, multiset.map_cons, multiset.sum_cons, sum_add_index h₀ h₁, ih] lemma multiset_map_sum [has_zero β] {f : α →₀ β} {m : γ → δ} {h : α → β → multiset γ} : multiset.map m (f.sum h) = f.sum (λa b, (h a b).map m) := (f.support.sum_hom _).symm lemma multiset_sum_sum [has_zero β] [add_comm_monoid γ] {f : α →₀ β} {h : α → β → multiset γ} : multiset.sum (f.sum h) = f.sum (λa b, multiset.sum (h a b)) := (f.support.sum_hom multiset.sum).symm section map_range variables [add_comm_monoid β₁] [add_comm_monoid β₂] (f : β₁ → β₂) [hf : is_add_monoid_hom f] instance is_add_monoid_hom_map_range : is_add_monoid_hom (map_range f hf.map_zero : (α →₀ β₁) → (α →₀ β₂)) := { map_zero := map_range_zero, map_add := λ a b, map_range_add hf.map_add _ _ } lemma map_range_multiset_sum (m : multiset (α →₀ β₁)) : map_range f hf.map_zero m.sum = (m.map $ λx, map_range f hf.map_zero x).sum := (m.sum_hom (map_range f hf.map_zero)).symm lemma map_range_finset_sum {ι : Type*} (s : finset ι) (g : ι → (α →₀ β₁)) : map_range f hf.map_zero (s.sum g) = s.sum (λx, map_range f hf.map_zero (g x)) := by rw [finset.sum.equations._eqn_1, map_range_multiset_sum, multiset.map_map]; refl end map_range section map_domain variables [add_comm_monoid β] {v v₁ v₂ : α →₀ β} /-- Given `f : α₁ → α₂` and `v : α₁ →₀ β`, `map_domain f v : α₂ →₀ β` is the finitely supported function whose value at `a : α₂` is the sum of `v x` over all `x` such that `f x = a`. -/ def map_domain (f : α₁ → α₂) (v : α₁ →₀ β) : α₂ →₀ β := v.sum $ λa, single (f a) lemma map_domain_apply {f : α₁ → α₂} (hf : function.injective f) (x : α₁ →₀ β) (a : α₁) : map_domain f x (f a) = x a := begin rw [map_domain, sum_apply, sum, finset.sum_eq_single a, single_eq_same], { assume b _ hba, exact single_eq_of_ne (hf.ne hba) }, { simp only [(∉), (≠), not_not, mem_support_iff], assume h, rw [h, single_zero], refl } end lemma map_domain_notin_range {f : α₁ → α₂} (x : α₁ →₀ β) (a : α₂) (h : a ∉ set.range f) : map_domain f x a = 0 := begin rw [map_domain, sum_apply, sum], exact finset.sum_eq_zero (assume a' h', single_eq_of_ne $ assume eq, h $ eq ▸ set.mem_range_self _) end lemma map_domain_id : map_domain id v = v := sum_single _ lemma map_domain_comp {f : α → α₁} {g : α₁ → α₂} : map_domain (g ∘ f) v = map_domain g (map_domain f v) := begin refine ((sum_sum_index _ _).trans _).symm, { intros, exact single_zero }, { intros, exact single_add }, refine sum_congr rfl (λ _ _, sum_single_index _), { exact single_zero } end lemma map_domain_single {f : α → α₁} {a : α} {b : β} : map_domain f (single a b) = single (f a) b := sum_single_index single_zero @[simp] lemma map_domain_zero {f : α → α₂} : map_domain f 0 = (0 : α₂ →₀ β) := sum_zero_index lemma map_domain_congr {f g : α → α₂} (h : ∀x∈v.support, f x = g x) : v.map_domain f = v.map_domain g := finset.sum_congr rfl $ λ _ H, by simp only [h _ H] lemma map_domain_add {f : α → α₂} : map_domain f (v₁ + v₂) = map_domain f v₁ + map_domain f v₂ := sum_add_index (λ _, single_zero) (λ _ _ _, single_add) lemma map_domain_finset_sum {f : α → α₂} {s : finset ι} {v : ι → α →₀ β} : map_domain f (s.sum v) = s.sum (λi, map_domain f (v i)) := eq.symm $ sum_finset_sum_index (λ _, single_zero) (λ _ _ _, single_add) lemma map_domain_sum [has_zero β₁] {f : α → α₂} {s : α →₀ β₁} {v : α → β₁ → α →₀ β} : map_domain f (s.sum v) = s.sum (λa b, map_domain f (v a b)) := eq.symm $ sum_finset_sum_index (λ _, single_zero) (λ _ _ _, single_add) lemma map_domain_support {f : α → α₂} {s : α →₀ β} : (s.map_domain f).support ⊆ s.support.image f := finset.subset.trans support_sum $ finset.subset.trans (finset.bind_mono $ assume a ha, support_single_subset) $ by rw [finset.bind_singleton]; exact subset.refl _ @[to_additive] lemma prod_map_domain_index [comm_monoid γ] {f : α → α₂} {s : α →₀ β} {h : α₂ → β → γ} (h_zero : ∀a, h a 0 = 1) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂) : (s.map_domain f).prod h = s.prod (λa b, h (f a) b) := (prod_sum_index h_zero h_add).trans $ prod_congr rfl $ λ _ _, prod_single_index (h_zero _) lemma emb_domain_eq_map_domain (f : α₁ ↪ α₂) (v : α₁ →₀ β) : emb_domain f v = map_domain f v := begin ext a, by_cases a ∈ set.range f, { rcases h with ⟨a, rfl⟩, rw [map_domain_apply (function.embedding.inj' _), emb_domain_apply] }, { rw [map_domain_notin_range, emb_domain_notin_range]; assumption } end lemma injective_map_domain {f : α₁ → α₂} (hf : function.injective f) : function.injective (map_domain f : (α₁ →₀ β) → (α₂ →₀ β)) := begin assume v₁ v₂ eq, ext a, have : map_domain f v₁ (f a) = map_domain f v₂ (f a), { rw eq }, rwa [map_domain_apply hf, map_domain_apply hf] at this, end end map_domain section comap_domain noncomputable def comap_domain {α₁ α₂ γ : Type*} [has_zero γ] (f : α₁ → α₂) (l : α₂ →₀ γ) (hf : set.inj_on f (f ⁻¹' l.support.to_set)) : α₁ →₀ γ := { support := l.support.preimage hf, to_fun := (λ a, l (f a)), mem_support_to_fun := begin intros a, simp only [finset.mem_def.symm, finset.mem_preimage], exact l.mem_support_to_fun (f a), end } lemma comap_domain_apply {α₁ α₂ γ : Type*} [has_zero γ] (f : α₁ → α₂) (l : α₂ →₀ γ) (hf : set.inj_on f (f ⁻¹' l.support.to_set)) (a : α₁) : comap_domain f l hf a = l (f a) := begin unfold_coes, unfold comap_domain, simp, refl end lemma sum_comap_domain {α₁ α₂ β γ : Type*} [has_zero β] [add_comm_monoid γ] (f : α₁ → α₂) (l : α₂ →₀ β) (g : α₂ → β → γ) (hf : set.bij_on f (f ⁻¹' l.support.to_set) l.support.to_set): (comap_domain f l (set.inj_on_of_bij_on hf)).sum (g ∘ f) = l.sum g := begin unfold sum, haveI := classical.dec_eq α₂, simp only [comap_domain, comap_domain_apply, finset.sum_preimage f _ _ (λ (x : α₂), g x (l x))], end lemma eq_zero_of_comap_domain_eq_zero {α₁ α₂ γ : Type*} [add_comm_monoid γ] (f : α₁ → α₂) (l : α₂ →₀ γ) (hf : set.bij_on f (f ⁻¹' l.support.to_set) l.support.to_set) : comap_domain f l (set.inj_on_of_bij_on hf) = 0 → l = 0 := begin rw [← support_eq_empty, ← support_eq_empty, comap_domain], simp only [finset.ext, finset.not_mem_empty, iff_false, mem_preimage], assume h a ha, cases hf.2.2 ha with b hb, exact h b (hb.2.symm ▸ ha) end lemma map_domain_comap_domain {α₁ α₂ γ : Type*} [add_comm_monoid γ] (f : α₁ → α₂) (l : α₂ →₀ γ) (hf : function.injective f) (hl : ↑l.support ⊆ set.range f): map_domain f (comap_domain f l (set.inj_on_of_injective _ hf)) = l := begin ext a, haveI := classical.dec (a ∈ set.range f), by_cases h_cases: a ∈ set.range f, { rcases set.mem_range.1 h_cases with ⟨b, hb⟩, rw [hb.symm, map_domain_apply hf, comap_domain_apply] }, { rw map_domain_notin_range _ _ h_cases, by_contra h_contr, apply h_cases (hl (finset.mem_coe.2 (mem_support_iff.2 (λ h, h_contr h.symm)))) } end end comap_domain /-- The product of `f g : α →₀ β` is the finitely supported function whose value at `a` is the sum of `f x * g y` over all pairs `x, y` such that `x + y = a`. (Think of the product of multivariate polynomials where `α` is the monoid of monomial exponents.) -/ instance [has_add α] [semiring β] : has_mul (α →₀ β) := ⟨λf g, f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, single (a₁ + a₂) (b₁ * b₂)⟩ lemma mul_def [has_add α] [semiring β] {f g : α →₀ β} : f * g = (f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, single (a₁ + a₂) (b₁ * b₂)) := rfl lemma support_mul [has_add α] [semiring β] (a b : α →₀ β) : (a * b).support ⊆ a.support.bind (λa₁, b.support.bind $ λa₂, {a₁ + a₂}) := subset.trans support_sum $ bind_mono $ assume a₁ _, subset.trans support_sum $ bind_mono $ assume a₂ _, support_single_subset /-- The unit of the multiplication is `single 0 1`, i.e. the function that is 1 at 0 and zero elsewhere. -/ instance [has_zero α] [has_zero β] [has_one β] : has_one (α →₀ β) := ⟨single 0 1⟩ lemma one_def [has_zero α] [has_zero β] [has_one β] : 1 = (single 0 1 : α →₀ β) := rfl section filter section has_zero variables [has_zero β] (p : α → Prop) (f : α →₀ β) /-- `filter p f` is the function which is `f a` if `p a` is true and 0 otherwise. -/ def filter (p : α → Prop) (f : α →₀ β) : α →₀ β := on_finset f.support (λa, if p a then f a else 0) $ λ a H, mem_support_iff.2 $ λ h, by rw [h, if_t_t] at H; exact H rfl @[simp] lemma filter_apply_pos {a : α} (h : p a) : f.filter p a = f a := if_pos h @[simp] lemma filter_apply_neg {a : α} (h : ¬ p a) : f.filter p a = 0 := if_neg h @[simp] lemma support_filter : (f.filter p).support = f.support.filter p := finset.ext.mpr $ assume a, if H : p a then by simp only [mem_support_iff, filter_apply_pos _ _ H, mem_filter, H, and_true] else by simp only [mem_support_iff, filter_apply_neg _ _ H, mem_filter, H, and_false, ne.def, ne_self_iff_false] lemma filter_zero : (0 : α →₀ β).filter p = 0 := by rw [← support_eq_empty, support_filter, support_zero, finset.filter_empty] @[simp] lemma filter_single_of_pos {a : α} {b : β} (h : p a) : (single a b).filter p = single a b := finsupp.ext $ λ x, begin by_cases h' : p x; simp [h'], rw single_eq_of_ne, rintro rfl, exact h' h end @[simp] lemma filter_single_of_neg {a : α} {b : β} (h : ¬ p a) : (single a b).filter p = 0 := finsupp.ext $ λ x, begin by_cases h' : p x; simp [h'], rw single_eq_of_ne, rintro rfl, exact h h' end end has_zero lemma filter_pos_add_filter_neg [add_monoid β] (f : α →₀ β) (p : α → Prop) : f.filter p + f.filter (λa, ¬ p a) = f := finsupp.ext $ assume a, if H : p a then by simp only [add_apply, filter_apply_pos, filter_apply_neg, H, not_not, add_zero] else by simp only [add_apply, filter_apply_pos, filter_apply_neg, H, not_false_iff, zero_add] end filter section frange variables [has_zero β] def frange (f : α →₀ β) : finset β := finset.image f f.support theorem mem_frange {f : α →₀ β} {y : β} : y ∈ f.frange ↔ y ≠ 0 ∧ ∃ x, f x = y := finset.mem_image.trans ⟨λ ⟨x, hx1, hx2⟩, ⟨hx2 ▸ mem_support_iff.1 hx1, x, hx2⟩, λ ⟨hy, x, hx⟩, ⟨x, mem_support_iff.2 (hx.symm ▸ hy), hx⟩⟩ theorem zero_not_mem_frange {f : α →₀ β} : (0:β) ∉ f.frange := λ H, (mem_frange.1 H).1 rfl theorem frange_single {x : α} {y : β} : frange (single x y) ⊆ {y} := λ r hr, let ⟨t, ht1, ht2⟩ := mem_frange.1 hr in ht2 ▸ (by rw single_apply at ht2 ⊢; split_ifs at ht2 ⊢; [exact finset.mem_singleton_self _, cc]) end frange section subtype_domain variables {α' : Type*} [has_zero δ] {p : α → Prop} section zero variables [has_zero β] {v v' : α' →₀ β} /-- `subtype_domain p f` is the restriction of the finitely supported function `f` to the subtype `p`. -/ def subtype_domain (p : α → Prop) (f : α →₀ β) : (subtype p →₀ β) := ⟨f.support.subtype p, f ∘ subtype.val, λ a, by simp only [mem_subtype, mem_support_iff]⟩ @[simp] lemma support_subtype_domain {f : α →₀ β} : (subtype_domain p f).support = f.support.subtype p := rfl @[simp] lemma subtype_domain_apply {a : subtype p} {v : α →₀ β} : (subtype_domain p v) a = v (a.val) := rfl @[simp] lemma subtype_domain_zero : subtype_domain p (0 : α →₀ β) = 0 := rfl @[to_additive] lemma prod_subtype_domain_index [comm_monoid γ] {v : α →₀ β} {h : α → β → γ} (hp : ∀x∈v.support, p x) : (v.subtype_domain p).prod (λa b, h a.1 b) = v.prod h := prod_bij (λp _, p.val) (λ _, mem_subtype.1) (λ _ _, rfl) (λ _ _ _ _, subtype.eq) (λ b hb, ⟨⟨b, hp b hb⟩, mem_subtype.2 hb, rfl⟩) end zero section monoid variables [add_monoid β] {v v' : α' →₀ β} @[simp] lemma subtype_domain_add {v v' : α →₀ β} : (v + v').subtype_domain p = v.subtype_domain p + v'.subtype_domain p := ext $ λ _, rfl instance subtype_domain.is_add_monoid_hom : is_add_monoid_hom (subtype_domain p : (α →₀ β) → subtype p →₀ β) := { map_add := λ _ _, subtype_domain_add, map_zero := subtype_domain_zero } @[simp] lemma filter_add {v v' : α →₀ β} : (v + v').filter p = v.filter p + v'.filter p := ext $ λ a, by by_cases p a; simp [h] instance filter.is_add_monoid_hom (p : α → Prop) : is_add_monoid_hom (filter p : (α →₀ β) → (α →₀ β)) := { map_zero := filter_zero p, map_add := λ x y, filter_add } end monoid section comm_monoid variables [add_comm_monoid β] lemma subtype_domain_sum {s : finset γ} {h : γ → α →₀ β} : (s.sum h).subtype_domain p = s.sum (λc, (h c).subtype_domain p) := eq.symm (s.sum_hom _) lemma subtype_domain_finsupp_sum {s : γ →₀ δ} {h : γ → δ → α →₀ β} : (s.sum h).subtype_domain p = s.sum (λc d, (h c d).subtype_domain p) := subtype_domain_sum lemma filter_sum (s : finset γ) (f : γ → α →₀ β) : (s.sum f).filter p = s.sum (λa, filter p (f a)) := (s.sum_hom (filter p)).symm end comm_monoid section group variables [add_group β] {v v' : α' →₀ β} @[simp] lemma subtype_domain_neg {v : α →₀ β} : (- v).subtype_domain p = - v.subtype_domain p := ext $ λ _, rfl @[simp] lemma subtype_domain_sub {v v' : α →₀ β} : (v - v').subtype_domain p = v.subtype_domain p - v'.subtype_domain p := ext $ λ _, rfl end group end subtype_domain section multiset def to_multiset (f : α →₀ ℕ) : multiset α := f.sum (λa n, add_monoid.smul n {a}) lemma to_multiset_zero : (0 : α →₀ ℕ).to_multiset = 0 := rfl lemma to_multiset_add (m n : α →₀ ℕ) : (m + n).to_multiset = m.to_multiset + n.to_multiset := sum_add_index (assume a, add_monoid.zero_smul _) (assume a b₁ b₂, add_monoid.add_smul _ _ _) lemma to_multiset_single (a : α) (n : ℕ) : to_multiset (single a n) = add_monoid.smul n {a} := by rw [to_multiset, sum_single_index]; apply add_monoid.zero_smul instance is_add_monoid_hom.to_multiset : is_add_monoid_hom (to_multiset : _ → multiset α) := { map_zero := to_multiset_zero, map_add := to_multiset_add } lemma card_to_multiset (f : α →₀ ℕ) : f.to_multiset.card = f.sum (λa, id) := begin refine f.induction _ _, { rw [to_multiset_zero, multiset.card_zero, sum_zero_index] }, { assume a n f _ _ ih, rw [to_multiset_add, multiset.card_add, ih, sum_add_index, to_multiset_single, sum_single_index, multiset.card_smul, multiset.singleton_eq_singleton, multiset.card_singleton, mul_one]; intros; refl } end lemma to_multiset_map (f : α →₀ ℕ) (g : α → β) : f.to_multiset.map g = (f.map_domain g).to_multiset := begin refine f.induction _ _, { rw [to_multiset_zero, multiset.map_zero, map_domain_zero, to_multiset_zero] }, { assume a n f _ _ ih, rw [to_multiset_add, multiset.map_add, ih, map_domain_add, map_domain_single, to_multiset_single, to_multiset_add, to_multiset_single, is_add_monoid_hom.map_smul (multiset.map g)], refl } end lemma prod_to_multiset [comm_monoid α] (f : α →₀ ℕ) : f.to_multiset.prod = f.prod (λa n, a ^ n) := begin refine f.induction _ _, { rw [to_multiset_zero, multiset.prod_zero, finsupp.prod_zero_index] }, { assume a n f _ _ ih, rw [to_multiset_add, multiset.prod_add, ih, to_multiset_single, finsupp.prod_add_index, finsupp.prod_single_index, multiset.prod_smul, multiset.singleton_eq_singleton, multiset.prod_singleton], { exact pow_zero a }, { exact pow_zero }, { exact pow_add } } end lemma to_finset_to_multiset (f : α →₀ ℕ) : f.to_multiset.to_finset = f.support := begin refine f.induction _ _, { rw [to_multiset_zero, multiset.to_finset_zero, support_zero] }, { assume a n f ha hn ih, rw [to_multiset_add, multiset.to_finset_add, ih, to_multiset_single, support_add_eq, support_single_ne_zero hn, multiset.to_finset_smul _ _ hn, multiset.singleton_eq_singleton, multiset.to_finset_cons, multiset.to_finset_zero], refl, refine disjoint_mono support_single_subset (subset.refl _) _, rwa [finset.singleton_eq_singleton, finset.singleton_disjoint] } end @[simp] lemma count_to_multiset (f : α →₀ ℕ) (a : α) : f.to_multiset.count a = f a := calc f.to_multiset.count a = f.sum (λx n, (add_monoid.smul n {x} : multiset α).count a) : (f.support.sum_hom $ multiset.count a).symm ... = f.sum (λx n, n * ({x} : multiset α).count a) : by simp only [multiset.count_smul] ... = f.sum (λx n, n * (x :: 0 : multiset α).count a) : rfl ... = f a * (a :: 0 : multiset α).count a : sum_eq_single _ (λ a' _ H, by simp only [multiset.count_cons_of_ne (ne.symm H), multiset.count_zero, mul_zero]) (λ H, by simp only [not_mem_support_iff.1 H, zero_mul]) ... = f a : by simp only [multiset.count_singleton, mul_one] def of_multiset (m : multiset α) : α →₀ ℕ := on_finset m.to_finset (λa, m.count a) $ λ a H, multiset.mem_to_finset.2 $ by_contradiction (mt multiset.count_eq_zero.2 H) @[simp] lemma of_multiset_apply (m : multiset α) (a : α) : of_multiset m a = m.count a := rfl def equiv_multiset : (α →₀ ℕ) ≃ (multiset α) := ⟨ to_multiset, of_multiset, assume f, finsupp.ext $ λ a, by rw [of_multiset_apply, count_to_multiset], assume m, multiset.ext.2 $ λ a, by rw [count_to_multiset, of_multiset_apply] ⟩ lemma mem_support_multiset_sum [add_comm_monoid β] {s : multiset (α →₀ β)} (a : α) : a ∈ s.sum.support → ∃f∈s, a ∈ (f : α →₀ β).support := multiset.induction_on s false.elim begin assume f s ih ha, by_cases a ∈ f.support, { exact ⟨f, multiset.mem_cons_self _ _, h⟩ }, { simp only [multiset.sum_cons, mem_support_iff, add_apply, not_mem_support_iff.1 h, zero_add] at ha, rcases ih (mem_support_iff.2 ha) with ⟨f', h₀, h₁⟩, exact ⟨f', multiset.mem_cons_of_mem h₀, h₁⟩ } end lemma mem_support_finset_sum [add_comm_monoid β] {s : finset γ} {h : γ → α →₀ β} (a : α) (ha : a ∈ (s.sum h).support) : ∃c∈s, a ∈ (h c).support := let ⟨f, hf, hfa⟩ := mem_support_multiset_sum a ha in let ⟨c, hc, eq⟩ := multiset.mem_map.1 hf in ⟨c, hc, eq.symm ▸ hfa⟩ lemma mem_support_single [has_zero β] (a a' : α) (b : β) : a ∈ (single a' b).support ↔ a = a' ∧ b ≠ 0 := ⟨λ H : (a ∈ ite _ _ _), if h : b = 0 then by rw if_pos h at H; exact H.elim else ⟨by rw if_neg h at H; exact mem_singleton.1 H, h⟩, λ ⟨h1, h2⟩, show a ∈ ite _ _ _, by rw [if_neg h2]; exact mem_singleton.2 h1⟩ end multiset section curry_uncurry protected def curry [add_comm_monoid γ] (f : (α × β) →₀ γ) : α →₀ (β →₀ γ) := f.sum $ λp c, single p.1 (single p.2 c) lemma sum_curry_index [add_comm_monoid γ] [add_comm_monoid δ] (f : (α × β) →₀ γ) (g : α → β → γ → δ) (hg₀ : ∀ a b, g a b 0 = 0) (hg₁ : ∀a b c₀ c₁, g a b (c₀ + c₁) = g a b c₀ + g a b c₁) : f.curry.sum (λa f, f.sum (g a)) = f.sum (λp c, g p.1 p.2 c) := begin rw [finsupp.curry], transitivity, { exact sum_sum_index (assume a, sum_zero_index) (assume a b₀ b₁, sum_add_index (assume a, hg₀ _ _) (assume c d₀ d₁, hg₁ _ _ _ _)) }, congr, funext p c, transitivity, { exact sum_single_index sum_zero_index }, exact sum_single_index (hg₀ _ _) end protected def uncurry [add_comm_monoid γ] (f : α →₀ (β →₀ γ)) : (α × β) →₀ γ := f.sum $ λa g, g.sum $ λb c, single (a, b) c def finsupp_prod_equiv [add_comm_monoid γ] : ((α × β) →₀ γ) ≃ (α →₀ (β →₀ γ)) := by refine ⟨finsupp.curry, finsupp.uncurry, λ f, _, λ f, _⟩; simp only [ finsupp.curry, finsupp.uncurry, sum_sum_index, sum_zero_index, sum_add_index, sum_single_index, single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff, prod.mk.eta, (single_sum _ _ _).symm, sum_single] lemma filter_curry [add_comm_monoid β] (f : α₁ × α₂ →₀ β) (p : α₁ → Prop) : (f.filter (λa:α₁×α₂, p a.1)).curry = f.curry.filter p := begin rw [finsupp.curry, finsupp.curry, finsupp.sum, finsupp.sum, @filter_sum _ (α₂ →₀ β) _ p _ f.support _], rw [support_filter, sum_filter], refine finset.sum_congr rfl _, rintros ⟨a₁, a₂⟩ ha, dsimp only, split_ifs, { rw [filter_apply_pos, filter_single_of_pos]; exact h }, { rwa [filter_single_of_neg] } end lemma support_curry [add_comm_monoid β] (f : α₁ × α₂ →₀ β) : f.curry.support ⊆ f.support.image prod.fst := begin rw ← finset.bind_singleton, refine finset.subset.trans support_sum _, refine finset.bind_mono (assume a _, support_single_subset) end end curry_uncurry section variables [add_monoid α] [semiring β] -- TODO: the simplifier unfolds 0 in the instance proof! private lemma zero_mul (f : α →₀ β) : 0 * f = 0 := by simp only [mul_def, sum_zero_index] private lemma mul_zero (f : α →₀ β) : f * 0 = 0 := by simp only [mul_def, sum_zero_index, sum_zero] private lemma left_distrib (a b c : α →₀ β) : a * (b + c) = a * b + a * c := by simp only [mul_def, sum_add_index, mul_add, _root_.mul_zero, single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff, sum_add] private lemma right_distrib (a b c : α →₀ β) : (a + b) * c = a * c + b * c := by simp only [mul_def, sum_add_index, add_mul, _root_.mul_zero, _root_.zero_mul, single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff, sum_zero, sum_add] instance : semiring (α →₀ β) := { one := 1, mul := (*), one_mul := assume f, by simp only [mul_def, one_def, sum_single_index, _root_.zero_mul, single_zero, sum_zero, zero_add, one_mul, sum_single], mul_one := assume f, by simp only [mul_def, one_def, sum_single_index, _root_.mul_zero, single_zero, sum_zero, add_zero, mul_one, sum_single], zero_mul := zero_mul, mul_zero := mul_zero, mul_assoc := assume f g h, by simp only [mul_def, sum_sum_index, sum_zero_index, sum_add_index, sum_single_index, single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff, add_mul, mul_add, add_assoc, mul_assoc, _root_.zero_mul, _root_.mul_zero, sum_zero, sum_add], left_distrib := left_distrib, right_distrib := right_distrib, .. finsupp.add_comm_monoid } end instance [add_comm_monoid α] [comm_semiring β] : comm_semiring (α →₀ β) := { mul_comm := assume f g, begin simp only [mul_def, finsupp.sum, mul_comm], rw [finset.sum_comm], simp only [add_comm] end, .. finsupp.semiring } instance [add_monoid α] [ring β] : ring (α →₀ β) := { neg := has_neg.neg, add_left_neg := add_left_neg, .. finsupp.semiring } instance [add_comm_monoid α] [comm_ring β] : comm_ring (α →₀ β) := { mul_comm := mul_comm, .. finsupp.ring} lemma single_mul_single [has_add α] [semiring β] {a₁ a₂ : α} {b₁ b₂ : β}: single a₁ b₁ * single a₂ b₂ = single (a₁ + a₂) (b₁ * b₂) := (sum_single_index (by simp only [_root_.zero_mul, single_zero, sum_zero])).trans (sum_single_index (by rw [_root_.mul_zero, single_zero])) lemma prod_single [add_comm_monoid α] [comm_semiring β] {s : finset ι} {a : ι → α} {b : ι → β} : s.prod (λi, single (a i) (b i)) = single (s.sum a) (s.prod b) := finset.induction_on s rfl $ λ a s has ih, by rw [prod_insert has, ih, single_mul_single, sum_insert has, prod_insert has] section instance [semiring γ] [add_comm_monoid β] [semimodule γ β] : has_scalar γ (α →₀ β) := ⟨λa v, v.map_range ((•) a) (smul_zero _)⟩ variables (α β) @[simp] lemma smul_apply' {R:semiring γ} [add_comm_monoid β] [semimodule γ β] {a : α} {b : γ} {v : α →₀ β} : (b • v) a = b • (v a) := rfl instance [semiring γ] [add_comm_monoid β] [semimodule γ β] : semimodule γ (α →₀ β) := { smul := (•), smul_add := λ a x y, finsupp.ext $ λ _, smul_add _ _ _, add_smul := λ a x y, finsupp.ext $ λ _, add_smul _ _ _, one_smul := λ x, finsupp.ext $ λ _, one_smul _ _, mul_smul := λ r s x, finsupp.ext $ λ _, mul_smul _ _ _, zero_smul := λ x, finsupp.ext $ λ _, zero_smul _ _, smul_zero := λ x, finsupp.ext $ λ _, smul_zero _ } instance [ring γ] [add_comm_group β] [module γ β] : module γ (α →₀ β) := { ..finsupp.semimodule α β } instance [discrete_field γ] [add_comm_group β] [vector_space γ β] : vector_space γ (α →₀ β) := { ..finsupp.module α β } variables {α β} lemma support_smul {R:semiring γ} [add_comm_monoid β] [semimodule γ β] {b : γ} {g : α →₀ β} : (b • g).support ⊆ g.support := λ a, by simp; exact mt (λ h, h.symm ▸ smul_zero _) section variables {α' : Type*} [has_zero δ] {p : α → Prop} @[simp] lemma filter_smul {R : semiring γ} [add_comm_monoid β] [semimodule γ β] {b : γ} {v : α →₀ β} : (b • v).filter p = b • v.filter p := ext $ λ a, by by_cases p a; simp [h] end lemma map_domain_smul {α'} {R : semiring γ} [add_comm_monoid β] [semimodule γ β] {f : α → α'} (b : γ) (v : α →₀ β) : map_domain f (b • v) = b • map_domain f v := begin change map_domain f (map_range _ _ _) = map_range _ _ _, apply finsupp.induction v, {simp}, intros a b v' hv₁ hv₂ IH, rw [map_range_add, map_domain_add, IH, map_domain_add, map_range_add, map_range_single, map_domain_single, map_domain_single, map_range_single]; apply smul_add end @[simp] lemma smul_single {R : semiring γ} [add_comm_monoid β] [semimodule γ β] (c : γ) (a : α) (b : β) : c • finsupp.single a b = finsupp.single a (c • b) := ext $ λ a', by by_cases a = a'; [{subst h, simp}, simp [h]] end @[simp] lemma smul_apply [ring β] {a : α} {b : β} {v : α →₀ β} : (b • v) a = b • (v a) := rfl lemma sum_smul_index [ring β] [add_comm_monoid γ] {g : α →₀ β} {b : β} {h : α → β → γ} (h0 : ∀i, h i 0 = 0) : (b • g).sum h = g.sum (λi a, h i (b * a)) := finsupp.sum_map_range_index h0 section variables [semiring β] [semiring γ] lemma sum_mul (b : γ) (s : α →₀ β) {f : α → β → γ} : (s.sum f) * b = s.sum (λ a c, (f a (s a)) * b) := by simp only [finsupp.sum, finset.sum_mul] lemma mul_sum (b : γ) (s : α →₀ β) {f : α → β → γ} : b * (s.sum f) = s.sum (λ a c, b * (f a (s a))) := by simp only [finsupp.sum, finset.mul_sum] protected lemma eq_zero_of_zero_eq_one (zero_eq_one : (0 : β) = 1) (l : α →₀ β) : l = 0 := by ext i; simp [eq_zero_of_zero_eq_one β zero_eq_one (l i)] end def restrict_support_equiv [add_comm_monoid β] (s : set α) : {f : α →₀ β // ↑f.support ⊆ s } ≃ (s →₀ β):= begin refine ⟨λf, subtype_domain (λx, x ∈ s) f.1, λ f, ⟨f.map_domain subtype.val, _⟩, _, _⟩, { refine set.subset.trans (finset.coe_subset.2 map_domain_support) _, rw [finset.coe_image, set.image_subset_iff], exact assume x hx, x.2 }, { rintros ⟨f, hf⟩, apply subtype.eq, ext a, dsimp only, refine classical.by_cases (assume h : a ∈ set.range (subtype.val : s → α), _) (assume h, _), { rcases h with ⟨x, rfl⟩, rw [map_domain_apply subtype.val_injective, subtype_domain_apply] }, { convert map_domain_notin_range _ _ h, rw [← not_mem_support_iff], refine mt _ h, exact assume ha, ⟨⟨a, hf ha⟩, rfl⟩ } }, { assume f, ext ⟨a, ha⟩, dsimp only, rw [subtype_domain_apply, map_domain_apply subtype.val_injective] } end protected def dom_congr [add_comm_monoid β] (e : α₁ ≃ α₂) : (α₁ →₀ β) ≃ (α₂ →₀ β) := ⟨map_domain e, map_domain e.symm, begin assume v, simp only [map_domain_comp.symm, (∘), equiv.symm_apply_apply], exact map_domain_id end, begin assume v, simp only [map_domain_comp.symm, (∘), equiv.apply_symm_apply], exact map_domain_id end⟩ section sigma variables {αs : ι → Type*} [has_zero β] (l : (Σ i, αs i) →₀ β) noncomputable def split (i : ι) : αs i →₀ β := l.comap_domain (sigma.mk i) (λ x1 x2 _ _ hx, heq_iff_eq.1 (sigma.mk.inj hx).2) lemma split_apply (i : ι) (x : αs i) : split l i x = l ⟨i, x⟩ := begin dunfold split, rw comap_domain_apply end def split_support : finset ι := l.support.image sigma.fst lemma mem_split_support_iff_nonzero (i : ι) : i ∈ split_support l ↔ split l i ≠ 0 := begin classical, rw [split_support, mem_image, ne.def, ← support_eq_empty, ← ne.def, ← finset.nonempty_iff_ne_empty, split, comap_domain, finset.nonempty], simp end noncomputable def split_comp [has_zero γ] (g : Π i, (αs i →₀ β) → γ) (hg : ∀ i x, x = 0 ↔ g i x = 0) : ι →₀ γ := { support := split_support l, to_fun := λ i, g i (split l i), mem_support_to_fun := begin intros i, rw mem_split_support_iff_nonzero, haveI := classical.dec, rwa not_iff_not, exact hg _ _, end } lemma sigma_support : l.support = l.split_support.sigma (λ i, (l.split i).support) := by simp [finset.ext, split_support, split, comap_domain]; tauto lemma sigma_sum [add_comm_monoid γ] (f : (Σ (i : ι), αs i) → β → γ) : l.sum f = (split_support l).sum (λ (i : ι), (split l i).sum (λ (a : αs i) b, f ⟨i, a⟩ b)) := by simp [sum, sigma_support, sum_sigma,split_apply] end sigma end finsupp namespace multiset def to_finsupp (s : multiset α) : α →₀ ℕ := { support := s.to_finset, to_fun := λ a, s.count a, mem_support_to_fun := λ a, begin rw mem_to_finset, convert not_iff_not_of_iff (count_eq_zero.symm), rw not_not end } @[simp] lemma to_finsupp_support (s : multiset α) : s.to_finsupp.support = s.to_finset := rfl @[simp] lemma to_finsupp_apply (s : multiset α) (a : α) : s.to_finsupp a = s.count a := rfl @[simp] lemma to_finsupp_zero : to_finsupp (0 : multiset α) = 0 := finsupp.ext $ λ a, count_zero a @[simp] lemma to_finsupp_add (s t : multiset α) : to_finsupp (s + t) = to_finsupp s + to_finsupp t := finsupp.ext $ λ a, count_add a s t lemma to_finsupp_singleton (a : α) : to_finsupp {a} = finsupp.single a 1 := finsupp.ext $ λ b, if h : a = b then by simp [finsupp.single_apply, h] else begin rw [to_finsupp_apply, finsupp.single_apply, if_neg h, count_eq_zero, singleton_eq_singleton, mem_singleton], rintro rfl, exact h rfl end namespace to_finsupp instance : is_add_monoid_hom (to_finsupp : multiset α → α →₀ ℕ) := { map_zero := to_finsupp_zero, map_add := to_finsupp_add } end to_finsupp @[simp] lemma to_finsupp_to_multiset (s : multiset α) : s.to_finsupp.to_multiset = s := ext.2 $ λ a, by rw [finsupp.count_to_multiset, to_finsupp_apply] end multiset namespace finsupp variables {σ : Type*} instance [preorder α] [has_zero α] : preorder (σ →₀ α) := { le := λ f g, ∀ s, f s ≤ g s, le_refl := λ f s, le_refl _, le_trans := λ f g h Hfg Hgh s, le_trans (Hfg s) (Hgh s) } instance [partial_order α] [has_zero α] : partial_order (σ →₀ α) := { le_antisymm := λ f g hfg hgf, finsupp.ext $ λ s, le_antisymm (hfg s) (hgf s), .. finsupp.preorder } instance [ordered_cancel_comm_monoid α] : add_left_cancel_semigroup (σ →₀ α) := { add_left_cancel := λ a b c h, finsupp.ext $ λ s, by { rw finsupp.ext_iff at h, exact add_left_cancel (h s) }, .. finsupp.add_monoid } instance [ordered_cancel_comm_monoid α] : add_right_cancel_semigroup (σ →₀ α) := { add_right_cancel := λ a b c h, finsupp.ext $ λ s, by { rw finsupp.ext_iff at h, exact add_right_cancel (h s) }, .. finsupp.add_monoid } instance [ordered_cancel_comm_monoid α] : ordered_cancel_comm_monoid (σ →₀ α) := { add_le_add_left := λ a b h c s, add_le_add_left (h s) (c s), le_of_add_le_add_left := λ a b c h s, le_of_add_le_add_left (h s), .. finsupp.add_comm_monoid, .. finsupp.partial_order, .. finsupp.add_left_cancel_semigroup, .. finsupp.add_right_cancel_semigroup } lemma le_iff [canonically_ordered_monoid α] (f g : σ →₀ α) : f ≤ g ↔ ∀ s ∈ f.support, f s ≤ g s := ⟨λ h s hs, h s, λ h s, if H : s ∈ f.support then h s H else (not_mem_support_iff.1 H).symm ▸ zero_le (g s)⟩ attribute [simp] to_multiset_zero to_multiset_add @[simp] lemma to_multiset_to_finsupp (f : σ →₀ ℕ) : f.to_multiset.to_finsupp = f := ext $ λ s, by rw [multiset.to_finsupp_apply, count_to_multiset] lemma to_multiset_strict_mono : strict_mono (@to_multiset σ) := λ m n h, begin rw lt_iff_le_and_ne at h ⊢, cases h with h₁ h₂, split, { rw multiset.le_iff_count, intro s, erw [count_to_multiset m s, count_to_multiset], exact h₁ s }, { intro H, apply h₂, replace H := congr_arg multiset.to_finsupp H, simpa using H } end lemma sum_id_lt_of_lt (m n : σ →₀ ℕ) (h : m < n) : m.sum (λ _, id) < n.sum (λ _, id) := begin rw [← card_to_multiset, ← card_to_multiset], apply multiset.card_lt_of_lt, exact to_multiset_strict_mono h end variable (σ) /-- The order on σ →₀ ℕ is well-founded.-/ lemma lt_wf : well_founded (@has_lt.lt (σ →₀ ℕ) _) := subrelation.wf (sum_id_lt_of_lt) $ inv_image.wf _ nat.lt_wf instance decidable_le : decidable_rel (@has_le.le (σ →₀ ℕ) _) := λ m n, by rw le_iff; apply_instance variable {σ} def antidiagonal (f : σ →₀ ℕ) : ((σ →₀ ℕ) × (σ →₀ ℕ)) →₀ ℕ := (f.to_multiset.antidiagonal.map (prod.map multiset.to_finsupp multiset.to_finsupp)).to_finsupp lemma mem_antidiagonal_support {f : σ →₀ ℕ} {p : (σ →₀ ℕ) × (σ →₀ ℕ)} : p ∈ (antidiagonal f).support ↔ p.1 + p.2 = f := begin erw [multiset.mem_to_finset, multiset.mem_map], split, { rintros ⟨⟨a, b⟩, h, rfl⟩, rw multiset.mem_antidiagonal at h, simpa using congr_arg multiset.to_finsupp h }, { intro h, refine ⟨⟨p.1.to_multiset, p.2.to_multiset⟩, _, _⟩, { simpa using congr_arg to_multiset h }, { rw [prod.map, to_multiset_to_finsupp, to_multiset_to_finsupp, prod.mk.eta] } } end @[simp] lemma antidiagonal_zero : antidiagonal (0 : σ →₀ ℕ) = single (0,0) 1 := by rw [← multiset.to_finsupp_singleton]; refl lemma swap_mem_antidiagonal_support {n : σ →₀ ℕ} {f} (hf : f ∈ (antidiagonal n).support) : f.swap ∈ (antidiagonal n).support := by simpa [mem_antidiagonal_support, add_comm] using hf end finsupp
641104ca9dbb5d5446081badc6780fa7bd9fa006
618003631150032a5676f229d13a079ac875ff77
/src/data/set/intervals/basic.lean
49bdee9c4ed1fcf394ccab7cff6bc44bd28cb328
[ "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
28,577
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Patrick Massot, Yury Kudryashov -/ import tactic.tauto import algebra.order_functions import algebra.ordered_field /-! # Intervals In any preorder `α`, we define intervals (which on each side can be either infinite, open, or closed) using the following naming conventions: - `i`: infinite - `o`: open - `c`: closed Each interval has the name `I` + letter for left side + letter for right side. For instance, `Ioc a b` denotes the inverval `(a, b]`. This file contains these definitions, and basic facts on inclusion, intersection, difference of intervals (where the precise statements may depend on the properties of the order, in particular for some statements it should be `linear_order` or `densely_ordered`). This file also contains statements on lower and upper bounds of intervals. TODO: This is just the beginning; a lot of rules are missing -/ universe u namespace set open set section intervals variables {α : Type u} [preorder α] {a a₁ a₂ b b₁ b₂ x : α} /-- Left-open right-open interval -/ def Ioo (a b : α) := {x | a < x ∧ x < b} /-- Left-closed right-open interval -/ def Ico (a b : α) := {x | a ≤ x ∧ x < b} /-- Left-infinite right-open interval -/ def Iio (a : α) := {x | x < a} /-- Left-closed right-closed interval -/ def Icc (a b : α) := {x | a ≤ x ∧ x ≤ b} /-- Left-infinite right-closed interval -/ def Iic (b : α) := {x | x ≤ b} /-- Left-open right-closed interval -/ def Ioc (a b : α) := {x | a < x ∧ x ≤ b} /-- Left-closed right-infinite interval -/ def Ici (a : α) := {x | a ≤ x} /-- Left-open right-infinite interval -/ def Ioi (a : α) := {x | a < x} @[simp] lemma mem_Ioo : x ∈ Ioo a b ↔ a < x ∧ x < b := iff.rfl @[simp] lemma mem_Ico : x ∈ Ico a b ↔ a ≤ x ∧ x < b := iff.rfl @[simp] lemma mem_Iio : x ∈ Iio b ↔ x < b := iff.rfl @[simp] lemma mem_Icc : x ∈ Icc a b ↔ a ≤ x ∧ x ≤ b := iff.rfl @[simp] lemma mem_Iic : x ∈ Iic b ↔ x ≤ b := iff.rfl @[simp] lemma mem_Ioc : x ∈ Ioc a b ↔ a < x ∧ x ≤ b := iff.rfl @[simp] lemma mem_Ici : x ∈ Ici a ↔ a ≤ x := iff.rfl @[simp] lemma mem_Ioi : x ∈ Ioi a ↔ a < x := iff.rfl @[simp] lemma left_mem_Ioo : a ∈ Ioo a b ↔ false := by simp [lt_irrefl] @[simp] lemma left_mem_Ico : a ∈ Ico a b ↔ a < b := by simp [le_refl] @[simp] lemma left_mem_Icc : a ∈ Icc a b ↔ a ≤ b := by simp [le_refl] @[simp] lemma left_mem_Ioc : a ∈ Ioc a b ↔ false := by simp [lt_irrefl] lemma left_mem_Ici : a ∈ Ici a := by simp @[simp] lemma right_mem_Ioo : b ∈ Ioo a b ↔ false := by simp [lt_irrefl] @[simp] lemma right_mem_Ico : b ∈ Ico a b ↔ false := by simp [lt_irrefl] @[simp] lemma right_mem_Icc : b ∈ Icc a b ↔ a ≤ b := by simp [le_refl] @[simp] lemma right_mem_Ioc : b ∈ Ioc a b ↔ a < b := by simp [le_refl] lemma right_mem_Iic : a ∈ Iic a := by simp @[simp] lemma dual_Ici : @Ici (order_dual α) _ a = @Iic α _ a := rfl @[simp] lemma dual_Iic : @Iic (order_dual α) _ a = @Ici α _ a := rfl @[simp] lemma dual_Ioi : @Ioi (order_dual α) _ a = @Iio α _ a := rfl @[simp] lemma dual_Iio : @Iio (order_dual α) _ a = @Ioi α _ a := rfl @[simp] lemma dual_Icc : @Icc (order_dual α) _ a b = @Icc α _ b a := set.ext $ λ x, and_comm _ _ @[simp] lemma dual_Ioc : @Ioc (order_dual α) _ a b = @Ico α _ b a := set.ext $ λ x, and_comm _ _ @[simp] lemma dual_Ico : @Ico (order_dual α) _ a b = @Ioc α _ b a := set.ext $ λ x, and_comm _ _ @[simp] lemma dual_Ioo : @Ioo (order_dual α) _ a b = @Ioo α _ b a := set.ext $ λ x, and_comm _ _ @[simp] lemma nonempty_Icc : (Icc a b).nonempty ↔ a ≤ b := ⟨λ ⟨x, hx⟩, le_trans hx.1 hx.2, λ h, ⟨a, left_mem_Icc.2 h⟩⟩ @[simp] lemma nonempty_Ico : (Ico a b).nonempty ↔ a < b := ⟨λ ⟨x, hx⟩, lt_of_le_of_lt hx.1 hx.2, λ h, ⟨a, left_mem_Ico.2 h⟩⟩ @[simp] lemma nonempty_Ioc : (Ioc a b).nonempty ↔ a < b := ⟨λ ⟨x, hx⟩, lt_of_lt_of_le hx.1 hx.2, λ h, ⟨b, right_mem_Ioc.2 h⟩⟩ @[simp] lemma nonempty_Ici : (Ici a).nonempty := ⟨a, left_mem_Ici⟩ @[simp] lemma nonempty_Iic : (Iic a).nonempty := ⟨a, right_mem_Iic⟩ @[simp] lemma nonempty_Ioo [densely_ordered α] : (Ioo a b).nonempty ↔ a < b := ⟨λ ⟨x, ha, hb⟩, lt_trans ha hb, dense⟩ @[simp] lemma nonempty_Ioi [no_top_order α] : (Ioi a).nonempty := no_top a @[simp] lemma nonempty_Iio [no_bot_order α] : (Iio a).nonempty := no_bot a @[simp] lemma Ioo_eq_empty (h : b ≤ a) : Ioo a b = ∅ := eq_empty_iff_forall_not_mem.2 $ λ x ⟨h₁, h₂⟩, not_le_of_lt (lt_trans h₁ h₂) h @[simp] lemma Ico_eq_empty (h : b ≤ a) : Ico a b = ∅ := eq_empty_iff_forall_not_mem.2 $ λ x ⟨h₁, h₂⟩, not_le_of_lt (lt_of_le_of_lt h₁ h₂) h @[simp] lemma Icc_eq_empty (h : b < a) : Icc a b = ∅ := eq_empty_iff_forall_not_mem.2 $ λ x ⟨h₁, h₂⟩, not_lt_of_le (le_trans h₁ h₂) h @[simp] lemma Ioc_eq_empty (h : b ≤ a) : Ioc a b = ∅ := eq_empty_iff_forall_not_mem.2 $ λ x ⟨h₁, h₂⟩, not_lt_of_le (le_trans h₂ h) h₁ @[simp] lemma Ioo_self (a : α) : Ioo a a = ∅ := Ioo_eq_empty $ le_refl _ @[simp] lemma Ico_self (a : α) : Ico a a = ∅ := Ico_eq_empty $ le_refl _ @[simp] lemma Ioc_self (a : α) : Ioc a a = ∅ := Ioc_eq_empty $ le_refl _ lemma Ici_subset_Ici : Ici a ⊆ Ici b ↔ b ≤ a := ⟨λ h, h $ left_mem_Ici, λ h x hx, le_trans h hx⟩ lemma Iic_subset_Iic : Iic a ⊆ Iic b ↔ a ≤ b := @Ici_subset_Ici (order_dual α) _ _ _ lemma Ici_subset_Ioi : Ici a ⊆ Ioi b ↔ b < a := ⟨λ h, h left_mem_Ici, λ h x hx, lt_of_lt_of_le h hx⟩ lemma Iic_subset_Iio : Iic a ⊆ Iio b ↔ a < b := ⟨λ h, h right_mem_Iic, λ h x hx, lt_of_le_of_lt hx h⟩ lemma Ioo_subset_Ioo (h₁ : a₂ ≤ a₁) (h₂ : b₁ ≤ b₂) : Ioo a₁ b₁ ⊆ Ioo a₂ b₂ := λ x ⟨hx₁, hx₂⟩, ⟨lt_of_le_of_lt h₁ hx₁, lt_of_lt_of_le hx₂ h₂⟩ lemma Ioo_subset_Ioo_left (h : a₁ ≤ a₂) : Ioo a₂ b ⊆ Ioo a₁ b := Ioo_subset_Ioo h (le_refl _) lemma Ioo_subset_Ioo_right (h : b₁ ≤ b₂) : Ioo a b₁ ⊆ Ioo a b₂ := Ioo_subset_Ioo (le_refl _) h lemma Ico_subset_Ico (h₁ : a₂ ≤ a₁) (h₂ : b₁ ≤ b₂) : Ico a₁ b₁ ⊆ Ico a₂ b₂ := λ x ⟨hx₁, hx₂⟩, ⟨le_trans h₁ hx₁, lt_of_lt_of_le hx₂ h₂⟩ lemma Ico_subset_Ico_left (h : a₁ ≤ a₂) : Ico a₂ b ⊆ Ico a₁ b := Ico_subset_Ico h (le_refl _) lemma Ico_subset_Ico_right (h : b₁ ≤ b₂) : Ico a b₁ ⊆ Ico a b₂ := Ico_subset_Ico (le_refl _) h lemma Icc_subset_Icc (h₁ : a₂ ≤ a₁) (h₂ : b₁ ≤ b₂) : Icc a₁ b₁ ⊆ Icc a₂ b₂ := λ x ⟨hx₁, hx₂⟩, ⟨le_trans h₁ hx₁, le_trans hx₂ h₂⟩ lemma Icc_subset_Icc_left (h : a₁ ≤ a₂) : Icc a₂ b ⊆ Icc a₁ b := Icc_subset_Icc h (le_refl _) lemma Icc_subset_Icc_right (h : b₁ ≤ b₂) : Icc a b₁ ⊆ Icc a b₂ := Icc_subset_Icc (le_refl _) h lemma Ioc_subset_Ioc (h₁ : a₂ ≤ a₁) (h₂ : b₁ ≤ b₂) : Ioc a₁ b₁ ⊆ Ioc a₂ b₂ := λ x ⟨hx₁, hx₂⟩, ⟨lt_of_le_of_lt h₁ hx₁, le_trans hx₂ h₂⟩ lemma Ioc_subset_Ioc_left (h : a₁ ≤ a₂) : Ioc a₂ b ⊆ Ioc a₁ b := Ioc_subset_Ioc h (le_refl _) lemma Ioc_subset_Ioc_right (h : b₁ ≤ b₂) : Ioc a b₁ ⊆ Ioc a b₂ := Ioc_subset_Ioc (le_refl _) h lemma Ico_subset_Ioo_left (h₁ : a₁ < a₂) : Ico a₂ b ⊆ Ioo a₁ b := λ x, and.imp_left $ lt_of_lt_of_le h₁ lemma Icc_subset_Ico_right (h₁ : b₁ < b₂) : Icc a b₁ ⊆ Ico a b₂ := λ x, and.imp_right $ λ h₂, lt_of_le_of_lt h₂ h₁ lemma Ioo_subset_Ico_self : Ioo a b ⊆ Ico a b := λ x, and.imp_left le_of_lt lemma Ioo_subset_Ioc_self : Ioo a b ⊆ Ioc a b := λ x, and.imp_right le_of_lt lemma Ico_subset_Icc_self : Ico a b ⊆ Icc a b := λ x, and.imp_right le_of_lt lemma Ioc_subset_Icc_self : Ioc a b ⊆ Icc a b := λ x, and.imp_left le_of_lt lemma Ioo_subset_Icc_self : Ioo a b ⊆ Icc a b := subset.trans Ioo_subset_Ico_self Ico_subset_Icc_self lemma Ico_subset_Iio_self : Ico a b ⊆ Iio b := λ x, and.right lemma Ioo_subset_Iio_self : Ioo a b ⊆ Iio b := λ x, and.right lemma Ioc_subset_Ioi_self : Ioc a b ⊆ Ioi a := λ x, and.left lemma Ioo_subset_Ioi_self : Ioo a b ⊆ Ioi a := λ x, and.left lemma Ioi_subset_Ici_self : Ioi a ⊆ Ici a := λx hx, le_of_lt hx lemma Iio_subset_Iic_self : Iio a ⊆ Iic a := λx hx, le_of_lt hx lemma Icc_subset_Icc_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Icc a₂ b₂ ↔ a₂ ≤ a₁ ∧ b₁ ≤ b₂ := ⟨λ h, ⟨(h ⟨le_refl _, h₁⟩).1, (h ⟨h₁, le_refl _⟩).2⟩, λ ⟨h, h'⟩ x ⟨hx, hx'⟩, ⟨le_trans h hx, le_trans hx' h'⟩⟩ lemma Icc_subset_Ioo_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Ioo a₂ b₂ ↔ a₂ < a₁ ∧ b₁ < b₂ := ⟨λ h, ⟨(h ⟨le_refl _, h₁⟩).1, (h ⟨h₁, le_refl _⟩).2⟩, λ ⟨h, h'⟩ x ⟨hx, hx'⟩, ⟨lt_of_lt_of_le h hx, lt_of_le_of_lt hx' h'⟩⟩ lemma Icc_subset_Ico_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Ico a₂ b₂ ↔ a₂ ≤ a₁ ∧ b₁ < b₂ := ⟨λ h, ⟨(h ⟨le_refl _, h₁⟩).1, (h ⟨h₁, le_refl _⟩).2⟩, λ ⟨h, h'⟩ x ⟨hx, hx'⟩, ⟨le_trans h hx, lt_of_le_of_lt hx' h'⟩⟩ lemma Icc_subset_Ioc_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Ioc a₂ b₂ ↔ a₂ < a₁ ∧ b₁ ≤ b₂ := ⟨λ h, ⟨(h ⟨le_refl _, h₁⟩).1, (h ⟨h₁, le_refl _⟩).2⟩, λ ⟨h, h'⟩ x ⟨hx, hx'⟩, ⟨lt_of_lt_of_le h hx, le_trans hx' h'⟩⟩ lemma Icc_subset_Iio_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Iio b₂ ↔ b₁ < b₂ := ⟨λ h, h ⟨h₁, le_refl _⟩, λ h x ⟨hx, hx'⟩, lt_of_le_of_lt hx' h⟩ lemma Icc_subset_Ioi_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Ioi a₂ ↔ a₂ < a₁ := ⟨λ h, h ⟨le_refl _, h₁⟩, λ h x ⟨hx, hx'⟩, lt_of_lt_of_le h hx⟩ lemma Icc_subset_Iic_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Iic b₂ ↔ b₁ ≤ b₂ := ⟨λ h, h ⟨h₁, le_refl _⟩, λ h x ⟨hx, hx'⟩, le_trans hx' h⟩ lemma Icc_subset_Ici_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Ici a₂ ↔ a₂ ≤ a₁ := ⟨λ h, h ⟨le_refl _, h₁⟩, λ h x ⟨hx, hx'⟩, le_trans h hx⟩ /-- If `a ≤ b`, then `(b, +∞) ⊆ (a, +∞)`. In preorders, this is just an implication. If you need the equivalence in linear orders, use `Ioi_subset_Ioi_iff`. -/ lemma Ioi_subset_Ioi (h : a ≤ b) : Ioi b ⊆ Ioi a := λx hx, lt_of_le_of_lt h hx /-- If `a ≤ b`, then `(b, +∞) ⊆ [a, +∞)`. In preorders, this is just an implication. If you need the equivalence in dense linear orders, use `Ioi_subset_Ici_iff`. -/ lemma Ioi_subset_Ici (h : a ≤ b) : Ioi b ⊆ Ici a := subset.trans (Ioi_subset_Ioi h) Ioi_subset_Ici_self /-- If `a ≤ b`, then `(-∞, a) ⊆ (-∞, b)`. In preorders, this is just an implication. If you need the equivalence in linear orders, use `Iio_subset_Iio_iff`. -/ lemma Iio_subset_Iio (h : a ≤ b) : Iio a ⊆ Iio b := λx hx, lt_of_lt_of_le hx h /-- If `a ≤ b`, then `(-∞, a) ⊆ (-∞, b]`. In preorders, this is just an implication. If you need the equivalence in dense linear orders, use `Iio_subset_Iic_iff`. -/ lemma Iio_subset_Iic (h : a ≤ b) : Iio a ⊆ Iic b := subset.trans (Iio_subset_Iio h) Iio_subset_Iic_self lemma Ici_inter_Iic : Ici a ∩ Iic b = Icc a b := rfl lemma Ici_inter_Iio : Ici a ∩ Iio b = Ico a b := rfl lemma Ioi_inter_Iic : Ioi a ∩ Iic b = Ioc a b := rfl lemma Ioi_inter_Iio : Ioi a ∩ Iio b = Ioo a b := rfl end intervals section partial_order variables {α : Type u} [partial_order α] {a b : α} @[simp] lemma Icc_self (a : α) : Icc a a = {a} := set.ext $ by simp [Icc, le_antisymm_iff, and_comm] lemma Ico_diff_Ioo_eq_singleton (h : a < b) : Ico a b \ Ioo a b = {a} := set.ext $ λ x, begin simp [not_and'], split, { rintro ⟨⟨ax, xb⟩, hne⟩, exact (eq_or_lt_of_le ax).elim eq.symm (λ h', absurd h' (hne xb)) }, { rintro rfl, exact ⟨⟨le_refl _, h⟩, λ _, lt_irrefl x⟩ } end lemma Ioc_diff_Ioo_eq_singleton (h : a < b) : Ioc a b \ Ioo a b = {b} := set.ext $ λ x, begin simp, split, { rintro ⟨⟨ax, xb⟩, hne⟩, exact (eq_or_lt_of_le xb).elim id (λ h', absurd h' (hne ax)) }, { rintro rfl, exact ⟨⟨h, le_refl _⟩, λ _, lt_irrefl x⟩ } end lemma Icc_diff_Ico_eq_singleton (h : a ≤ b) : Icc a b \ Ico a b = {b} := set.ext $ λ x, begin simp, split, { rintro ⟨⟨ax, xb⟩, h⟩, exact classical.by_contradiction (λ ne, h ax (lt_of_le_of_ne xb ne)) }, { rintro rfl, exact ⟨⟨h, le_refl _⟩, λ _, lt_irrefl x⟩ } end lemma Icc_diff_Ioc_eq_singleton (h : a ≤ b) : Icc a b \ Ioc a b = {a} := set.ext $ λ x, begin simp [not_and'], split, { rintro ⟨⟨ax, xb⟩, h⟩, exact classical.by_contradiction (λ hne, h xb (lt_of_le_of_ne ax (ne.symm hne))) }, { rintro rfl, exact ⟨⟨le_refl _, h⟩, λ _, lt_irrefl x⟩ } end end partial_order section linear_order variables {α : Type u} [linear_order α] {a a₁ a₂ b b₁ b₂ : α} lemma compl_Iic : -(Iic a) = Ioi a := ext $ λ _, not_le lemma compl_Ici : -(Ici a) = Iio a := ext $ λ _, not_le lemma compl_Iio : -(Iio a) = Ici a := ext $ λ _, not_lt lemma compl_Ioi : -(Ioi a) = Iic a := ext $ λ _, not_lt lemma Ioo_eq_empty_iff [densely_ordered α] : Ioo a b = ∅ ↔ b ≤ a := ⟨λ eq, le_of_not_lt $ λ h, let ⟨x, h₁, h₂⟩ := dense h in eq_empty_iff_forall_not_mem.1 eq x ⟨h₁, h₂⟩, Ioo_eq_empty⟩ lemma Ico_eq_empty_iff : Ico a b = ∅ ↔ b ≤ a := ⟨λ eq, le_of_not_lt $ λ h, eq_empty_iff_forall_not_mem.1 eq a ⟨le_refl _, h⟩, Ico_eq_empty⟩ lemma Icc_eq_empty_iff : Icc a b = ∅ ↔ b < a := ⟨λ eq, lt_of_not_ge $ λ h, eq_empty_iff_forall_not_mem.1 eq a ⟨le_refl _, h⟩, Icc_eq_empty⟩ lemma Ico_subset_Ico_iff (h₁ : a₁ < b₁) : Ico a₁ b₁ ⊆ Ico a₂ b₂ ↔ a₂ ≤ a₁ ∧ b₁ ≤ b₂ := ⟨λ h, have a₂ ≤ a₁ ∧ a₁ < b₂ := h ⟨le_refl _, h₁⟩, ⟨this.1, le_of_not_lt $ λ h', lt_irrefl b₂ (h ⟨le_of_lt this.2, h'⟩).2⟩, λ ⟨h₁, h₂⟩, Ico_subset_Ico h₁ h₂⟩ lemma Ioo_subset_Ioo_iff [densely_ordered α] (h₁ : a₁ < b₁) : Ioo a₁ b₁ ⊆ Ioo a₂ b₂ ↔ a₂ ≤ a₁ ∧ b₁ ≤ b₂ := ⟨λ h, begin rcases dense h₁ with ⟨x, xa, xb⟩, split; refine le_of_not_lt (λ h', _), { have ab := lt_trans (h ⟨xa, xb⟩).1 xb, exact lt_irrefl _ (h ⟨h', ab⟩).1 }, { have ab := lt_trans xa (h ⟨xa, xb⟩).2, exact lt_irrefl _ (h ⟨ab, h'⟩).2 } end, λ ⟨h₁, h₂⟩, Ioo_subset_Ioo h₁ h₂⟩ lemma Ico_eq_Ico_iff (h : a₁ < b₁ ∨ a₂ < b₂) : Ico a₁ b₁ = Ico a₂ b₂ ↔ a₁ = a₂ ∧ b₁ = b₂ := ⟨λ e, begin simp [subset.antisymm_iff] at e, simp [le_antisymm_iff], cases h; simp [Ico_subset_Ico_iff h] at e; [ rcases e with ⟨⟨h₁, h₂⟩, e'⟩, rcases e with ⟨e', ⟨h₁, h₂⟩⟩ ]; have := (Ico_subset_Ico_iff (lt_of_le_of_lt h₁ $ lt_of_lt_of_le h h₂)).1 e'; tauto end, λ ⟨h₁, h₂⟩, by rw [h₁, h₂]⟩ open_locale classical @[simp] lemma Ioi_subset_Ioi_iff : Ioi b ⊆ Ioi a ↔ a ≤ b := begin refine ⟨λh, _, λh, Ioi_subset_Ioi h⟩, by_contradiction ba, exact lt_irrefl _ (h (not_le.mp ba)) end @[simp] lemma Ioi_subset_Ici_iff [densely_ordered α] : Ioi b ⊆ Ici a ↔ a ≤ b := begin refine ⟨λh, _, λh, Ioi_subset_Ici h⟩, by_contradiction ba, obtain ⟨c, bc, ca⟩ : ∃c, b < c ∧ c < a := dense (not_le.mp ba), exact lt_irrefl _ (lt_of_lt_of_le ca (h bc)) end @[simp] lemma Iio_subset_Iio_iff : Iio a ⊆ Iio b ↔ a ≤ b := begin refine ⟨λh, _, λh, Iio_subset_Iio h⟩, by_contradiction ab, exact lt_irrefl _ (h (not_le.mp ab)) end @[simp] lemma Iio_subset_Iic_iff [densely_ordered α] : Iio a ⊆ Iic b ↔ a ≤ b := begin refine ⟨λh, _, λh, Iio_subset_Iic h⟩, by_contradiction ba, obtain ⟨c, bc, ca⟩ : ∃c, b < c ∧ c < a := dense (not_le.mp ba), exact lt_irrefl _ (lt_of_lt_of_le bc (h ca)) end /-! ### Unions of adjacent intervals -/ /-! #### Two infinite intervals -/ @[simp] lemma Iic_union_Ici : Iic a ∪ Ici a = univ := eq_univ_of_forall (λ x, le_total x a) @[simp] lemma Iio_union_Ici : Iio a ∪ Ici a = univ := eq_univ_of_forall (λ x, lt_or_le x a) @[simp] lemma Iic_union_Ioi : Iic a ∪ Ioi a = univ := eq_univ_of_forall (λ x, le_or_lt x a) /-! #### A finite and an infinite interval -/ @[simp] lemma Ioc_union_Ici_eq_Ioi (h : a < b) : Ioc a b ∪ Ici b = Ioi a := ext $ λ x, ⟨λ hx, hx.elim and.left (lt_of_lt_of_le h), λ hx, (le_total x b).elim (λ hxb, or.inl ⟨hx, hxb⟩) (λ hxb, or.inr hxb)⟩ @[simp] lemma Icc_union_Ici_eq_Ioi (h : a ≤ b) : Icc a b ∪ Ici b = Ici a := ext $ λ x, ⟨λ hx, hx.elim and.left (le_trans h), λ hx, (le_total x b).elim (λ hxb, or.inl ⟨hx, hxb⟩) (λ hxb, or.inr hxb)⟩ @[simp] lemma Ioo_union_Ici_eq_Ioi (h : a < b) : Ioo a b ∪ Ici b = Ioi a := ext $ λ x, ⟨λ hx, hx.elim and.left (lt_of_lt_of_le h), λ hx, (lt_or_le x b).elim (λ hxb, or.inl ⟨hx, hxb⟩) (λ hxb, or.inr hxb)⟩ @[simp] lemma Ico_union_Ici_eq_Ioi (h : a ≤ b) : Ico a b ∪ Ici b = Ici a := ext $ λ x, ⟨λ hx, hx.elim and.left (le_trans h), λ hx, (lt_or_le x b).elim (λ hxb, or.inl ⟨hx, hxb⟩) (λ hxb, or.inr hxb)⟩ @[simp] lemma Ioc_union_Ioi_eq_Ioi (h : a ≤ b) : Ioc a b ∪ Ioi b = Ioi a := ext $ λ x, ⟨λ hx, hx.elim and.left (lt_of_le_of_lt h), λ hx, (le_or_lt x b).elim (λ hxb, or.inl ⟨hx, hxb⟩) (λ hxb, or.inr hxb)⟩ @[simp] lemma Icc_union_Ioi_eq_Ioi (h : a ≤ b) : Icc a b ∪ Ioi b = Ici a := ext $ λ x, ⟨λ hx, hx.elim and.left (λ hx, le_trans h (le_of_lt hx)), λ hx, (le_or_lt x b).elim (λ hxb, or.inl ⟨hx, hxb⟩) (λ hxb, or.inr hxb)⟩ /-! #### An infinite and a finite interval -/ @[simp] lemma Iic_union_Icc_eq_Iic (h : a ≤ b) : Iic a ∪ Icc a b = Iic b := ext $ λ x, ⟨λ hx, hx.elim (λ hx, le_trans hx h) and.right, λ hx, (le_total x a).elim (λ hxa, or.inl hxa) (λ hxa, or.inr ⟨hxa, hx⟩)⟩ @[simp] lemma Iic_union_Ico_eq_Iio (h : a < b) : Iic a ∪ Ico a b = Iio b := ext $ λ x, ⟨λ hx, hx.elim (λ hx, lt_of_le_of_lt hx h) and.right, λ hx, (le_total x a).elim (λ hxa, or.inl hxa) (λ hxa, or.inr ⟨hxa, hx⟩)⟩ @[simp] lemma Iio_union_Icc_eq_Iic (h : a ≤ b) : Iio a ∪ Icc a b = Iic b := ext $ λ x, ⟨λ hx, hx.elim (λ hx, le_trans (le_of_lt hx) h) and.right, λ hx, (lt_or_le x a).elim (λ hxa, or.inl hxa) (λ hxa, or.inr ⟨hxa, hx⟩)⟩ @[simp] lemma Iio_union_Ico_eq_Iio (h : a ≤ b) : Iio a ∪ Ico a b = Iio b := ext $ λ x, ⟨λ hx, hx.elim (λ hx, lt_of_lt_of_le hx h) and.right, λ hx, (lt_or_le x a).elim (λ hxa, or.inl hxa) (λ hxa, or.inr ⟨hxa, hx⟩)⟩ @[simp] lemma Iic_union_Ioc_eq_Iic (h : a ≤ b) : Iic a ∪ Ioc a b = Iic b := ext $ λ x, ⟨λ hx, hx.elim (λ hx, le_trans hx h) and.right, λ hx, (le_or_lt x a).elim (λ hxa, or.inl hxa) (λ hxa, or.inr ⟨hxa, hx⟩)⟩ @[simp] lemma Iic_union_Ioo_eq_Iio (h : a < b) : Iic a ∪ Ioo a b = Iio b := ext $ λ x, ⟨λ hx, hx.elim (λ hx, lt_of_le_of_lt hx h) and.right, λ hx, (le_or_lt x a).elim (λ hxa, or.inl hxa) (λ hxa, or.inr ⟨hxa, hx⟩)⟩ /-! #### Two finite intervals with a common point -/ @[simp] lemma Ioc_union_Ico_eq_Ioo {c} (h₁ : a < b) (h₂ : b < c) : Ioc a b ∪ Ico b c = Ioo a c := ext $ λ x, ⟨λ hx, hx.elim (λ hx, ⟨hx.1, lt_of_le_of_lt hx.2 h₂⟩) (λ hx, ⟨lt_of_lt_of_le h₁ hx.1, hx.2⟩), λ hx, (le_total x b).elim (λ hxb, or.inl ⟨hx.1, hxb⟩) (λ hxb, or.inr ⟨hxb, hx.2⟩)⟩ @[simp] lemma Icc_union_Ico_eq_Ico {c} (h₁ : a ≤ b) (h₂ : b < c) : Icc a b ∪ Ico b c = Ico a c := ext $ λ x, ⟨λ hx, hx.elim (λ hx, ⟨hx.1, lt_of_le_of_lt hx.2 h₂⟩) (λ hx, ⟨le_trans h₁ hx.1, hx.2⟩), λ hx, (le_total x b).elim (λ hxb, or.inl ⟨hx.1, hxb⟩) (λ hxb, or.inr ⟨hxb, hx.2⟩)⟩ @[simp] lemma Icc_union_Icc_eq_Icc {c} (h₁ : a ≤ b) (h₂ : b ≤ c) : Icc a b ∪ Icc b c = Icc a c := ext $ λ x, ⟨λ hx, hx.elim (λ hx, ⟨hx.1, le_trans hx.2 h₂⟩) (λ hx, ⟨le_trans h₁ hx.1, hx.2⟩), λ hx, (le_total x b).elim (λ hxb, or.inl ⟨hx.1, hxb⟩) (λ hxb, or.inr ⟨hxb, hx.2⟩)⟩ @[simp] lemma Ioc_union_Icc_eq_Ioc {c} (h₁ : a < b) (h₂ : b ≤ c) : Ioc a b ∪ Icc b c = Ioc a c := ext $ λ x, ⟨λ hx, hx.elim (λ hx, ⟨hx.1, le_trans hx.2 h₂⟩) (λ hx, ⟨lt_of_lt_of_le h₁ hx.1, hx.2⟩), λ hx, (le_total x b).elim (λ hxb, or.inl ⟨hx.1, hxb⟩) (λ hxb, or.inr ⟨hxb, hx.2⟩)⟩ /-! #### Two finite intervals, `I?o` and `Ic?` -/ @[simp] lemma Ioo_union_Ico_eq_Ioo {c} (h₁ : a < b) (h₂ : b ≤ c) : Ioo a b ∪ Ico b c = Ioo a c := ext $ λ x, ⟨λ hx, hx.elim (λ hx, ⟨hx.1, lt_of_lt_of_le hx.2 h₂⟩) (λ hx, ⟨lt_of_lt_of_le h₁ hx.1, hx.2⟩), λ hx, (lt_or_le x b).elim (λ hxb, or.inl ⟨hx.1, hxb⟩) (λ hxb, or.inr ⟨hxb, hx.2⟩)⟩ @[simp] lemma Ico_union_Ico_eq_Ico {c} (h₁ : a ≤ b) (h₂ : b ≤ c) : Ico a b ∪ Ico b c = Ico a c := ext $ λ x, ⟨λ hx, hx.elim (λ hx, ⟨hx.1, lt_of_lt_of_le hx.2 h₂⟩) (λ hx, ⟨le_trans h₁ hx.1, hx.2⟩), λ hx, (lt_or_le x b).elim (λ hxb, or.inl ⟨hx.1, hxb⟩) (λ hxb, or.inr ⟨hxb, hx.2⟩)⟩ @[simp] lemma Ico_union_Icc_eq_Icc {c} (h₁ : a ≤ b) (h₂ : b ≤ c) : Ico a b ∪ Icc b c = Icc a c := ext $ λ x, ⟨λ hx, hx.elim (λ hx, ⟨hx.1, le_trans (le_of_lt hx.2) h₂⟩) (λ hx, ⟨le_trans h₁ hx.1, hx.2⟩), λ hx, (lt_or_le x b).elim (λ hxb, or.inl ⟨hx.1, hxb⟩) (λ hxb, or.inr ⟨hxb, hx.2⟩)⟩ @[simp] lemma Ioo_union_Icc_eq_Ioc {c} (h₁ : a < b) (h₂ : b ≤ c) : Ioo a b ∪ Icc b c = Ioc a c := ext $ λ x, ⟨λ hx, hx.elim (λ hx, ⟨hx.1, le_trans (le_of_lt hx.2) h₂⟩) (λ hx, ⟨lt_of_lt_of_le h₁ hx.1, hx.2⟩), λ hx, (lt_or_le x b).elim (λ hxb, or.inl ⟨hx.1, hxb⟩) (λ hxb, or.inr ⟨hxb, hx.2⟩)⟩ /-! #### Two finite intervals, `I?c` and `Io?` -/ @[simp] lemma Ioc_union_Ioo_eq_Ioo {c} (h₁ : a ≤ b) (h₂ : b < c) : Ioc a b ∪ Ioo b c = Ioo a c := ext $ λ x, ⟨λ hx, hx.elim (λ hx, ⟨hx.1, lt_of_le_of_lt hx.2 h₂⟩) (λ hx, ⟨lt_of_le_of_lt h₁ hx.1, hx.2⟩), λ hx, (le_or_lt x b).elim (λ hxb, or.inl ⟨hx.1, hxb⟩) (λ hxb, or.inr ⟨hxb, hx.2⟩)⟩ @[simp] lemma Icc_union_Ioo_eq_Ico {c} (h₁ : a ≤ b) (h₂ : b < c) : Icc a b ∪ Ioo b c = Ico a c := ext $ λ x, ⟨λ hx, hx.elim (λ hx, ⟨hx.1, lt_of_le_of_lt hx.2 h₂⟩) (λ hx, ⟨le_trans h₁ (le_of_lt hx.1), hx.2⟩), λ hx, (le_or_lt x b).elim (λ hxb, or.inl ⟨hx.1, hxb⟩) (λ hxb, or.inr ⟨hxb, hx.2⟩)⟩ @[simp] lemma Icc_union_Ioc_eq_Icc {c} (h₁ : a ≤ b) (h₂ : b ≤ c) : Icc a b ∪ Ioc b c = Icc a c := ext $ λ x, ⟨λ hx, hx.elim (λ hx, ⟨hx.1, le_trans hx.2 h₂⟩) (λ hx, ⟨le_trans h₁ (le_of_lt hx.1), hx.2⟩), λ hx, (le_or_lt x b).elim (λ hxb, or.inl ⟨hx.1, hxb⟩) (λ hxb, or.inr ⟨hxb, hx.2⟩)⟩ @[simp] lemma Ioc_union_Ioc_eq_Ioc {c} (h₁ : a ≤ b) (h₂ : b ≤ c) : Ioc a b ∪ Ioc b c = Ioc a c := ext $ λ x, ⟨λ hx, hx.elim (λ hx, ⟨hx.1, le_trans hx.2 h₂⟩) (λ hx, ⟨lt_of_le_of_lt h₁ hx.1, hx.2⟩), λ hx, (le_or_lt x b).elim (λ hxb, or.inl ⟨hx.1, hxb⟩) (λ hxb, or.inr ⟨hxb, hx.2⟩)⟩ end linear_order section lattice section inf variables {α : Type u} [semilattice_inf α] @[simp] lemma Iic_inter_Iic {a b : α} : Iic a ∩ Iic b = Iic (a ⊓ b) := by { ext x, simp [Iic] } @[simp] lemma Iio_inter_Iio [is_total α (≤)] {a b : α} : Iio a ∩ Iio b = Iio (a ⊓ b) := by { ext x, simp [Iio] } end inf section sup variables {α : Type u} [semilattice_sup α] @[simp] lemma Ici_inter_Ici {a b : α} : Ici a ∩ Ici b = Ici (a ⊔ b) := by { ext x, simp [Ici] } @[simp] lemma Ioi_inter_Ioi [is_total α (≤)] {a b : α} : Ioi a ∩ Ioi b = Ioi (a ⊔ b) := by { ext x, simp [Ioi] } end sup section both variables {α : Type u} [lattice α] [ht : is_total α (≤)] {a b c a₁ a₂ b₁ b₂ : α} lemma Icc_inter_Icc : Icc a₁ b₁ ∩ Icc a₂ b₂ = Icc (a₁ ⊔ a₂) (b₁ ⊓ b₂) := by simp only [Ici_inter_Iic.symm, Ici_inter_Ici.symm, Iic_inter_Iic.symm]; ac_refl @[simp] lemma Icc_inter_Icc_eq_singleton (hab : a ≤ b) (hbc : b ≤ c) : Icc a b ∩ Icc b c = {b} := by rw [Icc_inter_Icc, sup_of_le_right hab, inf_of_le_left hbc, Icc_self] include ht lemma Ico_inter_Ico : Ico a₁ b₁ ∩ Ico a₂ b₂ = Ico (a₁ ⊔ a₂) (b₁ ⊓ b₂) := by simp only [Ici_inter_Iio.symm, Ici_inter_Ici.symm, Iio_inter_Iio.symm]; ac_refl lemma Ioc_inter_Ioc : Ioc a₁ b₁ ∩ Ioc a₂ b₂ = Ioc (a₁ ⊔ a₂) (b₁ ⊓ b₂) := by simp only [Ioi_inter_Iic.symm, Ioi_inter_Ioi.symm, Iic_inter_Iic.symm]; ac_refl lemma Ioo_inter_Ioo : Ioo a₁ b₁ ∩ Ioo a₂ b₂ = Ioo (a₁ ⊔ a₂) (b₁ ⊓ b₂) := by simp only [Ioi_inter_Iio.symm, Ioi_inter_Ioi.symm, Iio_inter_Iio.symm]; ac_refl end both end lattice section decidable_linear_order variables {α : Type u} [decidable_linear_order α] {a a₁ a₂ b b₁ b₂ : α} @[simp] lemma Ico_diff_Iio {a b c : α} : Ico a b \ Iio c = Ico (max a c) b := set.ext $ by simp [Ico, Iio, iff_def, max_le_iff] {contextual:=tt} @[simp] lemma Ico_inter_Iio {a b c : α} : Ico a b ∩ Iio c = Ico a (min b c) := set.ext $ by simp [Ico, Iio, iff_def, lt_min_iff] {contextual:=tt} end decidable_linear_order section ordered_add_comm_group variables {α : Type u} [ordered_add_comm_group α] lemma image_add_left_Icc (a b c : α) : ((+) a) '' Icc b c = Icc (a + b) (a + c) := begin ext x, split, { rintros ⟨x, hx, rfl⟩, exact ⟨add_le_add_left hx.1 a, add_le_add_left hx.2 a⟩}, { intro hx, refine ⟨-a + x, _, add_neg_cancel_left _ _⟩, exact ⟨le_neg_add_iff_add_le.2 hx.1, neg_add_le_iff_le_add.2 hx.2⟩ } end lemma image_add_right_Icc (a b c : α) : (λ x, x + c) '' Icc a b = Icc (a + c) (b + c) := by convert image_add_left_Icc c a b using 1; simp only [add_comm _ c] lemma image_neg_Iio (r : α) : image (λz, -z) (Iio r) = Ioi (-r) := begin ext z, apply iff.intro, { intros hz, apply exists.elim hz, intros z' hz', rw [←hz'.2], simp only [mem_Ioi, neg_lt_neg_iff], exact hz'.1 }, { intros hz, simp only [mem_image, mem_Iio], use -z, simp [hz], exact neg_lt.1 hz } end lemma image_neg_Iic (r : α) : image (λz, -z) (Iic r) = Ici (-r) := begin apply set.ext, intros z, apply iff.intro, { intros hz, apply exists.elim hz, intros z' hz', rw [←hz'.2], simp only [neg_le_neg_iff, mem_Ici], exact hz'.1 }, { intros hz, simp only [mem_image, mem_Iic], use -z, simp [hz], exact neg_le.1 hz } end end ordered_add_comm_group section decidable_linear_ordered_add_comm_group variables {α : Type u} [decidable_linear_ordered_add_comm_group α] /-- If we remove a smaller interval from a larger, the result is nonempty -/ lemma nonempty_Ico_sdiff {x dx y dy : α} (h : dy < dx) (hx : 0 < dx) : nonempty ↥(Ico x (x + dx) \ Ico y (y + dy)) := begin cases lt_or_le x y with h' h', { use x, simp* }, { use max x (x + dy), simp [*, le_refl] } end end decidable_linear_ordered_add_comm_group section linear_ordered_field variables {α : Type u} [linear_ordered_field α] lemma image_mul_right_Icc' (a b : α) {c : α} (h : 0 < c) : (λ x, x * c) '' Icc a b = Icc (a * c) (b * c) := begin ext x, split, { rintros ⟨x, hx, rfl⟩, exact ⟨mul_le_mul_of_nonneg_right hx.1 (le_of_lt h), mul_le_mul_of_nonneg_right hx.2 (le_of_lt h)⟩ }, { intro hx, refine ⟨x / c, _, div_mul_cancel x (ne_of_gt h)⟩, exact ⟨le_div_of_mul_le h hx.1, div_le_of_le_mul h (mul_comm b c ▸ hx.2)⟩ } end lemma image_mul_right_Icc {a b c : α} (hab : a ≤ b) (hc : 0 ≤ c) : (λ x, x * c) '' Icc a b = Icc (a * c) (b * c) := begin cases eq_or_lt_of_le hc, { subst c, simp [(nonempty_Icc.2 hab).image_const] }, exact image_mul_right_Icc' a b ‹0 < c› end lemma image_mul_left_Icc' {a : α} (h : 0 < a) (b c : α) : ((*) a) '' Icc b c = Icc (a * b) (a * c) := by { convert image_mul_right_Icc' b c h using 1; simp only [mul_comm _ a] } lemma image_mul_left_Icc {a b c : α} (ha : 0 ≤ a) (hbc : b ≤ c) : ((*) a) '' Icc b c = Icc (a * b) (a * c) := by { convert image_mul_right_Icc hbc ha using 1; simp only [mul_comm _ a] } end linear_ordered_field end set
ac4758453afce9fa64efb499ff59cc7468f998bc
bb31430994044506fa42fd667e2d556327e18dfe
/src/ring_theory/ideal/basic.lean
fd1ffa938c20c51f856cdf3e3bf92faf864fb713
[ "Apache-2.0" ]
permissive
sgouezel/mathlib
0cb4e5335a2ba189fa7af96d83a377f83270e503
00638177efd1b2534fc5269363ebf42a7871df9a
refs/heads/master
1,674,527,483,042
1,673,665,568,000
1,673,665,568,000
119,598,202
0
0
null
1,517,348,647,000
1,517,348,646,000
null
UTF-8
Lean
false
false
25,691
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.associated import linear_algebra.basic import order.atoms import order.compactly_generated import tactic.abel import data.nat.choose.sum import linear_algebra.finsupp /-! # Ideals over a ring This file defines `ideal R`, the type of (left) ideals over a ring `R`. Note that over commutative rings, left ideals and two-sided ideals are equivalent. ## Implementation notes `ideal R` is implemented using `submodule R R`, where `•` is interpreted as `*`. ## TODO Support right ideals, and two-sided ideals over non-commutative rings. -/ universes u v w variables {α : Type u} {β : Type v} open set function open_locale classical big_operators pointwise /-- A (left) ideal in a semiring `R` is an additive submonoid `s` such that `a * b ∈ s` whenever `b ∈ s`. If `R` is a ring, then `s` is an additive subgroup. -/ @[reducible] def ideal (R : Type u) [semiring R] := submodule R R section semiring namespace ideal variables [semiring α] (I : ideal α) {a b : α} protected lemma zero_mem : (0 : α) ∈ I := I.zero_mem protected lemma add_mem : a ∈ I → b ∈ I → a + b ∈ I := I.add_mem variables (a) lemma mul_mem_left : b ∈ I → a * b ∈ I := I.smul_mem a variables {a} @[ext] lemma ext {I J : ideal α} (h : ∀ x, x ∈ I ↔ x ∈ J) : I = J := submodule.ext h lemma sum_mem (I : ideal α) {ι : Type*} {t : finset ι} {f : ι → α} : (∀c∈t, f c ∈ I) → (∑ i in t, f i) ∈ I := submodule.sum_mem I theorem eq_top_of_unit_mem (x y : α) (hx : x ∈ I) (h : y * x = 1) : I = ⊤ := eq_top_iff.2 $ λ z _, calc z = z * (y * x) : by simp [h] ... = (z * y) * x : eq.symm $ mul_assoc z y x ... ∈ I : I.mul_mem_left _ hx theorem eq_top_of_is_unit_mem {x} (hx : x ∈ I) (h : is_unit x) : I = ⊤ := let ⟨y, hy⟩ := h.exists_left_inv in eq_top_of_unit_mem I x y hx hy theorem eq_top_iff_one : I = ⊤ ↔ (1:α) ∈ I := ⟨by rintro rfl; trivial, λ h, eq_top_of_unit_mem _ _ 1 h (by simp)⟩ theorem ne_top_iff_one : I ≠ ⊤ ↔ (1:α) ∉ I := not_congr I.eq_top_iff_one @[simp] theorem unit_mul_mem_iff_mem {x y : α} (hy : is_unit y) : y * x ∈ I ↔ x ∈ I := begin refine ⟨λ h, _, λ h, I.mul_mem_left y h⟩, obtain ⟨y', hy'⟩ := hy.exists_left_inv, have := I.mul_mem_left y' h, rwa [← mul_assoc, hy', one_mul] at this, end /-- The ideal generated by a subset of a ring -/ def span (s : set α) : ideal α := submodule.span α s @[simp] lemma submodule_span_eq {s : set α} : submodule.span α s = ideal.span s := rfl @[simp] lemma span_empty : span (∅ : set α) = ⊥ := submodule.span_empty @[simp] lemma span_univ : span (set.univ : set α) = ⊤ := submodule.span_univ lemma span_union (s t : set α) : span (s ∪ t) = span s ⊔ span t := submodule.span_union _ _ lemma span_Union {ι} (s : ι → set α) : span (⋃ i, s i) = ⨆ i, span (s i) := submodule.span_Union _ lemma mem_span {s : set α} (x) : x ∈ span s ↔ ∀ p : ideal α, s ⊆ p → x ∈ p := mem_Inter₂ lemma subset_span {s : set α} : s ⊆ span s := submodule.subset_span lemma span_le {s : set α} {I} : span s ≤ I ↔ s ⊆ I := submodule.span_le lemma span_mono {s t : set α} : s ⊆ t → span s ≤ span t := submodule.span_mono @[simp] lemma span_eq : span (I : set α) = I := submodule.span_eq _ @[simp] lemma span_singleton_one : span ({1} : set α) = ⊤ := (eq_top_iff_one _).2 $ subset_span $ mem_singleton _ lemma mem_span_insert {s : set α} {x y} : x ∈ span (insert y s) ↔ ∃ a (z ∈ span s), x = a * y + z := submodule.mem_span_insert lemma mem_span_singleton' {x y : α} : x ∈ span ({y} : set α) ↔ ∃ a, a * y = x := submodule.mem_span_singleton lemma span_singleton_le_iff_mem {x : α} : span {x} ≤ I ↔ x ∈ I := submodule.span_singleton_le_iff_mem _ _ lemma span_singleton_mul_left_unit {a : α} (h2 : is_unit a) (x : α) : span ({a * x} : set α) = span {x} := begin apply le_antisymm; rw [span_singleton_le_iff_mem, mem_span_singleton'], exacts [⟨a, rfl⟩, ⟨_, h2.unit.inv_mul_cancel_left x⟩], end lemma span_insert (x) (s : set α) : span (insert x s) = span ({x} : set α) ⊔ span s := submodule.span_insert x s lemma span_eq_bot {s : set α} : span s = ⊥ ↔ ∀ x ∈ s, (x:α) = 0 := submodule.span_eq_bot @[simp] lemma span_singleton_eq_bot {x} : span ({x} : set α) = ⊥ ↔ x = 0 := submodule.span_singleton_eq_bot lemma span_singleton_ne_top {α : Type*} [comm_semiring α] {x : α} (hx : ¬ is_unit x) : ideal.span ({x} : set α) ≠ ⊤ := (ideal.ne_top_iff_one _).mpr $ λ h1, let ⟨y, hy⟩ := ideal.mem_span_singleton'.mp h1 in hx ⟨⟨x, y, mul_comm y x ▸ hy, hy⟩, rfl⟩ @[simp] lemma span_zero : span (0 : set α) = ⊥ := by rw [←set.singleton_zero, span_singleton_eq_bot] @[simp] lemma span_one : span (1 : set α) = ⊤ := by rw [←set.singleton_one, span_singleton_one] lemma span_eq_top_iff_finite (s : set α) : span s = ⊤ ↔ ∃ s' : finset α, ↑s' ⊆ s ∧ span (s' : set α) = ⊤ := begin simp_rw eq_top_iff_one, exact ⟨submodule.mem_span_finite_of_mem_span, λ ⟨s', h₁, h₂⟩, span_mono h₁ h₂⟩ end lemma mem_span_singleton_sup {S : Type*} [comm_semiring S] {x y : S} {I : ideal S} : x ∈ ideal.span {y} ⊔ I ↔ ∃ (a : S) (b ∈ I), a * y + b = x := begin rw submodule.mem_sup, split, { rintro ⟨ya, hya, b, hb, rfl⟩, obtain ⟨a, rfl⟩ := mem_span_singleton'.mp hya, exact ⟨a, b, hb, rfl⟩ }, { rintro ⟨a, b, hb, rfl⟩, exact ⟨a * y, ideal.mem_span_singleton'.mpr ⟨a, rfl⟩, b, hb, rfl⟩ } end /-- The ideal generated by an arbitrary binary relation. -/ def of_rel (r : α → α → Prop) : ideal α := submodule.span α { x | ∃ (a b) (h : r a b), x + b = a } /-- An ideal `P` of a ring `R` is prime if `P ≠ R` and `xy ∈ P → x ∈ P ∨ y ∈ P` -/ class is_prime (I : ideal α) : Prop := (ne_top' : I ≠ ⊤) (mem_or_mem' : ∀ {x y : α}, x * y ∈ I → x ∈ I ∨ y ∈ I) theorem is_prime_iff {I : ideal α} : is_prime I ↔ I ≠ ⊤ ∧ ∀ {x y : α}, x * y ∈ I → x ∈ I ∨ y ∈ I := ⟨λ h, ⟨h.1, λ _ _, h.2⟩, λ h, ⟨h.1, λ _ _, h.2⟩⟩ theorem is_prime.ne_top {I : ideal α} (hI : I.is_prime) : I ≠ ⊤ := hI.1 theorem is_prime.mem_or_mem {I : ideal α} (hI : I.is_prime) {x y : α} : x * y ∈ I → x ∈ I ∨ y ∈ I := hI.2 theorem is_prime.mem_or_mem_of_mul_eq_zero {I : ideal α} (hI : I.is_prime) {x y : α} (h : x * y = 0) : x ∈ I ∨ y ∈ I := hI.mem_or_mem (h.symm ▸ I.zero_mem) theorem is_prime.mem_of_pow_mem {I : ideal α} (hI : I.is_prime) {r : α} (n : ℕ) (H : r^n ∈ I) : r ∈ I := begin induction n with n ih, { rw pow_zero at H, exact (mt (eq_top_iff_one _).2 hI.1).elim H }, { rw pow_succ at H, exact or.cases_on (hI.mem_or_mem H) id ih } end lemma not_is_prime_iff {I : ideal α} : ¬ I.is_prime ↔ I = ⊤ ∨ ∃ (x ∉ I) (y ∉ I), x * y ∈ I := begin simp_rw [ideal.is_prime_iff, not_and_distrib, ne.def, not_not, not_forall, not_or_distrib], exact or_congr iff.rfl ⟨λ ⟨x, y, hxy, hx, hy⟩, ⟨x, hx, y, hy, hxy⟩, λ ⟨x, hx, y, hy, hxy⟩, ⟨x, y, hxy, hx, hy⟩⟩ end theorem zero_ne_one_of_proper {I : ideal α} (h : I ≠ ⊤) : (0:α) ≠ 1 := λ hz, I.ne_top_iff_one.1 h $ hz ▸ I.zero_mem lemma bot_prime {R : Type*} [ring R] [is_domain R] : (⊥ : ideal R).is_prime := ⟨λ h, one_ne_zero (by rwa [ideal.eq_top_iff_one, submodule.mem_bot] at h), λ x y h, mul_eq_zero.mp (by simpa only [submodule.mem_bot] using h)⟩ /-- An ideal is maximal if it is maximal in the collection of proper ideals. -/ class is_maximal (I : ideal α) : Prop := (out : is_coatom I) theorem is_maximal_def {I : ideal α} : I.is_maximal ↔ is_coatom I := ⟨λ h, h.1, λ h, ⟨h⟩⟩ theorem is_maximal.ne_top {I : ideal α} (h : I.is_maximal) : I ≠ ⊤ := (is_maximal_def.1 h).1 theorem is_maximal_iff {I : ideal α} : I.is_maximal ↔ (1:α) ∉ I ∧ ∀ (J : ideal α) x, I ≤ J → x ∉ I → x ∈ J → (1:α) ∈ J := is_maximal_def.trans $ and_congr I.ne_top_iff_one $ forall_congr $ λ J, by rw [lt_iff_le_not_le]; exact ⟨λ H x h hx₁ hx₂, J.eq_top_iff_one.1 $ H ⟨h, not_subset.2 ⟨_, hx₂, hx₁⟩⟩, λ H ⟨h₁, h₂⟩, let ⟨x, xJ, xI⟩ := not_subset.1 h₂ in J.eq_top_iff_one.2 $ H x h₁ xI xJ⟩ theorem is_maximal.eq_of_le {I J : ideal α} (hI : I.is_maximal) (hJ : J ≠ ⊤) (IJ : I ≤ J) : I = J := eq_iff_le_not_lt.2 ⟨IJ, λ h, hJ (hI.1.2 _ h)⟩ instance : is_coatomic (ideal α) := begin apply complete_lattice.coatomic_of_top_compact, rw ←span_singleton_one, exact submodule.singleton_span_is_compact_element 1, end /-- **Krull's theorem**: if `I` is an ideal that is not the whole ring, then it is included in some maximal ideal. -/ theorem exists_le_maximal (I : ideal α) (hI : I ≠ ⊤) : ∃ M : ideal α, M.is_maximal ∧ I ≤ M := let ⟨m, hm⟩ := (eq_top_or_exists_le_coatom I).resolve_left hI in ⟨m, ⟨⟨hm.1⟩, hm.2⟩⟩ variables (α) /-- Krull's theorem: a nontrivial ring has a maximal ideal. -/ theorem exists_maximal [nontrivial α] : ∃ M : ideal α, M.is_maximal := let ⟨I, ⟨hI, _⟩⟩ := exists_le_maximal (⊥ : ideal α) bot_ne_top in ⟨I, hI⟩ variables {α} instance [nontrivial α] : nontrivial (ideal α) := begin rcases @exists_maximal α _ _ with ⟨M, hM, _⟩, exact nontrivial_of_ne M ⊤ hM end /-- If P is not properly contained in any maximal ideal then it is not properly contained in any proper ideal -/ lemma maximal_of_no_maximal {R : Type u} [semiring R] {P : ideal R} (hmax : ∀ m : ideal R, P < m → ¬is_maximal m) (J : ideal R) (hPJ : P < J) : J = ⊤ := begin by_contradiction hnonmax, rcases exists_le_maximal J hnonmax with ⟨M, hM1, hM2⟩, exact hmax M (lt_of_lt_of_le hPJ hM2) hM1, end lemma span_pair_comm {x y : α} : (span {x, y} : ideal α) = span {y, x} := by simp only [span_insert, sup_comm] theorem mem_span_pair {x y z : α} : z ∈ span ({x, y} : set α) ↔ ∃ a b, a * x + b * y = z := submodule.mem_span_pair @[simp] lemma span_pair_add_mul_left {R : Type u} [comm_ring R] {x y : R} (z : R) : (span {x + y * z, y} : ideal R) = span {x, y} := begin ext, rw [mem_span_pair, mem_span_pair], exact ⟨λ ⟨a, b, h⟩, ⟨a, b + a * z, by { rw [← h], ring1 }⟩, λ ⟨a, b, h⟩, ⟨a, b - a * z, by { rw [← h], ring1 }⟩⟩ end @[simp] lemma span_pair_add_mul_right {R : Type u} [comm_ring R] {x y : R} (z : R) : (span {x, y + x * z} : ideal R) = span {x, y} := by rw [span_pair_comm, span_pair_add_mul_left, span_pair_comm] theorem is_maximal.exists_inv {I : ideal α} (hI : I.is_maximal) {x} (hx : x ∉ I) : ∃ y, ∃ i ∈ I, y * x + i = 1 := begin cases is_maximal_iff.1 hI with H₁ H₂, rcases mem_span_insert.1 (H₂ (span (insert x I)) x (set.subset.trans (subset_insert _ _) subset_span) hx (subset_span (mem_insert _ _))) with ⟨y, z, hz, hy⟩, refine ⟨y, z, _, hy.symm⟩, rwa ← span_eq I, end section lattice variables {R : Type u} [semiring R] lemma mem_sup_left {S T : ideal R} : ∀ {x : R}, x ∈ S → x ∈ S ⊔ T := show S ≤ S ⊔ T, from le_sup_left lemma mem_sup_right {S T : ideal R} : ∀ {x : R}, x ∈ T → x ∈ S ⊔ T := show T ≤ S ⊔ T, from le_sup_right lemma mem_supr_of_mem {ι : Sort*} {S : ι → ideal R} (i : ι) : ∀ {x : R}, x ∈ S i → x ∈ supr S := show S i ≤ supr S, from le_supr _ _ lemma mem_Sup_of_mem {S : set (ideal R)} {s : ideal R} (hs : s ∈ S) : ∀ {x : R}, x ∈ s → x ∈ Sup S := show s ≤ Sup S, from le_Sup hs theorem mem_Inf {s : set (ideal R)} {x : R} : x ∈ Inf s ↔ ∀ ⦃I⦄, I ∈ s → x ∈ I := ⟨λ hx I his, hx I ⟨I, infi_pos his⟩, λ H I ⟨J, hij⟩, hij ▸ λ S ⟨hj, hS⟩, hS ▸ H hj⟩ @[simp] lemma mem_inf {I J : ideal R} {x : R} : x ∈ I ⊓ J ↔ x ∈ I ∧ x ∈ J := iff.rfl @[simp] lemma mem_infi {ι : Sort*} {I : ι → ideal R} {x : R} : x ∈ infi I ↔ ∀ i, x ∈ I i := submodule.mem_infi _ @[simp] lemma mem_bot {x : R} : x ∈ (⊥ : ideal R) ↔ x = 0 := submodule.mem_bot _ end lattice section pi variables (ι : Type v) /-- `I^n` as an ideal of `R^n`. -/ def pi : ideal (ι → α) := { carrier := { x | ∀ i, x i ∈ I }, zero_mem' := λ i, I.zero_mem, add_mem' := λ a b ha hb i, I.add_mem (ha i) (hb i), smul_mem' := λ a b hb i, I.mul_mem_left (a i) (hb i) } lemma mem_pi (x : ι → α) : x ∈ I.pi ι ↔ ∀ i, x i ∈ I := iff.rfl end pi lemma Inf_is_prime_of_is_chain {s : set (ideal α)} (hs : s.nonempty) (hs' : is_chain (≤) s) (H : ∀ p ∈ s, ideal.is_prime p) : (Inf s).is_prime := ⟨λ e, let ⟨x, hx⟩ := hs in (H x hx).ne_top (eq_top_iff.mpr (e.symm.trans_le (Inf_le hx))), λ x y e, or_iff_not_imp_left.mpr $ λ hx, begin rw ideal.mem_Inf at hx ⊢ e, push_neg at hx, obtain ⟨I, hI, hI'⟩ := hx, intros J hJ, cases hs'.total hI hJ, { exact h (((H I hI).mem_or_mem (e hI)).resolve_left hI') }, { exact ((H J hJ).mem_or_mem (e hJ)).resolve_left (λ x, hI' $ h x) }, end⟩ end ideal end semiring section comm_semiring variables {a b : α} -- A separate namespace definition is needed because the variables were historically in a different -- order. namespace ideal variables [comm_semiring α] (I : ideal α) @[simp] theorem mul_unit_mem_iff_mem {x y : α} (hy : is_unit y) : x * y ∈ I ↔ x ∈ I := mul_comm y x ▸ unit_mul_mem_iff_mem I hy lemma mem_span_singleton {x y : α} : x ∈ span ({y} : set α) ↔ y ∣ x := mem_span_singleton'.trans $ exists_congr $ λ _, by rw [eq_comm, mul_comm] lemma mem_span_singleton_self (x : α) : x ∈ span ({x} : set α) := mem_span_singleton.mpr dvd_rfl lemma span_singleton_le_span_singleton {x y : α} : span ({x} : set α) ≤ span ({y} : set α) ↔ y ∣ x := span_le.trans $ singleton_subset_iff.trans mem_span_singleton lemma span_singleton_eq_span_singleton {α : Type u} [comm_ring α] [is_domain α] {x y : α} : span ({x} : set α) = span ({y} : set α) ↔ associated x y := begin rw [←dvd_dvd_iff_associated, le_antisymm_iff, and_comm], apply and_congr; rw span_singleton_le_span_singleton, end lemma span_singleton_mul_right_unit {a : α} (h2 : is_unit a) (x : α) : span ({x * a} : set α) = span {x} := by rw [mul_comm, span_singleton_mul_left_unit h2] lemma span_singleton_eq_top {x} : span ({x} : set α) = ⊤ ↔ is_unit x := by rw [is_unit_iff_dvd_one, ← span_singleton_le_span_singleton, span_singleton_one, eq_top_iff] theorem span_singleton_prime {p : α} (hp : p ≠ 0) : is_prime (span ({p} : set α)) ↔ prime p := by simp [is_prime_iff, prime, span_singleton_eq_top, hp, mem_span_singleton] theorem is_maximal.is_prime {I : ideal α} (H : I.is_maximal) : I.is_prime := ⟨H.1.1, λ x y hxy, or_iff_not_imp_left.2 $ λ hx, begin let J : ideal α := submodule.span α (insert x ↑I), have IJ : I ≤ J := (set.subset.trans (subset_insert _ _) subset_span), have xJ : x ∈ J := ideal.subset_span (set.mem_insert x I), cases is_maximal_iff.1 H with _ oJ, specialize oJ J x IJ hx xJ, rcases submodule.mem_span_insert.mp oJ with ⟨a, b, h, oe⟩, obtain (F : y * 1 = y * (a • x + b)) := congr_arg (λ g : α, y * g) oe, rw [← mul_one y, F, mul_add, mul_comm, smul_eq_mul, mul_assoc], refine submodule.add_mem I (I.mul_mem_left a hxy) (submodule.smul_mem I y _), rwa submodule.span_eq at h, end⟩ @[priority 100] -- see Note [lower instance priority] instance is_maximal.is_prime' (I : ideal α) : ∀ [H : I.is_maximal], I.is_prime := is_maximal.is_prime lemma span_singleton_lt_span_singleton [comm_ring β] [is_domain β] {x y : β} : span ({x} : set β) < span ({y} : set β) ↔ dvd_not_unit y x := by rw [lt_iff_le_not_le, span_singleton_le_span_singleton, span_singleton_le_span_singleton, dvd_and_not_dvd_iff] lemma factors_decreasing [comm_ring β] [is_domain β] (b₁ b₂ : β) (h₁ : b₁ ≠ 0) (h₂ : ¬ is_unit b₂) : span ({b₁ * b₂} : set β) < span {b₁} := lt_of_le_not_le (ideal.span_le.2 $ singleton_subset_iff.2 $ ideal.mem_span_singleton.2 ⟨b₂, rfl⟩) $ λ h, h₂ $ is_unit_of_dvd_one _ $ (mul_dvd_mul_iff_left h₁).1 $ by rwa [mul_one, ← ideal.span_singleton_le_span_singleton] variables (b) lemma mul_mem_right (h : a ∈ I) : a * b ∈ I := mul_comm b a ▸ I.mul_mem_left b h variables {b} lemma pow_mem_of_mem (ha : a ∈ I) (n : ℕ) (hn : 0 < n) : a ^ n ∈ I := nat.cases_on n (not.elim dec_trivial) (λ m hm, (pow_succ a m).symm ▸ I.mul_mem_right (a^m) ha) hn theorem is_prime.mul_mem_iff_mem_or_mem {I : ideal α} (hI : I.is_prime) : ∀ {x y : α}, x * y ∈ I ↔ x ∈ I ∨ y ∈ I := λ x y, ⟨hI.mem_or_mem, by { rintro (h | h), exacts [I.mul_mem_right y h, I.mul_mem_left x h] }⟩ theorem is_prime.pow_mem_iff_mem {I : ideal α} (hI : I.is_prime) {r : α} (n : ℕ) (hn : 0 < n) : r ^ n ∈ I ↔ r ∈ I := ⟨hI.mem_of_pow_mem n, (λ hr, I.pow_mem_of_mem hr n hn)⟩ theorem pow_multiset_sum_mem_span_pow (s : multiset α) (n : ℕ) : s.sum ^ (s.card * n + 1) ∈ span ((s.map (λ x, x ^ (n + 1))).to_finset : set α) := begin induction s using multiset.induction_on with a s hs, { simp }, simp only [finset.coe_insert, multiset.map_cons, multiset.to_finset_cons, multiset.sum_cons, multiset.card_cons, add_pow], refine submodule.sum_mem _ _, intros c hc, rw mem_span_insert, by_cases h : n+1 ≤ c, { refine ⟨a ^ (c - (n + 1)) * s.sum ^ ((s.card + 1) * n + 1 - c) * (((s.card + 1) * n + 1).choose c), 0, submodule.zero_mem _, _⟩, rw mul_comm _ (a ^ (n + 1)), simp_rw ← mul_assoc, rw [← pow_add, add_zero, add_tsub_cancel_of_le h], }, { use 0, simp_rw [zero_mul, zero_add], refine ⟨_,_,rfl⟩, replace h : c ≤ n := nat.lt_succ_iff.mp (not_le.mp h), have : (s.card + 1) * n + 1 - c = s.card * n + 1 + (n - c), { rw [add_mul, one_mul, add_assoc, add_comm n 1, ← add_assoc, add_tsub_assoc_of_le h] }, rw [this, pow_add], simp_rw [mul_assoc, mul_comm (s.sum ^ (s.card * n + 1)), ← mul_assoc], exact mul_mem_left _ _ hs } end theorem sum_pow_mem_span_pow {ι} (s : finset ι) (f : ι → α) (n : ℕ) : (∑ i in s, f i) ^ (s.card * n + 1) ∈ span ((λ i, f i ^ (n + 1)) '' s) := begin convert pow_multiset_sum_mem_span_pow (s.1.map f) n, { rw multiset.card_map, refl }, rw [multiset.map_map, multiset.to_finset_map, finset.val_to_finset, finset.coe_image] end theorem span_pow_eq_top (s : set α) (hs : span s = ⊤) (n : ℕ) : span ((λ x, x ^ n) '' s) = ⊤ := begin rw eq_top_iff_one, cases n, { obtain rfl | ⟨x, hx⟩ := eq_empty_or_nonempty s, { rw [set.image_empty, hs], trivial }, { exact subset_span ⟨_, hx, pow_zero _⟩ } }, rw [eq_top_iff_one, span, finsupp.mem_span_iff_total] at hs, rcases hs with ⟨f, hf⟩, change f.support.sum (λ a, f a * a) = 1 at hf, have := sum_pow_mem_span_pow f.support (λ a, f a * a) n, rw [hf, one_pow] at this, refine (span_le).mpr _ this, rintros _ hx, simp_rw [finset.mem_coe, set.mem_image] at hx, rcases hx with ⟨x, hx, rfl⟩, have : span ({x ^ (n + 1)} : set α) ≤ span ((λ (x : α), x ^ (n + 1)) '' s), { rw [span_le, set.singleton_subset_iff], exact subset_span ⟨x, x.prop, rfl⟩ }, refine this _, rw [mul_pow, mem_span_singleton], exact ⟨f x ^ (n + 1), mul_comm _ _⟩ end end ideal end comm_semiring section ring namespace ideal variables [ring α] (I : ideal α) {a b : α} protected lemma neg_mem_iff : -a ∈ I ↔ a ∈ I := neg_mem_iff protected lemma add_mem_iff_left : b ∈ I → (a + b ∈ I ↔ a ∈ I) := I.add_mem_iff_left protected lemma add_mem_iff_right : a ∈ I → (a + b ∈ I ↔ b ∈ I) := I.add_mem_iff_right protected lemma sub_mem : a ∈ I → b ∈ I → a - b ∈ I := sub_mem lemma mem_span_insert' {s : set α} {x y} : x ∈ span (insert y s) ↔ ∃a, x + a * y ∈ span s := submodule.mem_span_insert' @[simp] lemma span_singleton_neg (x : α) : (span {-x} : ideal α) = span {x} := by { ext, simp only [mem_span_singleton'], exact ⟨λ ⟨y, h⟩, ⟨-y, h ▸ neg_mul_comm y x⟩, λ ⟨y, h⟩, ⟨-y, h ▸ neg_mul_neg y x⟩⟩ } end ideal end ring section division_ring variables {K : Type u} [division_ring K] (I : ideal K) namespace ideal /-- All ideals in a division ring are trivial. -/ lemma eq_bot_or_top : I = ⊥ ∨ I = ⊤ := begin rw or_iff_not_imp_right, change _ ≠ _ → _, rw ideal.ne_top_iff_one, intro h1, rw eq_bot_iff, intros r hr, by_cases H : r = 0, {simpa}, simpa [H, h1] using I.mul_mem_left r⁻¹ hr, end /-- Ideals of a `division_ring` are a simple order. Thanks to the way abbreviations work, this automatically gives a `is_simple_module K` instance. -/ instance : is_simple_order (ideal K) := ⟨eq_bot_or_top⟩ lemma eq_bot_of_prime [h : I.is_prime] : I = ⊥ := or_iff_not_imp_right.mp I.eq_bot_or_top h.1 lemma bot_is_maximal : is_maximal (⊥ : ideal K) := ⟨⟨λ h, absurd ((eq_top_iff_one (⊤ : ideal K)).mp rfl) (by rw ← h; simp), λ I hI, or_iff_not_imp_left.mp (eq_bot_or_top I) (ne_of_gt hI)⟩⟩ end ideal end division_ring section comm_ring namespace ideal theorem mul_sub_mul_mem {R : Type*} [comm_ring R] (I : ideal R) {a b c d : R} (h1 : a - b ∈ I) (h2 : c - d ∈ I) : a * c - b * d ∈ I := begin rw (show a * c - b * d = (a - b) * c + b * (c - d), by {rw [sub_mul, mul_sub], abel}), exact I.add_mem (I.mul_mem_right _ h1) (I.mul_mem_left _ h2), end end ideal end comm_ring namespace ring variables {R : Type*} [comm_ring R] lemma not_is_field_of_subsingleton {R : Type*} [ring R] [subsingleton R] : ¬ is_field R := λ ⟨⟨x, y, hxy⟩, _, _⟩, hxy (subsingleton.elim x y) lemma exists_not_is_unit_of_not_is_field [nontrivial R] (hf : ¬ is_field R) : ∃ x ≠ (0 : R), ¬ is_unit x := begin have : ¬ _ := λ h, hf ⟨exists_pair_ne R, mul_comm, h⟩, simp_rw is_unit_iff_exists_inv, push_neg at ⊢ this, obtain ⟨x, hx, not_unit⟩ := this, exact ⟨x, hx, not_unit⟩ end lemma not_is_field_iff_exists_ideal_bot_lt_and_lt_top [nontrivial R] : ¬ is_field R ↔ ∃ I : ideal R, ⊥ < I ∧ I < ⊤ := begin split, { intro h, obtain ⟨x, nz, nu⟩ := exists_not_is_unit_of_not_is_field h, use ideal.span {x}, rw [bot_lt_iff_ne_bot, lt_top_iff_ne_top], exact ⟨mt ideal.span_singleton_eq_bot.mp nz, mt ideal.span_singleton_eq_top.mp nu⟩ }, { rintros ⟨I, bot_lt, lt_top⟩ hf, obtain ⟨x, mem, ne_zero⟩ := set_like.exists_of_lt bot_lt, rw submodule.mem_bot at ne_zero, obtain ⟨y, hy⟩ := hf.mul_inv_cancel ne_zero, rw [lt_top_iff_ne_top, ne.def, ideal.eq_top_iff_one, ← hy] at lt_top, exact lt_top (I.mul_mem_right _ mem), } end lemma not_is_field_iff_exists_prime [nontrivial R] : ¬ is_field R ↔ ∃ p : ideal R, p ≠ ⊥ ∧ p.is_prime := not_is_field_iff_exists_ideal_bot_lt_and_lt_top.trans ⟨λ ⟨I, bot_lt, lt_top⟩, let ⟨p, hp, le_p⟩ := I.exists_le_maximal (lt_top_iff_ne_top.mp lt_top) in ⟨p, bot_lt_iff_ne_bot.mp (lt_of_lt_of_le bot_lt le_p), hp.is_prime⟩, λ ⟨p, ne_bot, prime⟩, ⟨p, bot_lt_iff_ne_bot.mpr ne_bot, lt_top_iff_ne_top.mpr prime.1⟩⟩ /-- When a ring is not a field, the maximal ideals are nontrivial. -/ lemma ne_bot_of_is_maximal_of_not_is_field [nontrivial R] {M : ideal R} (max : M.is_maximal) (not_field : ¬ is_field R) : M ≠ ⊥ := begin rintros h, rw h at max, rcases max with ⟨⟨h1, h2⟩⟩, obtain ⟨I, hIbot, hItop⟩ := not_is_field_iff_exists_ideal_bot_lt_and_lt_top.mp not_field, exact ne_of_lt hItop (h2 I hIbot), end end ring namespace ideal /-- Maximal ideals in a non-field are nontrivial. -/ variables {R : Type u} [comm_ring R] [nontrivial R] lemma bot_lt_of_maximal (M : ideal R) [hm : M.is_maximal] (non_field : ¬ is_field R) : ⊥ < M := begin rcases (ring.not_is_field_iff_exists_ideal_bot_lt_and_lt_top.1 non_field) with ⟨I, Ibot, Itop⟩, split, { simp }, intro mle, apply @irrefl _ (<) _ (⊤ : ideal R), have : M = ⊥ := eq_bot_iff.mpr mle, rw this at *, rwa hm.1.2 I Ibot at Itop, end end ideal variables {a b : α} /-- The set of non-invertible elements of a monoid. -/ def nonunits (α : Type u) [monoid α] : set α := { a | ¬is_unit a } @[simp] theorem mem_nonunits_iff [monoid α] : a ∈ nonunits α ↔ ¬ is_unit a := iff.rfl theorem mul_mem_nonunits_right [comm_monoid α] : b ∈ nonunits α → a * b ∈ nonunits α := mt is_unit_of_mul_is_unit_right theorem mul_mem_nonunits_left [comm_monoid α] : a ∈ nonunits α → a * b ∈ nonunits α := mt is_unit_of_mul_is_unit_left theorem zero_mem_nonunits [semiring α] : 0 ∈ nonunits α ↔ (0:α) ≠ 1 := not_congr is_unit_zero_iff @[simp] theorem one_not_mem_nonunits [monoid α] : (1:α) ∉ nonunits α := not_not_intro is_unit_one theorem coe_subset_nonunits [semiring α] {I : ideal α} (h : I ≠ ⊤) : (I : set α) ⊆ nonunits α := λ x hx hu, h $ I.eq_top_of_is_unit_mem hx hu lemma exists_max_ideal_of_mem_nonunits [comm_semiring α] (h : a ∈ nonunits α) : ∃ I : ideal α, I.is_maximal ∧ a ∈ I := begin have : ideal.span ({a} : set α) ≠ ⊤, { intro H, rw ideal.span_singleton_eq_top at H, contradiction }, rcases ideal.exists_le_maximal _ this with ⟨I, Imax, H⟩, use [I, Imax], apply H, apply ideal.subset_span, exact set.mem_singleton a end
897b41c80189411a8f176e4468386a065397557f
9dd3f3912f7321eb58ee9aa8f21778ad6221f87c
/tests/lean/run/fingerprint.lean
7d613f90d5701b0105ed9a1fc4d5f084fb578eec
[ "Apache-2.0" ]
permissive
bre7k30/lean
de893411bcfa7b3c5572e61b9e1c52951b310aa4
5a924699d076dab1bd5af23a8f910b433e598d7a
refs/heads/master
1,610,900,145,817
1,488,006,845,000
1,488,006,845,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
775
lean
open tactic meta def nat.to_expr (n : nat) : tactic expr := to_expr (quote n) run_command attribute.fingerprint `reducible >>= trace definition ex0 : nat := by attribute.fingerprint `reducible >>= nat.to_expr >>= exact attribute [reducible] definition f : nat := 10 run_command attribute.fingerprint `reducible >>= trace definition ex1 : nat := by attribute.fingerprint `reducible >>= nat.to_expr >>= exact vm_eval ex1 definition g : nat := 20 run_command attribute.fingerprint `reducible >>= trace definition ex2 : nat := by attribute.fingerprint `reducible >>= nat.to_expr >>= exact vm_eval ex2 example : ex1 = ex2 := rfl definition h : nat := 20 definition ex3 : nat := by attribute.fingerprint `reducible >>= nat.to_expr >>= exact example : ex1 = ex3 := rfl
a5561f7e166fc6babce7bd0e84c0329dded496d3
3dc4623269159d02a444fe898d33e8c7e7e9461b
/.github/workflows/project_1_a_decrire/lean-scheme-submission/src/sheaves/sheaf_on_standard_basis.lean
2180b8a8035e4d9eaa6a586505d389e5b8bc5729
[]
no_license
Or7ando/lean
cc003e6c41048eae7c34aa6bada51c9e9add9e66
d41169cf4e416a0d42092fb6bdc14131cee9dd15
refs/heads/master
1,650,600,589,722
1,587,262,906,000
1,587,262,906,000
255,387,160
0
0
null
null
null
null
UTF-8
Lean
false
false
6,063
lean
/- Sheaf (of types) on standard basis. https://stacks.math.columbia.edu/tag/009L -/ import topology.basic import to_mathlib.opens import sheaves.covering.covering_on_standard_basis import sheaves.presheaf_of_rings_on_basis universe u open topological_space namespace sheaf_on_standard_basis variables {α : Type u} [topological_space α] variables {B : set (opens α)} {HB : opens.is_basis B} variables (Bstd : opens.univ ∈ B ∧ ∀ {U V}, U ∈ B → V ∈ B → U ∩ V ∈ B) include Bstd section properties -- Compactness definition. -- Basis elementsfinite subcover def basis_is_compact : Prop := ∀ {U} (BU : U ∈ B) (OC : covering_standard_basis B U), ∃ (γ : Type u) (Hfin : fintype γ) (f : γ → OC.γ), (⋃ (OC.Uis ∘ f)) = U end properties section sheaf_condition -- Restriction map from U to U ∩ V. def res_to_inter_left (F : presheaf_on_basis α HB) {U V} (BU : U ∈ B) (BV : V ∈ B) : (F BU) → (F (Bstd.2 BU BV)) := F.res BU (Bstd.2 BU BV) (set.inter_subset_left U V) @[simp] lemma res_to_inter_left' (F : presheaf_on_basis α HB) {U V} (BU : U ∈ B) (BV : V ∈ B) : sheaf_on_standard_basis.res_to_inter_left Bstd F BU BV = F.res BU (Bstd.2 BU BV) (set.inter_subset_left U V) := rfl -- Restriction map from V to U ∩ V. def res_to_inter_right (F : presheaf_on_basis α HB) {U V} (BU : U ∈ B) (BV : V ∈ B) : (F BV) → (F (Bstd.2 BU BV)) := F.res BV (Bstd.2 BU BV) (set.inter_subset_right U V) @[simp] lemma res_to_inter_right' (F : presheaf_on_basis α HB) {U V} (BU : U ∈ B) (BV : V ∈ B) : sheaf_on_standard_basis.res_to_inter_right Bstd F BU BV = F.res BV (Bstd.2 BU BV) (set.inter_subset_right U V) := rfl -- Sheaf condition. def locality (F : presheaf_on_basis α HB) {U} (BU : U ∈ B) (OC : covering_standard_basis B U) := ∀ (s t : F BU), (∀ i, F.res BU (OC.BUis i) (subset_covering i) s = F.res BU (OC.BUis i) (subset_covering i) t) → s = t def gluing (F : presheaf_on_basis α HB) {U} (BU : U ∈ B) (OC : covering_standard_basis B U) := ∀ (s : Π i, F (OC.BUis i)), (∀ j k, sheaf_on_standard_basis.res_to_inter_left Bstd F (OC.BUis j) (OC.BUis k) (s j) = sheaf_on_standard_basis.res_to_inter_right Bstd F (OC.BUis j) (OC.BUis k) (s k)) → ∃ S, ∀ i, F.res BU (OC.BUis i) (subset_covering i) S = s i def is_sheaf_on_standard_basis (F : presheaf_on_basis α HB) := ∀ {U} (BU : U ∈ B) (OC : covering_standard_basis B U), locality Bstd F BU OC ∧ gluing Bstd F BU OC end sheaf_condition section cofinal_system -- Suffices to prove the sheaf condition for finite covers. def is_sheaf_on_standard_basis_cofinal_system (F : presheaf_on_basis α HB) : Prop := ∀ {U} (BU : U ∈ B) (OC : covering_standard_basis B U) (Hfin : fintype OC.γ), locality Bstd F BU OC ∧ gluing Bstd F BU OC theorem cofinal_systems_coverings_standard_case (F : presheaf_on_basis α HB) (Hcompact : basis_is_compact Bstd) : is_sheaf_on_standard_basis_cofinal_system Bstd F → is_sheaf_on_standard_basis Bstd F := begin intros Hcofinal, have Hcofinal' := @Hcofinal, intros U BU OC, rcases (Hcompact BU OC) with ⟨γ, Hfinγ, fγ, Hcov⟩, have BUisfin : ∀ i, ((OC.Uis ∘ fγ) i) ∈ B := λ i, OC.BUis (fγ i), let OCfin : covering_standard_basis B U := {γ := γ, Uis := OC.Uis ∘ fγ, Hcov := Hcov, BUis := BUisfin}, replace Hcofinal := Hcofinal BU OCfin Hfinγ, rcases Hcofinal with ⟨Hloc, Hglue⟩, split, -- Locality. { intros s t Hres, apply Hloc, intros i, apply Hres, }, -- Gluing. { intros s Hinter, have Hinterfin : ∀ (j k), sheaf_on_standard_basis.res_to_inter_left Bstd F _ _ (s (fγ j)) = sheaf_on_standard_basis.res_to_inter_right Bstd F _ _ (s (fγ k)) := λ j k, Hinter (fγ j) (fγ k), have Hglobal := Hglue (λ i, s (fγ i)) Hinterfin, rcases Hglobal with ⟨S, HS⟩, existsi S, intros i, let Vjs := λ j : γ, (OCfin.Uis j) ∩ (OC.Uis i), have BVjs : ∀ j, (Vjs j) ∈ B := λ j, Bstd.2 (OCfin.BUis j) (OC.BUis i), have HVjscov : (⋃ Vjs) = OC.Uis i, apply opens.ext, apply set.ext, intros x, split, { intros HxUVjs, rcases HxUVjs with ⟨Vj, HVj, HxVj⟩, rcases HVj with ⟨VjO, ⟨⟨j, HVjO⟩, HVjeq⟩⟩, rw [←HVjeq, ←HVjO] at HxVj, exact HxVj.2, }, { intros HxUi, have HxU : x ∈ U := OC.Hcov ▸ (opens_supr_mem OC.Uis i x HxUi), rw ←Hcov at HxU, rcases HxU with ⟨Uj, HUj, HxUj⟩, rcases HUj with ⟨UjO, ⟨⟨j, HUjO⟩, HUjeq⟩⟩, use [(Vjs j).1, ⟨(Vjs j), ⟨⟨j, rfl⟩, rfl⟩⟩], rw [←HUjeq, ←HUjO] at HxUj, exact ⟨HxUj, HxUi⟩, }, have HVjUVjs : ∀ j, Vjs j ⊆ OC.Uis i := HVjscov ▸ λ j x Hx, opens_supr_mem Vjs j x Hx, have HVjU : ∀ j, Vjs j ⊆ U := λ j, set.subset.trans (HVjUVjs j) (subset_covering i), let Ui : opens α := OC.Uis i, let BUi : Ui ∈ B := OC.BUis i, let OCfin' : covering_standard_basis B Ui := {γ := γ, Uis := Vjs, Hcov := HVjscov, BUis := BVjs}, have Hloc' := (@Hcofinal' Ui BUi OCfin' Hfinγ).1, have Hglue' := (@Hcofinal' Ui BUi OCfin' Hfinγ).2, have Hglue'' := Hglue' (λ j, F.res BU (BVjs j) (HVjU j) S), have Hres' : ∀ (j k), sheaf_on_standard_basis.res_to_inter_left Bstd F (BVjs j) (BVjs k) (F.res BU (BVjs j) (HVjU j) S) = sheaf_on_standard_basis.res_to_inter_right Bstd F (BVjs j) (BVjs k) (F.res BU (BVjs k) (HVjU k) S), intros j k, simp, rw ←F.Hcomp', rw ←F.Hcomp', rcases (Hglue'' Hres') with ⟨S', HS'⟩, refine @eq.trans _ _ S' _ _ _, { apply Hloc', intro j, rw HS', rw ←F.Hcomp', refl, }, { apply eq.symm, apply Hloc', intro j, simp at Hinter, erw ←Hinter, rw HS', have Hsfj : s (fγ j) = _ := (HS j).symm, rw Hsfj, rw ←F.Hcomp', refl, }, }, end end cofinal_system end sheaf_on_standard_basis
34ee267e309cc7d7b323cd9a19e530db46308d91
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/multiset/nodup_auto.lean
22ef4a5acff35809130a0f31ff5bc1fd97f6ee1b
[]
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
9,537
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.multiset.powerset import Mathlib.data.multiset.range import Mathlib.PostPort universes u_1 u_2 u_3 namespace Mathlib /-! # The `nodup` predicate for multisets without duplicate elements. -/ namespace multiset /- nodup -/ /-- `nodup s` means that `s` has no duplicates, i.e. the multiplicity of any element is at most 1. -/ def nodup {α : Type u_1} (s : multiset α) := quot.lift_on s list.nodup sorry @[simp] theorem coe_nodup {α : Type u_1} {l : List α} : nodup ↑l ↔ list.nodup l := iff.rfl @[simp] theorem nodup_zero {α : Type u_1} : nodup 0 := list.pairwise.nil @[simp] theorem nodup_cons {α : Type u_1} {a : α} {s : multiset α} : nodup (a ::ₘ s) ↔ ¬a ∈ s ∧ nodup s := quot.induction_on s fun (l : List α) => list.nodup_cons theorem nodup_cons_of_nodup {α : Type u_1} {a : α} {s : multiset α} (m : ¬a ∈ s) (n : nodup s) : nodup (a ::ₘ s) := iff.mpr nodup_cons { left := m, right := n } theorem nodup_singleton {α : Type u_1} (a : α) : nodup (a ::ₘ 0) := list.nodup_singleton theorem nodup_of_nodup_cons {α : Type u_1} {a : α} {s : multiset α} (h : nodup (a ::ₘ s)) : nodup s := and.right (iff.mp nodup_cons h) theorem not_mem_of_nodup_cons {α : Type u_1} {a : α} {s : multiset α} (h : nodup (a ::ₘ s)) : ¬a ∈ s := and.left (iff.mp nodup_cons h) theorem nodup_of_le {α : Type u_1} {s : multiset α} {t : multiset α} (h : s ≤ t) : nodup t → nodup s := le_induction_on h fun (l₁ l₂ : List α) => list.nodup_of_sublist theorem not_nodup_pair {α : Type u_1} (a : α) : ¬nodup (a ::ₘ a ::ₘ 0) := list.not_nodup_pair theorem nodup_iff_le {α : Type u_1} {s : multiset α} : nodup s ↔ ∀ (a : α), ¬a ::ₘ a ::ₘ 0 ≤ s := quot.induction_on s fun (l : List α) => iff.trans list.nodup_iff_sublist (forall_congr fun (a : α) => not_congr (iff.symm repeat_le_coe)) theorem nodup_iff_ne_cons_cons {α : Type u_1} {s : multiset α} : nodup s ↔ ∀ (a : α) (t : multiset α), s ≠ a ::ₘ a ::ₘ t := sorry theorem nodup_iff_count_le_one {α : Type u_1} [DecidableEq α] {s : multiset α} : nodup s ↔ ∀ (a : α), count a s ≤ 1 := quot.induction_on s fun (l : List α) => list.nodup_iff_count_le_one @[simp] theorem count_eq_one_of_mem {α : Type u_1} [DecidableEq α] {a : α} {s : multiset α} (d : nodup s) (h : a ∈ s) : count a s = 1 := le_antisymm (iff.mp nodup_iff_count_le_one d a) (iff.mpr count_pos h) theorem nodup_iff_pairwise {α : Type u_1} {s : multiset α} : nodup s ↔ pairwise ne s := quotient.induction_on s fun (l : List α) => iff.symm (pairwise_coe_iff_pairwise fun (a b : α) => ne.symm) theorem pairwise_of_nodup {α : Type u_1} {r : α → α → Prop} {s : multiset α} : (∀ (a : α), a ∈ s → ∀ (b : α), b ∈ s → a ≠ b → r a b) → nodup s → pairwise r s := sorry theorem forall_of_pairwise {α : Type u_1} {r : α → α → Prop} (H : symmetric r) {s : multiset α} (hs : pairwise r s) (a : α) : a ∈ s → ∀ (b : α), b ∈ s → a ≠ b → r a b := sorry theorem nodup_add {α : Type u_1} {s : multiset α} {t : multiset α} : nodup (s + t) ↔ nodup s ∧ nodup t ∧ disjoint s t := quotient.induction_on₂ s t fun (l₁ l₂ : List α) => list.nodup_append theorem disjoint_of_nodup_add {α : Type u_1} {s : multiset α} {t : multiset α} (d : nodup (s + t)) : disjoint s t := and.right (and.right (iff.mp nodup_add d)) theorem nodup_add_of_nodup {α : Type u_1} {s : multiset α} {t : multiset α} (d₁ : nodup s) (d₂ : nodup t) : nodup (s + t) ↔ disjoint s t := sorry theorem nodup_of_nodup_map {α : Type u_1} {β : Type u_2} (f : α → β) {s : multiset α} : nodup (map f s) → nodup s := quot.induction_on s fun (l : List α) => list.nodup_of_nodup_map f theorem nodup_map_on {α : Type u_1} {β : Type u_2} {f : α → β} {s : multiset α} : (∀ (x : α), x ∈ s → ∀ (y : α), y ∈ s → f x = f y → x = y) → nodup s → nodup (map f s) := quot.induction_on s fun (l : List α) => list.nodup_map_on theorem nodup_map {α : Type u_1} {β : Type u_2} {f : α → β} {s : multiset α} (hf : function.injective f) : nodup s → nodup (map f s) := nodup_map_on fun (x : α) (_x : x ∈ s) (y : α) (_x : y ∈ s) (h : f x = f y) => hf h theorem nodup_filter {α : Type u_1} (p : α → Prop) [decidable_pred p] {s : multiset α} : nodup s → nodup (filter p s) := quot.induction_on s fun (l : List α) => list.nodup_filter p @[simp] theorem nodup_attach {α : Type u_1} {s : multiset α} : nodup (attach s) ↔ nodup s := quot.induction_on s fun (l : List α) => list.nodup_attach theorem nodup_pmap {α : Type u_1} {β : Type u_2} {p : α → Prop} {f : (a : α) → p a → β} {s : multiset α} {H : ∀ (a : α), a ∈ s → p a} (hf : ∀ (a : α) (ha : p a) (b : α) (hb : p b), f a ha = f b hb → a = b) : nodup s → nodup (pmap f s H) := quot.induction_on s (fun (l : List α) (H : ∀ (a : α), a ∈ Quot.mk setoid.r l → p a) => list.nodup_pmap hf) H protected instance nodup_decidable {α : Type u_1} [DecidableEq α] (s : multiset α) : Decidable (nodup s) := quotient.rec_on_subsingleton s fun (l : List α) => list.nodup_decidable l theorem nodup_erase_eq_filter {α : Type u_1} [DecidableEq α] (a : α) {s : multiset α} : nodup s → erase s a = filter (fun (_x : α) => _x ≠ a) s := quot.induction_on s fun (l : List α) (d : nodup (Quot.mk setoid.r l)) => congr_arg coe (list.nodup_erase_eq_filter a d) theorem nodup_erase_of_nodup {α : Type u_1} [DecidableEq α] (a : α) {l : multiset α} : nodup l → nodup (erase l a) := nodup_of_le (erase_le a l) theorem mem_erase_iff_of_nodup {α : Type u_1} [DecidableEq α] {a : α} {b : α} {l : multiset α} (d : nodup l) : a ∈ erase l b ↔ a ≠ b ∧ a ∈ l := sorry theorem mem_erase_of_nodup {α : Type u_1} [DecidableEq α] {a : α} {l : multiset α} (h : nodup l) : ¬a ∈ erase l a := sorry theorem nodup_product {α : Type u_1} {β : Type u_2} {s : multiset α} {t : multiset β} : nodup s → nodup t → nodup (product s t) := sorry theorem nodup_sigma {α : Type u_1} {σ : α → Type u_2} {s : multiset α} {t : (a : α) → multiset (σ a)} : nodup s → (∀ (a : α), nodup (t a)) → nodup (multiset.sigma s t) := sorry theorem nodup_filter_map {α : Type u_1} {β : Type u_2} (f : α → Option β) {s : multiset α} (H : ∀ (a a' : α) (b : β), b ∈ f a → b ∈ f a' → a = a') : nodup s → nodup (filter_map f s) := quot.induction_on s fun (l : List α) => list.nodup_filter_map H theorem nodup_range (n : ℕ) : nodup (range n) := list.nodup_range n theorem nodup_inter_left {α : Type u_1} [DecidableEq α] {s : multiset α} (t : multiset α) : nodup s → nodup (s ∩ t) := nodup_of_le (inter_le_left s t) theorem nodup_inter_right {α : Type u_1} [DecidableEq α] (s : multiset α) {t : multiset α} : nodup t → nodup (s ∩ t) := nodup_of_le (inter_le_right s t) @[simp] theorem nodup_union {α : Type u_1} [DecidableEq α] {s : multiset α} {t : multiset α} : nodup (s ∪ t) ↔ nodup s ∧ nodup t := sorry @[simp] theorem nodup_powerset {α : Type u_1} {s : multiset α} : nodup (powerset s) ↔ nodup s := sorry theorem nodup_powerset_len {α : Type u_1} {n : ℕ} {s : multiset α} (h : nodup s) : nodup (powerset_len n s) := nodup_of_le (powerset_len_le_powerset n s) (iff.mpr nodup_powerset h) @[simp] theorem nodup_bind {α : Type u_1} {β : Type u_2} {s : multiset α} {t : α → multiset β} : nodup (bind s t) ↔ (∀ (a : α), a ∈ s → nodup (t a)) ∧ pairwise (fun (a b : α) => disjoint (t a) (t b)) s := sorry theorem nodup_ext {α : Type u_1} {s : multiset α} {t : multiset α} : nodup s → nodup t → (s = t ↔ ∀ (a : α), a ∈ s ↔ a ∈ t) := quotient.induction_on₂ s t fun (l₁ l₂ : List α) (d₁ : nodup (quotient.mk l₁)) (d₂ : nodup (quotient.mk l₂)) => iff.trans quotient.eq (list.perm_ext d₁ d₂) theorem le_iff_subset {α : Type u_1} {s : multiset α} {t : multiset α} : nodup s → (s ≤ t ↔ s ⊆ t) := quotient.induction_on₂ s t fun (l₁ l₂ : List α) (d : nodup (quotient.mk l₁)) => { mp := subset_of_le, mpr := list.subperm_of_subset_nodup d } theorem range_le {m : ℕ} {n : ℕ} : range m ≤ range n ↔ m ≤ n := iff.trans (le_iff_subset (nodup_range m)) range_subset theorem mem_sub_of_nodup {α : Type u_1} [DecidableEq α] {a : α} {s : multiset α} {t : multiset α} (d : nodup s) : a ∈ s - t ↔ a ∈ s ∧ ¬a ∈ t := sorry theorem map_eq_map_of_bij_of_nodup {α : Type u_1} {β : Type u_2} {γ : Type u_3} (f : α → γ) (g : β → γ) {s : multiset α} {t : multiset β} (hs : nodup s) (ht : nodup t) (i : (a : α) → a ∈ s → β) (hi : ∀ (a : α) (ha : a ∈ s), i a ha ∈ t) (h : ∀ (a : α) (ha : a ∈ s), f a = g (i a ha)) (i_inj : ∀ (a₁ a₂ : α) (ha₁ : a₁ ∈ s) (ha₂ : a₂ ∈ s), i a₁ ha₁ = i a₂ ha₂ → a₁ = a₂) (i_surj : ∀ (b : β), b ∈ t → ∃ (a : α), ∃ (ha : a ∈ s), b = i a ha) : map f s = map g t := sorry end Mathlib
592a37595149dd798a55d233778a3ddaa6623a05
ce89339993655da64b6ccb555c837ce6c10f9ef4
/ukikagi/top39.lean
4dde198c9197d93ce524e7c90d970d5fc404c63c
[]
no_license
zeptometer/LearnLean
ef32dc36a22119f18d843f548d0bb42f907bff5d
bb84d5dbe521127ba134d4dbf9559b294a80b9f7
refs/heads/master
1,625,710,824,322
1,601,382,570,000
1,601,382,570,000
195,228,870
2
0
null
null
null
null
UTF-8
Lean
false
false
583
lean
theorem pnp {P: Prop}: ¬(P ↔ ¬P) := begin intro h, have hnp: ¬P, { intro hp, exact h.1 hp hp }, exact hnp (h.2 hnp) end example: (∀ P Q R, (P ↔ Q) ∨ (Q ↔ R) ∨ (R ↔ P)) → ∀ P, P ∨ ¬P := begin intros h P, cases h (P ∨ ¬P) ¬(P ∨ ¬P) ¬¬(P ∨ ¬P) with h1 h23, { exfalso, exact pnp h1, }, cases h23 with h2 h3, { exfalso, exact pnp h2, }, { apply h3.1, intro H, have hnp: ¬P, { intro hp, apply H, left, assumption }, apply H, right, assumption, } end
fee456a46dd77456c797b5a59da89dd9c8d66b0c
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/tactic/localized.lean
6fa977f7238cde7270a2584f50a39de88e20a77f
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
1,066
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 Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.tactic.core import Mathlib.PostPort namespace Mathlib /-! # Localized notation This consists of two user-commands which allow you to declare notation and commands localized to a locale. See the tactic doc entry below for more information. The code is inspired by code from Gabriel Ebner from the [hott3 repository](https://github.com/gebner/hott3). -/ /-- Get all commands in the given locale and return them as a list of strings -/ /-- Execute all commands in the given locale -/ /-- Add a new command to a locale and execute it right now. The new command is added as a declaration to the environment with name `_localized_decl.<number>`. This declaration has attribute `_localized` and as value a name-string pair. -/ /-- This consists of two user-commands which allow you to declare notation and commands localized to a
eff3c7cee5ce1d7ad7f3be4806dc1e62fe415c89
94e33a31faa76775069b071adea97e86e218a8ee
/src/linear_algebra/prod.lean
cfb0e6a6e6183b02a6bcced48d551f81eb7da55f
[ "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
31,170
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Kevin Buzzard, Yury Kudryashov, Eric Wieser -/ import linear_algebra.span import order.partial_sups import algebra.algebra.basic /-! ### Products of modules This file defines constructors for linear maps whose domains or codomains are products. It contains theorems relating these to each other, as well as to `submodule.prod`, `submodule.map`, `submodule.comap`, `linear_map.range`, and `linear_map.ker`. ## Main definitions - products in the domain: - `linear_map.fst` - `linear_map.snd` - `linear_map.coprod` - `linear_map.prod_ext` - products in the codomain: - `linear_map.inl` - `linear_map.inr` - `linear_map.prod` - products in both domain and codomain: - `linear_map.prod_map` - `linear_equiv.prod_map` - `linear_equiv.skew_prod` -/ universes u v w x y z u' v' w' y' variables {R : Type u} {K : Type u'} {M : Type v} {V : Type v'} {M₂ : Type w} {V₂ : Type w'} variables {M₃ : Type y} {V₃ : Type y'} {M₄ : Type z} {ι : Type x} variables {M₅ M₆ : Type*} section prod namespace linear_map variables (S : Type*) [semiring R] [semiring S] variables [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] [add_comm_monoid M₄] variables [add_comm_monoid M₅] [add_comm_monoid M₆] variables [module R M] [module R M₂] [module R M₃] [module R M₄] variables [module R M₅] [module R M₆] variables (f : M →ₗ[R] M₂) section variables (R M M₂) /-- The first projection of a product is a linear map. -/ def fst : M × M₂ →ₗ[R] M := { to_fun := prod.fst, map_add' := λ x y, rfl, map_smul' := λ x y, rfl } /-- The second projection of a product is a linear map. -/ def snd : M × M₂ →ₗ[R] M₂ := { to_fun := prod.snd, map_add' := λ x y, rfl, map_smul' := λ x y, rfl } end @[simp] theorem fst_apply (x : M × M₂) : fst R M M₂ x = x.1 := rfl @[simp] theorem snd_apply (x : M × M₂) : snd R M M₂ x = x.2 := rfl theorem fst_surjective : function.surjective (fst R M M₂) := λ x, ⟨(x, 0), rfl⟩ theorem snd_surjective : function.surjective (snd R M M₂) := λ x, ⟨(0, x), rfl⟩ /-- The prod of two linear maps is a linear map. -/ @[simps] def prod (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) : (M →ₗ[R] M₂ × M₃) := { to_fun := pi.prod f g, map_add' := λ x y, by simp only [pi.prod, prod.mk_add_mk, map_add], map_smul' := λ c x, by simp only [pi.prod, prod.smul_mk, map_smul, ring_hom.id_apply] } lemma coe_prod (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) : ⇑(f.prod g) = pi.prod f g := rfl @[simp] theorem fst_prod (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) : (fst R M₂ M₃).comp (prod f g) = f := by ext; refl @[simp] theorem snd_prod (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) : (snd R M₂ M₃).comp (prod f g) = g := by ext; refl @[simp] theorem pair_fst_snd : prod (fst R M M₂) (snd R M M₂) = linear_map.id := fun_like.coe_injective pi.prod_fst_snd /-- Taking the product of two maps with the same domain is equivalent to taking the product of their codomains. See note [bundled maps over different rings] for why separate `R` and `S` semirings are used. -/ @[simps] def prod_equiv [module S M₂] [module S M₃] [smul_comm_class R S M₂] [smul_comm_class R S M₃] : ((M →ₗ[R] M₂) × (M →ₗ[R] M₃)) ≃ₗ[S] (M →ₗ[R] M₂ × M₃) := { to_fun := λ f, f.1.prod f.2, inv_fun := λ f, ((fst _ _ _).comp f, (snd _ _ _).comp f), left_inv := λ f, by ext; refl, right_inv := λ f, by ext; refl, map_add' := λ a b, rfl, map_smul' := λ r a, rfl } section variables (R M M₂) /-- The left injection into a product is a linear map. -/ def inl : M →ₗ[R] M × M₂ := prod linear_map.id 0 /-- The right injection into a product is a linear map. -/ def inr : M₂ →ₗ[R] M × M₂ := prod 0 linear_map.id theorem range_inl : range (inl R M M₂) = ker (snd R M M₂) := begin ext x, simp only [mem_ker, mem_range], split, { rintros ⟨y, rfl⟩, refl }, { intro h, exact ⟨x.fst, prod.ext rfl h.symm⟩ } end theorem ker_snd : ker (snd R M M₂) = range (inl R M M₂) := eq.symm $ range_inl R M M₂ theorem range_inr : range (inr R M M₂) = ker (fst R M M₂) := begin ext x, simp only [mem_ker, mem_range], split, { rintros ⟨y, rfl⟩, refl }, { intro h, exact ⟨x.snd, prod.ext h.symm rfl⟩ } end theorem ker_fst : ker (fst R M M₂) = range (inr R M M₂) := eq.symm $ range_inr R M M₂ end @[simp] theorem coe_inl : (inl R M M₂ : M → M × M₂) = λ x, (x, 0) := rfl theorem inl_apply (x : M) : inl R M M₂ x = (x, 0) := rfl @[simp] theorem coe_inr : (inr R M M₂ : M₂ → M × M₂) = prod.mk 0 := rfl theorem inr_apply (x : M₂) : inr R M M₂ x = (0, x) := rfl theorem inl_eq_prod : inl R M M₂ = prod linear_map.id 0 := rfl theorem inr_eq_prod : inr R M M₂ = prod 0 linear_map.id := rfl theorem inl_injective : function.injective (inl R M M₂) := λ _, by simp theorem inr_injective : function.injective (inr R M M₂) := λ _, by simp /-- The coprod function `λ x : M × M₂, f x.1 + g x.2` is a linear map. -/ def coprod (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) : M × M₂ →ₗ[R] M₃ := f.comp (fst _ _ _) + g.comp (snd _ _ _) @[simp] theorem coprod_apply (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) (x : M × M₂) : coprod f g x = f x.1 + g x.2 := rfl @[simp] theorem coprod_inl (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) : (coprod f g).comp (inl R M M₂) = f := by ext; simp only [map_zero, add_zero, coprod_apply, inl_apply, comp_apply] @[simp] theorem coprod_inr (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) : (coprod f g).comp (inr R M M₂) = g := by ext; simp only [map_zero, coprod_apply, inr_apply, zero_add, comp_apply] @[simp] theorem coprod_inl_inr : coprod (inl R M M₂) (inr R M M₂) = linear_map.id := by ext; simp only [prod.mk_add_mk, add_zero, id_apply, coprod_apply, inl_apply, inr_apply, zero_add] theorem comp_coprod (f : M₃ →ₗ[R] M₄) (g₁ : M →ₗ[R] M₃) (g₂ : M₂ →ₗ[R] M₃) : f.comp (g₁.coprod g₂) = (f.comp g₁).coprod (f.comp g₂) := ext $ λ x, f.map_add (g₁ x.1) (g₂ x.2) theorem fst_eq_coprod : fst R M M₂ = coprod linear_map.id 0 := by ext; simp theorem snd_eq_coprod : snd R M M₂ = coprod 0 linear_map.id := by ext; simp @[simp] theorem coprod_comp_prod (f : M₂ →ₗ[R] M₄) (g : M₃ →ₗ[R] M₄) (f' : M →ₗ[R] M₂) (g' : M →ₗ[R] M₃) : (f.coprod g).comp (f'.prod g') = f.comp f' + g.comp g' := rfl @[simp] lemma coprod_map_prod (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) (S : submodule R M) (S' : submodule R M₂) : (submodule.prod S S').map (linear_map.coprod f g) = S.map f ⊔ S'.map g := set_like.coe_injective $ begin simp only [linear_map.coprod_apply, submodule.coe_sup, submodule.map_coe], rw [←set.image2_add, set.image2_image_left, set.image2_image_right], exact set.image_prod (λ m m₂, f m + g m₂), end /-- Taking the product of two maps with the same codomain is equivalent to taking the product of their domains. See note [bundled maps over different rings] for why separate `R` and `S` semirings are used. -/ @[simps] def coprod_equiv [module S M₃] [smul_comm_class R S M₃] : ((M →ₗ[R] M₃) × (M₂ →ₗ[R] M₃)) ≃ₗ[S] (M × M₂ →ₗ[R] M₃) := { to_fun := λ f, f.1.coprod f.2, inv_fun := λ f, (f.comp (inl _ _ _), f.comp (inr _ _ _)), left_inv := λ f, by simp only [prod.mk.eta, coprod_inl, coprod_inr], right_inv := λ f, by simp only [←comp_coprod, comp_id, coprod_inl_inr], map_add' := λ a b, by { ext, simp only [prod.snd_add, add_apply, coprod_apply, prod.fst_add, add_add_add_comm] }, map_smul' := λ r a, by { dsimp, ext, simp only [smul_add, smul_apply, prod.smul_snd, prod.smul_fst, coprod_apply] } } theorem prod_ext_iff {f g : M × M₂ →ₗ[R] M₃} : f = g ↔ f.comp (inl _ _ _) = g.comp (inl _ _ _) ∧ f.comp (inr _ _ _) = g.comp (inr _ _ _) := (coprod_equiv ℕ).symm.injective.eq_iff.symm.trans prod.ext_iff /-- Split equality of linear maps from a product into linear maps over each component, to allow `ext` to apply lemmas specific to `M →ₗ M₃` and `M₂ →ₗ M₃`. See note [partially-applied ext lemmas]. -/ @[ext] theorem prod_ext {f g : M × M₂ →ₗ[R] M₃} (hl : f.comp (inl _ _ _) = g.comp (inl _ _ _)) (hr : f.comp (inr _ _ _) = g.comp (inr _ _ _)) : f = g := prod_ext_iff.2 ⟨hl, hr⟩ /-- `prod.map` of two linear maps. -/ def prod_map (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₄) : (M × M₂) →ₗ[R] (M₃ × M₄) := (f.comp (fst R M M₂)).prod (g.comp (snd R M M₂)) @[simp] theorem prod_map_apply (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₄) (x) : f.prod_map g x = (f x.1, g x.2) := rfl lemma prod_map_comap_prod (f : M →ₗ[R] M₂) (g : M₃ →ₗ[R] M₄) (S : submodule R M₂) (S' : submodule R M₄) : (submodule.prod S S').comap (linear_map.prod_map f g) = (S.comap f).prod (S'.comap g) := set_like.coe_injective $ set.preimage_prod_map_prod f g _ _ lemma ker_prod_map (f : M →ₗ[R] M₂) (g : M₃ →ₗ[R] M₄) : (linear_map.prod_map f g).ker = submodule.prod f.ker g.ker := begin dsimp only [ker], rw [←prod_map_comap_prod, submodule.prod_bot], end @[simp] lemma prod_map_id : (id : M →ₗ[R] M).prod_map (id : M₂ →ₗ[R] M₂) = id := linear_map.ext $ λ _, prod.mk.eta @[simp] lemma prod_map_one : (1 : M →ₗ[R] M).prod_map (1 : M₂ →ₗ[R] M₂) = 1 := linear_map.ext $ λ _, prod.mk.eta lemma prod_map_comp (f₁₂ : M →ₗ[R] M₂) (f₂₃ : M₂ →ₗ[R] M₃) (g₁₂ : M₄ →ₗ[R] M₅) (g₂₃ : M₅ →ₗ[R] M₆) : f₂₃.prod_map g₂₃ ∘ₗ f₁₂.prod_map g₁₂ = (f₂₃ ∘ₗ f₁₂).prod_map (g₂₃ ∘ₗ g₁₂) := rfl lemma prod_map_mul (f₁₂ : M →ₗ[R] M) (f₂₃ : M →ₗ[R] M) (g₁₂ : M₂ →ₗ[R] M₂) (g₂₃ : M₂ →ₗ[R] M₂) : f₂₃.prod_map g₂₃ * f₁₂.prod_map g₁₂ = (f₂₃ * f₁₂).prod_map (g₂₃ * g₁₂) := rfl lemma prod_map_add (f₁ : M →ₗ[R] M₃) (f₂ : M →ₗ[R] M₃) (g₁ : M₂ →ₗ[R] M₄) (g₂ : M₂ →ₗ[R] M₄) : (f₁ + f₂).prod_map (g₁ + g₂) = f₁.prod_map g₁ + f₂.prod_map g₂ := rfl @[simp] lemma prod_map_zero : (0 : M →ₗ[R] M₂).prod_map (0 : M₃ →ₗ[R] M₄) = 0 := rfl @[simp] lemma prod_map_smul [module S M₃] [module S M₄] [smul_comm_class R S M₃] [smul_comm_class R S M₄] (s : S) (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₄) : prod_map (s • f) (s • g) = s • prod_map f g := rfl variables (R M M₂ M₃ M₄) /-- `linear_map.prod_map` as a `linear_map` -/ @[simps] def prod_map_linear [module S M₃] [module S M₄] [smul_comm_class R S M₃] [smul_comm_class R S M₄] : ((M →ₗ[R] M₃) × (M₂ →ₗ[R] M₄)) →ₗ[S] ((M × M₂) →ₗ[R] (M₃ × M₄)) := { to_fun := λ f, prod_map f.1 f.2, map_add' := λ _ _, rfl, map_smul' := λ _ _, rfl} /-- `linear_map.prod_map` as a `ring_hom` -/ @[simps] def prod_map_ring_hom : (M →ₗ[R] M) × (M₂ →ₗ[R] M₂) →+* ((M × M₂) →ₗ[R] (M × M₂)) := { to_fun := λ f, prod_map f.1 f.2, map_one' := prod_map_one, map_zero' := rfl, map_add' := λ _ _, rfl, map_mul' := λ _ _, rfl } variables {R M M₂ M₃ M₄} section map_mul variables {A : Type*} [non_unital_non_assoc_semiring A] [module R A] variables {B : Type*} [non_unital_non_assoc_semiring B] [module R B] lemma inl_map_mul (a₁ a₂ : A) : linear_map.inl R A B (a₁ * a₂) = linear_map.inl R A B a₁ * linear_map.inl R A B a₂ := prod.ext rfl (by simp) lemma inr_map_mul (b₁ b₂ : B) : linear_map.inr R A B (b₁ * b₂) = linear_map.inr R A B b₁ * linear_map.inr R A B b₂ := prod.ext (by simp) rfl end map_mul end linear_map end prod namespace linear_map variables (R M M₂) variables [comm_semiring R] variables [add_comm_monoid M] [add_comm_monoid M₂] variables [module R M] [module R M₂] /-- `linear_map.prod_map` as an `algebra_hom` -/ @[simps] def prod_map_alg_hom : (module.End R M) × (module.End R M₂) →ₐ[R] module.End R (M × M₂) := { commutes' := λ _, rfl, ..prod_map_ring_hom R M M₂ } end linear_map namespace linear_map open submodule variables [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] [add_comm_monoid M₄] [module R M] [module R M₂] [module R M₃] [module R M₄] lemma range_coprod (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) : (f.coprod g).range = f.range ⊔ g.range := submodule.ext $ λ x, by simp [mem_sup] lemma is_compl_range_inl_inr : is_compl (inl R M M₂).range (inr R M M₂).range := begin split, { rintros ⟨_, _⟩ ⟨⟨x, hx⟩, ⟨y, hy⟩⟩, simp only [prod.ext_iff, inl_apply, inr_apply, mem_bot] at hx hy ⊢, exact ⟨hy.1.symm, hx.2.symm⟩ }, { rintros ⟨x, y⟩ -, simp only [mem_sup, mem_range, exists_prop], refine ⟨(x, 0), ⟨x, rfl⟩, (0, y), ⟨y, rfl⟩, _⟩, simp } end lemma sup_range_inl_inr : (inl R M M₂).range ⊔ (inr R M M₂).range = ⊤ := is_compl_range_inl_inr.sup_eq_top lemma disjoint_inl_inr : disjoint (inl R M M₂).range (inr R M M₂).range := by simp [disjoint_def, @eq_comm M 0, @eq_comm M₂ 0] {contextual := tt}; intros; refl theorem map_coprod_prod (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) (p : submodule R M) (q : submodule R M₂) : map (coprod f g) (p.prod q) = map f p ⊔ map g q := begin refine le_antisymm _ (sup_le (map_le_iff_le_comap.2 _) (map_le_iff_le_comap.2 _)), { rw set_like.le_def, rintro _ ⟨x, ⟨h₁, h₂⟩, rfl⟩, exact mem_sup.2 ⟨_, ⟨_, h₁, rfl⟩, _, ⟨_, h₂, rfl⟩, rfl⟩ }, { exact λ x hx, ⟨(x, 0), by simp [hx]⟩ }, { exact λ x hx, ⟨(0, x), by simp [hx]⟩ } end theorem comap_prod_prod (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) (p : submodule R M₂) (q : submodule R M₃) : comap (prod f g) (p.prod q) = comap f p ⊓ comap g q := submodule.ext $ λ x, iff.rfl theorem prod_eq_inf_comap (p : submodule R M) (q : submodule R M₂) : p.prod q = p.comap (linear_map.fst R M M₂) ⊓ q.comap (linear_map.snd R M M₂) := submodule.ext $ λ x, iff.rfl theorem prod_eq_sup_map (p : submodule R M) (q : submodule R M₂) : p.prod q = p.map (linear_map.inl R M M₂) ⊔ q.map (linear_map.inr R M M₂) := by rw [← map_coprod_prod, coprod_inl_inr, map_id] lemma span_inl_union_inr {s : set M} {t : set M₂} : span R (inl R M M₂ '' s ∪ inr R M M₂ '' t) = (span R s).prod (span R t) := by rw [span_union, prod_eq_sup_map, ← span_image, ← span_image] @[simp] lemma ker_prod (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) : ker (prod f g) = ker f ⊓ ker g := by rw [ker, ← prod_bot, comap_prod_prod]; refl lemma range_prod_le (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) : range (prod f g) ≤ (range f).prod (range g) := begin simp only [set_like.le_def, prod_apply, mem_range, set_like.mem_coe, mem_prod, exists_imp_distrib], rintro _ x rfl, exact ⟨⟨x, rfl⟩, ⟨x, rfl⟩⟩ end lemma ker_prod_ker_le_ker_coprod {M₂ : Type*} [add_comm_group M₂] [module R M₂] {M₃ : Type*} [add_comm_group M₃] [module R M₃] (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) : (ker f).prod (ker g) ≤ ker (f.coprod g) := by { rintros ⟨y, z⟩, simp {contextual := tt} } lemma ker_coprod_of_disjoint_range {M₂ : Type*} [add_comm_group M₂] [module R M₂] {M₃ : Type*} [add_comm_group M₃] [module R M₃] (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) (hd : disjoint f.range g.range) : ker (f.coprod g) = (ker f).prod (ker g) := begin apply le_antisymm _ (ker_prod_ker_le_ker_coprod f g), rintros ⟨y, z⟩ h, simp only [mem_ker, mem_prod, coprod_apply] at h ⊢, have : f y ∈ f.range ⊓ g.range, { simp only [true_and, mem_range, mem_inf, exists_apply_eq_apply], use -z, rwa [eq_comm, map_neg, ← sub_eq_zero, sub_neg_eq_add] }, rw [hd.eq_bot, mem_bot] at this, rw [this] at h, simpa [this] using h, end end linear_map namespace submodule open linear_map variables [semiring R] variables [add_comm_monoid M] [add_comm_monoid M₂] variables [module R M] [module R M₂] lemma sup_eq_range (p q : submodule R M) : p ⊔ q = (p.subtype.coprod q.subtype).range := submodule.ext $ λ x, by simp [submodule.mem_sup, set_like.exists] variables (p : submodule R M) (q : submodule R M₂) @[simp] theorem map_inl : p.map (inl R M M₂) = prod p ⊥ := by { ext ⟨x, y⟩, simp only [and.left_comm, eq_comm, mem_map, prod.mk.inj_iff, inl_apply, mem_bot, exists_eq_left', mem_prod] } @[simp] theorem map_inr : q.map (inr R M M₂) = prod ⊥ q := by ext ⟨x, y⟩; simp [and.left_comm, eq_comm] @[simp] theorem comap_fst : p.comap (fst R M M₂) = prod p ⊤ := by ext ⟨x, y⟩; simp @[simp] theorem comap_snd : q.comap (snd R M M₂) = prod ⊤ q := by ext ⟨x, y⟩; simp @[simp] theorem prod_comap_inl : (prod p q).comap (inl R M M₂) = p := by ext; simp @[simp] theorem prod_comap_inr : (prod p q).comap (inr R M M₂) = q := by ext; simp @[simp] theorem prod_map_fst : (prod p q).map (fst R M M₂) = p := by ext x; simp [(⟨0, zero_mem _⟩ : ∃ x, x ∈ q)] @[simp] theorem prod_map_snd : (prod p q).map (snd R M M₂) = q := by ext x; simp [(⟨0, zero_mem _⟩ : ∃ x, x ∈ p)] @[simp] theorem ker_inl : (inl R M M₂).ker = ⊥ := by rw [ker, ← prod_bot, prod_comap_inl] @[simp] theorem ker_inr : (inr R M M₂).ker = ⊥ := by rw [ker, ← prod_bot, prod_comap_inr] @[simp] theorem range_fst : (fst R M M₂).range = ⊤ := by rw [range_eq_map, ← prod_top, prod_map_fst] @[simp] theorem range_snd : (snd R M M₂).range = ⊤ := by rw [range_eq_map, ← prod_top, prod_map_snd] variables (R M M₂) /-- `M` as a submodule of `M × N`. -/ def fst : submodule R (M × M₂) := (⊥ : submodule R M₂).comap (linear_map.snd R M M₂) /-- `M` as a submodule of `M × N` is isomorphic to `M`. -/ @[simps] def fst_equiv : submodule.fst R M M₂ ≃ₗ[R] M := { to_fun := λ x, x.1.1, inv_fun := λ m, ⟨⟨m, 0⟩, by tidy⟩, map_add' := by simp, map_smul' := by simp, left_inv := by tidy, right_inv := by tidy, } lemma fst_map_fst : (submodule.fst R M M₂).map (linear_map.fst R M M₂) = ⊤ := by tidy lemma fst_map_snd : (submodule.fst R M M₂).map (linear_map.snd R M M₂) = ⊥ := by { tidy, exact 0, } /-- `N` as a submodule of `M × N`. -/ def snd : submodule R (M × M₂) := (⊥ : submodule R M).comap (linear_map.fst R M M₂) /-- `N` as a submodule of `M × N` is isomorphic to `N`. -/ @[simps] def snd_equiv : submodule.snd R M M₂ ≃ₗ[R] M₂ := { to_fun := λ x, x.1.2, inv_fun := λ n, ⟨⟨0, n⟩, by tidy⟩, map_add' := by simp, map_smul' := by simp, left_inv := by tidy, right_inv := by tidy, } lemma snd_map_fst : (submodule.snd R M M₂).map (linear_map.fst R M M₂) = ⊥ := by { tidy, exact 0, } lemma snd_map_snd : (submodule.snd R M M₂).map (linear_map.snd R M M₂) = ⊤ := by tidy lemma fst_sup_snd : submodule.fst R M M₂ ⊔ submodule.snd R M M₂ = ⊤ := begin rw eq_top_iff, rintro ⟨m, n⟩ -, rw [show (m, n) = (m, 0) + (0, n), by simp], apply submodule.add_mem (submodule.fst R M M₂ ⊔ submodule.snd R M M₂), { exact submodule.mem_sup_left (submodule.mem_comap.mpr (by simp)), }, { exact submodule.mem_sup_right (submodule.mem_comap.mpr (by simp)), }, end lemma fst_inf_snd : submodule.fst R M M₂ ⊓ submodule.snd R M M₂ = ⊥ := by tidy lemma le_prod_iff {p₁ : submodule R M} {p₂ : submodule R M₂} {q : submodule R (M × M₂)} : q ≤ p₁.prod p₂ ↔ map (linear_map.fst R M M₂) q ≤ p₁ ∧ map (linear_map.snd R M M₂) q ≤ p₂ := begin split, { intros h, split, { rintros x ⟨⟨y1,y2⟩, ⟨hy1,rfl⟩⟩, exact (h hy1).1 }, { rintros x ⟨⟨y1,y2⟩, ⟨hy1,rfl⟩⟩, exact (h hy1).2 }, }, { rintros ⟨hH, hK⟩ ⟨x1, x2⟩ h, exact ⟨hH ⟨_ , h, rfl⟩, hK ⟨ _, h, rfl⟩⟩, } end lemma prod_le_iff {p₁ : submodule R M} {p₂ : submodule R M₂} {q : submodule R (M × M₂)} : p₁.prod p₂ ≤ q ↔ map (linear_map.inl R M M₂) p₁ ≤ q ∧ map (linear_map.inr R M M₂) p₂ ≤ q := begin split, { intros h, split, { rintros _ ⟨x, hx, rfl⟩, apply h, exact ⟨hx, zero_mem p₂⟩, }, { rintros _ ⟨x, hx, rfl⟩, apply h, exact ⟨zero_mem p₁, hx⟩, }, }, { rintros ⟨hH, hK⟩ ⟨x1, x2⟩ ⟨h1, h2⟩, have h1' : (linear_map.inl R _ _) x1 ∈ q, { apply hH, simpa using h1, }, have h2' : (linear_map.inr R _ _) x2 ∈ q, { apply hK, simpa using h2, }, simpa using add_mem h1' h2', } end lemma prod_eq_bot_iff {p₁ : submodule R M} {p₂ : submodule R M₂} : p₁.prod p₂ = ⊥ ↔ p₁ = ⊥ ∧ p₂ = ⊥ := by simp only [eq_bot_iff, prod_le_iff, (gc_map_comap _).le_iff_le, comap_bot, ker_inl, ker_inr] lemma prod_eq_top_iff {p₁ : submodule R M} {p₂ : submodule R M₂} : p₁.prod p₂ = ⊤ ↔ p₁ = ⊤ ∧ p₂ = ⊤ := by simp only [eq_top_iff, le_prod_iff, ← (gc_map_comap _).le_iff_le, map_top, range_fst, range_snd] end submodule namespace linear_equiv /-- Product of modules is commutative up to linear isomorphism. -/ @[simps apply] def prod_comm (R M N : Type*) [semiring R] [add_comm_monoid M] [add_comm_monoid N] [module R M] [module R N] : (M × N) ≃ₗ[R] (N × M) := { to_fun := prod.swap, map_smul' := λ r ⟨m, n⟩, rfl, ..add_equiv.prod_comm } section variables [semiring R] variables [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] [add_comm_monoid M₄] variables {module_M : module R M} {module_M₂ : module R M₂} variables {module_M₃ : module R M₃} {module_M₄ : module R M₄} variables (e₁ : M ≃ₗ[R] M₂) (e₂ : M₃ ≃ₗ[R] M₄) /-- Product of linear equivalences; the maps come from `equiv.prod_congr`. -/ protected def prod : (M × M₃) ≃ₗ[R] (M₂ × M₄) := { map_smul' := λ c x, prod.ext (e₁.map_smulₛₗ c _) (e₂.map_smulₛₗ c _), .. e₁.to_add_equiv.prod_congr e₂.to_add_equiv } lemma prod_symm : (e₁.prod e₂).symm = e₁.symm.prod e₂.symm := rfl @[simp] lemma prod_apply (p) : e₁.prod e₂ p = (e₁ p.1, e₂ p.2) := rfl @[simp, norm_cast] lemma coe_prod : (e₁.prod e₂ : (M × M₃) →ₗ[R] (M₂ × M₄)) = (e₁ : M →ₗ[R] M₂).prod_map (e₂ : M₃ →ₗ[R] M₄) := rfl end section variables [semiring R] variables [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] [add_comm_group M₄] variables {module_M : module R M} {module_M₂ : module R M₂} variables {module_M₃ : module R M₃} {module_M₄ : module R M₄} variables (e₁ : M ≃ₗ[R] M₂) (e₂ : M₃ ≃ₗ[R] M₄) /-- Equivalence given by a block lower diagonal matrix. `e₁` and `e₂` are diagonal square blocks, and `f` is a rectangular block below the diagonal. -/ protected def skew_prod (f : M →ₗ[R] M₄) : (M × M₃) ≃ₗ[R] M₂ × M₄ := { inv_fun := λ p : M₂ × M₄, (e₁.symm p.1, e₂.symm (p.2 - f (e₁.symm p.1))), left_inv := λ p, by simp, right_inv := λ p, by simp, .. ((e₁ : M →ₗ[R] M₂).comp (linear_map.fst R M M₃)).prod ((e₂ : M₃ →ₗ[R] M₄).comp (linear_map.snd R M M₃) + f.comp (linear_map.fst R M M₃)) } @[simp] lemma skew_prod_apply (f : M →ₗ[R] M₄) (x) : e₁.skew_prod e₂ f x = (e₁ x.1, e₂ x.2 + f x.1) := rfl @[simp] lemma skew_prod_symm_apply (f : M →ₗ[R] M₄) (x) : (e₁.skew_prod e₂ f).symm x = (e₁.symm x.1, e₂.symm (x.2 - f (e₁.symm x.1))) := rfl end end linear_equiv namespace linear_map open submodule variables [ring R] variables [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [module R M] [module R M₂] [module R M₃] /-- If the union of the kernels `ker f` and `ker g` spans the domain, then the range of `prod f g` is equal to the product of `range f` and `range g`. -/ lemma range_prod_eq {f : M →ₗ[R] M₂} {g : M →ₗ[R] M₃} (h : ker f ⊔ ker g = ⊤) : range (prod f g) = (range f).prod (range g) := begin refine le_antisymm (f.range_prod_le g) _, simp only [set_like.le_def, prod_apply, mem_range, set_like.mem_coe, mem_prod, exists_imp_distrib, and_imp, prod.forall, pi.prod], rintros _ _ x rfl y rfl, simp only [prod.mk.inj_iff, ← sub_mem_ker_iff], have : y - x ∈ ker f ⊔ ker g, { simp only [h, mem_top] }, rcases mem_sup.1 this with ⟨x', hx', y', hy', H⟩, refine ⟨x' + x, _, _⟩, { rwa add_sub_cancel }, { rwa [← eq_sub_iff_add_eq.1 H, add_sub_add_right_eq_sub, ← neg_mem_iff, neg_sub, add_sub_cancel'] } end end linear_map namespace linear_map /-! ## Tunnels and tailings Some preliminary work for establishing the strong rank condition for noetherian rings. Given a morphism `f : M × N →ₗ[R] M` which is `i : injective f`, we can find an infinite decreasing `tunnel f i n` of copies of `M` inside `M`, and sitting beside these, an infinite sequence of copies of `N`. We picturesquely name these as `tailing f i n` for each individual copy of `N`, and `tailings f i n` for the supremum of the first `n+1` copies: they are the pieces left behind, sitting inside the tunnel. By construction, each `tailing f i (n+1)` is disjoint from `tailings f i n`; later, when we assume `M` is noetherian, this implies that `N` must be trivial, and establishes the strong rank condition for any left-noetherian ring. -/ section tunnel -- (This doesn't work over a semiring: we need to use that `submodule R M` is a modular lattice, -- which requires cancellation.) variables [ring R] variables {N : Type*} [add_comm_group M] [module R M] [add_comm_group N] [module R N] open function /-- An auxiliary construction for `tunnel`. The composition of `f`, followed by the isomorphism back to `K`, followed by the inclusion of this submodule back into `M`. -/ def tunnel_aux (f : M × N →ₗ[R] M) (Kφ : Σ K : submodule R M, K ≃ₗ[R] M) : M × N →ₗ[R] M := (Kφ.1.subtype.comp Kφ.2.symm.to_linear_map).comp f lemma tunnel_aux_injective (f : M × N →ₗ[R] M) (i : injective f) (Kφ : Σ K : submodule R M, K ≃ₗ[R] M) : injective (tunnel_aux f Kφ) := (subtype.val_injective.comp Kφ.2.symm.injective).comp i noncomputable theory /-- Auxiliary definition for `tunnel`. -/ -- Even though we have `noncomputable theory`, -- we get an error without another `noncomputable` here. noncomputable def tunnel' (f : M × N →ₗ[R] M) (i : injective f) : ℕ → Σ (K : submodule R M), K ≃ₗ[R] M | 0 := ⟨⊤, linear_equiv.of_top ⊤ rfl⟩ | (n+1) := ⟨(submodule.fst R M N).map (tunnel_aux f (tunnel' n)), ((submodule.fst R M N).equiv_map_of_injective _ (tunnel_aux_injective f i (tunnel' n))).symm.trans (submodule.fst_equiv R M N)⟩ /-- Give an injective map `f : M × N →ₗ[R] M` we can find a nested sequence of submodules all isomorphic to `M`. -/ def tunnel (f : M × N →ₗ[R] M) (i : injective f) : ℕ →o (submodule R M)ᵒᵈ := ⟨λ n, (tunnel' f i n).1, monotone_nat_of_le_succ (λ n, begin dsimp [tunnel', tunnel_aux], rw [submodule.map_comp, submodule.map_comp], apply submodule.map_subtype_le, end)⟩ /-- Give an injective map `f : M × N →ₗ[R] M` we can find a sequence of submodules all isomorphic to `N`. -/ def tailing (f : M × N →ₗ[R] M) (i : injective f) (n : ℕ) : submodule R M := (submodule.snd R M N).map (tunnel_aux f (tunnel' f i n)) /-- Each `tailing f i n` is a copy of `N`. -/ def tailing_linear_equiv (f : M × N →ₗ[R] M) (i : injective f) (n : ℕ) : tailing f i n ≃ₗ[R] N := ((submodule.snd R M N).equiv_map_of_injective _ (tunnel_aux_injective f i (tunnel' f i n))).symm.trans (submodule.snd_equiv R M N) lemma tailing_le_tunnel (f : M × N →ₗ[R] M) (i : injective f) (n : ℕ) : tailing f i n ≤ tunnel f i n := begin dsimp [tailing, tunnel_aux], rw [submodule.map_comp, submodule.map_comp], apply submodule.map_subtype_le, end lemma tailing_disjoint_tunnel_succ (f : M × N →ₗ[R] M) (i : injective f) (n : ℕ) : disjoint (tailing f i n) (tunnel f i (n+1)) := begin rw disjoint_iff, dsimp [tailing, tunnel, tunnel'], rw [submodule.map_inf_eq_map_inf_comap, submodule.comap_map_eq_of_injective (tunnel_aux_injective _ i _), inf_comm, submodule.fst_inf_snd, submodule.map_bot], end lemma tailing_sup_tunnel_succ_le_tunnel (f : M × N →ₗ[R] M) (i : injective f) (n : ℕ) : tailing f i n ⊔ tunnel f i (n+1) ≤ tunnel f i n := begin dsimp [tailing, tunnel, tunnel', tunnel_aux], rw [←submodule.map_sup, sup_comm, submodule.fst_sup_snd, submodule.map_comp, submodule.map_comp], apply submodule.map_subtype_le, end /-- The supremum of all the copies of `N` found inside the tunnel. -/ def tailings (f : M × N →ₗ[R] M) (i : injective f) : ℕ → submodule R M := partial_sups (tailing f i) @[simp] lemma tailings_zero (f : M × N →ₗ[R] M) (i : injective f) : tailings f i 0 = tailing f i 0 := by simp [tailings] @[simp] lemma tailings_succ (f : M × N →ₗ[R] M) (i : injective f) (n : ℕ) : tailings f i (n+1) = tailings f i n ⊔ tailing f i (n+1) := by simp [tailings] lemma tailings_disjoint_tunnel (f : M × N →ₗ[R] M) (i : injective f) (n : ℕ) : disjoint (tailings f i n) (tunnel f i (n+1)) := begin induction n with n ih, { simp only [tailings_zero], apply tailing_disjoint_tunnel_succ, }, { simp only [tailings_succ], refine disjoint.disjoint_sup_left_of_disjoint_sup_right _ _, apply tailing_disjoint_tunnel_succ, apply disjoint.mono_right _ ih, apply tailing_sup_tunnel_succ_le_tunnel, }, end lemma tailings_disjoint_tailing (f : M × N →ₗ[R] M) (i : injective f) (n : ℕ) : disjoint (tailings f i n) (tailing f i (n+1)) := disjoint.mono_right (tailing_le_tunnel f i _) (tailings_disjoint_tunnel f i _) end tunnel section graph variables [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_group M₃] [add_comm_group M₄] [module R M] [module R M₂] [module R M₃] [module R M₄] (f : M →ₗ[R] M₂) (g : M₃ →ₗ[R] M₄) /-- Graph of a linear map. -/ def graph : submodule R (M × M₂) := { carrier := {p | p.2 = f p.1}, add_mem' := λ a b (ha : _ = _) (hb : _ = _), begin change _ + _ = f (_ + _), rw [map_add, ha, hb] end, zero_mem' := eq.symm (map_zero f), smul_mem' := λ c x (hx : _ = _), begin change _ • _ = f (_ • _), rw [map_smul, hx] end } @[simp] lemma mem_graph_iff (x : M × M₂) : x ∈ f.graph ↔ x.2 = f x.1 := iff.rfl lemma graph_eq_ker_coprod : g.graph = ((-g).coprod linear_map.id).ker := begin ext x, change _ = _ ↔ -(g x.1) + x.2 = _, rw [add_comm, add_neg_eq_zero] end lemma graph_eq_range_prod : f.graph = (linear_map.id.prod f).range := begin ext x, exact ⟨λ hx, ⟨x.1, prod.ext rfl hx.symm⟩, λ ⟨u, hu⟩, hu ▸ rfl⟩ end end graph end linear_map
e8b1f3e96597ada7aa1f2b8ae3f0c97e97e3d923
1a61aba1b67cddccce19532a9596efe44be4285f
/library/init/setoid.lean
a253d90ee4dde59314bbbd433ab84c76a1eb8e12
[ "Apache-2.0" ]
permissive
eigengrau/lean
07986a0f2548688c13ba36231f6cdbee82abf4c6
f8a773be1112015e2d232661ce616d23f12874d0
refs/heads/master
1,610,939,198,566
1,441,352,386,000
1,441,352,494,000
41,903,576
0
0
null
1,441,352,210,000
1,441,352,210,000
null
UTF-8
Lean
false
false
738
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.relation structure setoid [class] (A : Type) := (r : A → A → Prop) (iseqv : equivalence r) namespace setoid infix `≈` := setoid.r variable {A : Type} variable [s : setoid A] include s theorem refl (a : A) : a ≈ a := and.elim_left (@setoid.iseqv A s) a theorem symm {a b : A} : a ≈ b → b ≈ a := λ H, and.elim_left (and.elim_right (@setoid.iseqv A s)) a b H theorem trans {a b c : A} : a ≈ b → b ≈ c → a ≈ c := λ H₁ H₂, and.elim_right (and.elim_right (@setoid.iseqv A s)) a b c H₁ H₂ end setoid
a040a68fceece0cbf4450c9026879e1a39e4bc5e
957a80ea22c5abb4f4670b250d55534d9db99108
/tests/lean/run/struct_value.lean
6046a0ab200cf1b0010281094bee36a3a226bb13
[ "Apache-2.0" ]
permissive
GaloisInc/lean
aa1e64d604051e602fcf4610061314b9a37ab8cd
f1ec117a24459b59c6ff9e56a1d09d9e9e60a6c0
refs/heads/master
1,592,202,909,807
1,504,624,387,000
1,504,624,387,000
75,319,626
2
1
Apache-2.0
1,539,290,164,000
1,480,616,104,000
C++
UTF-8
Lean
false
false
756
lean
#check { prod . fst := 10, snd := 20 } #check ({ fst := 10, snd := 20 } : nat × nat) definition p : nat × nat := { snd := 20, fst := 10 } #print p meta def attr : user_attribute := { name := `foo, descr := "hello world" } #print attr definition p2 := { p with fst := 20 } #print p2 structure point := (x : nat) (y : nat) structure point3d extends point := (z : nat) definition p1 : point := { x := 1, y := 1 } definition p3 : point3d := { p1 with z := 10 } #print p3 #check { point3d . x := 1, y := 2, z := 3 } #check (⟨10, rfl⟩ : Σ' x : nat, x = x) #check ((| 10, rfl |) : Σ' x : nat, x = x) #check ({ fst := 10, snd := rfl } : Σ' x : nat, x = x) definition f (a : nat) : Σ' x : nat, x = x := { fst := a, snd := rfl } #print f
a2ec13638e34acd2523c39d8634d3c66d6144669
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebra/divisibility/units.lean
6cd70984f1a41bf8e1370a40e493182a49207ec1
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
3,864
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura, Floris van Doorn, Amelia Livingston, Yury Kudryashov, Neil Strickland, Aaron Anderson -/ import algebra.divisibility.basic import algebra.group.units /-! # Lemmas about divisibility and units > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. -/ variables {α : Type*} namespace units section monoid variables [monoid α] {a b : α} {u : αˣ} /-- Elements of the unit group of a monoid represented as elements of the monoid divide any element of the monoid. -/ lemma coe_dvd : ↑u ∣ a := ⟨↑u⁻¹ * a, by simp⟩ /-- In a monoid, an element `a` divides an element `b` iff `a` divides all associates of `b`. -/ lemma dvd_mul_right : a ∣ b * u ↔ a ∣ b := iff.intro (assume ⟨c, eq⟩, ⟨c * ↑u⁻¹, by rw [← mul_assoc, ← eq, units.mul_inv_cancel_right]⟩) (assume ⟨c, eq⟩, eq.symm ▸ (dvd_mul_right _ _).mul_right _) /-- In a monoid, an element `a` divides an element `b` iff all associates of `a` divide `b`. -/ lemma mul_right_dvd : a * u ∣ b ↔ a ∣ b := iff.intro (λ ⟨c, eq⟩, ⟨↑u * c, eq.trans (mul_assoc _ _ _)⟩) (λ h, dvd_trans (dvd.intro ↑u⁻¹ (by rw [mul_assoc, u.mul_inv, mul_one])) h) end monoid section comm_monoid variables [comm_monoid α] {a b : α} {u : αˣ} /-- In a commutative monoid, an element `a` divides an element `b` iff `a` divides all left associates of `b`. -/ lemma dvd_mul_left : a ∣ u * b ↔ a ∣ b := by { rw mul_comm, apply dvd_mul_right } /-- In a commutative monoid, an element `a` divides an element `b` iff all left associates of `a` divide `b`.-/ lemma mul_left_dvd : ↑u * a ∣ b ↔ a ∣ b := by { rw mul_comm, apply mul_right_dvd } end comm_monoid end units namespace is_unit section monoid variables [monoid α] {a b u : α} (hu : is_unit u) include hu /-- Units of a monoid divide any element of the monoid. -/ @[simp] lemma dvd : u ∣ a := by { rcases hu with ⟨u, rfl⟩, apply units.coe_dvd, } @[simp] lemma dvd_mul_right : a ∣ b * u ↔ a ∣ b := by { rcases hu with ⟨u, rfl⟩, apply units.dvd_mul_right, } /-- In a monoid, an element a divides an element b iff all associates of `a` divide `b`.-/ @[simp] lemma mul_right_dvd : a * u ∣ b ↔ a ∣ b := by { rcases hu with ⟨u, rfl⟩, apply units.mul_right_dvd, } end monoid section comm_monoid variables [comm_monoid α] (a b u : α) (hu : is_unit u) include hu /-- In a commutative monoid, an element `a` divides an element `b` iff `a` divides all left associates of `b`. -/ @[simp] lemma dvd_mul_left : a ∣ u * b ↔ a ∣ b := by { rcases hu with ⟨u, rfl⟩, apply units.dvd_mul_left, } /-- In a commutative monoid, an element `a` divides an element `b` iff all left associates of `a` divide `b`.-/ @[simp] lemma mul_left_dvd : u * a ∣ b ↔ a ∣ b := by { rcases hu with ⟨u, rfl⟩, apply units.mul_left_dvd, } end comm_monoid end is_unit section comm_monoid variables [comm_monoid α] theorem is_unit_iff_dvd_one {x : α} : is_unit x ↔ x ∣ 1 := ⟨is_unit.dvd, λ ⟨y, h⟩, ⟨⟨x, y, h.symm, by rw [h, mul_comm]⟩, rfl⟩⟩ theorem is_unit_iff_forall_dvd {x : α} : is_unit x ↔ ∀ y, x ∣ y := is_unit_iff_dvd_one.trans ⟨λ h y, h.trans (one_dvd _), λ h, h _⟩ theorem is_unit_of_dvd_unit {x y : α} (xy : x ∣ y) (hu : is_unit y) : is_unit x := is_unit_iff_dvd_one.2 $ xy.trans $ is_unit_iff_dvd_one.1 hu lemma is_unit_of_dvd_one : ∀a ∣ 1, is_unit (a:α) | a ⟨b, eq⟩ := ⟨units.mk_of_mul_eq_one a b eq.symm, rfl⟩ lemma not_is_unit_of_not_is_unit_dvd {a b : α} (ha : ¬is_unit a) (hb : a ∣ b) : ¬ is_unit b := mt (is_unit_of_dvd_unit hb) ha end comm_monoid
f87c9a3f2ac7e2307285c9ce873f767edd23b6e5
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/polynomial/degree/lemmas.lean
658ae828537f2c1590795ad13e4f2f03358f3ce8
[]
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
3,734
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Johannes Hölzl, Scott Morrison, Jens Wagemaker -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.polynomial.eval import Mathlib.tactic.interval_cases import Mathlib.PostPort universes u v namespace Mathlib /-! # Theory of degrees of polynomials Some of the main results include - `nat_degree_comp_le` : The degree of the composition is at most the product of degrees -/ namespace polynomial theorem nat_degree_comp_le {R : Type u} [semiring R] {p : polynomial R} {q : polynomial R} : nat_degree (comp p q) ≤ nat_degree p * nat_degree q := sorry theorem degree_map_le {R : Type u} {S : Type v} [semiring R] {p : polynomial R} [semiring S] (f : R →+* S) : degree (map f p) ≤ degree p := sorry theorem nat_degree_map_le {R : Type u} {S : Type v} [semiring R] {p : polynomial R} [semiring S] (f : R →+* S) : nat_degree (map f p) ≤ nat_degree p := sorry theorem degree_map_eq_of_leading_coeff_ne_zero {R : Type u} {S : Type v} [semiring R] {p : polynomial R} [semiring S] (f : R →+* S) (hf : coe_fn f (leading_coeff p) ≠ 0) : degree (map f p) = degree p := sorry theorem nat_degree_map_of_leading_coeff_ne_zero {R : Type u} {S : Type v} [semiring R] {p : polynomial R} [semiring S] (f : R →+* S) (hf : coe_fn f (leading_coeff p) ≠ 0) : nat_degree (map f p) = nat_degree p := nat_degree_eq_of_degree_eq (degree_map_eq_of_leading_coeff_ne_zero f hf) theorem leading_coeff_map_of_leading_coeff_ne_zero {R : Type u} {S : Type v} [semiring R] {p : polynomial R} [semiring S] (f : R →+* S) (hf : coe_fn f (leading_coeff p) ≠ 0) : leading_coeff (map f p) = coe_fn f (leading_coeff p) := sorry theorem degree_pos_of_root {R : Type u} {a : R} [semiring R] {p : polynomial R} (hp : p ≠ 0) (h : is_root p a) : 0 < degree p := sorry theorem nat_degree_pos_of_eval₂_root {R : Type u} {S : Type v} [semiring R] [semiring S] {p : polynomial R} (hp : p ≠ 0) (f : R →+* S) {z : S} (hz : eval₂ f z p = 0) (inj : ∀ (x : R), coe_fn f x = 0 → x = 0) : 0 < nat_degree p := sorry theorem degree_pos_of_eval₂_root {R : Type u} {S : Type v} [semiring R] [semiring S] {p : polynomial R} (hp : p ≠ 0) (f : R →+* S) {z : S} (hz : eval₂ f z p = 0) (inj : ∀ (x : R), coe_fn f x = 0 → x = 0) : 0 < degree p := iff.mp nat_degree_pos_iff_degree_pos (nat_degree_pos_of_eval₂_root hp f hz inj) theorem degree_map_eq_of_injective {R : Type u} {S : Type v} [semiring R] [semiring S] {f : R →+* S} (hf : function.injective ⇑f) (p : polynomial R) : degree (map f p) = degree p := sorry theorem degree_map' {R : Type u} {S : Type v} [semiring R] [semiring S] {f : R →+* S} (hf : function.injective ⇑f) (p : polynomial R) : degree (map f p) = degree p := degree_map_eq_of_injective hf p theorem nat_degree_map' {R : Type u} {S : Type v} [semiring R] [semiring S] {f : R →+* S} (hf : function.injective ⇑f) (p : polynomial R) : nat_degree (map f p) = nat_degree p := nat_degree_eq_of_degree_eq (degree_map' hf p) theorem leading_coeff_map' {R : Type u} {S : Type v} [semiring R] [semiring S] {f : R →+* S} (hf : function.injective ⇑f) (p : polynomial R) : leading_coeff (map f p) = coe_fn f (leading_coeff p) := sorry theorem monomial_nat_degree_leading_coeff_eq_self {R : Type u} [semiring R] {f : polynomial R} (h : finset.card (finsupp.support f) ≤ 1) : coe_fn (monomial (nat_degree f)) (leading_coeff f) = f := sorry theorem C_mul_X_pow_eq_self {R : Type u} [semiring R] {f : polynomial R} (h : finset.card (finsupp.support f) ≤ 1) : coe_fn C (leading_coeff f) * X ^ nat_degree f = f := sorry
4a1fbd76d8cdc7b39e78d4f0a45289cf985de6ad
4f643cce24b2d005aeeb5004c2316a8d6cc7f3b1
/src/for_mathlib/finvec.lean
0aee8894a77eea9c58ff9e15d27be2e5c56557dd
[]
no_license
rwbarton/lean-omin
da209ed061d64db65a8f7f71f198064986f30eb9
fd733c6d95ef6f4743aae97de5e15df79877c00e
refs/heads/master
1,674,408,673,325
1,607,343,535,000
1,607,343,535,000
285,150,399
9
0
null
null
null
null
UTF-8
Lean
false
false
12,848
lean
import data.equiv.fin import for_mathlib.fin import tactic.abel import tactic.fin_cases /- Finite vectors, implemented as functions on `fin n`. The main advantage of `finvec` over alternatives like `vector` is that extracting coordinates (components) of a `finvec` is just function application, so it's easy to reason about things like permuting coordinates. -/ /-- A (homogeneous) "vector" of `n` `α`s, implemented as a function from `fin n`. The `j`th component of such a vector `x` (where `j : fin n`) is simply `x j`. -/ def finvec (n : ℕ) (α : Type*) : Type* := fin n → α namespace finvec variables {α : Type*} /-- Transport a vector across an equality of dimensions. This is implemented without using `eq.rec` so that it will reduce when evaluated at a constructor `⟨j, h : j < n'⟩` of `fin n'`. -/ protected def cast {n n' : ℕ} (h : n = n') : finvec n α → finvec n' α := λ x, x ∘ fin.cast h.symm @[simp] lemma cast_app {n n' : ℕ} {h : n = n'} {x : finvec n α} {j : fin n'} : (x.cast h) j = x (j.cast h.symm) := rfl @[simp] lemma cast_id {n : ℕ} {h : n = n} {x : finvec n α} : x.cast h = x := by { ext ⟨i, _⟩, refl } section set /-- Transport a set of vectors across an equality of dimensions. -/ protected def set.cast {n n' : ℕ} (h : n = n') : set (finvec n α) → set (finvec n' α) := λ s, s ∘ finvec.cast h.symm lemma set.cast_id {n : ℕ} : finvec.set.cast rfl = (id : set (finvec n α) → set (finvec n α)) := begin ext s x, change x.cast rfl ∈ s ↔ x ∈ s, rw cast_id end lemma set.heq_iff_cast_eq {n n' : ℕ} (h : n = n') {s : set (finvec n α)} {s' : set (finvec n' α)} : s == s' ↔ s = finvec.set.cast h.symm s' := begin cases h, rw [heq_iff_eq, set.cast_id], refl end end set instance : unique (finvec 0 α) := ⟨⟨fin_zero_elim⟩, by { intro x, ext i, fin_cases i }⟩ section prod /-! ### Products The isomorphism αⁿ⁺ᵐ ≅ αⁿ × αᵐ is ubiquitous in mathematics, and usually invoked implicitly. Lean maintains a distinction between the two sides of course. Here, we provide an API which presents `finvec (n+m) α` as though it were a structure with two fields `left : finvec n α` and `right : finvec m α`, with constructor `append : finvec n α → finvec m α → finvec (n+m) α`. The arguments `n m : ℕ` are implicit throughout this API, to be inferred from the argument or result types; this may seem problematic, since a number can be written in the form `n+m` in many ways, but actually works well in practice. -/ variables {n m : ℕ} /-- Project `αⁿ⁺ᵐ ≅ αⁿ × αᵐ` to the first factor. -/ protected def left : finvec (n + m) α → finvec n α := λ x, x ∘ fin.cast_add m /-- Project `αⁿ⁺ᵐ ≅ αⁿ × αᵐ` to the second factor. -/ protected def right : finvec (n + m) α → finvec m α := λ x, x ∘ fin.nat_add n /-- The canonical equivalence `αⁿ⁺ᵐ ≅ αⁿ × αᵐ`. -/ def append_equiv : finvec (n + m) α ≃ finvec n α × finvec m α := calc (fin (n + m) → α) ≃ (fin n ⊕ fin m → α) : equiv.arrow_congr sum_fin_sum_equiv.symm (equiv.refl _) ... ≃ (fin n → α) × (fin m → α) : (equiv.sum_arrow_equiv_prod_arrow (fin n) (fin m) α) /-- The concatenation of two vectors. -/ def append (x : finvec n α) (y : finvec m α) : finvec (n + m) α := append_equiv.symm (x, y) lemma append_equiv_app {z : finvec (n + m) α} : append_equiv z = (z.left, z.right) := rfl localized "infixr ` ++ ` := finvec.append" in finvec lemma append_equiv_symm_app {x : finvec n α} {y : finvec m α} : append_equiv.symm (x, y) = x ++ y := rfl @[simp] lemma left_append_right (x : finvec (n + m) α) : x.left ++ x.right = x := append_equiv.symm_apply_apply x /-- Induction principle for `finvec (n + m) α`, imagined as a structure containing its left and right parts. -/ @[elab_as_eliminator] protected lemma rec {C : finvec (n + m) α → Prop} (h : Π (x : finvec n α) (y : finvec m α), C (x ++ y)) (z : finvec (n + m) α) : C z := begin rw ←left_append_right z, apply h end @[simp] lemma left_append {x : finvec n α} {y : finvec m α} : (x ++ y).left = x := congr_arg prod.fst (append_equiv.apply_symm_apply (x, y) : _) @[simp] lemma right_append {x : finvec n α} {y : finvec m α} : (x ++ y).right = y := congr_arg prod.snd (append_equiv.apply_symm_apply (x, y) : _) lemma prod_ext {z z' : finvec (n + m) α} : z = z' ↔ z.left = z'.left ∧ z.right = z'.right := append_equiv.apply_eq_iff_eq.symm.trans prod.mk.inj_iff lemma append.inj_iff {x x' : finvec n α} {y y' : finvec m α} : x ++ y = x' ++ y' ↔ x = x' ∧ y = y' := by simp only [append, equiv.apply_eq_iff_eq, prod.mk.inj_iff] lemma left_zero {x : finvec (n + 0) α} : x.left = x := by { ext ⟨_, _⟩, refl } lemma right_zero {x : finvec (0 + n) α} : x.right = x.cast (zero_add n) := funext $ λ _, congr_arg x (by rw fin.nat_add_zero) @[simp] lemma append_zero {x : finvec n α} {y : finvec 0 α} : x ++ y = x := begin rw [prod_ext, left_append, left_zero, right_append], simp end /-- The product (in the sense of `set.prod`) of sets of vectors, under the isomorphism `αⁿ × αᵐ ≅ αⁿ⁺ᵐ`. -/ def prod (s : set (finvec n α)) (t : set (finvec m α)) : set (finvec (n + m) α) := {z | z.left ∈ s ∧ z.right ∈ t} localized "infixr ` ⊠ `:70 := finvec.prod" in finvec lemma mem_prod_iff {s : set (finvec n α)} {t : set (finvec m α)} (z : finvec (n + m) α) : z ∈ s ⊠ t ↔ z.left ∈ s ∧ z.right ∈ t := iff.rfl lemma append_mem_prod_iff {s : set (finvec n α)} {t : set (finvec m α)} {x : finvec n α} {y : finvec m α} : x ++ y ∈ s ⊠ t ↔ x ∈ s ∧ y ∈ t := begin convert mem_prod_iff (x ++ y), { rw left_append }, { rw right_append } end def prod_univ (s : set (finvec n α)) (m : ℕ) : set (finvec (n + m) α) := {z | z.left ∈ s} section variables (n) def univ_prod (n : ℕ) (t : set (finvec m α)) : set (finvec (n + m) α) := {z | z.right ∈ t} end lemma prod_univ_eq {s : set (finvec n α)} : prod_univ s m = s ⊠ (set.univ : set (finvec m α)) := by { ext, exact (and_true _).symm } lemma univ_prod_eq {t : set (finvec m α)} : univ_prod n t = (set.univ : set (finvec n α)) ⊠ t := by { ext, exact (true_and _).symm } lemma prod_eq_prod_univ_inter_univ_prod {s : set (finvec n α)} {t : set (finvec m α)} : s ⊠ t = prod_univ s m ∩ univ_prod n t := rfl @[simp] lemma append_mem_prod_univ_iff {s : set (finvec n α)} {x : finvec n α} {y : finvec m α} : x ++ y ∈ prod_univ s m ↔ x ∈ s := begin change (x ++ y).left ∈ s ↔ x ∈ s, rw left_append end @[simp] lemma append_mem_univ_prod_iff {t : set (finvec m α)} {x : finvec n α} {y : finvec m α} : x ++ y ∈ univ_prod n t ↔ y ∈ t := begin change (x ++ y).right ∈ t ↔ y ∈ t, rw right_append end -- Lemmas for inductively adding coordinates on the right. -- These lemma statements (and proof) take advantage of -- the definitional equalities `n + 0 = n`, `n + (m + 1) = (n + m) + 1`. lemma prod_univ_zero_eq {s : set (finvec n α)} : prod_univ s 0 = s := begin ext x, change x.left ∈ s ↔ x ∈ s, rw left_zero end lemma prod_univ_plus_one_eq {s : set (finvec n α)} : prod_univ s (m + 1) = (prod_univ (prod_univ s m) 1 : _) := begin ext x, change _ ∈ s ↔ _ ∈ s, refl end -- Lemmas for inductively adding coordinates on the left. -- For these lemmas we do not have corresponding definitional equalities -- so TODO lemma univ_prod_zero_like {ι : Sort*} (C : Π {l : ℕ}, set (finvec l α) → ι) {t : set (finvec m α)} : C (univ_prod 0 t) = C t := begin have : 0 + m = m := zero_add m, congr', rw set.heq_iff_cast_eq this, ext x, change x.right ∈ t ↔ x.cast _ ∈ t, rw right_zero end lemma univ_prod_plus_one_like {ι : Sort*} (C : Π {l : ℕ}, set (finvec l α) → ι) {t : set (finvec m α)} : C (univ_prod (n + 1) t) = C (univ_prod 1 (univ_prod n t)) := begin have : (n + 1) + m = 1 + (n + m) := by abel, congr' 1, { exact this }, rw set.heq_iff_cast_eq this, ext x, change x.right ∈ t ↔ (x.cast _).right.right ∈ t, congr' 2, ext ⟨i, h⟩, change x _ = x _, congr, ext, change (n + 1) + i = 1 + (n + i), abel end end prod /- -- TODO: is it useful to introduce this definition? -- use in `tame_of_def`, `tame_of_constrained` etc. def finvec_one_equiv_self {α : Type*} : finvec 1 α ≃ α := equiv.fun_unique (fin 1) α -/ section snoc -- TODO: for append notation; this is a bit ugly open_locale finvec /-! ### Appending a single element (snoc) This section is parallel to the section on products but based on the isomorphism αⁿ⁺¹ ≅ αⁿ × α. We name the projections `init : finvec (n+1) α → finvec n α` (which equals `left` specialized to `m = 1`) and `last : finvec (n+1) α → α`, with constructor `snoc : finvec n α → α → finvec (n+1) α`. -/ variables {n : ℕ} protected def init : finvec (n + 1) α → finvec n α := λ x, x ∘ fin.cast_succ lemma left_eq_init {x : finvec (n + 1) α} : x.left = x.init := rfl -- TODO: simp lemmas? see uses of `simp [finvec.last]` protected def last : finvec (n + 1) α → α := λ x, x (fin.last n) lemma right_eq_last {x : finvec (n + 1) α} : x.right = function.const (fin 1) x.last := begin ext i, fin_cases i, refl end /-- The canonical equivalence `αⁿ⁺¹ ≅ αⁿ × α`. -/ def snoc_equiv : finvec (n + 1) α ≃ finvec n α × α := calc (fin (n + 1) → α) ≃ (fin n → α) × (fin 1 → α) : append_equiv ... ≃ (fin n → α) × α : equiv.prod_congr (equiv.refl _) (equiv.fun_unique (fin 1) α) def snoc (x : finvec n α) (a : α) : finvec (n + 1) α := snoc_equiv.symm (x, a) lemma snoc_equiv_app {z : finvec (n + 1) α} : snoc_equiv z = (z.init, z.last) := rfl lemma snoc_equiv_symm_app {x : finvec n α} {a : α} : snoc_equiv.symm (x, a) = x.snoc a := rfl lemma init_snoc_last (x : finvec (n + 1) α) : x.init.snoc x.last = x := snoc_equiv.symm_apply_apply x /-- Induction principle for `finvec (n + 1) α`, imagined as a structure containing its initial part and last element. -/ @[elab_as_eliminator] protected lemma snoc_rec {C : finvec (n + 1) α → Prop} (h : Π (x : finvec n α) (a : α), C (snoc x a)) (z : finvec (n + 1) α) : C z := begin rw ←init_snoc_last z, apply h end @[simp] lemma init_snoc {x : finvec n α} {a : α} : (x.snoc a).init = x := congr_arg prod.fst (snoc_equiv.apply_symm_apply (x, a) : _) @[simp] lemma last_snoc {x : finvec n α} {a : α} : (x.snoc a).last = a := congr_arg prod.snd (snoc_equiv.apply_symm_apply (x, a) : _) lemma snoc.inj_iff {x x' : finvec n α} {a a' : α} : x.snoc a = x'.snoc a' ↔ x = x' ∧ a = a' := by simp only [snoc, equiv.apply_eq_iff_eq, prod.mk.inj_iff] -- TODO: rather than `function.const (fin 1)` -- should we use a specialized `finvec_one_equiv_self`? lemma snoc_eq_append {x : finvec n α} {a : α} : x.snoc a = x ++ function.const (fin 1) a := begin -- TODO: think about whether this proof is still logical refine (left_append_right (x.snoc a : fin (n+1) → α)).symm.trans _, rw append.inj_iff, split, { rw [left_eq_init, init_snoc] }, { rw [right_eq_last, last_snoc] } end -- TODO: add versions for `left`, `right`? lemma mem_image_init {s : set (finvec (n + 1) α)} {y : finvec n α} : y ∈ finvec.init '' s ↔ ∃ z : α, finvec.snoc y z ∈ s := begin split; intro h, { obtain ⟨x, hx, rfl⟩ := h, refine ⟨x.last, _⟩, rw finvec.init_snoc_last, exact hx }, { obtain ⟨z, hz⟩ := h, refine ⟨finvec.snoc y z, hz, _⟩, simp } end -- TODO: comparison to prod, fin.snoc. end snoc section tail -- Same as `finvec.right` but with the "wrong" type: -- `finvec (n + 1) α → finvec n α` rather than `finvec (1 + n) α → finvec n α`. variables {n : ℕ} def tail (x : finvec (n + 1) α) : finvec n α := x ∘ fin.succ lemma univ_prod_one_like_preimage_tail {ι : Sort*} (C : Π {l : ℕ}, set (finvec l α) → ι) {t : set (finvec n α)} : C (univ_prod 1 t) = C (tail ⁻¹' t) := begin have : 1 + n = n + 1 := add_comm 1 n, congr', rw set.heq_iff_cast_eq this, ext x, change x.right ∈ t ↔ (x.cast _).tail ∈ t, congr', ext i, change x _ = x _, congr, ext, rw [fin.coe_cast, fin.coe_succ], apply add_comm end end tail /-- The canonical isomorphism `α² ≅ α × α`. -/ -- TODO: This most likely needs some lemmas. See its use in `o_minimal.mk'`. def finvec_two_equiv_prod_self {α : Type*} : finvec 2 α ≃ α × α := { to_fun := λ f, (f 0, f 1), inv_fun := λ p, finvec.append (λ _, p.1) (λ _, p.2), left_inv := λ f, by { ext i, fin_cases i; refl }, right_inv := λ p, by { cases p, refl } } -- TODO: instances? e.g. topological_space, add_comm_group, etc.? end finvec
b4f46b63f5e98223b545af43f9e7007ceb70706d
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/tests/bench/rbmap_checkpoint.lean
46a5a0f672225e481b95ba8546a8146457b13e66
[ "Apache-2.0" ]
permissive
mhuisi/lean4
28d35a4febc2e251c7f05492e13f3b05d6f9b7af
dda44bc47f3e5d024508060dac2bcb59fd12e4c0
refs/heads/master
1,621,225,489,283
1,585,142,689,000
1,585,142,689,000
250,590,438
0
2
Apache-2.0
1,602,443,220,000
1,585,327,814,000
C
UTF-8
Lean
false
false
3,417
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.Data.Option.Basic import Init.Data.List.BasicAux import Init.Data.String import Init.System.IO universes u v w w' inductive color | Red | Black inductive Tree | Leaf {} : Tree | Node (color : color) (lchild : Tree) (key : Nat) (val : Bool) (rchild : Tree) : Tree instance : Inhabited Tree := ⟨Tree.Leaf⟩ variables {σ : Type w} open color Nat Tree def fold (f : Nat → Bool → σ → σ) : Tree → σ → σ | Leaf, b => b | Node _ l k v r, b => fold r (f k v (fold l b)) @[inline] def balance1 : Nat → Bool → Tree → Tree → Tree | kv, vv, t, Node _ (Node Red l kx vx r₁) ky vy r₂ => Node Red (Node Black l kx vx r₁) ky vy (Node Black r₂ kv vv t) | kv, vv, t, Node _ l₁ ky vy (Node Red l₂ kx vx r) => Node Red (Node Black l₁ ky vy l₂) kx vx (Node Black r kv vv t) | kv, vv, t, Node _ l ky vy r => Node Black (Node Red l ky vy r) kv vv t | _, _, _, _ => Leaf @[inline] def balance2 : Tree → Nat → Bool → Tree → Tree | t, kv, vv, Node _ (Node Red l kx₁ vx₁ r₁) ky vy r₂ => Node Red (Node Black t kv vv l) kx₁ vx₁ (Node Black r₁ ky vy r₂) | t, kv, vv, Node _ l₁ ky vy (Node Red l₂ kx₂ vx₂ r₂) => Node Red (Node Black t kv vv l₁) ky vy (Node Black l₂ kx₂ vx₂ r₂) | t, kv, vv, Node _ l ky vy r => Node Black t kv vv (Node Red l ky vy r) | _, _, _, _ => Leaf def isRed : Tree → Bool | Node Red _ _ _ _ => true | _ => false def ins : Tree → Nat → Bool → Tree | Leaf, kx, vx => Node Red Leaf kx vx Leaf | Node Red a ky vy b, kx, vx => (if kx < ky then Node Red (ins a kx vx) ky vy b else if kx = ky then Node Red a kx vx b else Node Red a ky vy (ins b kx vx)) | Node Black a ky vy b, kx, vx => if kx < ky then (if isRed a then balance1 ky vy b (ins a kx vx) else Node Black (ins a kx vx) ky vy b) else if kx = ky then Node Black a kx vx b else if isRed b then balance2 a ky vy (ins b kx vx) else Node Black a ky vy (ins b kx vx) def setBlack : Tree → Tree | Node _ l k v r => Node Black l k v r | e => e def insert (t : Tree) (k : Nat) (v : Bool) : Tree := if isRed t then setBlack (ins t k v) else ins t k v def mkMapAux (freq : Nat) : Nat → Tree → List Tree → List Tree | 0, m, r => m::r | n+1, m, r => let m := insert m n (n % 10 = 0); let r := if n % freq == 0 then m::r else r; mkMapAux n m r def mkMap (n : Nat) (freq : Nat) : List Tree := mkMapAux freq n Leaf [] def myLen : List Tree → Nat → Nat | Node _ _ _ _ _ :: xs, r => myLen xs (r + 1) | _ :: xs, r => myLen xs r | [], r => r def main (xs : List String) : IO UInt32 := do [n, freq] ← pure xs | throw $ IO.userError "invalid input"; let n := n.toNat!; let freq := freq.toNat!; let freq := if freq == 0 then 1 else freq; let mList := mkMap n freq; let v := fold (fun (k : Nat) (v : Bool) (r : Nat) => if v then r + 1 else r) mList.head! 0; IO.println (toString (myLen mList 0) ++ " " ++ toString v) *> pure 0
c382fa1536764b6f4e87f89bed124e204d45182a
32025d5c2d6e33ad3b6dd8a3c91e1e838066a7f7
/stage0/src/Lean/Meta/Tactic/LocalDecl.lean
c297fa467ca45542f225f502064f64b07a5c2b50
[ "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
799
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.AppBuilder import Lean.Meta.Tactic.Util import Lean.Meta.Tactic.Assert import Lean.Meta.Tactic.Intro import Lean.Meta.Tactic.Clear namespace Lean namespace Meta def replaceLocalDecl (mvarId : MVarId) (fvarId : FVarId) (newType : Expr) (eqProof : Expr) : MetaM (FVarId × MVarId) := do withMVarContext mvarId $ do localDecl ← getLocalDecl fvarId; newTypePr ← mkEqMP eqProof (mkFVar fvarId); mvarId ← assert mvarId localDecl.userName newType newTypePr; (fvarIdNew, mvarId) ← intro1 mvarId; (do mvarId ← clear mvarId fvarId; pure (fvarIdNew, mvarId)) <|> pure (fvarIdNew, mvarId) end Meta end Lean
e244cfd31fea92a1062f50e8d08318b533dea78e
3dd1b66af77106badae6edb1c4dea91a146ead30
/tests/lean/run/tactic25.lean
5fa7c72058777155fe0e13b0d4574b65c8a2e9b1
[ "Apache-2.0" ]
permissive
silky/lean
79c20c15c93feef47bb659a2cc139b26f3614642
df8b88dca2f8da1a422cb618cd476ef5be730546
refs/heads/master
1,610,737,587,697
1,406,574,534,000
1,406,574,534,000
22,362,176
1
0
null
null
null
null
UTF-8
Lean
false
false
538
lean
import standard using tactic definition my_tac1 := apply @refl definition my_tac2 := repeat (apply @and_intro; assumption) tactic_hint my_tac1 tactic_hint my_tac2 theorem T1 {A : Type.{2}} (a : A) : a = a theorem T2 {a b c : Prop} (Ha : a) (Hb : b) (Hc : c) : a ∧ b ∧ c definition my_tac3 := fixpoint (λ f, [apply @or_intro_left; f | apply @or_intro_right; f | assumption]) tactic_hint [or] my_tac3 theorem T3 {a b c : Prop} (Hb : b) : a ∨ b ∨ c
8e330d8d7530cb52d52fc1978bee575b4c86661b
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/interactive/hole3.lean
c7f6faca58467846f5ad63479c897ad82b492d12
[ "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
145
lean
def x : nat → nat := λ a, {! 0 = a --^ "command": "hole", "action": "Infer" !} --^ "command": "hole", "action": "Infer"
f52b5f97e0ffe34899abef7dc40013ddfb3e9e1b
9dc8cecdf3c4634764a18254e94d43da07142918
/src/category_theory/preadditive/eilenberg_moore.lean
4ac0e531313ea5667ab3c65cf5d9554d1d9dfb38
[ "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
4,625
lean
/- Copyright (c) 2022 Julian Kuelshammer. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Julian Kuelshammer -/ import category_theory.preadditive.default import category_theory.monad.algebra import category_theory.preadditive.additive_functor /-! # Preadditive structure on algebras over a monad If `C` is a preadditive categories and `T` is an additive monad on `C` then `algebra T` is also preadditive. Dually, if `U` is an additive comonad on `C` then `coalgebra U` is preadditive as well. -/ universes v₁ u₁ -- morphism levels before object levels. See note [category_theory universes]. namespace category_theory variables (C : Type u₁) [category.{v₁} C] [preadditive C] (T : monad C) [functor.additive (T : C ⥤ C)] open category_theory.limits preadditive /-- The category of algebras over an additive monad on a preadditive category is preadditive. -/ @[simps] instance monad.algebra_preadditive : preadditive (monad.algebra T) := { hom_group := λ F G, { add := λ α β, { f := α.f + β.f, h' := by simp only [functor.map_add, add_comp, monad.algebra.hom.h, comp_add] }, zero := { f := 0, h' := by simp only [functor.map_zero, zero_comp, comp_zero] }, nsmul := λ n α, { f := n • α.f, h' := by rw [functor.map_nsmul, nsmul_comp, monad.algebra.hom.h, comp_nsmul] }, neg := λ α, { f := -α.f, h' := by simp only [functor.map_neg, neg_comp, monad.algebra.hom.h, comp_neg] }, sub := λ α β, { f := α.f - β.f, h' := by simp only [functor.map_sub, sub_comp, monad.algebra.hom.h, comp_sub] }, zsmul := λ r α, { f := r • α.f, h' := by rw [functor.map_zsmul, zsmul_comp, monad.algebra.hom.h, comp_zsmul] }, add_assoc := by { intros, ext, apply add_assoc }, zero_add := by { intros, ext, apply zero_add }, add_zero := by { intros, ext, apply add_zero }, nsmul_zero' := by { intros, ext, apply zero_smul }, nsmul_succ' := by { intros, ext, apply succ_nsmul }, sub_eq_add_neg := by { intros, ext, apply sub_eq_add_neg }, zsmul_zero' := by { intros, ext, apply zero_smul }, zsmul_succ' := by { intros, ext, dsimp, simp only [coe_nat_zsmul, succ_nsmul], refl, }, zsmul_neg' := by { intros, ext, simp only [zsmul_neg_succ_of_nat, neg_inj, nsmul_eq_smul_cast ℤ] }, add_left_neg := by { intros, ext, apply add_left_neg }, add_comm := by { intros, ext, apply add_comm } }, add_comp' := by { intros, ext, apply add_comp }, comp_add' := by { intros, ext, apply comp_add } } instance monad.forget_additive : (monad.forget T).additive := {} variables (U : comonad C) [functor.additive (U : C ⥤ C)] /-- The category of coalgebras over an additive comonad on a preadditive category is preadditive. -/ @[simps] instance comonad.coalgebra_preadditive : preadditive (comonad.coalgebra U) := { hom_group := λ F G, { add := λ α β, { f := α.f + β.f, h' := by simp only [functor.map_add, comp_add, comonad.coalgebra.hom.h, add_comp] }, zero := { f := 0, h' := by simp only [functor.map_zero, comp_zero, zero_comp] }, nsmul := λ n α, { f := n • α.f, h' := by rw [functor.map_nsmul, comp_nsmul, comonad.coalgebra.hom.h, nsmul_comp] }, neg := λ α, { f := -α.f, h' := by simp only [functor.map_neg, comp_neg, comonad.coalgebra.hom.h, neg_comp] }, sub := λ α β, { f := α.f - β.f, h' := by simp only [functor.map_sub, comp_sub, comonad.coalgebra.hom.h, sub_comp] }, zsmul := λ r α, { f := r • α.f, h' := by rw [functor.map_zsmul, comp_zsmul, comonad.coalgebra.hom.h, zsmul_comp] }, add_assoc := by { intros, ext, apply add_assoc }, zero_add := by { intros, ext, apply zero_add }, add_zero := by { intros, ext, apply add_zero }, nsmul_zero' := by { intros, ext, apply zero_smul }, nsmul_succ' := by { intros, ext, apply succ_nsmul }, sub_eq_add_neg := by { intros, ext, apply sub_eq_add_neg }, zsmul_zero' := by { intros, ext, apply zero_smul }, zsmul_succ' := by { intros, ext, dsimp, simp only [coe_nat_zsmul, succ_nsmul], refl, }, zsmul_neg' := by { intros, ext, simp only [zsmul_neg_succ_of_nat, neg_inj, nsmul_eq_smul_cast ℤ] }, add_left_neg := by { intros, ext, apply add_left_neg }, add_comm := by { intros, ext, apply add_comm } }, add_comp' := by { intros, ext, apply add_comp }, comp_add' := by { intros, ext, apply comp_add } } instance comonad.forget_additive : (comonad.forget U).additive := {} end category_theory
d5f81a2ad0d2e9d4b46e94e80c2bef6941943487
ac2987d8c7832fb4a87edb6bee26141facbb6fa0
/Mathlib/Tactic/Core.lean
d7c9378d25a6665120408ae24c4e21173dfaecce
[ "Apache-2.0" ]
permissive
AurelienSaue/mathlib4
52204b9bd9d207c922fe0cf3397166728bb6c2e2
84271fe0875bafdaa88ac41f1b5a7c18151bd0d5
refs/heads/master
1,689,156,096,545
1,629,378,840,000
1,629,378,840,000
389,648,603
0
0
Apache-2.0
1,627,307,284,000
1,627,307,284,000
null
UTF-8
Lean
false
false
710
lean
/- Copyright (c) 2021 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Aurélien Saue -/ import Lean.Expr namespace Lean.Expr private def getAppFnArgsAux : Expr → Array Expr → Nat → Name × Array Expr | app f a _, as, i => getAppFnArgsAux f (as.set! i a) (i-1) | const n _ _, as, i => (n, as) | _, as, _ => (Name.anonymous, as) def getAppFnArgs (e : Expr) : Name × Array Expr := let nargs := e.getAppNumArgs getAppFnArgsAux e (mkArray nargs arbitrary) (nargs-1) def natLit! : Expr → Nat | lit (Literal.natVal v) _ => v | _ => panic! "nat literal expected" end Expr
050e6c8c113ae239a04384e7e3031f8a3bd969cc
c777c32c8e484e195053731103c5e52af26a25d1
/src/number_theory/modular_forms/jacobi_theta.lean
dd6578c6a37ae4c22e5595651b96dc4e2f34e508
[ "Apache-2.0" ]
permissive
kbuzzard/mathlib
2ff9e85dfe2a46f4b291927f983afec17e946eb8
58537299e922f9c77df76cb613910914a479c1f7
refs/heads/master
1,685,313,702,744
1,683,974,212,000
1,683,974,212,000
128,185,277
1
0
null
1,522,920,600,000
1,522,920,600,000
null
UTF-8
Lean
false
false
9,139
lean
/- Copyright (c) 2023 David Loeffler. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: David Loeffler -/ import analysis.special_functions.gaussian import analysis.complex.locally_uniform_limit import analysis.complex.upper_half_plane.functions_bounded_at_infty import analysis.complex.upper_half_plane.topology /-! # Jacobi's theta function This file defines the Jacobi theta function $$\theta(\tau) = \sum_{n \in \mathbb{Z}} \exp (i \pi n ^ 2 \tau),$$ and proves the modular transformation properties `θ (τ + 2) = θ τ` and `θ (-1 / τ) = (-I * τ) ^ (1 / 2) * θ τ`, using Poisson's summation formula for the latter. We also show that `θ` is differentiable on `ℍ`, and `θ(τ) - 1` has exponential decay as `im τ → ∞`. -/ open complex real asymptotics open_locale real big_operators upper_half_plane manifold /-- Jacobi's theta function `∑' (n : ℤ), exp (π * I * n ^ 2 * τ)`. -/ noncomputable def jacobi_theta (τ : ℍ) : ℂ := ∑' (n : ℤ), cexp (π * I * n ^ 2 * τ) lemma norm_exp_mul_sq_le {z : ℂ} (hz : 0 < z.im) (n : ℤ) : ‖cexp (π * I * n ^ 2 * z)‖ ≤ exp (-π * z.im) ^ n.nat_abs := begin let y := rexp (-π * z.im), have h : y < 1, from exp_lt_one_iff.mpr (mul_neg_of_neg_of_pos (neg_lt_zero.mpr pi_pos) hz), refine (le_of_eq _).trans (_ : y ^ (n ^ 2) ≤ _), { rw [complex.norm_eq_abs, complex.abs_exp], have : (↑π * I * n ^ 2 * z).re = (-π * z.im) * n ^ 2, { rw [(by { push_cast, ring } : ↑π * I * n ^ 2 * z = ↑(π * n ^ 2) * (z * I)), of_real_mul_re, mul_I_re], ring }, obtain ⟨m, hm⟩ := int.eq_coe_of_zero_le (sq_nonneg n), rw [this, exp_mul, ←int.cast_pow, rpow_int_cast, hm, zpow_coe_nat] }, { have : n ^ 2 = ↑(n.nat_abs ^ 2), by rw [nat.cast_pow, int.nat_abs_sq], rw [this, zpow_coe_nat], exact pow_le_pow_of_le_one (exp_pos _).le h.le ((sq n.nat_abs).symm ▸ n.nat_abs.le_mul_self) }, end lemma exists_summable_bound_exp_mul_sq {R : ℝ} (hR : 0 < R) : ∃ (bd : ℤ → ℝ), (summable bd) ∧ (∀ {τ : ℂ} (hτ : R ≤ τ.im) (n : ℤ), ‖cexp (π * I * n ^ 2 * τ)‖ ≤ bd n) := begin let y := rexp (-π * R), have h : y < 1, from exp_lt_one_iff.mpr (mul_neg_of_neg_of_pos (neg_lt_zero.mpr pi_pos) hR), refine ⟨λ n, y ^ n.nat_abs, summable_int_of_summable_nat _ _, λ τ hτ n, _⟩, swap 3, { refine (norm_exp_mul_sq_le (hR.trans_le hτ) n).trans _, refine pow_le_pow_of_le_left (exp_pos _).le (real.exp_le_exp.mpr _) _, rwa [mul_le_mul_left_of_neg (neg_lt_zero.mpr pi_pos)] }, all_goals { simpa only [int.nat_abs_neg, int.nat_abs_of_nat] using summable_geometric_of_lt_1 (real.exp_pos _).le h }, end lemma summable_exp_mul_sq {z : ℂ} (hz : 0 < z.im) : summable (λ n : ℤ, cexp (π * I * n ^ 2 * z)) := let ⟨bd, h, h'⟩ := exists_summable_bound_exp_mul_sq hz in summable_norm_iff.mp (summable_of_nonneg_of_le (λ n, norm_nonneg _) (h' $ le_refl _) h) lemma jacobi_theta_two_vadd (τ : ℍ) : jacobi_theta ((2 : ℝ) +ᵥ τ) = jacobi_theta τ := begin refine tsum_congr (λ n, _), rw [upper_half_plane.coe_vadd, of_real_bit0, of_real_one], suffices : cexp (↑π * I * ↑n ^ 2 * 2) = 1, by rw [mul_add, complex.exp_add, this, one_mul], rw [(by { push_cast, ring } : ↑π * I * ↑n ^ 2 * 2 = ↑(n ^ 2) * (2 * π * I)), complex.exp_int_mul, complex.exp_two_pi_mul_I, one_zpow], end lemma jacobi_theta_T_sq_smul (τ : ℍ) : jacobi_theta (modular_group.T ^ 2 • τ) = jacobi_theta τ := begin suffices : (2 : ℝ) +ᵥ τ = modular_group.T ^ (2 : ℤ) • τ, from this ▸ (jacobi_theta_two_vadd τ), simp only [←subtype.coe_inj, upper_half_plane.modular_T_zpow_smul, int.cast_two], end lemma jacobi_theta_S_smul (τ : ℍ) : jacobi_theta (modular_group.S • τ) = (-I * τ) ^ (1 / 2 : ℂ) * jacobi_theta τ := begin unfold jacobi_theta, rw [upper_half_plane.modular_S_smul, upper_half_plane.coe_mk], have ha : 0 < (-I * τ).re, { rw [neg_mul, neg_re, mul_re, I_re, I_im, zero_mul, one_mul, zero_sub, neg_neg], exact τ.im_pos }, have ha' : (-I * τ) ^ (1 / 2 : ℂ) ≠ 0, { rw [ne.def, cpow_eq_zero_iff], contrapose! ha, rw [ha.1, zero_re] }, have hτ : (τ : ℂ) ≠ 0, from τ.ne_zero, have := complex.tsum_exp_neg_mul_int_sq ha, rw [mul_comm ((1:ℂ) / _) _, mul_one_div, eq_div_iff ha', mul_comm _ (_ ^ _), eq_comm] at this, convert this using 3, { ext1 n, congr' 1, field_simp [hτ, I_ne_zero], ring_nf, rw [I_sq, mul_neg, mul_one, neg_mul, neg_neg] }, { ext1 n, congr' 1, ring_nf } end lemma has_sum_nat_jacobi_theta (τ : ℍ) : has_sum (λ (n : ℕ), cexp (π * I * (n + 1) ^ 2 * τ)) ((jacobi_theta τ - 1) / 2) := begin have := (summable_exp_mul_sq τ.im_pos).has_sum.sum_nat_of_sum_int, rw ←@has_sum_nat_add_iff' ℂ _ _ _ _ 1 at this, simp_rw [finset.sum_range_one, int.cast_neg, int.cast_coe_nat, nat.cast_zero, neg_zero, int.cast_zero, sq (0:ℂ), mul_zero, zero_mul, neg_sq, ←mul_two, complex.exp_zero, add_sub_assoc, (by norm_num : (1 : ℂ) - 1 * 2 = -1), ←sub_eq_add_neg, nat.cast_add, nat.cast_one] at this, convert this.div_const 2, simp_rw mul_div_cancel _ two_ne_zero, end lemma jacobi_theta_eq_tsum_nat (τ : ℍ) : jacobi_theta τ = 1 + 2 * ∑' (n : ℕ), cexp (π * I * (n + 1) ^ 2 * τ) := by rw [(has_sum_nat_jacobi_theta τ).tsum_eq, mul_div_cancel' _ (two_ne_zero' ℂ), ←add_sub_assoc, add_sub_cancel'] /-- An explicit upper bound for `‖jacobi_theta τ - 1‖`. -/ lemma norm_jacobi_theta_sub_one_le (τ : ℍ) : ‖jacobi_theta τ - 1‖ ≤ 2 / (1 - exp (-π * τ.im)) * exp (-π * τ.im) := begin suffices : ‖∑' (n : ℕ), cexp (π * I * (n + 1) ^ 2 * τ)‖ ≤ exp (-π * τ.im) / (1 - exp (-π * τ.im)), { calc ‖jacobi_theta τ - 1‖ = 2 * ‖∑' (n : ℕ), cexp (π * I * (n + 1) ^ 2 * τ)‖ : by rw [sub_eq_iff_eq_add'.mpr (jacobi_theta_eq_tsum_nat τ), norm_mul, complex.norm_eq_abs, complex.abs_two] ... ≤ 2 * (rexp (-π * τ.im) / (1 - rexp (-π * τ.im))) : by rwa [mul_le_mul_left (zero_lt_two' ℝ)] ... = 2 / (1 - rexp (-π * τ.im)) * rexp (-π * τ.im) : by rw [div_mul_comm, mul_comm] }, have : ∀ (n : ℕ), ‖cexp (π * I * (n + 1) ^ 2 * τ)‖ ≤ exp (-π * τ.im) ^ (n + 1), { intro n, simpa only [int.cast_add, int.cast_one] using norm_exp_mul_sq_le τ.im_pos (n + 1) }, have s : has_sum (λ n : ℕ, rexp (-π * τ.im) ^ (n + 1)) (exp (-π * τ.im) / (1 - exp (-π * τ.im))), { simp_rw [pow_succ, div_eq_mul_inv, has_sum_mul_left_iff (real.exp_ne_zero _)], exact has_sum_geometric_of_lt_1 (exp_pos (-π * τ.im)).le (exp_lt_one_iff.mpr $ (mul_neg_of_neg_of_pos (neg_lt_zero.mpr pi_pos) τ.im_pos)) }, have aux : summable (λ (n : ℕ), ‖cexp (↑π * I * (↑n + 1) ^ 2 * ↑τ)‖), from summable_of_nonneg_of_le (λ n, norm_nonneg _) this s.summable, exact (norm_tsum_le_tsum_norm aux).trans ((tsum_mono aux s.summable this).trans (le_of_eq s.tsum_eq)), end /-- The norm of `jacobi_theta τ - 1` decays exponentially as `im τ → ∞`. -/ lemma is_O_at_im_infty_jacobi_theta_sub_one : is_O upper_half_plane.at_im_infty (λ τ, jacobi_theta τ - 1) (λ τ, rexp (-π * τ.im)) := begin simp_rw [is_O, is_O_with, filter.eventually, upper_half_plane.at_im_infty_mem], refine ⟨2 / (1 - rexp (-π)), 1, (λ τ hτ, (norm_jacobi_theta_sub_one_le τ).trans _)⟩, rw [real.norm_eq_abs, real.abs_exp], refine mul_le_mul_of_nonneg_right _ (exp_pos _).le, rw [div_le_div_left (zero_lt_two' ℝ), sub_le_sub_iff_left, exp_le_exp, neg_mul, neg_le_neg_iff], { exact le_mul_of_one_le_right pi_pos.le hτ }, { rw [sub_pos, exp_lt_one_iff, neg_mul, neg_lt_zero], exact mul_pos pi_pos τ.im_pos }, { rw [sub_pos, exp_lt_one_iff, neg_lt_zero], exact pi_pos } end lemma differentiable_at_tsum_exp_mul_sq (τ : ℍ) : differentiable_at ℂ (λ z, ∑' (n : ℤ), cexp (π * I * n ^ 2 * z)) ↑τ := begin suffices : ∀ (y : ℝ) (hy : 0 < y), differentiable_on ℂ (λ z, ∑' (n : ℤ), cexp (π * I * n ^ 2 * z)) {w : ℂ | y < im w}, from let ⟨y, hy, hy'⟩ := exists_between τ.im_pos in (this y hy).differentiable_at ((complex.continuous_im.is_open_preimage _ is_open_Ioi).mem_nhds (τ.coe_im ▸ hy')), intros y hy, have h1 : ∀ (n : ℤ) (w : ℂ) (hw : y < im w), differentiable_within_at ℂ (λ (v : ℂ), cexp (↑π * I * ↑n ^ 2 * v)) {z : ℂ | y < im z} w, from λ n w hw, (differentiable_at_id.const_mul _).cexp.differentiable_within_at, have h2 : is_open {w : ℂ | y < im w}, from continuous_im.is_open_preimage _ is_open_Ioi, obtain ⟨bd, bd_s, le_bd⟩ := exists_summable_bound_exp_mul_sq hy, exact differentiable_on_tsum_of_summable_norm bd_s h1 h2 (λ i w hw, le_bd (le_of_lt hw) i), end lemma mdifferentiable_jacobi_theta : mdifferentiable 𝓘(ℂ) 𝓘(ℂ) jacobi_theta := λ τ, (differentiable_at_tsum_exp_mul_sq τ).mdifferentiable_at.comp τ τ.mdifferentiable_coe lemma continuous_jacobi_theta : continuous jacobi_theta := mdifferentiable_jacobi_theta.continuous
afe63675ce5e088310edf25dc43c3e078351bcf4
6dc0c8ce7a76229dd81e73ed4474f15f88a9e294
/tests/lean/run/induction1.lean
3fd38124fe8af3f4d425c74a7c62bc2d31f20da0
[ "Apache-2.0" ]
permissive
williamdemeo/lean4
72161c58fe65c3ad955d6a3050bb7d37c04c0d54
6d00fcf1d6d873e195f9220c668ef9c58e9c4a35
refs/heads/master
1,678,305,356,877
1,614,708,995,000
1,614,708,995,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,479
lean
@[recursor 4] def Or.elim2 {p q r : Prop} (major : p ∨ q) (left : p → r) (right : q → r) : r := match major with | Or.inl h => left h | Or.inr h => right h theorem tst0 {p q : Prop } (h : p ∨ q) : q ∨ p := by { induction h; { apply Or.inr; assumption }; { apply Or.inl; assumption } } theorem tst0' {p q : Prop } (h : p ∨ q) : q ∨ p := by induction h focus apply Or.inr assumption focus apply Or.inl assumption theorem tst1 {p q : Prop } (h : p ∨ q) : q ∨ p := by induction h with | inr h2 => exact Or.inl h2 | inl h1 => exact Or.inr h1 theorem tst2 {p q : Prop } (h : p ∨ q) : q ∨ p := by induction h using elim2 with | left _ => apply Or.inr; assumption | right _ => apply Or.inl; assumption theorem tst2b {p q : Prop } (h : p ∨ q) : q ∨ p := by induction h using elim2 with | left => apply Or.inr; assumption | _ => apply Or.inl; assumption theorem tst3 {p q : Prop } (h : p ∨ q) : q ∨ p := by induction h using elim2 with | right h => exact Or.inl h | left h => exact Or.inr h theorem tst4 {p q : Prop } (h : p ∨ q) : q ∨ p := by induction h using elim2 with | right h => ?myright | left h => ?myleft case myleft => exact Or.inr h case myright => exact Or.inl h theorem tst5 {p q : Prop } (h : p ∨ q) : q ∨ p := by induction h using elim2 with | right h => _ | left h => refine Or.inr ?_ exact h case right => exact Or.inl h theorem tst6 {p q : Prop } (h : p ∨ q) : q ∨ p := by { cases h with | inr h2 => exact Or.inl h2 | inl h1 => exact Or.inr h1 } theorem tst7 {α : Type} (xs : List α) (h : (a : α) → (as : List α) → xs ≠ a :: as) : xs = [] := by { induction xs with | nil => exact rfl | cons z zs ih => exact absurd rfl (h z zs) } theorem tst8 {α : Type} (xs : List α) (h : (a : α) → (as : List α) → xs ≠ a :: as) : xs = [] := by { induction xs; exact rfl; exact absurd rfl $ h _ _ } theorem tst9 {α : Type} (xs : List α) (h : (a : α) → (as : List α) → xs ≠ a :: as) : xs = [] := by cases xs with | nil => exact rfl | cons z zs => exact absurd rfl (h z zs) theorem tst10 {p q : Prop } (h₁ : p ↔ q) (h₂ : p) : q := by induction h₁ with | intro h _ => exact h h₂ def Iff2 (m p q : Prop) := p ↔ q theorem tst11 {p q r : Prop } (h₁ : Iff2 r p q) (h₂ : p) : q := by induction h₁ using Iff.rec with | intro h _ => exact h h₂ theorem tst12 {p q : Prop } (h₁ : p ∨ q) (h₂ : p ↔ q) (h₃ : p) : q := by failIfSuccess induction h₁ using Iff.casesOn induction h₂ using Iff.casesOn with | intro h _ => exact h h₃ inductive Tree | leaf₁ | leaf₂ | node : Tree → Tree → Tree def Tree.isLeaf₁ : Tree → Bool | leaf₁ => true | _ => false theorem tst13 (x : Tree) (h : x = Tree.leaf₁) : x.isLeaf₁ = true := by cases x with | leaf₁ => rfl | _ => injection h theorem tst14 (x : Tree) (h : x = Tree.leaf₁) : x.isLeaf₁ = true := by induction x with | leaf₁ => rfl | _ => injection h inductive Vec (α : Type) : Nat → Type | nil : Vec α 0 | cons : (a : α) → {n : Nat} → (as : Vec α n) → Vec α (n+1) def getHeads {α β} {n} (xs : Vec α (n+1)) (ys : Vec β (n+1)) : α × β := by cases xs cases ys apply Prod.mk repeat traceState assumption done theorem ex1 (n m o : Nat) : n = m + 0 → m = o → m = o := by intro (h₁ : n = m) h₂ rw [← h₁, ← h₂] assumption
29f3b8d0b82cbfcf438e62a5929b23ba53aa27a3
63abd62053d479eae5abf4951554e1064a4c45b4
/src/algebraic_geometry/stalks.lean
6f2de5987d13b3ea01b5f682759c52596dc0dbbc
[ "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
2,850
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 algebraic_geometry.presheafed_space import topology.sheaves.stalks /-! # Stalks for presheaved spaces This file lifts constructions of stalks and pushforwards of stalks to work with the category of presheafed spaces. -/ noncomputable theory universes v u v' u' open category_theory open category_theory.limits category_theory.category category_theory.functor open algebraic_geometry open topological_space variables {C : Type u} [category.{v} C] [has_colimits C] local attribute [tidy] tactic.op_induction' open Top.presheaf namespace algebraic_geometry.PresheafedSpace /-- The stalk at `x` of a `PresheafedSpace`. -/ def stalk (X : PresheafedSpace C) (x : X) : C := X.presheaf.stalk x /-- A morphism of presheafed spaces induces a morphism of stalks. -/ def stalk_map {X Y : PresheafedSpace C} (α : X ⟶ Y) (x : X) : Y.stalk (α.base x) ⟶ X.stalk x := (stalk_functor C (α.base x)).map (α.c) ≫ X.presheaf.stalk_pushforward C α.base x section restrict -- PROJECT: restriction preserves stalks. -- We'll want to define cofinal functors, show precomposing with a cofinal functor preserves colimits, -- and (easily) verify that "open neighbourhoods of x within U" is cofinal in "open neighbourhoods of x". /- def restrict_stalk_iso {U : Top} (X : PresheafedSpace C) (f : U ⟶ (X : Top.{v})) (h : open_embedding f) (x : U) : (X.restrict f h).stalk x ≅ X.stalk (f x) := begin dsimp only [stalk, Top.presheaf.stalk, stalk_functor], dsimp [colim], sorry end -- TODO `restrict_stalk_iso` is compatible with `germ`. -/ end restrict namespace stalk_map @[simp] lemma id (X : PresheafedSpace C) (x : X) : stalk_map (𝟙 X) x = 𝟙 (X.stalk x) := begin dsimp [stalk_map], simp only [stalk_pushforward.id], rw [←map_comp], convert (stalk_functor C x).map_id X.presheaf, tidy, end -- TODO understand why this proof is still gross (i.e. requires using `erw`) @[simp] lemma comp {X Y Z : PresheafedSpace C} (α : X ⟶ Y) (β : Y ⟶ Z) (x : X) : stalk_map (α ≫ β) x = (stalk_map β (α.base x) : Z.stalk (β.base (α.base x)) ⟶ Y.stalk (α.base x)) ≫ (stalk_map α x : Y.stalk (α.base x) ⟶ X.stalk x) := begin dsimp [stalk_map, stalk_functor, stalk_pushforward], ext U, op_induction U, cases U, simp only [colimit.ι_map_assoc, colimit.ι_pre_assoc, colimit.ι_pre, whisker_left_app, whisker_right_app, assoc, id_comp, map_id, map_comp], dsimp, simp only [map_id, assoc, pushforward.comp_inv_app], -- FIXME Why doesn't simp do this: erw [category_theory.functor.map_id], erw [category_theory.functor.map_id], erw [id_comp, id_comp, id_comp], end end stalk_map end algebraic_geometry.PresheafedSpace
b54024fd7444f7c345e9e34485ba5498b53f3145
26b8b0964ca8e1c2e203585ba5940f83fe05e48a
/src/tidy/applicable.lean
10983948705e1309fc1a12ff17b6902826f0919f
[]
no_license
jcommelin/lean-tidy
ef3cd32a3804221d93f0dff9e180bb2c52f4b143
9cecf497e90db64b5ea140ad6ae1603976dcd402
refs/heads/master
1,585,129,919,276
1,533,512,680,000
1,533,512,680,000
143,677,361
0
0
null
1,616,803,481,000
1,533,530,576,000
Lean
UTF-8
Lean
false
false
3,434
lean
-- Copyright (c) 2017 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Scott Morrison import .pempty open tactic meta def applicable_attribute : user_attribute := { name := `applicable, descr := "A lemma that should be applied to a goal whenever possible." } run_cmd attribute.register `applicable_attribute /- Try to apply one of the given lemmas, it succeeds if one of them succeeds. -/ meta def any_apply : list name → tactic name | [] := failed | (c::cs) := (mk_const c >>= apply >> pure c) <|> any_apply cs /- Try to apply any lemma marked with the attribute @[applicable] -/ meta def applicable : tactic name := do cs ← attribute.get_instances `applicable, (any_apply cs) <|> fail "no @[applicable] lemmas could be applied" meta def semiapplicable_attribute : user_attribute := { name := `semiapplicable, descr := "A lemma that should be applied to a goal whenever possible, as long as it create no new goals." } run_cmd attribute.register `semiapplicable_attribute /- Try to apply one of the given lemmas, fulfilling all new goals using existing hypotheses. It succeeds if one of them succeeds. -/ meta def any_apply_no_new_goals : list name → tactic name | [] := failed | (c::cs) := (do n ← num_goals, t ← mk_const c, r ← seq (apply t >> skip) assumption, n' ← num_goals, guard (n = n' + 1), pure c) <|> any_apply_no_new_goals cs /- Try to apply any lemma marked with the attribute @[semiapplicable], as long as all hypotheses of that lemma can be satisfied immediately from hypotheses. -/ meta def semiapplicable : tactic name := do cs ← attribute.get_instances `semiapplicable, (any_apply_no_new_goals cs) <|> fail "no @[semiapplicable] lemmas could be applied" attribute [applicable] subsingleton.elim attribute [applicable] funext attribute [applicable] set.ext -- Order matters here: putting the attribute on set.ext after funext makes applicable prefer set.ext attribute [applicable] propext attribute [applicable] subtype.eq universes u₁ u₂ @[applicable] definition empty_exfalso (x : false) : empty := begin exfalso, trivial end @[applicable] definition pempty_exfalso (x : false) : pempty := begin exfalso, trivial end @[applicable] lemma punit.ext (a b : punit.{u₁}): a = b := by induction a; induction b; refl @[applicable] lemma ulift.ext {α : Type u₁} (X Y : ulift.{u₂} α) (w : X.down = Y.down) : X = Y := begin induction X, induction Y, dsimp at w, rw w, end @[applicable] lemma sigma.ext {α : Type u₁} (Z : α → Type u₂) (X Y : Σ a : α, Z a) (w1 : X.1 = Y.1) (w2 : @eq.rec_on _ X.1 _ _ w1 X.2 = Y.2) : X = Y := begin induction X, induction Y, dsimp at w1, dsimp at w2, induction w1, induction w2, refl, end @[applicable] lemma pair.ext {α : Type u₁} {β : Type u₂} {X Y : α × β} (p1 : X.1 = Y.1) (p2 : X.2 = Y.2) : X = Y := begin induction X, induction Y, dsimp at *, rw p1, rw p2, end -- TODO should `apply_instance` be in tidy? If so, these shouldn't be needed. @[applicable] definition decidable_true : decidable true := is_true dec_trivial @[applicable] definition decidable_false : decidable false := is_false dec_trivial attribute [applicable] quotient.mk quotient.sound attribute [semiapplicable] eqv_gen.rel attribute [semiapplicable] Exists.intro
e0ea617ba10a5d31e10671898d029dcc84dacd6a
200b12985a863d01fbbde6abfc9326bb82424a8b
/src/propLogic/Ex009.lean
815b8b62412a53cdf2b0e06b80d0a86a33f0e1e0
[]
no_license
SvenWille/LeanLogicExercises
38eacd36733ac48e5a7aacf863c681c9a9a48271
2dbc920feadd63bbc50f87e69646c0081db26eba
refs/heads/master
1,629,676,667,365
1,512,161,459,000
1,512,161,459,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
802
lean
open classical theorem Ex009(a b c: Prop): ¬c → a ∨ ((a ∨ c) → b):= assume H1:¬c , have A:¬(a ∨ ((a ∨ c) → b)) → false, from ( assume H2:¬(a ∨ ((a ∨ c) → b)), have B:(a ∨ c) → b, from ( assume H3:a ∨ c, show b , from or.elim H3 ( assume H4:a, have D:a ∨ ((a ∨ c) → b), from or.inl H4, have false, from H2 D, show b,from false.elim this ) ( assume H5:c, have E:false, from H1 H5, show b,from false.elim E ) ), have a ∨ ((a ∨ c) → b), from or.inr B, show false, from H2 this ), have F:¬¬(a ∨ ((a ∨ c) → b)), from not.intro A, by_contradiction ( assume H6:¬(a ∨ ((a ∨ c) → b)), show false, from F H6 )
14226a1e5aa4e4c51436c92c913b33c0a1c1b218
9dc8cecdf3c4634764a18254e94d43da07142918
/src/number_theory/legendre_symbol/mul_character.lean
117f6c465394c541b669cde174df16cd047c2426
[ "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
17,497
lean
/- Copyright (c) 2022 Michael Stoll. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Michael Stoll -/ import ring_theory.integral_domain /-! # Multiplicative characters of finite rings and fields Let `R` and `R'` be a commutative rings. A *multiplicative character* of `R` with values in `R'` is a morphism of monoids from the multiplicative monoid of `R` into that of `R'` that sends non-units to zero. We use the namespace `mul_char` for the definitions and results. ## Main results We show that the multiplicative characters form a group (if `R'` is commutative); see `mul_char.comm_group`. We also provide an equivalence with the homomorphisms `Rˣ →* R'ˣ`; see `mul_char.equiv_to_unit_hom`. We define a multiplicative character to be *quadratic* if its values are among `0`, `1` and `-1`, and we prove some properties of quadratic characters. Finally, we show that the sum of all values of a nontrivial multiplicative character vanishes; see `mul_char.is_nontrivial.sum_eq_zero`. ## Tags multiplicative character -/ section definition_and_group /-! ### Definitions related to multiplicative characters Even though the intended use is when domain and target of the characters are commutative rings, we define them in the more general setting when the domain is a commutative monoid and the target is a commutative monoid with zero. (We need a zero in the target, since non-units are supposed to map to zero.) In this setting, there is an equivalence between multiplicative characters `R → R'` and group homomorphisms `Rˣ → R'ˣ`, and the multiplicative characters have a natural structure as a commutative group. -/ universes u v section defi -- The domain of our multiplicative characters variables (R : Type u) [comm_monoid R] -- The target variables (R' : Type v) [comm_monoid_with_zero R'] /-- Define a structure for multiplicative characters. A multiplicative character from a commutative monoid `R` to a commutative monoid with zero `R'` is a homomorphism of (multiplicative) monoids that sends non-units to zero. -/ structure mul_char extends monoid_hom R R' := (map_nonunit' : ∀ a : R, ¬ is_unit a → to_fun a = 0) /-- This is the corresponding extension of `monoid_hom_class`. -/ class mul_char_class (F : Type*) (R R' : out_param $ Type*) [comm_monoid R] [comm_monoid_with_zero R'] extends monoid_hom_class F R R' := (map_nonunit : ∀ (χ : F) {a : R} (ha : ¬ is_unit a), χ a = 0) attribute [simp] mul_char_class.map_nonunit end defi section group namespace mul_char -- The domain of our multiplicative characters variables {R : Type u} [comm_monoid R] -- The target variables {R' : Type v} [comm_monoid_with_zero R'] instance coe_to_fun : has_coe_to_fun (mul_char R R') (λ _, R → R') := ⟨λ χ, χ.to_fun⟩ /-- See note [custom simps projection] -/ protected def simps.apply (χ : mul_char R R') : R → R' := χ initialize_simps_projections mul_char (to_monoid_hom_to_fun → apply, -to_monoid_hom) section trivial variables (R R') /-- The trivial multiplicative character. It takes the value `0` on non-units and the value `1` on units. -/ @[simps] noncomputable def trivial : mul_char R R' := { to_fun := by { classical, exact λ x, if is_unit x then 1 else 0 }, map_nonunit' := by { intros a ha, simp only [ha, if_false], }, map_one' := by simp only [is_unit_one, if_true], map_mul' := by { intros x y, simp only [is_unit.mul_iff, boole_mul], split_ifs; tauto, } } end trivial @[simp] lemma coe_coe (χ : mul_char R R') : (χ.to_monoid_hom : R → R') = χ := rfl @[simp] lemma to_fun_eq_coe (χ : mul_char R R') : χ.to_fun = χ := rfl @[simp] lemma coe_mk (f : R →* R') (hf) : (mul_char.mk f hf : R → R') = f := rfl /-- Extensionality. See `ext` below for the version that will actually be used. -/ lemma ext' {χ χ' : mul_char R R'} (h : ∀ a, χ a = χ' a) : χ = χ' := begin cases χ, cases χ', congr, exact monoid_hom.ext h, end instance : mul_char_class (mul_char R R') R R' := { coe := λ χ, χ.to_monoid_hom.to_fun, coe_injective' := λ f g h, ext' (λ a, congr_fun h a), map_mul := λ χ, χ.map_mul', map_one := λ χ, χ.map_one', map_nonunit := λ χ, χ.map_nonunit', } lemma map_nonunit (χ : mul_char R R') {a : R} (ha : ¬ is_unit a) : χ a = 0 := χ.map_nonunit' a ha /-- Extensionality. Since `mul_char`s always take the value zero on non-units, it is sufficient to compare the values on units. -/ @[ext] lemma ext {χ χ' : mul_char R R'} (h : ∀ a : Rˣ, χ a = χ' a) : χ = χ' := begin apply ext', intro a, by_cases ha : is_unit a, { exact h ha.unit, }, { rw [map_nonunit χ ha, map_nonunit χ' ha], }, end lemma ext_iff {χ χ' : mul_char R R'} : χ = χ' ↔ ∀ a : Rˣ, χ a = χ' a := ⟨by { rintro rfl a, refl }, ext⟩ /-! ### Equivalence of multiplicative characters with homomorphisms on units We show that restriction / extension by zero gives an equivalence between `mul_char R R'` and `Rˣ →* R'ˣ`. -/ /-- Turn a `mul_char` into a homomorphism between the unit groups. -/ def to_unit_hom (χ : mul_char R R') : Rˣ →* R'ˣ := units.map χ lemma coe_to_unit_hom (χ : mul_char R R') (a : Rˣ) : ↑(χ.to_unit_hom a) = χ a := rfl /-- Turn a homomorphism between unit groups into a `mul_char`. -/ noncomputable def of_unit_hom (f : Rˣ →* R'ˣ) : mul_char R R' := { to_fun := by { classical, exact λ x, if hx : is_unit x then f hx.unit else 0 }, map_one' := by { have h1 : (is_unit_one.unit : Rˣ) = 1 := units.eq_iff.mp rfl, simp only [h1, dif_pos, units.coe_eq_one, map_one, is_unit_one], }, map_mul' := begin intros x y, by_cases hx : is_unit x, { simp only [hx, is_unit.mul_iff, true_and, dif_pos], by_cases hy : is_unit y, { simp only [hy, dif_pos], have hm : (is_unit.mul_iff.mpr ⟨hx, hy⟩).unit = hx.unit * hy.unit := units.eq_iff.mp rfl, rw [hm, map_mul], norm_cast, }, { simp only [hy, not_false_iff, dif_neg, mul_zero], }, }, { simp only [hx, is_unit.mul_iff, false_and, not_false_iff, dif_neg, zero_mul], }, end , map_nonunit' := by { intros a ha, simp only [ha, not_false_iff, dif_neg], }, } lemma of_unit_hom_coe (f : Rˣ →* R'ˣ) (a : Rˣ) : of_unit_hom f ↑a = f a := by simp [of_unit_hom] /-- The equivalence between multiplicative characters and homomorphisms of unit groups. -/ noncomputable def equiv_to_unit_hom : mul_char R R' ≃ (Rˣ →* R'ˣ) := { to_fun := to_unit_hom, inv_fun := of_unit_hom, left_inv := by { intro χ, ext x, rw [of_unit_hom_coe, coe_to_unit_hom] }, right_inv := by { intro f, ext x, rw [coe_to_unit_hom, of_unit_hom_coe], } } @[simp] lemma to_unit_hom_eq (χ : mul_char R R') : to_unit_hom χ = equiv_to_unit_hom χ := rfl @[simp] lemma of_unit_hom_eq (χ : Rˣ →* R'ˣ) : of_unit_hom χ = equiv_to_unit_hom.symm χ := rfl @[simp] lemma coe_equiv_to_unit_hom (χ : mul_char R R') (a : Rˣ) : ↑(equiv_to_unit_hom χ a) = χ a := coe_to_unit_hom χ a @[simp] lemma equiv_unit_hom_symm_coe (f : Rˣ →* R'ˣ) (a : Rˣ) : equiv_to_unit_hom.symm f ↑a = f a := of_unit_hom_coe f a /-! ### Commutative group structure on multiplicative characters The multiplicative characters `R → R'` form a commutative group. -/ protected lemma map_one (χ : mul_char R R') : χ (1 : R) = 1 := χ.map_one' /-- If the domain has a zero (and is nontrivial), then `χ 0 = 0`. -/ protected lemma map_zero {R : Type u} [comm_monoid_with_zero R] [nontrivial R] (χ : mul_char R R') : χ (0 : R) = 0 := by rw [map_nonunit χ not_is_unit_zero] /-- If the domain is a ring `R`, then `χ (ring_char R) = 0`. -/ lemma map_ring_char {R : Type u} [comm_ring R] [nontrivial R] (χ : mul_char R R') : χ (ring_char R) = 0 := by rw [ring_char.nat.cast_ring_char, χ.map_zero] noncomputable instance has_one : has_one (mul_char R R') := ⟨trivial R R'⟩ noncomputable instance inhabited : inhabited (mul_char R R') := ⟨1⟩ /-- Evaluation of the trivial character -/ @[simp] lemma one_apply_coe (a : Rˣ) : (1 : mul_char R R') a = 1 := dif_pos a.is_unit /-- Multiplication of multiplicative characters. (This needs the target to be commutative.) -/ def mul (χ χ' : mul_char R R') : mul_char R R' := { to_fun := χ * χ', map_nonunit' := λ a ha, by simp [map_nonunit χ ha], ..χ.to_monoid_hom * χ'.to_monoid_hom } instance has_mul : has_mul (mul_char R R') := ⟨mul⟩ lemma mul_apply (χ χ' : mul_char R R') (a : R) : (χ * χ') a = χ a * χ' a := rfl @[simp] lemma coe_to_fun_mul (χ χ' : mul_char R R') : ⇑(χ * χ') = χ * χ' := rfl protected lemma one_mul (χ : mul_char R R') : (1 : mul_char R R') * χ = χ := by { ext, simp } protected lemma mul_one (χ : mul_char R R') : χ * 1 = χ := by { ext, simp } /-- The inverse of a multiplicative character. We define it as `inverse ∘ χ`. -/ noncomputable def inv (χ : mul_char R R') : mul_char R R' := { to_fun := λ a, monoid_with_zero.inverse (χ a), map_nonunit' := λ a ha, by simp [map_nonunit _ ha], ..monoid_with_zero.inverse.to_monoid_hom.comp χ.to_monoid_hom } noncomputable instance has_inv : has_inv (mul_char R R') := ⟨inv⟩ /-- The inverse of a multiplicative character `χ`, applied to `a`, is the inverse of `χ a`. -/ lemma inv_apply_eq_inv (χ : mul_char R R') (a : R) : χ⁻¹ a = ring.inverse (χ a) := eq.refl $ inv χ a /-- The inverse of a multiplicative character `χ`, applied to `a`, is the inverse of `χ a`. Variant when the target is a field -/ lemma inv_apply_eq_inv' {R' : Type v} [field R'] (χ : mul_char R R') (a : R) : χ⁻¹ a = (χ a)⁻¹ := (inv_apply_eq_inv χ a).trans $ ring.inverse_eq_inv (χ a) /-- When the domain has a zero, then the inverse of a multiplicative character `χ`, applied to `a`, is `χ` applied to the inverse of `a`. -/ lemma inv_apply {R : Type u} [comm_monoid_with_zero R] (χ : mul_char R R') (a : R) : χ⁻¹ a = χ (ring.inverse a) := begin by_cases ha : is_unit a, { rw [inv_apply_eq_inv], have h := is_unit.map χ ha, apply_fun ((*) (χ a)) using is_unit.mul_right_injective h, rw [ring.mul_inverse_cancel _ h, ← map_mul, ring.mul_inverse_cancel _ ha, mul_char.map_one], }, { revert ha, nontriviality R, intro ha, -- `nontriviality R` by itself doesn't do it rw [map_nonunit _ ha, ring.inverse_non_unit a ha, mul_char.map_zero χ], }, end /-- When the domain has a zero, then the inverse of a multiplicative character `χ`, applied to `a`, is `χ` applied to the inverse of `a`. -/ lemma inv_apply' {R : Type u} [field R] (χ : mul_char R R') (a : R) : χ⁻¹ a = χ a⁻¹ := (inv_apply χ a).trans $ congr_arg _ (ring.inverse_eq_inv a) /-- The product of a character with its inverse is the trivial character. -/ @[simp] lemma inv_mul (χ : mul_char R R') : χ⁻¹ * χ = 1 := begin ext x, rw [coe_to_fun_mul, pi.mul_apply, inv_apply_eq_inv, ring.inverse_mul_cancel _ (is_unit.map _ x.is_unit), one_apply_coe], end /-- The commutative group structure on `mul_char R R'`. -/ noncomputable instance comm_group : comm_group (mul_char R R') := { one := 1, mul := (*), inv := has_inv.inv, mul_left_inv := inv_mul, mul_assoc := by { intros χ₁ χ₂ χ₃, ext a, simp [mul_assoc], }, mul_comm := by { intros χ₁ χ₂, ext a, simp [mul_comm], }, one_mul := one_mul, mul_one := mul_one, } /-- If `a` is a unit and `n : ℕ`, then `(χ ^ n) a = (χ a) ^ n`. -/ lemma pow_apply_coe (χ : mul_char R R') (n : ℕ) (a : Rˣ) : (χ ^ n) a = (χ a) ^ n := begin induction n with n ih, { rw [pow_zero, pow_zero, one_apply_coe], }, { rw [pow_succ, pow_succ, mul_apply, ih], }, end /-- If `n` is positive, then `(χ ^ n) a = (χ a) ^ n`. -/ lemma pow_apply' (χ : mul_char R R') {n : ℕ} (hn : 0 < n) (a : R) : (χ ^ n) a = (χ a) ^ n := begin by_cases ha : is_unit a, { exact pow_apply_coe χ n ha.unit, }, { rw [map_nonunit (χ ^ n) ha, map_nonunit χ ha, zero_pow hn], }, end end mul_char end group end definition_and_group /-! ### Properties of multiplicative characters We introduce the properties of being nontrivial or quadratic and prove some basic facts about them. We now assume that domain and target are commutative rings. -/ section properties namespace mul_char universes u v w variables {R : Type u} [comm_ring R] {R' : Type v} [comm_ring R'] {R'' : Type w} [comm_ring R''] /-- A multiplicative character is *nontrivial* if it takes a value `≠ 1` on a unit. -/ def is_nontrivial (χ : mul_char R R') : Prop := ∃ a : Rˣ, χ a ≠ 1 /-- A multiplicative character is nontrivial iff it is not the trivial character. -/ lemma is_nontrivial_iff (χ : mul_char R R') : χ.is_nontrivial ↔ χ ≠ 1 := by simp only [is_nontrivial, ne.def, ext_iff, not_forall, one_apply_coe] /-- A multiplicative character is *quadratic* if it takes only the values `0`, `1`, `-1`. -/ def is_quadratic (χ : mul_char R R') : Prop := ∀ a, χ a = 0 ∨ χ a = 1 ∨ χ a = -1 /-- If two values of quadratic characters with target `ℤ` agree after coercion into a ring of characteristic not `2`, then they agree in `ℤ`. -/ lemma is_quadratic.eq_of_eq_coe {χ : mul_char R ℤ} (hχ : is_quadratic χ) {χ' : mul_char R' ℤ} (hχ' : is_quadratic χ') [nontrivial R''] (hR'' : ring_char R'' ≠ 2) {a : R} {a' : R'} (h : (χ a : R'') = χ' a') : χ a = χ' a' := int.cast_inj_on_of_ring_char_ne_two hR'' (hχ a) (hχ' a') h /-- We can post-compose a multiplicative character with a ring homomorphism. -/ @[simps] def ring_hom_comp (χ : mul_char R R') (f : R' →+* R'') : mul_char R R'' := { to_fun := λ a, f (χ a), map_nonunit' := λ a ha, by simp only [map_nonunit χ ha, map_zero], ..f.to_monoid_hom.comp χ.to_monoid_hom } /-- Composition with an injective ring homomorphism preserves nontriviality. -/ lemma is_nontrivial.comp {χ : mul_char R R'} (hχ : χ.is_nontrivial) {f : R' →+* R''} (hf : function.injective f) : (χ.ring_hom_comp f).is_nontrivial := begin obtain ⟨a, ha⟩ := hχ, use a, rw [ring_hom_comp_apply, ← ring_hom.map_one f], exact λ h, ha (hf h), end /-- Composition with a ring homomorphism preserves the property of being a quadratic character. -/ lemma is_quadratic.comp {χ : mul_char R R'} (hχ : χ.is_quadratic) (f : R' →+* R'') : (χ.ring_hom_comp f).is_quadratic := begin intro a, rcases hχ a with (ha | ha | ha); simp [ha], end /-- The inverse of a quadratic character is itself. → -/ lemma is_quadratic.inv {χ : mul_char R R'} (hχ : χ.is_quadratic) : χ⁻¹ = χ := begin ext x, rw [inv_apply_eq_inv], rcases hχ x with h₀ | h₁ | h₂, { rw [h₀, ring.inverse_zero], }, { rw [h₁, ring.inverse_one], }, { rw [h₂, (by norm_cast : (-1 : R') = (-1 : R'ˣ)), ring.inverse_unit (-1 : R'ˣ)], refl, }, end /-- The square of a quadratic character is the trivial character. -/ lemma is_quadratic.sq_eq_one {χ : mul_char R R'} (hχ : χ.is_quadratic) : χ ^ 2 = 1 := begin convert mul_left_inv _, rw [pow_two, hχ.inv], end /-- The `p`th power of a quadratic character is itself, when `p` is the (prime) characteristic of the target ring. -/ lemma is_quadratic.pow_char {χ : mul_char R R'} (hχ : χ.is_quadratic) (p : ℕ) [hp : fact p.prime] [char_p R' p] : χ ^ p = χ := begin ext x, rw [pow_apply_coe], rcases hχ x with (hx | hx | hx); rw hx, { rw [zero_pow (fact.out p.prime).pos], }, { rw [one_pow], }, { exact char_p.neg_one_pow_char R' p, }, end /-- The `n`th power of a quadratic character is the trivial character, when `n` is even. -/ lemma is_quadratic.pow_even {χ : mul_char R R'} (hχ : χ.is_quadratic) {n : ℕ} (hn : even n) : χ ^ n = 1 := begin obtain ⟨n, rfl⟩ := even_iff_two_dvd.mp hn, rw [pow_mul, hχ.sq_eq_one, one_pow] end /-- The `n`th power of a quadratic character is itself, when `n` is odd. -/ lemma is_quadratic.pow_odd {χ : mul_char R R'} (hχ : χ.is_quadratic) {n : ℕ} (hn : odd n) : χ ^ n = χ := begin obtain ⟨n, rfl⟩ := hn, rw [pow_add, pow_one, hχ.pow_even (even_two_mul _), one_mul] end open_locale big_operators /-- The sum over all values of a nontrivial multiplicative character on a finite ring is zero (when the target is a domain). -/ lemma is_nontrivial.sum_eq_zero [fintype R] [is_domain R'] {χ : mul_char R R'} (hχ : χ.is_nontrivial) : ∑ a, χ a = 0 := begin rcases hχ with ⟨b, hb⟩, refine eq_zero_of_mul_eq_self_left hb _, simp only [finset.mul_sum, ← map_mul], exact fintype.sum_bijective _ (units.mul_left_bijective b) _ _ (λ x, rfl) end /-- The sum over all values of the trivial multiplicative character on a finite ring is the cardinality of its unit group. -/ lemma sum_one_eq_card_units [fintype R] [decidable_eq R] : ∑ a, (1 : mul_char R R') a = fintype.card Rˣ := begin calc ∑ a, (1 : mul_char R R') a = ∑ a : R, if is_unit a then 1 else 0 : finset.sum_congr rfl (λ a _, _) ... = ((finset.univ : finset R).filter is_unit).card : finset.sum_boole ... = (finset.univ.map (⟨(coe : Rˣ → R), units.ext⟩)).card : _ ... = fintype.card Rˣ : congr_arg _ (finset.card_map _), { split_ifs with h h, { exact one_apply_coe h.unit }, { exact map_nonunit _ h } }, { congr, ext a, simp only [finset.mem_filter, finset.mem_univ, true_and, finset.mem_map, function.embedding.coe_fn_mk, exists_true_left, is_unit], }, end end mul_char end properties
6e3e75b4083036b421665cea468b3910b0800177
19cc34575500ee2e3d4586c15544632aa07a8e66
/src/data/complex/basic.lean
cab431a0ca0597611c3cfc0c480ccb2d2ce49476
[ "Apache-2.0" ]
permissive
LibertasSpZ/mathlib
b9fcd46625eb940611adb5e719a4b554138dade6
33f7870a49d7cc06d2f3036e22543e6ec5046e68
refs/heads/master
1,672,066,539,347
1,602,429,158,000
1,602,429,158,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
20,427
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 open_locale big_operators /-! # 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] }, 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 ℂ := 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, norm_cast] 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 (@zero_lt_two ℝ _)], 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 { simp_rw [_root_.abs_div, abs_abs, div_le_iff (abs_pos.2 hz), one_mul, 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 { simp_rw [_root_.abs_div, abs_abs, div_le_iff (abs_pos.2 hz), one_mul, 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)⟩) @[simp, norm_cast] lemma of_real_prod {α : Type*} (s : finset α) (f : α → ℝ) : ((∏ i in s, f i : ℝ) : ℂ) = ∏ i in s, (f i : ℂ) := ring_hom.map_prod of_real _ _ @[simp, norm_cast] lemma of_real_sum {α : Type*} (s : finset α) (f : α → ℝ) : ((∑ i in s, f i : ℝ) : ℂ) = ∑ i in s, (f i : ℂ) := ring_hom.map_sum of_real _ _ end complex