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
187eea4b78df2ca00f52db4a4294fa70c242f666
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/data/finsupp/antidiagonal.lean
f6cbda96357b44abf7e0d0246ca3620578d9d494
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
4,496
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Yury Kudryashov -/ import data.finsupp.basic import data.multiset.antidiagonal /-! # The `finsupp` counterpart of `multiset.antidiagonal`. The antidiagonal of `s : α →₀ ℕ` consists of all pairs `(t₁, t₂) : (α →₀ ℕ) × (α →₀ ℕ)` such that `t₁ + t₂ = s`. -/ noncomputable theory open_locale classical big_operators namespace finsupp open finset variables {α : Type*} /-- The `finsupp` counterpart of `multiset.antidiagonal`: the antidiagonal of `s : α →₀ ℕ` consists of all pairs `(t₁, t₂) : (α →₀ ℕ) × (α →₀ ℕ)` such that `t₁ + t₂ = s`. The finitely supported function `antidiagonal s` is equal to the multiplicities of these pairs. -/ def antidiagonal' (f : α →₀ ℕ) : ((α →₀ ℕ) × (α →₀ ℕ)) →₀ ℕ := (f.to_multiset.antidiagonal.map (prod.map multiset.to_finsupp multiset.to_finsupp)).to_finsupp /-- The antidiagonal of `s : α →₀ ℕ` is the finset of all pairs `(t₁, t₂) : (α →₀ ℕ) × (α →₀ ℕ)` such that `t₁ + t₂ = s`. -/ def antidiagonal (f : α →₀ ℕ) : finset ((α →₀ ℕ) × (α →₀ ℕ)) := f.antidiagonal'.support @[simp] lemma mem_antidiagonal {f : α →₀ ℕ} {p : (α →₀ ℕ) × (α →₀ ℕ)} : p ∈ antidiagonal f ↔ p.1 + p.2 = f := begin rcases p with ⟨p₁, p₂⟩, simp [antidiagonal, antidiagonal', ← and.assoc, ← finsupp.to_multiset.apply_eq_iff_eq] end lemma swap_mem_antidiagonal {n : α →₀ ℕ} {f : (α →₀ ℕ) × (α →₀ ℕ)} : f.swap ∈ antidiagonal n ↔ f ∈ antidiagonal n := by simp only [mem_antidiagonal, add_comm, prod.swap] lemma antidiagonal_filter_fst_eq (f g : α →₀ ℕ) [D : Π (p : (α →₀ ℕ) × (α →₀ ℕ)), decidable (p.1 = g)] : (antidiagonal f).filter (λ p, p.1 = g) = if g ≤ f then {(g, f - g)} else ∅ := begin ext ⟨a, b⟩, suffices : a = g → (a + b = f ↔ g ≤ f ∧ b = f - g), { simpa [apply_ite ((∈) (a, b)), ← and.assoc, @and.right_comm _ (a = _), and.congr_left_iff] }, unfreezingI {rintro rfl}, split, { rintro rfl, exact ⟨le_add_right le_rfl, (nat_add_sub_cancel_left _ _).symm⟩ }, { rintro ⟨h, rfl⟩, exact nat_add_sub_of_le h } end lemma antidiagonal_filter_snd_eq (f g : α →₀ ℕ) [D : Π (p : (α →₀ ℕ) × (α →₀ ℕ)), decidable (p.2 = g)] : (antidiagonal f).filter (λ p, p.2 = g) = if g ≤ f then {(f - g, g)} else ∅ := begin ext ⟨a, b⟩, suffices : b = g → (a + b = f ↔ g ≤ f ∧ a = f - g), { simpa [apply_ite ((∈) (a, b)), ← and.assoc, and.congr_left_iff] }, unfreezingI {rintro rfl}, split, { rintro rfl, exact ⟨le_add_left le_rfl, (nat_add_sub_cancel _ _).symm⟩ }, { rintro ⟨h, rfl⟩, exact nat_sub_add_cancel h } end @[simp] lemma antidiagonal_zero : antidiagonal (0 : α →₀ ℕ) = singleton (0,0) := by rw [antidiagonal, antidiagonal', multiset.to_finsupp_support]; refl @[to_additive] lemma prod_antidiagonal_swap {M : Type*} [comm_monoid M] (n : α →₀ ℕ) (f : (α →₀ ℕ) → (α →₀ ℕ) → M) : ∏ p in antidiagonal n, f p.1 p.2 = ∏ p in antidiagonal n, f p.2 p.1 := finset.prod_bij (λ p hp, p.swap) (λ p, swap_mem_antidiagonal.2) (λ p hp, rfl) (λ p₁ p₂ _ _ h, prod.swap_injective h) (λ p hp, ⟨p.swap, swap_mem_antidiagonal.2 hp, p.swap_swap.symm⟩) /-- The set `{m : α →₀ ℕ | m ≤ n}` as a `finset`. -/ def Iic_finset (n : α →₀ ℕ) : finset (α →₀ ℕ) := (antidiagonal n).image prod.fst @[simp] lemma mem_Iic_finset {m n : α →₀ ℕ} : m ∈ Iic_finset n ↔ m ≤ n := by simp [Iic_finset, le_iff_exists_add, eq_comm] @[simp] lemma coe_Iic_finset (n : α →₀ ℕ) : ↑(Iic_finset n) = set.Iic n := by { ext, simp } /-- Let `n : α →₀ ℕ` be a finitely supported function. The set of `m : α →₀ ℕ` that are coordinatewise less than or equal to `n`, is a finite set. -/ lemma finite_le_nat (n : α →₀ ℕ) : set.finite {m | m ≤ n} := by simpa using (Iic_finset n).finite_to_set /-- Let `n : α →₀ ℕ` be a finitely supported function. The set of `m : α →₀ ℕ` that are coordinatewise less than or equal to `n`, but not equal to `n` everywhere, is a finite set. -/ lemma finite_lt_nat (n : α →₀ ℕ) : set.finite {m | m < n} := (finite_le_nat n).subset $ λ m, le_of_lt end finsupp
c3c0eda7d91d68304e32512151ce4ec1c6118aea
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/introv.lean
ccf21f1e410fc119e9c0938a938470e1b0fe36ae
[ "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
288
lean
example : ∀ a b : nat, a = b → b = a := begin introv h, exact h.symm end example : ∀ a b : nat, a = b → ∀ c, b = c → a = c := begin introv h₁ h₂, exact h₁.trans h₂ end example : ∀ a b : nat, a = b → b = a := begin introv, intro h, exact h.symm end
247a1b796864bf77788489a4580a4ce0f81aa5cf
b815abf92ce063fe0d1fabf5b42da483552aa3e8
/library/init/algebra/ring.lean
af34352d7472d08592b8b8b08c6cabd484d294a9
[ "Apache-2.0" ]
permissive
yodalee/lean
a368d842df12c63e9f79414ed7bbee805b9001ef
317989bf9ef6ae1dec7488c2363dbfcdc16e0756
refs/heads/master
1,610,551,176,860
1,481,430,138,000
1,481,646,441,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
8,679
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura -/ prelude import init.algebra.group /- Make sure instances defined in this file have lower priority than the ones defined for concrete structures -/ set_option default_priority 100 universe variable u class distrib (α : Type u) extends has_mul α, has_add α := (left_distrib : ∀ a b c : α, a * (b + c) = (a * b) + (a * c)) (right_distrib : ∀ a b c : α, (a + b) * c = (a * c) + (b * c)) variable {α : Type u} lemma left_distrib [distrib α] (a b c : α) : a * (b + c) = a * b + a * c := distrib.left_distrib a b c def mul_add := @left_distrib lemma right_distrib [distrib α] (a b c : α) : (a + b) * c = a * c + b * c := distrib.right_distrib a b c def add_mul := @right_distrib class mul_zero_class (α : Type u) extends has_mul α, has_zero α := (zero_mul : ∀ a : α, 0 * a = 0) (mul_zero : ∀ a : α, a * 0 = 0) @[simp] lemma zero_mul [mul_zero_class α] (a : α) : 0 * a = 0 := mul_zero_class.zero_mul a @[simp] lemma mul_zero [mul_zero_class α] (a : α) : a * 0 = 0 := mul_zero_class.mul_zero a class zero_ne_one_class (α : Type u) extends has_zero α, has_one α := (zero_ne_one : 0 ≠ (1:α)) lemma zero_ne_one [s: zero_ne_one_class α] : 0 ≠ (1:α) := @zero_ne_one_class.zero_ne_one α s /- semiring -/ structure semiring (α : Type u) extends comm_monoid α renaming mul→add mul_assoc→add_assoc one→zero one_mul→zero_add mul_one→add_zero mul_comm→add_comm, monoid α, distrib α, mul_zero_class α attribute [class] semiring instance add_comm_monoid_of_semiring (α : Type u) [s : semiring α] : add_comm_monoid α := @semiring.to_comm_monoid α s instance monoid_of_semiring (α : Type u) [s : semiring α] : monoid α := @semiring.to_monoid α s instance distrib_of_semiring (α : Type u) [s : semiring α] : distrib α := @semiring.to_distrib α s instance mul_zero_class_of_semiring (α : Type u) [s : semiring α] : mul_zero_class α := @semiring.to_mul_zero_class α s section semiring variables [semiring α] lemma one_add_one_eq_two : 1 + 1 = (2 : α) := begin unfold bit0, reflexivity end lemma ne_zero_of_mul_ne_zero_right {a b : α} (h : a * b ≠ 0) : a ≠ 0 := suppose a = 0, have a * b = 0, by rw [this, zero_mul], h this lemma ne_zero_of_mul_ne_zero_left {a b : α} (h : a * b ≠ 0) : b ≠ 0 := suppose b = 0, have a * b = 0, by rw [this, mul_zero], h this lemma distrib_three_right (a b c d : α) : (a + b + c) * d = a * d + b * d + c * d := by simp [right_distrib] end semiring class comm_semiring (α : Type u) extends semiring α, comm_monoid α /- ring -/ structure ring (α : Type u) extends comm_group α renaming mul→add mul_assoc→add_assoc one→zero one_mul→zero_add mul_one→add_zero inv→neg mul_left_inv→add_left_inv mul_comm→add_comm, monoid α, distrib α attribute [class] ring instance to_add_comm_group_of_ring (α : Type u) [s : ring α] : add_comm_group α := @ring.to_comm_group α s instance monoid_of_ring (α : Type u) [s : ring α] : monoid α := @ring.to_monoid α s instance distrib_of_ring (α : Type u) [s : ring α] : distrib α := @ring.to_distrib α s lemma ring.mul_zero [ring α] (a : α) : a * 0 = 0 := have a * 0 + 0 = a * 0 + a * 0, from calc a * 0 + 0 = a * (0 + 0) : by simp ... = a * 0 + a * 0 : by rw left_distrib, show a * 0 = 0, from (add_left_cancel this)^.symm lemma ring.zero_mul [ring α] (a : α) : 0 * a = 0 := have 0 * a + 0 = 0 * a + 0 * a, from calc 0 * a + 0 = (0 + 0) * a : by simp ... = 0 * a + 0 * a : by rewrite right_distrib, show 0 * a = 0, from (add_left_cancel this)^.symm instance ring.to_semiring [s : ring α] : semiring α := { s with mul_zero := ring.mul_zero, zero_mul := ring.zero_mul } lemma neg_mul_eq_neg_mul [s : ring α] (a b : α) : -(a * b) = -a * b := neg_eq_of_add_eq_zero begin rw [-right_distrib, add_right_neg, zero_mul] end lemma neg_mul_eq_mul_neg [s : ring α] (a b : α) : -(a * b) = a * -b := neg_eq_of_add_eq_zero begin rw [-left_distrib, add_right_neg, mul_zero] end @[simp] lemma neg_mul_eq_neg_mul_symm [s : ring α] (a b : α) : - a * b = - (a * b) := eq.symm (neg_mul_eq_neg_mul a b) @[simp] lemma mul_neg_eq_neg_mul_symm [s : ring α] (a b : α) : a * - b = - (a * b) := eq.symm (neg_mul_eq_mul_neg a b) lemma neg_mul_neg [s : ring α] (a b : α) : -a * -b = a * b := by simp lemma neg_mul_comm [s : ring α] (a b : α) : -a * b = a * -b := by simp lemma mul_sub_left_distrib [s : ring α] (a b c : α) : a * (b - c) = a * b - a * c := calc a * (b - c) = a * b + a * -c : left_distrib a b (-c) ... = a * b - a * c : by simp def mul_sub := @mul_sub_left_distrib lemma mul_sub_right_distrib [s : ring α] (a b c : α) : (a - b) * c = a * c - b * c := calc (a - b) * c = a * c + -b * c : right_distrib a (-b) c ... = a * c - b * c : by simp def sub_mul := @mul_sub_right_distrib class comm_ring (α : Type u) extends ring α, comm_semigroup α instance comm_ring.to_comm_semiring [s : comm_ring α] : comm_semiring α := { s with mul_zero := mul_zero, zero_mul := zero_mul } section comm_ring variable [comm_ring α] lemma mul_self_sub_mul_self_eq (a b : α) : a * a - b * b = (a + b) * (a - b) := by simp [right_distrib, left_distrib] lemma mul_self_sub_one_eq (a : α) : a * a - 1 = (a + 1) * (a - 1) := by simp [right_distrib, left_distrib] lemma add_mul_self_eq (a b : α) : (a + b) * (a + b) = a*a + 2*a*b + b*b := calc (a + b)*(a + b) = a*a + (1+1)*a*b + b*b : by simp [right_distrib, left_distrib] ... = a*a + 2*a*b + b*b : by rw one_add_one_eq_two end comm_ring class no_zero_divisors (α : Type u) extends has_mul α, has_zero α := (eq_zero_or_eq_zero_of_mul_eq_zero : ∀ a b : α, a * b = 0 → a = 0 ∨ b = 0) lemma eq_zero_or_eq_zero_of_mul_eq_zero [no_zero_divisors α] {a b : α} (h : a * b = 0) : a = 0 ∨ b = 0 := no_zero_divisors.eq_zero_or_eq_zero_of_mul_eq_zero a b h lemma eq_zero_of_mul_self_eq_zero [no_zero_divisors α] {a : α} (h : a * a = 0) : a = 0 := or.elim (eq_zero_or_eq_zero_of_mul_eq_zero h) (assume h', h') (assume h', h') class integral_domain (α : Type u) extends comm_ring α, no_zero_divisors α, zero_ne_one_class α section integral_domain variable [integral_domain α] lemma mul_ne_zero {a b : α} (h₁ : a ≠ 0) (h₂ : b ≠ 0) : a * b ≠ 0 := λ h, or.elim (eq_zero_or_eq_zero_of_mul_eq_zero h) (assume h₃, h₁ h₃) (assume h₄, h₂ h₄) lemma eq_of_mul_eq_mul_right {a b c : α} (ha : a ≠ 0) (h : b * a = c * a) : b = c := have b * a - c * a = 0, from sub_eq_zero_of_eq h, have (b - c) * a = 0, by rw [mul_sub_right_distrib, this], have b - c = 0, from (eq_zero_or_eq_zero_of_mul_eq_zero this)^.resolve_right ha, eq_of_sub_eq_zero this lemma eq_of_mul_eq_mul_left {a b c : α} (ha : a ≠ 0) (h : a * b = a * c) : b = c := have a * b - a * c = 0, from sub_eq_zero_of_eq h, have a * (b - c) = 0, by rw [mul_sub_left_distrib, this], have b - c = 0, from (eq_zero_or_eq_zero_of_mul_eq_zero this)^.resolve_left ha, eq_of_sub_eq_zero this lemma eq_zero_of_mul_eq_self_right {a b : α} (h₁ : b ≠ 1) (h₂ : a * b = a) : a = 0 := have hb : b - 1 ≠ 0, from suppose b - 1 = 0, have b = 0 + 1, from eq_add_of_sub_eq this, have b = 1, by rwa zero_add at this, h₁ this, have a * b - a = 0, by simp [h₂], have a * (b - 1) = 0, by rwa [mul_sub_left_distrib, mul_one], show a = 0, from (eq_zero_or_eq_zero_of_mul_eq_zero this)^.resolve_right hb lemma eq_zero_of_mul_eq_self_left {a b : α} (h₁ : b ≠ 1) (h₂ : b * a = a) : a = 0 := eq_zero_of_mul_eq_self_right h₁ (by rwa mul_comm at h₂) lemma mul_self_eq_mul_self_iff (a b : α) : a * a = b * b ↔ a = b ∨ a = -b := iff.intro (suppose a * a = b * b, have (a - b) * (a + b) = 0, by rewrite [mul_comm, -mul_self_sub_mul_self_eq, this, sub_self], have a - b = 0 ∨ a + b = 0, from eq_zero_or_eq_zero_of_mul_eq_zero this, or.elim this (suppose a - b = 0, or.inl (eq_of_sub_eq_zero this)) (suppose a + b = 0, or.inr (eq_neg_of_add_eq_zero this))) (suppose a = b ∨ a = -b, or.elim this (suppose a = b, by rewrite this) (suppose a = -b, by rewrite [this, neg_mul_neg])) lemma mul_self_eq_one_iff (a : α) : a * a = 1 ↔ a = 1 ∨ a = -1 := have a * a = 1 * 1 ↔ a = 1 ∨ a = -1, from mul_self_eq_mul_self_iff a 1, by rwa mul_one at this end integral_domain
58a777ed1134004b363ad730c928a343e66f7745
22e97a5d648fc451e25a06c668dc03ac7ed7bc25
/src/ring_theory/power_series.lean
af6a4a9bbefac9b52609409102473d1a947770ab
[ "Apache-2.0" ]
permissive
keeferrowan/mathlib
f2818da875dbc7780830d09bd4c526b0764a4e50
aad2dfc40e8e6a7e258287a7c1580318e865817e
refs/heads/master
1,661,736,426,952
1,590,438,032,000
1,590,438,032,000
266,892,663
0
0
Apache-2.0
1,590,445,835,000
1,590,445,835,000
null
UTF-8
Lean
false
false
57,842
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 } } end -- TODO(jmc): once adic topology lands, show that this is complete end comm_ring section nonzero_comm_ring variables [nonzero_comm_ring α] instance : nonzero_comm_ring (mv_power_series σ α) := { zero_ne_one := assume h, zero_ne_one $ show (0:α) = 1, from congr_arg (constant_coeff σ α) h, .. mv_power_series.comm_ring } 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_comm_ring 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) 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.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 [nonzero_comm_ring α] : nonzero_comm_ring (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.nonzero_comm_ring } /-- The ideal spanned by the variable in the power series ring over an integral domain is a prime ideal.-/ lemma span_X_is_prime : (ideal.span ({X} : set (power_series α))).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 [nonzero_comm_ring α] /-- 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
0352e05400db0f82955bd53eec737cdf62b8d0c1
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/category_theory/pempty.lean
9188797a5e7b2b2c397003fd21fc6ab9c434cc49
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
1,571
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Bhavik Mehta -/ import category_theory.discrete_category /-! # The empty category Defines a category structure on `pempty`, and the unique functor `pempty ⥤ C` for any category `C`. -/ universes w v u -- morphism levels before object levels. See note [category_theory universes]. namespace category_theory namespace functor variables (C : Type u) [category.{v} C] /-- Equivalence between two empty categories. -/ def empty_equivalence : discrete.{w} pempty ≌ discrete.{v} pempty := equivalence.mk { obj := pempty.elim ∘ discrete.as, map := λ x, x.as.elim } { obj := pempty.elim ∘ discrete.as, map := λ x, x.as.elim } (by tidy) (by tidy) /-- The canonical functor out of the empty category. -/ def empty : discrete.{w} pempty ⥤ C := discrete.functor pempty.elim variable {C} /-- Any two functors out of the empty category are isomorphic. -/ def empty_ext (F G : discrete.{w} pempty ⥤ C) : F ≅ G := discrete.nat_iso (λ x, x.as.elim) /-- Any functor out of the empty category is isomorphic to the canonical functor from the empty category. -/ def unique_from_empty (F : discrete.{w} pempty ⥤ C) : F ≅ empty C := empty_ext _ _ /-- Any two functors out of the empty category are *equal*. You probably want to use `empty_ext` instead of this. -/ lemma empty_ext' (F G : discrete.{w} pempty ⥤ C) : F = G := functor.ext (λ x, x.as.elim) (λ x _ _, x.as.elim) end functor end category_theory
1f01251b5e0db99ce61e9a08474e23728a7fbe07
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/algebra/category/CommRing/limits_auto.lean
1bc3fd92a29af4ebd2ff50924ac2c199e8749c97
[]
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,312
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 Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.algebra.ring.pi import Mathlib.algebra.category.CommRing.basic import Mathlib.algebra.category.Group.limits import Mathlib.ring_theory.subring import Mathlib.PostPort universes u u_1 namespace Mathlib /-! # The category of (commutative) rings has all limits Further, these limits are preserved by the forgetful functor --- that is, the underlying types are just the limits in the category of types. -/ namespace SemiRing protected instance semiring_obj {J : Type u} [category_theory.small_category J] (F : J ⥤ SemiRing) (j : J) : semiring (category_theory.functor.obj (F ⋙ category_theory.forget SemiRing) j) := id (SemiRing.semiring (category_theory.functor.obj F j)) /-- The flat sections of a functor into `SemiRing` form a subsemiring of all sections. -/ def sections_subsemiring {J : Type u} [category_theory.small_category J] (F : J ⥤ SemiRing) : subsemiring ((j : J) → ↥(category_theory.functor.obj F j)) := subsemiring.mk (category_theory.functor.sections (F ⋙ category_theory.forget SemiRing)) sorry sorry sorry sorry protected instance limit_semiring {J : Type u} [category_theory.small_category J] (F : J ⥤ SemiRing) : semiring (category_theory.limits.cone.X (category_theory.limits.types.limit_cone (F ⋙ category_theory.forget SemiRing))) := subsemiring.to_semiring (sections_subsemiring F) /-- `limit.π (F ⋙ forget SemiRing) j` as a `ring_hom`. -/ def limit_π_ring_hom {J : Type u} [category_theory.small_category J] (F : J ⥤ SemiRing) (j : J) : category_theory.limits.cone.X (category_theory.limits.types.limit_cone (F ⋙ category_theory.forget SemiRing)) →+* category_theory.functor.obj (F ⋙ category_theory.forget SemiRing) j := ring_hom.mk (category_theory.nat_trans.app (category_theory.limits.cone.π (category_theory.limits.types.limit_cone (F ⋙ category_theory.forget SemiRing))) j) sorry sorry sorry sorry namespace has_limits -- The next two definitions are used in the construction of `has_limits SemiRing`. -- After that, the limits should be constructed using the generic limits API, -- e.g. `limit F`, `limit.cone F`, and `limit.is_limit F`. /-- Construction of a limit cone in `SemiRing`. (Internal use only; use the limits API.) -/ def limit_cone {J : Type u} [category_theory.small_category J] (F : J ⥤ SemiRing) : category_theory.limits.cone F := category_theory.limits.cone.mk (of (category_theory.limits.cone.X (category_theory.limits.types.limit_cone (F ⋙ category_theory.forget SemiRing)))) (category_theory.nat_trans.mk (limit_π_ring_hom F)) /-- Witness that the limit cone in `SemiRing` is a limit cone. (Internal use only; use the limits API.) -/ def limit_cone_is_limit {J : Type u} [category_theory.small_category J] (F : J ⥤ SemiRing) : category_theory.limits.is_limit (limit_cone F) := category_theory.limits.is_limit.of_faithful (category_theory.forget SemiRing) (category_theory.limits.types.limit_cone_is_limit (F ⋙ category_theory.forget SemiRing)) (fun (s : category_theory.limits.cone F) => ring_hom.mk (fun (v : category_theory.limits.cone.X (category_theory.functor.map_cone (category_theory.forget SemiRing) s)) => { val := fun (j : J) => category_theory.nat_trans.app (category_theory.limits.cone.π (category_theory.functor.map_cone (category_theory.forget SemiRing) s)) j v, property := sorry }) sorry sorry sorry sorry) sorry end has_limits /-- The category of rings has all limits. -/ protected instance has_limits : category_theory.limits.has_limits SemiRing := category_theory.limits.has_limits.mk fun (J : Type u_1) (𝒥 : category_theory.small_category J) => category_theory.limits.has_limits_of_shape.mk fun (F : J ⥤ SemiRing) => category_theory.limits.has_limit.mk (category_theory.limits.limit_cone.mk sorry sorry) /-- An auxiliary declaration to speed up typechecking. -/ def forget₂_AddCommMon_preserves_limits_aux {J : Type u} [category_theory.small_category J] (F : J ⥤ SemiRing) : category_theory.limits.is_limit (category_theory.functor.map_cone (category_theory.forget₂ SemiRing AddCommMon) (has_limits.limit_cone F)) := AddCommMon.limit_cone_is_limit (F ⋙ category_theory.forget₂ SemiRing AddCommMon) /-- The forgetful functor from semirings to additive commutative monoids preserves all limits. -/ protected instance forget₂_AddCommMon_preserves_limits : category_theory.limits.preserves_limits (category_theory.forget₂ SemiRing AddCommMon) := category_theory.limits.preserves_limits.mk fun (J : Type u_1) (𝒥 : category_theory.small_category J) => category_theory.limits.preserves_limits_of_shape.mk fun (F : J ⥤ SemiRing) => category_theory.limits.preserves_limit_of_preserves_limit_cone (has_limits.limit_cone_is_limit F) (forget₂_AddCommMon_preserves_limits_aux F) /-- An auxiliary declaration to speed up typechecking. -/ def forget₂_Mon_preserves_limits_aux {J : Type u} [category_theory.small_category J] (F : J ⥤ SemiRing) : category_theory.limits.is_limit (category_theory.functor.map_cone (category_theory.forget₂ SemiRing Mon) (has_limits.limit_cone F)) := Mon.has_limits.limit_cone_is_limit (F ⋙ category_theory.forget₂ SemiRing Mon) /-- The forgetful functor from semirings to monoids preserves all limits. -/ protected instance forget₂_Mon_preserves_limits : category_theory.limits.preserves_limits (category_theory.forget₂ SemiRing Mon) := category_theory.limits.preserves_limits.mk fun (J : Type u_1) (𝒥 : category_theory.small_category J) => category_theory.limits.preserves_limits_of_shape.mk fun (F : J ⥤ SemiRing) => category_theory.limits.preserves_limit_of_preserves_limit_cone (has_limits.limit_cone_is_limit F) (forget₂_Mon_preserves_limits_aux F) /-- The forgetful functor from semirings to types preserves all limits. -/ protected instance forget_preserves_limits : category_theory.limits.preserves_limits (category_theory.forget SemiRing) := category_theory.limits.preserves_limits.mk fun (J : Type u_1) (𝒥 : category_theory.small_category J) => category_theory.limits.preserves_limits_of_shape.mk fun (F : J ⥤ SemiRing) => category_theory.limits.preserves_limit_of_preserves_limit_cone (has_limits.limit_cone_is_limit F) (category_theory.limits.types.limit_cone_is_limit (F ⋙ category_theory.forget SemiRing)) end SemiRing namespace CommSemiRing protected instance comm_semiring_obj {J : Type u} [category_theory.small_category J] (F : J ⥤ CommSemiRing) (j : J) : comm_semiring (category_theory.functor.obj (F ⋙ category_theory.forget CommSemiRing) j) := id (CommSemiRing.comm_semiring (category_theory.functor.obj F j)) protected instance limit_comm_semiring {J : Type u} [category_theory.small_category J] (F : J ⥤ CommSemiRing) : comm_semiring (category_theory.limits.cone.X (category_theory.limits.types.limit_cone (F ⋙ category_theory.forget CommSemiRing))) := subsemiring.to_comm_semiring (SemiRing.sections_subsemiring (F ⋙ category_theory.forget₂ CommSemiRing SemiRing)) /-- We show that the forgetful functor `CommSemiRing ⥤ SemiRing` creates limits. All we need to do is notice that the limit point has a `comm_semiring` instance available, and then reuse the existing limit. -/ protected instance category_theory.forget₂.category_theory.creates_limit {J : Type u} [category_theory.small_category J] (F : J ⥤ CommSemiRing) : category_theory.creates_limit F (category_theory.forget₂ CommSemiRing SemiRing) := sorry /-- A choice of limit cone for a functor into `CommSemiRing`. (Generally, you'll just want to use `limit F`.) -/ def limit_cone {J : Type u} [category_theory.small_category J] (F : J ⥤ CommSemiRing) : category_theory.limits.cone F := category_theory.lift_limit (category_theory.limits.limit.is_limit (F ⋙ category_theory.forget₂ CommSemiRing SemiRing)) /-- The chosen cone is a limit cone. (Generally, you'll just want to use `limit.cone F`.) -/ def limit_cone_is_limit {J : Type u} [category_theory.small_category J] (F : J ⥤ CommSemiRing) : category_theory.limits.is_limit (limit_cone F) := category_theory.lifted_limit_is_limit (category_theory.limits.limit.is_limit (F ⋙ category_theory.forget₂ CommSemiRing SemiRing)) /-- The category of rings has all limits. -/ protected instance has_limits : category_theory.limits.has_limits CommSemiRing := category_theory.limits.has_limits.mk fun (J : Type u) (𝒥 : category_theory.small_category J) => category_theory.limits.has_limits_of_shape.mk fun (F : J ⥤ CommSemiRing) => category_theory.has_limit_of_created F (category_theory.forget₂ CommSemiRing SemiRing) /-- The forgetful functor from rings to semirings preserves all limits. -/ protected instance forget₂_SemiRing_preserves_limits : category_theory.limits.preserves_limits (category_theory.forget₂ CommSemiRing SemiRing) := category_theory.limits.preserves_limits.mk fun (J : Type u_1) (𝒥 : category_theory.small_category J) => category_theory.limits.preserves_limits_of_shape.mk fun (F : J ⥤ CommSemiRing) => category_theory.preserves_limit_of_creates_limit_and_has_limit F (category_theory.forget₂ CommSemiRing SemiRing) /-- The forgetful functor from rings to types preserves all limits. (That is, the underlying types could have been computed instead as limits in the category of types.) -/ protected instance forget_preserves_limits : category_theory.limits.preserves_limits (category_theory.forget CommSemiRing) := category_theory.limits.preserves_limits.mk fun (J : Type u_1) (𝒥 : category_theory.small_category J) => category_theory.limits.preserves_limits_of_shape.mk fun (F : J ⥤ CommSemiRing) => category_theory.limits.comp_preserves_limit (category_theory.forget₂ CommSemiRing SemiRing) (category_theory.forget SemiRing) end CommSemiRing namespace Ring protected instance ring_obj {J : Type u} [category_theory.small_category J] (F : J ⥤ Ring) (j : J) : ring (category_theory.functor.obj (F ⋙ category_theory.forget Ring) j) := id (Ring.ring (category_theory.functor.obj F j)) /-- The flat sections of a functor into `Ring` form a subring of all sections. -/ def sections_subring {J : Type u} [category_theory.small_category J] (F : J ⥤ Ring) : subring ((j : J) → ↥(category_theory.functor.obj F j)) := subring.mk (category_theory.functor.sections (F ⋙ category_theory.forget Ring)) sorry sorry sorry sorry sorry protected instance limit_ring {J : Type u} [category_theory.small_category J] (F : J ⥤ Ring) : ring (category_theory.limits.cone.X (category_theory.limits.types.limit_cone (F ⋙ category_theory.forget Ring))) := subring.to_ring (sections_subring F) /-- We show that the forgetful functor `CommRing ⥤ Ring` creates limits. All we need to do is notice that the limit point has a `ring` instance available, and then reuse the existing limit. -/ protected instance category_theory.forget₂.category_theory.creates_limit {J : Type u} [category_theory.small_category J] (F : J ⥤ Ring) : category_theory.creates_limit F (category_theory.forget₂ Ring SemiRing) := sorry /-- A choice of limit cone for a functor into `Ring`. (Generally, you'll just want to use `limit F`.) -/ def limit_cone {J : Type u} [category_theory.small_category J] (F : J ⥤ Ring) : category_theory.limits.cone F := category_theory.lift_limit (category_theory.limits.limit.is_limit (F ⋙ category_theory.forget₂ Ring SemiRing)) /-- The chosen cone
bac73be0b971b7e757befc0886ba67f8d7c76a87
ae1e94c332e17c7dc7051ce976d5a9eebe7ab8a5
/tests/compiler/t4.lean
548dbfe9960f2d95609944139781847fad5f98c2
[ "Apache-2.0" ]
permissive
dupuisf/lean4
d082d13b01243e1de29ae680eefb476961221eef
6a39c65bd28eb0e28c3870188f348c8914502718
refs/heads/master
1,676,948,755,391
1,610,665,114,000
1,610,665,114,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,486
lean
#lang lean4 /- Benchmark for new code generator -/ inductive Expr | Val : Int → Expr | Var : String → Expr | Add : Expr → Expr → Expr | Mul : Expr → Expr → Expr | Pow : Expr → Expr → Expr | Ln : Expr → Expr namespace Expr protected def Expr.toString : Expr → String | Val n => toString n | Var x => x | Add f g => "(" ++ Expr.toString f ++ " + " ++ Expr.toString g ++ ")" | Mul f g => "(" ++ Expr.toString f ++ " * " ++ Expr.toString g ++ ")" | Pow f g => "(" ++ Expr.toString f ++ " ^ " ++ Expr.toString g ++ ")" | Ln f => "ln(" ++ Expr.toString f ++ ")" instance : ToString Expr := ⟨Expr.toString⟩ partial def pown : Int → Int → Int | a, 0 => 1 | a, 1 => a | a, n => let b := pown a (n / 2); b * b * (if n % 2 = 0 then 1 else a) partial def addAux : Expr → Expr → Expr | Val n, Val m => Val (n + m) | Val 0, f => f | f, Val 0 => f | f, Val n => addAux (Val n) f | Val n, Add (Val m) f => addAux (Val (n+m)) f | f, Add (Val n) g => addAux (Val n) (addAux f g) | Add f g, h => addAux f (addAux g h) | f, g => Add f g def add (a b : Expr) : Expr := -- dbgTrace (">> add (" ++ toString a ++ ", " ++ toString b ++ ")") $ fun _ => addAux a b -- set_option trace.compiler.borrowed_inference true partial def mulAux : Expr → Expr → Expr | Val n, Val m => Val (n*m) | Val 0, _ => Val 0 | _, Val 0 => Val 0 | Val 1, f => f | f, Val 1 => f | f, Val n => mulAux (Val n) f | Val n, Mul (Val m) f => mulAux (Val (n*m)) f | f, Mul (Val n) g => mulAux (Val n) (mulAux f g) | Mul f g, h => mulAux f (mulAux g h) | f, g => Mul f g def mul (a b : Expr) : Expr := -- dbgTrace (">> mul (" ++ toString a ++ ", " ++ toString b ++ ")") $ fun _ => mulAux a b def pow : Expr → Expr → Expr | Val m, Val n => Val (pown m n) | _, Val 0 => Val 1 | f, Val 1 => f | Val 0, _ => Val 0 | f, g => Pow f g def ln : Expr → Expr | Val 1 => Val 0 | f => Ln f def d (x : String) : Expr → Expr | Val _ => Val 0 | Var y => if x = y then Val 1 else Val 0 | Add f g => add (d x f) (d x g) | Mul f g => -- dbgTrace (">> d (" ++ toString f ++ ", " ++ toString g ++ ")") $ fun _ => add (mul f (d x g)) (mul g (d x f)) | Pow f g => mul (pow f g) (add (mul (mul g (d x f)) (pow f (Val (-1)))) (mul (ln f) (d x g))) | Ln f => mul (d x f) (pow f (Val (-1))) def count : Expr → Nat | Val _ => 1 | Var _ => 1 | Add f g => count f + count g | Mul f g => count f + count g | Pow f g => count f + count g | Ln f => count f def nestAux (s : Nat) (f : Nat → Expr → IO Expr) : Nat → Expr → IO Expr | 0, x => pure x | m@(n+1), x => f (s - m) x >>= nestAux s f n def nest (f : Nat → Expr → IO Expr) (n : Nat) (e : Expr) : IO Expr := nestAux n f n e def deriv (i : Nat) (f : Expr) : IO Expr := do let d := d "x" f; IO.println (toString (i+1) ++ " count: " ++ (toString $ count d)); IO.println (toString d); pure d end Expr def main (xs : List String) : IO UInt32 := do let x := Expr.Var "x"; let f := Expr.add x (Expr.mul x (Expr.mul x (Expr.add x x))); IO.println f; discard <| Expr.nest Expr.deriv 3 f; pure 0 -- setOption profiler True -- #eval main []
d5c7eb91e02a4734dbac7af4aa9d93877ff498a3
b00eb947a9c4141624aa8919e94ce6dcd249ed70
/tests/lean/binderCacheIssue.lean
204d2550ceff01c315ca17459e500f6c50b75d48
[ "Apache-2.0" ]
permissive
gebner/lean4-old
a4129a041af2d4d12afb3a8d4deedabde727719b
ee51cdfaf63ee313c914d83264f91f414a0e3b6e
refs/heads/master
1,683,628,606,745
1,622,651,300,000
1,622,654,405,000
142,608,821
1
0
null
null
null
null
UTF-8
Lean
false
false
616
lean
universes u v w class Funtype (N : Sort u) (O : outParam (Sort v)) (T : outParam (Sort w)) := pack : O -> N unpack : N -> O apply : N -> T class LNot {P : Sort u} (L : P -> Prop) := toFun : (p : P) -> Not (L p) namespace LNot variable {P : Sort u} {L : P -> Prop} abbrev applyFun (K : LNot L) {p} := K.toFun p abbrev unpackFun (K : LNot L) := K.toFun instance isFuntype : Funtype (LNot L) ((p : P) -> Not (L p)) ({p : P} -> Not (L p)) := {pack := mk, unpack := unpackFun, apply := applyFun} end LNot #check LNot.unpackFun #check LNot.isFuntype.unpack #check LNot.applyFun #check LNot.isFuntype.apply
81ba270e8759aa01c2afff37be5d39cdb6a834e5
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/ring_theory/dedekind_domain.lean
7b1c13a2ffe0f5e117e81686e0ad15cb27d7939f
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
10,101
lean
/- Copyright (c) 2020 Kenji Nakagawa. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenji Nakagawa, Anne Baanen, Filippo A. E. Nuccio -/ import ring_theory.discrete_valuation_ring import ring_theory.fractional_ideal import ring_theory.ideal.over /-! # Dedekind domains This file defines the notion of a Dedekind domain (or Dedekind ring), giving three equivalent definitions (TODO: and shows that they are equivalent). ## Main definitions - `is_dedekind_domain` defines a Dedekind domain as a commutative ring that is not a field, Noetherian, integrally closed in its field of fractions and has Krull dimension exactly one. `is_dedekind_domain_iff` shows that this does not depend on the choice of field of fractions. - `is_dedekind_domain_dvr` alternatively defines a Dedekind domain as an integral domain that is not a field, Noetherian, and the localization at every nonzero prime ideal is a DVR. - `is_dedekind_domain_inv` alternatively defines a Dedekind domain as an integral domain that is not a field, and every nonzero fractional ideal is invertible. - `is_dedekind_domain_inv_iff` shows that this does note depend on the choice of field of fractions. ## Implementation notes The definitions that involve a field of fractions choose a canonical field of fractions, but are independent of that choice. The `..._iff` lemmas express this independence. ## References * [D. Marcus, *Number Fields*][marcus1977number] * [J.W.S. Cassels, A. Frölich, *Algebraic Number Theory*][cassels1967algebraic] ## Tags dedekind domain, dedekind ring -/ variables (R A K : Type*) [comm_ring R] [integral_domain A] [field K] /-- A ring `R` has Krull dimension at most one if all nonzero prime ideals are maximal. -/ def ring.dimension_le_one : Prop := ∀ p ≠ (⊥ : ideal R), p.is_prime → p.is_maximal open ideal ring namespace ring lemma dimension_le_one.principal_ideal_ring [is_principal_ideal_ring A] : dimension_le_one A := λ p nonzero prime, by { haveI := prime, exact is_prime.to_maximal_ideal nonzero } lemma dimension_le_one.integral_closure [nontrivial R] [algebra R A] (h : dimension_le_one R) : dimension_le_one (integral_closure R A) := λ p ne_bot prime, by exactI integral_closure.is_maximal_of_is_maximal_comap p (h _ (integral_closure.comap_ne_bot ne_bot) infer_instance) end ring /-- A Dedekind domain is an integral domain that is Noetherian, integrally closed, and has Krull dimension exactly one (`not_is_field` and `dimension_le_one`). The integral closure condition is independent of the choice of field of fractions: use `is_dedekind_domain_iff` to prove `is_dedekind_domain` for a given `fraction_map`. This is the default implementation, but there are equivalent definitions, `is_dedekind_domain_dvr` and `is_dedekind_domain_inv`. TODO: Prove that these are actually equivalent definitions. -/ class is_dedekind_domain : Prop := (not_is_field : ¬ is_field A) (is_noetherian_ring : is_noetherian_ring A) (dimension_le_one : dimension_le_one A) (is_integrally_closed : integral_closure A (fraction_ring A) = ⊥) /-- An integral domain is a Dedekind domain iff and only if it is not a field, is Noetherian, has dimension ≤ 1, and is integrally closed in a given fraction field. In particular, this definition does not depend on the choice of this fraction field. -/ lemma is_dedekind_domain_iff (f : fraction_map A K) : is_dedekind_domain A ↔ (¬ is_field A) ∧ is_noetherian_ring A ∧ dimension_le_one A ∧ integral_closure A f.codomain = ⊥ := ⟨λ ⟨hf, hr, hd, hi⟩, ⟨hf, hr, hd, by rw [←integral_closure_map_alg_equiv (fraction_ring.alg_equiv_of_quotient f), hi, algebra.map_bot]⟩, λ ⟨hf, hr, hd, hi⟩, ⟨hf, hr, hd, by rw [←integral_closure_map_alg_equiv (fraction_ring.alg_equiv_of_quotient f).symm, hi, algebra.map_bot]⟩⟩ /-- A Dedekind domain is an integral domain that is not a field, is Noetherian, and the localization at every nonzero prime is a discrete valuation ring. This is equivalent to `is_dedekind_domain`. TODO: prove the equivalence. -/ structure is_dedekind_domain_dvr : Prop := (not_is_field : ¬ is_field A) (is_noetherian_ring : is_noetherian_ring A) (is_dvr_at_nonzero_prime : ∀ P ≠ (⊥ : ideal A), P.is_prime → discrete_valuation_ring (localization.at_prime P)) section inverse open_locale classical variables {R₁ : Type*} [integral_domain R₁] {g : fraction_map R₁ K} variables {I J : fractional_ideal g} noncomputable instance : has_inv (fractional_ideal g) := ⟨λ I, 1 / I⟩ lemma inv_eq : I⁻¹ = 1 / I := rfl lemma inv_zero' : (0 : fractional_ideal g)⁻¹ = 0 := fractional_ideal.div_zero lemma inv_nonzero {J : fractional_ideal g} (h : J ≠ 0) : J⁻¹ = ⟨(1 : fractional_ideal g) / J, fractional_ideal.fractional_div_of_nonzero h⟩ := fractional_ideal.div_nonzero _ lemma coe_inv_of_nonzero {J : fractional_ideal g} (h : J ≠ 0) : (↑J⁻¹ : submodule R₁ g.codomain) = g.coe_submodule 1 / J := by { rwa inv_nonzero _, refl, assumption} /-- `I⁻¹` is the inverse of `I` if `I` has an inverse. -/ theorem right_inverse_eq (I J : fractional_ideal g) (h : I * J = 1) : J = I⁻¹ := begin have hI : I ≠ 0 := fractional_ideal.ne_zero_of_mul_eq_one I J h, suffices h' : I * (1 / I) = 1, { exact (congr_arg units.inv $ @units.ext _ _ (units.mk_of_mul_eq_one _ _ h) (units.mk_of_mul_eq_one _ _ h') rfl) }, apply le_antisymm, { apply fractional_ideal.mul_le.mpr _, intros x hx y hy, rw mul_comm, exact (fractional_ideal.mem_div_iff_of_nonzero hI).mp hy x hx }, rw ← h, apply fractional_ideal.mul_left_mono I, apply (fractional_ideal.le_div_iff_of_nonzero hI).mpr _, intros y hy x hx, rw mul_comm, exact fractional_ideal.mul_mem_mul hx hy end theorem mul_inv_cancel_iff {I : fractional_ideal g} : I * I⁻¹ = 1 ↔ ∃ J, I * J = 1 := ⟨λ h, ⟨I⁻¹, h⟩, λ ⟨J, hJ⟩, by rwa [← @right_inverse_eq _ _ _ _ _ I J hJ]⟩ variables {K' : Type*} [field K'] {g' : fraction_map R₁ K'} @[simp] lemma map_inv (I : fractional_ideal g) (h : g.codomain ≃ₐ[R₁] g'.codomain) : (I⁻¹).map (h : g.codomain →ₐ[R₁] g'.codomain) = (I.map h)⁻¹ := by rw [inv_eq, fractional_ideal.map_div, fractional_ideal.map_one, inv_eq] open_locale classical open submodule submodule.is_principal @[simp] lemma span_singleton_inv (x : g.codomain) : (fractional_ideal.span_singleton x)⁻¹ = fractional_ideal.span_singleton (x⁻¹) := fractional_ideal.one_div_span_singleton x lemma mul_generator_self_inv (I : fractional_ideal g) [submodule.is_principal (I : submodule R₁ g.codomain)] (h : I ≠ 0) : I * fractional_ideal.span_singleton (generator (I : submodule R₁ g.codomain))⁻¹ = 1 := begin -- Rewrite only the `I` that appears alone. conv_lhs { congr, rw fractional_ideal.eq_span_singleton_of_principal I }, rw [fractional_ideal.span_singleton_mul_span_singleton, mul_inv_cancel, fractional_ideal.span_singleton_one], intro generator_I_eq_zero, apply h, rw [fractional_ideal.eq_span_singleton_of_principal I, generator_I_eq_zero, fractional_ideal.span_singleton_zero] end lemma invertible_of_principal (I : fractional_ideal g) [submodule.is_principal (I : submodule R₁ g.codomain)] (h : I ≠ 0) : I * I⁻¹ = 1 := (fractional_ideal.mul_div_self_cancel_iff).mpr ⟨fractional_ideal.span_singleton (generator (I : submodule R₁ g.codomain))⁻¹, @mul_generator_self_inv _ _ _ _ _ I _ h⟩ lemma invertible_iff_generator_nonzero (I : fractional_ideal g) [submodule.is_principal (I : submodule R₁ g.codomain)] : I * I⁻¹ = 1 ↔ generator (I : submodule R₁ g.codomain) ≠ 0 := begin split, { intros hI hg, apply fractional_ideal.ne_zero_of_mul_eq_one _ _ hI, rw [fractional_ideal.eq_span_singleton_of_principal I, hg, fractional_ideal.span_singleton_zero] }, { intro hg, apply invertible_of_principal, rw [fractional_ideal.eq_span_singleton_of_principal I], intro hI, have := fractional_ideal.mem_span_singleton_self (generator (I : submodule R₁ g.codomain)), rw [hI, fractional_ideal.mem_zero_iff] at this, contradiction } end lemma is_principal_inv (I : fractional_ideal g) [submodule.is_principal (I : submodule R₁ g.codomain)] (h : I ≠ 0) : submodule.is_principal (I⁻¹).1 := begin rw [fractional_ideal.val_eq_coe, fractional_ideal.is_principal_iff], use (generator (I : submodule R₁ g.codomain))⁻¹, have hI : I * fractional_ideal.span_singleton ((generator (I : submodule R₁ g.codomain))⁻¹) = 1, apply @mul_generator_self_inv _ _ _ _ _ I _ h, apply (@right_inverse_eq _ _ _ _ _ I (fractional_ideal.span_singleton ( (generator (I : submodule R₁ g.codomain))⁻¹)) hI).symm, end /-- A Dedekind domain is an integral domain that is not a field such that every fractional ideal has an inverse. This is equivalent to `is_dedekind_domain`. TODO: prove the equivalence. -/ structure is_dedekind_domain_inv : Prop := (not_is_field : ¬ is_field A) (mul_inv_cancel : ∀ I ≠ (⊥ : fractional_ideal (fraction_ring.of A)), I * (1 / I) = 1) open ring.fractional_ideal lemma is_dedekind_domain_inv_iff (f : fraction_map A K) : is_dedekind_domain_inv A ↔ (¬ is_field A) ∧ (∀ I ≠ (⊥ : fractional_ideal f), I * I⁻¹ = 1) := begin set h : (fraction_ring.of A).codomain ≃ₐ[A] f.codomain := fraction_ring.alg_equiv_of_quotient f, split; rintros ⟨hf, hi⟩; use hf; intros I hI, { have := hi (map ↑h.symm I) (map_ne_zero _ hI), convert congr_arg (map (h : (fraction_ring.of A).codomain →ₐ[A] f.codomain)) this; simp only [map_symm_map, map_one, fractional_ideal.map_mul, fractional_ideal.map_div, inv_eq] }, { have := hi (map ↑h I) (map_ne_zero _ hI), convert congr_arg (map (h.symm : f.codomain →ₐ[A] (fraction_ring.of A).codomain)) this; simp only [map_map_symm, map_one, fractional_ideal.map_mul, fractional_ideal.map_div, inv_eq] }, end end inverse
1259108804984c42099a0fcec3f4f77a7910b8b7
682dc1c167e5900ba3168b89700ae1cf501cfa29
/src/basicmodal/syntax/soundness.lean
01cb4d45b8485c637706e7dbe5388c8a0988c56d
[]
no_license
paulaneeley/modal
834558c87f55cdd6d8a29bb46c12f4d1de3239bc
ee5d149d4ecb337005b850bddf4453e56a5daf04
refs/heads/master
1,675,911,819,093
1,609,785,144,000
1,609,785,144,000
270,388,715
13
1
null
null
null
null
UTF-8
Lean
false
false
3,456
lean
/- Copyright (c) 2021 Paula Neeley. All rights reserved. Author: Paula Neeley -/ import basicmodal.language data.set.basic basicmodal.semantics.semantics import basicmodal.semantics.definability basicmodal.syntax.syntaxlemmas local attribute [instance] classical.prop_decidable ---------------------- Soundness ---------------------- theorem soundness (AX : ctx) (φ : form) : prfK AX φ → global_sem_csq AX φ := begin intro h, induction h, {intros f v h x, exact (h h_φ x) h_h}, {intros f v x h2 h3 h4, exact h3}, {intros f v x h2 h3 h4 h5, apply h3, exact h5, apply h4, exact h5}, {intros f x v h1 h2 h3, by_contradiction h4, exact (h2 h4) (h3 h4)}, {intros f v x h1 h2 h3, exact and.intro h2 h3}, {intros f v x h1 h2, exact h2.left}, {intros f v x h1 h2, exact h2.right}, {intros f v x h1 h2 h3, repeat {rw forces at h2}, repeat {rw imp_false at h2}, rw not_imp_not at h2, exact h2 h3}, {intros f v x h1 h2 h3 x' h4, exact h2 x' h4 (h3 x' h4)}, {intros f v x h, exact (h_ih_hpq f v x h) (h_ih_hp f v x h)}, {intros f v h1 x y h2, exact h_ih f v h1 y}, end lemma soundnesshelper {Γ : ctx} {φ : form} {C : set (frame)} : prfK Γ φ → (∀ ψ ∈ Γ, F_valid ψ C) → F_valid φ C := begin intros h1 h2 f h3 v, induction h1, {intro x, exact h2 h1_φ h1_h f h3 v x}, {intros x h4 h5, exact h4}, {intros x h4 h5 h6, exact (h4 h6) (h5 h6)}, {intros x h3 h4, by_contradiction h5, specialize h3 h5, rw ←not_forces_imp at h3, exact h3 (h4 h5)}, {intros x h4 h5, exact and.intro h4 h5}, {intros x h4, exact h4.left}, {intros x h4, exact h4.right}, {intros x h4 h5, repeat {rw forces at h4}, repeat {rw imp_false at h4}, rw not_imp_not at h4, exact h4 h5}, {intros x h3 h4, intros x' h5, exact (h3 x' h5) (h4 x' h5)}, {intro x, exact h1_ih_hpq h2 x (h1_ih_hp h2 x)}, {intros x y h3, apply h1_ih, exact h2} end lemma inclusion_valid {C C' : set (frame)} : ∀ ψ, C ⊆ C' → F_valid ψ C' → F_valid ψ C := begin intros φ h1 h2 f h3 v x, exact h2 f (set.mem_of_subset_of_mem h1 h3) v x end def T_axioms : ctx := {φ : form | ∃ ψ, φ = (□ ψ ⊃ ψ)} def S4_axioms : ctx := T_axioms ∪ {φ : form | ∃ ψ, φ = (□ ψ ⊃ □ (□ ψ))} def S5_axioms : ctx := T_axioms ∪ {φ : form | ∃ ψ, φ = (◇ ψ ⊃ □ (◇ ψ))} lemma T_helper : ∀ φ ∈ T_axioms, F_valid φ ref_class := begin intros φ h1 f h2 v x, cases h1 with ψ h1, subst h1, apply ref_helper, exact h2 end theorem T_soundness (φ : form) : prfK T_axioms φ → F_valid φ ref_class := begin intro h, apply soundnesshelper, apply h, apply T_helper end lemma S4_helper : ∀ φ ∈ S4_axioms, F_valid φ ref_trans_class := begin intros φ h1 f h2 v x, cases h2 with h2l h2r, cases h1 with h1 h3, {apply T_helper, exact h1, exact h2l}, {cases h3 with ψ h3, subst h3, apply trans_helper, exact h2r} end theorem S4_soundness (φ : form) : prfK S4_axioms φ → F_valid φ ref_trans_class := begin intro h, apply soundnesshelper, apply h, apply S4_helper end lemma S5_helper : ∀ φ ∈ S5_axioms, F_valid φ equiv_class := begin intros φ h1 f h2 v x, cases h2 with h2l h2r, cases h2r with h2r h2rr, cases h1 with h1 h3, {apply T_helper, exact h1, exact h2l}, {cases h3 with ψ h3, dsimp at h3, subst h3, apply euclid_helper, intros x y z h1 h2, exact h2rr (h2r h1) h2} end theorem S5_soundness (φ : form) : prfK S5_axioms φ → F_valid φ equiv_class := begin intro h, apply soundnesshelper, apply h, apply S5_helper end
1a32a42506dba1dde8276c9845514bfeab35a5b7
54deab7025df5d2df4573383df7e1e5497b7a2c2
/data/nat/sub.lean
453128851a8bb9901a05a4c22ff4244624e7f1c8
[ "Apache-2.0" ]
permissive
HGldJ1966/mathlib
f8daac93a5b4ae805cfb0ecebac21a9ce9469009
c5c5b504b918a6c5e91e372ee29ed754b0513e85
refs/heads/master
1,611,340,395,683
1,503,040,489,000
1,503,040,489,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
6,291
lean
/- Copyright (c) 2014 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Jeremy Avigad Subtraction on the natural numbers, as well as min, max, and distance. -/ import data.nat.basic namespace nat /- interaction with inequalities -/ protected theorem le_sub_add (n m : ℕ) : n ≤ n - m + m := or.elim (le_total n m) (assume : n ≤ m, begin rw [sub_eq_zero_of_le this, zero_add], exact this end) (assume : m ≤ n, begin rw (nat.sub_add_cancel this) end) protected theorem sub_eq_of_eq_add {n m k : ℕ} (h : k = n + m) : k - n = m := begin rw [h, nat.add_sub_cancel_left] end protected theorem lt_of_sub_pos {m n : ℕ} (h : n - m > 0) : m < n := lt_of_not_ge (assume : m ≥ n, have n - m = 0, from sub_eq_zero_of_le this, begin rw this at h, exact lt_irrefl _ h end) protected theorem lt_of_sub_lt_sub_right {n m k : ℕ} (h : n - k < m - k) : n < m := lt_of_not_ge (assume : m ≤ n, have m - k ≤ n - k, from nat.sub_le_sub_right this _, not_le_of_gt h this) protected theorem lt_of_sub_lt_sub_left {n m k : ℕ} (h : n - m < n - k) : k < m := lt_of_not_ge (assume : m ≤ k, have n - k ≤ n - m, from nat.sub_le_sub_left _ this, not_le_of_gt h this) protected theorem sub_lt_self {m n : ℕ} (h₁ : m > 0) (h₂ : n > 0) : m - n < m := calc m - n = succ (pred m) - succ (pred n) : by rw [succ_pred_eq_of_pos h₁, succ_pred_eq_of_pos h₂] ... = pred m - pred n : by rw succ_sub_succ ... ≤ pred m : sub_le _ _ ... < succ (pred m) : lt_succ_self _ ... = m : succ_pred_eq_of_pos h₁ protected theorem le_sub_of_add_le {m n k : ℕ} (h : m + k ≤ n) : m ≤ n - k := calc m = m + k - k : by rw nat.add_sub_cancel ... ≤ n - k : nat.sub_le_sub_right h k protected theorem lt_sub_of_add_lt {m n k : ℕ} (h : m + k < n) : m < n - k := lt_of_succ_le (nat.le_sub_of_add_le (calc succ m + k = succ (m + k) : by rw succ_add ... ≤ n : succ_le_of_lt h)) protected theorem add_lt_of_lt_sub {m n k : ℕ} (h : m < n - k) : m + k < n := @nat.lt_of_sub_lt_sub_right _ _ k (by rwa nat.add_sub_cancel) protected theorem sub_lt_of_lt_add {k n m : nat} (h₁ : k < n + m) (h₂ : n ≤ k) : k - n < m := have succ k ≤ n + m, from succ_le_of_lt h₁, have succ (k - n) ≤ m, from calc succ (k - n) = succ k - n : by rw (succ_sub h₂) ... ≤ n + m - n : nat.sub_le_sub_right this n ... = m : by rw nat.add_sub_cancel_left, lt_of_succ_le this /- distance -/ def dist (n m : ℕ) := (n - m) + (m - n) theorem dist.def (n m : ℕ) : dist n m = (n - m) + (m - n) := rfl @[simp] theorem dist_comm (n m : ℕ) : dist n m = dist m n := by simp [dist.def] @[simp] theorem dist_self (n : ℕ) : dist n n = 0 := by simp [dist.def, nat.sub_self] theorem eq_of_dist_eq_zero {n m : ℕ} (h : dist n m = 0) : n = m := have n - m = 0, from eq_zero_of_add_eq_zero_right h, have n ≤ m, from nat.le_of_sub_eq_zero this, have m - n = 0, from eq_zero_of_add_eq_zero_left h, have m ≤ n, from nat.le_of_sub_eq_zero this, le_antisymm ‹n ≤ m› ‹m ≤ n› theorem dist_eq_zero {n m : ℕ} (h : n = m) : dist n m = 0 := begin rw [h, dist_self] end theorem dist_eq_sub_of_le {n m : ℕ} (h : n ≤ m) : dist n m = m - n := begin rw [dist.def, sub_eq_zero_of_le h, zero_add] end theorem dist_eq_sub_of_ge {n m : ℕ} (h : n ≥ m) : dist n m = n - m := begin rw [dist_comm], apply dist_eq_sub_of_le h end theorem dist_zero_right (n : ℕ) : dist n 0 = n := eq.trans (dist_eq_sub_of_ge (zero_le n)) (nat.sub_zero n) theorem dist_zero_left (n : ℕ) : dist 0 n = n := eq.trans (dist_eq_sub_of_le (zero_le n)) (nat.sub_zero n) theorem dist_add_add_right (n k m : ℕ) : dist (n + k) (m + k) = dist n m := calc dist (n + k) (m + k) = ((n + k) - (m + k)) + ((m + k)-(n + k)) : rfl ... = (n - m) + ((m + k) - (n + k)) : by rw nat.add_sub_add_right ... = (n - m) + (m - n) : by rw nat.add_sub_add_right theorem dist_add_add_left (k n m : ℕ) : dist (k + n) (k + m) = dist n m := begin rw [add_comm k n, add_comm k m], apply dist_add_add_right end theorem dist_eq_intro {n m k l : ℕ} (h : n + m = k + l) : dist n k = dist l m := calc dist n k = dist (n + m) (k + m) : by rw dist_add_add_right ... = dist (k + l) (k + m) : by rw h ... = dist l m : by rw dist_add_add_left protected theorem sub_lt_sub_add_sub (n m k : ℕ) : n - k ≤ (n - m) + (m - k) := or.elim (le_total k m) (assume : k ≤ m, begin rw ←nat.add_sub_assoc this, apply nat.sub_le_sub_right, apply nat.le_sub_add end) (assume : k ≥ m, begin rw [sub_eq_zero_of_le this, add_zero], apply nat.sub_le_sub_left, exact this end) theorem dist.triangle_inequality (n m k : ℕ) : dist n k ≤ dist n m + dist m k := have dist n m + dist m k = (n - m) + (m - k) + ((k - m) + (m - n)), by simp [dist.def], begin rw [this, dist.def], apply add_le_add, repeat { apply nat.sub_lt_sub_add_sub } end theorem dist_mul_right (n k m : ℕ) : dist (n * k) (m * k) = dist n m * k := by rw [dist.def, dist.def, right_distrib, nat.mul_sub_right_distrib, nat.mul_sub_right_distrib] theorem dist_mul_left (k n m : ℕ) : dist (k * n) (k * m) = k * dist n m := by rw [mul_comm k n, mul_comm k m, dist_mul_right, mul_comm] -- TODO(Jeremy): do when we have max and minx --theorem dist_eq_max_sub_min {i j : nat} : dist i j = (max i j) - min i j := --sorry /- or.elim (lt_or_ge i j) (assume : i < j, by rw [max_eq_right_of_lt this, min_eq_left_of_lt this, dist_eq_sub_of_lt this]) (assume : i ≥ j, by rw [max_eq_left this , min_eq_right this, dist_eq_sub_of_ge this]) -/ theorem dist_succ_succ {i j : nat} : dist (succ i) (succ j) = dist i j := by simp [dist.def, succ_sub_succ] theorem dist_pos_of_ne {i j : nat} : i ≠ j → dist i j > 0 := assume hne, nat.lt_by_cases (assume : i < j, begin rw [dist_eq_sub_of_le (le_of_lt this)], apply nat.sub_pos_of_lt this end) (assume : i = j, by contradiction) (assume : i > j, begin rw [dist_eq_sub_of_ge (le_of_lt this)], apply nat.sub_pos_of_lt this end) end nat
42c17cefb17ff2a4cd5fb6dd0c1d5d61a26a913f
4fa161becb8ce7378a709f5992a594764699e268
/src/category_theory/simple.lean
22088fe0a8196631c31d213e18c816654006cd9c
[ "Apache-2.0" ]
permissive
laughinggas/mathlib
e4aa4565ae34e46e834434284cb26bd9d67bc373
86dcd5cda7a5017c8b3c8876c89a510a19d49aad
refs/heads/master
1,669,496,232,688
1,592,831,995,000
1,592,831,995,000
274,155,979
0
0
Apache-2.0
1,592,835,190,000
1,592,835,189,000
null
UTF-8
Lean
false
false
3,919
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Markus Himmel, Scott Morrison -/ import category_theory.limits.shapes.zero import category_theory.limits.shapes.kernels import category_theory.abelian.basic open category_theory.limits namespace category_theory universes v u variables {C : Type u} [category.{v} C] section variables [has_zero_morphisms.{v} C] /-- An object is simple if monomorphisms into it are (exclusively) either isomorphisms or zero. -/ -- This is a constructive definition, from which we can extract an inverse for `f` given `f ≠ 0`. -- We show below that although it contains data, it is a subsingleton. class simple (X : C) : Type (max u v) := (mono_is_iso_equiv_nonzero : ∀ {Y : C} (f : Y ⟶ X) [mono f], is_iso.{v} f ≃ (f ≠ 0)) @[ext] lemma simple.ext {X : C} {a b : simple.{v} X} : a = b := begin unfreezeI, cases a, cases b, congr, funext Y f m, ext, refl, end instance subsingleton_simple (X : C) : subsingleton (simple.{v} X) := subsingleton.intro (@simple.ext _ _ _ X) /-- A nonzero monomorphism to a simple object is an isomorphism. -/ def is_iso_of_mono_of_nonzero {X Y : C} [simple.{v} Y] {f : X ⟶ Y} [mono f] (w : f ≠ 0) : is_iso f := (simple.mono_is_iso_equiv_nonzero f).symm w lemma kernel_zero_of_nonzero_from_simple {X Y : C} [simple.{v} X] {f : X ⟶ Y} [has_kernel f] (w : f ≠ 0) : kernel.ι f = 0 := begin classical, by_contradiction h, haveI := is_iso_of_mono_of_nonzero h, exact w (eq_zero_of_epi_kernel f), end lemma mono_to_simple_zero_of_not_iso {X Y : C} [simple.{v} Y] {f : X ⟶ Y} [mono f] (w : is_iso.{v} f → false) : f = 0 := begin classical, by_contradiction h, apply w, exact is_iso_of_mono_of_nonzero h, end section variable [has_zero_object.{v} C] local attribute [instance] has_zero_object.has_zero /-- We don't want the definition of 'simple' to include the zero object, so we check that here. -/ lemma zero_not_simple [simple.{v} (0 : C)] : false := (simple.mono_is_iso_equiv_nonzero (0 : (0 : C) ⟶ (0 : C))) { inv := 0, } rfl end end -- We next make the dual arguments, but for this we must be in an abelian category. section abelian variables [abelian.{v} C] /-- In an abelian category, an object satisfying the dual of the definition of a simple object is simple. -/ def simple_of_cosimple (X : C) (h : ∀ {Z : C} (f : X ⟶ Z) [epi f], is_iso.{v} f ≃ (f ≠ 0)) : simple.{v} X := ⟨λ Y f I, begin classical, apply equiv_of_subsingleton_of_subsingleton, { introsI, have hx := cokernel.π_of_epi f, by_contradiction h, push_neg at h, subst h, exact h _ (cokernel.π_of_zero _ _) hx }, { intro hf, suffices : epi f, { apply abelian.is_iso_of_mono_of_epi }, apply preadditive.epi_of_cokernel_zero, by_contradiction h', exact cokernel_not_iso_of_nonzero hf ((h _).symm h') } end⟩ /-- A nonzero epimorphism from a simple object is an isomorphism. -/ def is_iso_of_epi_of_nonzero {X Y : C} [simple.{v} X] {f : X ⟶ Y} [epi f] (w : f ≠ 0) : is_iso f := begin -- `f ≠ 0` means that `kernel.ι f` is not an iso, and hence zero, and hence `f` is a mono. haveI : mono f := preadditive.mono_of_kernel_zero (mono_to_simple_zero_of_not_iso (kernel_not_iso_of_nonzero w)), exact abelian.is_iso_of_mono_of_epi f, end lemma cokernel_zero_of_nonzero_to_simple {X Y : C} [simple.{v} Y] {f : X ⟶ Y} [has_cokernel f] (w : f ≠ 0) : cokernel.π f = 0 := begin classical, by_contradiction h, haveI := is_iso_of_epi_of_nonzero h, exact w (eq_zero_of_mono_cokernel f), end lemma epi_from_simple_zero_of_not_iso {X Y : C} [simple.{v} X] {f : X ⟶ Y} [epi f] (w : is_iso.{v} f → false) : f = 0 := begin classical, by_contradiction h, apply w, exact is_iso_of_epi_of_nonzero h, end end abelian end category_theory
45cb7e337533b693a9a68bb1e4b4f007de0cf55e
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/algebra/continued_fractions/computation/approximations.lean
332d061f9549b73757301533288ff3e7f2ec6c8b
[ "Apache-2.0" ]
permissive
AntoineChambert-Loir/mathlib
64aabb896129885f12296a799818061bc90da1ff
07be904260ab6e36a5769680b6012f03a4727134
refs/heads/master
1,693,187,631,771
1,636,719,886,000
1,636,719,886,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
29,787
lean
/- Copyright (c) 2020 Kevin Kappelmann. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Kappelmann -/ import algebra.continued_fractions.computation.correctness_terminating import data.nat.fib import tactic.solve_by_elim /-! # Approximations for Continued Fraction Computations (`generalized_continued_fraction.of`) ## Summary This file contains useful approximations for the values involved in the continued fractions computation `generalized_continued_fraction.of`. In particular, we derive the so-called *determinant formula* for `generalized_continued_fraction.of`: `Aₙ * Bₙ₊₁ - Bₙ * Aₙ₊₁ = (-1)^(n + 1)`. Moreover, we derive some upper bounds for the error term when computing a continued fraction up a given position, i.e. bounds for the term `|v - (generalized_continued_fraction.of v).convergents n|`. The derived bounds will show us that the error term indeed gets smaller. As a corollary, we will be able to show that `(generalized_continued_fraction.of v).convergents` converges to `v` in `algebra.continued_fractions.computation.approximation_corollaries`. ## Main Theorems - `generalized_continued_fraction.of_part_num_eq_one`: shows that all partial numerators `aᵢ` are equal to one. - `generalized_continued_fraction.exists_int_eq_of_part_denom`: shows that all partial denominators `bᵢ` correspond to an integer. - `generalized_continued_fraction.one_le_of_nth_part_denom`: shows that `1 ≤ bᵢ`. - `generalized_continued_fraction.succ_nth_fib_le_of_nth_denom`: shows that the `n`th denominator `Bₙ` is greater than or equal to the `n + 1`th fibonacci number `nat.fib (n + 1)`. - `generalized_continued_fraction.le_of_succ_nth_denom`: shows that `bₙ * Bₙ ≤ Bₙ₊₁`, where `bₙ` is the `n`th partial denominator of the continued fraction. - `generalized_continued_fraction.abs_sub_convergents_le`: shows that `|v - Aₙ / Bₙ| ≤ 1 / (Bₙ * Bₙ₊₁)`, where `Aₙ` is the nth partial numerator. ## References - [*Hardy, GH and Wright, EM and Heath-Brown, Roger and Silverman, Joseph*][hardy2008introduction] - https://en.wikipedia.org/wiki/Generalized_continued_fraction#The_determinant_formula -/ namespace generalized_continued_fraction open generalized_continued_fraction (of) int variables {K : Type*} {v : K} {n : ℕ} [linear_ordered_field K] [floor_ring K] namespace int_fract_pair /-! We begin with some lemmas about the stream of `int_fract_pair`s, which presumably are not of great interest for the end user. -/ /-- Shows that the fractional parts of the stream are in `[0,1)`. -/ lemma nth_stream_fr_nonneg_lt_one {ifp_n : int_fract_pair K} (nth_stream_eq : int_fract_pair.stream v n = some ifp_n) : 0 ≤ ifp_n.fr ∧ ifp_n.fr < 1 := begin cases n, case nat.zero { have : int_fract_pair.of v = ifp_n, by injection nth_stream_eq, rw [←this, int_fract_pair.of], exact ⟨fract_nonneg _, fract_lt_one _⟩ }, case nat.succ { rcases (succ_nth_stream_eq_some_iff.elim_left nth_stream_eq) with ⟨_, _, _, ifp_of_eq_ifp_n⟩, rw [←ifp_of_eq_ifp_n, int_fract_pair.of], exact ⟨fract_nonneg _, fract_lt_one _⟩ } end /-- Shows that the fractional parts of the stream are nonnegative. -/ lemma nth_stream_fr_nonneg {ifp_n : int_fract_pair K} (nth_stream_eq : int_fract_pair.stream v n = some ifp_n) : 0 ≤ ifp_n.fr := (nth_stream_fr_nonneg_lt_one nth_stream_eq).left /-- Shows that the fractional parts of the stream are smaller than one. -/ lemma nth_stream_fr_lt_one {ifp_n : int_fract_pair K} (nth_stream_eq : int_fract_pair.stream v n = some ifp_n) : ifp_n.fr < 1 := (nth_stream_fr_nonneg_lt_one nth_stream_eq).right /-- Shows that the integer parts of the stream are at least one. -/ lemma one_le_succ_nth_stream_b {ifp_succ_n : int_fract_pair K} (succ_nth_stream_eq : int_fract_pair.stream v (n + 1) = some ifp_succ_n) : 1 ≤ ifp_succ_n.b := begin obtain ⟨ifp_n, nth_stream_eq, stream_nth_fr_ne_zero, ⟨-⟩⟩ : ∃ ifp_n, int_fract_pair.stream v n = some ifp_n ∧ ifp_n.fr ≠ 0 ∧ int_fract_pair.of ifp_n.fr⁻¹ = ifp_succ_n, from succ_nth_stream_eq_some_iff.elim_left succ_nth_stream_eq, suffices : 1 ≤ ifp_n.fr⁻¹, { rw_mod_cast [le_floor], assumption }, suffices : ifp_n.fr ≤ 1, { have h : 0 < ifp_n.fr, from lt_of_le_of_ne (nth_stream_fr_nonneg nth_stream_eq) stream_nth_fr_ne_zero.symm, apply one_le_inv h this }, simp only [le_of_lt (nth_stream_fr_lt_one nth_stream_eq)] end /-- Shows that the `n + 1`th integer part `bₙ₊₁` of the stream is smaller or equal than the inverse of the `n`th fractional part `frₙ` of the stream. This result is straight-forward as `bₙ₊₁` is defined as the floor of `1 / frₙ` -/ lemma succ_nth_stream_b_le_nth_stream_fr_inv {ifp_n ifp_succ_n : int_fract_pair K} (nth_stream_eq : int_fract_pair.stream v n = some ifp_n) (succ_nth_stream_eq : int_fract_pair.stream v (n + 1) = some ifp_succ_n) : (ifp_succ_n.b : K) ≤ ifp_n.fr⁻¹ := begin suffices : (⌊ifp_n.fr⁻¹⌋ : K) ≤ ifp_n.fr⁻¹, { cases ifp_n with _ ifp_n_fr, have : ifp_n_fr ≠ 0, { intro h, simpa [h, int_fract_pair.stream, nth_stream_eq] using succ_nth_stream_eq }, have : int_fract_pair.of ifp_n_fr⁻¹ = ifp_succ_n, { simpa [this, int_fract_pair.stream, nth_stream_eq, option.coe_def] using succ_nth_stream_eq }, rwa ←this }, exact (floor_le ifp_n.fr⁻¹) end end int_fract_pair /-! Next we translate above results about the stream of `int_fract_pair`s to the computed continued fraction `generalized_continued_fraction.of`. -/ /-- Shows that the integer parts of the continued fraction are at least one. -/ lemma of_one_le_nth_part_denom {b : K} (nth_part_denom_eq : (of v).partial_denominators.nth n = some b) : 1 ≤ b := begin obtain ⟨gp_n, nth_s_eq, ⟨-⟩⟩ : ∃ gp_n, (of v).s.nth n = some gp_n ∧ gp_n.b = b, from exists_s_b_of_part_denom nth_part_denom_eq, obtain ⟨ifp_n, succ_nth_stream_eq, ifp_n_b_eq_gp_n_b⟩ : ∃ ifp, int_fract_pair.stream v (n + 1) = some ifp ∧ (ifp.b : K) = gp_n.b, from int_fract_pair.exists_succ_nth_stream_of_gcf_of_nth_eq_some nth_s_eq, rw [←ifp_n_b_eq_gp_n_b], exact_mod_cast (int_fract_pair.one_le_succ_nth_stream_b succ_nth_stream_eq) end /-- Shows that the partial numerators `aᵢ` of the continued fraction are equal to one and the partial denominators `bᵢ` correspond to integers. -/ lemma of_part_num_eq_one_and_exists_int_part_denom_eq {gp : generalized_continued_fraction.pair K} (nth_s_eq : (of v).s.nth n = some gp) : gp.a = 1 ∧ ∃ (z : ℤ), gp.b = (z : K) := begin obtain ⟨ifp, stream_succ_nth_eq, -⟩ : ∃ ifp, int_fract_pair.stream v (n + 1) = some ifp ∧ _, from int_fract_pair.exists_succ_nth_stream_of_gcf_of_nth_eq_some nth_s_eq, have : gp = ⟨1, ifp.b⟩, by { have : (of v).s.nth n = some ⟨1, ifp.b⟩, from nth_of_eq_some_of_succ_nth_int_fract_pair_stream stream_succ_nth_eq, have : some gp = some ⟨1, ifp.b⟩, by rwa nth_s_eq at this, injection this }, finish end /-- Shows that the partial numerators `aᵢ` are equal to one. -/ lemma of_part_num_eq_one {a : K} (nth_part_num_eq : (of v).partial_numerators.nth n = some a) : a = 1 := begin obtain ⟨gp, nth_s_eq, gp_a_eq_a_n⟩ : ∃ gp, (of v).s.nth n = some gp ∧ gp.a = a, from exists_s_a_of_part_num nth_part_num_eq, have : gp.a = 1, from (of_part_num_eq_one_and_exists_int_part_denom_eq nth_s_eq).left, rwa gp_a_eq_a_n at this end /-- Shows that the partial denominators `bᵢ` correspond to an integer. -/ lemma exists_int_eq_of_part_denom {b : K} (nth_part_denom_eq : (of v).partial_denominators.nth n = some b) : ∃ (z : ℤ), b = (z : K) := begin obtain ⟨gp, nth_s_eq, gp_b_eq_b_n⟩ : ∃ gp, (of v).s.nth n = some gp ∧ gp.b = b, from exists_s_b_of_part_denom nth_part_denom_eq, have : ∃ (z : ℤ), gp.b = (z : K), from (of_part_num_eq_one_and_exists_int_part_denom_eq nth_s_eq).right, rwa gp_b_eq_b_n at this end /-! One of our next goals is to show that `bₙ * Bₙ ≤ Bₙ₊₁`. For this, we first show that the partial denominators `Bₙ` are bounded from below by the fibonacci sequence `nat.fib`. This then implies that `0 ≤ Bₙ` and hence `Bₙ₊₂ = bₙ₊₁ * Bₙ₊₁ + Bₙ ≥ bₙ₊₁ * Bₙ₊₁ + 0 = bₙ₊₁ * Bₙ₊₁`. -/ -- open `nat` as we will make use of fibonacci numbers. open nat lemma fib_le_of_continuants_aux_b : (n ≤ 1 ∨ ¬(of v).terminated_at (n - 2)) → (fib n : K) ≤ ((of v).continuants_aux n).b := nat.strong_induction_on n begin clear n, assume n IH hyp, rcases n with _|_|n, { simp [fib_succ_succ, continuants_aux] }, -- case n = 0 { simp [fib_succ_succ, continuants_aux] }, -- case n = 1 { let g := of v, -- case 2 ≤ n have : ¬(n + 2 ≤ 1), by linarith, have not_terminated_at_n : ¬g.terminated_at n, from or.resolve_left hyp this, obtain ⟨gp, s_ppred_nth_eq⟩ : ∃ gp, g.s.nth n = some gp, from option.ne_none_iff_exists'.mp not_terminated_at_n, set pconts := g.continuants_aux (n + 1) with pconts_eq, set ppconts := g.continuants_aux n with ppconts_eq, -- use the recurrence of continuants_aux suffices : (fib n : K) + fib (n + 1) ≤ gp.a * ppconts.b + gp.b * pconts.b, by simpa [fib_succ_succ, add_comm, (continuants_aux_recurrence s_ppred_nth_eq ppconts_eq pconts_eq)], -- make use of the fact that gp.a = 1 suffices : (fib n : K) + fib (n + 1) ≤ ppconts.b + gp.b * pconts.b, by simpa [(of_part_num_eq_one $ part_num_eq_s_a s_ppred_nth_eq)], have not_terminated_at_pred_n : ¬g.terminated_at (n - 1), from mt (terminated_stable $ nat.sub_le n 1) not_terminated_at_n, have not_terminated_at_ppred_n : ¬terminated_at g (n - 2), from mt (terminated_stable (n - 1).pred_le) not_terminated_at_pred_n, -- use the IH to get the inequalities for `pconts` and `ppconts` have : (fib (n + 1) : K) ≤ pconts.b, from IH _ (nat.lt.base $ n + 1) (or.inr not_terminated_at_pred_n), have ppred_nth_fib_le_ppconts_B : (fib n : K) ≤ ppconts.b, from IH n (lt_trans (nat.lt.base n) $ nat.lt.base $ n + 1) (or.inr not_terminated_at_ppred_n), suffices : (fib (n + 1) : K) ≤ gp.b * pconts.b, solve_by_elim [add_le_add ppred_nth_fib_le_ppconts_B], -- finally use the fact that 1 ≤ gp.b to solve the goal suffices : 1 * (fib (n + 1) : K) ≤ gp.b * pconts.b, by rwa [one_mul] at this, have one_le_gp_b : (1 : K) ≤ gp.b, from of_one_le_nth_part_denom (part_denom_eq_s_b s_ppred_nth_eq), have : (0 : K) ≤ fib (n + 1), by exact_mod_cast (fib (n + 1)).zero_le, have : (0 : K) ≤ gp.b, from le_trans zero_le_one one_le_gp_b, mono } end /-- Shows that the `n`th denominator is greater than or equal to the `n + 1`th fibonacci number, that is `nat.fib (n + 1) ≤ Bₙ`. -/ lemma succ_nth_fib_le_of_nth_denom (hyp: n = 0 ∨ ¬(of v).terminated_at (n - 1)) : (fib (n + 1) : K) ≤ (of v).denominators n := begin rw [denom_eq_conts_b, nth_cont_eq_succ_nth_cont_aux], have : (n + 1) ≤ 1 ∨ ¬(of v).terminated_at (n - 1), by { cases n, case nat.zero : { exact (or.inl $ le_refl 1) }, case nat.succ : { exact or.inr (or.resolve_left hyp n.succ_ne_zero) } }, exact (fib_le_of_continuants_aux_b this) end /-! As a simple consequence, we can now derive that all denominators are nonnegative. -/ lemma zero_le_of_continuants_aux_b : 0 ≤ ((of v).continuants_aux n).b := begin let g := of v, induction n with n IH, case nat.zero: { refl }, case nat.succ: { cases (decidable.em $ g.terminated_at (n - 1)) with terminated not_terminated, { cases n, -- terminating case { simp [zero_le_one] }, { have : g.continuants_aux (n + 2) = g.continuants_aux (n + 1), from continuants_aux_stable_step_of_terminated terminated, simp only [this, IH] } }, { calc -- non-terminating case (0 : K) ≤ fib (n + 1) : by exact_mod_cast (n + 1).fib.zero_le ... ≤ ((of v).continuants_aux (n + 1)).b : fib_le_of_continuants_aux_b (or.inr not_terminated) } } end /-- Shows that all denominators are nonnegative. -/ lemma zero_le_of_denom : 0 ≤ (of v).denominators n := by { rw [denom_eq_conts_b, nth_cont_eq_succ_nth_cont_aux], exact zero_le_of_continuants_aux_b } lemma le_of_succ_succ_nth_continuants_aux_b {b : K} (nth_part_denom_eq : (of v).partial_denominators.nth n = some b) : b * ((of v).continuants_aux $ n + 1).b ≤ ((of v).continuants_aux $ n + 2).b := begin set g := of v with g_eq, obtain ⟨gp_n, nth_s_eq, gpnb_eq_b⟩ : ∃ gp_n, g.s.nth n = some gp_n ∧ gp_n.b = b, from exists_s_b_of_part_denom nth_part_denom_eq, let conts := g.continuants_aux (n + 2), set pconts := g.continuants_aux (n + 1) with pconts_eq, set ppconts := g.continuants_aux n with ppconts_eq, -- use the recurrence of continuants_aux and the fact that gp_n.a = 1 suffices : gp_n.b * pconts.b ≤ ppconts.b + gp_n.b * pconts.b, by { have : gp_n.a = 1, from of_part_num_eq_one (part_num_eq_s_a nth_s_eq), finish [generalized_continued_fraction.continuants_aux_recurrence nth_s_eq ppconts_eq pconts_eq] }, have : 0 ≤ ppconts.b, from zero_le_of_continuants_aux_b, solve_by_elim [le_add_of_nonneg_of_le, le_refl] end /-- Shows that `bₙ * Bₙ ≤ Bₙ₊₁`, where `bₙ` is the `n`th partial denominator and `Bₙ₊₁` and `Bₙ` are the `n + 1`th and `n`th denominator of the continued fraction. -/ theorem le_of_succ_nth_denom {b : K} (nth_part_denom_eq : (of v).partial_denominators.nth n = some b) : b * (of v).denominators n ≤ (of v).denominators (n + 1) := begin rw [denom_eq_conts_b, nth_cont_eq_succ_nth_cont_aux], exact (le_of_succ_succ_nth_continuants_aux_b nth_part_denom_eq) end /-- Shows that the sequence of denominators is monotone, that is `Bₙ ≤ Bₙ₊₁`. -/ theorem of_denom_mono : (of v).denominators n ≤ (of v).denominators (n + 1) := begin let g := of v, cases (decidable.em $ g.partial_denominators.terminated_at n) with terminated not_terminated, { have : g.partial_denominators.nth n = none, by rwa seq.terminated_at at terminated, have : g.terminated_at n, from terminated_at_iff_part_denom_none.elim_right (by rwa seq.terminated_at at terminated), have : g.denominators (n + 1) = g.denominators n, from denominators_stable_of_terminated n.le_succ this, rw this }, { obtain ⟨b, nth_part_denom_eq⟩ : ∃ b, g.partial_denominators.nth n = some b, from option.ne_none_iff_exists'.mp not_terminated, have : 1 ≤ b, from of_one_le_nth_part_denom nth_part_denom_eq, calc g.denominators n ≤ b * g.denominators n : by simpa using (mul_le_mul_of_nonneg_right this zero_le_of_denom) ... ≤ g.denominators (n + 1) : le_of_succ_nth_denom nth_part_denom_eq } end section determinant /-! ### Determinant Formula Next we prove the so-called *determinant formula* for `generalized_continued_fraction.of`: `Aₙ * Bₙ₊₁ - Bₙ * Aₙ₊₁ = (-1)^(n + 1)`. -/ lemma determinant_aux (hyp: n = 0 ∨ ¬(of v).terminated_at (n - 1)) : ((of v).continuants_aux n).a * ((of v).continuants_aux (n + 1)).b - ((of v).continuants_aux n).b * ((of v).continuants_aux (n + 1)).a = (-1)^n := begin induction n with n IH, case nat.zero { simp [continuants_aux] }, case nat.succ { -- set up some shorthand notation let g := of v, let conts := continuants_aux g (n + 2), set pred_conts := continuants_aux g (n + 1) with pred_conts_eq, set ppred_conts := continuants_aux g n with ppred_conts_eq, let pA := pred_conts.a, let pB := pred_conts.b, let ppA := ppred_conts.a, let ppB := ppred_conts.b, -- let's change the goal to something more readable change pA * conts.b - pB * conts.a = (-1)^(n + 1), have not_terminated_at_n : ¬terminated_at g n, from or.resolve_left hyp n.succ_ne_zero, obtain ⟨gp, s_nth_eq⟩ : ∃ gp, g.s.nth n = some gp, from option.ne_none_iff_exists'.elim_left not_terminated_at_n, -- unfold the recurrence relation for `conts` once and simplify to derive the following suffices : pA * (ppB + gp.b * pB) - pB * (ppA + gp.b * pA) = (-1)^(n + 1), by { simp only [conts, (continuants_aux_recurrence s_nth_eq ppred_conts_eq pred_conts_eq)], have gp_a_eq_one : gp.a = 1, from of_part_num_eq_one (part_num_eq_s_a s_nth_eq), rw [gp_a_eq_one, this.symm], ring }, suffices : pA * ppB - pB * ppA = (-1)^(n + 1), calc pA * (ppB + gp.b * pB) - pB * (ppA + gp.b * pA) = pA * ppB + pA * gp.b * pB - pB * ppA - pB * gp.b * pA : by ring ... = pA * ppB - pB * ppA : by ring ... = (-1)^(n + 1) : by assumption, suffices : ppA * pB - ppB * pA = (-1)^n, by { have pow_succ_n : (-1 : K)^(n + 1) = (-1) * (-1)^n, from pow_succ (-1) n, rw [pow_succ_n, ←this], ring }, exact (IH $ or.inr $ mt (terminated_stable $ n.sub_le 1) not_terminated_at_n) } end /-- The determinant formula `Aₙ * Bₙ₊₁ - Bₙ * Aₙ₊₁ = (-1)^(n + 1)` -/ lemma determinant (not_terminated_at_n : ¬(of v).terminated_at n) : (of v).numerators n * (of v).denominators (n + 1) - (of v).denominators n * (of v).numerators (n + 1) = (-1)^(n + 1) := (determinant_aux $ or.inr $ not_terminated_at_n) end determinant section error_term /-! ### Approximation of Error Term Next we derive some approximations for the error term when computing a continued fraction up a given position, i.e. bounds for the term `|v - (generalized_continued_fraction.of v).convergents n|`. -/ /-- This lemma follows from the finite correctness proof, the determinant equality, and by simplifying the difference. -/ lemma sub_convergents_eq {ifp : int_fract_pair K} (stream_nth_eq : int_fract_pair.stream v n = some ifp) : let g := of v in let B := (g.continuants_aux (n + 1)).b in let pB := (g.continuants_aux n).b in v - g.convergents n = if ifp.fr = 0 then 0 else (-1)^n / (B * (ifp.fr⁻¹ * B + pB)) := begin -- set up some shorthand notation let g := of v, let conts := g.continuants_aux (n + 1), let pred_conts := g.continuants_aux n, have g_finite_correctness : v = generalized_continued_fraction.comp_exact_value pred_conts conts ifp.fr, from comp_exact_value_correctness_of_stream_eq_some stream_nth_eq, cases decidable.em (ifp.fr = 0) with ifp_fr_eq_zero ifp_fr_ne_zero, { suffices : v - g.convergents n = 0, by simpa [ifp_fr_eq_zero], replace g_finite_correctness : v = g.convergents n, by simpa [generalized_continued_fraction.comp_exact_value, ifp_fr_eq_zero] using g_finite_correctness, exact (sub_eq_zero.elim_right g_finite_correctness) }, { -- more shorthand notation let A := conts.a, let B := conts.b, let pA := pred_conts.a, let pB := pred_conts.b, -- first, let's simplify the goal as `ifp.fr ≠ 0` suffices : v - A / B = (-1)^n / (B * (ifp.fr⁻¹ * B + pB)), by simpa [ifp_fr_ne_zero], -- now we can unfold `g.comp_exact_value` to derive the following equality for `v` replace g_finite_correctness : v = (pA + ifp.fr⁻¹ * A) / (pB + ifp.fr⁻¹ * B), by simpa [generalized_continued_fraction.comp_exact_value, ifp_fr_ne_zero, next_continuants, next_numerator, next_denominator, add_comm] using g_finite_correctness, -- let's rewrite this equality for `v` in our goal suffices : (pA + ifp.fr⁻¹ * A) / (pB + ifp.fr⁻¹ * B) - A / B = (-1)^n / (B * (ifp.fr⁻¹ * B + pB)), by rwa g_finite_correctness, -- To continue, we need use the determinant equality. So let's derive the needed hypothesis. have n_eq_zero_or_not_terminated_at_pred_n : n = 0 ∨ ¬g.terminated_at (n - 1), by { cases n with n', { simp }, { have : int_fract_pair.stream v (n' + 1) ≠ none, by simp [stream_nth_eq], have : ¬g.terminated_at n', from (not_iff_not_of_iff of_terminated_at_n_iff_succ_nth_int_fract_pair_stream_eq_none) .elim_right this, exact (or.inr this) } }, have determinant_eq : pA * B - pB * A = (-1)^n, from determinant_aux n_eq_zero_or_not_terminated_at_pred_n, -- now all we got to do is to rewrite this equality in our goal and re-arrange terms; -- however, for this, we first have to derive quite a few tedious inequalities. have pB_ineq : (fib n : K) ≤ pB, by { have : n ≤ 1 ∨ ¬g.terminated_at (n - 2), by { cases n_eq_zero_or_not_terminated_at_pred_n with n_eq_zero not_terminated_at_pred_n, { simp [n_eq_zero] }, { exact (or.inr $ mt (terminated_stable (n - 1).pred_le) not_terminated_at_pred_n) } }, exact (fib_le_of_continuants_aux_b this) }, have B_ineq : (fib (n + 1) : K) ≤ B, by { have : n + 1 ≤ 1 ∨ ¬g.terminated_at (n + 1 - 2), by { cases n_eq_zero_or_not_terminated_at_pred_n with n_eq_zero not_terminated_at_pred_n, { simp [n_eq_zero, le_refl] }, { exact (or.inr not_terminated_at_pred_n) } }, exact (fib_le_of_continuants_aux_b this) }, have zero_lt_B : 0 < B, { have : 1 ≤ B, from le_trans (by exact_mod_cast fib_pos (lt_of_le_of_ne n.succ.zero_le n.succ_ne_zero.symm)) B_ineq, exact (lt_of_lt_of_le zero_lt_one this) }, have zero_ne_B : 0 ≠ B, from ne_of_lt zero_lt_B, have : 0 ≠ pB + ifp.fr⁻¹ * B, by { have : (0 : K) ≤ fib n, by exact_mod_cast (fib n).zero_le, -- 0 ≤ fib n ≤ pB have zero_le_pB : 0 ≤ pB, from le_trans this pB_ineq, have : 0 < ifp.fr⁻¹, by { suffices : 0 < ifp.fr, by rwa inv_pos, have : 0 ≤ ifp.fr, from int_fract_pair.nth_stream_fr_nonneg stream_nth_eq, change ifp.fr ≠ 0 at ifp_fr_ne_zero, exact lt_of_le_of_ne this ifp_fr_ne_zero.symm }, have : 0 < ifp.fr⁻¹ * B, from mul_pos this zero_lt_B, have : 0 < pB + ifp.fr⁻¹ * B, from add_pos_of_nonneg_of_pos zero_le_pB this, exact (ne_of_lt this) }, -- finally, let's do the rewriting calc (pA + ifp.fr⁻¹ * A) / (pB + ifp.fr⁻¹ * B) - A / B = ((pA + ifp.fr⁻¹ * A) * B - (pB + ifp.fr⁻¹ * B) * A) / ((pB + ifp.fr⁻¹ * B) * B) : by rw (div_sub_div _ _ this.symm zero_ne_B.symm) ... = (pA * B + ifp.fr⁻¹ * A * B - (pB * A + ifp.fr⁻¹ * B * A)) / _ : by repeat { rw [add_mul] } ... = (pA * B - pB * A) / ((pB + ifp.fr⁻¹ * B) * B) : by ring ... = (-1)^n / ((pB + ifp.fr⁻¹ * B) * B) : by rw determinant_eq ... = (-1)^n / (B * (ifp.fr⁻¹ * B + pB)) : by ac_refl } end /-- Shows that `|v - Aₙ / Bₙ| ≤ 1 / (Bₙ * Bₙ₊₁)` -/ theorem abs_sub_convergents_le (not_terminated_at_n : ¬(of v).terminated_at n) : |v - (of v).convergents n| ≤ 1 / (((of v).denominators n) * ((of v).denominators $ n + 1)) := begin -- shorthand notation let g := of v, let nextConts := g.continuants_aux (n + 2), set conts := continuants_aux g (n + 1) with conts_eq, set pred_conts := continuants_aux g n with pred_conts_eq, -- change the goal to something more readable change |v - convergents g n| ≤ 1 / (conts.b * nextConts.b), obtain ⟨gp, s_nth_eq⟩ : ∃ gp, g.s.nth n = some gp, from option.ne_none_iff_exists'.elim_left not_terminated_at_n, have gp_a_eq_one : gp.a = 1, from of_part_num_eq_one (part_num_eq_s_a s_nth_eq), -- unfold the recurrence relation for `nextConts.b` have nextConts_b_eq : nextConts.b = pred_conts.b + gp.b * conts.b, by simp [nextConts, (continuants_aux_recurrence s_nth_eq pred_conts_eq conts_eq), gp_a_eq_one, pred_conts_eq.symm, conts_eq.symm, add_comm], let denom := conts.b * (pred_conts.b + gp.b * conts.b), suffices : |v - g.convergents n| ≤ 1 / denom, by { rw [nextConts_b_eq], congr' 1 }, obtain ⟨ifp_succ_n, succ_nth_stream_eq, ifp_succ_n_b_eq_gp_b⟩ : ∃ ifp_succ_n, int_fract_pair.stream v (n + 1) = some ifp_succ_n ∧ (ifp_succ_n.b : K) = gp.b, from int_fract_pair.exists_succ_nth_stream_of_gcf_of_nth_eq_some s_nth_eq, obtain ⟨ifp_n, stream_nth_eq, stream_nth_fr_ne_zero, if_of_eq_ifp_succ_n⟩ : ∃ ifp_n, int_fract_pair.stream v n = some ifp_n ∧ ifp_n.fr ≠ 0 ∧ int_fract_pair.of ifp_n.fr⁻¹ = ifp_succ_n, from int_fract_pair.succ_nth_stream_eq_some_iff.elim_left succ_nth_stream_eq, let denom' := conts.b * (pred_conts.b + ifp_n.fr⁻¹ * conts.b), -- now we can use `sub_convergents_eq` to simplify our goal suffices : |(-1)^n / denom'| ≤ 1 / denom, by { have : v - g.convergents n = (-1)^n / denom', by { -- apply `sub_convergens_eq` and simplify the result have tmp, from sub_convergents_eq stream_nth_eq, delta at tmp, simp only [stream_nth_fr_ne_zero, conts_eq.symm, pred_conts_eq.symm] at tmp, rw tmp, simp only [denom'], ring_nf, ac_refl }, rwa this }, -- derive some tedious inequalities that we need to rewrite our goal have nextConts_b_ineq : (fib (n + 2) : K) ≤ (pred_conts.b + gp.b * conts.b), by { have : (fib (n + 2) : K) ≤ nextConts.b, from fib_le_of_continuants_aux_b (or.inr not_terminated_at_n), rwa [nextConts_b_eq] at this }, have conts_b_ineq : (fib (n + 1) : K) ≤ conts.b, by { have : ¬g.terminated_at (n - 1), from mt (terminated_stable n.pred_le) not_terminated_at_n, exact (fib_le_of_continuants_aux_b $ or.inr this) }, have zero_lt_conts_b : 0 < conts.b, by { have : (0 : K) < fib (n + 1), by exact_mod_cast (fib_pos (lt_of_le_of_ne n.succ.zero_le n.succ_ne_zero.symm)), exact (lt_of_lt_of_le this conts_b_ineq) }, -- `denom'` is positive, so we can remove `|⬝|` from our goal suffices : 1 / denom' ≤ 1 / denom, by { have : |(-1)^n / denom'| = 1 / denom', by { suffices : 1 / |denom'| = 1 / denom', by rwa [abs_div, (abs_neg_one_pow n)], have : 0 < denom', by { have : 0 ≤ pred_conts.b, by { have : (fib n : K) ≤ pred_conts.b, by { have : ¬g.terminated_at (n - 2), from mt (terminated_stable (n.sub_le 2)) not_terminated_at_n, exact (fib_le_of_continuants_aux_b $ or.inr this) }, exact le_trans (by exact_mod_cast (fib n).zero_le) this }, have : 0 < ifp_n.fr⁻¹, by { have zero_le_ifp_n_fract : 0 ≤ ifp_n.fr, from int_fract_pair.nth_stream_fr_nonneg stream_nth_eq, exact inv_pos.elim_right (lt_of_le_of_ne zero_le_ifp_n_fract stream_nth_fr_ne_zero.symm) }, any_goals { repeat { apply mul_pos <|> apply add_pos_of_nonneg_of_pos } }; assumption }, rwa (abs_of_pos this) }, rwa this }, suffices : 0 < denom ∧ denom ≤ denom', from div_le_div_of_le_left zero_le_one this.left this.right, split, { have : 0 < pred_conts.b + gp.b * conts.b, from lt_of_lt_of_le (by exact_mod_cast (fib_pos (lt_of_le_of_ne n.succ.succ.zero_le n.succ.succ_ne_zero.symm))) nextConts_b_ineq, solve_by_elim [mul_pos] }, { -- we can cancel multiplication by `conts.b` and addition with `pred_conts.b` suffices : gp.b * conts.b ≤ ifp_n.fr⁻¹ * conts.b, from ((mul_le_mul_left zero_lt_conts_b).elim_right $ (add_le_add_iff_left pred_conts.b).elim_right this), suffices : (ifp_succ_n.b : K) * conts.b ≤ ifp_n.fr⁻¹ * conts.b, by rwa [←ifp_succ_n_b_eq_gp_b], have : (ifp_succ_n.b : K) ≤ ifp_n.fr⁻¹, from int_fract_pair.succ_nth_stream_b_le_nth_stream_fr_inv stream_nth_eq succ_nth_stream_eq, have : 0 ≤ conts.b, from le_of_lt zero_lt_conts_b, mono } end /-- Shows that `|v - Aₙ / Bₙ| ≤ 1 / (bₙ * Bₙ * Bₙ)`. This bound is worse than the one shown in `gcf.abs_sub_convergents_le`, but sometimes it is easier to apply and sufficient for one's use case. -/ lemma abs_sub_convergents_le' {b : K} (nth_part_denom_eq : (of v).partial_denominators.nth n = some b) : |v - (of v).convergents n| ≤ 1 / (b * ((of v).denominators n) * ((of v).denominators n)) := begin let g := of v, let B := g.denominators n, let nB := g.denominators (n + 1), have not_terminated_at_n : ¬g.terminated_at n, by { have : g.partial_denominators.nth n ≠ none, by simp [nth_part_denom_eq], exact (not_iff_not_of_iff terminated_at_iff_part_denom_none).elim_right this }, suffices : 1 / (B * nB) ≤ (1 : K) / (b * B * B), by { have : |v - g.convergents n| ≤ 1 / (B * nB), from abs_sub_convergents_le not_terminated_at_n, transitivity; assumption }, -- derive some inequalities needed to show the claim have zero_lt_B : 0 < B, by { have : (fib (n + 1) : K) ≤ B, from succ_nth_fib_le_of_nth_denom (or.inr $ mt (terminated_stable n.pred_le) not_terminated_at_n), exact (lt_of_lt_of_le (by exact_mod_cast (fib_pos (lt_of_le_of_ne n.succ.zero_le n.succ_ne_zero.symm))) this) }, have denoms_ineq : b * B * B ≤ B * nB, by { have : b * B ≤ nB, from le_of_succ_nth_denom nth_part_denom_eq, rwa [(mul_comm B nB), (mul_le_mul_right zero_lt_B)] }, have : (0 : K) < b * B * B, by { have : 0 < b, from lt_of_lt_of_le zero_lt_one (of_one_le_nth_part_denom nth_part_denom_eq), any_goals { repeat { apply mul_pos } }; assumption }, exact (div_le_div_of_le_left zero_le_one this denoms_ineq) end end error_term end generalized_continued_fraction
2c6f8fc790142c727221e1ab89c81a03b529ec69
7cef822f3b952965621309e88eadf618da0c8ae9
/src/algebra/category/Group.lean
31e27afd7bfa89faf7a36ab95f419d3cc0fe219b
[ "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
6,042
lean
/- Copyright (c) 2018 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import algebra.punit_instances import algebra.category.Mon.basic import category_theory.endomorphism /-! # Category instances for group, add_group, comm_group, and add_comm_group. We introduce the bundled categories: * `Group` * `AddGroup` * `CommGroup` * `AddCommGroup` along with the relevant forgetful functors between them, and to the bundled monoid categories. ## Implementation notes See the note [locally reducible category instances]. -/ universes u v open category_theory /-- The category of groups and group morphisms. -/ @[to_additive AddGroup] def Group : Type (u+1) := induced_category Mon (bundled.map group.to_monoid) namespace Group /-- Construct a bundled Group from the underlying type and typeclass. -/ @[to_additive] def of (X : Type u) [group X] : Group := bundled.of X local attribute [reducible] Group @[to_additive] instance : has_coe_to_sort Group := infer_instance -- short-circuit type class inference @[to_additive add_group] instance (G : Group) : group G := G.str @[to_additive] instance : has_one Group := ⟨Group.of punit⟩ @[to_additive] instance : concrete_category Group := infer_instance -- short-circuit type class inference @[to_additive has_forget_to_AddMon] instance has_forget_to_Mon : has_forget₂ Group Mon := infer_instance -- short-circuit type class inference end Group /-- The category of commutative groups and group morphisms. -/ @[to_additive AddCommGroup] def CommGroup : Type (u+1) := induced_category Group (bundled.map comm_group.to_group) namespace CommGroup /-- Construct a bundled CommGroup from the underlying type and typeclass. -/ @[to_additive] def of (G : Type u) [comm_group G] : CommGroup := bundled.of G local attribute [reducible] CommGroup @[to_additive] instance : has_coe_to_sort CommGroup := infer_instance -- short-circuit type class inference @[to_additive add_comm_group] instance (G : CommGroup) : comm_group G := G.str @[to_additive] instance : has_one CommGroup := ⟨CommGroup.of punit⟩ @[to_additive] instance : concrete_category CommGroup := infer_instance -- short-circuit type class inference @[to_additive has_forget_to_AddGroup] instance has_forget_to_Group : has_forget₂ CommGroup Group := infer_instance -- short-circuit type class inference @[to_additive has_forget_to_AddCommMon] instance has_forget_to_CommMon : has_forget₂ CommGroup CommMon := induced_category.has_forget₂ (λ G : CommGroup, CommMon.of G) end CommGroup variables {X Y : Type u} /-- Build an isomorphism in the category `Group` from a `mul_equiv` between `group`s. -/ @[to_additive add_equiv.to_AddGroup_iso "Build an isomorphism in the category `AddGroup` from a `add_equiv` between `add_group`s."] def mul_equiv.to_Group_iso [group X] [group Y] (e : X ≃* Y) : Group.of X ≅ Group.of Y := { hom := e.to_monoid_hom, inv := e.symm.to_monoid_hom } attribute [simps] mul_equiv.to_Group_iso add_equiv.to_AddGroup_iso /-- Build an isomorphism in the category `CommGroup` from a `mul_equiv` between `comm_group`s. -/ @[simps, to_additive add_equiv.to_AddCommGroup_iso "Build an isomorphism in the category `AddCommGroup` from a `add_equiv` between `add_comm_group`s."] def mul_equiv.to_CommGroup_iso [comm_group X] [comm_group Y] (e : X ≃* Y) : CommGroup.of X ≅ CommGroup.of Y := { hom := e.to_monoid_hom, inv := e.symm.to_monoid_hom } attribute [simps] mul_equiv.to_CommGroup_iso add_equiv.to_AddCommGroup_iso namespace category_theory.iso /-- Build a `mul_equiv` from an isomorphism in the category `Group`. -/ @[to_additive AddGroup_iso_to_add_equiv "Build an `add_equiv` from an isomorphism in the category `AddGroup`."] def Group_iso_to_mul_equiv {X Y : Group.{u}} (i : X ≅ Y) : X ≃* Y := { to_fun := i.hom, inv_fun := i.inv, left_inv := by tidy, right_inv := by tidy, map_mul' := by tidy }. attribute [simps] Group_iso_to_mul_equiv AddGroup_iso_to_add_equiv /-- Build a `mul_equiv` from an isomorphism in the category `CommGroup`. -/ @[to_additive AddCommGroup_iso_to_add_equiv "Build an `add_equiv` from an isomorphism in the category `AddCommGroup`."] def CommGroup_iso_to_mul_equiv {X Y : CommGroup.{u}} (i : X ≅ Y) : X ≃* Y := { to_fun := i.hom, inv_fun := i.inv, left_inv := by tidy, right_inv := by tidy, map_mul' := by tidy }. attribute [simps] CommGroup_iso_to_mul_equiv AddCommGroup_iso_to_add_equiv end category_theory.iso /-- multiplicative equivalences between `group`s are the same as (isomorphic to) isomorphisms in `Group` -/ @[to_additive add_equiv_iso_AddGroup_iso "additive equivalences between `add_group`s are the same as (isomorphic to) isomorphisms in `AddGroup`"] def mul_equiv_iso_Group_iso {X Y : Type u} [group X] [group Y] : (X ≃* Y) ≅ (Group.of X ≅ Group.of Y) := { hom := λ e, e.to_Group_iso, inv := λ i, i.Group_iso_to_mul_equiv, } /-- multiplicative equivalences between `comm_group`s are the same as (isomorphic to) isomorphisms in `CommGroup` -/ @[to_additive add_equiv_iso_AddCommGroup_iso "additive equivalences between `add_comm_group`s are the same as (isomorphic to) isomorphisms in `AddCommGroup`"] def mul_equiv_iso_CommGroup_iso {X Y : Type u} [comm_group X] [comm_group Y] : (X ≃* Y) ≅ (CommGroup.of X ≅ CommGroup.of Y) := { hom := λ e, e.to_CommGroup_iso, inv := λ i, i.CommGroup_iso_to_mul_equiv, } namespace category_theory.Aut /-- The (bundled) group of automorphisms of a type is isomorphic to the (bundled) group of permutations. -/ def iso_perm {α : Type u} : Group.of (Aut α) ≅ Group.of (equiv.perm α) := { hom := ⟨λ g, g.to_equiv, (by tidy), (by tidy)⟩, inv := ⟨λ g, g.to_iso, (by tidy), (by tidy)⟩ } /-- The (unbundled) group of automorphisms of a type is `mul_equiv` to the (unbundled) group of permutations. -/ def mul_equiv_perm {α : Type u} : Aut α ≃* equiv.perm α := iso_perm.Group_iso_to_mul_equiv end category_theory.Aut
37befba0587be215ad68b778f418c3c72919cfe7
c3f2fcd060adfa2ca29f924839d2d925e8f2c685
/tests/lean/run/group2.lean
f7ff60a4e0d2de830cee483cc1514a674462ea9b
[ "Apache-2.0" ]
permissive
respu/lean
6582d19a2f2838a28ecd2b3c6f81c32d07b5341d
8c76419c60b63d0d9f7bc04ebb0b99812d0ec654
refs/heads/master
1,610,882,451,231
1,427,747,084,000
1,427,747,429,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,684
lean
import logic context variable {A : Type} variable f : A → A → A variable one : A variable inv : A → A infixl `*` := f postfix `^-1`:100 := inv definition is_assoc := ∀ a b c, (a*b)*c = a*b*c definition is_id := ∀ a, a*one = a definition is_inv := ∀ a, a*a^-1 = one end inductive group_struct [class] (A : Type) : Type := mk : Π (mul : A → A → A) (one : A) (inv : A → A), is_assoc mul → is_id mul one → is_inv mul one inv → group_struct A inductive group : Type := mk : Π (A : Type), group_struct A → group definition carrier (g : group) : Type := group.rec (λ c s, c) g attribute carrier [coercion] definition group_to_struct [instance] (g : group) : group_struct (carrier g) := group.rec (λ (A : Type) (s : group_struct A), s) g check group_struct definition mul {A : Type} [s : group_struct A] (a b : A) : A := group_struct.rec (λ mul one inv h1 h2 h3, mul) s a b infixl `*` := mul section variable G1 : group variable G2 : group variables a b c : G2 variables d e : G1 check a * b * b check d * e end constant G : group.{1} constants a b : G definition val : G := a*b check val constant pos_real : Type.{1} constant rmul : pos_real → pos_real → pos_real constant rone : pos_real constant rinv : pos_real → pos_real axiom H1 : is_assoc rmul axiom H2 : is_id rmul rone axiom H3 : is_inv rmul rone rinv definition real_group_struct [instance] : group_struct pos_real := group_struct.mk rmul rone rinv H1 H2 H3 constants x y : pos_real check x * y set_option pp.implicit true print "---------------" theorem T (a b : pos_real): (rmul a b) = a*b := eq.refl (rmul a b)
c217a0d379aa0edfffca91d543fecccdb7a07870
bb31430994044506fa42fd667e2d556327e18dfe
/src/data/pnat/factors.lean
f49517117765b61b63c9fa1d38f5974cea8a9560
[ "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
14,620
lean
/- Copyright (c) 2019 Neil Strickland. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Neil Strickland -/ import algebra.big_operators.multiset.basic import data.pnat.prime import data.nat.factors import data.multiset.sort /-! # Prime factors of nonzero naturals This file defines the factorization of a nonzero natural number `n` as a multiset of primes, the multiplicity of `p` in this factors multiset being the p-adic valuation of `n`. ## Main declarations * `prime_multiset`: Type of multisets of prime numbers. * `factor_multiset n`: Multiset of prime factors of `n`. -/ /-- The type of multisets of prime numbers. Unique factorization gives an equivalence between this set and ℕ+, as we will formalize below. -/ @[derive [inhabited, canonically_ordered_add_monoid, distrib_lattice, semilattice_sup, order_bot, has_sub, has_ordered_sub]] def prime_multiset := multiset nat.primes namespace prime_multiset -- `@[derive]` doesn't work for `meta` instances meta instance : has_repr prime_multiset := by delta prime_multiset; apply_instance /-- The multiset consisting of a single prime -/ def of_prime (p : nat.primes) : prime_multiset := ({p} : multiset nat.primes) theorem card_of_prime (p : nat.primes) : multiset.card (of_prime p) = 1 := rfl /-- We can forget the primality property and regard a multiset of primes as just a multiset of positive integers, or a multiset of natural numbers. In the opposite direction, if we have a multiset of positive integers or natural numbers, together with a proof that all the elements are prime, then we can regard it as a multiset of primes. The next block of results records obvious properties of these coercions. -/ def to_nat_multiset : prime_multiset → multiset ℕ := λ v, v.map (λ p, (p : ℕ)) instance coe_nat : has_coe prime_multiset (multiset ℕ) := ⟨to_nat_multiset⟩ /-- `prime_multiset.coe`, the coercion from a multiset of primes to a multiset of naturals, promoted to an `add_monoid_hom`. -/ def coe_nat_monoid_hom : prime_multiset →+ multiset ℕ := { to_fun := coe, .. multiset.map_add_monoid_hom coe } @[simp] lemma coe_coe_nat_monoid_hom : (coe_nat_monoid_hom : prime_multiset → multiset ℕ) = coe := rfl theorem coe_nat_injective : function.injective (coe : prime_multiset → multiset ℕ) := multiset.map_injective nat.primes.coe_nat_injective theorem coe_nat_of_prime (p : nat.primes) : ((of_prime p) : multiset ℕ) = {p} := rfl theorem coe_nat_prime (v : prime_multiset) (p : ℕ) (h : p ∈ (v : multiset ℕ)) : p.prime := by { rcases multiset.mem_map.mp h with ⟨⟨p', hp'⟩, ⟨h_mem, h_eq⟩⟩, exact h_eq ▸ hp' } /-- Converts a `prime_multiset` to a `multiset ℕ+`. -/ def to_pnat_multiset : prime_multiset → multiset ℕ+ := λ v, v.map (λ p, (p : ℕ+)) instance coe_pnat : has_coe prime_multiset (multiset ℕ+) := ⟨to_pnat_multiset⟩ /-- `coe_pnat`, the coercion from a multiset of primes to a multiset of positive naturals, regarded as an `add_monoid_hom`. -/ def coe_pnat_monoid_hom : prime_multiset →+ multiset ℕ+ := { to_fun := coe, .. multiset.map_add_monoid_hom coe } @[simp] lemma coe_coe_pnat_monoid_hom : (coe_pnat_monoid_hom : prime_multiset → multiset ℕ+) = coe := rfl theorem coe_pnat_injective : function.injective (coe : prime_multiset → multiset ℕ+) := multiset.map_injective nat.primes.coe_pnat_injective theorem coe_pnat_of_prime (p : nat.primes) : ((of_prime p) : multiset ℕ+) = {(p : ℕ+)} := rfl theorem coe_pnat_prime (v : prime_multiset) (p : ℕ+) (h : p ∈ (v : multiset ℕ+)) : p.prime := by { rcases multiset.mem_map.mp h with ⟨⟨p', hp'⟩, ⟨h_mem, h_eq⟩⟩, exact h_eq ▸ hp' } instance coe_multiset_pnat_nat : has_coe (multiset ℕ+) (multiset ℕ) := ⟨λ v, v.map (λ n, (n : ℕ))⟩ theorem coe_pnat_nat (v : prime_multiset) : ((v : (multiset ℕ+)) : (multiset ℕ)) = (v : multiset ℕ) := by { change (v.map (coe : nat.primes → ℕ+)).map subtype.val = v.map subtype.val, rw [multiset.map_map], congr } /-- The product of a `prime_multiset`, as a `ℕ+`. -/ def prod (v : prime_multiset) : ℕ+ := (v : multiset pnat).prod theorem coe_prod (v : prime_multiset) : (v.prod : ℕ) = (v : multiset ℕ).prod := begin let h : (v.prod : ℕ) = ((v.map coe).map coe).prod := (pnat.coe_monoid_hom.map_multiset_prod v.to_pnat_multiset), rw [multiset.map_map] at h, have : (coe : ℕ+ → ℕ) ∘ (coe : nat.primes → ℕ+) = coe := funext (λ p, rfl), rw[this] at h, exact h, end theorem prod_of_prime (p : nat.primes) : (of_prime p).prod = (p : ℕ+) := multiset.prod_singleton _ /-- If a `multiset ℕ` consists only of primes, it can be recast as a `prime_multiset`. -/ def of_nat_multiset (v : multiset ℕ) (h : ∀ (p : ℕ), p ∈ v → p.prime) : prime_multiset := @multiset.pmap ℕ nat.primes nat.prime (λ p hp, ⟨p, hp⟩) v h theorem to_of_nat_multiset (v : multiset ℕ) (h) : ((of_nat_multiset v h) : multiset ℕ) = v := begin unfold_coes, dsimp [of_nat_multiset, to_nat_multiset], have : (λ (p : ℕ) (h : p.prime), ((⟨p, h⟩ : nat.primes) : ℕ)) = (λ p h, id p) := by {funext p h, refl}, rw [multiset.map_pmap, this, multiset.pmap_eq_map, multiset.map_id] end theorem prod_of_nat_multiset (v : multiset ℕ) (h) : ((of_nat_multiset v h).prod : ℕ) = (v.prod : ℕ) := by rw[coe_prod, to_of_nat_multiset] /-- If a `multiset ℕ+` consists only of primes, it can be recast as a `prime_multiset`. -/ def of_pnat_multiset (v : multiset ℕ+) (h : ∀ (p : ℕ+), p ∈ v → p.prime) : prime_multiset := @multiset.pmap ℕ+ nat.primes pnat.prime (λ p hp, ⟨(p : ℕ), hp⟩) v h theorem to_of_pnat_multiset (v : multiset ℕ+) (h) : ((of_pnat_multiset v h) : multiset ℕ+) = v := begin unfold_coes, dsimp[of_pnat_multiset, to_pnat_multiset], have : (λ (p : ℕ+) (h : p.prime), ((coe : nat.primes → ℕ+) ⟨p, h⟩)) = (λ p h, id p) := by {funext p h, apply subtype.eq, refl}, rw[multiset.map_pmap, this, multiset.pmap_eq_map, multiset.map_id] end theorem prod_of_pnat_multiset (v : multiset ℕ+) (h) : ((of_pnat_multiset v h).prod : ℕ+) = v.prod := by { dsimp [prod], rw [to_of_pnat_multiset] } /-- Lists can be coerced to multisets; here we have some results about how this interacts with our constructions on multisets. -/ def of_nat_list (l : list ℕ) (h : ∀ (p : ℕ), p ∈ l → p.prime) : prime_multiset := of_nat_multiset (l : multiset ℕ) h theorem prod_of_nat_list (l : list ℕ) (h) : ((of_nat_list l h).prod : ℕ) = l.prod := by { have := prod_of_nat_multiset (l : multiset ℕ) h, rw [multiset.coe_prod] at this, exact this } /-- If a `list ℕ+` consists only of primes, it can be recast as a `prime_multiset` with the coercion from lists to multisets. -/ def of_pnat_list (l : list ℕ+) (h : ∀ (p : ℕ+), p ∈ l → p.prime) : prime_multiset := of_pnat_multiset (l : multiset ℕ+) h theorem prod_of_pnat_list (l : list ℕ+) (h) : (of_pnat_list l h).prod = l.prod := by { have := prod_of_pnat_multiset (l : multiset ℕ+) h, rw [multiset.coe_prod] at this, exact this } /-- The product map gives a homomorphism from the additive monoid of multisets to the multiplicative monoid ℕ+. -/ theorem prod_zero : (0 : prime_multiset).prod = 1 := by { dsimp [prod], exact multiset.prod_zero } theorem prod_add (u v : prime_multiset) : (u + v).prod = u.prod * v.prod := begin change (coe_pnat_monoid_hom (u + v)).prod = _, rw coe_pnat_monoid_hom.map_add, exact multiset.prod_add _ _, end theorem prod_smul (d : ℕ) (u : prime_multiset) : (d • u).prod = u.prod ^ d := by { induction d with d ih, refl, rw [succ_nsmul, prod_add, ih, nat.succ_eq_add_one, pow_succ, mul_comm] } end prime_multiset namespace pnat /-- The prime factors of n, regarded as a multiset -/ def factor_multiset (n : ℕ+) : prime_multiset := prime_multiset.of_nat_list (nat.factors n) (@nat.prime_of_mem_factors n) /-- The product of the factors is the original number -/ theorem prod_factor_multiset (n : ℕ+) : (factor_multiset n).prod = n := eq $ by { dsimp [factor_multiset], rw [prime_multiset.prod_of_nat_list], exact nat.prod_factors n.ne_zero } theorem coe_nat_factor_multiset (n : ℕ+) : ((factor_multiset n) : (multiset ℕ)) = ((nat.factors n) : multiset ℕ) := prime_multiset.to_of_nat_multiset (nat.factors n) (@nat.prime_of_mem_factors n) end pnat namespace prime_multiset /-- If we start with a multiset of primes, take the product and then factor it, we get back the original multiset. -/ theorem factor_multiset_prod (v : prime_multiset) : v.prod.factor_multiset = v := begin apply prime_multiset.coe_nat_injective, rw [v.prod.coe_nat_factor_multiset, prime_multiset.coe_prod], rcases v with ⟨l⟩, unfold_coes, dsimp [prime_multiset.to_nat_multiset], rw [multiset.coe_prod], let l' := l.map (coe : nat.primes → ℕ), have : ∀ (p : ℕ), p ∈ l' → p.prime := λ p hp, by {rcases list.mem_map.mp hp with ⟨⟨p', hp'⟩, ⟨h_mem, h_eq⟩⟩, exact h_eq ▸ hp'}, exact multiset.coe_eq_coe.mpr (@nat.factors_unique _ l' rfl this).symm, end end prime_multiset namespace pnat /-- Positive integers biject with multisets of primes. -/ def factor_multiset_equiv : ℕ+ ≃ prime_multiset := { to_fun := factor_multiset, inv_fun := prime_multiset.prod, left_inv := prod_factor_multiset, right_inv := prime_multiset.factor_multiset_prod } /-- Factoring gives a homomorphism from the multiplicative monoid ℕ+ to the additive monoid of multisets. -/ theorem factor_multiset_one : factor_multiset 1 = 0 := by simp [factor_multiset, prime_multiset.of_nat_list, prime_multiset.of_nat_multiset] theorem factor_multiset_mul (n m : ℕ+) : factor_multiset (n * m) = (factor_multiset n) + (factor_multiset m) := begin let u := factor_multiset n, let v := factor_multiset m, have : n = u.prod := (prod_factor_multiset n).symm, rw[this], have : m = v.prod := (prod_factor_multiset m).symm, rw[this], rw[← prime_multiset.prod_add], repeat {rw[prime_multiset.factor_multiset_prod]}, end theorem factor_multiset_pow (n : ℕ+) (m : ℕ) : factor_multiset (n ^ m) = m • (factor_multiset n) := begin let u := factor_multiset n, have : n = u.prod := (prod_factor_multiset n).symm, rw[this, ← prime_multiset.prod_smul], repeat {rw[prime_multiset.factor_multiset_prod]}, end /-- Factoring a prime gives the corresponding one-element multiset. -/ theorem factor_multiset_of_prime (p : nat.primes) : (p : ℕ+).factor_multiset = prime_multiset.of_prime p := begin apply factor_multiset_equiv.symm.injective, change (p : ℕ+).factor_multiset.prod = (prime_multiset.of_prime p).prod, rw[(p : ℕ+).prod_factor_multiset, prime_multiset.prod_of_prime], end /-- We now have four different results that all encode the idea that inequality of multisets corresponds to divisibility of positive integers. -/ theorem factor_multiset_le_iff {m n : ℕ+} : factor_multiset m ≤ factor_multiset n ↔ m ∣ n := begin split, { intro h, rw [← prod_factor_multiset m, ← prod_factor_multiset m], apply dvd.intro (n.factor_multiset - m.factor_multiset).prod, rw [← prime_multiset.prod_add, prime_multiset.factor_multiset_prod, add_tsub_cancel_of_le h, prod_factor_multiset] }, { intro h, rw [← mul_div_exact h, factor_multiset_mul], exact le_self_add } end theorem factor_multiset_le_iff' {m : ℕ+} {v : prime_multiset}: factor_multiset m ≤ v ↔ m ∣ v.prod := by { let h := @factor_multiset_le_iff m v.prod, rw [v.factor_multiset_prod] at h, exact h } end pnat namespace prime_multiset theorem prod_dvd_iff {u v : prime_multiset} : u.prod ∣ v.prod ↔ u ≤ v := by { let h := @pnat.factor_multiset_le_iff' u.prod v, rw [u.factor_multiset_prod] at h, exact h.symm } theorem prod_dvd_iff' {u : prime_multiset} {n : ℕ+} : u.prod ∣ n ↔ u ≤ n.factor_multiset := by { let h := @prod_dvd_iff u n.factor_multiset, rw [n.prod_factor_multiset] at h, exact h } end prime_multiset namespace pnat /-- The gcd and lcm operations on positive integers correspond to the inf and sup operations on multisets. -/ theorem factor_multiset_gcd (m n : ℕ+) : factor_multiset (gcd m n) = (factor_multiset m) ⊓ (factor_multiset n) := begin apply le_antisymm, { apply le_inf_iff.mpr; split; apply factor_multiset_le_iff.mpr, exact gcd_dvd_left m n, exact gcd_dvd_right m n}, { rw[← prime_multiset.prod_dvd_iff, prod_factor_multiset], apply dvd_gcd; rw[prime_multiset.prod_dvd_iff'], exact inf_le_left, exact inf_le_right} end theorem factor_multiset_lcm (m n : ℕ+) : factor_multiset (lcm m n) = (factor_multiset m) ⊔ (factor_multiset n) := begin apply le_antisymm, { rw[← prime_multiset.prod_dvd_iff, prod_factor_multiset], apply lcm_dvd; rw[← factor_multiset_le_iff'], exact le_sup_left, exact le_sup_right}, { apply sup_le_iff.mpr; split; apply factor_multiset_le_iff.mpr, exact dvd_lcm_left m n, exact dvd_lcm_right m n }, end /-- The number of occurrences of p in the factor multiset of m is the same as the p-adic valuation of m. -/ theorem count_factor_multiset (m : ℕ+) (p : nat.primes) (k : ℕ) : (p : ℕ+) ^ k ∣ m ↔ k ≤ m.factor_multiset.count p := begin intros, rw [multiset.le_count_iff_repeat_le], rw [← factor_multiset_le_iff, factor_multiset_pow, factor_multiset_of_prime], congr' 2, apply multiset.eq_repeat.mpr, split, { rw [multiset.card_nsmul, prime_multiset.card_of_prime, mul_one] }, { intros q h, rw [prime_multiset.of_prime, multiset.nsmul_singleton _ k] at h, exact multiset.eq_of_mem_repeat h } end end pnat namespace prime_multiset theorem prod_inf (u v : prime_multiset) : (u ⊓ v).prod = pnat.gcd u.prod v.prod := begin let n := u.prod, let m := v.prod, change (u ⊓ v).prod = pnat.gcd n m, have : u = n.factor_multiset := u.factor_multiset_prod.symm, rw [this], have : v = m.factor_multiset := v.factor_multiset_prod.symm, rw [this], rw [← pnat.factor_multiset_gcd n m, pnat.prod_factor_multiset] end theorem prod_sup (u v : prime_multiset) : (u ⊔ v).prod = pnat.lcm u.prod v.prod := begin let n := u.prod, let m := v.prod, change (u ⊔ v).prod = pnat.lcm n m, have : u = n.factor_multiset := u.factor_multiset_prod.symm, rw [this], have : v = m.factor_multiset := v.factor_multiset_prod.symm, rw [this], rw[← pnat.factor_multiset_lcm n m, pnat.prod_factor_multiset] end end prime_multiset
6a35df85bde8c5da05b946448653f1f3323a3dbe
510e96af568b060ed5858226ad954c258549f143
/data/list/basic.lean
75bbef44de3e6fb799a2ccb0d83e40b7025c13fc
[]
no_license
Shamrock-Frost/library_dev
cb6d1739237d81e17720118f72ba0a6db8a5906b
0245c71e4931d3aceeacf0aea776454f6ee03c9c
refs/heads/master
1,609,481,034,595
1,500,165,215,000
1,500,165,347,000
97,350,162
0
0
null
1,500,164,969,000
1,500,164,969,000
null
UTF-8
Lean
false
false
12,567
lean
/- Copyright (c) 2014 Parikshit Khanna. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Parikshit Khanna, Jeremy Avigad, Leonardo de Moura, Floris van Doorn Basic properties of lists. -/ import logic.basic ..nat.basic open function nat namespace list universe variable uu variable {α : Type uu} /- theorems -/ @[simp] lemma cons_ne_nil (a : α) (l : list α) : a::l ≠ [] := begin intro, contradiction end lemma head_eq_of_cons_eq {α : Type} {h₁ h₂ : α} {t₁ t₂ : list α} : (h₁::t₁) = (h₂::t₂) → h₁ = h₂ := assume Peq, list.no_confusion Peq (assume Pheq Pteq, Pheq) lemma tail_eq_of_cons_eq {α : Type} {h₁ h₂ : α} {t₁ t₂ : list α} : (h₁::t₁) = (h₂::t₂) → t₁ = t₂ := assume Peq, list.no_confusion Peq (assume Pheq Pteq, Pteq) lemma cons_inj {α : Type} {a : α} : injective (cons a) := assume l₁ l₂, assume Pe, tail_eq_of_cons_eq Pe /- append -/ -- TODO(Jeremy): append_nil in the lean library should be nil_append attribute [simp] cons_append nil_append @[simp] theorem append.assoc (s t u : list α) : s ++ t ++ u = s ++ (t ++ u) := begin induction s with a s ih, reflexivity, simp [ih] end /- length -/ attribute [simp] length_cons attribute [simp] length_append /- concat -/ @[simp] theorem concat_nil (a : α) : concat [] a = [a] := rfl @[simp] theorem concat_cons (a b : α) (l : list α) : concat (a::l) b = a::(concat l b) := rfl @[simp] theorem concat_ne_nil (a : α) (l : list α) : concat l a ≠ [] := begin induction l, repeat { intro h, contradiction } end attribute [simp] length_concat @[simp] theorem concat_append (a : α) (l₁ l₂ : list α) : concat l₁ a ++ l₂ = l₁ ++ a :: l₂ := begin induction l₁ with b l₁ ih, simp, simp [ih] end theorem append_concat (a : α) (l₁ l₂ : list α) : l₁ ++ concat l₂ a = concat (l₁ ++ l₂) a := begin induction l₂ with b l₂ ih, repeat { simp } end /- last -/ @[simp] lemma last_singleton (a : α) (h : [a] ≠ []) : last [a] h = a := rfl @[simp] lemma last_cons_cons (a₁ a₂ : α) (l : list α) (h : a₁::a₂::l ≠ []) : last (a₁::a₂::l) h = last (a₂::l) (cons_ne_nil a₂ l) := rfl theorem last_congr {l₁ l₂ : list α} (h₁ : l₁ ≠ []) (h₂ : l₂ ≠ []) (h₃ : l₁ = l₂) : last l₁ h₁ = last l₂ h₂ := by subst l₁ /- head and tail -/ @[simp] theorem head_cons [h : inhabited α] (a : α) (l : list α) : head (a::l) = a := rfl @[simp] theorem tail_nil : tail (@nil α) = [] := rfl @[simp] theorem tail_cons (a : α) (l : list α) : tail (a::l) = l := rfl /- list membership -/ attribute [simp] mem_nil_iff mem_cons_self mem_cons_iff /- index_of -/ section index_of variable [decidable_eq α] @[simp] theorem index_of_nil (a : α) : index_of a [] = 0 := rfl theorem index_of_cons (a b : α) (l : list α) : index_of a (b::l) = if a = b then 0 else succ (index_of a l) := rfl @[simp] theorem index_of_cons_of_eq {a b : α} (l : list α) : a = b → index_of a (b::l) = 0 := assume e, if_pos e @[simp] theorem index_of_cons_of_ne {a b : α} (l : list α) : a ≠ b → index_of a (b::l) = succ (index_of a l) := assume n, if_neg n @[simp] theorem index_of_of_not_mem {l : list α} {a : α} : ¬a ∈ l → index_of a l = length l := list.rec_on l (suppose ¬a ∈ [], rfl) (assume b l, assume ih : ¬a ∈ l → index_of a l = length l, suppose ¬a ∈ b::l, have ¬a = b ∧ ¬a ∈ l, begin rw [mem_cons_iff, not_or_iff] at this, exact this end, show index_of a (b::l) = length (b::l), begin rw [index_of_cons, if_neg this^.left, ih this^.right], reflexivity end) lemma index_of_le_length {a : α} {l : list α} : index_of a l ≤ length l := list.rec_on l (by simp) (assume b l, assume ih : index_of a l ≤ length l, show index_of a (b::l) ≤ length (b::l), from decidable.by_cases (suppose a = b, begin simp [this, index_of_cons_of_eq l (eq.refl b)], apply zero_le end) (suppose a ≠ b, begin rw [index_of_cons_of_ne l this], apply succ_le_succ ih end)) lemma not_mem_of_index_of_eq_length : ∀ {a : α} {l : list α}, index_of a l = length l → a ∉ l | a [] := by simp | a (b::l) := begin have h := decidable.em (a = b), cases h with aeqb aneb, { rw [index_of_cons_of_eq l aeqb, length_cons], intros, contradiction }, rw [index_of_cons_of_ne l aneb, length_cons, mem_cons_iff, not_or_iff], intro h, split, assumption, exact not_mem_of_index_of_eq_length (nat.succ_inj h) end lemma index_of_lt_length {a} {l : list α} (al : a ∈ l) : index_of a l < length l := begin apply lt_of_le_of_ne, apply index_of_le_length, apply not.intro, intro Peq, exact absurd al (not_mem_of_index_of_eq_length Peq) end end index_of /- nth element -/ section nth attribute [simp] nth_succ theorem nth_eq_some : ∀ {l : list α} {n : nat}, n < length l → { a : α // nth l n = some a} | ([] : list α) n h := absurd h (not_lt_zero _) | (a::l) 0 h := ⟨a, rfl⟩ | (a::l) (succ n) h := have n < length l, from lt_of_succ_lt_succ h, subtype.rec_on (nth_eq_some this) (assume b : α, assume hb : nth l n = some b, show { b : α // nth (a::l) (succ n) = some b }, from ⟨b, by rw [nth_succ, hb]⟩) theorem index_of_nth [decidable_eq α] {a : α} : ∀ {l : list α}, a ∈ l → nth l (index_of a l) = some a | [] ain := absurd ain (not_mem_nil _) | (b::l) ainbl := decidable.by_cases (λ aeqb : a = b, by rw [index_of_cons_of_eq _ aeqb]; simp [nth, aeqb]) (λ aneb : a ≠ b, or.elim (eq_or_mem_of_mem_cons ainbl) (λ aeqb : a = b, absurd aeqb aneb) (λ ainl : a ∈ l, by rewrite [index_of_cons_of_ne _ aneb, nth_succ, index_of_nth ainl])) definition inth [h : inhabited α] (l : list α) (n : nat) : α := match (nth l n) with | (some a) := a | none := arbitrary α end theorem inth_zero [inhabited α] (a : α) (l : list α) : inth (a :: l) 0 = a := rfl theorem inth_succ [inhabited α] (a : α) (l : list α) (n : nat) : inth (a::l) (n+1) = inth l n := rfl end nth section ith definition ith : Π (l : list α) (i : nat), i < length l → α | nil i h := absurd h (not_lt_zero i) | (a::ains) 0 h := a | (a::ains) (succ i) h := ith ains i (lt_of_succ_lt_succ h) @[simp] lemma ith_zero (a : α) (l : list α) (h : 0 < length (a::l)) : ith (a::l) 0 h = a := rfl @[simp] lemma ith_succ (a : α) (l : list α) (i : nat) (h : succ i < length (a::l)) : ith (a::l) (succ i) h = ith l i (lt_of_succ_lt_succ h) := rfl end ith section take @[simp] lemma taken_zero : ∀ (l : list α), take 0 l = [] := begin intros, reflexivity end @[simp] lemma taken_nil : ∀ n, take n [] = ([] : list α) | 0 := rfl | (n+1) := rfl lemma taken_cons : ∀ n (a : α) (l : list α), take (succ n) (a::l) = a :: take n l := begin intros, reflexivity end lemma taken_all : ∀ (l : list α), take (length l) l = l | [] := rfl | (a::l) := begin change a :: (take (length l) l) = a :: l, rw taken_all end lemma taken_all_of_ge : ∀ {n} {l : list α}, n ≥ length l → take n l = l | 0 [] h := rfl | 0 (a::l) h := absurd h (not_le_of_gt (zero_lt_succ _)) | (n+1) [] h := rfl | (n+1) (a::l) h := begin change a :: take n l = a :: l, rw [taken_all_of_ge (le_of_succ_le_succ h)] end -- TODO(Jeremy): restore when we have min /- lemma taken_taken : ∀ (n m) (l : list α), take n (take m l) = take (min n m) l | n 0 l := sorry -- by rewrite [min_zero, taken_zero, taken_nil] | 0 m l := sorry -- by rewrite [zero_min] | (succ n) (succ m) nil := sorry -- by rewrite [*taken_nil] | (succ n) (succ m) (a::l) := sorry -- by rewrite [*taken_cons, taken_taken, min_succ_succ] -/ lemma length_taken_le : ∀ (n) (l : list α), length (take n l) ≤ n | 0 l := begin rw [taken_zero], reflexivity end | (succ n) (a::l) := begin rw [taken_cons, length_cons], apply succ_le_succ, apply length_taken_le end | (succ n) [] := begin simp [take, length], apply zero_le end -- TODO(Jeremy): restore when we have min /- lemma length_taken_eq : ∀ (n) (l : list α), length (take n l) = min n (length l) | 0 l := sorry -- by rewrite [taken_zero, zero_min] | (succ n) (a::l) := sorry -- by rewrite [taken_cons, *length_cons, *add_one, min_succ_succ, length_taken_eq] | (succ n) [] := sorry -- by rewrite [taken_nil] -/ end take -- TODO(Jeremy): restore when we have nat.sub /- section drop -- 'drop n l' drops the first 'n' elements of 'l' theorem length_dropn : ∀ (i : ℕ) (l : list α), length (drop i l) = length l - i | 0 l := rfl | (succ i) [] := calc length (drop (succ i) []) = 0 - succ i : sorry -- by rewrite (nat.zero_sub (succ i)) | (succ i) (x::l) := calc length (drop (succ i) (x::l)) = length (drop i l) : by reflexivity ... = length l - i : length_dropn i l ... = succ (length l) - succ i : sorry -- by rewrite (succ_sub_succ (length l) i) end drop -/ section count variable [decidable_eq α] definition count (a : α) : list α → nat | [] := 0 | (x::xs) := if a = x then succ (count xs) else count xs @[simp] lemma count_nil (a : α) : count a [] = 0 := rfl lemma count_cons (a b : α) (l : list α) : count a (b :: l) = if a = b then succ (count a l) else count a l := rfl lemma count_cons' (a b : α) (l : list α) : count a (b :: l) = count a l + (if a = b then 1 else 0) := decidable.by_cases (suppose a = b, begin rw [count_cons, if_pos this, if_pos this] end) (suppose a ≠ b, begin rw [count_cons, if_neg this, if_neg this], reflexivity end) @[simp] lemma count_cons_self (a : α) (l : list α) : count a (a::l) = succ (count a l) := if_pos rfl @[simp] lemma count_cons_of_ne {a b : α} (h : a ≠ b) (l : list α) : count a (b::l) = count a l := if_neg h lemma count_cons_ge_count (a b : α) (l : list α) : count a (b :: l) ≥ count a l := decidable.by_cases (suppose a = b, begin subst b, rewrite count_cons_self, apply le_succ end) (suppose a ≠ b, begin rw (count_cons_of_ne this), apply le_refl end) -- TODO(Jeremy): without the reflexivity, this yields the goal "1 = 1". the first is from has_one, -- the second is succ 0. Make sure the simplifier can eventually handle this. lemma count_singleton (a : α) : count a [a] = 1 := by simp @[simp] lemma count_append (a : α) : ∀ l₁ l₂, count a (l₁ ++ l₂) = count a l₁ + count a l₂ | [] l₂ := begin rw [nil_append, count_nil, zero_add] end | (b::l₁) l₂ := decidable.by_cases (suppose a = b, by rw [←this, cons_append, count_cons_self, count_cons_self, succ_add, count_append]) (suppose a ≠ b, by rw [cons_append, count_cons_of_ne this, count_cons_of_ne this, count_append]) @[simp] lemma count_concat (a : α) (l : list α) : count a (concat l a) = succ (count a l) := by rw [concat_eq_append, count_append, count_singleton] lemma mem_of_count_pos : ∀ {a : α} {l : list α}, count a l > 0 → a ∈ l | a [] h := absurd h (lt_irrefl _) | a (b::l) h := decidable.by_cases (suppose a = b, begin subst b, apply mem_cons_self end) (suppose a ≠ b, have count a l > 0, begin rw [count_cons_of_ne this] at h, exact h end, have a ∈ l, from mem_of_count_pos this, show a ∈ b::l, from mem_cons_of_mem _ this) lemma count_pos_of_mem : ∀ {a : α} {l : list α}, a ∈ l → count a l > 0 | a [] h := absurd h (not_mem_nil _) | a (b::l) h := or.elim h (suppose a = b, begin subst b, rw count_cons_self, apply zero_lt_succ end) (suppose a ∈ l, calc count a (b::l) ≥ count a l : count_cons_ge_count _ _ _ ... > 0 : count_pos_of_mem this) lemma mem_iff_count_pos (a : α) (l : list α) : a ∈ l ↔ count a l > 0 := iff.intro count_pos_of_mem mem_of_count_pos @[simp] lemma count_eq_zero_of_not_mem {a : α} {l : list α} (h : a ∉ l) : count a l = 0 := have ∀ n, count a l = n → count a l = 0, begin intro n, cases n, { intro this, exact this }, intro this, exact absurd (mem_of_count_pos (begin rw this, exact dec_trivial end)) h end, this (count a l) rfl lemma not_mem_of_count_eq_zero {a : α} {l : list α} (h : count a l = 0) : a ∉ l := suppose a ∈ l, have count a l > 0, from count_pos_of_mem this, show false, begin rw h at this, exact nat.not_lt_zero _ this end end count end list
0499ada635408ad7f8850070bda6f84d1cf3599d
4727251e0cd73359b15b664c3170e5d754078599
/src/tactic/doc_commands.lean
f51df2877e074b9223215062a3bd1a01d5037622
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
17,315
lean
/- Copyright (c) 2020 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Y. Lewis -/ import tactic.fix_reflect_string /-! # Documentation commands We generate html documentation from mathlib. It is convenient to collect lists of tactics, commands, notes, etc. To facilitate this, we declare these documentation entries in the library using special commands. * `library_note` adds a note describing a certain feature or design decision. These can be referenced in doc strings with the text `note [name of note]`. * `add_tactic_doc` adds an entry documenting an interactive tactic, command, hole command, or attribute. Since these commands are used in files imported by `tactic.core`, this file has no imports. ## Implementation details `library_note note_id note_msg` creates a declaration `` `library_note.i `` for some `i`. This declaration is a pair of strings `note_id` and `note_msg`, and it gets tagged with the `library_note` attribute. Similarly, `add_tactic_doc` creates a declaration `` `tactic_doc.i `` that stores the provided information. -/ /-- A rudimentary hash function on strings. -/ def string.hash (s : string) : ℕ := s.fold 1 (λ h c, (33*h + c.val) % unsigned_sz) /-- `mk_hashed_name nspace id` hashes the string `id` to a value `i` and returns the name `nspace._i` -/ meta def string.mk_hashed_name (nspace : name) (id : string) : name := nspace <.> ("_" ++ to_string id.hash) open tactic /-- `copy_doc_string fr to` copies the docstring from the declaration named `fr` to each declaration named in the list `to`. -/ meta def tactic.copy_doc_string (fr : name) (to : list name) : tactic unit := do fr_ds ← doc_string fr, to.mmap' $ λ tgt, add_doc_string tgt fr_ds open lean lean.parser interactive /-- `copy_doc_string source → target_1 target_2 ... target_n` copies the doc string of the declaration named `source` to each of `target_1`, `target_2`, ..., `target_n`. -/ @[user_command] meta def copy_doc_string_cmd (_ : parse (tk "copy_doc_string")) : parser unit := do fr ← parser.ident, tk "->", to ← parser.many parser.ident, expr.const fr _ ← resolve_name fr, to ← parser.of_tactic (to.mmap $ λ n, expr.const_name <$> resolve_name n), tactic.copy_doc_string fr to /-! ### The `library_note` command -/ /-- A user attribute `library_note` for tagging decls of type `string × string` for use in note output. -/ @[user_attribute] meta def library_note_attr : user_attribute := { name := `library_note, descr := "Notes about library features to be included in documentation", parser := failed } /-- `mk_reflected_definition name val` constructs a definition declaration by reflection. Example: ``mk_reflected_definition `foo 17`` constructs the definition declaration corresponding to `def foo : ℕ := 17` -/ meta def mk_reflected_definition (decl_name : name) {type} [reflected type] (body : type) [reflected body] : declaration := mk_definition decl_name (reflect type).collect_univ_params (reflect type) (reflect body) /-- If `note_name` and `note` are `pexpr`s representing strings, `add_library_note note_name note` adds a declaration of type `string × string` and tags it with the `library_note` attribute. -/ meta def tactic.add_library_note (note_name note : string) : tactic unit := do let decl_name := note_name.mk_hashed_name `library_note, add_decl $ mk_reflected_definition decl_name (note_name, note), library_note_attr.set decl_name () tt none open tactic /-- A command to add library notes. Syntax: ``` /-- note message -/ library_note "note id" ``` -/ @[user_command] meta def library_note (mi : interactive.decl_meta_info) (_ : parse (tk "library_note")) : parser unit := do note_name ← parser.pexpr, note_name ← eval_pexpr string note_name, some doc_string ← pure mi.doc_string | fail "library_note requires a doc string", add_library_note note_name doc_string /-- Collects all notes in the current environment. Returns a list of pairs `(note_id, note_content)` -/ meta def tactic.get_library_notes : tactic (list (string × string)) := attribute.get_instances `library_note >>= list.mmap (λ dcl, mk_const dcl >>= eval_expr (string × string)) /-! ### The `add_tactic_doc_entry` command -/ /-- The categories of tactic doc entry. -/ @[derive [decidable_eq, has_reflect]] inductive doc_category | tactic | cmd | hole_cmd | attr /-- Format a `doc_category` -/ meta def doc_category.to_string : doc_category → string | doc_category.tactic := "tactic" | doc_category.cmd := "command" | doc_category.hole_cmd := "hole_command" | doc_category.attr := "attribute" meta instance : has_to_format doc_category := ⟨↑doc_category.to_string⟩ /-- The information used to generate a tactic doc entry -/ @[derive has_reflect] structure tactic_doc_entry := (name : string) (category : doc_category) (decl_names : list _root_.name) (tags : list string := []) (description : string := "") (inherit_description_from : option _root_.name := none) /-- Turns a `tactic_doc_entry` into a JSON representation. -/ meta def tactic_doc_entry.to_json (d : tactic_doc_entry) : json := json.object [ ("name", d.name), ("category", d.category.to_string), ("decl_names", d.decl_names.map (json.of_string ∘ to_string)), ("tags", d.tags.map json.of_string), ("description", d.description) ] meta instance : has_to_string tactic_doc_entry := ⟨json.unparse ∘ tactic_doc_entry.to_json⟩ /-- `update_description_from tde inh_id` replaces the `description` field of `tde` with the doc string of the declaration named `inh_id`. -/ meta def tactic_doc_entry.update_description_from (tde : tactic_doc_entry) (inh_id : name) : tactic tactic_doc_entry := do ds ← doc_string inh_id <|> fail (to_string inh_id ++ " has no doc string"), return { description := ds .. tde } /-- `update_description tde` replaces the `description` field of `tde` with: * the doc string of `tde.inherit_description_from`, if this field has a value * the doc string of the entry in `tde.decl_names`, if this field has length 1 If neither of these conditions are met, it returns `tde`. -/ meta def tactic_doc_entry.update_description (tde : tactic_doc_entry) : tactic tactic_doc_entry := match tde.inherit_description_from, tde.decl_names with | some inh_id, _ := tde.update_description_from inh_id | none, [inh_id] := tde.update_description_from inh_id | none, _ := return tde end /-- A user attribute `tactic_doc` for tagging decls of type `tactic_doc_entry` for use in doc output -/ @[user_attribute] meta def tactic_doc_entry_attr : user_attribute := { name := `tactic_doc, descr := "Information about a tactic to be included in documentation", parser := failed } /-- Collects everything in the environment tagged with the attribute `tactic_doc`. -/ meta def tactic.get_tactic_doc_entries : tactic (list tactic_doc_entry) := attribute.get_instances `tactic_doc >>= list.mmap (λ dcl, mk_const dcl >>= eval_expr tactic_doc_entry) /-- `add_tactic_doc tde` adds a declaration to the environment with `tde` as its body and tags it with the `tactic_doc` attribute. If `tde.decl_names` has exactly one entry `` `decl`` and if `tde.description` is the empty string, `add_tactic_doc` uses the doc string of `decl` as the description. -/ meta def tactic.add_tactic_doc (tde : tactic_doc_entry) : tactic unit := do when (tde.description = "" ∧ tde.inherit_description_from.is_none ∧ tde.decl_names.length ≠ 1) $ fail "A tactic doc entry must either: 1. have a description written as a doc-string for the `add_tactic_doc` invocation, or 2. have a single declaration in the `decl_names` field, to inherit a description from, or 3. explicitly indicate the declaration to inherit the description from using `inherit_description_from`.", tde ← if tde.description = "" then tde.update_description else return tde, let decl_name := (tde.name ++ tde.category.to_string).mk_hashed_name `tactic_doc, add_decl $ mk_definition decl_name [] `(tactic_doc_entry) (reflect tde), tactic_doc_entry_attr.set decl_name () tt none /-- A command used to add documentation for a tactic, command, hole command, or attribute. Usage: after defining an interactive tactic, command, or attribute, add its documentation as follows. ```lean /-- describe what the command does here -/ add_tactic_doc { name := "display name of the tactic", category := cat, decl_names := [`dcl_1, `dcl_2], tags := ["tag_1", "tag_2"] } ``` The argument to `add_tactic_doc` is a structure of type `tactic_doc_entry`. * `name` refers to the display name of the tactic; it is used as the header of the doc entry. * `cat` refers to the category of doc entry. Options: `doc_category.tactic`, `doc_category.cmd`, `doc_category.hole_cmd`, `doc_category.attr` * `decl_names` is a list of the declarations associated with this doc. For instance, the entry for `linarith` would set ``decl_names := [`tactic.interactive.linarith]``. Some entries may cover multiple declarations. It is only necessary to list the interactive versions of tactics. * `tags` is an optional list of strings used to categorize entries. * The doc string is the body of the entry. It can be formatted with markdown. What you are reading now is the description of `add_tactic_doc`. If only one related declaration is listed in `decl_names` and if this invocation of `add_tactic_doc` does not have a doc string, the doc string of that declaration will become the body of the tactic doc entry. If there are multiple declarations, you can select the one to be used by passing a name to the `inherit_description_from` field. If you prefer a tactic to have a doc string that is different then the doc entry, you should write the doc entry as a doc string for the `add_tactic_doc` invocation. Note that providing a badly formed `tactic_doc_entry` to the command can result in strange error messages. -/ @[user_command] meta def add_tactic_doc_command (mi : interactive.decl_meta_info) (_ : parse $ tk "add_tactic_doc") : parser unit := do pe ← parser.pexpr, e ← eval_pexpr tactic_doc_entry pe, let e : tactic_doc_entry := match mi.doc_string with | some desc := { description := desc, ..e } | none := e end, tactic.add_tactic_doc e . /-- At various places in mathlib, we leave implementation notes that are referenced from many other files. To keep track of these notes, we use the command `library_note`. This makes it easy to retrieve a list of all notes, e.g. for documentation output. These notes can be referenced in mathlib with the syntax `Note [note id]`. Often, these references will be made in code comments (`--`) that won't be displayed in docs. If such a reference is made in a doc string or module doc, it will be linked to the corresponding note in the doc display. Syntax: ``` /-- note message -/ library_note "note id" ``` An example from `meta.expr`: ``` /-- Some declarations work with open expressions, i.e. an expr that has free variables. Terms will free variables are not well-typed, and one should not use them in tactics like `infer_type` or `unify`. You can still do syntactic analysis/manipulation on them. The reason for working with open types is for performance: instantiating variables requires iterating through the expression. In one performance test `pi_binders` was more than 6x quicker than `mk_local_pis` (when applied to the type of all imported declarations 100x). -/ library_note "open expressions" ``` This note can be referenced near a usage of `pi_binders`: ``` -- See Note [open expressions] /-- behavior of f -/ def f := pi_binders ... ``` -/ add_tactic_doc { name := "library_note", category := doc_category.cmd, decl_names := [`library_note, `tactic.add_library_note], tags := ["documentation"], inherit_description_from := `library_note } add_tactic_doc { name := "add_tactic_doc", category := doc_category.cmd, decl_names := [`add_tactic_doc_command, `tactic.add_tactic_doc], tags := ["documentation"], inherit_description_from := `add_tactic_doc_command } add_tactic_doc { name := "copy_doc_string", category := doc_category.cmd, decl_names := [`copy_doc_string_cmd, `tactic.copy_doc_string], tags := ["documentation"], inherit_description_from := `copy_doc_string_cmd } -- add docs to core tactics /-- The congruence closure tactic `cc` tries to solve the goal by chaining equalities from context and applying congruence (i.e. if `a = b`, then `f a = f b`). It is a finishing tactic, i.e. it is meant to close the current goal, not to make some inconclusive progress. A mostly trivial example would be: ```lean example (a b c : ℕ) (f : ℕ → ℕ) (h: a = b) (h' : b = c) : f a = f c := by cc ``` As an example requiring some thinking to do by hand, consider: ```lean example (f : ℕ → ℕ) (x : ℕ) (H1 : f (f (f x)) = x) (H2 : f (f (f (f (f x)))) = x) : f x = x := by cc ``` The tactic works by building an equality matching graph. It's a graph where the vertices are terms and they are linked by edges if they are known to be equal. Once you've added all the equalities in your context, you take the transitive closure of the graph and, for each connected component (i.e. equivalence class) you can elect a term that will represent the whole class and store proofs that the other elements are equal to it. You then take the transitive closure of these equalities under the congruence lemmas. The `cc` implementation in Lean does a few more tricks: for example it derives `a=b` from `nat.succ a = nat.succ b`, and `nat.succ a != nat.zero` for any `a`. * The starting reference point is Nelson, Oppen, [Fast decision procedures based on congruence closure](http://www.cs.colorado.edu/~bec/courses/csci5535-s09/reading/nelson-oppen-congruence.pdf), Journal of the ACM (1980) * The congruence lemmas for dependent type theory as used in Lean are described in [Congruence closure in intensional type theory](https://leanprover.github.io/papers/congr.pdf) (de Moura, Selsam IJCAR 2016). -/ add_tactic_doc { name := "cc (congruence closure)", category := doc_category.tactic, decl_names := [`tactic.interactive.cc], tags := ["core", "finishing"] } /-- `conv {...}` allows the user to perform targeted rewriting on a goal or hypothesis, by focusing on particular subexpressions. See <https://leanprover-community.github.io/extras/conv.html> for more details. Inside `conv` blocks, mathlib currently additionally provides * `erw`, * `ring`, `ring2` and `ring_exp`, * `norm_num`, * `norm_cast`, * `apply_congr`, and * `conv` (within another `conv`). `apply_congr` applies congruence lemmas to step further inside expressions, and sometimes gives better results than the automatically generated congruence lemmas used by `congr`. Using `conv` inside a `conv` block allows the user to return to the previous state of the outer `conv` block after it is finished. Thus you can continue editing an expression without having to start a new `conv` block and re-scoping everything. For example: ```lean example (a b c d : ℕ) (h₁ : b = c) (h₂ : a + c = a + d) : a + b = a + d := by conv { to_lhs, conv { congr, skip, rw h₁ }, rw h₂, } ``` Without `conv`, the above example would need to be proved using two successive `conv` blocks, each beginning with `to_lhs`. Also, as a shorthand, `conv_lhs` and `conv_rhs` are provided, so that ```lean example : 0 + 0 = 0 := begin conv_lhs { simp } end ``` just means ```lean example : 0 + 0 = 0 := begin conv { to_lhs, simp } end ``` and likewise for `to_rhs`. -/ add_tactic_doc { name := "conv", category := doc_category.tactic, decl_names := [`tactic.interactive.conv], tags := ["core"] } add_tactic_doc { name := "simp", category := doc_category.tactic, decl_names := [`tactic.interactive.simp], tags := ["core", "simplification"] } /-- Accepts terms with the type `component tactic_state string` or `html empty` and renders them interactively. Requires a compatible version of the vscode extension to view the resulting widget. ### Example: ```lean /-- A simple counter that can be incremented or decremented with some buttons. -/ meta def counter_widget {π α : Type} : component π α := component.ignore_props $ component.mk_simple int int 0 (λ _ x y, (x + y, none)) (λ _ s, h "div" [] [ button "+" (1 : int), html.of_string $ to_string $ s, button "-" (-1) ] ) #html counter_widget ``` -/ add_tactic_doc { name := "#html", category := doc_category.cmd, decl_names := [`show_widget_cmd], tags := ["core", "widgets"] } /-- The `add_decl_doc` command is used to add a doc string to an existing declaration. ```lean def foo := 5 /-- Doc string for foo. -/ add_decl_doc foo ``` -/ @[user_command] meta def add_decl_doc_command (mi : interactive.decl_meta_info) (_ : parse $ tk "add_decl_doc") : parser unit := do n ← parser.ident, n ← resolve_constant n, some doc ← pure mi.doc_string | fail "add_decl_doc requires a doc string", add_doc_string n doc add_tactic_doc { name := "add_decl_doc", category := doc_category.cmd, decl_names := [``add_decl_doc_command], tags := ["documentation"] }
8f6163bc9f0344b99e82c2edf98123726fef6bcb
b147e1312077cdcfea8e6756207b3fa538982e12
/computability/partrec.lean
5da7da75d066a4f3b2e014407b9a3ecc49e0eac4
[ "Apache-2.0" ]
permissive
SzJS/mathlib
07836ee708ca27cd18347e1e11ce7dd5afb3e926
23a5591fca0d43ee5d49d89f6f0ee07a24a6ca29
refs/heads/master
1,584,980,332,064
1,532,063,841,000
1,532,063,841,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
28,402
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro The partial recursive functions are defined similarly to the primitive recursive functions, but now all functions are partial, implemented using the `roption` monad, and there is an additional operation, called μ-recursion, which performs unbounded minimization. -/ import computability.primrec data.pfun open encodable denumerable roption namespace nat section rfind parameter (p : ℕ →. bool) private def lbp (m n : ℕ) : Prop := m = n + 1 ∧ ∀ k ≤ n, ff ∈ p k parameter (H : ∃ n, tt ∈ p n ∧ ∀ k < n, (p k).dom) private def wf_lbp : well_founded lbp := ⟨let ⟨n, pn⟩ := H in begin suffices : ∀m k, n ≤ k + m → acc (lbp p) k, { from λa, this _ _ (nat.le_add_left _ _) }, intros m k kn, induction m with m IH generalizing k; refine ⟨_, λ y r, _⟩; rcases r with ⟨rfl, a⟩, { injection mem_unique pn.1 (a _ kn) }, { exact IH _ (by rw nat.add_right_comm; exact kn) } end⟩ def rfind_x : {n // tt ∈ p n ∧ ∀m < n, ff ∈ p m} := suffices ∀ k, (∀n < k, ff ∈ p n) → {n // tt ∈ p n ∧ ∀m < n, ff ∈ p m}, from this 0 (λ n, (nat.not_lt_zero _).elim), @well_founded.fix _ _ lbp wf_lbp begin intros m IH al, have pm : (p m).dom, { rcases H with ⟨n, h₁, h₂⟩, rcases lt_trichotomy m n with h₃|h₃|h₃, { exact h₂ _ h₃ }, { rw h₃, exact h₁.fst }, { injection mem_unique h₁ (al _ h₃) } }, cases e : (p m).get pm, { suffices, exact IH _ ⟨rfl, this⟩ (λ n h, this _ (le_of_lt_succ h)), intros n h, cases lt_or_eq_of_le h with h h, { exact al _ h }, { rw h, exact ⟨_, e⟩ } }, { exact ⟨m, ⟨_, e⟩, al⟩ } end end rfind def rfind (p : ℕ →. bool) : roption ℕ := ⟨_, λ h, (rfind_x p h).1⟩ theorem rfind_spec {p : ℕ →. bool} {n : ℕ} (h : n ∈ rfind p) : tt ∈ p n := h.snd ▸ (rfind_x p h.fst).2.1 theorem rfind_min {p : ℕ →. bool} {n : ℕ} (h : n ∈ rfind p) : ∀ {m : ℕ}, m < n → ff ∈ p m := h.snd ▸ (rfind_x p h.fst).2.2 @[simp] theorem rfind_dom {p : ℕ →. bool} : (rfind p).dom ↔ ∃ n, tt ∈ p n ∧ ∀ {m : ℕ}, m < n → (p m).dom := iff.rfl @[simp] theorem rfind_dom' {p : ℕ →. bool} : (rfind p).dom ↔ ∃ n, tt ∈ p n ∧ ∀ {m : ℕ}, m ≤ n → (p m).dom := exists_congr $ λ n, and_congr_right $ λ pn, ⟨λ H m h, (eq_or_lt_of_le h).elim (λ e, e.symm ▸ pn.fst) (H _), λ H m h, H (le_of_lt h)⟩ @[simp] theorem mem_rfind {p : ℕ →. bool} {n : ℕ} : n ∈ rfind p ↔ tt ∈ p n ∧ ∀ {m : ℕ}, m < n → ff ∈ p m := ⟨λ h, ⟨rfind_spec h, @rfind_min _ _ h⟩, λ ⟨h₁, h₂⟩, let ⟨m, hm⟩ := dom_iff_mem.1 $ (@rfind_dom p).2 ⟨_, h₁, λ m mn, (h₂ mn).fst⟩ in begin rcases lt_trichotomy m n with h|h|h, { injection mem_unique (h₂ h) (rfind_spec hm) }, { rwa ← h }, { injection mem_unique h₁ (rfind_min hm h) }, end⟩ theorem rfind_min' {p : ℕ → bool} {m : ℕ} (pm : p m) : ∃ n ∈ rfind p, n ≤ m := have tt ∈ (p : ℕ →. bool) m, from ⟨trivial, pm⟩, let ⟨n, hn⟩ := dom_iff_mem.1 $ (@rfind_dom p).2 ⟨m, this, λ k h, ⟨⟩⟩ in ⟨n, hn, not_lt.1 $ λ h, by injection mem_unique this (rfind_min hn h)⟩ theorem rfind_zero_none (p : ℕ →. bool) (p0 : p 0 = none) : rfind p = none := eq_none_iff.2 $ λ a h, let ⟨n, h₁, h₂⟩ := rfind_dom'.1 h.fst in (p0 ▸ h₂ (zero_le _) : (@roption.none bool).dom) def rfind_opt {α} (f : ℕ → option α) : roption α := (rfind (λ n, (f n).is_some)).bind (λ n, f n) theorem rfind_opt_spec {α} {f : ℕ → option α} {a} (h : a ∈ rfind_opt f) : ∃ n, a ∈ f n := let ⟨n, h₁, h₂⟩ := mem_bind_iff.1 h in ⟨n, mem_coe.1 h₂⟩ theorem rfind_opt_dom {α} {f : ℕ → option α} : (rfind_opt f).dom ↔ ∃ n a, a ∈ f n := ⟨λ h, (rfind_opt_spec ⟨h, rfl⟩).imp (λ n h, ⟨_, h⟩), λ h, begin have h' : ∃ n, (f n).is_some := h.imp (λ n, option.is_some_iff_exists.2), have s := nat.find_spec h', have fd : (rfind (λ n, (f n).is_some)).dom := ⟨nat.find h', by simpa using s.symm, λ _ _, trivial⟩, refine ⟨fd, _⟩, have := rfind_spec (get_mem fd), simp at this ⊢, cases option.is_some_iff_exists.1 this.symm with a e, rw e, trivial end⟩ theorem rfind_opt_mono {α} {f : ℕ → option α} (H : ∀ {a m n}, m ≤ n → a ∈ f m → a ∈ f n) {a} : a ∈ rfind_opt f ↔ ∃ n, a ∈ f n := ⟨rfind_opt_spec, λ ⟨n, h⟩, begin have h' := rfind_opt_dom.2 ⟨_, _, h⟩, cases rfind_opt_spec ⟨h', rfl⟩ with k hk, have := (H (le_max_left _ _) h).symm.trans (H (le_max_right _ _) hk), simp at this, simp [this, get_mem] end⟩ inductive partrec : (ℕ →. ℕ) → Prop | zero : partrec (pure 0) | succ : partrec succ | left : partrec (λ n, n.unpair.1) | right : partrec (λ n, n.unpair.2) | pair {f g} : partrec f → partrec g → partrec (λ n, mkpair <$> f n <*> g n) | comp {f g} : partrec f → partrec g → partrec (λ n, g n >>= f) | prec {f g} : partrec f → partrec g → partrec (unpaired (λ a n, n.elim (f a) (λ y IH, do i ← IH, g (mkpair a (mkpair y i))))) | rfind {f} : partrec f → partrec (λ a, rfind (λ n, (λ m, m = 0) <$> f (mkpair a n))) namespace partrec theorem of_eq {f g : ℕ →. ℕ} (hf : partrec f) (H : ∀ n, f n = g n) : partrec g := (funext H : f = g) ▸ hf theorem of_eq_tot {f : ℕ →. ℕ} {g : ℕ → ℕ} (hf : partrec f) (H : ∀ n, g n ∈ f n) : partrec g := hf.of_eq (λ n, eq_some_iff.2 (H n)) theorem of_primrec {f : ℕ → ℕ} (hf : primrec f) : partrec f := begin induction hf, case nat.primrec.zero { exact zero }, case nat.primrec.succ { exact succ }, case nat.primrec.left { exact left }, case nat.primrec.right { exact right }, case nat.primrec.pair : f g hf hg pf pg { refine (pf.pair pg).of_eq_tot (λ n, _), simp [has_seq.seq] }, case nat.primrec.comp : f g hf hg pf pg { refine (pf.comp pg).of_eq_tot (λ n, _), simp }, case nat.primrec.prec : f g hf hg pf pg { refine (pf.prec pg).of_eq_tot (λ n, _), simp, induction n.unpair.2 with m IH, {simp}, simp, exact ⟨_, IH, rfl⟩ }, end protected theorem some : partrec some := of_primrec primrec.id theorem none : partrec (λ n, none) := (of_primrec (nat.primrec.const 1)).rfind.of_eq $ λ n, eq_none_iff.2 $ λ a ⟨h, e⟩, by simpa using h theorem prec' {f g h} (hf : partrec f) (hg : partrec g) (hh : partrec h) : partrec (λ a, (f a).bind (λ n, n.elim (g a) (λ y IH, do i ← IH, h (mkpair a (mkpair y i))))) := ((prec hg hh).comp (pair partrec.some hf)).of_eq $ λ a, ext $ λ s, by simp [(<*>)]; exact ⟨λ ⟨n, h₁, h₂⟩, ⟨_, ⟨_, h₁, rfl⟩, by simpa using h₂⟩, λ ⟨_, ⟨n, h₁, rfl⟩, h₂⟩, ⟨_, h₁, by simpa using h₂⟩⟩ theorem ppred : partrec (λ n, ppred n) := have primrec₂ (λ n m, if n = nat.succ m then 0 else 1), from (primrec.ite (@@primrec_rel.comp _ _ _ _ _ _ _ primrec.eq primrec.fst (_root_.primrec.succ.comp primrec.snd)) (_root_.primrec.const 0) (_root_.primrec.const 1)).to₂, (of_primrec (primrec₂.unpaired'.2 this)).rfind.of_eq $ λ n, begin cases n; simp, { exact eq_none_iff.2 (λ a ⟨⟨m, h, _⟩, _⟩, by simpa [show 0 ≠ m.succ, by intro h; injection h] using h) }, { refine eq_some_iff.2 _, simp, intros m h, simp [ne_of_gt h] } end end partrec end nat def partrec {α σ} [primcodable α] [primcodable σ] (f : α →. σ) := nat.partrec (λ n, roption.bind (decode α n) (λ a, (f a).map encode)) def partrec₂ {α β σ} [primcodable α] [primcodable β] [primcodable σ] (f : α → β →. σ) := partrec (λ p : α × β, f p.1 p.2) def computable {α σ} [primcodable α] [primcodable σ] (f : α → σ) := partrec (f : α →. σ) def computable₂ {α β σ} [primcodable α] [primcodable β] [primcodable σ] (f : α → β → σ) := computable (λ p : α × β, f p.1 p.2) theorem primrec.to_comp {α σ} [primcodable α] [primcodable σ] {f : α → σ} (hf : primrec f) : computable f := (nat.partrec.ppred.comp (nat.partrec.of_primrec hf)).of_eq $ λ n, by simp; cases decode α n; simp [option.map, option.bind] theorem primrec₂.to_comp {α β σ} [primcodable α] [primcodable β] [primcodable σ] {f : α → β → σ} (hf : primrec₂ f) : computable₂ f := hf.to_comp theorem computable.part {α σ} [primcodable α] [primcodable σ] {f : α → σ} (hf : computable f) : partrec (f : α →. σ) := hf theorem computable₂.part {α β σ} [primcodable α] [primcodable β] [primcodable σ] {f : α → β → σ} (hf : computable₂ f) : partrec₂ (λ a, (f a : β →. σ)) := hf namespace computable variables {α : Type*} {β : Type*} {γ : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable γ] [primcodable σ] theorem of_eq {f g : α → σ} (hf : computable f) (H : ∀ n, f n = g n) : computable g := (funext H : f = g) ▸ hf theorem const (s : σ) : computable (λ a : α, s) := (primrec.const _).to_comp theorem of_option {f : α → option β} (hf : computable f) : partrec (λ a, (f a : roption β)) := (nat.partrec.ppred.comp hf).of_eq $ λ n, begin cases decode α n with a; simp, cases f a with b; simp end theorem to₂ {f : α × β → σ} (hf : computable f) : computable₂ (λ a b, f (a, b)) := hf.of_eq $ λ ⟨a, b⟩, rfl protected theorem id : computable (@id α) := primrec.id.to_comp theorem fst : computable (@prod.fst α β) := primrec.fst.to_comp theorem snd : computable (@prod.snd α β) := primrec.snd.to_comp theorem pair {f : α → β} {g : α → γ} (hf : computable f) (hg : computable g) : computable (λ a, (f a, g a)) := (hf.pair hg).of_eq $ λ n, by cases decode α n; simp [(<*>)] theorem unpair : computable nat.unpair := primrec.unpair.to_comp theorem succ : computable nat.succ := primrec.succ.to_comp theorem pred : computable nat.pred := primrec.pred.to_comp theorem nat_bodd : computable nat.bodd := primrec.nat_bodd.to_comp theorem nat_div2 : computable nat.div2 := primrec.nat_div2.to_comp theorem sum_inl : computable (@sum.inl α β) := primrec.sum_inl.to_comp theorem sum_inr : computable (@sum.inr α β) := primrec.sum_inr.to_comp theorem list_cons : computable₂ (@list.cons α) := primrec.list_cons.to_comp theorem list_reverse : computable (@list.reverse α) := primrec.list_reverse.to_comp theorem list_nth : computable₂ (@list.nth α) := primrec.list_nth.to_comp theorem list_append : computable₂ ((++) : list α → list α → list α) := primrec.list_append.to_comp theorem list_concat : computable₂ (λ l (a:α), l ++ [a]) := primrec.list_concat.to_comp theorem list_length : computable (@list.length α) := primrec.list_length.to_comp theorem vector_cons {n} : computable₂ (@vector.cons α n) := primrec.vector_cons.to_comp theorem vector_to_list {n} : computable (@vector.to_list α n) := primrec.vector_to_list.to_comp theorem vector_length {n} : computable (@vector.length α n) := primrec.vector_length.to_comp theorem vector_head {n} : computable (@vector.head α n) := primrec.vector_head.to_comp theorem vector_tail {n} : computable (@vector.tail α n) := primrec.vector_tail.to_comp theorem vector_nth {n} : computable₂ (@vector.nth α n) := primrec.vector_nth.to_comp theorem vector_nth' {n} : computable (@vector.nth α n) := primrec.vector_nth'.to_comp theorem vector_of_fn' {n} : computable (@vector.of_fn α n) := primrec.vector_of_fn'.to_comp theorem fin_app {n} : computable₂ (@id (fin n → σ)) := primrec.fin_app.to_comp protected theorem encode : computable (@encode α _) := primrec.encode.to_comp protected theorem decode : computable (decode α) := primrec.decode.to_comp protected theorem of_nat (α) [denumerable α] : computable (of_nat α) := (primrec.of_nat _).to_comp theorem encode_iff {f : α → σ} : computable (λ a, encode (f a)) ↔ computable f := iff.rfl theorem option_some : computable (@option.some α) := primrec.option_some.to_comp end computable namespace partrec variables {α : Type*} {β : Type*} {γ : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable γ] [primcodable σ] open computable theorem of_eq {f g : α →. σ} (hf : partrec f) (H : ∀ n, f n = g n) : partrec g := (funext H : f = g) ▸ hf theorem of_eq_tot {f : α →. σ} {g : α → σ} (hf : partrec f) (H : ∀ n, g n ∈ f n) : computable g := hf.of_eq (λ a, eq_some_iff.2 (H a)) theorem none : partrec (λ a : α, @roption.none σ) := nat.partrec.none.of_eq $ λ n, by cases decode α n; simp protected theorem some : partrec (@roption.some α) := computable.id theorem const' (s : roption σ) : partrec (λ a : α, s) := by haveI := classical.dec s.dom; exact (of_option (const (to_option s))).of_eq (λ a, of_to_option s) protected theorem bind {f : α →. β} {g : α → β →. σ} (hf : partrec f) (hg : partrec₂ g) : partrec (λ a, (f a).bind (g a)) := (hg.comp (nat.partrec.some.pair hf)).of_eq $ λ n, by simp [(<*>)]; cases e : decode α n with a; simp [e, option.bind, option.map, encodek] theorem map {f : α →. β} {g : α → β → σ} (hf : partrec f) (hg : computable₂ g) : partrec (λ a, (f a).map (g a)) := by simpa [bind_some_eq_map] using @@partrec.bind _ _ _ (λ a b, roption.some (g a b)) hf hg theorem to₂ {f : α × β →. σ} (hf : partrec f) : partrec₂ (λ a b, f (a, b)) := hf.of_eq $ λ ⟨a, b⟩, rfl theorem nat_elim {f : α → ℕ} {g : α →. σ} {h : α → ℕ × σ →. σ} (hf : computable f) (hg : partrec g) (hh : partrec₂ h) : partrec (λ a, (f a).elim (g a) (λ y IH, IH.bind (λ i, h a (y, i)))) := (nat.partrec.prec' hf hg hh).of_eq $ λ n, begin cases e : decode α n with a; simp [e], induction f a with m IH; simp, rw [IH, bind_map], congr, funext s, simp [option.map, option.bind, encodek] end theorem comp {f : β →. σ} {g : α → β} (hf : partrec f) (hg : computable g) : partrec (λ a, f (g a)) := (hf.comp hg).of_eq $ λ n, by simp; cases e : decode α n with a; simp [e, option.bind, option.map, encodek] theorem nat_iff {f : ℕ →. ℕ} : partrec f ↔ nat.partrec f := by simp [partrec, map_id'] theorem map_encode_iff {f : α →. σ} : partrec (λ a, (f a).map encode) ↔ partrec f := iff.rfl end partrec namespace partrec₂ variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable γ] [primcodable δ] [primcodable σ] theorem unpaired {f : ℕ → ℕ →. α} : partrec (nat.unpaired f) ↔ partrec₂ f := ⟨λ h, by simpa using h.comp primrec₂.mkpair.to_comp, λ h, h.comp primrec.unpair.to_comp⟩ theorem unpaired' {f : ℕ → ℕ →. ℕ} : nat.partrec (nat.unpaired f) ↔ partrec₂ f := partrec.nat_iff.symm.trans unpaired theorem comp {f : β → γ →. σ} {g : α → β} {h : α → γ} (hf : partrec₂ f) (hg : computable g) (hh : computable h) : partrec (λ a, f (g a) (h a)) := hf.comp (hg.pair hh) theorem comp₂ {f : γ → δ →. σ} {g : α → β → γ} {h : α → β → δ} (hf : partrec₂ f) (hg : computable₂ g) (hh : computable₂ h) : partrec₂ (λ a b, f (g a b) (h a b)) := hf.comp hg hh end partrec₂ namespace computable variables {α : Type*} {β : Type*} {γ : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable γ] [primcodable σ] theorem comp {f : β → σ} {g : α → β} (hf : computable f) (hg : computable g) : computable (λ a, f (g a)) := hf.comp hg theorem comp₂ {f : γ → σ} {g : α → β → γ} (hf : computable f) (hg : computable₂ g) : computable₂ (λ a b, f (g a b)) := hf.comp hg end computable namespace computable₂ variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable γ] [primcodable δ] [primcodable σ] theorem comp {f : β → γ → σ} {g : α → β} {h : α → γ} (hf : computable₂ f) (hg : computable g) (hh : computable h) : computable (λ a, f (g a) (h a)) := hf.comp (hg.pair hh) theorem comp₂ {f : γ → δ → σ} {g : α → β → γ} {h : α → β → δ} (hf : computable₂ f) (hg : computable₂ g) (hh : computable₂ h) : computable₂ (λ a b, f (g a b) (h a b)) := hf.comp hg hh end computable₂ namespace partrec variables {α : Type*} {β : Type*} {γ : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable γ] [primcodable σ] open computable theorem rfind {p : α → ℕ →. bool} (hp : partrec₂ p) : partrec (λ a, nat.rfind (p a)) := (nat.partrec.rfind $ hp.map ((primrec.dom_bool (λ b, cond b 0 1)) .comp primrec.snd).to₂.to_comp).of_eq $ λ n, begin cases e : decode α n with a; simp [e, option.bind, option.map, nat.rfind_zero_none, map_id'], congr, funext n, simp [roption.map_map, (∘)], apply map_id' (λ b, _), cases b; refl end theorem rfind_opt {f : α → ℕ → option σ} (hf : computable₂ f) : partrec (λ a, nat.rfind_opt (f a)) := (rfind (primrec.option_is_some.to_comp.comp hf).part.to₂).bind (of_option hf) theorem nat_cases_right {f : α → ℕ} {g : α → σ} {h : α → ℕ →. σ} (hf : computable f) (hg : computable g) (hh : partrec₂ h) : partrec (λ a, (f a).cases (some (g a)) (h a)) := (nat_elim hf hg (hh.comp fst (pred.comp $ hf.comp fst)).to₂).of_eq $ λ a, begin simp, cases f a; simp, refine ext (λ b, ⟨λ H, _, λ H, _⟩), { rcases mem_bind_iff.1 H with ⟨c, h₁, h₂⟩, exact h₂ }, { have : ∀ m, (nat.elim (roption.some (g a)) (λ y IH, IH.bind (λ _, h a n)) m).dom, { intro, induction m; simp [*, H.fst] }, exact ⟨⟨this n, H.fst⟩, H.snd⟩ } end theorem bind_decode2_iff {f : α →. σ} : partrec f ↔ nat.partrec (λ n, roption.bind (decode2 α n) (λ a, (f a).map encode)) := ⟨λ hf, nat_iff.1 $ (of_option primrec.decode2.to_comp).bind $ (map hf (computable.encode.comp snd).to₂).comp snd, λ h, map_encode_iff.1 $ by simpa [encodek2] using (nat_iff.2 h).comp (@computable.encode α _)⟩ theorem vector_m_of_fn : ∀ {n} {f : fin n → α →. σ}, (∀ i, partrec (f i)) → partrec (λ (a : α), vector.m_of_fn (λ i, f i a)) | 0 f hf := const _ | (n+1) f hf := by simp [vector.m_of_fn]; exact (hf 0).bind (partrec.bind ((vector_m_of_fn (λ i, hf i.succ)).comp fst) (primrec.vector_cons.to_comp.comp (snd.comp fst) snd)) end partrec @[simp] theorem vector.m_of_fn_roption_some {α n} : ∀ (f : fin n → α), vector.m_of_fn (λ i, roption.some (f i)) = roption.some (vector.of_fn f) := vector.m_of_fn_pure namespace computable variables {α : Type*} {β : Type*} {γ : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable γ] [primcodable σ] theorem option_some_iff {f : α → σ} : computable (λ a, some (f a)) ↔ computable f := ⟨λ h, encode_iff.1 $ primrec.pred.to_comp.comp $ encode_iff.2 h, option_some.comp⟩ theorem bind_decode_iff {f : α → β → option σ} : computable₂ (λ a n, (decode β n).bind (f a)) ↔ computable₂ f := ⟨λ hf, nat.partrec.of_eq (((partrec.nat_iff.2 (nat.partrec.ppred.comp $ nat.partrec.of_primrec $ primcodable.prim β)).comp snd).bind (computable.comp hf fst).to₂.part) $ λ n, by simp; cases decode α n.unpair.1; simp [option.bind, option.map]; cases decode β n.unpair.2; simp [option.bind, option.map], λ hf, begin have : partrec (λ a : α × ℕ, (encode (decode β a.2)).cases (some option.none) (λ n, roption.map (f a.1) (decode β n))) := partrec.nat_cases_right (primrec.encdec.to_comp.comp snd) (const none) ((of_option (computable.decode.comp snd)).map (hf.comp (fst.comp $ fst.comp fst) snd).to₂), refine this.of_eq (λ a, _), simp, cases decode β a.2; simp [option.bind, option.map, encodek] end⟩ theorem map_decode_iff {f : α → β → σ} : computable₂ (λ a n, (decode β n).map (f a)) ↔ computable₂ f := bind_decode_iff.trans option_some_iff theorem nat_elim {f : α → ℕ} {g : α → σ} {h : α → ℕ × σ → σ} (hf : computable f) (hg : computable g) (hh : computable₂ h) : computable (λ a, (f a).elim (g a) (λ y IH, h a (y, IH))) := (partrec.nat_elim hf hg hh.part).of_eq $ λ a, by simp; induction f a; simp * theorem nat_cases {f : α → ℕ} {g : α → σ} {h : α → ℕ → σ} (hf : computable f) (hg : computable g) (hh : computable₂ h) : computable (λ a, (f a).cases (g a) (h a)) := nat_elim hf hg (hh.comp fst $ fst.comp snd).to₂ theorem cond {c : α → bool} {f : α → σ} {g : α → σ} (hc : computable c) (hf : computable f) (hg : computable g) : computable (λ a, cond (c a) (f a) (g a)) := (nat_cases (encode_iff.2 hc) hg (hf.comp fst).to₂).of_eq $ λ a, by cases c a; refl theorem option_cases {o : α → option β} {f : α → σ} {g : α → β → σ} (ho : computable o) (hf : computable f) (hg : computable₂ g) : @computable _ σ _ _ (λ a, option.cases_on (o a) (f a) (g a)) := option_some_iff.1 $ (nat_cases (encode_iff.2 ho) (option_some_iff.2 hf) (map_decode_iff.2 hg)).of_eq $ λ a, by cases o a; simp [encodek]; refl theorem option_bind {f : α → option β} {g : α → β → option σ} (hf : computable f) (hg : computable₂ g) : computable (λ a, (f a).bind (g a)) := (option_cases hf (const option.none) hg).of_eq $ λ a, by cases f a; refl theorem option_map {f : α → option β} {g : α → β → σ} (hf : computable f) (hg : computable₂ g) : computable (λ a, (f a).map (g a)) := option_bind hf (option_some.comp₂ hg) theorem sum_cases {f : α → β ⊕ γ} {g : α → β → σ} {h : α → γ → σ} (hf : computable f) (hg : computable₂ g) (hh : computable₂ h) : @computable _ σ _ _ (λ a, sum.cases_on (f a) (g a) (h a)) := option_some_iff.1 $ (cond (nat_bodd.comp $ encode_iff.2 hf) (option_map (computable.decode.comp $ nat_div2.comp $ encode_iff.2 hf) hh) (option_map (computable.decode.comp $ nat_div2.comp $ encode_iff.2 hf) hg)).of_eq $ λ a, by cases f a with b c; simp [nat.div2_bit, nat.bodd_bit, encodek]; refl theorem nat_strong_rec (f : α → ℕ → σ) {g : α → list σ → option σ} (hg : computable₂ g) (H : ∀ a n, g a ((list.range n).map (f a)) = some (f a n)) : computable₂ f := suffices computable₂ (λ a n, (list.range n).map (f a)), from option_some_iff.1 $ (list_nth.comp (this.comp fst (succ.comp snd)) snd).to₂.of_eq $ λ a, by simp [list.nth_range (nat.lt_succ_self a.2)]; refl, option_some_iff.1 $ (nat_elim snd (const (option.some [])) (to₂ $ option_bind (snd.comp snd) $ to₂ $ option_map (hg.comp (fst.comp $ fst.comp fst) snd) (to₂ $ list_concat.comp (snd.comp fst) snd))).of_eq $ λ a, begin simp, induction a.2 with n IH, {refl}, simp [IH, H, list.range_concat, option.bind] end theorem list_of_fn : ∀ {n} {f : fin n → α → σ}, (∀ i, computable (f i)) → computable (λ a, list.of_fn (λ i, f i a)) | 0 f hf := const [] | (n+1) f hf := by simp [list.of_fn_succ]; exact list_cons.comp (hf 0) (list_of_fn (λ i, hf i.succ)) theorem vector_of_fn {n} {f : fin n → α → σ} (hf : ∀ i, computable (f i)) : computable (λ a, vector.of_fn (λ i, f i a)) := (partrec.vector_m_of_fn hf).of_eq $ λ a, by simp end computable namespace partrec variables {α : Type*} {β : Type*} {γ : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable γ] [primcodable σ] open computable theorem option_some_iff {f : α →. σ} : partrec (λ a, (f a).map option.some) ↔ partrec f := ⟨λ h, (nat.partrec.ppred.comp h).of_eq $ λ n, by simp [roption.bind_assoc, bind_some_eq_map], λ hf, hf.map (option_some.comp snd).to₂⟩ theorem option_cases_right {o : α → option β} {f : α → σ} {g : α → β →. σ} (ho : computable o) (hf : computable f) (hg : partrec₂ g) : @partrec _ σ _ _ (λ a, option.cases_on (o a) (some (f a)) (g a)) := have partrec (λ (a : α), nat.cases (roption.some (f a)) (λ n, roption.bind (decode β n) (g a)) (encode (o a))) := nat_cases_right (encode_iff.2 ho) hf.part $ ((@computable.decode β _).comp snd).of_option.bind (hg.comp (fst.comp fst) snd).to₂, this.of_eq $ λ a, by cases o a with b; simp [encodek] theorem sum_cases_right {f : α → β ⊕ γ} {g : α → β → σ} {h : α → γ →. σ} (hf : computable f) (hg : computable₂ g) (hh : partrec₂ h) : @partrec _ σ _ _ (λ a, sum.cases_on (f a) (λ b, some (g a b)) (h a)) := have partrec (λ a, (option.cases_on (sum.cases_on (f a) (λ b, option.none) option.some : option γ) (some (sum.cases_on (f a) (λ b, some (g a b)) (λ c, option.none))) (λ c, (h a c).map option.some) : roption (option σ))) := option_cases_right (sum_cases hf (const option.none).to₂ (option_some.comp snd).to₂) (sum_cases hf (option_some.comp hg) (const option.none).to₂) (option_some_iff.2 hh), option_some_iff.1 $ this.of_eq $ λ a, by cases f a; simp theorem sum_cases_left {f : α → β ⊕ γ} {g : α → β →. σ} {h : α → γ → σ} (hf : computable f) (hg : partrec₂ g) (hh : computable₂ h) : @partrec _ σ _ _ (λ a, sum.cases_on (f a) (g a) (λ c, some (h a c))) := (sum_cases_right (sum_cases hf (sum_inr.comp snd).to₂ (sum_inl.comp snd).to₂) hh hg).of_eq $ λ a, by cases f a; simp private lemma fix_aux {f : α →. σ ⊕ α} (hf : partrec f) (a : α) (b : σ) : let F : α → ℕ →. σ ⊕ α := λ a n, n.elim (some (sum.inr a)) $ λ y IH, IH.bind $ λ s, sum.cases_on s (λ _, roption.some s) f in (∃ (n : ℕ), ((∃ (b' : σ), sum.inl b' ∈ F a n) ∧ ∀ {m : ℕ}, m < n → (∃ (b : α), sum.inr b ∈ F a m)) ∧ sum.inl b ∈ F a n) ↔ b ∈ pfun.fix f a := begin intro, refine ⟨λ h, _, λ h, _⟩, { rcases h with ⟨n, ⟨_x, h₁⟩, h₂⟩, have : ∀ m a' (_: sum.inr a' ∈ F a m) (_: b ∈ pfun.fix f a'), b ∈ pfun.fix f a, { intros m a' am ba, induction m with m IH generalizing a'; simp [F] at am, { rwa ← am }, rcases am with ⟨a₂, am₂, fa₂⟩, exact IH _ am₂ (pfun.mem_fix_iff.2 (or.inr ⟨_, fa₂, ba⟩)) }, cases n; simp [F] at h₂, {cases h₂}, rcases h₂ with h₂ | ⟨a', am', fa'⟩, { cases h₁ (nat.lt_succ_self _) with a' h, injection mem_unique h h₂ }, { exact this _ _ am' (pfun.mem_fix_iff.2 (or.inl fa')) } }, { suffices : ∀ a' (_: b ∈ pfun.fix f a') k (_: sum.inr a' ∈ F a k), ∃ n, sum.inl b ∈ F a n ∧ ∀ (m < n) (_ : k ≤ m), ∃ a₂, sum.inr a₂ ∈ F a m, { rcases this _ h 0 (by simp [F]) with ⟨n, hn₁, hn₂⟩, exact ⟨_, ⟨⟨_, hn₁⟩, λ m mn, hn₂ m mn (nat.zero_le _)⟩, hn₁⟩ }, intros a₁ h₁, apply pfun.fix_induction h₁, intros a₂ h₂ IH k hk, rcases pfun.mem_fix_iff.1 h₂ with h₂ | ⟨a₃, am₃, fa₃⟩, { refine ⟨k.succ, _, λ m mk km, ⟨a₂, _⟩⟩, { simp [F], exact or.inr ⟨_, hk, h₂⟩ }, { rwa le_antisymm (nat.le_of_lt_succ mk) km } }, { rcases IH _ fa₃ am₃ k.succ _ with ⟨n, hn₁, hn₂⟩, { refine ⟨n, hn₁, λ m mn km, _⟩, cases lt_or_eq_of_le km with km km, { exact hn₂ _ mn km }, { exact km ▸ ⟨_, hk⟩ } }, { simp [F], exact ⟨_, hk, am₃⟩ } } } end theorem fix {f : α →. σ ⊕ α} (hf : partrec f) : partrec (pfun.fix f) := let F : α → ℕ →. σ ⊕ α := λ a n, n.elim (some (sum.inr a)) $ λ y IH, IH.bind $ λ s, sum.cases_on s (λ _, roption.some s) f in have hF : partrec₂ F := partrec.nat_elim snd (sum_inr.comp fst).part (sum_cases_right (snd.comp snd) (snd.comp $ snd.comp fst).to₂ (hf.comp snd).to₂).to₂, let p := λ a n, @roption.map _ bool (λ s, sum.cases_on s (λ_, tt) (λ _, ff)) (F a n) in have hp : partrec₂ p := hF.map ((sum_cases computable.id (const tt).to₂ (const ff).to₂).comp snd).to₂, (hp.rfind.bind (hF.bind (sum_cases_right snd snd.to₂ none.to₂).to₂).to₂).of_eq $ λ a, ext $ λ b, by simp; apply fix_aux hf end partrec
986f5c68ff52b89a01d85926c38a9b99fa33888c
592ee40978ac7604005a4e0d35bbc4b467389241
/Library/generated/mathscheme-lean/MedialQuasiGroup.lean
d1bec6c1367a0826d9dd0851fc9a5f2c7469c97a
[]
no_license
ysharoda/Deriving-Definitions
3e149e6641fae440badd35ac110a0bd705a49ad2
dfecb27572022de3d4aa702cae8db19957523a59
refs/heads/master
1,679,127,857,700
1,615,939,007,000
1,615,939,007,000
229,785,731
4
0
null
null
null
null
UTF-8
Lean
false
false
12,369
lean
import init.data.nat.basic import init.data.fin.basic import data.vector import .Prelude open Staged open nat open fin open vector section MedialQuasiGroup structure MedialQuasiGroup (A : Type) : Type := (op : (A → (A → A))) (linv : (A → (A → A))) (leftCancel : (∀ {x y : A} , (op x (linv x y)) = y)) (lefCancelOp : (∀ {x y : A} , (linv x (op x y)) = y)) (rinv : (A → (A → A))) (rightCancel : (∀ {x y : A} , (op (rinv y x) x) = y)) (rightCancelOp : (∀ {x y : A} , (rinv (op y x) x) = y)) (mediates : (∀ {w x y z : A} , (op (op x y) (op z w)) = (op (op x z) (op y w)))) open MedialQuasiGroup structure Sig (AS : Type) : Type := (opS : (AS → (AS → AS))) (linvS : (AS → (AS → AS))) (rinvS : (AS → (AS → AS))) structure Product (A : Type) : Type := (opP : ((Prod A A) → ((Prod A A) → (Prod A A)))) (linvP : ((Prod A A) → ((Prod A A) → (Prod A A)))) (rinvP : ((Prod A A) → ((Prod A A) → (Prod A A)))) (leftCancelP : (∀ {xP yP : (Prod A A)} , (opP xP (linvP xP yP)) = yP)) (lefCancelOpP : (∀ {xP yP : (Prod A A)} , (linvP xP (opP xP yP)) = yP)) (rightCancelP : (∀ {xP yP : (Prod A A)} , (opP (rinvP yP xP) xP) = yP)) (rightCancelOpP : (∀ {xP yP : (Prod A A)} , (rinvP (opP yP xP) xP) = yP)) (mediatesP : (∀ {wP xP yP zP : (Prod A A)} , (opP (opP xP yP) (opP zP wP)) = (opP (opP xP zP) (opP yP wP)))) structure Hom {A1 : Type} {A2 : Type} (Me1 : (MedialQuasiGroup A1)) (Me2 : (MedialQuasiGroup A2)) : Type := (hom : (A1 → A2)) (pres_op : (∀ {x1 x2 : A1} , (hom ((op Me1) x1 x2)) = ((op Me2) (hom x1) (hom x2)))) (pres_linv : (∀ {x1 x2 : A1} , (hom ((linv Me1) x1 x2)) = ((linv Me2) (hom x1) (hom x2)))) (pres_rinv : (∀ {x1 x2 : A1} , (hom ((rinv Me1) x1 x2)) = ((rinv Me2) (hom x1) (hom x2)))) structure RelInterp {A1 : Type} {A2 : Type} (Me1 : (MedialQuasiGroup A1)) (Me2 : (MedialQuasiGroup A2)) : Type 1 := (interp : (A1 → (A2 → Type))) (interp_op : (∀ {x1 x2 : A1} {y1 y2 : A2} , ((interp x1 y1) → ((interp x2 y2) → (interp ((op Me1) x1 x2) ((op Me2) y1 y2)))))) (interp_linv : (∀ {x1 x2 : A1} {y1 y2 : A2} , ((interp x1 y1) → ((interp x2 y2) → (interp ((linv Me1) x1 x2) ((linv Me2) y1 y2)))))) (interp_rinv : (∀ {x1 x2 : A1} {y1 y2 : A2} , ((interp x1 y1) → ((interp x2 y2) → (interp ((rinv Me1) x1 x2) ((rinv Me2) y1 y2)))))) inductive MedialQuasiGroupTerm : Type | opL : (MedialQuasiGroupTerm → (MedialQuasiGroupTerm → MedialQuasiGroupTerm)) | linvL : (MedialQuasiGroupTerm → (MedialQuasiGroupTerm → MedialQuasiGroupTerm)) | rinvL : (MedialQuasiGroupTerm → (MedialQuasiGroupTerm → MedialQuasiGroupTerm)) open MedialQuasiGroupTerm inductive ClMedialQuasiGroupTerm (A : Type) : Type | sing : (A → ClMedialQuasiGroupTerm) | opCl : (ClMedialQuasiGroupTerm → (ClMedialQuasiGroupTerm → ClMedialQuasiGroupTerm)) | linvCl : (ClMedialQuasiGroupTerm → (ClMedialQuasiGroupTerm → ClMedialQuasiGroupTerm)) | rinvCl : (ClMedialQuasiGroupTerm → (ClMedialQuasiGroupTerm → ClMedialQuasiGroupTerm)) open ClMedialQuasiGroupTerm inductive OpMedialQuasiGroupTerm (n : ℕ) : Type | v : ((fin n) → OpMedialQuasiGroupTerm) | opOL : (OpMedialQuasiGroupTerm → (OpMedialQuasiGroupTerm → OpMedialQuasiGroupTerm)) | linvOL : (OpMedialQuasiGroupTerm → (OpMedialQuasiGroupTerm → OpMedialQuasiGroupTerm)) | rinvOL : (OpMedialQuasiGroupTerm → (OpMedialQuasiGroupTerm → OpMedialQuasiGroupTerm)) open OpMedialQuasiGroupTerm inductive OpMedialQuasiGroupTerm2 (n : ℕ) (A : Type) : Type | v2 : ((fin n) → OpMedialQuasiGroupTerm2) | sing2 : (A → OpMedialQuasiGroupTerm2) | opOL2 : (OpMedialQuasiGroupTerm2 → (OpMedialQuasiGroupTerm2 → OpMedialQuasiGroupTerm2)) | linvOL2 : (OpMedialQuasiGroupTerm2 → (OpMedialQuasiGroupTerm2 → OpMedialQuasiGroupTerm2)) | rinvOL2 : (OpMedialQuasiGroupTerm2 → (OpMedialQuasiGroupTerm2 → OpMedialQuasiGroupTerm2)) open OpMedialQuasiGroupTerm2 def simplifyCl {A : Type} : ((ClMedialQuasiGroupTerm A) → (ClMedialQuasiGroupTerm A)) | (opCl x1 x2) := (opCl (simplifyCl x1) (simplifyCl x2)) | (linvCl x1 x2) := (linvCl (simplifyCl x1) (simplifyCl x2)) | (rinvCl x1 x2) := (rinvCl (simplifyCl x1) (simplifyCl x2)) | (sing x1) := (sing x1) def simplifyOpB {n : ℕ} : ((OpMedialQuasiGroupTerm n) → (OpMedialQuasiGroupTerm n)) | (opOL x1 x2) := (opOL (simplifyOpB x1) (simplifyOpB x2)) | (linvOL x1 x2) := (linvOL (simplifyOpB x1) (simplifyOpB x2)) | (rinvOL x1 x2) := (rinvOL (simplifyOpB x1) (simplifyOpB x2)) | (v x1) := (v x1) def simplifyOp {n : ℕ} {A : Type} : ((OpMedialQuasiGroupTerm2 n A) → (OpMedialQuasiGroupTerm2 n A)) | (opOL2 x1 x2) := (opOL2 (simplifyOp x1) (simplifyOp x2)) | (linvOL2 x1 x2) := (linvOL2 (simplifyOp x1) (simplifyOp x2)) | (rinvOL2 x1 x2) := (rinvOL2 (simplifyOp x1) (simplifyOp x2)) | (v2 x1) := (v2 x1) | (sing2 x1) := (sing2 x1) def evalB {A : Type} : ((MedialQuasiGroup A) → (MedialQuasiGroupTerm → A)) | Me (opL x1 x2) := ((op Me) (evalB Me x1) (evalB Me x2)) | Me (linvL x1 x2) := ((linv Me) (evalB Me x1) (evalB Me x2)) | Me (rinvL x1 x2) := ((rinv Me) (evalB Me x1) (evalB Me x2)) def evalCl {A : Type} : ((MedialQuasiGroup A) → ((ClMedialQuasiGroupTerm A) → A)) | Me (sing x1) := x1 | Me (opCl x1 x2) := ((op Me) (evalCl Me x1) (evalCl Me x2)) | Me (linvCl x1 x2) := ((linv Me) (evalCl Me x1) (evalCl Me x2)) | Me (rinvCl x1 x2) := ((rinv Me) (evalCl Me x1) (evalCl Me x2)) def evalOpB {A : Type} {n : ℕ} : ((MedialQuasiGroup A) → ((vector A n) → ((OpMedialQuasiGroupTerm n) → A))) | Me vars (v x1) := (nth vars x1) | Me vars (opOL x1 x2) := ((op Me) (evalOpB Me vars x1) (evalOpB Me vars x2)) | Me vars (linvOL x1 x2) := ((linv Me) (evalOpB Me vars x1) (evalOpB Me vars x2)) | Me vars (rinvOL x1 x2) := ((rinv Me) (evalOpB Me vars x1) (evalOpB Me vars x2)) def evalOp {A : Type} {n : ℕ} : ((MedialQuasiGroup A) → ((vector A n) → ((OpMedialQuasiGroupTerm2 n A) → A))) | Me vars (v2 x1) := (nth vars x1) | Me vars (sing2 x1) := x1 | Me vars (opOL2 x1 x2) := ((op Me) (evalOp Me vars x1) (evalOp Me vars x2)) | Me vars (linvOL2 x1 x2) := ((linv Me) (evalOp Me vars x1) (evalOp Me vars x2)) | Me vars (rinvOL2 x1 x2) := ((rinv Me) (evalOp Me vars x1) (evalOp Me vars x2)) def inductionB {P : (MedialQuasiGroupTerm → Type)} : ((∀ (x1 x2 : MedialQuasiGroupTerm) , ((P x1) → ((P x2) → (P (opL x1 x2))))) → ((∀ (x1 x2 : MedialQuasiGroupTerm) , ((P x1) → ((P x2) → (P (linvL x1 x2))))) → ((∀ (x1 x2 : MedialQuasiGroupTerm) , ((P x1) → ((P x2) → (P (rinvL x1 x2))))) → (∀ (x : MedialQuasiGroupTerm) , (P x))))) | popl plinvl prinvl (opL x1 x2) := (popl _ _ (inductionB popl plinvl prinvl x1) (inductionB popl plinvl prinvl x2)) | popl plinvl prinvl (linvL x1 x2) := (plinvl _ _ (inductionB popl plinvl prinvl x1) (inductionB popl plinvl prinvl x2)) | popl plinvl prinvl (rinvL x1 x2) := (prinvl _ _ (inductionB popl plinvl prinvl x1) (inductionB popl plinvl prinvl x2)) def inductionCl {A : Type} {P : ((ClMedialQuasiGroupTerm A) → Type)} : ((∀ (x1 : A) , (P (sing x1))) → ((∀ (x1 x2 : (ClMedialQuasiGroupTerm A)) , ((P x1) → ((P x2) → (P (opCl x1 x2))))) → ((∀ (x1 x2 : (ClMedialQuasiGroupTerm A)) , ((P x1) → ((P x2) → (P (linvCl x1 x2))))) → ((∀ (x1 x2 : (ClMedialQuasiGroupTerm A)) , ((P x1) → ((P x2) → (P (rinvCl x1 x2))))) → (∀ (x : (ClMedialQuasiGroupTerm A)) , (P x)))))) | psing popcl plinvcl prinvcl (sing x1) := (psing x1) | psing popcl plinvcl prinvcl (opCl x1 x2) := (popcl _ _ (inductionCl psing popcl plinvcl prinvcl x1) (inductionCl psing popcl plinvcl prinvcl x2)) | psing popcl plinvcl prinvcl (linvCl x1 x2) := (plinvcl _ _ (inductionCl psing popcl plinvcl prinvcl x1) (inductionCl psing popcl plinvcl prinvcl x2)) | psing popcl plinvcl prinvcl (rinvCl x1 x2) := (prinvcl _ _ (inductionCl psing popcl plinvcl prinvcl x1) (inductionCl psing popcl plinvcl prinvcl x2)) def inductionOpB {n : ℕ} {P : ((OpMedialQuasiGroupTerm n) → Type)} : ((∀ (fin : (fin n)) , (P (v fin))) → ((∀ (x1 x2 : (OpMedialQuasiGroupTerm n)) , ((P x1) → ((P x2) → (P (opOL x1 x2))))) → ((∀ (x1 x2 : (OpMedialQuasiGroupTerm n)) , ((P x1) → ((P x2) → (P (linvOL x1 x2))))) → ((∀ (x1 x2 : (OpMedialQuasiGroupTerm n)) , ((P x1) → ((P x2) → (P (rinvOL x1 x2))))) → (∀ (x : (OpMedialQuasiGroupTerm n)) , (P x)))))) | pv popol plinvol prinvol (v x1) := (pv x1) | pv popol plinvol prinvol (opOL x1 x2) := (popol _ _ (inductionOpB pv popol plinvol prinvol x1) (inductionOpB pv popol plinvol prinvol x2)) | pv popol plinvol prinvol (linvOL x1 x2) := (plinvol _ _ (inductionOpB pv popol plinvol prinvol x1) (inductionOpB pv popol plinvol prinvol x2)) | pv popol plinvol prinvol (rinvOL x1 x2) := (prinvol _ _ (inductionOpB pv popol plinvol prinvol x1) (inductionOpB pv popol plinvol prinvol x2)) def inductionOp {n : ℕ} {A : Type} {P : ((OpMedialQuasiGroupTerm2 n A) → Type)} : ((∀ (fin : (fin n)) , (P (v2 fin))) → ((∀ (x1 : A) , (P (sing2 x1))) → ((∀ (x1 x2 : (OpMedialQuasiGroupTerm2 n A)) , ((P x1) → ((P x2) → (P (opOL2 x1 x2))))) → ((∀ (x1 x2 : (OpMedialQuasiGroupTerm2 n A)) , ((P x1) → ((P x2) → (P (linvOL2 x1 x2))))) → ((∀ (x1 x2 : (OpMedialQuasiGroupTerm2 n A)) , ((P x1) → ((P x2) → (P (rinvOL2 x1 x2))))) → (∀ (x : (OpMedialQuasiGroupTerm2 n A)) , (P x))))))) | pv2 psing2 popol2 plinvol2 prinvol2 (v2 x1) := (pv2 x1) | pv2 psing2 popol2 plinvol2 prinvol2 (sing2 x1) := (psing2 x1) | pv2 psing2 popol2 plinvol2 prinvol2 (opOL2 x1 x2) := (popol2 _ _ (inductionOp pv2 psing2 popol2 plinvol2 prinvol2 x1) (inductionOp pv2 psing2 popol2 plinvol2 prinvol2 x2)) | pv2 psing2 popol2 plinvol2 prinvol2 (linvOL2 x1 x2) := (plinvol2 _ _ (inductionOp pv2 psing2 popol2 plinvol2 prinvol2 x1) (inductionOp pv2 psing2 popol2 plinvol2 prinvol2 x2)) | pv2 psing2 popol2 plinvol2 prinvol2 (rinvOL2 x1 x2) := (prinvol2 _ _ (inductionOp pv2 psing2 popol2 plinvol2 prinvol2 x1) (inductionOp pv2 psing2 popol2 plinvol2 prinvol2 x2)) def stageB : (MedialQuasiGroupTerm → (Staged MedialQuasiGroupTerm)) | (opL x1 x2) := (stage2 opL (codeLift2 opL) (stageB x1) (stageB x2)) | (linvL x1 x2) := (stage2 linvL (codeLift2 linvL) (stageB x1) (stageB x2)) | (rinvL x1 x2) := (stage2 rinvL (codeLift2 rinvL) (stageB x1) (stageB x2)) def stageCl {A : Type} : ((ClMedialQuasiGroupTerm A) → (Staged (ClMedialQuasiGroupTerm A))) | (sing x1) := (Now (sing x1)) | (opCl x1 x2) := (stage2 opCl (codeLift2 opCl) (stageCl x1) (stageCl x2)) | (linvCl x1 x2) := (stage2 linvCl (codeLift2 linvCl) (stageCl x1) (stageCl x2)) | (rinvCl x1 x2) := (stage2 rinvCl (codeLift2 rinvCl) (stageCl x1) (stageCl x2)) def stageOpB {n : ℕ} : ((OpMedialQuasiGroupTerm n) → (Staged (OpMedialQuasiGroupTerm n))) | (v x1) := (const (code (v x1))) | (opOL x1 x2) := (stage2 opOL (codeLift2 opOL) (stageOpB x1) (stageOpB x2)) | (linvOL x1 x2) := (stage2 linvOL (codeLift2 linvOL) (stageOpB x1) (stageOpB x2)) | (rinvOL x1 x2) := (stage2 rinvOL (codeLift2 rinvOL) (stageOpB x1) (stageOpB x2)) def stageOp {n : ℕ} {A : Type} : ((OpMedialQuasiGroupTerm2 n A) → (Staged (OpMedialQuasiGroupTerm2 n A))) | (sing2 x1) := (Now (sing2 x1)) | (v2 x1) := (const (code (v2 x1))) | (opOL2 x1 x2) := (stage2 opOL2 (codeLift2 opOL2) (stageOp x1) (stageOp x2)) | (linvOL2 x1 x2) := (stage2 linvOL2 (codeLift2 linvOL2) (stageOp x1) (stageOp x2)) | (rinvOL2 x1 x2) := (stage2 rinvOL2 (codeLift2 rinvOL2) (stageOp x1) (stageOp x2)) structure StagedRepr (A : Type) (Repr : (Type → Type)) : Type := (opT : ((Repr A) → ((Repr A) → (Repr A)))) (linvT : ((Repr A) → ((Repr A) → (Repr A)))) (rinvT : ((Repr A) → ((Repr A) → (Repr A)))) end MedialQuasiGroup
2394598a031bdb189b47ba0bbf4c2b8d82424232
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/tactic/omega/int/main.lean
ce10475d055fc34b379dda1449bd40cca33c1676
[ "Apache-2.0" ]
permissive
gebner/mathlib
eab0150cc4f79ec45d2016a8c21750244a2e7ff0
cc6a6edc397c55118df62831e23bfbd6e6c6b4ab
refs/heads/master
1,625,574,853,976
1,586,712,827,000
1,586,712,827,000
99,101,412
1
0
Apache-2.0
1,586,716,389,000
1,501,667,958,000
Lean
UTF-8
Lean
false
false
6,327
lean
/- Copyright (c) 2019 Seul Baek. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Seul Baek Main procedure for linear integer arithmetic. -/ import tactic.omega.prove_unsats import tactic.omega.int.dnf import tactic.omega.misc open tactic namespace omega namespace int open_locale omega.int run_cmd mk_simp_attr `sugar attribute [sugar] ne not_le not_lt int.lt_iff_add_one_le or_false false_or and_true true_and ge gt mul_add add_mul one_mul mul_one mul_comm sub_eq_add_neg classical.imp_iff_not_or classical.iff_iff_not_or_and_or_not meta def desugar := `[try {simp only with sugar}] lemma univ_close_of_unsat_clausify (m : nat) (p : preform) : clauses.unsat (dnf (¬* p)) → univ_close p (λ x, 0) m | h1 := begin apply univ_close_of_valid, apply valid_of_unsat_not, apply unsat_of_clauses_unsat, exact h1 end /-- Given a (p : preform), return the expr of a (t : univ_close m p) -/ meta def prove_univ_close (m : nat) (p : preform) : tactic expr := do x ← prove_unsats (dnf (¬*p)), return `(univ_close_of_unsat_clausify %%`(m) %%`(p) %%x) /-- Reification to imtermediate shadow syntax that retains exprs -/ meta def to_exprterm : expr → tactic exprterm | `(- %%x) := --return (exprterm.exp (-1 : int) x) ( do z ← eval_expr' int x, return (exprterm.cst (-z : int)) ) <|> ( return $ exprterm.exp (-1 : int) x ) | `(%%mx * %%zx) := do z ← eval_expr' int zx, return (exprterm.exp z mx) | `(%%t1x + %%t2x) := do t1 ← to_exprterm t1x, t2 ← to_exprterm t2x, return (exprterm.add t1 t2) | x := ( do z ← eval_expr' int x, return (exprterm.cst z) ) <|> ( return $ exprterm.exp 1 x ) /-- Reification to imtermediate shadow syntax that retains exprs -/ meta def to_exprform : expr → tactic exprform | `(%%tx1 = %%tx2) := do t1 ← to_exprterm tx1, t2 ← to_exprterm tx2, return (exprform.eq t1 t2) | `(%%tx1 ≤ %%tx2) := do t1 ← to_exprterm tx1, t2 ← to_exprterm tx2, return (exprform.le t1 t2) | `(¬ %%px) := do p ← to_exprform px, return (exprform.not p) | `(%%px ∨ %%qx) := do p ← to_exprform px, q ← to_exprform qx, return (exprform.or p q) | `(%%px ∧ %%qx) := do p ← to_exprform px, q ← to_exprform qx, return (exprform.and p q) | `(_ → %%px) := to_exprform px | x := trace "Cannot reify expr : " >> trace x >> failed /-- List of all unreified exprs -/ meta def exprterm.exprs : exprterm → list expr | (exprterm.cst _) := [] | (exprterm.exp _ x) := [x] | (exprterm.add t s) := list.union t.exprs s.exprs /-- List of all unreified exprs -/ meta def exprform.exprs : exprform → list expr | (exprform.eq t s) := list.union t.exprs s.exprs | (exprform.le t s) := list.union t.exprs s.exprs | (exprform.not p) := p.exprs | (exprform.or p q) := list.union p.exprs q.exprs | (exprform.and p q) := list.union p.exprs q.exprs /-- Reification to an intermediate shadow syntax which eliminates exprs, but still includes non-canonical terms -/ meta def exprterm.to_preterm (xs : list expr) : exprterm → tactic preterm | (exprterm.cst k) := return & k | (exprterm.exp k x) := let m := xs.index_of x in if m < xs.length then return (k ** m) else failed | (exprterm.add xa xb) := do a ← xa.to_preterm, b ← xb.to_preterm, return (a +* b) /-- Reification to an intermediate shadow syntax which eliminates exprs, but still includes non-canonical terms -/ meta def exprform.to_preform (xs : list expr) : exprform → tactic preform | (exprform.eq xa xb) := do a ← xa.to_preterm xs, b ← xb.to_preterm xs, return (a =* b) | (exprform.le xa xb) := do a ← xa.to_preterm xs, b ← xb.to_preterm xs, return (a ≤* b) | (exprform.not xp) := do p ← xp.to_preform, return ¬* p | (exprform.or xp xq) := do p ← xp.to_preform, q ← xq.to_preform, return (p ∨* q) | (exprform.and xp xq) := do p ← xp.to_preform, q ← xq.to_preform, return (p ∧* q) /-- Reification to an intermediate shadow syntax which eliminates exprs, but still includes non-canonical terms. -/ meta def to_preform (x : expr) : tactic (preform × nat) := do xf ← to_exprform x, let xs := xf.exprs, f ← xf.to_preform xs, return (f, xs.length) /-- Return expr of proof of current LIA goal -/ meta def prove : tactic expr := do (p,m) ← target >>= to_preform, trace_if_enabled `omega p, prove_univ_close m p /-- Succeed iff argument is the expr of ℤ -/ meta def eq_int (x : expr) : tactic unit := if x = `(int) then skip else failed /-- Check whether argument is expr of a well-formed formula of LIA-/ meta def wff : expr → tactic unit | `(¬ %%px) := wff px | `(%%px ∨ %%qx) := wff px >> wff qx | `(%%px ∧ %%qx) := wff px >> wff qx | `(%%px ↔ %%qx) := wff px >> wff qx | `(%%(expr.pi _ _ px qx)) := monad.cond (if expr.has_var px then return tt else is_prop px) (wff px >> wff qx) (eq_int px >> wff qx) | `(@has_lt.lt %%dx %%h _ _) := eq_int dx | `(@has_le.le %%dx %%h _ _) := eq_int dx | `(@eq %%dx _ _) := eq_int dx | `(@ge %%dx %%h _ _) := eq_int dx | `(@gt %%dx %%h _ _) := eq_int dx | `(@ne %%dx _ _) := eq_int dx | `(true) := skip | `(false) := skip | _ := failed /-- Succeed iff argument is expr of term whose type is wff -/ meta def wfx (x : expr) : tactic unit := infer_type x >>= wff /-- Intro all universal quantifiers over ℤ -/ meta def intro_ints_core : tactic unit := do x ← target, match x with | (expr.pi _ _ `(int) _) := intro_fresh >> intro_ints_core | _ := skip end meta def intro_ints : tactic unit := do (expr.pi _ _ `(int) _) ← target, intro_ints_core /-- If the goal has universal quantifiers over integers, introduce all of them. Otherwise, revert all hypotheses that are formulas of linear integer arithmetic. -/ meta def preprocess : tactic unit := intro_ints <|> (revert_cond_all wfx >> desugar) end int end omega open omega.int /-- The core omega tactic for integers. -/ meta def omega_int (is_manual : bool) : tactic unit := desugar ; (if is_manual then skip else preprocess) ; prove >>= apply >> skip
7677f5e4d5255a18b97b83fc68c3ae05761869f2
968e2f50b755d3048175f176376eff7139e9df70
/examples/prop_logic_theory/unnamed_664.lean
747d572ab075e7ecbd5d1ccfda98bf16cd2107c4
[]
no_license
gihanmarasingha/mth1001_sphinx
190a003269ba5e54717b448302a27ca26e31d491
05126586cbf5786e521be1ea2ef5b4ba3c44e74a
refs/heads/master
1,672,913,933,677
1,604,516,583,000
1,604,516,583,000
309,245,750
1
0
null
null
null
null
UTF-8
Lean
false
false
209
lean
variables a b c d e f : Prop -- BEGIN example (h₁ : d → a) (h₂ : f → b) (h₃ : e → c) (h₄ : e → a) (h₅ : d → e) (h₆ : b → e) (h₇ : c) (h₈ : f) : a := begin sorry end -- END
a2654960b41151ec1e8bf8f5f007db107cdc35b4
2a70b774d16dbdf5a533432ee0ebab6838df0948
/_target/deps/mathlib/src/data/finset/basic.lean
a7f2676c0448a915ce03a7191d93ab2ac5e7d19b
[ "Apache-2.0" ]
permissive
hjvromen/lewis
40b035973df7c77ebf927afab7878c76d05ff758
105b675f73630f028ad5d890897a51b3c1146fb0
refs/heads/master
1,677,944,636,343
1,676,555,301,000
1,676,555,301,000
327,553,599
0
0
null
null
null
null
UTF-8
Lean
false
false
104,158
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Jeremy Avigad, Minchao Wu, Mario Carneiro -/ import data.multiset.finset_ops import tactic.monotonicity import tactic.apply import tactic.nth_rewrite /-! # Finite sets mathlib has several different models for finite sets, and it can be confusing when you're first getting used to them! This file builds the basic theory of `finset α`, modelled as a `multiset α` without duplicates. It's "constructive" in the since that there is an underlying list of elements, although this is wrapped in a quotient by permutations, so anytime you actually use this list you're obligated to show you didn't depend on the ordering. There's also the typeclass `fintype α` (which asserts that there is some `finset α` containing every term of type `α`) as well as the predicate `finite` on `s : set α` (which asserts `nonempty (fintype s)`). -/ open multiset subtype nat function variables {α : Type*} {β : Type*} {γ : Type*} /-- `finset α` is the type of finite sets of elements of `α`. It is implemented as a multiset (a list up to permutation) which has no duplicate elements. -/ structure finset (α : Type*) := (val : multiset α) (nodup : nodup val) namespace finset theorem eq_of_veq : ∀ {s t : finset α}, s.1 = t.1 → s = t | ⟨s, _⟩ ⟨t, _⟩ rfl := rfl @[simp] theorem val_inj {s t : finset α} : s.1 = t.1 ↔ s = t := ⟨eq_of_veq, congr_arg _⟩ @[simp] theorem erase_dup_eq_self [decidable_eq α] (s : finset α) : erase_dup s.1 = s.1 := erase_dup_eq_self.2 s.2 instance has_decidable_eq [decidable_eq α] : decidable_eq (finset α) | s₁ s₂ := decidable_of_iff _ val_inj /-! ### membership -/ instance : has_mem α (finset α) := ⟨λ a s, a ∈ s.1⟩ theorem mem_def {a : α} {s : finset α} : a ∈ s ↔ a ∈ s.1 := iff.rfl @[simp] theorem mem_mk {a : α} {s nd} : a ∈ @finset.mk α s nd ↔ a ∈ s := iff.rfl instance decidable_mem [h : decidable_eq α] (a : α) (s : finset α) : decidable (a ∈ s) := multiset.decidable_mem _ _ /-! ### set coercion -/ /-- Convert a finset to a set in the natural way. -/ instance : has_coe_t (finset α) (set α) := ⟨λ s, {x | x ∈ s}⟩ @[simp, norm_cast] lemma mem_coe {a : α} {s : finset α} : a ∈ (s : set α) ↔ a ∈ s := iff.rfl @[simp] lemma set_of_mem {α} {s : finset α} : {a | a ∈ s} = s := rfl @[simp] lemma coe_mem {s : finset α} (x : (s : set α)) : ↑x ∈ s := x.2 @[simp] lemma mk_coe {s : finset α} (x : (s : set α)) {h} : (⟨x, h⟩ : (s : set α)) = x := subtype.coe_eta _ _ instance decidable_mem' [decidable_eq α] (a : α) (s : finset α) : decidable (a ∈ (s : set α)) := s.decidable_mem _ /-! ### extensionality -/ theorem ext_iff {s₁ s₂ : finset α} : s₁ = s₂ ↔ ∀ a, a ∈ s₁ ↔ a ∈ s₂ := val_inj.symm.trans $ nodup_ext s₁.2 s₂.2 @[ext] theorem ext {s₁ s₂ : finset α} : (∀ a, a ∈ s₁ ↔ a ∈ s₂) → s₁ = s₂ := ext_iff.2 @[simp, norm_cast] theorem coe_inj {s₁ s₂ : finset α} : (s₁ : set α) = s₂ ↔ s₁ = s₂ := set.ext_iff.trans ext_iff.symm lemma coe_injective {α} : injective (coe : finset α → set α) := λ s t, coe_inj.1 /-! ### subset -/ instance : has_subset (finset α) := ⟨λ s₁ s₂, ∀ ⦃a⦄, a ∈ s₁ → a ∈ s₂⟩ theorem subset_def {s₁ s₂ : finset α} : s₁ ⊆ s₂ ↔ s₁.1 ⊆ s₂.1 := iff.rfl @[simp] theorem subset.refl (s : finset α) : s ⊆ s := subset.refl _ theorem subset_of_eq {s t : finset α} (h : s = t) : s ⊆ t := h ▸ subset.refl _ theorem subset.trans {s₁ s₂ s₃ : finset α} : s₁ ⊆ s₂ → s₂ ⊆ s₃ → s₁ ⊆ s₃ := subset.trans theorem superset.trans {s₁ s₂ s₃ : finset α} : s₁ ⊇ s₂ → s₂ ⊇ s₃ → s₁ ⊇ s₃ := λ h' h, subset.trans h h' -- TODO: these should be global attributes, but this will require fixing other files local attribute [trans] subset.trans superset.trans theorem mem_of_subset {s₁ s₂ : finset α} {a : α} : s₁ ⊆ s₂ → a ∈ s₁ → a ∈ s₂ := mem_of_subset theorem subset.antisymm {s₁ s₂ : finset α} (H₁ : s₁ ⊆ s₂) (H₂ : s₂ ⊆ s₁) : s₁ = s₂ := ext $ λ a, ⟨@H₁ a, @H₂ a⟩ theorem subset_iff {s₁ s₂ : finset α} : s₁ ⊆ s₂ ↔ ∀ ⦃x⦄, x ∈ s₁ → x ∈ s₂ := iff.rfl @[simp, norm_cast] theorem coe_subset {s₁ s₂ : finset α} : (s₁ : set α) ⊆ s₂ ↔ s₁ ⊆ s₂ := iff.rfl @[simp] theorem val_le_iff {s₁ s₂ : finset α} : s₁.1 ≤ s₂.1 ↔ s₁ ⊆ s₂ := le_iff_subset s₁.2 instance : has_ssubset (finset α) := ⟨λa b, a ⊆ b ∧ ¬ b ⊆ a⟩ instance : partial_order (finset α) := { le := (⊆), lt := (⊂), le_refl := subset.refl, le_trans := @subset.trans _, le_antisymm := @subset.antisymm _ } theorem subset.antisymm_iff {s₁ s₂ : finset α} : s₁ = s₂ ↔ s₁ ⊆ s₂ ∧ s₂ ⊆ s₁ := le_antisymm_iff @[simp] theorem le_iff_subset {s₁ s₂ : finset α} : s₁ ≤ s₂ ↔ s₁ ⊆ s₂ := iff.rfl @[simp] theorem lt_iff_ssubset {s₁ s₂ : finset α} : s₁ < s₂ ↔ s₁ ⊂ s₂ := iff.rfl @[simp, norm_cast] lemma coe_ssubset {s₁ s₂ : finset α} : (s₁ : set α) ⊂ s₂ ↔ s₁ ⊂ s₂ := show (s₁ : set α) ⊂ s₂ ↔ s₁ ⊆ s₂ ∧ ¬s₂ ⊆ s₁, by simp only [set.ssubset_def, finset.coe_subset] @[simp] theorem val_lt_iff {s₁ s₂ : finset α} : s₁.1 < s₂.1 ↔ s₁ ⊂ s₂ := and_congr val_le_iff $ not_congr val_le_iff theorem ssubset_iff_of_subset {s₁ s₂ : finset α} (h : s₁ ⊆ s₂) : s₁ ⊂ s₂ ↔ ∃ x ∈ s₂, x ∉ s₁ := set.ssubset_iff_of_subset h /-! ### Nonempty -/ /-- The property `s.nonempty` expresses the fact that the finset `s` is not empty. It should be used in theorem assumptions instead of `∃ x, x ∈ s` or `s ≠ ∅` as it gives access to a nice API thanks to the dot notation. -/ protected def nonempty (s : finset α) : Prop := ∃ x:α, x ∈ s @[simp, norm_cast] lemma coe_nonempty {s : finset α} : (s:set α).nonempty ↔ s.nonempty := iff.rfl lemma nonempty.bex {s : finset α} (h : s.nonempty) : ∃ x:α, x ∈ s := h lemma nonempty.mono {s t : finset α} (hst : s ⊆ t) (hs : s.nonempty) : t.nonempty := set.nonempty.mono hst hs /-! ### empty -/ /-- The empty finset -/ protected def empty : finset α := ⟨0, nodup_zero⟩ instance : has_emptyc (finset α) := ⟨finset.empty⟩ instance : inhabited (finset α) := ⟨∅⟩ @[simp] theorem empty_val : (∅ : finset α).1 = 0 := rfl @[simp] theorem not_mem_empty (a : α) : a ∉ (∅ : finset α) := id @[simp] theorem not_nonempty_empty : ¬(∅ : finset α).nonempty := λ ⟨x, hx⟩, not_mem_empty x hx @[simp] theorem mk_zero : (⟨0, nodup_zero⟩ : finset α) = ∅ := rfl theorem ne_empty_of_mem {a : α} {s : finset α} (h : a ∈ s) : s ≠ ∅ := λ e, not_mem_empty a $ e ▸ h theorem nonempty.ne_empty {s : finset α} (h : s.nonempty) : s ≠ ∅ := exists.elim h $ λ a, ne_empty_of_mem @[simp] theorem empty_subset (s : finset α) : ∅ ⊆ s := zero_subset _ theorem eq_empty_of_forall_not_mem {s : finset α} (H : ∀x, x ∉ s) : s = ∅ := eq_of_veq (eq_zero_of_forall_not_mem H) lemma eq_empty_iff_forall_not_mem {s : finset α} : s = ∅ ↔ ∀ x, x ∉ s := ⟨by rintro rfl x; exact id, λ h, eq_empty_of_forall_not_mem h⟩ @[simp] theorem val_eq_zero {s : finset α} : s.1 = 0 ↔ s = ∅ := @val_inj _ s ∅ theorem subset_empty {s : finset α} : s ⊆ ∅ ↔ s = ∅ := subset_zero.trans val_eq_zero theorem nonempty_of_ne_empty {s : finset α} (h : s ≠ ∅) : s.nonempty := exists_mem_of_ne_zero (mt val_eq_zero.1 h) theorem nonempty_iff_ne_empty {s : finset α} : s.nonempty ↔ s ≠ ∅ := ⟨nonempty.ne_empty, nonempty_of_ne_empty⟩ @[simp] theorem not_nonempty_iff_eq_empty {s : finset α} : ¬s.nonempty ↔ s = ∅ := by { rw nonempty_iff_ne_empty, exact not_not, } theorem eq_empty_or_nonempty (s : finset α) : s = ∅ ∨ s.nonempty := classical.by_cases or.inl (λ h, or.inr (nonempty_of_ne_empty h)) @[simp] lemma coe_empty : ((∅ : finset α) : set α) = ∅ := rfl /-- A `finset` for an empty type is empty. -/ lemma eq_empty_of_not_nonempty (h : ¬ nonempty α) (s : finset α) : s = ∅ := finset.eq_empty_of_forall_not_mem $ λ x, false.elim $ not_nonempty_iff_imp_false.1 h x /-! ### singleton -/ /-- `{a} : finset a` is the set `{a}` containing `a` and nothing else. This differs from `insert a ∅` in that it does not require a `decidable_eq` instance for `α`. -/ instance : has_singleton α (finset α) := ⟨λ a, ⟨{a}, nodup_singleton a⟩⟩ @[simp] theorem singleton_val (a : α) : ({a} : finset α).1 = a ::ₘ 0 := rfl @[simp] theorem mem_singleton {a b : α} : b ∈ ({a} : finset α) ↔ b = a := mem_singleton theorem not_mem_singleton {a b : α} : a ∉ ({b} : finset α) ↔ a ≠ b := not_congr mem_singleton theorem mem_singleton_self (a : α) : a ∈ ({a} : finset α) := or.inl rfl theorem singleton_inj {a b : α} : ({a} : finset α) = {b} ↔ a = b := ⟨λ h, mem_singleton.1 (h ▸ mem_singleton_self _), congr_arg _⟩ @[simp] theorem singleton_nonempty (a : α) : ({a} : finset α).nonempty := ⟨a, mem_singleton_self a⟩ @[simp] theorem singleton_ne_empty (a : α) : ({a} : finset α) ≠ ∅ := (singleton_nonempty a).ne_empty @[simp, norm_cast] lemma coe_singleton (a : α) : (({a} : finset α) : set α) = {a} := by { ext, simp } lemma eq_singleton_iff_unique_mem {s : finset α} {a : α} : s = {a} ↔ a ∈ s ∧ ∀ x ∈ s, x = a := begin split; intro t, rw t, refine ⟨finset.mem_singleton_self _, λ _, finset.mem_singleton.1⟩, ext, rw finset.mem_singleton, refine ⟨t.right _, λ r, r.symm ▸ t.left⟩ end lemma eq_singleton_iff_nonempty_unique_mem {s : finset α} {a : α} : s = {a} ↔ s.nonempty ∧ ∀ x ∈ s, x = a := begin split, { intros h, subst h, simp, }, { rintros ⟨hne, h_uniq⟩, rw eq_singleton_iff_unique_mem, refine ⟨_, h_uniq⟩, rw ← h_uniq hne.some hne.some_spec, apply hne.some_spec, }, end lemma singleton_iff_unique_mem (s : finset α) : (∃ a, s = {a}) ↔ ∃! a, a ∈ s := by simp only [eq_singleton_iff_unique_mem, exists_unique] lemma singleton_subset_set_iff {s : set α} {a : α} : ↑({a} : finset α) ⊆ s ↔ a ∈ s := by rw [coe_singleton, set.singleton_subset_iff] @[simp] lemma singleton_subset_iff {s : finset α} {a : α} : {a} ⊆ s ↔ a ∈ s := singleton_subset_set_iff /-! ### cons -/ /-- `cons a s h` is the set `{a} ∪ s` containing `a` and the elements of `s`. It is the same as `insert a s` when it is defined, but unlike `insert a s` it does not require `decidable_eq α`, and the union is guaranteed to be disjoint. -/ def cons {α} (a : α) (s : finset α) (h : a ∉ s) : finset α := ⟨a ::ₘ s.1, multiset.nodup_cons.2 ⟨h, s.2⟩⟩ @[simp] theorem mem_cons {α a s h b} : b ∈ @cons α a s h ↔ b = a ∨ b ∈ s := by rcases s with ⟨⟨s⟩⟩; apply list.mem_cons_iff @[simp] theorem cons_val {a : α} {s : finset α} (h : a ∉ s) : (cons a s h).1 = a ::ₘ s.1 := rfl @[simp] theorem mk_cons {a : α} {s : multiset α} (h : (a ::ₘ s).nodup) : (⟨a ::ₘ s, h⟩ : finset α) = cons a ⟨s, (multiset.nodup_cons.1 h).2⟩ (multiset.nodup_cons.1 h).1 := rfl @[simp] theorem nonempty_cons {a : α} {s : finset α} (h : a ∉ s) : (cons a s h).nonempty := ⟨a, mem_cons.2 (or.inl rfl)⟩ @[simp] lemma nonempty_mk_coe : ∀ {l : list α} {hl}, (⟨↑l, hl⟩ : finset α).nonempty ↔ l ≠ [] | [] hl := by simp | (a::l) hl := by simp [← multiset.cons_coe] /-! ### disjoint union -/ /-- `disj_union s t h` is the set such that `a ∈ disj_union s t h` iff `a ∈ s` or `a ∈ t`. It is the same as `s ∪ t`, but it does not require decidable equality on the type. The hypothesis ensures that the sets are disjoint. -/ def disj_union {α} (s t : finset α) (h : ∀ a ∈ s, a ∉ t) : finset α := ⟨s.1 + t.1, multiset.nodup_add.2 ⟨s.2, t.2, h⟩⟩ @[simp] theorem mem_disj_union {α s t h a} : a ∈ @disj_union α s t h ↔ a ∈ s ∨ a ∈ t := by rcases s with ⟨⟨s⟩⟩; rcases t with ⟨⟨t⟩⟩; apply list.mem_append /-! ### insert -/ section decidable_eq variables [decidable_eq α] /-- `insert a s` is the set `{a} ∪ s` containing `a` and the elements of `s`. -/ instance : has_insert α (finset α) := ⟨λ a s, ⟨_, nodup_ndinsert a s.2⟩⟩ theorem insert_def (a : α) (s : finset α) : insert a s = ⟨_, nodup_ndinsert a s.2⟩ := rfl @[simp] theorem insert_val (a : α) (s : finset α) : (insert a s).1 = ndinsert a s.1 := rfl theorem insert_val' (a : α) (s : finset α) : (insert a s).1 = erase_dup (a ::ₘ s.1) := by rw [erase_dup_cons, erase_dup_eq_self]; refl theorem insert_val_of_not_mem {a : α} {s : finset α} (h : a ∉ s) : (insert a s).1 = a ::ₘ s.1 := by rw [insert_val, ndinsert_of_not_mem h] @[simp] theorem mem_insert {a b : α} {s : finset α} : a ∈ insert b s ↔ a = b ∨ a ∈ s := mem_ndinsert theorem mem_insert_self (a : α) (s : finset α) : a ∈ insert a s := mem_ndinsert_self a s.1 theorem mem_insert_of_mem {a b : α} {s : finset α} (h : a ∈ s) : a ∈ insert b s := mem_ndinsert_of_mem h theorem mem_of_mem_insert_of_ne {a b : α} {s : finset α} (h : b ∈ insert a s) : b ≠ a → b ∈ s := (mem_insert.1 h).resolve_left @[simp] theorem cons_eq_insert {α} [decidable_eq α] (a s h) : @cons α a s h = insert a s := ext $ λ a, by simp @[simp, norm_cast] lemma coe_insert (a : α) (s : finset α) : ↑(insert a s) = (insert a s : set α) := set.ext $ λ x, by simp only [mem_coe, mem_insert, set.mem_insert_iff] lemma mem_insert_coe {s : finset α} {x y : α} : x ∈ insert y s ↔ x ∈ insert y (s : set α) := by simp instance : is_lawful_singleton α (finset α) := ⟨λ a, by { ext, simp }⟩ @[simp] theorem insert_eq_of_mem {a : α} {s : finset α} (h : a ∈ s) : insert a s = s := eq_of_veq $ ndinsert_of_mem h @[simp] theorem insert_singleton_self_eq (a : α) : ({a, a} : finset α) = {a} := insert_eq_of_mem $ mem_singleton_self _ theorem insert.comm (a b : α) (s : finset α) : insert a (insert b s) = insert b (insert a s) := ext $ λ x, by simp only [mem_insert, or.left_comm] theorem insert_singleton_comm (a b : α) : ({a, b} : finset α) = {b, a} := begin ext, simp [or.comm] end @[simp] theorem insert_idem (a : α) (s : finset α) : insert a (insert a s) = insert a s := ext $ λ x, by simp only [mem_insert, or.assoc.symm, or_self] @[simp] theorem insert_nonempty (a : α) (s : finset α) : (insert a s).nonempty := ⟨a, mem_insert_self a s⟩ @[simp] theorem insert_ne_empty (a : α) (s : finset α) : insert a s ≠ ∅ := (insert_nonempty a s).ne_empty section universe u /-! The universe annotation is required for the following instance, possibly this is a bug in Lean. See leanprover.zulipchat.com/#narrow/stream/113488-general/topic/strange.20error.20(universe.20issue.3F) -/ instance {α : Type u} [decidable_eq α] (i : α) (s : finset α) : nonempty.{u + 1} ((insert i s : finset α) : set α) := (finset.coe_nonempty.mpr (s.insert_nonempty i)).to_subtype end lemma ne_insert_of_not_mem (s t : finset α) {a : α} (h : a ∉ s) : s ≠ insert a t := by { contrapose! h, simp [h] } theorem insert_subset {a : α} {s t : finset α} : insert a s ⊆ t ↔ a ∈ t ∧ s ⊆ t := by simp only [subset_iff, mem_insert, forall_eq, or_imp_distrib, forall_and_distrib] theorem subset_insert (a : α) (s : finset α) : s ⊆ insert a s := λ b, mem_insert_of_mem theorem insert_subset_insert (a : α) {s t : finset α} (h : s ⊆ t) : insert a s ⊆ insert a t := insert_subset.2 ⟨mem_insert_self _ _, subset.trans h (subset_insert _ _)⟩ lemma ssubset_iff {s t : finset α} : s ⊂ t ↔ (∃a ∉ s, insert a s ⊆ t) := by exact_mod_cast @set.ssubset_iff_insert α s t lemma ssubset_insert {s : finset α} {a : α} (h : a ∉ s) : s ⊂ insert a s := ssubset_iff.mpr ⟨a, h, subset.refl _⟩ @[elab_as_eliminator] protected theorem induction {α : Type*} {p : finset α → Prop} [decidable_eq α] (h₁ : p ∅) (h₂ : ∀ ⦃a : α⦄ {s : finset α}, a ∉ s → p s → p (insert a s)) : ∀ s, p s | ⟨s, nd⟩ := multiset.induction_on s (λ _, h₁) (λ a s IH nd, begin cases nodup_cons.1 nd with m nd', rw [← (eq_of_veq _ : insert a (finset.mk s _) = ⟨a ::ₘ s, nd⟩)], { exact h₂ (by exact m) (IH nd') }, { rw [insert_val, ndinsert_of_not_mem m] } end) nd /-- To prove a proposition about an arbitrary `finset α`, it suffices to prove it for the empty `finset`, and to show that if it holds for some `finset α`, then it holds for the `finset` obtained by inserting a new element. -/ @[elab_as_eliminator] protected theorem induction_on {α : Type*} {p : finset α → Prop} [decidable_eq α] (s : finset α) (h₁ : p ∅) (h₂ : ∀ ⦃a : α⦄ {s : finset α}, a ∉ s → p s → p (insert a s)) : p s := finset.induction h₁ h₂ s /-- To prove a proposition about `S : finset α`, it suffices to prove it for the empty `finset`, and to show that if it holds for some `finset α ⊆ S`, then it holds for the `finset` obtained by inserting a new element of `S`. -/ @[elab_as_eliminator] theorem induction_on' {α : Type*} {p : finset α → Prop} [decidable_eq α] (S : finset α) (h₁ : p ∅) (h₂ : ∀ {a s}, a ∈ S → s ⊆ S → a ∉ s → p s → p (insert a s)) : p S := @finset.induction_on α (λ T, T ⊆ S → p T) _ S (λ _, h₁) (λ a s has hqs hs, let ⟨hS, sS⟩ := finset.insert_subset.1 hs in h₂ hS sS has (hqs sS)) (finset.subset.refl S) /-- Inserting an element to a finite set is equivalent to the option type. -/ def subtype_insert_equiv_option {t : finset α} {x : α} (h : x ∉ t) : {i // i ∈ insert x t} ≃ option {i // i ∈ t} := begin refine { to_fun := λ y, if h : ↑y = x then none else some ⟨y, (mem_insert.mp y.2).resolve_left h⟩, inv_fun := λ y, y.elim ⟨x, mem_insert_self _ _⟩ $ λ z, ⟨z, mem_insert_of_mem z.2⟩, .. }, { intro y, by_cases h : ↑y = x, simp only [subtype.ext_iff, h, option.elim, dif_pos, subtype.coe_mk], simp only [h, option.elim, dif_neg, not_false_iff, subtype.coe_eta, subtype.coe_mk] }, { rintro (_|y), simp only [option.elim, dif_pos, subtype.coe_mk], have : ↑y ≠ x, { rintro ⟨⟩, exact h y.2 }, simp only [this, option.elim, subtype.eta, dif_neg, not_false_iff, subtype.coe_eta, subtype.coe_mk] }, end /-! ### union -/ /-- `s ∪ t` is the set such that `a ∈ s ∪ t` iff `a ∈ s` or `a ∈ t`. -/ instance : has_union (finset α) := ⟨λ s₁ s₂, ⟨_, nodup_ndunion s₁.1 s₂.2⟩⟩ theorem union_val_nd (s₁ s₂ : finset α) : (s₁ ∪ s₂).1 = ndunion s₁.1 s₂.1 := rfl @[simp] theorem union_val (s₁ s₂ : finset α) : (s₁ ∪ s₂).1 = s₁.1 ∪ s₂.1 := ndunion_eq_union s₁.2 @[simp] theorem mem_union {a : α} {s₁ s₂ : finset α} : a ∈ s₁ ∪ s₂ ↔ a ∈ s₁ ∨ a ∈ s₂ := mem_ndunion @[simp] theorem disj_union_eq_union {α} [decidable_eq α] (s t h) : @disj_union α s t h = s ∪ t := ext $ λ a, by simp theorem mem_union_left {a : α} {s₁ : finset α} (s₂ : finset α) (h : a ∈ s₁) : a ∈ s₁ ∪ s₂ := mem_union.2 $ or.inl h theorem mem_union_right {a : α} {s₂ : finset α} (s₁ : finset α) (h : a ∈ s₂) : a ∈ s₁ ∪ s₂ := mem_union.2 $ or.inr h theorem forall_mem_union {s₁ s₂ : finset α} {p : α → Prop} : (∀ ab ∈ (s₁ ∪ s₂), p ab) ↔ (∀ a ∈ s₁, p a) ∧ (∀ b ∈ s₂, p b) := ⟨λ h, ⟨λ a, h a ∘ mem_union_left _, λ b, h b ∘ mem_union_right _⟩, λ h ab hab, (mem_union.mp hab).elim (h.1 _) (h.2 _)⟩ theorem not_mem_union {a : α} {s₁ s₂ : finset α} : a ∉ s₁ ∪ s₂ ↔ a ∉ s₁ ∧ a ∉ s₂ := by rw [mem_union, not_or_distrib] @[simp, norm_cast] lemma coe_union (s₁ s₂ : finset α) : ↑(s₁ ∪ s₂) = (s₁ ∪ s₂ : set α) := set.ext $ λ x, mem_union theorem union_subset {s₁ s₂ s₃ : finset α} (h₁ : s₁ ⊆ s₃) (h₂ : s₂ ⊆ s₃) : s₁ ∪ s₂ ⊆ s₃ := val_le_iff.1 (ndunion_le.2 ⟨h₁, val_le_iff.2 h₂⟩) theorem subset_union_left (s₁ s₂ : finset α) : s₁ ⊆ s₁ ∪ s₂ := λ x, mem_union_left _ theorem subset_union_right (s₁ s₂ : finset α) : s₂ ⊆ s₁ ∪ s₂ := λ x, mem_union_right _ lemma union_subset_union {s1 t1 s2 t2 : finset α} (h1 : s1 ⊆ t1) (h2 : s2 ⊆ t2) : s1 ∪ s2 ⊆ t1 ∪ t2 := by { intros x hx, rw finset.mem_union at hx ⊢, tauto } theorem union_comm (s₁ s₂ : finset α) : s₁ ∪ s₂ = s₂ ∪ s₁ := ext $ λ x, by simp only [mem_union, or_comm] instance : is_commutative (finset α) (∪) := ⟨union_comm⟩ @[simp] theorem union_assoc (s₁ s₂ s₃ : finset α) : (s₁ ∪ s₂) ∪ s₃ = s₁ ∪ (s₂ ∪ s₃) := ext $ λ x, by simp only [mem_union, or_assoc] instance : is_associative (finset α) (∪) := ⟨union_assoc⟩ @[simp] theorem union_idempotent (s : finset α) : s ∪ s = s := ext $ λ _, mem_union.trans $ or_self _ instance : is_idempotent (finset α) (∪) := ⟨union_idempotent⟩ theorem union_left_comm (s₁ s₂ s₃ : finset α) : s₁ ∪ (s₂ ∪ s₃) = s₂ ∪ (s₁ ∪ s₃) := ext $ λ _, by simp only [mem_union, or.left_comm] theorem union_right_comm (s₁ s₂ s₃ : finset α) : (s₁ ∪ s₂) ∪ s₃ = (s₁ ∪ s₃) ∪ s₂ := ext $ λ x, by simp only [mem_union, or_assoc, or_comm (x ∈ s₂)] theorem union_self (s : finset α) : s ∪ s = s := union_idempotent s @[simp] theorem union_empty (s : finset α) : s ∪ ∅ = s := ext $ λ x, mem_union.trans $ or_false _ @[simp] theorem empty_union (s : finset α) : ∅ ∪ s = s := ext $ λ x, mem_union.trans $ false_or _ theorem insert_eq (a : α) (s : finset α) : insert a s = {a} ∪ s := rfl @[simp] theorem insert_union (a : α) (s t : finset α) : insert a s ∪ t = insert a (s ∪ t) := by simp only [insert_eq, union_assoc] @[simp] theorem union_insert (a : α) (s t : finset α) : s ∪ insert a t = insert a (s ∪ t) := by simp only [insert_eq, union_left_comm] theorem insert_union_distrib (a : α) (s t : finset α) : insert a (s ∪ t) = insert a s ∪ insert a t := by simp only [insert_union, union_insert, insert_idem] @[simp] lemma union_eq_left_iff_subset {s t : finset α} : s ∪ t = s ↔ t ⊆ s := begin split, { assume h, have : t ⊆ s ∪ t := subset_union_right _ _, rwa h at this }, { assume h, exact subset.antisymm (union_subset (subset.refl _) h) (subset_union_left _ _) } end @[simp] lemma left_eq_union_iff_subset {s t : finset α} : s = s ∪ t ↔ t ⊆ s := by rw [← union_eq_left_iff_subset, eq_comm] @[simp] lemma union_eq_right_iff_subset {s t : finset α} : t ∪ s = s ↔ t ⊆ s := by rw [union_comm, union_eq_left_iff_subset] @[simp] lemma right_eq_union_iff_subset {s t : finset α} : s = t ∪ s ↔ t ⊆ s := by rw [← union_eq_right_iff_subset, eq_comm] /-- To prove a relation on pairs of `finset X`, it suffices to show that it is * symmetric, * it holds when one of the `finset`s is empty, * it holds for pairs of singletons, * if it holds for `[a, c]` and for `[b, c]`, then it holds for `[a ∪ b, c]`. -/ lemma induction_on_union (P : finset α → finset α → Prop) (symm : ∀ {a b}, P a b → P b a) (empty_right : ∀ {a}, P a ∅) (singletons : ∀ {a b}, P {a} {b}) (union_of : ∀ {a b c}, P a c → P b c → P (a ∪ b) c) : ∀ a b, P a b := begin intros a b, refine finset.induction_on b empty_right (λ x s xs hi, symm _), rw finset.insert_eq, apply union_of _ (symm hi), refine finset.induction_on a empty_right (λ a t ta hi, symm _), rw finset.insert_eq, exact union_of singletons (symm hi), end /-! ### inter -/ /-- `s ∩ t` is the set such that `a ∈ s ∩ t` iff `a ∈ s` and `a ∈ t`. -/ instance : has_inter (finset α) := ⟨λ s₁ s₂, ⟨_, nodup_ndinter s₂.1 s₁.2⟩⟩ theorem inter_val_nd (s₁ s₂ : finset α) : (s₁ ∩ s₂).1 = ndinter s₁.1 s₂.1 := rfl @[simp] theorem inter_val (s₁ s₂ : finset α) : (s₁ ∩ s₂).1 = s₁.1 ∩ s₂.1 := ndinter_eq_inter s₁.2 @[simp] theorem mem_inter {a : α} {s₁ s₂ : finset α} : a ∈ s₁ ∩ s₂ ↔ a ∈ s₁ ∧ a ∈ s₂ := mem_ndinter theorem mem_of_mem_inter_left {a : α} {s₁ s₂ : finset α} (h : a ∈ s₁ ∩ s₂) : a ∈ s₁ := (mem_inter.1 h).1 theorem mem_of_mem_inter_right {a : α} {s₁ s₂ : finset α} (h : a ∈ s₁ ∩ s₂) : a ∈ s₂ := (mem_inter.1 h).2 theorem mem_inter_of_mem {a : α} {s₁ s₂ : finset α} : a ∈ s₁ → a ∈ s₂ → a ∈ s₁ ∩ s₂ := and_imp.1 mem_inter.2 theorem inter_subset_left (s₁ s₂ : finset α) : s₁ ∩ s₂ ⊆ s₁ := λ a, mem_of_mem_inter_left theorem inter_subset_right (s₁ s₂ : finset α) : s₁ ∩ s₂ ⊆ s₂ := λ a, mem_of_mem_inter_right theorem subset_inter {s₁ s₂ s₃ : finset α} : s₁ ⊆ s₂ → s₁ ⊆ s₃ → s₁ ⊆ s₂ ∩ s₃ := by simp only [subset_iff, mem_inter] {contextual:=tt}; intros; split; trivial @[simp, norm_cast] lemma coe_inter (s₁ s₂ : finset α) : ↑(s₁ ∩ s₂) = (s₁ ∩ s₂ : set α) := set.ext $ λ _, mem_inter @[simp] theorem union_inter_cancel_left {s t : finset α} : (s ∪ t) ∩ s = s := by rw [← coe_inj, coe_inter, coe_union, set.union_inter_cancel_left] @[simp] theorem union_inter_cancel_right {s t : finset α} : (s ∪ t) ∩ t = t := by rw [← coe_inj, coe_inter, coe_union, set.union_inter_cancel_right] theorem inter_comm (s₁ s₂ : finset α) : s₁ ∩ s₂ = s₂ ∩ s₁ := ext $ λ _, by simp only [mem_inter, and_comm] @[simp] theorem inter_assoc (s₁ s₂ s₃ : finset α) : (s₁ ∩ s₂) ∩ s₃ = s₁ ∩ (s₂ ∩ s₃) := ext $ λ _, by simp only [mem_inter, and_assoc] theorem inter_left_comm (s₁ s₂ s₃ : finset α) : s₁ ∩ (s₂ ∩ s₃) = s₂ ∩ (s₁ ∩ s₃) := ext $ λ _, by simp only [mem_inter, and.left_comm] theorem inter_right_comm (s₁ s₂ s₃ : finset α) : (s₁ ∩ s₂) ∩ s₃ = (s₁ ∩ s₃) ∩ s₂ := ext $ λ _, by simp only [mem_inter, and.right_comm] @[simp] theorem inter_self (s : finset α) : s ∩ s = s := ext $ λ _, mem_inter.trans $ and_self _ @[simp] theorem inter_empty (s : finset α) : s ∩ ∅ = ∅ := ext $ λ _, mem_inter.trans $ and_false _ @[simp] theorem empty_inter (s : finset α) : ∅ ∩ s = ∅ := ext $ λ _, mem_inter.trans $ false_and _ @[simp] lemma inter_union_self (s t : finset α) : s ∩ (t ∪ s) = s := by rw [inter_comm, union_inter_cancel_right] @[simp] theorem insert_inter_of_mem {s₁ s₂ : finset α} {a : α} (h : a ∈ s₂) : insert a s₁ ∩ s₂ = insert a (s₁ ∩ s₂) := ext $ λ x, have x = a ∨ x ∈ s₂ ↔ x ∈ s₂, from or_iff_right_of_imp $ by rintro rfl; exact h, by simp only [mem_inter, mem_insert, or_and_distrib_left, this] @[simp] theorem inter_insert_of_mem {s₁ s₂ : finset α} {a : α} (h : a ∈ s₁) : s₁ ∩ insert a s₂ = insert a (s₁ ∩ s₂) := by rw [inter_comm, insert_inter_of_mem h, inter_comm] @[simp] theorem insert_inter_of_not_mem {s₁ s₂ : finset α} {a : α} (h : a ∉ s₂) : insert a s₁ ∩ s₂ = s₁ ∩ s₂ := ext $ λ x, have ¬ (x = a ∧ x ∈ s₂), by rintro ⟨rfl, H⟩; exact h H, by simp only [mem_inter, mem_insert, or_and_distrib_right, this, false_or] @[simp] theorem inter_insert_of_not_mem {s₁ s₂ : finset α} {a : α} (h : a ∉ s₁) : s₁ ∩ insert a s₂ = s₁ ∩ s₂ := by rw [inter_comm, insert_inter_of_not_mem h, inter_comm] @[simp] theorem singleton_inter_of_mem {a : α} {s : finset α} (H : a ∈ s) : {a} ∩ s = {a} := show insert a ∅ ∩ s = insert a ∅, by rw [insert_inter_of_mem H, empty_inter] @[simp] theorem singleton_inter_of_not_mem {a : α} {s : finset α} (H : a ∉ s) : {a} ∩ s = ∅ := eq_empty_of_forall_not_mem $ by simp only [mem_inter, mem_singleton]; rintro x ⟨rfl, h⟩; exact H h @[simp] theorem inter_singleton_of_mem {a : α} {s : finset α} (h : a ∈ s) : s ∩ {a} = {a} := by rw [inter_comm, singleton_inter_of_mem h] @[simp] theorem inter_singleton_of_not_mem {a : α} {s : finset α} (h : a ∉ s) : s ∩ {a} = ∅ := by rw [inter_comm, singleton_inter_of_not_mem h] @[mono] lemma inter_subset_inter {x y s t : finset α} (h : x ⊆ y) (h' : s ⊆ t) : x ∩ s ⊆ y ∩ t := begin intros a a_in, rw finset.mem_inter at a_in ⊢, exact ⟨h a_in.1, h' a_in.2⟩ end lemma inter_subset_inter_right {x y s : finset α} (h : x ⊆ y) : x ∩ s ⊆ y ∩ s := finset.inter_subset_inter h (finset.subset.refl _) lemma inter_subset_inter_left {x y s : finset α} (h : x ⊆ y) : s ∩ x ⊆ s ∩ y := finset.inter_subset_inter (finset.subset.refl _) h /-! ### lattice laws -/ instance : lattice (finset α) := { sup := (∪), sup_le := assume a b c, union_subset, le_sup_left := subset_union_left, le_sup_right := subset_union_right, inf := (∩), le_inf := assume a b c, subset_inter, inf_le_left := inter_subset_left, inf_le_right := inter_subset_right, ..finset.partial_order } @[simp] theorem sup_eq_union (s t : finset α) : s ⊔ t = s ∪ t := rfl @[simp] theorem inf_eq_inter (s t : finset α) : s ⊓ t = s ∩ t := rfl instance : semilattice_inf_bot (finset α) := { bot := ∅, bot_le := empty_subset, ..finset.lattice } instance {α : Type*} [decidable_eq α] : semilattice_sup_bot (finset α) := { ..finset.semilattice_inf_bot, ..finset.lattice } instance : distrib_lattice (finset α) := { le_sup_inf := assume a b c, show (a ∪ b) ∩ (a ∪ c) ⊆ a ∪ b ∩ c, by simp only [subset_iff, mem_inter, mem_union, and_imp, or_imp_distrib] {contextual:=tt}; simp only [true_or, imp_true_iff, true_and, or_true], ..finset.lattice } theorem inter_distrib_left (s t u : finset α) : s ∩ (t ∪ u) = (s ∩ t) ∪ (s ∩ u) := inf_sup_left theorem inter_distrib_right (s t u : finset α) : (s ∪ t) ∩ u = (s ∩ u) ∪ (t ∩ u) := inf_sup_right theorem union_distrib_left (s t u : finset α) : s ∪ (t ∩ u) = (s ∪ t) ∩ (s ∪ u) := sup_inf_left theorem union_distrib_right (s t u : finset α) : (s ∩ t) ∪ u = (s ∪ u) ∩ (t ∪ u) := sup_inf_right lemma union_eq_empty_iff (A B : finset α) : A ∪ B = ∅ ↔ A = ∅ ∧ B = ∅ := sup_eq_bot_iff /-! ### erase -/ /-- `erase s a` is the set `s - {a}`, that is, the elements of `s` which are not equal to `a`. -/ def erase (s : finset α) (a : α) : finset α := ⟨_, nodup_erase_of_nodup a s.2⟩ @[simp] theorem erase_val (s : finset α) (a : α) : (erase s a).1 = s.1.erase a := rfl @[simp] theorem mem_erase {a b : α} {s : finset α} : a ∈ erase s b ↔ a ≠ b ∧ a ∈ s := mem_erase_iff_of_nodup s.2 theorem not_mem_erase (a : α) (s : finset α) : a ∉ erase s a := mem_erase_of_nodup s.2 @[simp] theorem erase_empty (a : α) : erase ∅ a = ∅ := rfl theorem ne_of_mem_erase {a b : α} {s : finset α} : b ∈ erase s a → b ≠ a := by simp only [mem_erase]; exact and.left theorem mem_of_mem_erase {a b : α} {s : finset α} : b ∈ erase s a → b ∈ s := mem_of_mem_erase theorem mem_erase_of_ne_of_mem {a b : α} {s : finset α} : a ≠ b → a ∈ s → a ∈ erase s b := by simp only [mem_erase]; exact and.intro /-- An element of `s` that is not an element of `erase s a` must be `a`. -/ lemma eq_of_mem_of_not_mem_erase {a b : α} {s : finset α} (hs : b ∈ s) (hsa : b ∉ s.erase a) : b = a := begin rw [mem_erase, not_and] at hsa, exact not_imp_not.mp hsa hs end theorem erase_insert {a : α} {s : finset α} (h : a ∉ s) : erase (insert a s) a = s := ext $ assume x, by simp only [mem_erase, mem_insert, and_or_distrib_left, not_and_self, false_or]; apply and_iff_right_of_imp; rintro H rfl; exact h H theorem insert_erase {a : α} {s : finset α} (h : a ∈ s) : insert a (erase s a) = s := ext $ assume x, by simp only [mem_insert, mem_erase, or_and_distrib_left, dec_em, true_and]; apply or_iff_right_of_imp; rintro rfl; exact h theorem erase_subset_erase (a : α) {s t : finset α} (h : s ⊆ t) : erase s a ⊆ erase t a := val_le_iff.1 $ erase_le_erase _ $ val_le_iff.2 h theorem erase_subset (a : α) (s : finset α) : erase s a ⊆ s := erase_subset _ _ @[simp, norm_cast] lemma coe_erase (a : α) (s : finset α) : ↑(erase s a) = (s \ {a} : set α) := set.ext $ λ _, mem_erase.trans $ by rw [and_comm, set.mem_diff, set.mem_singleton_iff]; refl lemma erase_ssubset {a : α} {s : finset α} (h : a ∈ s) : s.erase a ⊂ s := calc s.erase a ⊂ insert a (s.erase a) : ssubset_insert $ not_mem_erase _ _ ... = _ : insert_erase h theorem erase_eq_of_not_mem {a : α} {s : finset α} (h : a ∉ s) : erase s a = s := eq_of_veq $ erase_of_not_mem h theorem subset_insert_iff {a : α} {s t : finset α} : s ⊆ insert a t ↔ erase s a ⊆ t := by simp only [subset_iff, or_iff_not_imp_left, mem_erase, mem_insert, and_imp]; exact forall_congr (λ x, forall_swap) theorem erase_insert_subset (a : α) (s : finset α) : erase (insert a s) a ⊆ s := subset_insert_iff.1 $ subset.refl _ theorem insert_erase_subset (a : α) (s : finset α) : s ⊆ insert a (erase s a) := subset_insert_iff.2 $ subset.refl _ /-! ### sdiff -/ /-- `s \ t` is the set consisting of the elements of `s` that are not in `t`. -/ instance : has_sdiff (finset α) := ⟨λs₁ s₂, ⟨s₁.1 - s₂.1, nodup_of_le (sub_le_self _ _) s₁.2⟩⟩ @[simp] theorem mem_sdiff {a : α} {s₁ s₂ : finset α} : a ∈ s₁ \ s₂ ↔ a ∈ s₁ ∧ a ∉ s₂ := mem_sub_of_nodup s₁.2 lemma not_mem_sdiff_of_mem_right {a : α} {s t : finset α} (h : a ∈ t) : a ∉ s \ t := by simp only [mem_sdiff, h, not_true, not_false_iff, and_false] theorem sdiff_union_of_subset {s₁ s₂ : finset α} (h : s₁ ⊆ s₂) : (s₂ \ s₁) ∪ s₁ = s₂ := ext $ λ a, by simpa only [mem_sdiff, mem_union, or_comm, or_and_distrib_left, dec_em, and_true] using or_iff_right_of_imp (@h a) theorem union_sdiff_of_subset {s₁ s₂ : finset α} (h : s₁ ⊆ s₂) : s₁ ∪ (s₂ \ s₁) = s₂ := (union_comm _ _).trans (sdiff_union_of_subset h) theorem inter_sdiff (s t u : finset α) : s ∩ (t \ u) = s ∩ t \ u := by { ext x, simp [and_assoc] } @[simp] theorem inter_sdiff_self (s₁ s₂ : finset α) : s₁ ∩ (s₂ \ s₁) = ∅ := eq_empty_of_forall_not_mem $ by simp only [mem_inter, mem_sdiff]; rintro x ⟨h, _, hn⟩; exact hn h @[simp] theorem sdiff_inter_self (s₁ s₂ : finset α) : (s₂ \ s₁) ∩ s₁ = ∅ := (inter_comm _ _).trans (inter_sdiff_self _ _) @[simp] theorem sdiff_self (s₁ : finset α) : s₁ \ s₁ = ∅ := by ext; simp theorem sdiff_inter_distrib_right (s₁ s₂ s₃ : finset α) : s₁ \ (s₂ ∩ s₃) = (s₁ \ s₂) ∪ (s₁ \ s₃) := by ext; simp only [and_or_distrib_left, mem_union, not_and_distrib, mem_sdiff, mem_inter] @[simp] theorem sdiff_inter_self_left (s₁ s₂ : finset α) : s₁ \ (s₁ ∩ s₂) = s₁ \ s₂ := by simp only [sdiff_inter_distrib_right, sdiff_self, empty_union] @[simp] theorem sdiff_inter_self_right (s₁ s₂ : finset α) : s₁ \ (s₂ ∩ s₁) = s₁ \ s₂ := by simp only [sdiff_inter_distrib_right, sdiff_self, union_empty] @[simp] theorem sdiff_empty {s₁ : finset α} : s₁ \ ∅ = s₁ := ext (by simp) @[mono] theorem sdiff_subset_sdiff {s₁ s₂ t₁ t₂ : finset α} (h₁ : t₁ ⊆ t₂) (h₂ : s₂ ⊆ s₁) : t₁ \ s₁ ⊆ t₂ \ s₂ := by simpa only [subset_iff, mem_sdiff, and_imp] using λ a m₁ m₂, and.intro (h₁ m₁) (mt (@h₂ _) m₂) theorem sdiff_subset_self {s₁ s₂ : finset α} : s₁ \ s₂ ⊆ s₁ := suffices s₁ \ s₂ ⊆ s₁ \ ∅, by simpa [sdiff_empty] using this, sdiff_subset_sdiff (subset.refl _) (empty_subset _) @[simp, norm_cast] lemma coe_sdiff (s₁ s₂ : finset α) : ↑(s₁ \ s₂) = (s₁ \ s₂ : set α) := set.ext $ λ _, mem_sdiff @[simp] theorem union_sdiff_self_eq_union {s t : finset α} : s ∪ (t \ s) = s ∪ t := ext $ λ a, by simp only [mem_union, mem_sdiff, or_iff_not_imp_left, imp_and_distrib, and_iff_left id] @[simp] theorem sdiff_union_self_eq_union {s t : finset α} : (s \ t) ∪ t = s ∪ t := by rw [union_comm, union_sdiff_self_eq_union, union_comm] lemma union_sdiff_symm {s t : finset α} : s ∪ (t \ s) = t ∪ (s \ t) := by rw [union_sdiff_self_eq_union, union_sdiff_self_eq_union, union_comm] lemma sdiff_union_inter (s t : finset α) : (s \ t) ∪ (s ∩ t) = s := by { simp only [ext_iff, mem_union, mem_sdiff, mem_inter], tauto } @[simp] lemma sdiff_idem (s t : finset α) : s \ t \ t = s \ t := by { simp only [ext_iff, mem_sdiff], tauto } lemma sdiff_eq_empty_iff_subset {s t : finset α} : s \ t = ∅ ↔ s ⊆ t := by { rw [subset_iff, ext_iff], simp } @[simp] lemma empty_sdiff (s : finset α) : ∅ \ s = ∅ := by { rw sdiff_eq_empty_iff_subset, exact empty_subset _ } lemma insert_sdiff_of_not_mem (s : finset α) {t : finset α} {x : α} (h : x ∉ t) : (insert x s) \ t = insert x (s \ t) := begin rw [← coe_inj, coe_insert, coe_sdiff, coe_sdiff, coe_insert], exact set.insert_diff_of_not_mem s h end lemma insert_sdiff_of_mem (s : finset α) {t : finset α} {x : α} (h : x ∈ t) : (insert x s) \ t = s \ t := begin rw [← coe_inj, coe_sdiff, coe_sdiff, coe_insert], exact set.insert_diff_of_mem s h end @[simp] lemma insert_sdiff_insert (s t : finset α) (x : α) : (insert x s) \ (insert x t) = s \ insert x t := insert_sdiff_of_mem _ (mem_insert_self _ _) lemma sdiff_insert_of_not_mem {s : finset α} {x : α} (h : x ∉ s) (t : finset α) : s \ (insert x t) = s \ t := begin refine subset.antisymm (sdiff_subset_sdiff (subset.refl _) (subset_insert _ _)) (λ y hy, _), simp only [mem_sdiff, mem_insert, not_or_distrib] at hy ⊢, exact ⟨hy.1, λ hxy, h $ hxy ▸ hy.1, hy.2⟩ end @[simp] lemma sdiff_subset (s t : finset α) : s \ t ⊆ s := by simp [subset_iff, mem_sdiff] {contextual := tt} lemma union_sdiff_distrib (s₁ s₂ t : finset α) : (s₁ ∪ s₂) \ t = s₁ \ t ∪ s₂ \ t := by { simp only [ext_iff, mem_sdiff, mem_union], tauto } lemma sdiff_union_distrib (s t₁ t₂ : finset α) : s \ (t₁ ∪ t₂) = (s \ t₁) ∩ (s \ t₂) := by { simp only [ext_iff, mem_union, mem_sdiff, mem_inter], tauto } lemma union_sdiff_self (s t : finset α) : (s ∪ t) \ t = s \ t := by rw [union_sdiff_distrib, sdiff_self, union_empty] lemma sdiff_singleton_eq_erase (a : α) (s : finset α) : s \ singleton a = erase s a := by { ext, rw [mem_erase, mem_sdiff, mem_singleton], tauto } lemma sdiff_sdiff_self_left (s t : finset α) : s \ (s \ t) = s ∩ t := by { simp only [ext_iff, mem_sdiff, mem_inter], tauto } lemma inter_eq_inter_of_sdiff_eq_sdiff {s t₁ t₂ : finset α} : s \ t₁ = s \ t₂ → s ∩ t₁ = s ∩ t₂ := by { simp only [ext_iff, mem_sdiff, mem_inter], intros b c, replace b := b c, split; tauto } end decidable_eq /-! ### attach -/ /-- `attach s` takes the elements of `s` and forms a new set of elements of the subtype `{x // x ∈ s}`. -/ def attach (s : finset α) : finset {x // x ∈ s} := ⟨attach s.1, nodup_attach.2 s.2⟩ theorem sizeof_lt_sizeof_of_mem [has_sizeof α] {x : α} {s : finset α} (hx : x ∈ s) : sizeof x < sizeof s := by { cases s, dsimp [sizeof, has_sizeof.sizeof, finset.sizeof], apply lt_add_left, exact multiset.sizeof_lt_sizeof_of_mem hx } @[simp] theorem attach_val (s : finset α) : s.attach.1 = s.1.attach := rfl @[simp] theorem mem_attach (s : finset α) : ∀ x, x ∈ s.attach := mem_attach _ @[simp] theorem attach_empty : attach (∅ : finset α) = ∅ := rfl /-! ### piecewise -/ section piecewise /-- `s.piecewise f g` is the function equal to `f` on the finset `s`, and to `g` on its complement. -/ def piecewise {α : Type*} {δ : α → Sort*} (s : finset α) (f g : Πi, δ i) [∀j, decidable (j ∈ s)] : Πi, δ i := λi, if i ∈ s then f i else g i variables {δ : α → Sort*} (s : finset α) (f g : Πi, δ i) @[simp] lemma piecewise_insert_self [decidable_eq α] {j : α} [∀i, decidable (i ∈ insert j s)] : (insert j s).piecewise f g j = f j := by simp [piecewise] @[simp] lemma piecewise_empty [∀i : α, decidable (i ∈ (∅ : finset α))] : piecewise ∅ f g = g := by { ext i, simp [piecewise] } variable [∀j, decidable (j ∈ s)] @[norm_cast] lemma piecewise_coe [∀j, decidable (j ∈ (s : set α))] : (s : set α).piecewise f g = s.piecewise f g := by { ext, congr } @[simp, priority 980] lemma piecewise_eq_of_mem {i : α} (hi : i ∈ s) : s.piecewise f g i = f i := by simp [piecewise, hi] @[simp, priority 980] lemma piecewise_eq_of_not_mem {i : α} (hi : i ∉ s) : s.piecewise f g i = g i := by simp [piecewise, hi] lemma piecewise_congr {f f' g g' : Π i, δ i} (hf : ∀ i ∈ s, f i = f' i) (hg : ∀ i ∉ s, g i = g' i) : s.piecewise f g = s.piecewise f' g' := funext $ λ i, if_ctx_congr iff.rfl (hf i) (hg i) @[simp, priority 990] lemma piecewise_insert_of_ne [decidable_eq α] {i j : α} [∀i, decidable (i ∈ insert j s)] (h : i ≠ j) : (insert j s).piecewise f g i = s.piecewise f g i := by simp [piecewise, h] lemma piecewise_insert [decidable_eq α] (j : α) [∀i, decidable (i ∈ insert j s)] : (insert j s).piecewise f g = update (s.piecewise f g) j (f j) := begin classical, rw [← piecewise_coe, ← piecewise_coe, ← set.piecewise_insert, ← coe_insert j s], congr end lemma piecewise_cases {i} (p : δ i → Prop) (hf : p (f i)) (hg : p (g i)) : p (s.piecewise f g i) := by by_cases hi : i ∈ s; simpa [hi] lemma piecewise_mem_set_pi {δ : α → Type*} {t : set α} {t' : Π i, set (δ i)} {f g} (hf : f ∈ set.pi t t') (hg : g ∈ set.pi t t') : s.piecewise f g ∈ set.pi t t' := by { classical, rw ← piecewise_coe, exact set.piecewise_mem_pi ↑s hf hg } lemma piecewise_singleton [decidable_eq α] (i : α) : piecewise {i} f g = update g i (f i) := by rw [← insert_emptyc_eq, piecewise_insert, piecewise_empty] lemma piecewise_piecewise_of_subset_left {s t : finset α} [Π i, decidable (i ∈ s)] [Π i, decidable (i ∈ t)] (h : s ⊆ t) (f₁ f₂ g : Π a, δ a) : s.piecewise (t.piecewise f₁ f₂) g = s.piecewise f₁ g := s.piecewise_congr (λ i hi, piecewise_eq_of_mem _ _ _ (h hi)) (λ _ _, rfl) @[simp] lemma piecewise_idem_left (f₁ f₂ g : Π a, δ a) : s.piecewise (s.piecewise f₁ f₂) g = s.piecewise f₁ g := piecewise_piecewise_of_subset_left (subset.refl _) _ _ _ lemma piecewise_piecewise_of_subset_right {s t : finset α} [Π i, decidable (i ∈ s)] [Π i, decidable (i ∈ t)] (h : t ⊆ s) (f g₁ g₂ : Π a, δ a) : s.piecewise f (t.piecewise g₁ g₂) = s.piecewise f g₂ := s.piecewise_congr (λ _ _, rfl) (λ i hi, t.piecewise_eq_of_not_mem _ _ (mt (@h _) hi)) @[simp] lemma piecewise_idem_right (f g₁ g₂ : Π a, δ a) : s.piecewise f (s.piecewise g₁ g₂) = s.piecewise f g₂ := piecewise_piecewise_of_subset_right (subset.refl _) f g₁ g₂ lemma update_eq_piecewise {β : Type*} [decidable_eq α] (f : α → β) (i : α) (v : β) : update f i v = piecewise (singleton i) (λj, v) f := (piecewise_singleton _ _ _).symm lemma update_piecewise [decidable_eq α] (i : α) (v : δ i) : update (s.piecewise f g) i v = s.piecewise (update f i v) (update g i v) := begin ext j, rcases em (j = i) with (rfl|hj); by_cases hs : j ∈ s; simp * end lemma update_piecewise_of_mem [decidable_eq α] {i : α} (hi : i ∈ s) (v : δ i) : update (s.piecewise f g) i v = s.piecewise (update f i v) g := begin rw update_piecewise, refine s.piecewise_congr (λ _ _, rfl) (λ j hj, update_noteq _ _ _), exact λ h, hj (h.symm ▸ hi) end lemma update_piecewise_of_not_mem [decidable_eq α] {i : α} (hi : i ∉ s) (v : δ i) : update (s.piecewise f g) i v = s.piecewise f (update g i v) := begin rw update_piecewise, refine s.piecewise_congr (λ j hj, update_noteq _ _ _) (λ _ _, rfl), exact λ h, hi (h ▸ hj) end lemma piecewise_le_of_le_of_le {δ : α → Type*} [Π i, preorder (δ i)] {f g h : Π i, δ i} (Hf : f ≤ h) (Hg : g ≤ h) : s.piecewise f g ≤ h := λ x, piecewise_cases s f g (≤ h x) (Hf x) (Hg x) lemma le_piecewise_of_le_of_le {δ : α → Type*} [Π i, preorder (δ i)] {f g h : Π i, δ i} (Hf : h ≤ f) (Hg : h ≤ g) : h ≤ s.piecewise f g := λ x, piecewise_cases s f g (λ y, h x ≤ y) (Hf x) (Hg x) lemma piecewise_le_piecewise' {δ : α → Type*} [Π i, preorder (δ i)] {f g f' g' : Π i, δ i} (Hf : ∀ x ∈ s, f x ≤ f' x) (Hg : ∀ x ∉ s, g x ≤ g' x) : s.piecewise f g ≤ s.piecewise f' g' := λ x, by { by_cases hx : x ∈ s; simp [hx, *] } lemma piecewise_le_piecewise {δ : α → Type*} [Π i, preorder (δ i)] {f g f' g' : Π i, δ i} (Hf : f ≤ f') (Hg : g ≤ g') : s.piecewise f g ≤ s.piecewise f' g' := s.piecewise_le_piecewise' (λ x _, Hf x) (λ x _, Hg x) lemma piecewise_mem_Icc_of_mem_of_mem {δ : α → Type*} [Π i, preorder (δ i)] {f f₁ g g₁ : Π i, δ i} (hf : f ∈ set.Icc f₁ g₁) (hg : g ∈ set.Icc f₁ g₁) : s.piecewise f g ∈ set.Icc f₁ g₁ := ⟨le_piecewise_of_le_of_le _ hf.1 hg.1, piecewise_le_of_le_of_le _ hf.2 hg.2⟩ lemma piecewise_mem_Icc {δ : α → Type*} [Π i, preorder (δ i)] {f g : Π i, δ i} (h : f ≤ g) : s.piecewise f g ∈ set.Icc f g := piecewise_mem_Icc_of_mem_of_mem _ (set.left_mem_Icc.2 h) (set.right_mem_Icc.2 h) lemma piecewise_mem_Icc' {δ : α → Type*} [Π i, preorder (δ i)] {f g : Π i, δ i} (h : g ≤ f) : s.piecewise f g ∈ set.Icc g f := piecewise_mem_Icc_of_mem_of_mem _ (set.right_mem_Icc.2 h) (set.left_mem_Icc.2 h) end piecewise section decidable_pi_exists variables {s : finset α} instance decidable_dforall_finset {p : Πa∈s, Prop} [hp : ∀a (h : a ∈ s), decidable (p a h)] : decidable (∀a (h : a ∈ s), p a h) := multiset.decidable_dforall_multiset /-- decidable equality for functions whose domain is bounded by finsets -/ instance decidable_eq_pi_finset {β : α → Type*} [h : ∀a, decidable_eq (β a)] : decidable_eq (Πa∈s, β a) := multiset.decidable_eq_pi_multiset instance decidable_dexists_finset {p : Πa∈s, Prop} [hp : ∀a (h : a ∈ s), decidable (p a h)] : decidable (∃a (h : a ∈ s), p a h) := multiset.decidable_dexists_multiset end decidable_pi_exists /-! ### filter -/ section filter variables (p q : α → Prop) [decidable_pred p] [decidable_pred q] /-- `filter p s` is the set of elements of `s` that satisfy `p`. -/ def filter (s : finset α) : finset α := ⟨_, nodup_filter p s.2⟩ @[simp] theorem filter_val (s : finset α) : (filter p s).1 = s.1.filter p := rfl @[simp] theorem filter_subset (s : finset α) : s.filter p ⊆ s := filter_subset _ _ variable {p} @[simp] theorem mem_filter {s : finset α} {a : α} : a ∈ s.filter p ↔ a ∈ s ∧ p a := mem_filter theorem filter_ssubset {s : finset α} : s.filter p ⊂ s ↔ ∃ x ∈ s, ¬ p x := ⟨λ h, let ⟨x, hs, hp⟩ := set.exists_of_ssubset h in ⟨x, hs, mt (λ hp, mem_filter.2 ⟨hs, hp⟩) hp⟩, λ ⟨x, hs, hp⟩, ⟨s.filter_subset _, λ h, hp (mem_filter.1 (h hs)).2⟩⟩ variable (p) theorem filter_filter (s : finset α) : (s.filter p).filter q = s.filter (λa, p a ∧ q a) := ext $ assume a, by simp only [mem_filter, and_comm, and.left_comm] lemma filter_true {s : finset α} [h : decidable_pred (λ _, true)] : @finset.filter α (λ _, true) h s = s := by ext; simp @[simp] theorem filter_false {h} (s : finset α) : @filter α (λa, false) h s = ∅ := ext $ assume a, by simp only [mem_filter, and_false]; refl variables {p q} /-- If all elements of a `finset` satisfy the predicate `p`, `s.filter p` is `s`. -/ @[simp] lemma filter_true_of_mem {s : finset α} (h : ∀ x ∈ s, p x) : s.filter p = s := ext $ λ x, ⟨λ h, (mem_filter.1 h).1, λ hx, mem_filter.2 ⟨hx, h x hx⟩⟩ /-- If all elements of a `finset` fail to satisfy the predicate `p`, `s.filter p` is `∅`. -/ lemma filter_false_of_mem {s : finset α} (h : ∀ x ∈ s, ¬ p x) : s.filter p = ∅ := eq_empty_of_forall_not_mem (by simpa) lemma filter_congr {s : finset α} (H : ∀ x ∈ s, p x ↔ q x) : filter p s = filter q s := eq_of_veq $ filter_congr H variables (p q) lemma filter_empty : filter p ∅ = ∅ := subset_empty.1 $ filter_subset _ _ lemma filter_subset_filter {s t : finset α} (h : s ⊆ t) : s.filter p ⊆ t.filter p := assume a ha, mem_filter.2 ⟨h (mem_filter.1 ha).1, (mem_filter.1 ha).2⟩ @[simp, norm_cast] lemma coe_filter (s : finset α) : ↑(s.filter p) = ({x ∈ ↑s | p x} : set α) := set.ext $ λ _, mem_filter theorem filter_singleton (a : α) : filter p (singleton a) = if p a then singleton a else ∅ := by { classical, ext x, simp, split_ifs with h; by_cases h' : x = a; simp [h, h'] } variable [decidable_eq α] theorem filter_union (s₁ s₂ : finset α) : (s₁ ∪ s₂).filter p = s₁.filter p ∪ s₂.filter p := ext $ λ _, by simp only [mem_filter, mem_union, or_and_distrib_right] theorem filter_union_right (s : finset α) : s.filter p ∪ s.filter q = s.filter (λx, p x ∨ q x) := ext $ λ x, by simp only [mem_filter, mem_union, and_or_distrib_left.symm] lemma filter_mem_eq_inter {s t : finset α} [Π i, decidable (i ∈ t)] : s.filter (λ i, i ∈ t) = s ∩ t := ext $ λ i, by rw [mem_filter, mem_inter] theorem filter_inter (s t : finset α) : filter p s ∩ t = filter p (s ∩ t) := by { ext, simp only [mem_inter, mem_filter, and.right_comm] } theorem inter_filter (s t : finset α) : s ∩ filter p t = filter p (s ∩ t) := by rw [inter_comm, filter_inter, inter_comm] theorem filter_insert (a : α) (s : finset α) : filter p (insert a s) = if p a then insert a (filter p s) else filter p s := by { ext x, simp, split_ifs with h; by_cases h' : x = a; simp [h, h'] } theorem filter_or [decidable_pred (λ a, p a ∨ q a)] (s : finset α) : s.filter (λ a, p a ∨ q a) = s.filter p ∪ s.filter q := ext $ λ _, by simp only [mem_filter, mem_union, and_or_distrib_left] theorem filter_and [decidable_pred (λ a, p a ∧ q a)] (s : finset α) : s.filter (λ a, p a ∧ q a) = s.filter p ∩ s.filter q := ext $ λ _, by simp only [mem_filter, mem_inter, and_comm, and.left_comm, and_self] theorem filter_not [decidable_pred (λ a, ¬ p a)] (s : finset α) : s.filter (λ a, ¬ p a) = s \ s.filter p := ext $ by simpa only [mem_filter, mem_sdiff, and_comm, not_and] using λ a, and_congr_right $ λ h : a ∈ s, (imp_iff_right h).symm.trans imp_not_comm theorem sdiff_eq_filter (s₁ s₂ : finset α) : s₁ \ s₂ = filter (∉ s₂) s₁ := ext $ λ _, by simp only [mem_sdiff, mem_filter] theorem sdiff_eq_self (s₁ s₂ : finset α) : s₁ \ s₂ = s₁ ↔ s₁ ∩ s₂ ⊆ ∅ := by { simp [subset.antisymm_iff,sdiff_subset_self], split; intro h, { transitivity' ((s₁ \ s₂) ∩ s₂), mono, simp }, { calc s₁ \ s₂ ⊇ s₁ \ (s₁ ∩ s₂) : by simp [(⊇)] ... ⊇ s₁ \ ∅ : by mono using [(⊇)] ... ⊇ s₁ : by simp [(⊇)] } } theorem filter_union_filter_neg_eq [decidable_pred (λ a, ¬ p a)] (s : finset α) : s.filter p ∪ s.filter (λa, ¬ p a) = s := by simp only [filter_not, union_sdiff_of_subset (filter_subset p s)] theorem filter_inter_filter_neg_eq (s : finset α) : s.filter p ∩ s.filter (λa, ¬ p a) = ∅ := by simp only [filter_not, inter_sdiff_self] lemma subset_union_elim {s : finset α} {t₁ t₂ : set α} (h : ↑s ⊆ t₁ ∪ t₂) : ∃s₁ s₂ : finset α, s₁ ∪ s₂ = s ∧ ↑s₁ ⊆ t₁ ∧ ↑s₂ ⊆ t₂ \ t₁ := begin classical, refine ⟨s.filter (∈ t₁), s.filter (∉ t₁), _, _ , _⟩, { simp [filter_union_right, em] }, { intro x, simp }, { intro x, simp, intros hx hx₂, refine ⟨or.resolve_left (h hx) hx₂, hx₂⟩ } end /- We can simplify an application of filter where the decidability is inferred in "the wrong way" -/ @[simp] lemma filter_congr_decidable {α} (s : finset α) (p : α → Prop) (h : decidable_pred p) [decidable_pred p] : @filter α p h s = s.filter p := by congr section classical open_locale classical /-- The following instance allows us to write `{ x ∈ s | p x }` for `finset.filter s p`. Since the former notation requires us to define this for all propositions `p`, and `finset.filter` only works for decidable propositions, the notation `{ x ∈ s | p x }` is only compatible with classical logic because it uses `classical.prop_decidable`. We don't want to redo all lemmas of `finset.filter` for `has_sep.sep`, so we make sure that `simp` unfolds the notation `{ x ∈ s | p x }` to `finset.filter s p`. If `p` happens to be decidable, the simp-lemma `filter_congr_decidable` will make sure that `finset.filter` uses the right instance for decidability. -/ noncomputable instance {α : Type*} : has_sep α (finset α) := ⟨λ p x, x.filter p⟩ @[simp] lemma sep_def {α : Type*} (s : finset α) (p : α → Prop) : {x ∈ s | p x} = s.filter p := rfl end classical /-- After filtering out everything that does not equal a given value, at most that value remains. This is equivalent to `filter_eq'` with the equality the other way. -/ -- This is not a good simp lemma, as it would prevent `finset.mem_filter` from firing -- on, e.g. `x ∈ s.filter(eq b)`. lemma filter_eq [decidable_eq β] (s : finset β) (b : β) : s.filter (eq b) = ite (b ∈ s) {b} ∅ := begin split_ifs, { ext, simp only [mem_filter, mem_singleton], exact ⟨λ h, h.2.symm, by { rintro ⟨h⟩, exact ⟨h, rfl⟩, }⟩ }, { ext, simp only [mem_filter, not_and, iff_false, not_mem_empty], rintros m ⟨e⟩, exact h m, } end /-- After filtering out everything that does not equal a given value, at most that value remains. This is equivalent to `filter_eq` with the equality the other way. -/ lemma filter_eq' [decidable_eq β] (s : finset β) (b : β) : s.filter (λ a, a = b) = ite (b ∈ s) {b} ∅ := trans (filter_congr (λ _ _, ⟨eq.symm, eq.symm⟩)) (filter_eq s b) lemma filter_ne [decidable_eq β] (s : finset β) (b : β) : s.filter (λ a, b ≠ a) = s.erase b := by { ext, simp only [mem_filter, mem_erase, ne.def], cc, } lemma filter_ne' [decidable_eq β] (s : finset β) (b : β) : s.filter (λ a, a ≠ b) = s.erase b := trans (filter_congr (λ _ _, ⟨ne.symm, ne.symm⟩)) (filter_ne s b) end filter /-! ### range -/ section range variables {n m l : ℕ} /-- `range n` is the set of natural numbers less than `n`. -/ def range (n : ℕ) : finset ℕ := ⟨_, nodup_range n⟩ @[simp] theorem range_coe (n : ℕ) : (range n).1 = multiset.range n := rfl @[simp] theorem mem_range : m ∈ range n ↔ m < n := mem_range @[simp] theorem range_zero : range 0 = ∅ := rfl @[simp] theorem range_one : range 1 = {0} := rfl theorem range_succ : range (succ n) = insert n (range n) := eq_of_veq $ (range_succ n).trans $ (ndinsert_of_not_mem not_mem_range_self).symm theorem range_add_one : range (n + 1) = insert n (range n) := range_succ @[simp] theorem not_mem_range_self : n ∉ range n := not_mem_range_self @[simp] theorem self_mem_range_succ (n : ℕ) : n ∈ range (n + 1) := multiset.self_mem_range_succ n @[simp] theorem range_subset {n m} : range n ⊆ range m ↔ n ≤ m := range_subset theorem range_mono : monotone range := λ _ _, range_subset.2 lemma mem_range_succ_iff {a b : ℕ} : a ∈ finset.range b.succ ↔ a ≤ b := finset.mem_range.trans nat.lt_succ_iff end range /- useful rules for calculations with quantifiers -/ theorem exists_mem_empty_iff (p : α → Prop) : (∃ x, x ∈ (∅ : finset α) ∧ p x) ↔ false := by simp only [not_mem_empty, false_and, exists_false] theorem exists_mem_insert [d : decidable_eq α] (a : α) (s : finset α) (p : α → Prop) : (∃ x, x ∈ insert a s ∧ p x) ↔ p a ∨ (∃ x, x ∈ s ∧ p x) := by simp only [mem_insert, or_and_distrib_right, exists_or_distrib, exists_eq_left] theorem forall_mem_empty_iff (p : α → Prop) : (∀ x, x ∈ (∅ : finset α) → p x) ↔ true := iff_true_intro $ λ _, false.elim theorem forall_mem_insert [d : decidable_eq α] (a : α) (s : finset α) (p : α → Prop) : (∀ x, x ∈ insert a s → p x) ↔ p a ∧ (∀ x, x ∈ s → p x) := by simp only [mem_insert, or_imp_distrib, forall_and_distrib, forall_eq] end finset /-- Equivalence between the set of natural numbers which are `≥ k` and `ℕ`, given by `n → n - k`. -/ def not_mem_range_equiv (k : ℕ) : {n // n ∉ range k} ≃ ℕ := { to_fun := λ i, i.1 - k, inv_fun := λ j, ⟨j + k, by simp⟩, left_inv := begin assume j, rw subtype.ext_iff_val, apply nat.sub_add_cancel, simpa using j.2 end, right_inv := λ j, nat.add_sub_cancel _ _ } @[simp] lemma coe_not_mem_range_equiv (k : ℕ) : (not_mem_range_equiv k : {n // n ∉ range k} → ℕ) = (λ i, i - k) := rfl @[simp] lemma coe_not_mem_range_equiv_symm (k : ℕ) : ((not_mem_range_equiv k).symm : ℕ → {n // n ∉ range k}) = λ j, ⟨j + k, by simp⟩ := rfl namespace option /-- Construct an empty or singleton finset from an `option` -/ def to_finset (o : option α) : finset α := match o with | none := ∅ | some a := {a} end @[simp] theorem to_finset_none : none.to_finset = (∅ : finset α) := rfl @[simp] theorem to_finset_some {a : α} : (some a).to_finset = {a} := rfl @[simp] theorem mem_to_finset {a : α} {o : option α} : a ∈ o.to_finset ↔ a ∈ o := by cases o; simp only [to_finset, finset.mem_singleton, option.mem_def, eq_comm]; refl end option /-! ### erase_dup on list and multiset -/ namespace multiset variable [decidable_eq α] /-- `to_finset s` removes duplicates from the multiset `s` to produce a finset. -/ def to_finset (s : multiset α) : finset α := ⟨_, nodup_erase_dup s⟩ @[simp] theorem to_finset_val (s : multiset α) : s.to_finset.1 = s.erase_dup := rfl theorem to_finset_eq {s : multiset α} (n : nodup s) : finset.mk s n = s.to_finset := finset.val_inj.1 (erase_dup_eq_self.2 n).symm @[simp] theorem mem_to_finset {a : α} {s : multiset α} : a ∈ s.to_finset ↔ a ∈ s := mem_erase_dup @[simp] lemma to_finset_zero : to_finset (0 : multiset α) = ∅ := rfl @[simp] lemma to_finset_cons (a : α) (s : multiset α) : to_finset (a ::ₘ s) = insert a (to_finset s) := finset.eq_of_veq erase_dup_cons @[simp] lemma to_finset_add (s t : multiset α) : to_finset (s + t) = to_finset s ∪ to_finset t := finset.ext $ by simp @[simp] lemma to_finset_nsmul (s : multiset α) : ∀(n : ℕ) (hn : n ≠ 0), (n •ℕ s).to_finset = s.to_finset | 0 h := by contradiction | (n+1) h := begin by_cases n = 0, { rw [h, zero_add, one_nsmul] }, { rw [add_nsmul, to_finset_add, one_nsmul, to_finset_nsmul n h, finset.union_idempotent] } end @[simp] lemma to_finset_inter (s t : multiset α) : to_finset (s ∩ t) = to_finset s ∩ to_finset t := finset.ext $ by simp @[simp] lemma to_finset_union (s t : multiset α) : (s ∪ t).to_finset = s.to_finset ∪ t.to_finset := by ext; simp theorem to_finset_eq_empty {m : multiset α} : m.to_finset = ∅ ↔ m = 0 := finset.val_inj.symm.trans multiset.erase_dup_eq_zero @[simp] lemma to_finset_subset (m1 m2 : multiset α) : m1.to_finset ⊆ m2.to_finset ↔ m1 ⊆ m2 := by simp only [finset.subset_iff, multiset.subset_iff, multiset.mem_to_finset] end multiset namespace list variable [decidable_eq α] /-- `to_finset l` removes duplicates from the list `l` to produce a finset. -/ def to_finset (l : list α) : finset α := multiset.to_finset l @[simp] theorem to_finset_val (l : list α) : l.to_finset.1 = (l.erase_dup : multiset α) := rfl theorem to_finset_eq {l : list α} (n : nodup l) : @finset.mk α l n = l.to_finset := multiset.to_finset_eq n @[simp] theorem mem_to_finset {a : α} {l : list α} : a ∈ l.to_finset ↔ a ∈ l := mem_erase_dup @[simp] theorem to_finset_nil : to_finset (@nil α) = ∅ := rfl @[simp] theorem to_finset_cons {a : α} {l : list α} : to_finset (a :: l) = insert a (to_finset l) := finset.eq_of_veq $ by by_cases h : a ∈ l; simp [finset.insert_val', multiset.erase_dup_cons, h] lemma to_finset_surj_on : set.surj_on to_finset {l : list α | l.nodup} set.univ := begin rintro s -, cases s with t hl, induction t using quot.ind with l, refine ⟨l, hl, (to_finset_eq hl).symm⟩ end theorem to_finset_surjective : surjective (to_finset : list α → finset α) := by { intro s, rcases to_finset_surj_on (set.mem_univ s) with ⟨l, -, hls⟩, exact ⟨l, hls⟩ } end list namespace finset /-! ### map -/ section map open function /-- When `f` is an embedding of `α` in `β` and `s` is a finset in `α`, then `s.map f` is the image finset in `β`. The embedding condition guarantees that there are no duplicates in the image. -/ def map (f : α ↪ β) (s : finset α) : finset β := ⟨s.1.map f, nodup_map f.2 s.2⟩ @[simp] theorem map_val (f : α ↪ β) (s : finset α) : (map f s).1 = s.1.map f := rfl @[simp] theorem map_empty (f : α ↪ β) : (∅ : finset α).map f = ∅ := rfl variables {f : α ↪ β} {s : finset α} @[simp] theorem mem_map {b : β} : b ∈ s.map f ↔ ∃ a ∈ s, f a = b := mem_map.trans $ by simp only [exists_prop]; refl theorem mem_map' (f : α ↪ β) {a} {s : finset α} : f a ∈ s.map f ↔ a ∈ s := mem_map_of_injective f.2 theorem mem_map_of_mem (f : α ↪ β) {a} {s : finset α} : a ∈ s → f a ∈ s.map f := (mem_map' _).2 @[simp, norm_cast] theorem coe_map (f : α ↪ β) (s : finset α) : (↑(s.map f) : set β) = f '' ↑s := set.ext $ λ x, mem_map.trans set.mem_image_iff_bex.symm theorem coe_map_subset_range (f : α ↪ β) (s : finset α) : (↑(s.map f) : set β) ⊆ set.range f := calc ↑(s.map f) = f '' ↑s : coe_map f s ... ⊆ set.range f : set.image_subset_range f ↑s theorem map_to_finset [decidable_eq α] [decidable_eq β] {s : multiset α} : s.to_finset.map f = (s.map f).to_finset := ext $ λ _, by simp only [mem_map, multiset.mem_map, exists_prop, multiset.mem_to_finset] @[simp] theorem map_refl : s.map (embedding.refl _) = s := ext $ λ _, by simpa only [mem_map, exists_prop] using exists_eq_right theorem map_map {g : β ↪ γ} : (s.map f).map g = s.map (f.trans g) := eq_of_veq $ by simp only [map_val, multiset.map_map]; refl theorem map_subset_map {s₁ s₂ : finset α} : s₁.map f ⊆ s₂.map f ↔ s₁ ⊆ s₂ := ⟨λ h x xs, (mem_map' _).1 $ h $ (mem_map' f).2 xs, λ h, by simp [subset_def, map_subset_map h]⟩ theorem map_inj {s₁ s₂ : finset α} : s₁.map f = s₂.map f ↔ s₁ = s₂ := by simp only [subset.antisymm_iff, map_subset_map] /-- Associate to an embedding `f` from `α` to `β` the embedding that maps a finset to its image under `f`. -/ def map_embedding (f : α ↪ β) : finset α ↪ finset β := ⟨map f, λ s₁ s₂, map_inj.1⟩ @[simp] theorem map_embedding_apply : map_embedding f s = map f s := rfl theorem map_filter {p : β → Prop} [decidable_pred p] : (s.map f).filter p = (s.filter (p ∘ f)).map f := ext $ λ b, by simp only [mem_filter, mem_map, exists_prop, and_assoc]; exact ⟨by rintro ⟨⟨x, h1, rfl⟩, h2⟩; exact ⟨x, h1, h2, rfl⟩, by rintro ⟨x, h1, h2, rfl⟩; exact ⟨⟨x, h1, rfl⟩, h2⟩⟩ theorem map_union [decidable_eq α] [decidable_eq β] {f : α ↪ β} (s₁ s₂ : finset α) : (s₁ ∪ s₂).map f = s₁.map f ∪ s₂.map f := ext $ λ _, by simp only [mem_map, mem_union, exists_prop, or_and_distrib_right, exists_or_distrib] theorem map_inter [decidable_eq α] [decidable_eq β] {f : α ↪ β} (s₁ s₂ : finset α) : (s₁ ∩ s₂).map f = s₁.map f ∩ s₂.map f := ext $ λ b, by simp only [mem_map, mem_inter, exists_prop]; exact ⟨by rintro ⟨a, ⟨m₁, m₂⟩, rfl⟩; exact ⟨⟨a, m₁, rfl⟩, ⟨a, m₂, rfl⟩⟩, by rintro ⟨⟨a, m₁, e⟩, ⟨a', m₂, rfl⟩⟩; cases f.2 e; exact ⟨_, ⟨m₁, m₂⟩, rfl⟩⟩ @[simp] theorem map_singleton (f : α ↪ β) (a : α) : map f {a} = {f a} := ext $ λ _, by simp only [mem_map, mem_singleton, exists_prop, exists_eq_left]; exact eq_comm @[simp] theorem map_insert [decidable_eq α] [decidable_eq β] (f : α ↪ β) (a : α) (s : finset α) : (insert a s).map f = insert (f a) (s.map f) := by simp only [insert_eq, map_union, map_singleton] @[simp] theorem map_eq_empty : s.map f = ∅ ↔ s = ∅ := ⟨λ h, eq_empty_of_forall_not_mem $ λ a m, ne_empty_of_mem (mem_map_of_mem _ m) h, λ e, e.symm ▸ rfl⟩ lemma attach_map_val {s : finset α} : s.attach.map (embedding.subtype _) = s := eq_of_veq $ by rw [map_val, attach_val]; exact attach_map_val _ lemma nonempty.map (h : s.nonempty) (f : α ↪ β) : (s.map f).nonempty := let ⟨a, ha⟩ := h in ⟨f a, (mem_map' f).mpr ha⟩ end map lemma range_add_one' (n : ℕ) : range (n + 1) = insert 0 ((range n).map ⟨λi, i + 1, assume i j, nat.succ.inj⟩) := by ext (⟨⟩ | ⟨n⟩); simp [nat.succ_eq_add_one, nat.zero_lt_succ n] /-! ### image -/ section image variables [decidable_eq β] /-- `image f s` is the forward image of `s` under `f`. -/ def image (f : α → β) (s : finset α) : finset β := (s.1.map f).to_finset @[simp] theorem image_val (f : α → β) (s : finset α) : (image f s).1 = (s.1.map f).erase_dup := rfl @[simp] theorem image_empty (f : α → β) : (∅ : finset α).image f = ∅ := rfl variables {f : α → β} {s : finset α} @[simp] theorem mem_image {b : β} : b ∈ s.image f ↔ ∃ a ∈ s, f a = b := by simp only [mem_def, image_val, mem_erase_dup, multiset.mem_map, exists_prop] theorem mem_image_of_mem (f : α → β) {a} {s : finset α} (h : a ∈ s) : f a ∈ s.image f := mem_image.2 ⟨_, h, rfl⟩ lemma filter_mem_image_eq_image (f : α → β) (s : finset α) (t : finset β) (h : ∀ x ∈ s, f x ∈ t) : t.filter (λ y, y ∈ s.image f) = s.image f := by { ext, rw [mem_filter, mem_image], simp only [and_imp, exists_prop, and_iff_right_iff_imp, exists_imp_distrib], rintros x xel rfl, exact h _ xel } lemma fiber_nonempty_iff_mem_image (f : α → β) (s : finset α) (y : β) : (s.filter (λ x, f x = y)).nonempty ↔ y ∈ s.image f := by simp [finset.nonempty] @[simp, norm_cast] lemma coe_image {f : α → β} : ↑(s.image f) = f '' ↑s := set.ext $ λ _, mem_image.trans set.mem_image_iff_bex.symm lemma nonempty.image (h : s.nonempty) (f : α → β) : (s.image f).nonempty := let ⟨a, ha⟩ := h in ⟨f a, mem_image_of_mem f ha⟩ theorem image_to_finset [decidable_eq α] {s : multiset α} : s.to_finset.image f = (s.map f).to_finset := ext $ λ _, by simp only [mem_image, multiset.mem_to_finset, exists_prop, multiset.mem_map] theorem image_val_of_inj_on (H : ∀x∈s, ∀y∈s, f x = f y → x = y) : (image f s).1 = s.1.map f := multiset.erase_dup_eq_self.2 (nodup_map_on H s.2) @[simp] theorem image_id [decidable_eq α] : s.image id = s := ext $ λ _, by simp only [mem_image, exists_prop, id, exists_eq_right] theorem image_image [decidable_eq γ] {g : β → γ} : (s.image f).image g = s.image (g ∘ f) := eq_of_veq $ by simp only [image_val, erase_dup_map_erase_dup_eq, multiset.map_map] theorem image_subset_image {s₁ s₂ : finset α} (h : s₁ ⊆ s₂) : s₁.image f ⊆ s₂.image f := by simp only [subset_def, image_val, subset_erase_dup', erase_dup_subset', multiset.map_subset_map h] theorem image_subset_iff {s : finset α} {t : finset β} {f : α → β} : s.image f ⊆ t ↔ ∀ x ∈ s, f x ∈ t := calc s.image f ⊆ t ↔ f '' ↑s ⊆ ↑t : by norm_cast ... ↔ _ : set.image_subset_iff theorem image_mono (f : α → β) : monotone (finset.image f) := λ _ _, image_subset_image theorem coe_image_subset_range : ↑(s.image f) ⊆ set.range f := calc ↑(s.image f) = f '' ↑s : coe_image ... ⊆ set.range f : set.image_subset_range f ↑s theorem image_filter {p : β → Prop} [decidable_pred p] : (s.image f).filter p = (s.filter (p ∘ f)).image f := ext $ λ b, by simp only [mem_filter, mem_image, exists_prop]; exact ⟨by rintro ⟨⟨x, h1, rfl⟩, h2⟩; exact ⟨x, ⟨h1, h2⟩, rfl⟩, by rintro ⟨x, ⟨h1, h2⟩, rfl⟩; exact ⟨⟨x, h1, rfl⟩, h2⟩⟩ theorem image_union [decidable_eq α] {f : α → β} (s₁ s₂ : finset α) : (s₁ ∪ s₂).image f = s₁.image f ∪ s₂.image f := ext $ λ _, by simp only [mem_image, mem_union, exists_prop, or_and_distrib_right, exists_or_distrib] theorem image_inter [decidable_eq α] (s₁ s₂ : finset α) (hf : ∀x y, f x = f y → x = y) : (s₁ ∩ s₂).image f = s₁.image f ∩ s₂.image f := ext $ by simp only [mem_image, exists_prop, mem_inter]; exact λ b, ⟨λ ⟨a, ⟨m₁, m₂⟩, e⟩, ⟨⟨a, m₁, e⟩, ⟨a, m₂, e⟩⟩, λ ⟨⟨a, m₁, e₁⟩, ⟨a', m₂, e₂⟩⟩, ⟨a, ⟨m₁, hf _ _ (e₂.trans e₁.symm) ▸ m₂⟩, e₁⟩⟩. @[simp] theorem image_singleton (f : α → β) (a : α) : image f {a} = {f a} := ext $ λ x, by simpa only [mem_image, exists_prop, mem_singleton, exists_eq_left] using eq_comm @[simp] theorem image_insert [decidable_eq α] (f : α → β) (a : α) (s : finset α) : (insert a s).image f = insert (f a) (s.image f) := by simp only [insert_eq, image_singleton, image_union] @[simp] theorem image_eq_empty : s.image f = ∅ ↔ s = ∅ := ⟨λ h, eq_empty_of_forall_not_mem $ λ a m, ne_empty_of_mem (mem_image_of_mem _ m) h, λ e, e.symm ▸ rfl⟩ lemma attach_image_val [decidable_eq α] {s : finset α} : s.attach.image subtype.val = s := eq_of_veq $ by rw [image_val, attach_val, multiset.attach_map_val, erase_dup_eq_self] @[simp] lemma attach_insert [decidable_eq α] {a : α} {s : finset α} : attach (insert a s) = insert (⟨a, mem_insert_self a s⟩ : {x // x ∈ insert a s}) ((attach s).image (λx, ⟨x.1, mem_insert_of_mem x.2⟩)) := ext $ λ ⟨x, hx⟩, ⟨or.cases_on (mem_insert.1 hx) (λ h : x = a, λ _, mem_insert.2 $ or.inl $ subtype.eq h) (λ h : x ∈ s, λ _, mem_insert_of_mem $ mem_image.2 $ ⟨⟨x, h⟩, mem_attach _ _, subtype.eq rfl⟩), λ _, finset.mem_attach _ _⟩ theorem map_eq_image (f : α ↪ β) (s : finset α) : s.map f = s.image f := eq_of_veq $ (multiset.erase_dup_eq_self.2 (s.map f).2).symm lemma image_const {s : finset α} (h : s.nonempty) (b : β) : s.image (λa, b) = singleton b := ext $ assume b', by simp only [mem_image, exists_prop, exists_and_distrib_right, h.bex, true_and, mem_singleton, eq_comm] /-- Because `finset.image` requires a `decidable_eq` instances for the target type, we can only construct a `functor finset` when working classically. -/ instance [Π P, decidable P] : functor finset := { map := λ α β f s, s.image f, } instance [Π P, decidable P] : is_lawful_functor finset := { id_map := λ α x, image_id, comp_map := λ α β γ f g s, image_image.symm, } /-- Given a finset `s` and a predicate `p`, `s.subtype p` is the finset of `subtype p` whose elements belong to `s`. -/ protected def subtype {α} (p : α → Prop) [decidable_pred p] (s : finset α) : finset (subtype p) := (s.filter p).attach.map ⟨λ x, ⟨x.1, (finset.mem_filter.1 x.2).2⟩, λ x y H, subtype.eq $ subtype.mk.inj H⟩ @[simp] lemma mem_subtype {p : α → Prop} [decidable_pred p] {s : finset α} : ∀{a : subtype p}, a ∈ s.subtype p ↔ (a : α) ∈ s | ⟨a, ha⟩ := by simp [finset.subtype, ha] lemma subtype_eq_empty {p : α → Prop} [decidable_pred p] {s : finset α} : s.subtype p = ∅ ↔ ∀ x, p x → x ∉ s := by simp [ext_iff, subtype.forall, subtype.coe_mk]; refl /-- `s.subtype p` converts back to `s.filter p` with `embedding.subtype`. -/ @[simp] lemma subtype_map (p : α → Prop) [decidable_pred p] : (s.subtype p).map (embedding.subtype _) = s.filter p := begin ext x, rw mem_map, change (∃ a : {x // p x}, ∃ H, (a : α) = x) ↔ _, split, { rintros ⟨y, hy, hyval⟩, rw [mem_subtype, hyval] at hy, rw mem_filter, use hy, rw ← hyval, use y.property }, { intro hx, rw mem_filter at hx, use ⟨⟨x, hx.2⟩, mem_subtype.2 hx.1, rfl⟩ } end /-- If all elements of a `finset` satisfy the predicate `p`, `s.subtype p` converts back to `s` with `embedding.subtype`. -/ lemma subtype_map_of_mem {p : α → Prop} [decidable_pred p] (h : ∀ x ∈ s, p x) : (s.subtype p).map (embedding.subtype _) = s := by rw [subtype_map, filter_true_of_mem h] /-- If a `finset` of a subtype is converted to the main type with `embedding.subtype`, all elements of the result have the property of the subtype. -/ lemma property_of_mem_map_subtype {p : α → Prop} (s : finset {x // p x}) {a : α} (h : a ∈ s.map (embedding.subtype _)) : p a := begin rcases mem_map.1 h with ⟨x, hx, rfl⟩, exact x.2 end /-- If a `finset` of a subtype is converted to the main type with `embedding.subtype`, the result does not contain any value that does not satisfy the property of the subtype. -/ lemma not_mem_map_subtype_of_not_property {p : α → Prop} (s : finset {x // p x}) {a : α} (h : ¬ p a) : a ∉ (s.map (embedding.subtype _)) := mt s.property_of_mem_map_subtype h /-- If a `finset` of a subtype is converted to the main type with `embedding.subtype`, the result is a subset of the set giving the subtype. -/ lemma map_subtype_subset {t : set α} (s : finset t) : ↑(s.map (embedding.subtype _)) ⊆ t := begin intros a ha, rw mem_coe at ha, convert property_of_mem_map_subtype s ha end lemma subset_image_iff {f : α → β} {s : finset β} {t : set α} : ↑s ⊆ f '' t ↔ ∃s' : finset α, ↑s' ⊆ t ∧ s'.image f = s := begin classical, split, swap, { rintro ⟨s, hs, rfl⟩, rw [coe_image], exact set.image_subset f hs }, intro h, induction s using finset.induction with a s has ih h, { refine ⟨∅, set.empty_subset _, _⟩, convert finset.image_empty _ }, rw [finset.coe_insert, set.insert_subset] at h, rcases ih h.2 with ⟨s', hst, hsi⟩, rcases h.1 with ⟨x, hxt, rfl⟩, refine ⟨insert x s', _, _⟩, { rw [finset.coe_insert, set.insert_subset], exact ⟨hxt, hst⟩ }, rw [finset.image_insert, hsi], congr end end image end finset theorem multiset.to_finset_map [decidable_eq α] [decidable_eq β] (f : α → β) (m : multiset α) : (m.map f).to_finset = m.to_finset.image f := finset.val_inj.1 (multiset.erase_dup_map_erase_dup_eq _ _).symm namespace finset /-! ### card -/ section card /-- `card s` is the cardinality (number of elements) of `s`. -/ def card (s : finset α) : nat := s.1.card theorem card_def (s : finset α) : s.card = s.1.card := rfl @[simp] lemma card_mk {m nodup} : (⟨m, nodup⟩ : finset α).card = m.card := rfl @[simp] theorem card_empty : card (∅ : finset α) = 0 := rfl @[simp] theorem card_eq_zero {s : finset α} : card s = 0 ↔ s = ∅ := card_eq_zero.trans val_eq_zero theorem card_pos {s : finset α} : 0 < card s ↔ s.nonempty := pos_iff_ne_zero.trans $ (not_congr card_eq_zero).trans nonempty_iff_ne_empty.symm theorem card_ne_zero_of_mem {s : finset α} {a : α} (h : a ∈ s) : card s ≠ 0 := (not_congr card_eq_zero).2 (ne_empty_of_mem h) theorem card_eq_one {s : finset α} : s.card = 1 ↔ ∃ a, s = {a} := by cases s; simp only [multiset.card_eq_one, finset.card, ← val_inj, singleton_val] @[simp] theorem card_insert_of_not_mem [decidable_eq α] {a : α} {s : finset α} (h : a ∉ s) : card (insert a s) = card s + 1 := by simpa only [card_cons, card, insert_val] using congr_arg multiset.card (ndinsert_of_not_mem h) theorem card_insert_of_mem [decidable_eq α] {a : α} {s : finset α} (h : a ∈ s) : card (insert a s) = card s := by rw insert_eq_of_mem h theorem card_insert_le [decidable_eq α] (a : α) (s : finset α) : card (insert a s) ≤ card s + 1 := by by_cases a ∈ s; [{rw [insert_eq_of_mem h], apply nat.le_add_right}, rw [card_insert_of_not_mem h]] @[simp] theorem card_singleton (a : α) : card ({a} : finset α) = 1 := card_singleton _ lemma card_singleton_inter [decidable_eq α] {x : α} {s : finset α} : ({x} ∩ s).card ≤ 1 := begin cases (finset.decidable_mem x s), { simp [finset.singleton_inter_of_not_mem h] }, { simp [finset.singleton_inter_of_mem h] }, end theorem card_erase_of_mem [decidable_eq α] {a : α} {s : finset α} : a ∈ s → card (erase s a) = pred (card s) := card_erase_of_mem theorem card_erase_lt_of_mem [decidable_eq α] {a : α} {s : finset α} : a ∈ s → card (erase s a) < card s := card_erase_lt_of_mem theorem card_erase_le [decidable_eq α] {a : α} {s : finset α} : card (erase s a) ≤ card s := card_erase_le theorem pred_card_le_card_erase [decidable_eq α] {a : α} {s : finset α} : card s - 1 ≤ card (erase s a) := begin by_cases h : a ∈ s, { rw [card_erase_of_mem h], refl }, { rw [erase_eq_of_not_mem h], apply nat.sub_le } end @[simp] theorem card_range (n : ℕ) : card (range n) = n := card_range n @[simp] theorem card_attach {s : finset α} : card (attach s) = card s := multiset.card_attach end card end finset theorem multiset.to_finset_card_le [decidable_eq α] (m : multiset α) : m.to_finset.card ≤ m.card := card_le_of_le (erase_dup_le _) theorem list.to_finset_card_le [decidable_eq α] (l : list α) : l.to_finset.card ≤ l.length := multiset.to_finset_card_le ⟦l⟧ namespace finset section card theorem card_image_le [decidable_eq β] {f : α → β} {s : finset α} : card (image f s) ≤ card s := by simpa only [card_map] using (s.1.map f).to_finset_card_le theorem card_image_of_inj_on [decidable_eq β] {f : α → β} {s : finset α} (H : ∀x∈s, ∀y∈s, f x = f y → x = y) : card (image f s) = card s := by simp only [card, image_val_of_inj_on H, card_map] theorem card_image_of_injective [decidable_eq β] {f : α → β} (s : finset α) (H : injective f) : card (image f s) = card s := card_image_of_inj_on $ λ x _ y _ h, H h lemma fiber_card_ne_zero_iff_mem_image (s : finset α) (f : α → β) [decidable_eq β] (y : β) : (s.filter (λ x, f x = y)).card ≠ 0 ↔ y ∈ s.image f := by { rw [←pos_iff_ne_zero, card_pos, fiber_nonempty_iff_mem_image] } @[simp] lemma card_map {α β} (f : α ↪ β) {s : finset α} : (s.map f).card = s.card := multiset.card_map _ _ lemma card_eq_of_bijective {s : finset α} {n : ℕ} (f : ∀i, i < n → α) (hf : ∀a∈s, ∃i, ∃h:i<n, f i h = a) (hf' : ∀i (h : i < n), f i h ∈ s) (f_inj : ∀i j (hi : i < n) (hj : j < n), f i hi = f j hj → i = j) : card s = n := begin classical, have : ∀ (a : α), a ∈ s ↔ ∃i (hi : i ∈ range n), f i (mem_range.1 hi) = a, from assume a, ⟨assume ha, let ⟨i, hi, eq⟩ := hf a ha in ⟨i, mem_range.2 hi, eq⟩, assume ⟨i, hi, eq⟩, eq ▸ hf' i (mem_range.1 hi)⟩, have : s = ((range n).attach.image $ λi, f i.1 (mem_range.1 i.2)), by simpa only [ext_iff, mem_image, exists_prop, subtype.exists, mem_attach, true_and], calc card s = card ((range n).attach.image $ λi, f i.1 (mem_range.1 i.2)) : by rw [this] ... = card ((range n).attach) : card_image_of_injective _ $ assume ⟨i, hi⟩ ⟨j, hj⟩ eq, subtype.eq $ f_inj i j (mem_range.1 hi) (mem_range.1 hj) eq ... = card (range n) : card_attach ... = n : card_range n end lemma card_eq_succ [decidable_eq α] {s : finset α} {n : ℕ} : s.card = n + 1 ↔ (∃a t, a ∉ t ∧ insert a t = s ∧ card t = n) := iff.intro (assume eq, have 0 < card s, from eq.symm ▸ nat.zero_lt_succ _, let ⟨a, has⟩ := card_pos.mp this in ⟨a, s.erase a, s.not_mem_erase a, insert_erase has, by simp only [eq, card_erase_of_mem has, pred_succ]⟩) (assume ⟨a, t, hat, s_eq, n_eq⟩, s_eq ▸ n_eq ▸ card_insert_of_not_mem hat) theorem card_le_of_subset {s t : finset α} : s ⊆ t → card s ≤ card t := multiset.card_le_of_le ∘ val_le_iff.mpr theorem eq_of_subset_of_card_le {s t : finset α} (h : s ⊆ t) (h₂ : card t ≤ card s) : s = t := eq_of_veq $ multiset.eq_of_le_of_card_le (val_le_iff.mpr h) h₂ lemma card_lt_card {s t : finset α} (h : s ⊂ t) : s.card < t.card := card_lt_of_lt (val_lt_iff.2 h) lemma card_le_card_of_inj_on {s : finset α} {t : finset β} (f : α → β) (hf : ∀a∈s, f a ∈ t) (f_inj : ∀a₁∈s, ∀a₂∈s, f a₁ = f a₂ → a₁ = a₂) : card s ≤ card t := begin classical, calc card s = card (s.image f) : by rw [card_image_of_inj_on f_inj] ... ≤ card t : card_le_of_subset $ assume x hx, match x, finset.mem_image.1 hx with _, ⟨a, ha, rfl⟩ := hf a ha end end /-- If there are more pigeons than pigeonholes, then there are two pigeons in the same pigeonhole. -/ lemma exists_ne_map_eq_of_card_lt_of_maps_to {s : finset α} {t : finset β} (hc : t.card < s.card) {f : α → β} (hf : ∀ a ∈ s, f a ∈ t) : ∃ (x ∈ s) (y ∈ s), x ≠ y ∧ f x = f y := begin classical, by_contra hz, push_neg at hz, refine hc.not_le (card_le_card_of_inj_on f hf _), intros x hx y hy, contrapose, exact hz x hx y hy, end lemma card_le_of_inj_on {n} {s : finset α} (f : ℕ → α) (hf : ∀i<n, f i ∈ s) (f_inj : ∀i j, i<n → j<n → f i = f j → i = j) : n ≤ card s := calc n = card (range n) : (card_range n).symm ... ≤ card s : card_le_card_of_inj_on f (by simpa only [mem_range]) (by simp only [mem_range]; exact assume a₁ h₁ a₂ h₂, f_inj a₁ a₂ h₁ h₂) /-- Suppose that, given objects defined on all strict subsets of any finset `s`, one knows how to define an object on `s`. Then one can inductively define an object on all finsets, starting from the empty set and iterating. This can be used either to define data, or to prove properties. -/ @[elab_as_eliminator] def strong_induction_on {p : finset α → Sort*} : ∀ (s : finset α), (∀s, (∀t ⊂ s, p t) → p s) → p s | ⟨s, nd⟩ ih := multiset.strong_induction_on s (λ s IH nd, ih ⟨s, nd⟩ (λ ⟨t, nd'⟩ ss, IH t (val_lt_iff.2 ss) nd')) nd @[elab_as_eliminator] lemma case_strong_induction_on [decidable_eq α] {p : finset α → Prop} (s : finset α) (h₀ : p ∅) (h₁ : ∀ a s, a ∉ s → (∀t ⊆ s, p t) → p (insert a s)) : p s := finset.strong_induction_on s $ λ s, finset.induction_on s (λ _, h₀) $ λ a s n _ ih, h₁ a s n $ λ t ss, ih _ (lt_of_le_of_lt ss (ssubset_insert n) : t < _) lemma card_congr {s : finset α} {t : finset β} (f : Π a ∈ s, β) (h₁ : ∀ a ha, f a ha ∈ t) (h₂ : ∀ a b ha hb, f a ha = f b hb → a = b) (h₃ : ∀ b ∈ t, ∃ a ha, f a ha = b) : s.card = t.card := by haveI := classical.prop_decidable; exact calc s.card = s.attach.card : card_attach.symm ... = (s.attach.image (λ (a : {a // a ∈ s}), f a.1 a.2)).card : eq.symm (card_image_of_injective _ (λ a b h, subtype.eq (h₂ _ _ _ _ h))) ... = t.card : congr_arg card (finset.ext $ λ b, ⟨λ h, let ⟨a, ha₁, ha₂⟩ := mem_image.1 h in ha₂ ▸ h₁ _ _, λ h, let ⟨a, ha₁, ha₂⟩ := h₃ b h in mem_image.2 ⟨⟨a, ha₁⟩, by simp [ha₂]⟩⟩) lemma card_union_add_card_inter [decidable_eq α] (s t : finset α) : (s ∪ t).card + (s ∩ t).card = s.card + t.card := finset.induction_on t (by simp) $ λ a r har, by by_cases a ∈ s; simp *; cc lemma card_union_le [decidable_eq α] (s t : finset α) : (s ∪ t).card ≤ s.card + t.card := card_union_add_card_inter s t ▸ le_add_right _ _ lemma card_union_eq [decidable_eq α] {s t : finset α} (h : disjoint s t) : (s ∪ t).card = s.card + t.card := begin rw [← card_union_add_card_inter], convert (add_zero _).symm, rw [card_eq_zero], rwa [disjoint_iff] at h end lemma surj_on_of_inj_on_of_card_le {s : finset α} {t : finset β} (f : Π a ∈ s, β) (hf : ∀ a ha, f a ha ∈ t) (hinj : ∀ a₁ a₂ ha₁ ha₂, f a₁ ha₁ = f a₂ ha₂ → a₁ = a₂) (hst : card t ≤ card s) : (∀ b ∈ t, ∃ a ha, b = f a ha) := by haveI := classical.dec_eq β; exact λ b hb, have h : card (image (λ (a : {a // a ∈ s}), f a a.prop) (attach s)) = card s, from @card_attach _ s ▸ card_image_of_injective _ (λ ⟨a₁, ha₁⟩ ⟨a₂, ha₂⟩ h, subtype.eq $ hinj _ _ _ _ h), have h₁ : image (λ a : {a // a ∈ s}, f a a.prop) s.attach = t := eq_of_subset_of_card_le (λ b h, let ⟨a, ha₁, ha₂⟩ := mem_image.1 h in ha₂ ▸ hf _ _) (by simp [hst, h]), begin rw ← h₁ at hb, rcases mem_image.1 hb with ⟨a, ha₁, ha₂⟩, exact ⟨a, a.2, ha₂.symm⟩, end open function lemma inj_on_of_surj_on_of_card_le {s : finset α} {t : finset β} (f : Π a ∈ s, β) (hf : ∀ a ha, f a ha ∈ t) (hsurj : ∀ b ∈ t, ∃ a ha, b = f a ha) (hst : card s ≤ card t) ⦃a₁ a₂⦄ (ha₁ : a₁ ∈ s) (ha₂ : a₂ ∈ s) (ha₁a₂: f a₁ ha₁ = f a₂ ha₂) : a₁ = a₂ := by haveI : inhabited {x // x ∈ s} := ⟨⟨a₁, ha₁⟩⟩; exact let f' : {x // x ∈ s} → {x // x ∈ t} := λ x, ⟨f x.1 x.2, hf x.1 x.2⟩ in let g : {x // x ∈ t} → {x // x ∈ s} := @surj_inv _ _ f' (λ x, let ⟨y, hy₁, hy₂⟩ := hsurj x.1 x.2 in ⟨⟨y, hy₁⟩, subtype.eq hy₂.symm⟩) in have hg : injective g, from injective_surj_inv _, have hsg : surjective g, from λ x, let ⟨y, hy⟩ := surj_on_of_inj_on_of_card_le (λ (x : {x // x ∈ t}) (hx : x ∈ t.attach), g x) (λ x _, show (g x) ∈ s.attach, from mem_attach _ _) (λ x y _ _ hxy, hg hxy) (by simpa) x (mem_attach _ _) in ⟨y, hy.snd.symm⟩, have hif : injective f', from (left_inverse_of_surjective_of_right_inverse hsg (right_inverse_surj_inv _)).injective, subtype.ext_iff_val.1 (@hif ⟨a₁, ha₁⟩ ⟨a₂, ha₂⟩ (subtype.eq ha₁a₂)) end card /-! ### bind -/ section bind variables [decidable_eq β] {s : finset α} {t : α → finset β} /-- `bind s t` is the union of `t x` over `x ∈ s` -/ protected def bind (s : finset α) (t : α → finset β) : finset β := (s.1.bind (λ a, (t a).1)).to_finset @[simp] theorem bind_val (s : finset α) (t : α → finset β) : (s.bind t).1 = (s.1.bind (λ a, (t a).1)).erase_dup := rfl @[simp] theorem bind_empty : finset.bind ∅ t = ∅ := rfl @[simp] theorem mem_bind {b : β} : b ∈ s.bind t ↔ ∃a∈s, b ∈ t a := by simp only [mem_def, bind_val, mem_erase_dup, mem_bind, exists_prop] @[simp] theorem bind_insert [decidable_eq α] {a : α} : (insert a s).bind t = t a ∪ s.bind t := ext $ λ x, by simp only [mem_bind, exists_prop, mem_union, mem_insert, or_and_distrib_right, exists_or_distrib, exists_eq_left] -- ext $ λ x, by simp [or_and_distrib_right, exists_or_distrib] @[simp] lemma singleton_bind {a : α} : finset.bind {a} t = t a := begin classical, rw [← insert_emptyc_eq, bind_insert, bind_empty, union_empty] end theorem bind_inter (s : finset α) (f : α → finset β) (t : finset β) : s.bind f ∩ t = s.bind (λ x, f x ∩ t) := begin ext x, simp only [mem_bind, mem_inter], tauto end theorem inter_bind (t : finset β) (s : finset α) (f : α → finset β) : t ∩ s.bind f = s.bind (λ x, t ∩ f x) := by rw [inter_comm, bind_inter]; simp [inter_comm] theorem image_bind [decidable_eq γ] {f : α → β} {s : finset α} {t : β → finset γ} : (s.image f).bind t = s.bind (λa, t (f a)) := by haveI := classical.dec_eq α; exact finset.induction_on s rfl (λ a s has ih, by simp only [image_insert, bind_insert, ih]) theorem bind_image [decidable_eq γ] {s : finset α} {t : α → finset β} {f : β → γ} : (s.bind t).image f = s.bind (λa, (t a).image f) := by haveI := classical.dec_eq α; exact finset.induction_on s rfl (λ a s has ih, by simp only [bind_insert, image_union, ih]) theorem bind_to_finset [decidable_eq α] (s : multiset α) (t : α → multiset β) : (s.bind t).to_finset = s.to_finset.bind (λa, (t a).to_finset) := ext $ λ x, by simp only [multiset.mem_to_finset, mem_bind, multiset.mem_bind, exists_prop] lemma bind_mono {t₁ t₂ : α → finset β} (h : ∀a∈s, t₁ a ⊆ t₂ a) : s.bind t₁ ⊆ s.bind t₂ := have ∀b a, a ∈ s → b ∈ t₁ a → (∃ (a : α), a ∈ s ∧ b ∈ t₂ a), from assume b a ha hb, ⟨a, ha, finset.mem_of_subset (h a ha) hb⟩, by simpa only [subset_iff, mem_bind, exists_imp_distrib, and_imp, exists_prop] lemma bind_subset_bind_of_subset_left {α : Type*} {s₁ s₂ : finset α} (t : α → finset β) (h : s₁ ⊆ s₂) : s₁.bind t ⊆ s₂.bind t := begin intro x, simp only [and_imp, mem_bind, exists_prop], exact Exists.imp (λ a ha, ⟨h ha.1, ha.2⟩) end lemma bind_singleton {f : α → β} : s.bind (λa, {f a}) = s.image f := ext $ λ x, by simp only [mem_bind, mem_image, mem_singleton, eq_comm] @[simp] lemma bind_singleton_eq_self [decidable_eq α] : s.bind (singleton : α → finset α) = s := by { rw bind_singleton, exact image_id } lemma bind_filter_eq_of_maps_to [decidable_eq α] {s : finset α} {t : finset β} {f : α → β} (h : ∀ x ∈ s, f x ∈ t) : t.bind (λa, s.filter $ (λc, f c = a)) = s := begin ext b, suffices : (∃ a ∈ t, b ∈ s ∧ f b = a) ↔ b ∈ s, by simpa, exact ⟨λ ⟨a, ha, hb, hab⟩, hb, λ hb, ⟨f b, h b hb, hb, rfl⟩⟩ end lemma image_bind_filter_eq [decidable_eq α] (s : finset β) (g : β → α) : (s.image g).bind (λa, s.filter $ (λc, g c = a)) = s := bind_filter_eq_of_maps_to (λ x, mem_image_of_mem g) end bind /-! ### prod -/ section prod variables {s : finset α} {t : finset β} /-- `product s t` is the set of pairs `(a, b)` such that `a ∈ s` and `b ∈ t`. -/ protected def product (s : finset α) (t : finset β) : finset (α × β) := ⟨_, nodup_product s.2 t.2⟩ @[simp] theorem product_val : (s.product t).1 = s.1.product t.1 := rfl @[simp] theorem mem_product {p : α × β} : p ∈ s.product t ↔ p.1 ∈ s ∧ p.2 ∈ t := mem_product theorem subset_product [decidable_eq α] [decidable_eq β] {s : finset (α × β)} : s ⊆ (s.image prod.fst).product (s.image prod.snd) := λ p hp, mem_product.2 ⟨mem_image_of_mem _ hp, mem_image_of_mem _ hp⟩ theorem product_eq_bind [decidable_eq α] [decidable_eq β] (s : finset α) (t : finset β) : s.product t = s.bind (λa, t.image $ λb, (a, b)) := ext $ λ ⟨x, y⟩, by simp only [mem_product, mem_bind, mem_image, exists_prop, prod.mk.inj_iff, and.left_comm, exists_and_distrib_left, exists_eq_right, exists_eq_left] @[simp] theorem card_product (s : finset α) (t : finset β) : card (s.product t) = card s * card t := multiset.card_product _ _ theorem filter_product (p : α → Prop) (q : β → Prop) [decidable_pred p] [decidable_pred q] : (s.product t).filter (λ (x : α × β), p x.1 ∧ q x.2) = (s.filter p).product (t.filter q) := by { ext ⟨a, b⟩, simp only [mem_filter, mem_product], finish, } lemma filter_product_card (s : finset α) (t : finset β) (p : α → Prop) (q : β → Prop) [decidable_pred p] [decidable_pred q] : ((s.product t).filter (λ (x : α × β), p x.1 ↔ q x.2)).card = (s.filter p).card * (t.filter q).card + (s.filter (not ∘ p)).card * (t.filter (not ∘ q)).card := begin classical, rw [← card_product, ← card_product, ← filter_product, ← filter_product, ← card_union_eq], { apply congr_arg, ext ⟨a, b⟩, simp only [filter_union_right, mem_filter, mem_product], split; intros; finish, }, { rw disjoint_iff, change _ ∩ _ = ∅, ext ⟨a, b⟩, rw mem_inter, finish, }, end end prod /-! ### sigma -/ section sigma variables {σ : α → Type*} {s : finset α} {t : Πa, finset (σ a)} /-- `sigma s t` is the set of dependent pairs `⟨a, b⟩` such that `a ∈ s` and `b ∈ t a`. -/ protected def sigma (s : finset α) (t : Πa, finset (σ a)) : finset (Σa, σ a) := ⟨_, nodup_sigma s.2 (λ a, (t a).2)⟩ @[simp] theorem mem_sigma {p : sigma σ} : p ∈ s.sigma t ↔ p.1 ∈ s ∧ p.2 ∈ t (p.1) := mem_sigma theorem sigma_mono {s₁ s₂ : finset α} {t₁ t₂ : Πa, finset (σ a)} (H1 : s₁ ⊆ s₂) (H2 : ∀a, t₁ a ⊆ t₂ a) : s₁.sigma t₁ ⊆ s₂.sigma t₂ := λ ⟨x, sx⟩ H, let ⟨H3, H4⟩ := mem_sigma.1 H in mem_sigma.2 ⟨H1 H3, H2 x H4⟩ theorem sigma_eq_bind [decidable_eq (Σ a, σ a)] (s : finset α) (t : Πa, finset (σ a)) : s.sigma t = s.bind (λa, (t a).map $ embedding.sigma_mk a) := by { ext ⟨x, y⟩, simp [and.left_comm] } end sigma /-! ### disjoint -/ section disjoint variable [decidable_eq α] theorem disjoint_left {s t : finset α} : disjoint s t ↔ ∀ {a}, a ∈ s → a ∉ t := by simp only [_root_.disjoint, inf_eq_inter, le_iff_subset, subset_iff, mem_inter, not_and, and_imp]; refl theorem disjoint_val {s t : finset α} : disjoint s t ↔ s.1.disjoint t.1 := disjoint_left theorem disjoint_iff_inter_eq_empty {s t : finset α} : disjoint s t ↔ s ∩ t = ∅ := disjoint_iff instance decidable_disjoint (U V : finset α) : decidable (disjoint U V) := decidable_of_decidable_of_iff (by apply_instance) eq_bot_iff theorem disjoint_right {s t : finset α} : disjoint s t ↔ ∀ {a}, a ∈ t → a ∉ s := by rw [disjoint.comm, disjoint_left] theorem disjoint_iff_ne {s t : finset α} : disjoint s t ↔ ∀ a ∈ s, ∀ b ∈ t, a ≠ b := by simp only [disjoint_left, imp_not_comm, forall_eq'] theorem disjoint_of_subset_left {s t u : finset α} (h : s ⊆ u) (d : disjoint u t) : disjoint s t := disjoint_left.2 (λ x m₁, (disjoint_left.1 d) (h m₁)) theorem disjoint_of_subset_right {s t u : finset α} (h : t ⊆ u) (d : disjoint s u) : disjoint s t := disjoint_right.2 (λ x m₁, (disjoint_right.1 d) (h m₁)) @[simp] theorem disjoint_empty_left (s : finset α) : disjoint ∅ s := disjoint_bot_left @[simp] theorem disjoint_empty_right (s : finset α) : disjoint s ∅ := disjoint_bot_right @[simp] theorem singleton_disjoint {s : finset α} {a : α} : disjoint (singleton a) s ↔ a ∉ s := by simp only [disjoint_left, mem_singleton, forall_eq] @[simp] theorem disjoint_singleton {s : finset α} {a : α} : disjoint s (singleton a) ↔ a ∉ s := disjoint.comm.trans singleton_disjoint @[simp] theorem disjoint_insert_left {a : α} {s t : finset α} : disjoint (insert a s) t ↔ a ∉ t ∧ disjoint s t := by simp only [disjoint_left, mem_insert, or_imp_distrib, forall_and_distrib, forall_eq] @[simp] theorem disjoint_insert_right {a : α} {s t : finset α} : disjoint s (insert a t) ↔ a ∉ s ∧ disjoint s t := disjoint.comm.trans $ by rw [disjoint_insert_left, disjoint.comm] @[simp] theorem disjoint_union_left {s t u : finset α} : disjoint (s ∪ t) u ↔ disjoint s u ∧ disjoint t u := by simp only [disjoint_left, mem_union, or_imp_distrib, forall_and_distrib] @[simp] theorem disjoint_union_right {s t u : finset α} : disjoint s (t ∪ u) ↔ disjoint s t ∧ disjoint s u := by simp only [disjoint_right, mem_union, or_imp_distrib, forall_and_distrib] lemma sdiff_disjoint {s t : finset α} : disjoint (t \ s) s := disjoint_left.2 $ assume a ha, (mem_sdiff.1 ha).2 lemma disjoint_sdiff {s t : finset α} : disjoint s (t \ s) := sdiff_disjoint.symm lemma disjoint_sdiff_inter (s t : finset α) : disjoint (s \ t) (s ∩ t) := disjoint_of_subset_right (inter_subset_right _ _) sdiff_disjoint lemma sdiff_eq_self_iff_disjoint {s t : finset α} : s \ t = s ↔ disjoint s t := by rw [sdiff_eq_self, subset_empty, disjoint_iff_inter_eq_empty] lemma sdiff_eq_self_of_disjoint {s t : finset α} (h : disjoint s t) : s \ t = s := sdiff_eq_self_iff_disjoint.2 h lemma disjoint_self_iff_empty (s : finset α) : disjoint s s ↔ s = ∅ := disjoint_self lemma disjoint_bind_left {ι : Type*} (s : finset ι) (f : ι → finset α) (t : finset α) : disjoint (s.bind f) t ↔ (∀i∈s, disjoint (f i) t) := begin classical, refine s.induction _ _, { simp only [forall_mem_empty_iff, bind_empty, disjoint_empty_left] }, { assume i s his ih, simp only [disjoint_union_left, bind_insert, his, forall_mem_insert, ih] } end lemma disjoint_bind_right {ι : Type*} (s : finset α) (t : finset ι) (f : ι → finset α) : disjoint s (t.bind f) ↔ (∀i∈t, disjoint s (f i)) := by simpa only [disjoint.comm] using disjoint_bind_left t f s @[simp] theorem card_disjoint_union {s t : finset α} (h : disjoint s t) : card (s ∪ t) = card s + card t := by rw [← card_union_add_card_inter, disjoint_iff_inter_eq_empty.1 h, card_empty, add_zero] theorem card_sdiff {s t : finset α} (h : s ⊆ t) : card (t \ s) = card t - card s := suffices card (t \ s) = card ((t \ s) ∪ s) - card s, by rwa sdiff_union_of_subset h at this, by rw [card_disjoint_union sdiff_disjoint, nat.add_sub_cancel] lemma disjoint_filter {s : finset α} {p q : α → Prop} [decidable_pred p] [decidable_pred q] : disjoint (s.filter p) (s.filter q) ↔ (∀ x ∈ s, p x → ¬ q x) := by split; simp [disjoint_left] {contextual := tt} lemma disjoint_filter_filter {s t : finset α} {p q : α → Prop} [decidable_pred p] [decidable_pred q] : (disjoint s t) → disjoint (s.filter p) (t.filter q) := disjoint.mono (filter_subset _ _) (filter_subset _ _) lemma disjoint_iff_disjoint_coe {α : Type*} {a b : finset α} [decidable_eq α] : disjoint a b ↔ disjoint (↑a : set α) (↑b : set α) := by { rw [finset.disjoint_left, set.disjoint_left], refl } lemma filter_card_add_filter_neg_card_eq_card {α : Type*} {s : finset α} (p : α → Prop) [decidable_pred p] : (s.filter p).card + (s.filter (not ∘ p)).card = s.card := by { classical, simp [← card_union_eq, filter_union_filter_neg_eq, disjoint_filter], } end disjoint section self_prod variables (s : finset α) [decidable_eq α] /-- Given a finite set `s`, the diagonal, `s.diag` is the set of pairs of the form `(a, a)` for `a ∈ s`. -/ def diag := (s.product s).filter (λ (a : α × α), a.fst = a.snd) /-- Given a finite set `s`, the off-diagonal, `s.off_diag` is the set of pairs `(a, b)` with `a ≠ b` for `a, b ∈ s`. -/ def off_diag := (s.product s).filter (λ (a : α × α), a.fst ≠ a.snd) @[simp] lemma mem_diag (x : α × α) : x ∈ s.diag ↔ x.1 ∈ s ∧ x.1 = x.2 := by { simp only [diag, mem_filter, mem_product], split; intros; finish, } @[simp] lemma mem_off_diag (x : α × α) : x ∈ s.off_diag ↔ x.1 ∈ s ∧ x.2 ∈ s ∧ x.1 ≠ x.2 := by { simp only [off_diag, mem_filter, mem_product], split; intros; finish, } @[simp] lemma diag_card : (diag s).card = s.card := begin suffices : diag s = s.image (λ a, (a, a)), { rw this, apply card_image_of_inj_on, finish, }, ext ⟨a₁, a₂⟩, rw mem_diag, split; intros; finish, end @[simp] lemma off_diag_card : (off_diag s).card = s.card * s.card - s.card := begin suffices : (diag s).card + (off_diag s).card = s.card * s.card, { nth_rewrite 2 ← s.diag_card, finish, }, rw ← card_product, apply filter_card_add_filter_neg_card_eq_card, end end self_prod /-- Given a set A and a set B inside it, we can shrink A to any appropriate size, and keep B inside it. -/ lemma exists_intermediate_set {A B : finset α} (i : ℕ) (h₁ : i + card B ≤ card A) (h₂ : B ⊆ A) : ∃ (C : finset α), B ⊆ C ∧ C ⊆ A ∧ card C = i + card B := begin classical, rcases nat.le.dest h₁ with ⟨k, _⟩, clear h₁, induction k with k ih generalizing A, { exact ⟨A, h₂, subset.refl _, h.symm⟩ }, { have : (A \ B).nonempty, { rw [← card_pos, card_sdiff h₂, ← h, nat.add_right_comm, nat.add_sub_cancel, nat.add_succ], apply nat.succ_pos }, rcases this with ⟨a, ha⟩, have z : i + card B + k = card (erase A a), { rw [card_erase_of_mem, ← h, nat.add_succ, nat.pred_succ], rw mem_sdiff at ha, exact ha.1 }, rcases ih _ z with ⟨B', hB', B'subA', cards⟩, { exact ⟨B', hB', trans B'subA' (erase_subset _ _), cards⟩ }, { rintros t th, apply mem_erase_of_ne_of_mem _ (h₂ th), rintro rfl, exact not_mem_sdiff_of_mem_right th ha } } end /-- We can shrink A to any smaller size. -/ lemma exists_smaller_set (A : finset α) (i : ℕ) (h₁ : i ≤ card A) : ∃ (B : finset α), B ⊆ A ∧ card B = i := let ⟨B, _, x₁, x₂⟩ := exists_intermediate_set i (by simpa) (empty_subset A) in ⟨B, x₁, x₂⟩ /-- `finset.fin_range k` is the finset `{0, 1, ..., k-1}`, as a `finset (fin k)`. -/ def fin_range (k : ℕ) : finset (fin k) := ⟨list.fin_range k, list.nodup_fin_range k⟩ @[simp] lemma fin_range_card {k : ℕ} : (fin_range k).card = k := by simp [fin_range] @[simp] lemma mem_fin_range {k : ℕ} (m : fin k) : m ∈ fin_range k := list.mem_fin_range m @[simp] lemma coe_fin_range (k : ℕ) : (fin_range k : set (fin k)) = set.univ := set.eq_univ_of_forall mem_fin_range /-- Given a finset `s` of `ℕ` contained in `{0,..., n-1}`, the corresponding finset in `fin n` is `s.attach_fin h` where `h` is a proof that all elements of `s` are less than `n`. -/ def attach_fin (s : finset ℕ) {n : ℕ} (h : ∀ m ∈ s, m < n) : finset (fin n) := ⟨s.1.pmap (λ a ha, ⟨a, ha⟩) h, multiset.nodup_pmap (λ _ _ _ _, fin.veq_of_eq) s.2⟩ @[simp] lemma mem_attach_fin {n : ℕ} {s : finset ℕ} (h : ∀ m ∈ s, m < n) {a : fin n} : a ∈ s.attach_fin h ↔ (a : ℕ) ∈ s := ⟨λ h, let ⟨b, hb₁, hb₂⟩ := multiset.mem_pmap.1 h in hb₂ ▸ hb₁, λ h, multiset.mem_pmap.2 ⟨a, h, fin.eta _ _⟩⟩ @[simp] lemma card_attach_fin {n : ℕ} (s : finset ℕ) (h : ∀ m ∈ s, m < n) : (s.attach_fin h).card = s.card := multiset.card_pmap _ _ _ /-! ### choose -/ section choose variables (p : α → Prop) [decidable_pred p] (l : finset α) /-- Given a finset `l` and a predicate `p`, associate to a proof that there is a unique element of `l` satisfying `p` this unique element, as an element of the corresponding subtype. -/ def choose_x (hp : (∃! a, a ∈ l ∧ p a)) : { a // a ∈ l ∧ p a } := multiset.choose_x p l.val hp /-- Given a finset `l` and a predicate `p`, associate to a proof that there is a unique element of `l` satisfying `p` this unique element, as an element of the ambient type. -/ def choose (hp : ∃! a, a ∈ l ∧ p a) : α := choose_x p l hp lemma choose_spec (hp : ∃! a, a ∈ l ∧ p a) : choose p l hp ∈ l ∧ p (choose p l hp) := (choose_x p l hp).property lemma choose_mem (hp : ∃! a, a ∈ l ∧ p a) : choose p l hp ∈ l := (choose_spec _ _ _).1 lemma choose_property (hp : ∃! a, a ∈ l ∧ p a) : p (choose p l hp) := (choose_spec _ _ _).2 end choose theorem lt_wf {α} : well_founded (@has_lt.lt (finset α) _) := have H : subrelation (@has_lt.lt (finset α) _) (inv_image (<) card), from λ x y hxy, card_lt_card hxy, subrelation.wf H $ inv_image.wf _ $ nat.lt_wf end finset namespace equiv /-- Given an equivalence `α` to `β`, produce an equivalence between `finset α` and `finset β`. -/ protected def finset_congr (e : α ≃ β) : finset α ≃ finset β := { to_fun := λ s, s.map e.to_embedding, inv_fun := λ s, s.map e.symm.to_embedding, left_inv := λ s, by simp [finset.map_map], right_inv := λ s, by simp [finset.map_map] } @[simp] lemma finset_congr_apply (e : α ≃ β) (s : finset α) : e.finset_congr s = s.map e.to_embedding := rfl @[simp] lemma finset_congr_symm_apply (e : α ≃ β) (s : finset β) : e.finset_congr.symm s = s.map e.symm.to_embedding := rfl end equiv namespace list variable [decidable_eq α] theorem to_finset_card_of_nodup {l : list α} (h : l.nodup) : l.to_finset.card = l.length := congr_arg card $ (@multiset.erase_dup_eq_self α _ l).2 h end list namespace multiset variable [decidable_eq α] theorem to_finset_card_of_nodup {l : multiset α} (h : l.nodup) : l.to_finset.card = l.card := congr_arg card $ (@multiset.erase_dup_eq_self α _ l).2 h lemma disjoint_to_finset (m1 m2 : multiset α) : _root_.disjoint m1.to_finset m2.to_finset ↔ m1.disjoint m2 := begin rw finset.disjoint_iff_ne, split, { intro h, intros a ha1 ha2, rw ← multiset.mem_to_finset at ha1 ha2, exact h _ ha1 _ ha2 rfl }, { rintros h a ha b hb rfl, rw multiset.mem_to_finset at ha hb, exact h ha hb } end end multiset
190073d884f3f214197a855e5dc8896b07273cda
a45212b1526d532e6e83c44ddca6a05795113ddc
/src/category/functor.lean
703386168e6ce9fcce8e5a6892e0b74a1ec14dc9
[ "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
4,263
lean
/- Copyright (c) 2017 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Simon Hudon Standard identity and composition functors -/ import tactic.ext tactic.cache category.basic universe variables u v w section functor variables {F : Type u → Type v} variables {α β γ : Type u} variables [functor F] [is_lawful_functor F] lemma functor.map_id : (<$>) id = (id : F α → F α) := by apply funext; apply id_map lemma functor.map_comp_map (f : α → β) (g : β → γ) : ((<$>) g ∘ (<$>) f : F α → F γ) = (<$>) (g ∘ f) := by apply funext; intro; rw comp_map theorem functor.ext {F} : ∀ {F1 : functor F} {F2 : functor F} [@is_lawful_functor F F1] [@is_lawful_functor F F2] (H : ∀ α β (f : α → β) (x : F α), @functor.map _ F1 _ _ f x = @functor.map _ F2 _ _ f x), F1 = F2 | ⟨m, mc⟩ ⟨m', mc'⟩ H1 H2 H := begin cases show @m = @m', by funext α β f x; apply H, congr, funext α β, have E1 := @map_const_eq _ ⟨@m, @mc⟩ H1, have E2 := @map_const_eq _ ⟨@m, @mc'⟩ H2, exact E1.trans E2.symm end end functor def id.mk {α : Sort u} : α → id α := id namespace functor def const (α : Type*) (β : Type*) := α @[pattern] def const.mk {α β} (x : α) : const α β := x def const.mk' {α} (x : α) : const α punit := x def const.run {α β} (x : const α β) : α := x namespace const protected lemma ext {α β} {x y : const α β} (h : x.run = y.run) : x = y := h protected def map {γ α β} (f : α → β) (x : const γ β) : const γ α := x instance {γ} : functor (const γ) := { map := @const.map γ } instance {γ} : is_lawful_functor (const γ) := by constructor; intros; refl end const def add_const (α : Type*) := const α @[pattern] def add_const.mk {α β} (x : α) : add_const α β := x def add_const.run {α β} : add_const α β → α := id instance add_const.functor {γ} : functor (add_const γ) := @const.functor γ instance add_const.is_lawful_functor {γ} : is_lawful_functor (add_const γ) := @const.is_lawful_functor γ /-- `functor.comp` is a wrapper around `function.comp` for types. It prevents Lean's type class resolution mechanism from trying a `functor (comp F id)` when `functor F` would do. -/ def comp (F : Type u → Type w) (G : Type v → Type u) (α : Type v) : Type w := F $ G α @[pattern] def comp.mk {F : Type u → Type w} {G : Type v → Type u} {α : Type v} (x : F (G α)) : comp F G α := x def comp.run {F : Type u → Type w} {G : Type v → Type u} {α : Type v} (x : comp F G α) : F (G α) := x namespace comp variables {F : Type u → Type w} {G : Type v → Type u} protected lemma ext {α} {x y : comp F G α} : x.run = y.run → x = y := id variables [functor F] [functor G] protected def map {α β : Type v} (h : α → β) : comp F G α → comp F G β | (comp.mk x) := comp.mk ((<$>) h <$> x) instance : functor (comp F G) := { map := @comp.map F G _ _ } @[functor_norm] lemma map_mk {α β} (h : α → β) (x : F (G α)) : h <$> comp.mk x = comp.mk ((<$>) h <$> x) := rfl variables [is_lawful_functor F] [is_lawful_functor G] variables {α β γ : Type v} protected lemma id_map : ∀ (x : comp F G α), comp.map id x = x | (comp.mk x) := by simp [comp.map, functor.map_id] protected lemma comp_map (g' : α → β) (h : β → γ) : ∀ (x : comp F G α), comp.map (h ∘ g') x = comp.map h (comp.map g' x) | (comp.mk x) := by simp [comp.map, functor.map_comp_map g' h] with functor_norm @[simp] protected lemma run_map (h : α → β) (x : comp F G α) : (h <$> x).run = (<$>) h <$> x.run := rfl instance : is_lawful_functor (comp F G) := { id_map := @comp.id_map F G _ _ _ _, comp_map := @comp.comp_map F G _ _ _ _ } theorem functor_comp_id {F} [AF : functor F] [is_lawful_functor F] : @comp.functor F id _ _ = AF := @functor.ext F _ AF (@comp.is_lawful_functor F id _ _ _ _) _ (λ α β f x, rfl) theorem functor_id_comp {F} [AF : functor F] [is_lawful_functor F] : @comp.functor id F _ _ = AF := @functor.ext F _ AF (@comp.is_lawful_functor id F _ _ _ _) _ (λ α β f x, rfl) end comp end functor namespace ulift instance : functor ulift := { map := λ α β f, up ∘ f ∘ down } end ulift
a3285c223c8f317fd254e2d3829232defaf3ca5e
60bf3fa4185ec5075eaea4384181bfbc7e1dc319
/src/game/order/level08.lean
a7f06e73f8c3efe9ab8282f238c433f836a0f01f
[ "Apache-2.0" ]
permissive
anrddh/real-number-game
660f1127d03a78fd35986c771d65c3132c5f4025
c708c4e02ec306c657e1ea67862177490db041b0
refs/heads/master
1,668,214,277,092
1,593,105,075,000
1,593,105,075,000
264,269,218
0
0
null
1,589,567,264,000
1,589,567,264,000
null
UTF-8
Lean
false
false
875
lean
import data.real.basic import data.real.irrational open real namespace xena -- hide /- # Chapter 2 : Order ## Level 8 Prove by example that there exist pairs of real numbers $a$ and $b$ such that $a \in \mathbb{R} \setminus \mathbb{Q}$, $b \in \mathbb{R} \setminus \mathbb{Q}$, but their product $a \cdot b$ is a rational number, $(a \cdot b) \in \mathbb{Q}$. You may use this result in the Lean mathlib library: `irrational_sqrt_two : irrational (sqrt 2) -/ /- Lemma Not true that for any $a$, $b$, irrational numbers, the product is also an irrational number. -/ theorem not_prod_irrational : ¬ ( ∀ (a b : ℝ), irrational a → irrational b → irrational (a*b) ) := begin intro H, have H2 := H (sqrt 2) (sqrt 2), have H3 := H2 irrational_sqrt_two irrational_sqrt_two, apply H3, existsi (2 : ℚ), simp, norm_num, done end end xena -- hide
992812f2b36274098ad2e6d3a5195dade01f23df
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/algebra/category/Group/basic.lean
55f7e8e85dd6fb67dcc6944fdab277878908c059
[]
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
10,512
lean
/- Copyright (c) 2018 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.algebra.category.Mon.basic import Mathlib.category_theory.endomorphism import Mathlib.PostPort universes u u_1 namespace Mathlib /-! # Category instances for group, add_group, comm_group, and add_comm_group. We introduce the bundled categories: * `Group` * `AddGroup` * `CommGroup` * `AddCommGroup` along with the relevant forgetful functors between them, and to the bundled monoid categories. -/ /-- The category of groups and group morphisms. -/ def AddGroup := category_theory.bundled add_group /-- The category of additive groups and group morphisms -/ namespace Group protected instance Mathlib.AddGroup.group.to_monoid.category_theory.bundled_hom.parent_projection : category_theory.bundled_hom.parent_projection add_group.to_add_monoid := category_theory.bundled_hom.parent_projection.mk protected instance has_coe_to_sort : has_coe_to_sort Group := category_theory.bundled.has_coe_to_sort /-- Construct a bundled `Group` from the underlying type and typeclass. -/ def of (X : Type u) [group X] : Group := category_theory.bundled.of X /-- Construct a bundled `AddGroup` from the underlying type and typeclass. -/ protected instance group (G : Group) : group ↥G := category_theory.bundled.str G @[simp] theorem coe_of (R : Type u) [group R] : ↥(of R) = R := rfl protected instance Mathlib.AddGroup.has_zero : HasZero AddGroup := { zero := AddGroup.of PUnit } protected instance inhabited : Inhabited Group := { default := 1 } protected instance one.unique : unique ↥1 := unique.mk { default := 1 } sorry @[simp] theorem one_apply (G : Group) (H : Group) (g : ↥G) : coe_fn 1 g = 1 := rfl theorem ext (G : Group) (H : Group) (f₁ : G ⟶ H) (f₂ : G ⟶ H) (w : ∀ (x : ↥G), coe_fn f₁ x = coe_fn f₂ x) : f₁ = f₂ := monoid_hom.ext fun (x : ↥G) => w x -- should to_additive do this automatically? protected instance Mathlib.AddGroup.has_forget_to_AddMon : category_theory.has_forget₂ AddGroup AddMon := category_theory.bundled_hom.forget₂ add_monoid_hom add_group.to_add_monoid end Group /-- The category of commutative groups and group morphisms. -/ def AddCommGroup := category_theory.bundled add_comm_group /-- The category of additive commutative groups and group morphisms. -/ /-- `Ab` is an abbreviation for `AddCommGroup`, for the sake of mathematicians' sanity. -/ def Ab := AddCommGroup namespace CommGroup protected instance comm_group.to_group.category_theory.bundled_hom.parent_projection : category_theory.bundled_hom.parent_projection comm_group.to_group := category_theory.bundled_hom.parent_projection.mk protected instance large_category : category_theory.large_category CommGroup := category_theory.bundled_hom.category (category_theory.bundled_hom.map_hom (category_theory.bundled_hom.map_hom monoid_hom group.to_monoid) comm_group.to_group) /-- Construct a bundled `CommGroup` from the underlying type and typeclass. -/ def of (G : Type u) [comm_group G] : CommGroup := category_theory.bundled.of G /-- Construct a bundled `AddCommGroup` from the underlying type and typeclass. -/ protected instance Mathlib.AddCommGroup.add_comm_group_instance (G : AddCommGroup) : add_comm_group ↥G := category_theory.bundled.str G @[simp] theorem coe_of (R : Type u) [comm_group R] : ↥(of R) = R := rfl protected instance Mathlib.AddCommGroup.has_zero : HasZero AddCommGroup := { zero := AddCommGroup.of PUnit } protected instance inhabited : Inhabited CommGroup := { default := 1 } protected instance one.unique : unique ↥1 := unique.mk { default := 1 } sorry @[simp] theorem one_apply (G : CommGroup) (H : CommGroup) (g : ↥G) : coe_fn 1 g = 1 := rfl theorem ext (G : CommGroup) (H : CommGroup) (f₁ : G ⟶ H) (f₂ : G ⟶ H) (w : ∀ (x : ↥G), coe_fn f₁ x = coe_fn f₂ x) : f₁ = f₂ := monoid_hom.ext fun (x : ↥G) => w x protected instance Mathlib.AddCommGroup.has_forget_to_AddGroup : category_theory.has_forget₂ AddCommGroup AddGroup := category_theory.bundled_hom.forget₂ (category_theory.bundled_hom.map_hom add_monoid_hom add_group.to_add_monoid) add_comm_group.to_add_group protected instance Mathlib.AddCommGroup.has_forget_to_AddCommMon : category_theory.has_forget₂ AddCommGroup AddCommMon := category_theory.induced_category.has_forget₂ fun (G : AddCommGroup) => AddCommMon.of ↥G end CommGroup -- This example verifies an improvement possible in Lean 3.8. -- Before that, to have `monoid_hom.map_map` usable by `simp` here, -- we had to mark all the concrete category `has_coe_to_sort` instances reducible. -- Now, it just works. namespace AddCommGroup /-- Any element of an abelian group gives a unique morphism from `ℤ` sending `1` to that element. -/ -- Note that because `ℤ : Type 0`, this forces `G : AddCommGroup.{0}`, -- so we write this explicitly to be clear. -- TODO generalize this, requiring a `ulift_instances.lean` file def as_hom {G : AddCommGroup} (g : ↥G) : of ℤ ⟶ G := coe_fn (gmultiples_hom ↥G) g @[simp] theorem as_hom_apply {G : AddCommGroup} (g : ↥G) (i : ℤ) : coe_fn (as_hom g) i = i • g := rfl theorem as_hom_injective {G : AddCommGroup} : function.injective as_hom := sorry theorem int_hom_ext {G : AddCommGroup} (f : of ℤ ⟶ G) (g : of ℤ ⟶ G) (w : coe_fn f 1 = coe_fn g 1) : f = g := add_monoid_hom.ext_int w -- TODO: this argument should be generalised to the situation where -- the forgetful functor is representable. theorem injective_of_mono {G : AddCommGroup} {H : AddCommGroup} (f : G ⟶ H) [category_theory.mono f] : function.injective ⇑f := sorry end AddCommGroup /-- Build an isomorphism in the category `Group` from a `mul_equiv` between `group`s. -/ def mul_equiv.to_Group_iso {X : Type u} {Y : Type u} [group X] [group Y] (e : X ≃* Y) : Group.of X ≅ Group.of Y := category_theory.iso.mk (mul_equiv.to_monoid_hom e) (mul_equiv.to_monoid_hom (mul_equiv.symm e)) /-- Build an isomorphism in the category `AddGroup` from an `add_equiv` between `add_group`s. -/ /-- Build an isomorphism in the category `CommGroup` from a `mul_equiv` between `comm_group`s. -/ def add_equiv.to_AddCommGroup_iso {X : Type u} {Y : Type u} [add_comm_group X] [add_comm_group Y] (e : X ≃+ Y) : AddCommGroup.of X ≅ AddCommGroup.of Y := category_theory.iso.mk (add_equiv.to_add_monoid_hom e) (add_equiv.to_add_monoid_hom (add_equiv.symm e)) /-- Build an isomorphism in the category `AddCommGroup` from a `add_equiv` between `add_comm_group`s. -/ namespace category_theory.iso /-- Build a `mul_equiv` from an isomorphism in the category `Group`. -/ @[simp] theorem Group_iso_to_add_equiv_apply {X : AddGroup} {Y : AddGroup} (i : X ≅ Y) : ∀ (ᾰ : ↥X), coe_fn (AddGroup_iso_to_add_equiv i) ᾰ = coe_fn (hom i) ᾰ := fun (ᾰ : ↥X) => Eq.refl (coe_fn (hom i) ᾰ) /-- Build a `mul_equiv` from an isomorphism in the category `CommGroup`. -/ @[simp] theorem CommGroup_iso_to_add_equiv_apply {X : AddCommGroup} {Y : AddCommGroup} (i : X ≅ Y) : ∀ (ᾰ : ↥X), coe_fn (AddCommGroup_iso_to_add_equiv i) ᾰ = coe_fn (hom i) ᾰ := fun (ᾰ : ↥X) => Eq.refl (coe_fn (hom i) ᾰ) end category_theory.iso /-- multiplicative equivalences between `group`s are the same as (isomorphic to) isomorphisms in `Group` -/ def add_equiv_iso_AddGroup_iso {X : Type u} {Y : Type u} [add_group X] [add_group Y] : X ≃+ Y ≅ AddGroup.of X ≅ AddGroup.of Y := category_theory.iso.mk (fun (e : X ≃+ Y) => add_equiv.to_AddGroup_iso e) fun (i : AddGroup.of X ≅ AddGroup.of Y) => category_theory.iso.AddGroup_iso_to_add_equiv i /-- multiplicative equivalences between `comm_group`s are the same as (isomorphic to) isomorphisms in `CommGroup` -/ def mul_equiv_iso_CommGroup_iso {X : Type u} {Y : Type u} [comm_group X] [comm_group Y] : X ≃* Y ≅ CommGroup.of X ≅ CommGroup.of Y := category_theory.iso.mk (fun (e : X ≃* Y) => mul_equiv.to_CommGroup_iso e) fun (i : CommGroup.of X ≅ CommGroup.of Y) => category_theory.iso.CommGroup_iso_to_mul_equiv i namespace category_theory.Aut /-- The (bundled) group of automorphisms of a type is isomorphic to the (bundled) group of permutations. -/ def iso_perm {α : Type u} : Group.of (Aut α) ≅ Group.of (equiv.perm α) := iso.mk (monoid_hom.mk (fun (g : ↥(Group.of (Aut α))) => iso.to_equiv g) sorry sorry) (monoid_hom.mk (fun (g : ↥(Group.of (equiv.perm α))) => equiv.to_iso g) sorry sorry) /-- The (unbundled) group of automorphisms of a type is `mul_equiv` to the (unbundled) group of permutations. -/ def mul_equiv_perm {α : Type u} : Aut α ≃* equiv.perm α := iso.Group_iso_to_mul_equiv iso_perm end category_theory.Aut protected instance Group.forget_reflects_isos : category_theory.reflects_isomorphisms (category_theory.forget Group) := category_theory.reflects_isomorphisms.mk fun (X Y : Group) (f : X ⟶ Y) (_x : category_theory.is_iso (category_theory.functor.map (category_theory.forget Group) f)) => let i : category_theory.functor.obj (category_theory.forget Group) X ≅ category_theory.functor.obj (category_theory.forget Group) Y := category_theory.as_iso (category_theory.functor.map (category_theory.forget Group) f); let e : ↥X ≃* ↥Y := mul_equiv.mk (monoid_hom.to_fun f) (equiv.inv_fun (category_theory.iso.to_equiv i)) sorry sorry sorry; category_theory.is_iso.mk (category_theory.iso.inv (mul_equiv.to_Group_iso e)) protected instance CommGroup.forget_reflects_isos : category_theory.reflects_isomorphisms (category_theory.forget CommGroup) := category_theory.reflects_isomorphisms.mk fun (X Y : CommGroup) (f : X ⟶ Y) (_x : category_theory.is_iso (category_theory.functor.map (category_theory.forget CommGroup) f)) => let i : category_theory.functor.obj (category_theory.forget CommGroup) X ≅ category_theory.functor.obj (category_theory.forget CommGroup) Y := category_theory.as_iso (category_theory.functor.map (category_theory.forget CommGroup) f); let e : ↥X ≃* ↥Y := mul_equiv.mk (monoid_hom.to_fun f) (equiv.inv_fun (category_theory.iso.to_equiv i)) sorry sorry sorry; category_theory.is_iso.mk (category_theory.iso.inv (mul_equiv.to_CommGroup_iso e))
90740bfc40266b9b4d1df1991634251a631afd0b
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/group_theory/perm/cycles_auto.lean
9775769cb2bd280d0be57a49e8fea47d60b0421f
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
8,248
lean
/- Copyright (c) 2019 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.group_theory.perm.sign import Mathlib.PostPort universes u_2 u_1 namespace Mathlib /-! # Cyclic permutations ## Main definitions In the following, `f : equiv.perm β`. * `equiv.perm.is_cycle`: `f.is_cycle` when two nonfixed points of `β` are related by repeated application of `f`. * `equiv.perm.same_cycle`: `f.same_cycle x y` when `x` and `y` are in the same cycle of `f`. The following two definitions require that `β` is a `fintype`: * `equiv.perm.cycle_of`: `f.cycle_of x` is the cycle of `f` that `x` belongs to. * `equiv.perm.cycle_factors`: `f.cycle_factors` is a list of disjoint cyclic permutations that multiply to `f`. -/ namespace equiv.perm /-! ### `is_cycle` -/ /-- A permutation is a cycle when any two nonfixed points of the permutation are related by repeated application of the permutation. -/ def is_cycle {β : Type u_2} (f : perm β) := ∃ (x : β), coe_fn f x ≠ x ∧ ∀ (y : β), coe_fn f y ≠ y → ∃ (i : ℤ), coe_fn (f ^ i) x = y theorem is_cycle.swap {α : Type u_1} [DecidableEq α] {x : α} {y : α} (hxy : x ≠ y) : is_cycle (swap x y) := sorry theorem is_cycle.inv {β : Type u_2} {f : perm β} (hf : is_cycle f) : is_cycle (f⁻¹) := sorry theorem is_cycle.exists_gpow_eq {β : Type u_2} {f : perm β} (hf : is_cycle f) {x : β} {y : β} (hx : coe_fn f x ≠ x) (hy : coe_fn f y ≠ y) : ∃ (i : ℤ), coe_fn (f ^ i) x = y := sorry theorem is_cycle.exists_pow_eq {β : Type u_2} [fintype β] {f : perm β} (hf : is_cycle f) {x : β} {y : β} (hx : coe_fn f x ≠ x) (hy : coe_fn f y ≠ y) : ∃ (i : ℕ), coe_fn (f ^ i) x = y := sorry theorem is_cycle_swap_mul_aux₁ {α : Type u_1} [DecidableEq α] (n : ℕ) {b : α} {x : α} {f : perm α} (hb : coe_fn (swap x (coe_fn f x) * f) b ≠ b) (h : coe_fn (f ^ n) (coe_fn f x) = b) : ∃ (i : ℤ), coe_fn ((swap x (coe_fn f x) * f) ^ i) (coe_fn f x) = b := sorry theorem is_cycle_swap_mul_aux₂ {α : Type u_1} [DecidableEq α] (n : ℤ) {b : α} {x : α} {f : perm α} (hb : coe_fn (swap x (coe_fn f x) * f) b ≠ b) (h : coe_fn (f ^ n) (coe_fn f x) = b) : ∃ (i : ℤ), coe_fn ((swap x (coe_fn f x) * f) ^ i) (coe_fn f x) = b := sorry theorem is_cycle.eq_swap_of_apply_apply_eq_self {α : Type u_1} [DecidableEq α] {f : perm α} (hf : is_cycle f) {x : α} (hfx : coe_fn f x ≠ x) (hffx : coe_fn f (coe_fn f x) = x) : f = swap x (coe_fn f x) := sorry theorem is_cycle.swap_mul {α : Type u_1} [DecidableEq α] {f : perm α} (hf : is_cycle f) {x : α} (hx : coe_fn f x ≠ x) (hffx : coe_fn f (coe_fn f x) ≠ x) : is_cycle (swap x (coe_fn f x) * f) := sorry theorem is_cycle.sign {α : Type u_1} [DecidableEq α] [fintype α] {f : perm α} (hf : is_cycle f) : coe_fn sign f = -(-1) ^ finset.card (support f) := sorry /-! ### `same_cycle` -/ /-- The equivalence relation indicating that two points are in the same cycle of a permutation. -/ def same_cycle {β : Type u_2} (f : perm β) (x : β) (y : β) := ∃ (i : ℤ), coe_fn (f ^ i) x = y theorem same_cycle.refl {β : Type u_2} (f : perm β) (x : β) : same_cycle f x x := Exists.intro 0 rfl theorem same_cycle.symm {β : Type u_2} (f : perm β) {x : β} {y : β} : same_cycle f x y → same_cycle f y x := sorry theorem same_cycle.trans {β : Type u_2} (f : perm β) {x : β} {y : β} {z : β} : same_cycle f x y → same_cycle f y z → same_cycle f x z := sorry theorem same_cycle.apply_eq_self_iff {β : Type u_2} {f : perm β} {x : β} {y : β} : same_cycle f x y → (coe_fn f x = x ↔ coe_fn f y = y) := sorry theorem is_cycle.same_cycle {β : Type u_2} {f : perm β} (hf : is_cycle f) {x : β} {y : β} (hx : coe_fn f x ≠ x) (hy : coe_fn f y ≠ y) : same_cycle f x y := is_cycle.exists_gpow_eq hf hx hy protected instance same_cycle.decidable_rel {α : Type u_1} [DecidableEq α] [fintype α] (f : perm α) : DecidableRel (same_cycle f) := fun (x y : α) => decidable_of_iff (∃ (n : ℕ), ∃ (H : n ∈ list.range (order_of f)), coe_fn (f ^ n) x = y) sorry theorem same_cycle_apply {β : Type u_2} {f : perm β} {x : β} {y : β} : same_cycle f x (coe_fn f y) ↔ same_cycle f x y := sorry theorem same_cycle_cycle {β : Type u_2} {f : perm β} {x : β} (hx : coe_fn f x ≠ x) : is_cycle f ↔ ∀ {y : β}, same_cycle f x y ↔ coe_fn f y ≠ y := sorry theorem same_cycle_inv {β : Type u_2} (f : perm β) {x : β} {y : β} : same_cycle (f⁻¹) x y ↔ same_cycle f x y := sorry theorem same_cycle_inv_apply {β : Type u_2} {f : perm β} {x : β} {y : β} : same_cycle f x (coe_fn (f⁻¹) y) ↔ same_cycle f x y := sorry /-! ### `cycle_of` -/ /-- `f.cycle_of x` is the cycle of the permutation `f` to which `x` belongs. -/ def cycle_of {α : Type u_1} [DecidableEq α] [fintype α] (f : perm α) (x : α) : perm α := coe_fn of_subtype (subtype_perm f sorry) theorem cycle_of_apply {α : Type u_1} [DecidableEq α] [fintype α] (f : perm α) (x : α) (y : α) : coe_fn (cycle_of f x) y = ite (same_cycle f x y) (coe_fn f y) y := rfl theorem cycle_of_inv {α : Type u_1} [DecidableEq α] [fintype α] (f : perm α) (x : α) : cycle_of f x⁻¹ = cycle_of (f⁻¹) x := sorry @[simp] theorem cycle_of_pow_apply_self {α : Type u_1} [DecidableEq α] [fintype α] (f : perm α) (x : α) (n : ℕ) : coe_fn (cycle_of f x ^ n) x = coe_fn (f ^ n) x := sorry @[simp] theorem cycle_of_gpow_apply_self {α : Type u_1} [DecidableEq α] [fintype α] (f : perm α) (x : α) (n : ℤ) : coe_fn (cycle_of f x ^ n) x = coe_fn (f ^ n) x := sorry theorem same_cycle.cycle_of_apply {α : Type u_1} [DecidableEq α] [fintype α] {f : perm α} {x : α} {y : α} (h : same_cycle f x y) : coe_fn (cycle_of f x) y = coe_fn f y := dif_pos h theorem cycle_of_apply_of_not_same_cycle {α : Type u_1} [DecidableEq α] [fintype α] {f : perm α} {x : α} {y : α} (h : ¬same_cycle f x y) : coe_fn (cycle_of f x) y = y := dif_neg h @[simp] theorem cycle_of_apply_self {α : Type u_1} [DecidableEq α] [fintype α] (f : perm α) (x : α) : coe_fn (cycle_of f x) x = coe_fn f x := same_cycle.cycle_of_apply (same_cycle.refl f x) theorem is_cycle.cycle_of_eq {α : Type u_1} [DecidableEq α] [fintype α] {f : perm α} (hf : is_cycle f) {x : α} (hx : coe_fn f x ≠ x) : cycle_of f x = f := sorry theorem cycle_of_one {α : Type u_1} [DecidableEq α] [fintype α] (x : α) : cycle_of 1 x = 1 := sorry theorem is_cycle_cycle_of {α : Type u_1} [DecidableEq α] [fintype α] (f : perm α) {x : α} (hx : coe_fn f x ≠ x) : is_cycle (cycle_of f x) := sorry /-! ### `cycle_factors` -/ /-- Given a list `l : list α` and a permutation `f : perm α` whose nonfixed points are all in `l`, recursively factors `f` into cycles. -/ def cycle_factors_aux {α : Type u_1} [DecidableEq α] [fintype α] (l : List α) (f : perm α) : (∀ {x : α}, coe_fn f x ≠ x → x ∈ l) → Subtype fun (l : List (perm α)) => list.prod l = f ∧ (∀ (g : perm α), g ∈ l → is_cycle g) ∧ list.pairwise disjoint l := sorry /-- Factors a permutation `f` into a list of disjoint cyclic permutations that multiply to `f`. -/ def cycle_factors {α : Type u_1} [DecidableEq α] [fintype α] [linear_order α] (f : perm α) : Subtype fun (l : List (perm α)) => list.prod l = f ∧ (∀ (g : perm α), g ∈ l → is_cycle g) ∧ list.pairwise disjoint l := cycle_factors_aux (finset.sort LessEq finset.univ) f sorry /-! ### Fixed points -/ theorem one_lt_nonfixed_point_card_of_ne_one {α : Type u_1} [DecidableEq α] [fintype α] {σ : perm α} (h : σ ≠ 1) : 1 < finset.card (finset.filter (fun (x : α) => coe_fn σ x ≠ x) finset.univ) := sorry theorem fixed_point_card_lt_of_ne_one {α : Type u_1} [DecidableEq α] [fintype α] {σ : perm α} (h : σ ≠ 1) : finset.card (finset.filter (fun (x : α) => coe_fn σ x = x) finset.univ) < fintype.card α - 1 := sorry end Mathlib
53e4ce4d4d157efda159d77b2fc0b5f4e78a7f6f
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/moduleOf.lean
0ed70033b8b9bf3cbcbbe7038549008862cbbf12
[ "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
430
lean
import Lean def f (x : Nat) := x + x open Lean def tst : MetaM Unit := do IO.println (← findModuleOf? `HAdd.hAdd) IO.println (← findModuleOf? `Lean.Core.CoreM) IO.println (← findModuleOf? `Lean.Elab.Term.elabTerm) IO.println (← findModuleOf? `Lean.HashMap.insert) IO.println (← findModuleOf? `tst) IO.println (← findModuleOf? `f) IO.println (← findModuleOf? `foo) -- Error: unknown 'foo' #eval tst
47cd8da5bbd47d93f0693e16eee7ec531958eec2
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/gcd.lean
be5b9c5dfc30c4ad640a5dcf32d077f10c02f375
[ "Apache-2.0" ]
permissive
leanprover-community/lean
12b87f69d92e614daea8bcc9d4de9a9ace089d0e
cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0
refs/heads/master
1,687,508,156,644
1,684,951,104,000
1,684,951,104,000
169,960,991
457
107
Apache-2.0
1,686,744,372,000
1,549,790,268,000
C++
UTF-8
Lean
false
false
1,484
lean
open nat well_founded decidable prod namespace playground -- Setup definition pair_nat.lt := lex nat.lt nat.lt definition pair_nat.lt.wf : well_founded pair_nat.lt := prod.lex_wf lt_wf lt_wf infixl `≺`:50 := pair_nat.lt -- Lemma for justifying recursive call private lemma lt₁ (x₁ y₁ : nat) : (x₁ - y₁, succ y₁) ≺ (succ x₁, succ y₁) := lex.left _ _ (lt_succ_of_le (x₁.sub_le y₁)) -- Lemma for justifying recursive call private lemma lt₂ (x₁ y₁ : nat) : (succ x₁, y₁ - x₁) ≺ (succ x₁, succ y₁) := lex.right _ (lt_succ_of_le (y₁.sub_le x₁)) definition gcd.F (p₁ : nat × nat) : (Π p₂ : nat × nat, p₂ ≺ p₁ → nat) → nat := prod.cases_on p₁ (λ (x y : nat), nat.cases_on x (λ f, y) -- x = 0 (λ x₁, nat.cases_on y (λ f, succ x₁) -- y = 0 (λ y₁ (f : (Π p₂ : nat × nat, p₂ ≺ (succ x₁, succ y₁) → nat)), if y₁ ≤ x₁ then f (x₁ - y₁, succ y₁) (lt₁ _ _ ) else f (succ x₁, y₁ - x₁) (lt₂ _ _)))) definition gcd (x y : nat) := fix pair_nat.lt.wf gcd.F (x, y) theorem gcd_def_z_y (y : nat) : gcd 0 y = y := well_founded.fix_eq pair_nat.lt.wf gcd.F (0, y) theorem gcd_def_sx_z (x : nat) : gcd (x+1) 0 = x+1 := well_founded.fix_eq pair_nat.lt.wf gcd.F (x+1, 0) theorem gcd_def_sx_sy (x y : nat) : gcd (x+1) (y+1) = if y ≤ x then gcd (x-y) (y+1) else gcd (x+1) (y-x) := well_founded.fix_eq pair_nat.lt.wf gcd.F (x+1, y+1) end playground
02f1da64243fd927522260a7d53ac14ce0177a77
54ce0561cebde424526f41d45f490ed56be2bd0c
/src/game/ch4_Integers_and_Rationals/1_The_Integers.lean
e53a58cd8dd086103e5ff0f777390b01bacac3f4
[]
no_license
melembroucarlitos/Tao_Analysis-LEAN
cf7b3298d317891a09e4bf21cfe7c7ffcb57b9a9
3f4fc7e090d96b6cef64896492fba4bef124794b
refs/heads/master
1,692,952,385,694
1,636,287,522,000
1,636,287,522,000
400,630,166
3
0
null
1,635,910,807,000
1,630,096,823,000
Lean
UTF-8
Lean
false
false
162
lean
-- Level name : The Integers /- # Hey yall ## This is just to a placeholder to make sure all is working these are some words and these are some other words -/
8423ea569dac263cabc34d185d32457e08ab45e3
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/computability/DFA.lean
f4cf327219af278f72c797c07b98793af3b25ead
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
4,611
lean
/- Copyright (c) 2020 Fox Thomson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Fox Thomson -/ import data.fintype.basic import computability.language import tactic.norm_num /-! # Deterministic Finite Automata This file contains the definition of a Deterministic Finite Automaton (DFA), a state machine which determines whether a string (implemented as a list over an arbitrary alphabet) is in a regular set in linear time. Note that this definition allows for Automaton with infinite states, a `fintype` instance must be supplied for true DFA's. -/ universes u v /-- A DFA is a set of states (`σ`), a transition function from state to state labelled by the alphabet (`step`), a starting state (`start`) and a set of acceptance states (`accept`). -/ structure DFA (α : Type u) (σ : Type v) := (step : σ → α → σ) (start : σ) (accept : set σ) namespace DFA variables {α : Type u} {σ : Type v} (M : DFA α σ) instance [inhabited σ] : inhabited (DFA α σ) := ⟨DFA.mk (λ _ _, default) default ∅⟩ /-- `M.eval_from s x` evaluates `M` with input `x` starting from the state `s`. -/ def eval_from (start : σ) : list α → σ := list.foldl M.step start /-- `M.eval x` evaluates `M` with input `x` starting from the state `M.start`. -/ def eval := M.eval_from M.start /-- `M.accepts` is the language of `x` such that `M.eval x` is an accept state. -/ def accepts : language α := λ x, M.eval x ∈ M.accept lemma mem_accepts (x : list α) : x ∈ M.accepts ↔ M.eval_from M.start x ∈ M.accept := by refl lemma eval_from_of_append (start : σ) (x y : list α) : M.eval_from start (x ++ y) = M.eval_from (M.eval_from start x) y := x.foldl_append _ _ y lemma eval_from_split [fintype σ] {x : list α} {s t : σ} (hlen : fintype.card σ ≤ x.length) (hx : M.eval_from s x = t) : ∃ q a b c, x = a ++ b ++ c ∧ a.length + b.length ≤ fintype.card σ ∧ b ≠ [] ∧ M.eval_from s a = q ∧ M.eval_from q b = q ∧ M.eval_from q c = t := begin obtain ⟨n, m, hneq, heq⟩ := fintype.exists_ne_map_eq_of_card_lt (λ n : fin (fintype.card σ + 1), M.eval_from s (x.take n)) (by norm_num), wlog hle : (n : ℕ) ≤ m using n m, have hlt : (n : ℕ) < m := (ne.le_iff_lt hneq).mp hle, have hm : (m : ℕ) ≤ fintype.card σ := fin.is_le m, dsimp at heq, refine ⟨M.eval_from s ((x.take m).take n), (x.take m).take n, (x.take m).drop n, x.drop m, _, _, _, by refl, _⟩, { rw [list.take_append_drop, list.take_append_drop] }, { simp only [list.length_drop, list.length_take], rw [min_eq_left (hm.trans hlen), min_eq_left hle, add_tsub_cancel_of_le hle], exact hm }, { intro h, have hlen' := congr_arg list.length h, simp only [list.length_drop, list.length, list.length_take] at hlen', rw [min_eq_left, tsub_eq_zero_iff_le] at hlen', { apply hneq, apply le_antisymm, assumption' }, exact hm.trans hlen, }, have hq : M.eval_from (M.eval_from s ((x.take m).take n)) ((x.take m).drop n) = M.eval_from s ((x.take m).take n), { rw [list.take_take, min_eq_left hle, ←eval_from_of_append, heq, ←min_eq_left hle, ←list.take_take, min_eq_left hle, list.take_append_drop] }, use hq, rwa [←hq, ←eval_from_of_append, ←eval_from_of_append, ←list.append_assoc, list.take_append_drop, list.take_append_drop] end lemma eval_from_of_pow {x y : list α} {s : σ} (hx : M.eval_from s x = s) (hy : y ∈ @language.star α {x}) : M.eval_from s y = s := begin rw language.mem_star at hy, rcases hy with ⟨ S, rfl, hS ⟩, induction S with a S ih, { refl }, { have ha := hS a (list.mem_cons_self _ _), rw set.mem_singleton_iff at ha, rw [list.join, eval_from_of_append, ha, hx], apply ih, intros z hz, exact hS z (list.mem_cons_of_mem a hz) } end lemma pumping_lemma [fintype σ] {x : list α} (hx : x ∈ M.accepts) (hlen : fintype.card σ ≤ list.length x) : ∃ a b c, x = a ++ b ++ c ∧ a.length + b.length ≤ fintype.card σ ∧ b ≠ [] ∧ {a} * language.star {b} * {c} ≤ M.accepts := begin obtain ⟨_, a, b, c, hx, hlen, hnil, rfl, hb, hc⟩ := M.eval_from_split hlen rfl, use [a, b, c, hx, hlen, hnil], intros y hy, rw language.mem_mul at hy, rcases hy with ⟨ ab, c', hab, hc', rfl ⟩, rw language.mem_mul at hab, rcases hab with ⟨ a', b', ha', hb', rfl ⟩, rw set.mem_singleton_iff at ha' hc', substs ha' hc', have h := M.eval_from_of_pow hb hb', rwa [mem_accepts, eval_from_of_append, eval_from_of_append, h, hc] end end DFA
346ecd30a379e03a10707b4308229a134b0d4826
1a61aba1b67cddccce19532a9596efe44be4285f
/tests/lean/notation3.lean
65def3ce7bd2a14a0e9fd5aa0e7ceccb7a86c0ab
[ "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
315
lean
import data.prod data.num inductive list (T : Type) : Type := nil {} : list T | cons : T → list T → list T open list notation h :: t := cons h t notation `[` l:(foldr `,` (h t, cons h t) nil) `]` := l open prod num constants a b : num check [a, b, b] check (a, true, a = b, b) check (a, b) check [1, 2+2, 3]
d997603a13a7ba6f30708c20e2aaf53f804b2a12
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/data/quot.lean
cfb4f54fa88962ca07024c6edf7813eb2998f9c7
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
23,482
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 extends 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⟧⟩ instance [subsingleton α] : subsingleton (quot ra) := ⟨λ x, quot.induction_on x (λ y, quot.ind (λ b, congr_arg _ (subsingleton.elim _ _)))⟩ /-- 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 [heq_self_iff_true] ... == f a₂ b : ca pa ... == @quot.hrec_on _ _ (φ _) ⟦b⟧ (f a₂) (@cb _) : by simp [heq_self_iff_true] /-- 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} /-- **Alias** of `quot.lift_beta`. -/ lemma lift_mk (f : α → γ) (h : ∀ a₁ a₂, r a₁ a₂ → f a₁ = f a₂) (a : α) : quot.lift f h (quot.mk r a) = f a := quot.lift_beta f h a @[simp] lemma lift_on_mk (a : α) (f : α → γ) (h : ∀ a₁ a₂, r a₁ a₂ → f a₁ = f a₂) : quot.lift_on (quot.mk r a) f h = f a := rfl /-- 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 (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) (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⟧⟩ instance (s : setoid α) [subsingleton α] : subsingleton (quotient s) := quot.subsingleton /-- 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₂) @[simp] lemma map₂_mk (f : α → β → γ) (h : ((≈) ⇒ (≈) ⇒ (≈)) f f) (x : α) (y : β) : quotient.map₂ f h (⟦x⟧ : quotient sa) (⟦y⟧ : quotient sb) = (⟦f x y⟧ : quotient sc) := rfl 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_mk [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₂_mk {α : Sort*} {β : Sort*} {γ : Sort*} [setoid α] [setoid β] (f : α → β → γ) (h : ∀ (a₁ : α) (a₂ : β) (b₁ : α) (b₂ : β), a₁ ≈ b₁ → a₂ ≈ b₂ → f a₁ a₂ = f b₁ b₂) (a : α) (b : β) : quotient.lift₂ f h (quotient.mk a) (quotient.mk b) = f a b := rfl @[simp] lemma quotient.lift_on_mk [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₂_mk {α : Sort*} {β : Sort*} [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 /-- `quot.mk r` is a surjective function. -/ lemma surjective_quot_mk (r : α → α → Prop) : function.surjective (quot.mk r) := quot.exists_rep /-- `quotient.mk` is a surjective function. -/ lemma surjective_quotient_mk (α : Sort*) [s : setoid α] : function.surjective (quotient.mk : α → quotient s) := quot.exists_rep /-- 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 _) lemma quotient.mk_eq_iff_out [s : setoid α] {x : α} {y : quotient s} : ⟦x⟧ = y ↔ x ≈ quotient.out y := begin refine iff.trans _ quotient.eq, rw quotient.out_eq y, end lemma quotient.eq_mk_iff_out [s : setoid α] {x : quotient s} {y : α} : x = ⟦y⟧ ↔ quotient.out x ≈ y := begin refine iff.trans _ quotient.eq, rw quotient.out_eq x, end @[simp] lemma quotient.out_equiv_out [s : setoid α] {x y : quotient s} : x.out ≈ y.out ↔ x = y := by rw [← quotient.eq_mk_iff_out, quotient.out_eq] @[simp] lemma quotient.out_inj [s : setoid α] {x y : quotient s} : x.out = y.out ↔ x = y := ⟨λ h, quotient.out_equiv_out.1 $ h ▸ setoid.refl _, λ h, h ▸ rfl⟩ section pi 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⟧ @[simp] theorem quotient.choice_eq {ι : Type*} {α : ι → Type*} [Π i, setoid (α i)] (f : Π i, α i) : quotient.choice (λ i, ⟦f i⟧) = ⟦f⟧ := quotient.sound $ λ i, quotient.mk_out _ @[elab_as_eliminator] lemma quotient.induction_on_pi {ι : Type*} {α : ι → Sort*} [s : ∀ i, setoid (α i)] {p : (Π i, quotient (s i)) → Prop} (f : Π i, quotient (s i)) (h : ∀ a : Π i, α i, p (λ i, ⟦a i⟧)) : p f := begin rw ← (funext (λ i, quotient.out_eq (f i)) : (λ i, ⟦(f i).out⟧) = f), apply h, end end pi 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_mk (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 _ _ protected theorem nonempty (q : trunc α) : nonempty α := nonempty_of_exists q.exists_rep end trunc 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 /-- `quotient.mk'` is a surjective function. -/ lemma surjective_quotient_mk' : function.surjective (quotient.mk' : α → quotient s₁) := quot.exists_rep /-- 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 @[simp] protected lemma lift_on'_mk' (f : α → φ) (h) (x : α) : quotient.lift_on' (@quotient.mk' _ s₁ x) f h = f x := rfl /-- 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 @[simp] protected lemma lift_on₂'_mk' (f : α → β → γ) (h) (a : α) (b : β) : quotient.lift_on₂' (@quotient.mk' _ s₁ a) (@quotient.mk' _ s₂ b) f h = f a b := rfl /-- 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 /-- A version of `quotient.rec_on_subsingleton` taking `{s₁ : setoid α}` as an implicit argument instead of an instance argument. -/ @[elab_as_eliminator] protected def rec_on_subsingleton' {φ : quotient s₁ → Sort*} [h : ∀ a, subsingleton (φ ⟦a⟧)] (q : quotient s₁) (f : Π a, φ (quotient.mk' a)) : φ q := quotient.rec_on_subsingleton q f /-- A version of `quotient.rec_on_subsingleton₂` taking `{s₁ : setoid α} {s₂ : setoid α}` as implicit arguments instead of instance arguments. -/ attribute [reducible, elab_as_eliminator] protected def rec_on_subsingleton₂' {φ : quotient s₁ → quotient s₂ → Sort*} [h : ∀ a b, subsingleton (φ ⟦a⟧ ⟦b⟧)] (q₁ : quotient s₁) (q₂ : quotient s₂) (f : Π a₁ a₂, φ (quotient.mk' a₁) (quotient.mk' a₂)) : φ q₁ q₂ := quotient.rec_on_subsingleton₂ q₁ q₂ f /-- 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
3a10cec563eb447653bebcce83892a5b81a49c10
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/linear_algebra/basic.lean
5d62e6270da791261af80bf21305187ebc57fc75
[ "Apache-2.0" ]
permissive
AntoineChambert-Loir/mathlib
64aabb896129885f12296a799818061bc90da1ff
07be904260ab6e36a5769680b6012f03a4727134
refs/heads/master
1,693,187,631,771
1,636,719,886,000
1,636,719,886,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
107,460
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, Frédéric Dupuis, Heather Macbeth -/ import algebra.big_operators.pi import algebra.module.hom import algebra.module.prod import algebra.module.submodule_lattice import data.dfinsupp import data.finsupp.basic import order.compactly_generated import order.omega_complete_partial_order /-! # Linear algebra This file defines the basics of linear algebra. It sets up the "categorical/lattice structure" of modules over a ring, submodules, and linear maps. Many of the relevant definitions, including `module`, `submodule`, and `linear_map`, are found in `src/algebra/module`. ## Main definitions * Many constructors for (semi)linear maps * `submodule.span s` is defined to be the smallest submodule containing the set `s`. * The kernel `ker` and range `range` of a linear map are submodules of the domain and codomain respectively. * The general linear group is defined to be the group of invertible linear maps from `M` to itself. See `linear_algebra.quotient` for quotients by submodules. ## Main theorems See `linear_algebra.isomorphisms` for Noether's three isomorphism theorems for modules. ## Notations * We continue to use the notations `M →ₛₗ[σ] M₂` and `M →ₗ[R] M₂` for the type of semilinear (resp. linear) maps from `M` to `M₂` over the ring homomorphism `σ` (resp. over the ring `R`). * We introduce the notation `R ∙ v` for the span of a singleton, `submodule.span R {v}`. This is `\.`, not the same as the scalar multiplication `•`/`\bub`. ## Implementation notes We note that, when constructing linear maps, it is convenient to use operations defined on bundled maps (`linear_map.prod`, `linear_map.coprod`, arithmetic operations like `+`) instead of defining a function and proving it is linear. ## TODO * Parts of this file have not yet been generalized to semilinear maps ## Tags linear algebra, vector space, module -/ open function open_locale big_operators pointwise variables {R : Type*} {R₁ : Type*} {R₂ : Type*} {R₃ : Type*} {R₄ : Type*} variables {S : Type*} variables {K : Type*} {K₂ : Type*} variables {M : Type*} {M' : Type*} {M₁ : Type*} {M₂ : Type*} {M₃ : Type*} {M₄ : Type*} variables {N : Type*} {N₂ : Type*} variables {ι : Type*} variables {V : Type*} {V₂ : Type*} namespace finsupp lemma smul_sum {α : Type*} {β : Type*} {R : Type*} {M : Type*} [has_zero β] [monoid R] [add_comm_monoid M] [distrib_mul_action R M] {v : α →₀ β} {c : R} {h : α → β → M} : c • (v.sum h) = v.sum (λa b, c • h a b) := finset.smul_sum @[simp] lemma sum_smul_index_linear_map' {α : Type*} {R : Type*} {M : Type*} {M₂ : Type*} [semiring R] [add_comm_monoid M] [module R M] [add_comm_monoid M₂] [module R M₂] {v : α →₀ M} {c : R} {h : α → M →ₗ[R] M₂} : (c • v).sum (λ a, h a) = c • (v.sum (λ a, h a)) := begin rw [finsupp.sum_smul_index', finsupp.smul_sum], { simp only [linear_map.map_smul], }, { intro i, exact (h i).map_zero }, end variables (α : Type*) [fintype α] variables (R M) [add_comm_monoid M] [semiring R] [module R M] /-- Given `fintype α`, `linear_equiv_fun_on_fintype R` is the natural `R`-linear equivalence between `α →₀ β` and `α → β`. -/ @[simps apply] noncomputable def linear_equiv_fun_on_fintype : (α →₀ M) ≃ₗ[R] (α → M) := { to_fun := coe_fn, map_add' := λ f g, by { ext, refl }, map_smul' := λ c f, by { ext, refl }, .. equiv_fun_on_fintype } @[simp] lemma linear_equiv_fun_on_fintype_single [decidable_eq α] (x : α) (m : M) : (linear_equiv_fun_on_fintype R M α) (single x m) = pi.single x m := begin ext a, change (equiv_fun_on_fintype (single x m)) a = _, convert _root_.congr_fun (equiv_fun_on_fintype_single x m) a, end @[simp] lemma linear_equiv_fun_on_fintype_symm_single [decidable_eq α] (x : α) (m : M) : (linear_equiv_fun_on_fintype R M α).symm (pi.single x m) = single x m := begin ext a, change (equiv_fun_on_fintype.symm (pi.single x m)) a = _, convert congr_fun (equiv_fun_on_fintype_symm_single x m) a, end @[simp] lemma linear_equiv_fun_on_fintype_symm_coe (f : α →₀ M) : (linear_equiv_fun_on_fintype R M α).symm f = f := by { ext, simp [linear_equiv_fun_on_fintype], } end finsupp section open_locale classical /-- decomposing `x : ι → R` as a sum along the canonical basis -/ lemma pi_eq_sum_univ {ι : Type*} [fintype ι] {R : Type*} [semiring R] (x : ι → R) : x = ∑ i, x i • (λj, if i = j then 1 else 0) := by { ext, simp } end /-! ### Properties of linear maps -/ namespace linear_map section add_comm_monoid variables [semiring R] [semiring R₂] [semiring R₃] [semiring R₄] variables [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₃] [module R₄ M₄] variables {σ₁₂ : R →+* R₂} {σ₂₃ : R₂ →+* R₃} {σ₃₄ : R₃ →+* R₄} variables {σ₁₃ : R →+* R₃} {σ₂₄ : R₂ →+* R₄} {σ₁₄ : R →+* R₄} variables [ring_hom_comp_triple σ₁₂ σ₂₃ σ₁₃] [ring_hom_comp_triple σ₂₃ σ₃₄ σ₂₄] variables [ring_hom_comp_triple σ₁₃ σ₃₄ σ₁₄] [ring_hom_comp_triple σ₁₂ σ₂₄ σ₁₄] variables (f : M →ₛₗ[σ₁₂] M₂) (g : M₂ →ₛₗ[σ₂₃] M₃) include R R₂ theorem comp_assoc (h : M₃ →ₛₗ[σ₃₄] M₄) : ((h.comp g : M₂ →ₛₗ[σ₂₄] M₄).comp f : M →ₛₗ[σ₁₄] M₄) = h.comp (g.comp f : M →ₛₗ[σ₁₃] M₃) := rfl omit R R₂ /-- The restriction of a linear map `f : M → M₂` to a submodule `p ⊆ M` gives a linear map `p → M₂`. -/ def dom_restrict (f : M →ₛₗ[σ₁₂] M₂) (p : submodule R M) : p →ₛₗ[σ₁₂] M₂ := f.comp p.subtype @[simp] lemma dom_restrict_apply (f : M →ₛₗ[σ₁₂] M₂) (p : submodule R M) (x : p) : f.dom_restrict p x = f x := rfl /-- A linear map `f : M₂ → M` whose values lie in a submodule `p ⊆ M` can be restricted to a linear map M₂ → p. -/ def cod_restrict (p : submodule R₂ M₂) (f : M →ₛₗ[σ₁₂] M₂) (h : ∀c, f c ∈ p) : M →ₛₗ[σ₁₂] p := by refine {to_fun := λc, ⟨f c, h c⟩, ..}; intros; apply set_coe.ext; simp @[simp] theorem cod_restrict_apply (p : submodule R₂ M₂) (f : M →ₛₗ[σ₁₂] M₂) {h} (x : M) : (cod_restrict p f h x : M₂) = f x := rfl @[simp] lemma comp_cod_restrict (p : submodule R₃ M₃) (h : ∀b, g b ∈ p) : ((cod_restrict p g h).comp f : M →ₛₗ[σ₁₃] p) = cod_restrict p (g.comp f) (assume b, h _) := ext $ assume b, rfl @[simp] lemma subtype_comp_cod_restrict (p : submodule R₂ M₂) (h : ∀b, f b ∈ p) : p.subtype.comp (cod_restrict p f h) = f := ext $ assume b, rfl /-- Restrict domain and codomain of an endomorphism. -/ def restrict (f : M →ₗ[R] M) {p : submodule R M} (hf : ∀ x ∈ p, f x ∈ p) : p →ₗ[R] p := (f.dom_restrict p).cod_restrict p $ set_like.forall.2 hf lemma restrict_apply {f : M →ₗ[R] M} {p : submodule R M} (hf : ∀ x ∈ p, f x ∈ p) (x : p) : f.restrict hf x = ⟨f x, hf x.1 x.2⟩ := rfl lemma subtype_comp_restrict {f : M →ₗ[R] M} {p : submodule R M} (hf : ∀ x ∈ p, f x ∈ p) : p.subtype.comp (f.restrict hf) = f.dom_restrict p := rfl lemma restrict_eq_cod_restrict_dom_restrict {f : M →ₗ[R] M} {p : submodule R M} (hf : ∀ x ∈ p, f x ∈ p) : f.restrict hf = (f.dom_restrict p).cod_restrict p (λ x, hf x.1 x.2) := rfl lemma restrict_eq_dom_restrict_cod_restrict {f : M →ₗ[R] M} {p : submodule R M} (hf : ∀ x, f x ∈ p) : f.restrict (λ x _, hf x) = (f.cod_restrict p hf).dom_restrict p := rfl instance unique_of_left [subsingleton M] : unique (M →ₛₗ[σ₁₂] M₂) := { uniq := λ f, ext $ λ x, by rw [subsingleton.elim x 0, map_zero, map_zero], .. linear_map.inhabited } instance unique_of_right [subsingleton M₂] : unique (M →ₛₗ[σ₁₂] M₂) := coe_injective.unique /-- Evaluation of a `σ₁₂`-linear map at a fixed `a`, as an `add_monoid_hom`. -/ def eval_add_monoid_hom (a : M) : (M →ₛₗ[σ₁₂] M₂) →+ M₂ := { to_fun := λ f, f a, map_add' := λ f g, linear_map.add_apply f g a, map_zero' := rfl } /-- `linear_map.to_add_monoid_hom` promoted to an `add_monoid_hom` -/ def to_add_monoid_hom' : (M →ₛₗ[σ₁₂] M₂) →+ (M →+ M₂) := { to_fun := to_add_monoid_hom, map_zero' := by ext; refl, map_add' := by intros; ext; refl } lemma sum_apply (t : finset ι) (f : ι → M →ₛₗ[σ₁₂] M₂) (b : M) : (∑ d in t, f d) b = ∑ d in t, f d b := add_monoid_hom.map_sum ((add_monoid_hom.eval b).comp to_add_monoid_hom') f _ section smul_right variables [semiring S] [module R S] [module S M] [is_scalar_tower R S M] /-- When `f` is an `R`-linear map taking values in `S`, then `λb, f b • x` is an `R`-linear map. -/ def smul_right (f : M₁ →ₗ[R] S) (x : M) : M₁ →ₗ[R] M := { to_fun := λb, f b • x, map_add' := λ x y, by rw [f.map_add, add_smul], map_smul' := λ b y, by dsimp; rw [f.map_smul, smul_assoc] } @[simp] theorem coe_smul_right (f : M₁ →ₗ[R] S) (x : M) : (smul_right f x : M₁ → M) = λ c, f c • x := rfl theorem smul_right_apply (f : M₁ →ₗ[R] S) (x : M) (c : M₁) : smul_right f x c = f c • x := rfl end smul_right instance [nontrivial M] : nontrivial (module.End R M) := begin obtain ⟨m, ne⟩ := (nontrivial_iff_exists_ne (0 : M)).mp infer_instance, exact nontrivial_of_ne 1 0 (λ p, ne (linear_map.congr_fun p m)), end @[simp, norm_cast] lemma coe_fn_sum {ι : Type*} (t : finset ι) (f : ι → M →ₛₗ[σ₁₂] M₂) : ⇑(∑ i in t, f i) = ∑ i in t, (f i : M → M₂) := add_monoid_hom.map_sum ⟨@to_fun R R₂ _ _ σ₁₂ M M₂ _ _ _ _, rfl, λ x y, rfl⟩ _ _ @[simp] lemma pow_apply (f : M →ₗ[R] M) (n : ℕ) (m : M) : (f^n) m = (f^[n] m) := begin induction n with n ih, { refl, }, { simp only [function.comp_app, function.iterate_succ, linear_map.mul_apply, pow_succ, ih], exact (function.commute.iterate_self _ _ m).symm, }, end lemma pow_map_zero_of_le {f : module.End R M} {m : M} {k l : ℕ} (hk : k ≤ l) (hm : (f^k) m = 0) : (f^l) m = 0 := by rw [← tsub_add_cancel_of_le hk, pow_add, mul_apply, hm, map_zero] lemma commute_pow_left_of_commute {f : M →ₛₗ[σ₁₂] M₂} {g : module.End R M} {g₂ : module.End R₂ M₂} (h : g₂.comp f = f.comp g) (k : ℕ) : (g₂^k).comp f = f.comp (g^k) := begin induction k with k ih, { simpa only [pow_zero], }, { rw [pow_succ, pow_succ, linear_map.mul_eq_comp, linear_map.comp_assoc, ih, ← linear_map.comp_assoc, h, linear_map.comp_assoc, linear_map.mul_eq_comp], }, end lemma submodule_pow_eq_zero_of_pow_eq_zero {N : submodule R M} {g : module.End R N} {G : module.End R M} (h : G.comp N.subtype = N.subtype.comp g) {k : ℕ} (hG : G^k = 0) : g^k = 0 := begin ext m, have hg : N.subtype.comp (g^k) m = 0, { rw [← commute_pow_left_of_commute h, hG, zero_comp, zero_apply], }, simp only [submodule.subtype_apply, comp_app, submodule.coe_eq_zero, coe_comp] at hg, rw [hg, linear_map.zero_apply], end lemma coe_pow (f : M →ₗ[R] M) (n : ℕ) : ⇑(f^n) = (f^[n]) := by { ext m, apply pow_apply, } @[simp] lemma id_pow (n : ℕ) : (id : M →ₗ[R] M)^n = id := one_pow n section variables {f' : M →ₗ[R] M} lemma iterate_succ (n : ℕ) : (f' ^ (n + 1)) = comp (f' ^ n) f' := by rw [pow_succ', mul_eq_comp] lemma iterate_surjective (h : surjective f') : ∀ n : ℕ, surjective ⇑(f' ^ n) | 0 := surjective_id | (n + 1) := by { rw [iterate_succ], exact surjective.comp (iterate_surjective n) h, } lemma iterate_injective (h : injective f') : ∀ n : ℕ, injective ⇑(f' ^ n) | 0 := injective_id | (n + 1) := by { rw [iterate_succ], exact injective.comp (iterate_injective n) h, } lemma iterate_bijective (h : bijective f') : ∀ n : ℕ, bijective ⇑(f' ^ n) | 0 := bijective_id | (n + 1) := by { rw [iterate_succ], exact bijective.comp (iterate_bijective n) h, } lemma injective_of_iterate_injective {n : ℕ} (hn : n ≠ 0) (h : injective ⇑(f' ^ n)) : injective f' := begin rw [← nat.succ_pred_eq_of_pos (pos_iff_ne_zero.mpr hn), iterate_succ, coe_comp] at h, exact injective.of_comp h, end lemma surjective_of_iterate_surjective {n : ℕ} (hn : n ≠ 0) (h : surjective ⇑(f' ^ n)) : surjective f' := begin rw [← nat.succ_pred_eq_of_pos (pos_iff_ne_zero.mpr hn), nat.succ_eq_add_one, add_comm, pow_add] at h, exact surjective.of_comp h, end end section open_locale classical /-- A linear map `f` applied to `x : ι → R` can be computed using the image under `f` of elements of the canonical basis. -/ lemma pi_apply_eq_sum_univ [fintype ι] (f : (ι → R) →ₗ[R] M) (x : ι → R) : f x = ∑ i, x i • (f (λj, if i = j then 1 else 0)) := begin conv_lhs { rw [pi_eq_sum_univ x, f.map_sum] }, apply finset.sum_congr rfl (λl hl, _), rw f.map_smul end end end add_comm_monoid section module variables [semiring R] [semiring S] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] [module R M] [module R M₂] [module R M₃] [module S M₂] [module S M₃] [smul_comm_class R S M₂] [smul_comm_class R S M₃] (f : M →ₗ[R] M₂) variable (S) /-- Applying a linear map at `v : M`, seen as `S`-linear map from `M →ₗ[R] M₂` to `M₂`. See `linear_map.applyₗ` for a version where `S = R`. -/ @[simps] def applyₗ' : M →+ (M →ₗ[R] M₂) →ₗ[S] M₂ := { to_fun := λ v, { to_fun := λ f, f v, map_add' := λ f g, f.add_apply g v, map_smul' := λ x f, f.smul_apply x v }, map_zero' := linear_map.ext $ λ f, f.map_zero, map_add' := λ x y, linear_map.ext $ λ f, f.map_add _ _ } section variables (R M) /-- The equivalence between R-linear maps from `R` to `M`, and points of `M` itself. This says that the forgetful functor from `R`-modules to types is representable, by `R`. This as an `S`-linear equivalence, under the assumption that `S` acts on `M` commuting with `R`. When `R` is commutative, we can take this to be the usual action with `S = R`. Otherwise, `S = ℕ` shows that the equivalence is additive. See note [bundled maps over different rings]. -/ @[simps] def ring_lmap_equiv_self [module S M] [smul_comm_class R S M] : (R →ₗ[R] M) ≃ₗ[S] M := { to_fun := λ f, f 1, inv_fun := smul_right (1 : R →ₗ[R] R), left_inv := λ f, by { ext, simp }, right_inv := λ x, by simp, .. applyₗ' S (1 : R) } end end module section comm_semiring variables [comm_semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] variables [module R M] [module R M₂] [module R M₃] variables (f g : M →ₗ[R] M₂) include R /-- Composition by `f : M₂ → M₃` is a linear map from the space of linear maps `M → M₂` to the space of linear maps `M₂ → M₃`. -/ def comp_right (f : M₂ →ₗ[R] M₃) : (M →ₗ[R] M₂) →ₗ[R] (M →ₗ[R] M₃) := { to_fun := f.comp, map_add' := λ _ _, linear_map.ext $ λ _, f.map_add _ _, map_smul' := λ _ _, linear_map.ext $ λ _, f.map_smul _ _ } /-- Applying a linear map at `v : M`, seen as a linear map from `M →ₗ[R] M₂` to `M₂`. See also `linear_map.applyₗ'` for a version that works with two different semirings. This is the `linear_map` version of `add_monoid_hom.eval`. -/ @[simps] def applyₗ : M →ₗ[R] (M →ₗ[R] M₂) →ₗ[R] M₂ := { to_fun := λ v, { to_fun := λ f, f v, ..applyₗ' R v }, map_smul' := λ x y, linear_map.ext $ λ f, f.map_smul _ _, ..applyₗ' R } /-- Alternative version of `dom_restrict` as a linear map. -/ def dom_restrict' (p : submodule R M) : (M →ₗ[R] M₂) →ₗ[R] (p →ₗ[R] M₂) := { to_fun := λ φ, φ.dom_restrict p, map_add' := by simp [linear_map.ext_iff], map_smul' := by simp [linear_map.ext_iff] } @[simp] lemma dom_restrict'_apply (f : M →ₗ[R] M₂) (p : submodule R M) (x : p) : dom_restrict' p f x = f x := rfl end comm_semiring section comm_ring variables [comm_ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [module R M] [module R M₂] [module R M₃] /-- The family of linear maps `M₂ → M` parameterised by `f ∈ M₂ → R`, `x ∈ M`, is linear in `f`, `x`. -/ def smul_rightₗ : (M₂ →ₗ[R] R) →ₗ[R] M →ₗ[R] M₂ →ₗ[R] M := { to_fun := λ f, { to_fun := linear_map.smul_right f, map_add' := λ m m', by { ext, apply smul_add, }, map_smul' := λ c m, by { ext, apply smul_comm, } }, map_add' := λ f f', by { ext, apply add_smul, }, map_smul' := λ c f, by { ext, apply mul_smul, } } @[simp] lemma smul_rightₗ_apply (f : M₂ →ₗ[R] R) (x : M) (c : M₂) : (smul_rightₗ : (M₂ →ₗ[R] R) →ₗ[R] M →ₗ[R] M₂ →ₗ[R] M) f x c = (f c) • x := rfl end comm_ring end linear_map /-- The `R`-linear equivalence between additive morphisms `A →+ B` and `ℕ`-linear morphisms `A →ₗ[ℕ] B`. -/ @[simps] def add_monoid_hom_lequiv_nat {A B : Type*} (R : Type*) [semiring R] [add_comm_monoid A] [add_comm_monoid B] [module R B] : (A →+ B) ≃ₗ[R] (A →ₗ[ℕ] B) := { to_fun := add_monoid_hom.to_nat_linear_map, inv_fun := linear_map.to_add_monoid_hom, map_add' := by { intros, ext, refl }, map_smul' := by { intros, ext, refl }, left_inv := by { intros f, ext, refl }, right_inv := by { intros f, ext, refl } } /-- The `R`-linear equivalence between additive morphisms `A →+ B` and `ℤ`-linear morphisms `A →ₗ[ℤ] B`. -/ @[simps] def add_monoid_hom_lequiv_int {A B : Type*} (R : Type*) [semiring R] [add_comm_group A] [add_comm_group B] [module R B] : (A →+ B) ≃ₗ[R] (A →ₗ[ℤ] B) := { to_fun := add_monoid_hom.to_int_linear_map, inv_fun := linear_map.to_add_monoid_hom, map_add' := by { intros, ext, refl }, map_smul' := by { intros, ext, refl }, left_inv := by { intros f, ext, refl }, right_inv := by { intros f, ext, refl } } /-! ### Properties of submodules -/ namespace submodule section add_comm_monoid variables [semiring R] [semiring R₂] [semiring R₃] variables [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] [add_comm_monoid M'] variables [module R M] [module R M'] [module R₂ M₂] [module R₃ M₃] variables {σ₁₂ : R →+* R₂} {σ₂₃ : R₂ →+* R₃} {σ₁₃ : R →+* R₃} variables {σ₂₁ : R₂ →+* R} variables [ring_hom_inv_pair σ₁₂ σ₂₁] [ring_hom_inv_pair σ₂₁ σ₁₂] variables [ring_hom_comp_triple σ₁₂ σ₂₃ σ₁₃] variables (p p' : submodule R M) (q q' : submodule R₂ M₂) variables (q₁ q₁' : submodule R M') variables {r : R} {x y : M} open set variables {p p'} /-- If two submodules `p` and `p'` satisfy `p ⊆ p'`, then `of_le p p'` is the linear map version of this inclusion. -/ def of_le (h : p ≤ p') : p →ₗ[R] p' := p.subtype.cod_restrict p' $ λ ⟨x, hx⟩, h hx @[simp] theorem coe_of_le (h : p ≤ p') (x : p) : (of_le h x : M) = x := rfl theorem of_le_apply (h : p ≤ p') (x : p) : of_le h x = ⟨x, h x.2⟩ := rfl theorem of_le_injective (h : p ≤ p') : function.injective (of_le h) := λ x y h, subtype.val_injective (subtype.mk.inj h) variables (p p') lemma subtype_comp_of_le (p q : submodule R M) (h : p ≤ q) : q.subtype.comp (of_le h) = p.subtype := by { ext ⟨b, hb⟩, refl } variables (R) @[simp] lemma subsingleton_iff : subsingleton (submodule R M) ↔ subsingleton M := have h : subsingleton (submodule R M) ↔ subsingleton (add_submonoid M), { rw [←subsingleton_iff_bot_eq_top, ←subsingleton_iff_bot_eq_top], convert to_add_submonoid_eq.symm; refl, }, h.trans add_submonoid.subsingleton_iff @[simp] lemma nontrivial_iff : nontrivial (submodule R M) ↔ nontrivial M := not_iff_not.mp ( (not_nontrivial_iff_subsingleton.trans $ subsingleton_iff R).trans not_nontrivial_iff_subsingleton.symm) variables {R} instance [subsingleton M] : unique (submodule R M) := ⟨⟨⊥⟩, λ a, @subsingleton.elim _ ((subsingleton_iff R).mpr ‹_›) a _⟩ instance unique' [subsingleton R] : unique (submodule R M) := by haveI := module.subsingleton R M; apply_instance instance [nontrivial M] : nontrivial (submodule R M) := (nontrivial_iff R).mpr ‹_› theorem disjoint_def {p p' : submodule R M} : disjoint p p' ↔ ∀ x ∈ p, x ∈ p' → x = (0:M) := show (∀ x, x ∈ p ∧ x ∈ p' → x ∈ ({0} : set M)) ↔ _, by simp theorem disjoint_def' {p p' : submodule R M} : disjoint p p' ↔ ∀ (x ∈ p) (y ∈ p'), x = y → x = (0:M) := disjoint_def.trans ⟨λ h x hx y hy hxy, h x hx $ hxy.symm ▸ hy, λ h x hx hx', h _ hx x hx' rfl⟩ theorem mem_right_iff_eq_zero_of_disjoint {p p' : submodule R M} (h : disjoint p p') {x : p} : (x:M) ∈ p' ↔ x = 0 := ⟨λ hx, coe_eq_zero.1 $ disjoint_def.1 h x x.2 hx, λ h, h.symm ▸ p'.zero_mem⟩ theorem mem_left_iff_eq_zero_of_disjoint {p p' : submodule R M} (h : disjoint p p') {x : p'} : (x:M) ∈ p ↔ x = 0 := ⟨λ hx, coe_eq_zero.1 $ disjoint_def.1 h x hx x.2, λ h, h.symm ▸ p.zero_mem⟩ section variables [ring_hom_surjective σ₁₂] /-- The pushforward of a submodule `p ⊆ M` by `f : M → M₂` -/ def map (f : M →ₛₗ[σ₁₂] M₂) (p : submodule R M) : submodule R₂ M₂ := { carrier := f '' p, smul_mem' := begin rintro c x ⟨y, hy, rfl⟩, obtain ⟨a, rfl⟩ := σ₁₂.is_surjective c, exact ⟨_, p.smul_mem a hy, f.map_smulₛₗ _ _⟩, end, .. p.to_add_submonoid.map f.to_add_monoid_hom } @[simp] lemma map_coe (f : M →ₛₗ[σ₁₂] M₂) (p : submodule R M) : (map f p : set M₂) = f '' p := rfl @[simp] lemma mem_map {f : M →ₛₗ[σ₁₂] M₂} {p : submodule R M} {x : M₂} : x ∈ map f p ↔ ∃ y, y ∈ p ∧ f y = x := iff.rfl theorem mem_map_of_mem {f : M →ₛₗ[σ₁₂] M₂} {p : submodule R M} {r} (h : r ∈ p) : f r ∈ map f p := set.mem_image_of_mem _ h lemma apply_coe_mem_map (f : M →ₛₗ[σ₁₂] M₂) {p : submodule R M} (r : p) : f r ∈ map f p := mem_map_of_mem r.prop @[simp] lemma map_id : map (linear_map.id : M →ₗ[R] M) p = p := submodule.ext $ λ a, by simp lemma map_comp [ring_hom_surjective σ₂₃] [ring_hom_surjective σ₁₃] (f : M →ₛₗ[σ₁₂] M₂) (g : M₂ →ₛₗ[σ₂₃] M₃) (p : submodule R M) : map (g.comp f : M →ₛₗ[σ₁₃] M₃) p = map g (map f p) := set_like.coe_injective $ by simp [map_coe]; rw ← image_comp lemma map_mono {f : M →ₛₗ[σ₁₂] M₂} {p p' : submodule R M} : p ≤ p' → map f p ≤ map f p' := image_subset _ @[simp] lemma map_zero : map (0 : M →ₛₗ[σ₁₂] M₂) p = ⊥ := have ∃ (x : M), x ∈ p := ⟨0, p.zero_mem⟩, ext $ by simp [this, eq_comm] lemma map_add_le (f g : M →ₛₗ[σ₁₂] M₂) : map (f + g) p ≤ map f p ⊔ map g p := begin rintros x ⟨m, hm, rfl⟩, exact add_mem_sup (mem_map_of_mem hm) (mem_map_of_mem hm), end lemma range_map_nonempty (N : submodule R M) : (set.range (λ ϕ, submodule.map ϕ N : (M →ₛₗ[σ₁₂] M₂) → submodule R₂ M₂)).nonempty := ⟨_, set.mem_range.mpr ⟨0, rfl⟩⟩ end include σ₂₁ /-- The pushforward of a submodule by an injective linear map is linearly equivalent to the original submodule. -/ noncomputable def equiv_map_of_injective (f : M →ₛₗ[σ₁₂] M₂) (i : injective f) (p : submodule R M) : p ≃ₛₗ[σ₁₂] p.map f := { map_add' := by { intros, simp, refl, }, map_smul' := by { intros, simp, refl, }, ..(equiv.set.image f p i) } @[simp] lemma coe_equiv_map_of_injective_apply (f : M →ₛₗ[σ₁₂] M₂) (i : injective f) (p : submodule R M) (x : p) : (equiv_map_of_injective f i p x : M₂) = f x := rfl omit σ₂₁ /-- The pullback of a submodule `p ⊆ M₂` along `f : M → M₂` -/ def comap (f : M →ₛₗ[σ₁₂] M₂) (p : submodule R₂ M₂) : submodule R M := { carrier := f ⁻¹' p, smul_mem' := λ a x h, by simp [p.smul_mem _ h], .. p.to_add_submonoid.comap f.to_add_monoid_hom } @[simp] lemma comap_coe (f : M →ₛₗ[σ₁₂] M₂) (p : submodule R₂ M₂) : (comap f p : set M) = f ⁻¹' p := rfl @[simp] lemma mem_comap {f : M →ₛₗ[σ₁₂] M₂} {p : submodule R₂ M₂} : x ∈ comap f p ↔ f x ∈ p := iff.rfl lemma comap_id : comap linear_map.id p = p := set_like.coe_injective rfl lemma comap_comp (f : M →ₛₗ[σ₁₂] M₂) (g : M₂ →ₛₗ[σ₂₃] M₃) (p : submodule R₃ M₃) : comap (g.comp f : M →ₛₗ[σ₁₃] M₃) p = comap f (comap g p) := rfl lemma comap_mono {f : M →ₛₗ[σ₁₂] M₂} {q q' : submodule R₂ M₂} : q ≤ q' → comap f q ≤ comap f q' := preimage_mono section variables [ring_hom_surjective σ₁₂] lemma map_le_iff_le_comap {f : M →ₛₗ[σ₁₂] M₂} {p : submodule R M} {q : submodule R₂ M₂} : map f p ≤ q ↔ p ≤ comap f q := image_subset_iff lemma gc_map_comap (f : M →ₛₗ[σ₁₂] M₂) : galois_connection (map f) (comap f) | p q := map_le_iff_le_comap @[simp] lemma map_bot (f : M →ₛₗ[σ₁₂] M₂) : map f ⊥ = ⊥ := (gc_map_comap f).l_bot @[simp] lemma map_sup (f : M →ₛₗ[σ₁₂] M₂) : map f (p ⊔ p') = map f p ⊔ map f p' := (gc_map_comap f).l_sup @[simp] lemma map_supr {ι : Sort*} (f : M →ₛₗ[σ₁₂] M₂) (p : ι → submodule R M) : map f (⨆i, p i) = (⨆i, map f (p i)) := (gc_map_comap f).l_supr end @[simp] lemma comap_top (f : M →ₛₗ[σ₁₂] M₂) : comap f ⊤ = ⊤ := rfl @[simp] lemma comap_inf (f : M →ₛₗ[σ₁₂] M₂) : comap f (q ⊓ q') = comap f q ⊓ comap f q' := rfl @[simp] lemma comap_infi [ring_hom_surjective σ₁₂] {ι : Sort*} (f : M →ₛₗ[σ₁₂] M₂) (p : ι → submodule R₂ M₂) : comap f (⨅i, p i) = (⨅i, comap f (p i)) := (gc_map_comap f).u_infi @[simp] lemma comap_zero : comap (0 : M →ₛₗ[σ₁₂] M₂) q = ⊤ := ext $ by simp lemma map_comap_le [ring_hom_surjective σ₁₂] (f : M →ₛₗ[σ₁₂] M₂) (q : submodule R₂ M₂) : map f (comap f q) ≤ q := (gc_map_comap f).l_u_le _ lemma le_comap_map [ring_hom_surjective σ₁₂] (f : M →ₛₗ[σ₁₂] M₂) (p : submodule R M) : p ≤ comap f (map f p) := (gc_map_comap f).le_u_l _ section galois_insertion variables {f : M →ₛₗ[σ₁₂] M₂} (hf : surjective f) variables [ring_hom_surjective σ₁₂] include hf /-- `map f` and `comap f` form a `galois_insertion` when `f` is surjective. -/ def gi_map_comap : galois_insertion (map f) (comap f) := (gc_map_comap f).to_galois_insertion (λ S x hx, begin rcases hf x with ⟨y, rfl⟩, simp only [mem_map, mem_comap], exact ⟨y, hx, rfl⟩ end) lemma map_comap_eq_of_surjective (p : submodule R₂ M₂) : (p.comap f).map f = p := (gi_map_comap hf).l_u_eq _ lemma map_surjective_of_surjective : function.surjective (map f) := (gi_map_comap hf).l_surjective lemma comap_injective_of_surjective : function.injective (comap f) := (gi_map_comap hf).u_injective lemma map_sup_comap_of_surjective (p q : submodule R₂ M₂) : (p.comap f ⊔ q.comap f).map f = p ⊔ q := (gi_map_comap hf).l_sup_u _ _ lemma map_supr_comap_of_sujective (S : ι → submodule R₂ M₂) : (⨆ i, (S i).comap f).map f = supr S := (gi_map_comap hf).l_supr_u _ lemma map_inf_comap_of_surjective (p q : submodule R₂ M₂) : (p.comap f ⊓ q.comap f).map f = p ⊓ q := (gi_map_comap hf).l_inf_u _ _ lemma map_infi_comap_of_surjective (S : ι → submodule R₂ M₂) : (⨅ i, (S i).comap f).map f = infi S := (gi_map_comap hf).l_infi_u _ lemma comap_le_comap_iff_of_surjective (p q : submodule R₂ M₂) : p.comap f ≤ q.comap f ↔ p ≤ q := (gi_map_comap hf).u_le_u_iff lemma comap_strict_mono_of_surjective : strict_mono (comap f) := (gi_map_comap hf).strict_mono_u end galois_insertion section galois_coinsertion variables [ring_hom_surjective σ₁₂] {f : M →ₛₗ[σ₁₂] M₂} (hf : injective f) include hf /-- `map f` and `comap f` form a `galois_coinsertion` when `f` is injective. -/ def gci_map_comap : galois_coinsertion (map f) (comap f) := (gc_map_comap f).to_galois_coinsertion (λ S x, by simp [mem_comap, mem_map, hf.eq_iff]) lemma comap_map_eq_of_injective (p : submodule R M) : (p.map f).comap f = p := (gci_map_comap hf).u_l_eq _ lemma comap_surjective_of_injective : function.surjective (comap f) := (gci_map_comap hf).u_surjective lemma map_injective_of_injective : function.injective (map f) := (gci_map_comap hf).l_injective lemma comap_inf_map_of_injective (p q : submodule R M) : (p.map f ⊓ q.map f).comap f = p ⊓ q := (gci_map_comap hf).u_inf_l _ _ lemma comap_infi_map_of_injective (S : ι → submodule R M) : (⨅ i, (S i).map f).comap f = infi S := (gci_map_comap hf).u_infi_l _ lemma comap_sup_map_of_injective (p q : submodule R M) : (p.map f ⊔ q.map f).comap f = p ⊔ q := (gci_map_comap hf).u_sup_l _ _ lemma comap_supr_map_of_injective (S : ι → submodule R M) : (⨆ i, (S i).map f).comap f = supr S := (gci_map_comap hf).u_supr_l _ lemma map_le_map_iff_of_injective (p q : submodule R M) : p.map f ≤ q.map f ↔ p ≤ q := (gci_map_comap hf).l_le_l_iff lemma map_strict_mono_of_injective : strict_mono (map f) := (gci_map_comap hf).strict_mono_l end galois_coinsertion --TODO(Mario): is there a way to prove this from order properties? lemma map_inf_eq_map_inf_comap [ring_hom_surjective σ₁₂] {f : M →ₛₗ[σ₁₂] M₂} {p : submodule R M} {p' : submodule R₂ M₂} : map f p ⊓ p' = map f (p ⊓ comap f p') := le_antisymm (by rintro _ ⟨⟨x, h₁, rfl⟩, h₂⟩; exact ⟨_, ⟨h₁, h₂⟩, rfl⟩) (le_inf (map_mono inf_le_left) (map_le_iff_le_comap.2 inf_le_right)) lemma map_comap_subtype : map p.subtype (comap p.subtype p') = p ⊓ p' := ext $ λ x, ⟨by rintro ⟨⟨_, h₁⟩, h₂, rfl⟩; exact ⟨h₁, h₂⟩, λ ⟨h₁, h₂⟩, ⟨⟨_, h₁⟩, h₂, rfl⟩⟩ lemma eq_zero_of_bot_submodule : ∀(b : (⊥ : submodule R M)), b = 0 | ⟨b', hb⟩ := subtype.eq $ show b' = 0, from (mem_bot R).1 hb section variables (R) /-- The span of a set `s ⊆ M` is the smallest submodule of M that contains `s`. -/ def span (s : set M) : submodule R M := Inf {p | s ⊆ p} end variables {s t : set M} lemma mem_span : x ∈ span R s ↔ ∀ p : submodule R M, s ⊆ p → x ∈ p := mem_bInter_iff lemma subset_span : s ⊆ span R s := λ x h, mem_span.2 $ λ p hp, hp h lemma span_le {p} : span R s ≤ p ↔ s ⊆ p := ⟨subset.trans subset_span, λ ss x h, mem_span.1 h _ ss⟩ lemma span_mono (h : s ⊆ t) : span R s ≤ span R t := span_le.2 $ subset.trans h subset_span lemma span_eq_of_le (h₁ : s ⊆ p) (h₂ : p ≤ span R s) : span R s = p := le_antisymm (span_le.2 h₁) h₂ lemma span_eq : span R (p : set M) = p := span_eq_of_le _ (subset.refl _) subset_span /-- A version of `submodule.span_eq` for when the span is by a smaller ring. -/ @[simp] lemma span_coe_eq_restrict_scalars [semiring S] [has_scalar S R] [module S M] [is_scalar_tower S R M] : span S (p : set M) = p.restrict_scalars S := span_eq (p.restrict_scalars S) lemma map_span [ring_hom_surjective σ₁₂] (f : M →ₛₗ[σ₁₂] M₂) (s : set M) : (span R s).map f = span R₂ (f '' s) := eq.symm $ span_eq_of_le _ (set.image_subset f subset_span) $ map_le_iff_le_comap.2 $ span_le.2 $ λ x hx, subset_span ⟨x, hx, rfl⟩ alias submodule.map_span ← linear_map.map_span lemma map_span_le [ring_hom_surjective σ₁₂] (f : M →ₛₗ[σ₁₂] M₂) (s : set M) (N : submodule R₂ M₂) : map f (span R s) ≤ N ↔ ∀ m ∈ s, f m ∈ N := begin rw [f.map_span, span_le, set.image_subset_iff], exact iff.rfl end alias submodule.map_span_le ← linear_map.map_span_le @[simp] lemma span_insert_zero : span R (insert (0 : M) s) = span R s := begin refine le_antisymm _ (submodule.span_mono (set.subset_insert 0 s)), rw [span_le, set.insert_subset], exact ⟨by simp only [set_like.mem_coe, submodule.zero_mem], submodule.subset_span⟩, end /- See also `span_preimage_eq` below. -/ lemma span_preimage_le (f : M →ₛₗ[σ₁₂] M₂) (s : set M₂) : span R (f ⁻¹' s) ≤ (span R₂ s).comap f := by { rw [span_le, comap_coe], exact preimage_mono (subset_span), } alias submodule.span_preimage_le ← linear_map.span_preimage_le /-- An induction principle for span membership. If `p` holds for 0 and all elements of `s`, and is preserved under addition and scalar multiplication, then `p` holds for all elements of the span of `s`. -/ @[elab_as_eliminator] lemma span_induction {p : M → Prop} (h : x ∈ span R s) (Hs : ∀ x ∈ s, p x) (H0 : p 0) (H1 : ∀ x y, p x → p y → p (x + y)) (H2 : ∀ (a:R) x, p x → p (a • x)) : p x := (@span_le _ _ _ _ _ _ ⟨p, H0, H1, H2⟩).2 Hs h lemma span_nat_eq_add_submonoid_closure (s : set M) : (span ℕ s).to_add_submonoid = add_submonoid.closure s := begin refine eq.symm (add_submonoid.closure_eq_of_le subset_span _), apply add_submonoid.to_nat_submodule.symm.to_galois_connection.l_le _, rw span_le, exact add_submonoid.subset_closure, end @[simp] lemma span_nat_eq (s : add_submonoid M) : (span ℕ (s : set M)).to_add_submonoid = s := by rw [span_nat_eq_add_submonoid_closure, s.closure_eq] lemma span_int_eq_add_subgroup_closure {M : Type*} [add_comm_group M] (s : set M) : (span ℤ s).to_add_subgroup = add_subgroup.closure s := eq.symm $ add_subgroup.closure_eq_of_le _ subset_span $ λ x hx, span_induction hx (λ x hx, add_subgroup.subset_closure hx) (add_subgroup.zero_mem _) (λ _ _, add_subgroup.add_mem _) (λ _ _ _, add_subgroup.zsmul_mem _ ‹_› _) @[simp] lemma span_int_eq {M : Type*} [add_comm_group M] (s : add_subgroup M) : (span ℤ (s : set M)).to_add_subgroup = s := by rw [span_int_eq_add_subgroup_closure, s.closure_eq] section variables (R M) /-- `span` forms a Galois insertion with the coercion from submodule to set. -/ protected def gi : galois_insertion (@span R M _ _ _) coe := { choice := λ s _, span R s, gc := λ s t, span_le, le_l_u := λ s, subset_span, choice_eq := λ s h, rfl } end @[simp] lemma span_empty : span R (∅ : set M) = ⊥ := (submodule.gi R M).gc.l_bot @[simp] lemma span_univ : span R (univ : set M) = ⊤ := eq_top_iff.2 $ set_like.le_def.2 $ subset_span lemma span_union (s t : set M) : span R (s ∪ t) = span R s ⊔ span R t := (submodule.gi R M).gc.l_sup lemma span_Union {ι} (s : ι → set M) : span R (⋃ i, s i) = ⨆ i, span R (s i) := (submodule.gi R M).gc.l_supr lemma span_eq_supr_of_singleton_spans (s : set M) : span R s = ⨆ x ∈ s, span R {x} := by simp only [←span_Union, set.bUnion_of_singleton s] @[simp] theorem coe_supr_of_directed {ι} [hι : nonempty ι] (S : ι → submodule R M) (H : directed (≤) S) : ((supr S : submodule R M) : set M) = ⋃ i, S i := begin refine subset.antisymm _ (Union_subset $ le_supr S), suffices : (span R (⋃ i, (S i : set M)) : set M) ⊆ ⋃ (i : ι), ↑(S i), by simpa only [span_Union, span_eq] using this, refine (λ x hx, span_induction hx (λ _, id) _ _ _); simp only [mem_Union, exists_imp_distrib], { exact hι.elim (λ i, ⟨i, (S i).zero_mem⟩) }, { intros x y i hi j hj, rcases H i j with ⟨k, ik, jk⟩, exact ⟨k, add_mem _ (ik hi) (jk hj)⟩ }, { exact λ a x i hi, ⟨i, smul_mem _ a hi⟩ }, end @[simp] theorem mem_supr_of_directed {ι} [nonempty ι] (S : ι → submodule R M) (H : directed (≤) S) {x} : x ∈ supr S ↔ ∃ i, x ∈ S i := by { rw [← set_like.mem_coe, coe_supr_of_directed S H, mem_Union], refl } theorem mem_Sup_of_directed {s : set (submodule R M)} {z} (hs : s.nonempty) (hdir : directed_on (≤) s) : z ∈ Sup s ↔ ∃ y ∈ s, z ∈ y := begin haveI : nonempty s := hs.to_subtype, simp only [Sup_eq_supr', mem_supr_of_directed _ hdir.directed_coe, set_coe.exists, subtype.coe_mk] end @[norm_cast, simp] lemma coe_supr_of_chain (a : ℕ →ₘ submodule R M) : (↑(⨆ k, a k) : set M) = ⋃ k, (a k : set M) := coe_supr_of_directed a a.monotone.directed_le /-- We can regard `coe_supr_of_chain` as the statement that `coe : (submodule R M) → set M` is Scott continuous for the ω-complete partial order induced by the complete lattice structures. -/ lemma coe_scott_continuous : omega_complete_partial_order.continuous' (coe : submodule R M → set M) := ⟨set_like.coe_mono, coe_supr_of_chain⟩ @[simp] lemma mem_supr_of_chain (a : ℕ →ₘ submodule R M) (m : M) : m ∈ (⨆ k, a k) ↔ ∃ k, m ∈ a k := mem_supr_of_directed a a.monotone.directed_le section variables {p p'} lemma mem_sup : x ∈ p ⊔ p' ↔ ∃ (y ∈ p) (z ∈ p'), y + z = x := ⟨λ h, begin rw [← span_eq p, ← span_eq p', ← span_union] at h, apply span_induction h, { rintro y (h | h), { exact ⟨y, h, 0, by simp, by simp⟩ }, { exact ⟨0, by simp, y, h, by simp⟩ } }, { exact ⟨0, by simp, 0, by simp⟩ }, { rintro _ _ ⟨y₁, hy₁, z₁, hz₁, rfl⟩ ⟨y₂, hy₂, z₂, hz₂, rfl⟩, exact ⟨_, add_mem _ hy₁ hy₂, _, add_mem _ hz₁ hz₂, by simp [add_assoc]; cc⟩ }, { rintro a _ ⟨y, hy, z, hz, rfl⟩, exact ⟨_, smul_mem _ a hy, _, smul_mem _ a hz, by simp [smul_add]⟩ } end, by rintro ⟨y, hy, z, hz, rfl⟩; exact add_mem _ ((le_sup_left : p ≤ p ⊔ p') hy) ((le_sup_right : p' ≤ p ⊔ p') hz)⟩ lemma mem_sup' : x ∈ p ⊔ p' ↔ ∃ (y : p) (z : p'), (y:M) + z = x := mem_sup.trans $ by simp only [set_like.exists, coe_mk] lemma coe_sup : ↑(p ⊔ p') = (p + p' : set M) := by { ext, rw [set_like.mem_coe, mem_sup, set.mem_add], simp, } end /- This is the character `∙`, with escape sequence `\.`, and is thus different from the scalar multiplication character `•`, with escape sequence `\bub`. -/ notation R`∙`:1000 x := span R (@singleton _ _ set.has_singleton x) lemma mem_span_singleton_self (x : M) : x ∈ R ∙ x := subset_span rfl lemma nontrivial_span_singleton {x : M} (h : x ≠ 0) : nontrivial (R ∙ x) := ⟨begin use [0, x, submodule.mem_span_singleton_self x], intros H, rw [eq_comm, submodule.mk_eq_zero] at H, exact h H end⟩ lemma mem_span_singleton {y : M} : x ∈ (R ∙ y) ↔ ∃ a:R, a • y = x := ⟨λ h, begin apply span_induction h, { rintro y (rfl|⟨⟨⟩⟩), exact ⟨1, by simp⟩ }, { exact ⟨0, by simp⟩ }, { rintro _ _ ⟨a, rfl⟩ ⟨b, rfl⟩, exact ⟨a + b, by simp [add_smul]⟩ }, { rintro a _ ⟨b, rfl⟩, exact ⟨a * b, by simp [smul_smul]⟩ } end, by rintro ⟨a, y, rfl⟩; exact smul_mem _ _ (subset_span $ by simp)⟩ lemma le_span_singleton_iff {s : submodule R M} {v₀ : M} : s ≤ (R ∙ v₀) ↔ ∀ v ∈ s, ∃ r : R, r • v₀ = v := by simp_rw [set_like.le_def, mem_span_singleton] lemma span_singleton_eq_top_iff (x : M) : (R ∙ x) = ⊤ ↔ ∀ v, ∃ r : R, r • x = v := begin rw [eq_top_iff, le_span_singleton_iff], finish, end @[simp] lemma span_zero_singleton : (R ∙ (0:M)) = ⊥ := by { ext, simp [mem_span_singleton, eq_comm] } lemma span_singleton_eq_range (y : M) : ↑(R ∙ y) = range ((• y) : R → M) := set.ext $ λ x, mem_span_singleton lemma span_singleton_smul_le (r : R) (x : M) : (R ∙ (r • x)) ≤ R ∙ x := begin rw [span_le, set.singleton_subset_iff, set_like.mem_coe], exact smul_mem _ _ (mem_span_singleton_self _) end lemma span_singleton_smul_eq {K E : Type*} [division_ring K] [add_comm_group E] [module K E] {r : K} (x : E) (hr : r ≠ 0) : (K ∙ (r • x)) = K ∙ x := begin refine le_antisymm (span_singleton_smul_le r x) _, convert span_singleton_smul_le r⁻¹ (r • x), exact (inv_smul_smul₀ hr _).symm end lemma disjoint_span_singleton {K E : Type*} [division_ring K] [add_comm_group E] [module K E] {s : submodule K E} {x : E} : disjoint s (K ∙ x) ↔ (x ∈ s → x = 0) := begin refine disjoint_def.trans ⟨λ H hx, H x hx $ subset_span $ mem_singleton x, _⟩, assume H y hy hyx, obtain ⟨c, hc⟩ := mem_span_singleton.1 hyx, subst y, classical, by_cases hc : c = 0, by simp only [hc, zero_smul], rw [s.smul_mem_iff hc] at hy, rw [H hy, smul_zero] end lemma disjoint_span_singleton' {K E : Type*} [division_ring K] [add_comm_group E] [module K E] {p : submodule K E} {x : E} (x0 : x ≠ 0) : disjoint p (K ∙ x) ↔ x ∉ p := disjoint_span_singleton.trans ⟨λ h₁ h₂, x0 (h₁ h₂), λ h₁ h₂, (h₁ h₂).elim⟩ lemma mem_span_insert {y} : x ∈ span R (insert y s) ↔ ∃ (a:R) (z ∈ span R s), x = a • y + z := begin simp only [← union_singleton, span_union, mem_sup, mem_span_singleton, exists_prop, exists_exists_eq_and], rw [exists_comm], simp only [eq_comm, add_comm, exists_and_distrib_left] end lemma span_insert (x) (s : set M) : span R (insert x s) = span R ({x} : set M) ⊔ span R s := by rw [insert_eq, span_union] lemma span_insert_eq_span (h : x ∈ span R s) : span R (insert x s) = span R s := span_eq_of_le _ (set.insert_subset.mpr ⟨h, subset_span⟩) (span_mono $ subset_insert _ _) lemma span_span : span R (span R s : set M) = span R s := span_eq _ variables (R S s) /-- If `R` is "smaller" ring than `S` then the span by `R` is smaller than the span by `S`. -/ lemma span_le_restrict_scalars [semiring S] [has_scalar R S] [module S M] [is_scalar_tower R S M] : span R s ≤ (span S s).restrict_scalars R := submodule.span_le.2 submodule.subset_span /-- A version of `submodule.span_le_restrict_scalars` with coercions. -/ @[simp] lemma span_subset_span [semiring S] [has_scalar R S] [module S M] [is_scalar_tower R S M] : ↑(span R s) ⊆ (span S s : set M) := span_le_restrict_scalars R S s /-- Taking the span by a large ring of the span by the small ring is the same as taking the span by just the large ring. -/ lemma span_span_of_tower [semiring S] [has_scalar R S] [module S M] [is_scalar_tower R S M] : span S (span R s : set M) = span S s := le_antisymm (span_le.2 $ span_subset_span R S s) (span_mono subset_span) variables {R S s} lemma span_eq_bot : span R (s : set M) = ⊥ ↔ ∀ x ∈ s, (x:M) = 0 := eq_bot_iff.trans ⟨ λ H x h, (mem_bot R).1 $ H $ subset_span h, λ H, span_le.2 (λ x h, (mem_bot R).2 $ H x h)⟩ @[simp] lemma span_singleton_eq_bot : (R ∙ x) = ⊥ ↔ x = 0 := span_eq_bot.trans $ by simp @[simp] lemma span_zero : span R (0 : set M) = ⊥ := by rw [←singleton_zero, span_singleton_eq_bot] @[simp] lemma span_image [ring_hom_surjective σ₁₂] (f : M →ₛₗ[σ₁₂] M₂) : span R₂ (f '' s) = map f (span R s) := (map_span f s).symm lemma apply_mem_span_image_of_mem_span [ring_hom_surjective σ₁₂] (f : M →ₛₗ[σ₁₂] M₂) {x : M} {s : set M} (h : x ∈ submodule.span R s) : f x ∈ submodule.span R₂ (f '' s) := begin rw submodule.span_image, exact submodule.mem_map_of_mem h end /-- `f` is an explicit argument so we can `apply` this theorem and obtain `h` as a new goal. -/ lemma not_mem_span_of_apply_not_mem_span_image [ring_hom_surjective σ₁₂] (f : M →ₛₗ[σ₁₂] M₂) {x : M} {s : set M} (h : f x ∉ submodule.span R₂ (f '' s)) : x ∉ submodule.span R s := h.imp (apply_mem_span_image_of_mem_span f) lemma supr_eq_span {ι : Sort*} (p : ι → submodule R M) : (⨆ (i : ι), p i) = submodule.span R (⋃ (i : ι), ↑(p i)) := le_antisymm (supr_le $ assume i, subset.trans (assume m hm, set.mem_Union.mpr ⟨i, hm⟩) subset_span) (span_le.mpr $ Union_subset_iff.mpr $ assume i m hm, mem_supr_of_mem i hm) lemma span_singleton_le_iff_mem (m : M) (p : submodule R M) : (R ∙ m) ≤ p ↔ m ∈ p := by rw [span_le, singleton_subset_iff, set_like.mem_coe] lemma singleton_span_is_compact_element (x : M) : complete_lattice.is_compact_element (span R {x} : submodule R M) := begin rw complete_lattice.is_compact_element_iff_le_of_directed_Sup_le, intros d hemp hdir hsup, have : x ∈ Sup d, from (set_like.le_def.mp hsup) (mem_span_singleton_self x), obtain ⟨y, ⟨hyd, hxy⟩⟩ := (mem_Sup_of_directed hemp hdir).mp this, exact ⟨y, ⟨hyd, by simpa only [span_le, singleton_subset_iff]⟩⟩, end instance : is_compactly_generated (submodule R M) := ⟨λ s, ⟨(λ x, span R {x}) '' s, ⟨λ t ht, begin rcases (set.mem_image _ _ _).1 ht with ⟨x, hx, rfl⟩, apply singleton_span_is_compact_element, end, by rw [Sup_eq_supr, supr_image, ←span_eq_supr_of_singleton_spans, span_eq]⟩⟩⟩ lemma lt_sup_iff_not_mem {I : submodule R M} {a : M} : I < I ⊔ (R ∙ a) ↔ a ∉ I := begin split, { intro h, by_contra akey, have h1 : I ⊔ (R ∙ a) ≤ I, { simp only [sup_le_iff], split, { exact le_refl I, }, { exact (span_singleton_le_iff_mem a I).mpr akey, } }, have h2 := gt_of_ge_of_gt h1 h, exact lt_irrefl I h2, }, { intro h, apply set_like.lt_iff_le_and_exists.mpr, split, simp only [le_sup_left], use a, split, swap, { assumption, }, { have : (R ∙ a) ≤ I ⊔ (R ∙ a) := le_sup_right, exact this (mem_span_singleton_self a), } }, end lemma mem_supr {ι : Sort*} (p : ι → submodule R M) {m : M} : (m ∈ ⨆ i, p i) ↔ (∀ N, (∀ i, p i ≤ N) → m ∈ N) := begin rw [← span_singleton_le_iff_mem, le_supr_iff], simp only [span_singleton_le_iff_mem], end section open_locale classical /-- For every element in the span of a set, there exists a finite subset of the set such that the element is contained in the span of the subset. -/ lemma mem_span_finite_of_mem_span {S : set M} {x : M} (hx : x ∈ span R S) : ∃ T : finset M, ↑T ⊆ S ∧ x ∈ span R (T : set M) := begin refine span_induction hx (λ x hx, _) _ _ _, { refine ⟨{x}, _, _⟩, { rwa [finset.coe_singleton, set.singleton_subset_iff] }, { rw finset.coe_singleton, exact submodule.mem_span_singleton_self x } }, { use ∅, simp }, { rintros x y ⟨X, hX, hxX⟩ ⟨Y, hY, hyY⟩, refine ⟨X ∪ Y, _, _⟩, { rw finset.coe_union, exact set.union_subset hX hY }, rw [finset.coe_union, span_union, mem_sup], exact ⟨x, hxX, y, hyY, rfl⟩, }, { rintros a x ⟨T, hT, h2⟩, exact ⟨T, hT, smul_mem _ _ h2⟩ } end end /-- The product of two submodules is a submodule. -/ def prod : submodule R (M × M') := { carrier := set.prod p q₁, smul_mem' := by rintro a ⟨x, y⟩ ⟨hx, hy⟩; exact ⟨smul_mem _ a hx, smul_mem _ a hy⟩, .. p.to_add_submonoid.prod q₁.to_add_submonoid } @[simp] lemma prod_coe : (prod p q₁ : set (M × M')) = set.prod p q₁ := rfl @[simp] lemma mem_prod {p : submodule R M} {q : submodule R M'} {x : M × M'} : x ∈ prod p q ↔ x.1 ∈ p ∧ x.2 ∈ q := set.mem_prod lemma span_prod_le (s : set M) (t : set M') : span R (set.prod s t) ≤ prod (span R s) (span R t) := span_le.2 $ set.prod_mono subset_span subset_span @[simp] lemma prod_top : (prod ⊤ ⊤ : submodule R (M × M')) = ⊤ := by ext; simp @[simp] lemma prod_bot : (prod ⊥ ⊥ : submodule R (M × M')) = ⊥ := by ext ⟨x, y⟩; simp [prod.zero_eq_mk] lemma prod_mono {p p' : submodule R M} {q q' : submodule R M'} : p ≤ p' → q ≤ q' → prod p q ≤ prod p' q' := prod_mono @[simp] lemma prod_inf_prod : prod p q₁ ⊓ prod p' q₁' = prod (p ⊓ p') (q₁ ⊓ q₁') := set_like.coe_injective set.prod_inter_prod @[simp] lemma prod_sup_prod : prod p q₁ ⊔ prod p' q₁' = prod (p ⊔ p') (q₁ ⊔ q₁') := begin refine le_antisymm (sup_le (prod_mono le_sup_left le_sup_left) (prod_mono le_sup_right le_sup_right)) _, simp [set_like.le_def], intros xx yy hxx hyy, rcases mem_sup.1 hxx with ⟨x, hx, x', hx', rfl⟩, rcases mem_sup.1 hyy with ⟨y, hy, y', hy', rfl⟩, refine mem_sup.2 ⟨(x, y), ⟨hx, hy⟩, (x', y'), ⟨hx', hy'⟩, rfl⟩ end end add_comm_monoid variables [ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [module R M] [module R M₂] [module R M₃] variables (p p' : submodule R M) (q q' : submodule R M₂) variables {r : R} {x y : M} open set @[simp] lemma neg_coe : -(p : set M) = p := set.ext $ λ x, p.neg_mem_iff @[simp] protected lemma map_neg (f : M →ₗ[R] M₂) : map (-f) p = map f p := ext $ λ y, ⟨λ ⟨x, hx, hy⟩, hy ▸ ⟨-x, neg_mem _ hx, f.map_neg x⟩, λ ⟨x, hx, hy⟩, hy ▸ ⟨-x, neg_mem _ hx, ((-f).map_neg _).trans (neg_neg (f x))⟩⟩ @[simp] lemma span_neg (s : set M) : span R (-s) = span R s := calc span R (-s) = span R ((-linear_map.id : M →ₗ[R] M) '' s) : by simp ... = map (-linear_map.id) (span R s) : ((-linear_map.id).map_span _).symm ... = span R s : by simp lemma mem_span_insert' {y} {s : set M} : x ∈ span R (insert y s) ↔ ∃(a:R), x + a • y ∈ span R s := begin rw mem_span_insert, split, { rintro ⟨a, z, hz, rfl⟩, exact ⟨-a, by simp [hz, add_assoc]⟩ }, { rintro ⟨a, h⟩, exact ⟨-a, _, h, by simp [add_comm, add_left_comm]⟩ } end end submodule namespace submodule variables [field K] variables [add_comm_group V] [module K V] variables [add_comm_group V₂] [module K V₂] lemma comap_smul (f : V →ₗ[K] V₂) (p : submodule K V₂) (a : K) (h : a ≠ 0) : p.comap (a • f) = p.comap f := by ext b; simp only [submodule.mem_comap, p.smul_mem_iff h, linear_map.smul_apply] lemma map_smul (f : V →ₗ[K] V₂) (p : submodule K V) (a : K) (h : a ≠ 0) : p.map (a • f) = p.map f := le_antisymm begin rw [map_le_iff_le_comap, comap_smul f _ a h, ← map_le_iff_le_comap], exact le_refl _ end begin rw [map_le_iff_le_comap, ← comap_smul f _ a h, ← map_le_iff_le_comap], exact le_refl _ end lemma comap_smul' (f : V →ₗ[K] V₂) (p : submodule K V₂) (a : K) : p.comap (a • f) = (⨅ h : a ≠ 0, p.comap f) := by classical; by_cases a = 0; simp [h, comap_smul] lemma map_smul' (f : V →ₗ[K] V₂) (p : submodule K V) (a : K) : p.map (a • f) = (⨆ h : a ≠ 0, p.map f) := by classical; by_cases a = 0; simp [h, map_smul] end submodule /-! ### Properties of linear maps -/ namespace linear_map section add_comm_monoid variables [semiring R] [semiring R₂] [semiring R₃] variables [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] variables {σ₁₂ : R →+* R₂} {σ₂₃ : R₂ →+* R₃} {σ₁₃ : R →+* R₃} variables [ring_hom_comp_triple σ₁₂ σ₂₃ σ₁₃] variables [module R M] [module R₂ M₂] [module R₃ M₃] include R open submodule /-- If two linear maps are equal on a set `s`, then they are equal on `submodule.span s`. See also `linear_map.eq_on_span'` for a version using `set.eq_on`. -/ lemma eq_on_span {s : set M} {f g : M →ₛₗ[σ₁₂] M₂} (H : set.eq_on f g s) ⦃x⦄ (h : x ∈ span R s) : f x = g x := by apply span_induction h H; simp {contextual := tt} /-- If two linear maps are equal on a set `s`, then they are equal on `submodule.span s`. This version uses `set.eq_on`, and the hidden argument will expand to `h : x ∈ (span R s : set M)`. See `linear_map.eq_on_span` for a version that takes `h : x ∈ span R s` as an argument. -/ lemma eq_on_span' {s : set M} {f g : M →ₛₗ[σ₁₂] M₂} (H : set.eq_on f g s) : set.eq_on f g (span R s : set M) := eq_on_span H /-- If `s` generates the whole module and linear maps `f`, `g` are equal on `s`, then they are equal. -/ lemma ext_on {s : set M} {f g : M →ₛₗ[σ₁₂] M₂} (hv : span R s = ⊤) (h : set.eq_on f g s) : f = g := linear_map.ext (λ x, eq_on_span h (eq_top_iff'.1 hv _)) /-- If the range of `v : ι → M` generates the whole module and linear maps `f`, `g` are equal at each `v i`, then they are equal. -/ lemma ext_on_range {v : ι → M} {f g : M →ₛₗ[σ₁₂] M₂} (hv : span R (set.range v) = ⊤) (h : ∀i, f (v i) = g (v i)) : f = g := ext_on hv (set.forall_range_iff.2 h) section finsupp variables {γ : Type*} [has_zero γ] @[simp] lemma map_finsupp_sum (f : M →ₛₗ[σ₁₂] M₂) {t : ι →₀ γ} {g : ι → γ → M} : f (t.sum g) = t.sum (λ i d, f (g i d)) := f.map_sum lemma coe_finsupp_sum (t : ι →₀ γ) (g : ι → γ → M →ₛₗ[σ₁₂] M₂) : ⇑(t.sum g) = t.sum (λ i d, g i d) := coe_fn_sum _ _ @[simp] lemma finsupp_sum_apply (t : ι →₀ γ) (g : ι → γ → M →ₛₗ[σ₁₂] M₂) (b : M) : (t.sum g) b = t.sum (λ i d, g i d b) := sum_apply _ _ _ end finsupp section dfinsupp open dfinsupp variables {γ : ι → Type*} [decidable_eq ι] section sum variables [Π i, has_zero (γ i)] [Π i (x : γ i), decidable (x ≠ 0)] @[simp] lemma map_dfinsupp_sum (f : M →ₛₗ[σ₁₂] M₂) {t : Π₀ i, γ i} {g : Π i, γ i → M} : f (t.sum g) = t.sum (λ i d, f (g i d)) := f.map_sum lemma coe_dfinsupp_sum (t : Π₀ i, γ i) (g : Π i, γ i → M →ₛₗ[σ₁₂] M₂) : ⇑(t.sum g) = t.sum (λ i d, g i d) := coe_fn_sum _ _ @[simp] lemma dfinsupp_sum_apply (t : Π₀ i, γ i) (g : Π i, γ i → M →ₛₗ[σ₁₂] M₂) (b : M) : (t.sum g) b = t.sum (λ i d, g i d b) := sum_apply _ _ _ end sum section sum_add_hom variables [Π i, add_zero_class (γ i)] @[simp] lemma map_dfinsupp_sum_add_hom (f : M →ₛₗ[σ₁₂] M₂) {t : Π₀ i, γ i} {g : Π i, γ i →+ M} : f (sum_add_hom g t) = sum_add_hom (λ i, f.to_add_monoid_hom.comp (g i)) t := f.to_add_monoid_hom.map_dfinsupp_sum_add_hom _ _ end sum_add_hom end dfinsupp variables {σ₂₁ : R₂ →+* R} {τ₁₂ : R →+* R₂} {τ₂₃ : R₂ →+* R₃} {τ₁₃ : R →+* R₃} variables [ring_hom_comp_triple τ₁₂ τ₂₃ τ₁₃] theorem map_cod_restrict [ring_hom_surjective σ₂₁] (p : submodule R M) (f : M₂ →ₛₗ[σ₂₁] M) (h p') : submodule.map (cod_restrict p f h) p' = comap p.subtype (p'.map f) := submodule.ext $ λ ⟨x, hx⟩, by simp [subtype.ext_iff_val] theorem comap_cod_restrict (p : submodule R M) (f : M₂ →ₛₗ[σ₂₁] M) (hf p') : submodule.comap (cod_restrict p f hf) p' = submodule.comap f (map p.subtype p') := submodule.ext $ λ x, ⟨λ h, ⟨⟨_, hf x⟩, h, rfl⟩, by rintro ⟨⟨_, _⟩, h, ⟨⟩⟩; exact h⟩ section /-- The range of a linear map `f : M → M₂` is a submodule of `M₂`. See Note [range copy pattern]. -/ def range [ring_hom_surjective τ₁₂] (f : M →ₛₗ[τ₁₂] M₂) : submodule R₂ M₂ := (map f ⊤).copy (set.range f) set.image_univ.symm theorem range_coe [ring_hom_surjective τ₁₂] (f : M →ₛₗ[τ₁₂] M₂) : (range f : set M₂) = set.range f := rfl @[simp] theorem mem_range [ring_hom_surjective τ₁₂] {f : M →ₛₗ[τ₁₂] M₂} {x} : x ∈ range f ↔ ∃ y, f y = x := iff.rfl lemma range_eq_map [ring_hom_surjective τ₁₂] (f : M →ₛₗ[τ₁₂] M₂) : f.range = map f ⊤ := by { ext, simp } theorem mem_range_self [ring_hom_surjective τ₁₂] (f : M →ₛₗ[τ₁₂] M₂) (x : M) : f x ∈ f.range := ⟨x, rfl⟩ @[simp] theorem range_id : range (linear_map.id : M →ₗ[R] M) = ⊤ := set_like.coe_injective set.range_id theorem range_comp [ring_hom_surjective τ₁₂] [ring_hom_surjective τ₂₃] [ring_hom_surjective τ₁₃] (f : M →ₛₗ[τ₁₂] M₂) (g : M₂ →ₛₗ[τ₂₃] M₃) : range (g.comp f : M →ₛₗ[τ₁₃] M₃) = map g (range f) := set_like.coe_injective (set.range_comp g f) theorem range_comp_le_range [ring_hom_surjective τ₂₃] [ring_hom_surjective τ₁₃] (f : M →ₛₗ[τ₁₂] M₂) (g : M₂ →ₛₗ[τ₂₃] M₃) : range (g.comp f : M →ₛₗ[τ₁₃] M₃) ≤ range g := set_like.coe_mono (set.range_comp_subset_range f g) theorem range_eq_top [ring_hom_surjective τ₁₂] {f : M →ₛₗ[τ₁₂] M₂} : range f = ⊤ ↔ surjective f := by rw [set_like.ext'_iff, range_coe, top_coe, set.range_iff_surjective] lemma range_le_iff_comap [ring_hom_surjective τ₁₂] {f : M →ₛₗ[τ₁₂] M₂} {p : submodule R₂ M₂} : range f ≤ p ↔ comap f p = ⊤ := by rw [range_eq_map, map_le_iff_le_comap, eq_top_iff] lemma map_le_range [ring_hom_surjective τ₁₂] {f : M →ₛₗ[τ₁₂] M₂} {p : submodule R M} : map f p ≤ range f := set_like.coe_mono (set.image_subset_range f p) end /-- The decreasing sequence of submodules consisting of the ranges of the iterates of a linear map. -/ @[simps] def iterate_range (f : M →ₗ[R] M) : ℕ →ₘ order_dual (submodule R M) := ⟨λ n, (f ^ n).range, λ n m w x h, begin obtain ⟨c, rfl⟩ := le_iff_exists_add.mp w, rw linear_map.mem_range at h, obtain ⟨m, rfl⟩ := h, rw linear_map.mem_range, use (f ^ c) m, rw [pow_add, linear_map.mul_apply], end⟩ /-- Restrict the codomain of a linear map `f` to `f.range`. This is the bundled version of `set.range_factorization`. -/ @[reducible] def range_restrict [ring_hom_surjective τ₁₂] (f : M →ₛₗ[τ₁₂] M₂) : M →ₛₗ[τ₁₂] f.range := f.cod_restrict f.range f.mem_range_self --set_option trace.class_instances true /-- The range of a linear map is finite if the domain is finite. Note: this instance can form a diamond with `subtype.fintype` in the presence of `fintype M₂`. -/ instance fintype_range [fintype M] [decidable_eq M₂] [ring_hom_surjective τ₁₂] (f : M →ₛₗ[τ₁₂] M₂) : fintype (range f) := set.fintype_range f section variables (R) (M) /-- Given an element `x` of a module `M` over `R`, the natural map from `R` to scalar multiples of `x`.-/ @[simps] def to_span_singleton (x : M) : R →ₗ[R] M := linear_map.id.smul_right x /-- The range of `to_span_singleton x` is the span of `x`.-/ lemma span_singleton_eq_range (x : M) : (R ∙ x) = (to_span_singleton R M x).range := submodule.ext $ λ y, by {refine iff.trans _ mem_range.symm, exact mem_span_singleton } lemma to_span_singleton_one (x : M) : to_span_singleton R M x 1 = x := one_smul _ _ end /-- The kernel of a linear map `f : M → M₂` is defined to be `comap f ⊥`. This is equivalent to the set of `x : M` such that `f x = 0`. The kernel is a submodule of `M`. -/ def ker (f : M →ₛₗ[τ₁₂] M₂) : submodule R M := comap f ⊥ @[simp] theorem mem_ker {f : M →ₛₗ[τ₁₂] M₂} {y} : y ∈ ker f ↔ f y = 0 := mem_bot R₂ @[simp] theorem ker_id : ker (linear_map.id : M →ₗ[R] M) = ⊥ := rfl @[simp] theorem map_coe_ker (f : M →ₛₗ[τ₁₂] M₂) (x : ker f) : f x = 0 := mem_ker.1 x.2 lemma comp_ker_subtype (f : M →ₛₗ[τ₁₂] M₂) : f.comp f.ker.subtype = 0 := linear_map.ext $ λ x, suffices f x = 0, by simp [this], mem_ker.1 x.2 theorem ker_comp (f : M →ₛₗ[τ₁₂] M₂) (g : M₂ →ₛₗ[τ₂₃] M₃) : ker (g.comp f : M →ₛₗ[τ₁₃] M₃) = comap f (ker g) := rfl theorem ker_le_ker_comp (f : M →ₛₗ[τ₁₂] M₂) (g : M₂ →ₛₗ[τ₂₃] M₃) : ker f ≤ ker (g.comp f : M →ₛₗ[τ₁₃] M₃) := by rw ker_comp; exact comap_mono bot_le theorem disjoint_ker {f : M →ₛₗ[τ₁₂] M₂} {p : submodule R M} : disjoint p (ker f) ↔ ∀ x ∈ p, f x = 0 → x = 0 := by simp [disjoint_def] theorem ker_eq_bot' {f : M →ₛₗ[τ₁₂] M₂} : ker f = ⊥ ↔ (∀ m, f m = 0 → m = 0) := by simpa [disjoint] using @disjoint_ker _ _ _ _ _ _ _ _ _ _ _ f ⊤ theorem ker_eq_bot_of_inverse {τ₂₁ : R₂ →+* R} [ring_hom_inv_pair τ₁₂ τ₂₁] {f : M →ₛₗ[τ₁₂] M₂} {g : M₂ →ₛₗ[τ₂₁] M} (h : (g.comp f : M →ₗ[R] M) = id) : ker f = ⊥ := ker_eq_bot'.2 $ λ m hm, by rw [← id_apply m, ← h, comp_apply, hm, g.map_zero] lemma le_ker_iff_map [ring_hom_surjective τ₁₂] {f : M →ₛₗ[τ₁₂] M₂} {p : submodule R M} : p ≤ ker f ↔ map f p = ⊥ := by rw [ker, eq_bot_iff, map_le_iff_le_comap] lemma ker_cod_restrict {τ₂₁ : R₂ →+* R} (p : submodule R M) (f : M₂ →ₛₗ[τ₂₁] M) (hf) : ker (cod_restrict p f hf) = ker f := by rw [ker, comap_cod_restrict, map_bot]; refl lemma range_cod_restrict {τ₂₁ : R₂ →+* R} [ring_hom_surjective τ₂₁] (p : submodule R M) (f : M₂ →ₛₗ[τ₂₁] M) (hf) : range (cod_restrict p f hf) = comap p.subtype f.range := by simpa only [range_eq_map] using map_cod_restrict _ _ _ _ lemma ker_restrict {p : submodule R M} {f : M →ₗ[R] M} (hf : ∀ x : M, x ∈ p → f x ∈ p) : ker (f.restrict hf) = (f.dom_restrict p).ker := by rw [restrict_eq_cod_restrict_dom_restrict, ker_cod_restrict] lemma _root_.submodule.map_comap_eq [ring_hom_surjective τ₁₂] (f : M →ₛₗ[τ₁₂] M₂) (q : submodule R₂ M₂) : map f (comap f q) = range f ⊓ q := le_antisymm (le_inf map_le_range (map_comap_le _ _)) $ by rintro _ ⟨⟨x, _, rfl⟩, hx⟩; exact ⟨x, hx, rfl⟩ lemma _root_.submodule.map_comap_eq_self [ring_hom_surjective τ₁₂] {f : M →ₛₗ[τ₁₂] M₂} {q : submodule R₂ M₂} (h : q ≤ range f) : map f (comap f q) = q := by rwa [submodule.map_comap_eq, inf_eq_right] @[simp] theorem ker_zero : ker (0 : M →ₛₗ[τ₁₂] M₂) = ⊤ := eq_top_iff'.2 $ λ x, by simp @[simp] theorem range_zero [ring_hom_surjective τ₁₂] : range (0 : M →ₛₗ[τ₁₂] M₂) = ⊥ := by simpa only [range_eq_map] using submodule.map_zero _ theorem ker_eq_top {f : M →ₛₗ[τ₁₂] M₂} : ker f = ⊤ ↔ f = 0 := ⟨λ h, ext $ λ x, mem_ker.1 $ h.symm ▸ trivial, λ h, h.symm ▸ ker_zero⟩ section variables [ring_hom_surjective τ₁₂] lemma range_le_bot_iff (f : M →ₛₗ[τ₁₂] M₂) : range f ≤ ⊥ ↔ f = 0 := by rw [range_le_iff_comap]; exact ker_eq_top theorem range_eq_bot {f : M →ₛₗ[τ₁₂] M₂} : range f = ⊥ ↔ f = 0 := by rw [← range_le_bot_iff, le_bot_iff] lemma range_le_ker_iff {f : M →ₛₗ[τ₁₂] M₂} {g : M₂ →ₛₗ[τ₂₃] M₃} : range f ≤ ker g ↔ (g.comp f : M →ₛₗ[τ₁₃] M₃) = 0 := ⟨λ h, ker_eq_top.1 $ eq_top_iff'.2 $ λ x, h $ ⟨_, rfl⟩, λ h x hx, mem_ker.2 $ exists.elim hx $ λ y hy, by rw [←hy, ←comp_apply, h, zero_apply]⟩ theorem comap_le_comap_iff {f : M →ₛₗ[τ₁₂] M₂} (hf : range f = ⊤) {p p'} : comap f p ≤ comap f p' ↔ p ≤ p' := ⟨λ H x hx, by rcases range_eq_top.1 hf x with ⟨y, hy, rfl⟩; exact H hx, comap_mono⟩ theorem comap_injective {f : M →ₛₗ[τ₁₂] M₂} (hf : range f = ⊤) : injective (comap f) := λ p p' h, le_antisymm ((comap_le_comap_iff hf).1 (le_of_eq h)) ((comap_le_comap_iff hf).1 (ge_of_eq h)) end theorem ker_eq_bot_of_injective {f : M →ₛₗ[τ₁₂] M₂} (hf : injective f) : ker f = ⊥ := begin have : disjoint ⊤ f.ker, by { rw [disjoint_ker, ← map_zero f], exact λ x hx H, hf H }, simpa [disjoint] end /-- The increasing sequence of submodules consisting of the kernels of the iterates of a linear map. -/ @[simps] def iterate_ker (f : M →ₗ[R] M) : ℕ →ₘ submodule R M := ⟨λ n, (f ^ n).ker, λ n m w x h, begin obtain ⟨c, rfl⟩ := le_iff_exists_add.mp w, rw linear_map.mem_ker at h, rw [linear_map.mem_ker, add_comm, pow_add, linear_map.mul_apply, h, linear_map.map_zero], end⟩ end add_comm_monoid section add_comm_group variables [semiring R] [semiring R₂] [semiring R₃] variables [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [module R M] [module R₂ M₂] [module R₃ M₃] variables {τ₁₂ : R →+* R₂} {τ₂₃ : R₂ →+* R₃} {τ₁₃ : R →+* R₃} variables [ring_hom_comp_triple τ₁₂ τ₂₃ τ₁₃] [ring_hom_surjective τ₁₂] include R open submodule lemma _root_.submodule.comap_map_eq (f : M →ₛₗ[τ₁₂] M₂) (p : submodule R M) : comap f (map f p) = p ⊔ ker f := begin refine le_antisymm _ (sup_le (le_comap_map _ _) (comap_mono bot_le)), rintro x ⟨y, hy, e⟩, exact mem_sup.2 ⟨y, hy, x - y, by simpa using sub_eq_zero.2 e.symm, by simp⟩ end lemma _root_.submodule.comap_map_eq_self {f : M →ₛₗ[τ₁₂] M₂} {p : submodule R M} (h : ker f ≤ p) : comap f (map f p) = p := by rw [submodule.comap_map_eq, sup_of_le_left h] theorem map_le_map_iff (f : M →ₛₗ[τ₁₂] M₂) {p p'} : map f p ≤ map f p' ↔ p ≤ p' ⊔ ker f := by rw [map_le_iff_le_comap, submodule.comap_map_eq] theorem map_le_map_iff' {f : M →ₛₗ[τ₁₂] M₂} (hf : ker f = ⊥) {p p'} : map f p ≤ map f p' ↔ p ≤ p' := by rw [map_le_map_iff, hf, sup_bot_eq] theorem map_injective {f : M →ₛₗ[τ₁₂] M₂} (hf : ker f = ⊥) : injective (map f) := λ p p' h, le_antisymm ((map_le_map_iff' hf).1 (le_of_eq h)) ((map_le_map_iff' hf).1 (ge_of_eq h)) theorem map_eq_top_iff {f : M →ₛₗ[τ₁₂] M₂} (hf : range f = ⊤) {p : submodule R M} : p.map f = ⊤ ↔ p ⊔ f.ker = ⊤ := by simp_rw [← top_le_iff, ← hf, range_eq_map, map_le_map_iff] end add_comm_group section ring variables [ring R] [ring R₂] [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₃] variables {τ₁₂ : R →+* R₂} {τ₂₃ : R₂ →+* R₃} {τ₁₃ : R →+* R₃} variables [ring_hom_comp_triple τ₁₂ τ₂₃ τ₁₃] variables {f : M →ₛₗ[τ₁₂] M₂} include R open submodule theorem sub_mem_ker_iff {x y} : x - y ∈ f.ker ↔ f x = f y := by rw [mem_ker, map_sub, sub_eq_zero] theorem disjoint_ker' {p : submodule R M} : disjoint p (ker f) ↔ ∀ x y ∈ p, f x = f y → x = y := disjoint_ker.trans ⟨λ H x y hx hy h, eq_of_sub_eq_zero $ H _ (sub_mem _ hx hy) (by simp [h]), λ H x h₁ h₂, H x 0 h₁ (zero_mem _) (by simpa using h₂)⟩ theorem inj_of_disjoint_ker {p : submodule R M} {s : set M} (h : s ⊆ p) (hd : disjoint p (ker f)) : ∀ x y ∈ s, f x = f y → x = y := λ x y hx hy, disjoint_ker'.1 hd _ _ (h hx) (h hy) theorem ker_eq_bot : ker f = ⊥ ↔ injective f := by simpa [disjoint] using @disjoint_ker' _ _ _ _ _ _ _ _ _ _ _ f ⊤ lemma ker_le_iff [ring_hom_surjective τ₁₂] {p : submodule R M} : ker f ≤ p ↔ ∃ (y ∈ range f), f ⁻¹' {y} ⊆ p := begin split, { intros h, use 0, rw [← set_like.mem_coe, f.range_coe], exact ⟨⟨0, map_zero f⟩, h⟩, }, { rintros ⟨y, h₁, h₂⟩, rw set_like.le_def, intros z hz, simp only [mem_ker, set_like.mem_coe] at hz, rw [← set_like.mem_coe, f.range_coe, set.mem_range] at h₁, obtain ⟨x, hx⟩ := h₁, have hx' : x ∈ p, { exact h₂ hx, }, have hxz : z + x ∈ p, { apply h₂, simp [hx, hz], }, suffices : z + x - x ∈ p, { simpa only [this, add_sub_cancel], }, exact p.sub_mem hxz hx', }, end end ring section field variables [field K] [field K₂] variables [add_comm_group V] [module K V] variables [add_comm_group V₂] [module K V₂] lemma ker_smul (f : V →ₗ[K] V₂) (a : K) (h : a ≠ 0) : ker (a • f) = ker f := submodule.comap_smul f _ a h lemma ker_smul' (f : V →ₗ[K] V₂) (a : K) : ker (a • f) = ⨅(h : a ≠ 0), ker f := submodule.comap_smul' f _ a lemma range_smul (f : V →ₗ[K] V₂) (a : K) (h : a ≠ 0) : range (a • f) = range f := by simpa only [range_eq_map] using submodule.map_smul f _ a h lemma range_smul' (f : V →ₗ[K] V₂) (a : K) : range (a • f) = ⨆(h : a ≠ 0), range f := by simpa only [range_eq_map] using submodule.map_smul' f _ a lemma span_singleton_sup_ker_eq_top (f : V →ₗ[K] K) {x : V} (hx : f x ≠ 0) : (K ∙ x) ⊔ f.ker = ⊤ := eq_top_iff.2 (λ y hy, submodule.mem_sup.2 ⟨(f y * (f x)⁻¹) • x, submodule.mem_span_singleton.2 ⟨f y * (f x)⁻¹, rfl⟩, ⟨y - (f y * (f x)⁻¹) • x, by rw [linear_map.mem_ker, f.map_sub, f.map_smul, smul_eq_mul, mul_assoc, inv_mul_cancel hx, mul_one, sub_self], by simp only [add_sub_cancel'_right]⟩⟩) end field end linear_map namespace is_linear_map lemma is_linear_map_add [semiring R] [add_comm_monoid M] [module R M] : is_linear_map R (λ (x : M × M), x.1 + x.2) := begin apply is_linear_map.mk, { intros x y, simp, cc }, { intros x y, simp [smul_add] } end lemma is_linear_map_sub {R M : Type*} [semiring R] [add_comm_group M] [module R M]: is_linear_map R (λ (x : M × M), x.1 - x.2) := begin apply is_linear_map.mk, { intros x y, simp [add_comm, add_left_comm, sub_eq_add_neg] }, { intros x y, simp [smul_sub] } end end is_linear_map namespace submodule section add_comm_monoid variables [semiring R] [semiring R₂] [add_comm_monoid M] [add_comm_monoid M₂] variables [module R M] [module R₂ M₂] variables (p p' : submodule R M) (q : submodule R₂ M₂) variables {τ₁₂ : R →+* R₂} open linear_map @[simp] theorem map_top [ring_hom_surjective τ₁₂] (f : M →ₛₗ[τ₁₂] M₂) : map f ⊤ = range f := f.range_eq_map.symm @[simp] theorem comap_bot (f : M →ₛₗ[τ₁₂] M₂) : comap f ⊥ = ker f := rfl @[simp] theorem ker_subtype : p.subtype.ker = ⊥ := ker_eq_bot_of_injective $ λ x y, subtype.ext_val @[simp] theorem range_subtype : p.subtype.range = p := by simpa using map_comap_subtype p ⊤ lemma map_subtype_le (p' : submodule R p) : map p.subtype p' ≤ p := by simpa using (map_le_range : map p.subtype p' ≤ p.subtype.range) /-- Under the canonical linear map from a submodule `p` to the ambient space `M`, the image of the maximal submodule of `p` is just `p `. -/ @[simp] lemma map_subtype_top : map p.subtype (⊤ : submodule R p) = p := by simp @[simp] lemma comap_subtype_eq_top {p p' : submodule R M} : comap p.subtype p' = ⊤ ↔ p ≤ p' := eq_top_iff.trans $ map_le_iff_le_comap.symm.trans $ by rw [map_subtype_top] @[simp] lemma comap_subtype_self : comap p.subtype p = ⊤ := comap_subtype_eq_top.2 (le_refl _) @[simp] theorem ker_of_le (p p' : submodule R M) (h : p ≤ p') : (of_le h).ker = ⊥ := by rw [of_le, ker_cod_restrict, ker_subtype] lemma range_of_le (p q : submodule R M) (h : p ≤ q) : (of_le h).range = comap q.subtype p := by rw [← map_top, of_le, linear_map.map_cod_restrict, map_top, range_subtype] lemma disjoint_iff_comap_eq_bot {p q : submodule R M} : disjoint p q ↔ comap p.subtype q = ⊥ := by rw [←(map_injective_of_injective (show injective p.subtype, from subtype.coe_injective)).eq_iff, map_comap_subtype, map_bot, disjoint_iff] /-- If `N ⊆ M` then submodules of `N` are the same as submodules of `M` contained in `N` -/ def map_subtype.rel_iso : submodule R p ≃o {p' : submodule R M // p' ≤ p} := { to_fun := λ p', ⟨map p.subtype p', map_subtype_le p _⟩, inv_fun := λ q, comap p.subtype q, left_inv := λ p', comap_map_eq_of_injective subtype.coe_injective p', right_inv := λ ⟨q, hq⟩, subtype.ext_val $ by simp [map_comap_subtype p, inf_of_le_right hq], map_rel_iff' := λ p₁ p₂, subtype.coe_le_coe.symm.trans begin dsimp, rw [map_le_iff_le_comap, comap_map_eq_of_injective (show injective p.subtype, from subtype.coe_injective) p₂], end } /-- If `p ⊆ M` is a submodule, the ordering of submodules of `p` is embedded in the ordering of submodules of `M`. -/ def map_subtype.order_embedding : submodule R p ↪o submodule R M := (rel_iso.to_rel_embedding $ map_subtype.rel_iso p).trans (subtype.rel_embedding _ _) @[simp] lemma map_subtype_embedding_eq (p' : submodule R p) : map_subtype.order_embedding p p' = map p.subtype p' := rfl end add_comm_monoid end submodule namespace linear_map section semiring variables [semiring R] [semiring R₂] [semiring R₃] variables [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] variables [module R M] [module R₂ M₂] [module R₃ M₃] variables {τ₁₂ : R →+* R₂} {τ₂₃ : R₂ →+* R₃} {τ₁₃ : R →+* R₃} variables [ring_hom_comp_triple τ₁₂ τ₂₃ τ₁₃] /-- A monomorphism is injective. -/ lemma ker_eq_bot_of_cancel {f : M →ₛₗ[τ₁₂] M₂} (h : ∀ (u v : f.ker →ₗ[R] M), f.comp u = f.comp v → u = v) : f.ker = ⊥ := begin have h₁ : f.comp (0 : f.ker →ₗ[R] M) = 0 := comp_zero _, rw [←submodule.range_subtype f.ker, ←h 0 f.ker.subtype (eq.trans h₁ (comp_ker_subtype f).symm)], exact range_zero end lemma range_comp_of_range_eq_top [ring_hom_surjective τ₁₂] [ring_hom_surjective τ₂₃] [ring_hom_surjective τ₁₃] {f : M →ₛₗ[τ₁₂] M₂} (g : M₂ →ₛₗ[τ₂₃] M₃) (hf : range f = ⊤) : range (g.comp f : M →ₛₗ[τ₁₃] M₃) = range g := by rw [range_comp, hf, submodule.map_top] lemma ker_comp_of_ker_eq_bot (f : M →ₛₗ[τ₁₂] M₂) {g : M₂ →ₛₗ[τ₂₃] M₃} (hg : ker g = ⊥) : ker (g.comp f : M →ₛₗ[τ₁₃] M₃) = ker f := by rw [ker_comp, hg, submodule.comap_bot] section image /-- If `O` is a submodule of `M`, and `Φ : O →ₗ M'` is a linear map, then `(ϕ : O →ₗ M').submodule_image N` is `ϕ(N)` as a submodule of `M'` -/ def submodule_image {M' : Type*} [add_comm_monoid M'] [module R M'] {O : submodule R M} (ϕ : O →ₗ[R] M') (N : submodule R M) : submodule R M' := (N.comap O.subtype).map ϕ @[simp] lemma mem_submodule_image {M' : Type*} [add_comm_monoid M'] [module R M'] {O : submodule R M} {ϕ : O →ₗ[R] M'} {N : submodule R M} {x : M'} : x ∈ ϕ.submodule_image N ↔ ∃ y (yO : y ∈ O) (yN : y ∈ N), ϕ ⟨y, yO⟩ = x := begin refine submodule.mem_map.trans ⟨_, _⟩; simp_rw submodule.mem_comap, { rintro ⟨⟨y, yO⟩, (yN : y ∈ N), h⟩, exact ⟨y, yO, yN, h⟩ }, { rintro ⟨y, yO, yN, h⟩, exact ⟨⟨y, yO⟩, yN, h⟩ } end lemma mem_submodule_image_of_le {M' : Type*} [add_comm_monoid M'] [module R M'] {O : submodule R M} {ϕ : O →ₗ[R] M'} {N : submodule R M} (hNO : N ≤ O) {x : M'} : x ∈ ϕ.submodule_image N ↔ ∃ y (yN : y ∈ N), ϕ ⟨y, hNO yN⟩ = x := begin refine mem_submodule_image.trans ⟨_, _⟩, { rintro ⟨y, yO, yN, h⟩, exact ⟨y, yN, h⟩ }, { rintro ⟨y, yN, h⟩, exact ⟨y, hNO yN, yN, h⟩ } end lemma submodule_image_apply_of_le {M' : Type*} [add_comm_group M'] [module R M'] {O : submodule R M} (ϕ : O →ₗ[R] M') (N : submodule R M) (hNO : N ≤ O) : ϕ.submodule_image N = (ϕ.comp (submodule.of_le hNO)).range := by rw [submodule_image, range_comp, submodule.range_of_le] end image end semiring end linear_map @[simp] lemma linear_map.range_range_restrict [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [module R M] [module R M₂] (f : M →ₗ[R] M₂) : f.range_restrict.range = ⊤ := by simp [f.range_cod_restrict _] /-! ### Linear equivalences -/ namespace linear_equiv section add_comm_monoid section subsingleton variables [semiring R] [semiring R₂] [semiring R₃] [semiring R₄] variables [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] [add_comm_monoid M₄] variables [module R M] [module R₂ M₂] variables [subsingleton M] [subsingleton M₂] variables {σ₁₂ : R →+* R₂} {σ₂₁ : R₂ →+* R} variables [ring_hom_inv_pair σ₁₂ σ₂₁] [ring_hom_inv_pair σ₂₁ σ₁₂] include σ₂₁ /-- Between two zero modules, the zero map is an equivalence. -/ instance : has_zero (M ≃ₛₗ[σ₁₂] M₂) := ⟨{ to_fun := 0, inv_fun := 0, right_inv := λ x, subsingleton.elim _ _, left_inv := λ x, subsingleton.elim _ _, ..(0 : M →ₛₗ[σ₁₂] M₂)}⟩ omit σ₂₁ -- Even though these are implied by `subsingleton.elim` via the `unique` instance below, they're -- nice to have as `rfl`-lemmas for `dsimp`. include σ₂₁ @[simp] lemma zero_symm : (0 : M ≃ₛₗ[σ₁₂] M₂).symm = 0 := rfl @[simp] lemma coe_zero : ⇑(0 : M ≃ₛₗ[σ₁₂] M₂) = 0 := rfl lemma zero_apply (x : M) : (0 : M ≃ₛₗ[σ₁₂] M₂) x = 0 := rfl /-- Between two zero modules, the zero map is the only equivalence. -/ instance : unique (M ≃ₛₗ[σ₁₂] M₂) := { uniq := λ f, to_linear_map_injective (subsingleton.elim _ _), default := 0 } omit σ₂₁ end subsingleton section variables [semiring R] [semiring R₂] [semiring R₃] [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 {σ₁₂ : R →+* R₂} {σ₂₁ : R₂ →+* R} variables {re₁₂ : ring_hom_inv_pair σ₁₂ σ₂₁} {re₂₁ : ring_hom_inv_pair σ₂₁ σ₁₂} variables (e e' : M ≃ₛₗ[σ₁₂] M₂) lemma map_eq_comap {p : submodule R M} : (p.map (e : M →ₛₗ[σ₁₂] M₂) : submodule R₂ M₂) = p.comap (e.symm : M₂ →ₛₗ[σ₂₁] M) := set_like.coe_injective $ by simp [e.image_eq_preimage] /-- A linear equivalence of two modules restricts to a linear equivalence from any submodule `p` of the domain onto the image of that submodule. This is `linear_equiv.of_submodule'` but with `map` on the right instead of `comap` on the left. -/ def of_submodule (p : submodule R M) : p ≃ₛₗ[σ₁₂] ↥(p.map (e : M →ₛₗ[σ₁₂] M₂) : submodule R₂ M₂) := { inv_fun := λ y, ⟨(e.symm : M₂ →ₛₗ[σ₂₁] M) y, by { rcases y with ⟨y', hy⟩, rw submodule.mem_map at hy, rcases hy with ⟨x, hx, hxy⟩, subst hxy, simp only [symm_apply_apply, submodule.coe_mk, coe_coe, hx], }⟩, left_inv := λ x, by simp, right_inv := λ y, by { apply set_coe.ext, simp, }, ..((e : M →ₛₗ[σ₁₂] M₂).dom_restrict p).cod_restrict (p.map (e : M →ₛₗ[σ₁₂] M₂)) (λ x, ⟨x, by simp⟩) } include σ₂₁ @[simp] lemma of_submodule_apply (p : submodule R M) (x : p) : ↑(e.of_submodule p x) = e x := rfl @[simp] lemma of_submodule_symm_apply (p : submodule R M) (x : (p.map (e : M →ₛₗ[σ₁₂] M₂) : submodule R₂ M₂)) : ↑((e.of_submodule p).symm x) = e.symm x := rfl omit σ₂₁ end section finsupp variables {γ : Type*} variables [semiring R] [semiring R₂] variables [add_comm_monoid M] [add_comm_monoid M₂] variables [module R M] [module R₂ M₂] [has_zero γ] variables {τ₁₂ : R →+* R₂} {τ₂₁ : R₂ →+* R} variables [ring_hom_inv_pair τ₁₂ τ₂₁] [ring_hom_inv_pair τ₂₁ τ₁₂] include τ₂₁ @[simp] lemma map_finsupp_sum (f : M ≃ₛₗ[τ₁₂] M₂) {t : ι →₀ γ} {g : ι → γ → M} : f (t.sum g) = t.sum (λ i d, f (g i d)) := f.map_sum _ omit τ₂₁ end finsupp section dfinsupp open dfinsupp variables [semiring R] [semiring R₂] variables [add_comm_monoid M] [add_comm_monoid M₂] variables [module R M] [module R₂ M₂] variables {τ₁₂ : R →+* R₂} {τ₂₁ : R₂ →+* R} variables [ring_hom_inv_pair τ₁₂ τ₂₁] [ring_hom_inv_pair τ₂₁ τ₁₂] variables {γ : ι → Type*} [decidable_eq ι] include τ₂₁ @[simp] lemma map_dfinsupp_sum [Π i, has_zero (γ i)] [Π i (x : γ i), decidable (x ≠ 0)] (f : M ≃ₛₗ[τ₁₂] M₂) (t : Π₀ i, γ i) (g : Π i, γ i → M) : f (t.sum g) = t.sum (λ i d, f (g i d)) := f.map_sum _ @[simp] lemma map_dfinsupp_sum_add_hom [Π i, add_zero_class (γ i)] (f : M ≃ₛₗ[τ₁₂] M₂) (t : Π₀ i, γ i) (g : Π i, γ i →+ M) : f (sum_add_hom g t) = sum_add_hom (λ i, f.to_add_equiv.to_add_monoid_hom.comp (g i)) t := f.to_add_equiv.map_dfinsupp_sum_add_hom _ _ end dfinsupp section uncurry variables [semiring R] [semiring R₂] [semiring R₃] [semiring R₄] variables [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] [add_comm_monoid M₄] variables (V V₂ R) /-- Linear equivalence between a curried and uncurried function. Differs from `tensor_product.curry`. -/ protected def curry : (V × V₂ → R) ≃ₗ[R] (V → V₂ → R) := { map_add' := λ _ _, by { ext, refl }, map_smul' := λ _ _, by { ext, refl }, .. equiv.curry _ _ _ } @[simp] lemma coe_curry : ⇑(linear_equiv.curry R V V₂) = curry := rfl @[simp] lemma coe_curry_symm : ⇑(linear_equiv.curry R V V₂).symm = uncurry := rfl end uncurry section variables [semiring R] [semiring R₂] [semiring R₃] [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₂} {module_M₃ : module R₃ M₃} variables {σ₁₂ : R →+* R₂} {σ₂₁ : R₂ →+* R} variables {σ₂₃ : R₂ →+* R₃} {σ₁₃ : R →+* R₃} [ring_hom_comp_triple σ₁₂ σ₂₃ σ₁₃] variables {σ₃₂ : R₃ →+* R₂} variables {re₁₂ : ring_hom_inv_pair σ₁₂ σ₂₁} {re₂₁ : ring_hom_inv_pair σ₂₁ σ₁₂} variables {re₂₃ : ring_hom_inv_pair σ₂₃ σ₃₂} {re₃₂ : ring_hom_inv_pair σ₃₂ σ₂₃} variables (f : M →ₛₗ[σ₁₂] M₂) (g : M₂ →ₛₗ[σ₂₁] M) (e : M ≃ₛₗ[σ₁₂] M₂) (h : M₂ →ₛₗ[σ₂₃] M₃) variables (e'' : M₂ ≃ₛₗ[σ₂₃] M₃) variables (p q : submodule R M) /-- Linear equivalence between two equal submodules. -/ def of_eq (h : p = q) : p ≃ₗ[R] q := { map_smul' := λ _ _, rfl, map_add' := λ _ _, rfl, .. equiv.set.of_eq (congr_arg _ h) } variables {p q} @[simp] lemma coe_of_eq_apply (h : p = q) (x : p) : (of_eq p q h x : M) = x := rfl @[simp] lemma of_eq_symm (h : p = q) : (of_eq p q h).symm = of_eq q p h.symm := rfl include σ₂₁ /-- A linear equivalence which maps a submodule of one module onto another, restricts to a linear equivalence of the two submodules. -/ def of_submodules (p : submodule R M) (q : submodule R₂ M₂) (h : p.map (e : M →ₛₗ[σ₁₂] M₂) = q) : p ≃ₛₗ[σ₁₂] q := (e.of_submodule p).trans (linear_equiv.of_eq _ _ h) @[simp] lemma of_submodules_apply {p : submodule R M} {q : submodule R₂ M₂} (h : p.map ↑e = q) (x : p) : ↑(e.of_submodules p q h x) = e x := rfl @[simp] lemma of_submodules_symm_apply {p : submodule R M} {q : submodule R₂ M₂} (h : p.map ↑e = q) (x : q) : ↑((e.of_submodules p q h).symm x) = e.symm x := rfl include re₁₂ re₂₁ /-- A linear equivalence of two modules restricts to a linear equivalence from the preimage of any submodule to that submodule. This is `linear_equiv.of_submodule` but with `comap` on the left instead of `map` on the right. -/ def of_submodule' [module R M] [module R₂ M₂] (f : M ≃ₛₗ[σ₁₂] M₂) (U : submodule R₂ M₂) : U.comap (f : M →ₛₗ[σ₁₂] M₂) ≃ₛₗ[σ₁₂] U := (f.symm.of_submodules _ _ f.symm.map_eq_comap).symm lemma of_submodule'_to_linear_map [module R M] [module R₂ M₂] (f : M ≃ₛₗ[σ₁₂] M₂) (U : submodule R₂ M₂) : (f.of_submodule' U).to_linear_map = (f.to_linear_map.dom_restrict _).cod_restrict _ subtype.prop := by { ext, refl } @[simp] lemma of_submodule'_apply [module R M] [module R₂ M₂] (f : M ≃ₛₗ[σ₁₂] M₂) (U : submodule R₂ M₂) (x : U.comap (f : M →ₛₗ[σ₁₂] M₂)) : (f.of_submodule' U x : M₂) = f (x : M) := rfl @[simp] lemma of_submodule'_symm_apply [module R M] [module R₂ M₂] (f : M ≃ₛₗ[σ₁₂] M₂) (U : submodule R₂ M₂) (x : U) : ((f.of_submodule' U).symm x : M) = f.symm (x : M₂) := rfl variable (p) omit σ₂₁ re₁₂ re₂₁ /-- The top submodule of `M` is linearly equivalent to `M`. -/ def of_top (h : p = ⊤) : p ≃ₗ[R] M := { inv_fun := λ x, ⟨x, h.symm ▸ trivial⟩, left_inv := λ ⟨x, h⟩, rfl, right_inv := λ x, rfl, .. p.subtype } @[simp] theorem of_top_apply {h} (x : p) : of_top p h x = x := rfl @[simp] theorem coe_of_top_symm_apply {h} (x : M) : ((of_top p h).symm x : M) = x := rfl theorem of_top_symm_apply {h} (x : M) : (of_top p h).symm x = ⟨x, h.symm ▸ trivial⟩ := rfl include σ₂₁ re₁₂ re₂₁ /-- If a linear map has an inverse, it is a linear equivalence. -/ def of_linear (h₁ : f.comp g = linear_map.id) (h₂ : g.comp f = linear_map.id) : M ≃ₛₗ[σ₁₂] M₂ := { inv_fun := g, left_inv := linear_map.ext_iff.1 h₂, right_inv := linear_map.ext_iff.1 h₁, ..f } omit σ₂₁ re₁₂ re₂₁ include σ₂₁ re₁₂ re₂₁ @[simp] theorem of_linear_apply {h₁ h₂} (x : M) : of_linear f g h₁ h₂ x = f x := rfl omit σ₂₁ re₁₂ re₂₁ include σ₂₁ re₁₂ re₂₁ @[simp] theorem of_linear_symm_apply {h₁ h₂} (x : M₂) : (of_linear f g h₁ h₂).symm x = g x := rfl omit σ₂₁ re₁₂ re₂₁ @[simp] protected theorem range : (e : M →ₛₗ[σ₁₂] M₂).range = ⊤ := linear_map.range_eq_top.2 e.to_equiv.surjective include σ₂₁ re₁₂ re₂₁ lemma eq_bot_of_equiv [module R₂ M₂] (e : p ≃ₛₗ[σ₁₂] (⊥ : submodule R₂ M₂)) : p = ⊥ := begin refine bot_unique (set_like.le_def.2 $ assume b hb, (submodule.mem_bot R).2 _), rw [← p.mk_eq_zero hb, ← e.map_eq_zero_iff], apply submodule.eq_zero_of_bot_submodule end omit σ₂₁ re₁₂ re₂₁ @[simp] protected theorem ker : (e : M →ₛₗ[σ₁₂] M₂).ker = ⊥ := linear_map.ker_eq_bot_of_injective e.to_equiv.injective @[simp] theorem range_comp [ring_hom_surjective σ₁₂] [ring_hom_surjective σ₂₃] [ring_hom_surjective σ₁₃] : (h.comp (e : M →ₛₗ[σ₁₂] M₂) : M →ₛₗ[σ₁₃] M₃).range = h.range := linear_map.range_comp_of_range_eq_top _ e.range include module_M @[simp] theorem ker_comp (l : M →ₛₗ[σ₁₂] M₂) : (((e'' : M₂ →ₛₗ[σ₂₃] M₃).comp l : M →ₛₗ[σ₁₃] M₃) : M →ₛₗ[σ₁₃] M₃).ker = l.ker := linear_map.ker_comp_of_ker_eq_bot _ e''.ker omit module_M variables {f g} include σ₂₁ /-- An linear map `f : M →ₗ[R] M₂` with a left-inverse `g : M₂ →ₗ[R] M` defines a linear equivalence between `M` and `f.range`. This is a computable alternative to `linear_equiv.of_injective`, and a bidirectional version of `linear_map.range_restrict`. -/ def of_left_inverse [ring_hom_inv_pair σ₁₂ σ₂₁] [ring_hom_inv_pair σ₂₁ σ₁₂] {g : M₂ → M} (h : function.left_inverse g f) : M ≃ₛₗ[σ₁₂] f.range := { to_fun := f.range_restrict, inv_fun := g ∘ f.range.subtype, left_inv := h, right_inv := λ x, subtype.ext $ let ⟨x', hx'⟩ := linear_map.mem_range.mp x.prop in show f (g x) = x, by rw [←hx', h x'], .. f.range_restrict } omit σ₂₁ @[simp] lemma of_left_inverse_apply [ring_hom_inv_pair σ₁₂ σ₂₁] [ring_hom_inv_pair σ₂₁ σ₁₂] (h : function.left_inverse g f) (x : M) : ↑(of_left_inverse h x) = f x := rfl include σ₂₁ @[simp] lemma of_left_inverse_symm_apply [ring_hom_inv_pair σ₁₂ σ₂₁] [ring_hom_inv_pair σ₂₁ σ₁₂] (h : function.left_inverse g f) (x : f.range) : (of_left_inverse h).symm x = g x := rfl omit σ₂₁ variables (f) /-- An `injective` linear map `f : M →ₗ[R] M₂` defines a linear equivalence between `M` and `f.range`. See also `linear_map.of_left_inverse`. -/ noncomputable def of_injective [ring_hom_inv_pair σ₁₂ σ₂₁] [ring_hom_inv_pair σ₂₁ σ₁₂] (h : injective f) : M ≃ₛₗ[σ₁₂] f.range := of_left_inverse $ classical.some_spec h.has_left_inverse @[simp] theorem of_injective_apply [ring_hom_inv_pair σ₁₂ σ₂₁] [ring_hom_inv_pair σ₂₁ σ₁₂] {h : injective f} (x : M) : ↑(of_injective f h x) = f x := rfl /-- A bijective linear map is a linear equivalence. -/ noncomputable def of_bijective [ring_hom_inv_pair σ₁₂ σ₂₁] [ring_hom_inv_pair σ₂₁ σ₁₂] (hf₁ : injective f) (hf₂ : surjective f) : M ≃ₛₗ[σ₁₂] M₂ := (of_injective f hf₁).trans (of_top _ $ linear_map.range_eq_top.2 hf₂) @[simp] theorem of_bijective_apply [ring_hom_inv_pair σ₁₂ σ₂₁] [ring_hom_inv_pair σ₂₁ σ₁₂] {hf₁ hf₂} (x : M) : of_bijective f hf₁ hf₂ x = f x := rfl end end add_comm_monoid section add_comm_group variables [semiring R] [semiring R₂] [semiring R₃] [semiring R₄] variables [add_comm_group M] [add_comm_group M₂] [add_comm_group 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 {σ₁₂ : R →+* R₂} {σ₃₄ : R₃ →+* R₄} variables {σ₂₁ : R₂ →+* R} {σ₄₃ : R₄ →+* R₃} variables {re₁₂ : ring_hom_inv_pair σ₁₂ σ₂₁} {re₂₁ : ring_hom_inv_pair σ₂₁ σ₁₂} variables {re₃₄ : ring_hom_inv_pair σ₃₄ σ₄₃} {re₄₃ : ring_hom_inv_pair σ₄₃ σ₃₄} variables (e e₁ : M ≃ₛₗ[σ₁₂] M₂) (e₂ : M₃ ≃ₛₗ[σ₃₄] M₄) @[simp] theorem map_neg (a : M) : e (-a) = -e a := e.to_linear_map.map_neg a @[simp] theorem map_sub (a b : M) : e (a - b) = e a - e b := e.to_linear_map.map_sub a b end add_comm_group section neg variables (R) [semiring R] [add_comm_group M] [module R M] /-- `x ↦ -x` as a `linear_equiv` -/ def neg : M ≃ₗ[R] M := { .. equiv.neg M, .. (-linear_map.id : M →ₗ[R] M) } variable {R} @[simp] lemma coe_neg : ⇑(neg R : M ≃ₗ[R] M) = -id := rfl lemma neg_apply (x : M) : neg R x = -x := by simp @[simp] lemma symm_neg : (neg R : M ≃ₗ[R] M).symm = neg R := rfl end neg section comm_semiring variables [comm_semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] variables [module R M] [module R M₂] [module R M₃] open _root_.linear_map /-- Multiplying by a unit `a` of the ring `R` is a linear equivalence. -/ def smul_of_unit (a : units R) : M ≃ₗ[R] M := of_linear ((a:R) • 1 : M →ₗ[R] M) (((a⁻¹ : units R) : R) • 1 : M →ₗ[R] M) (by rw [smul_comp, comp_smul, smul_smul, units.mul_inv, one_smul]; refl) (by rw [smul_comp, comp_smul, smul_smul, units.inv_mul, one_smul]; refl) /-- A linear isomorphism between the domains and codomains of two spaces of linear maps gives a linear isomorphism between the two function spaces. -/ def arrow_congr {R M₁ M₂ M₂₁ M₂₂ : Sort*} [comm_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₂₂] (e₁ : M₁ ≃ₗ[R] M₂) (e₂ : M₂₁ ≃ₗ[R] M₂₂) : (M₁ →ₗ[R] M₂₁) ≃ₗ[R] (M₂ →ₗ[R] M₂₂) := { to_fun := λ f : M₁ →ₗ[R] M₂₁, (e₂ : M₂₁ →ₗ[R] M₂₂).comp $ f.comp (e₁.symm : M₂ →ₗ[R] M₁), inv_fun := λ f, (e₂.symm : M₂₂ →ₗ[R] M₂₁).comp $ f.comp (e₁ : M₁ →ₗ[R] M₂), left_inv := λ f, by { ext x, simp only [symm_apply_apply, comp_app, coe_comp, coe_coe]}, right_inv := λ f, by { ext x, simp only [comp_app, apply_symm_apply, coe_comp, coe_coe]}, map_add' := λ f g, by { ext x, simp only [map_add, add_apply, comp_app, coe_comp, coe_coe]}, map_smul' := λ c f, by { ext x, simp only [smul_apply, comp_app, coe_comp, map_smulₛₗ, coe_coe]} } @[simp] lemma arrow_congr_apply {R M₁ M₂ M₂₁ M₂₂ : Sort*} [comm_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₂₂] (e₁ : M₁ ≃ₗ[R] M₂) (e₂ : M₂₁ ≃ₗ[R] M₂₂) (f : M₁ →ₗ[R] M₂₁) (x : M₂) : arrow_congr e₁ e₂ f x = e₂ (f (e₁.symm x)) := rfl @[simp] lemma arrow_congr_symm_apply {R M₁ M₂ M₂₁ M₂₂ : Sort*} [comm_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₂₂] (e₁ : M₁ ≃ₗ[R] M₂) (e₂ : M₂₁ ≃ₗ[R] M₂₂) (f : M₂ →ₗ[R] M₂₂) (x : M₁) : (arrow_congr e₁ e₂).symm f x = e₂.symm (f (e₁ x)) := rfl lemma arrow_congr_comp {N N₂ N₃ : Sort*} [add_comm_monoid N] [add_comm_monoid N₂] [add_comm_monoid N₃] [module R N] [module R N₂] [module R N₃] (e₁ : M ≃ₗ[R] N) (e₂ : M₂ ≃ₗ[R] N₂) (e₃ : M₃ ≃ₗ[R] N₃) (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) : arrow_congr e₁ e₃ (g.comp f) = (arrow_congr e₂ e₃ g).comp (arrow_congr e₁ e₂ f) := by { ext, simp only [symm_apply_apply, arrow_congr_apply, linear_map.comp_apply], } lemma arrow_congr_trans {M₁ M₂ M₃ N₁ N₂ N₃ : Sort*} [add_comm_monoid M₁] [module R M₁] [add_comm_monoid M₂] [module R M₂] [add_comm_monoid M₃] [module R M₃] [add_comm_monoid N₁] [module R N₁] [add_comm_monoid N₂] [module R N₂] [add_comm_monoid N₃] [module R N₃] (e₁ : M₁ ≃ₗ[R] M₂) (e₂ : N₁ ≃ₗ[R] N₂) (e₃ : M₂ ≃ₗ[R] M₃) (e₄ : N₂ ≃ₗ[R] N₃) : (arrow_congr e₁ e₂).trans (arrow_congr e₃ e₄) = arrow_congr (e₁.trans e₃) (e₂.trans e₄) := rfl /-- If `M₂` and `M₃` are linearly isomorphic then the two spaces of linear maps from `M` into `M₂` and `M` into `M₃` are linearly isomorphic. -/ def congr_right (f : M₂ ≃ₗ[R] M₃) : (M →ₗ[R] M₂) ≃ₗ[R] (M →ₗ[R] M₃) := arrow_congr (linear_equiv.refl R M) f /-- If `M` and `M₂` are linearly isomorphic then the two spaces of linear maps from `M` and `M₂` to themselves are linearly isomorphic. -/ def conj (e : M ≃ₗ[R] M₂) : (module.End R M) ≃ₗ[R] (module.End R M₂) := arrow_congr e e lemma conj_apply (e : M ≃ₗ[R] M₂) (f : module.End R M) : e.conj f = ((↑e : M →ₗ[R] M₂).comp f).comp (e.symm : M₂ →ₗ[R] M) := rfl lemma symm_conj_apply (e : M ≃ₗ[R] M₂) (f : module.End R M₂) : e.symm.conj f = ((↑e.symm : M₂ →ₗ[R] M).comp f).comp (e : M →ₗ[R] M₂) := rfl lemma conj_comp (e : M ≃ₗ[R] M₂) (f g : module.End R M) : e.conj (g.comp f) = (e.conj g).comp (e.conj f) := arrow_congr_comp e e e f g lemma conj_trans (e₁ : M ≃ₗ[R] M₂) (e₂ : M₂ ≃ₗ[R] M₃) : e₁.conj.trans e₂.conj = (e₁.trans e₂).conj := by { ext f x, refl, } @[simp] lemma conj_id (e : M ≃ₗ[R] M₂) : e.conj linear_map.id = linear_map.id := by { ext, simp [conj_apply], } end comm_semiring section field variables [field K] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [module K M] [module K M₂] [module K M₃] variables (K) (M) open _root_.linear_map /-- Multiplying by a nonzero element `a` of the field `K` is a linear equivalence. -/ def smul_of_ne_zero (a : K) (ha : a ≠ 0) : M ≃ₗ[K] M := smul_of_unit $ units.mk0 a ha section noncomputable theory open_locale classical lemma ker_to_span_singleton {x : M} (h : x ≠ 0) : (to_span_singleton K M x).ker = ⊥ := begin ext c, split, { intros hc, rw submodule.mem_bot, rw mem_ker at hc, by_contra hc', have : x = 0, calc x = c⁻¹ • (c • x) : by rw [← mul_smul, inv_mul_cancel hc', one_smul] ... = c⁻¹ • ((to_span_singleton K M x) c) : rfl ... = 0 : by rw [hc, smul_zero], tauto }, { rw [mem_ker, submodule.mem_bot], intros h, rw h, simp } end /-- Given a nonzero element `x` of a vector space `M` over a field `K`, the natural map from `K` to the span of `x`, with invertibility check to consider it as an isomorphism.-/ def to_span_nonzero_singleton (x : M) (h : x ≠ 0) : K ≃ₗ[K] (K ∙ x) := linear_equiv.trans (linear_equiv.of_injective (to_span_singleton K M x) (ker_eq_bot.1 $ ker_to_span_singleton K M h)) (of_eq (to_span_singleton K M x).range (K ∙ x) (span_singleton_eq_range K M x).symm) lemma to_span_nonzero_singleton_one (x : M) (h : x ≠ 0) : to_span_nonzero_singleton K M x h 1 = (⟨x, submodule.mem_span_singleton_self x⟩ : K ∙ x) := begin apply set_like.coe_eq_coe.mp, have : ↑(to_span_nonzero_singleton K M x h 1) = to_span_singleton K M x 1 := rfl, rw [this, to_span_singleton_one, submodule.coe_mk], end /-- Given a nonzero element `x` of a vector space `M` over a field `K`, the natural map from the span of `x` to `K`.-/ abbreviation coord (x : M) (h : x ≠ 0) : (K ∙ x) ≃ₗ[K] K := (to_span_nonzero_singleton K M x h).symm lemma coord_self (x : M) (h : x ≠ 0) : (coord K M x h) (⟨x, submodule.mem_span_singleton_self x⟩ : K ∙ x) = 1 := by rw [← to_span_nonzero_singleton_one K M x h, symm_apply_apply] end end field end linear_equiv namespace submodule section module variables [semiring R] [add_comm_monoid M] [module R M] /-- Given `p` a submodule of the module `M` and `q` a submodule of `p`, `p.equiv_subtype_map q` is the natural `linear_equiv` between `q` and `q.map p.subtype`. -/ def equiv_subtype_map (p : submodule R M) (q : submodule R p) : q ≃ₗ[R] q.map p.subtype := { inv_fun := begin rintro ⟨x, hx⟩, refine ⟨⟨x, _⟩, _⟩; rcases hx with ⟨⟨_, h⟩, _, rfl⟩; assumption end, left_inv := λ ⟨⟨_, _⟩, _⟩, rfl, right_inv := λ ⟨x, ⟨_, h⟩, _, rfl⟩, rfl, .. (p.subtype.dom_restrict q).cod_restrict _ begin rintro ⟨x, hx⟩, refine ⟨x, hx, rfl⟩, end } @[simp] lemma equiv_subtype_map_apply {p : submodule R M} {q : submodule R p} (x : q) : (p.equiv_subtype_map q x : M) = p.subtype.dom_restrict q x := rfl @[simp] lemma equiv_subtype_map_symm_apply {p : submodule R M} {q : submodule R p} (x : q.map p.subtype) : ((p.equiv_subtype_map q).symm x : M) = x := by { cases x, refl } /-- If `s ≤ t`, then we can view `s` as a submodule of `t` by taking the comap of `t.subtype`. -/ @[simps] def comap_subtype_equiv_of_le {p q : submodule R M} (hpq : p ≤ q) : comap q.subtype p ≃ₗ[R] p := { to_fun := λ x, ⟨x, x.2⟩, inv_fun := λ x, ⟨⟨x, hpq x.2⟩, x.2⟩, left_inv := λ x, by simp only [coe_mk, set_like.eta, coe_coe], right_inv := λ x, by simp only [subtype.coe_mk, set_like.eta, coe_coe], map_add' := λ x y, rfl, map_smul' := λ c x, rfl } end module end submodule namespace submodule variables [comm_semiring R] [comm_semiring R₂] variables [add_comm_monoid M] [add_comm_monoid M₂] [module R M] [module R₂ M₂] variables [add_comm_monoid N] [add_comm_monoid N₂] [module R N] [module R N₂] variables {τ₁₂ : R →+* R₂} {τ₂₁ : R₂ →+* R} variables [ring_hom_inv_pair τ₁₂ τ₂₁] [ring_hom_inv_pair τ₂₁ τ₁₂] variables (p : submodule R M) (q : submodule R₂ M₂) variables (pₗ : submodule R N) (qₗ : submodule R N₂) include τ₂₁ @[simp] lemma mem_map_equiv {e : M ≃ₛₗ[τ₁₂] M₂} {x : M₂} : x ∈ p.map (e : M →ₛₗ[τ₁₂] M₂) ↔ e.symm x ∈ p := begin rw submodule.mem_map, split, { rintros ⟨y, hy, hx⟩, simp [←hx, hy], }, { intros hx, refine ⟨e.symm x, hx, by simp⟩, }, end omit τ₂₁ lemma map_equiv_eq_comap_symm (e : M ≃ₛₗ[τ₁₂] M₂) (K : submodule R M) : K.map (e : M →ₛₗ[τ₁₂] M₂) = K.comap (e.symm : M₂ →ₛₗ[τ₂₁] M) := submodule.ext (λ _, by rw [mem_map_equiv, mem_comap, linear_equiv.coe_coe]) lemma comap_equiv_eq_map_symm (e : M ≃ₛₗ[τ₁₂] M₂) (K : submodule R₂ M₂) : K.comap (e : M →ₛₗ[τ₁₂] M₂) = K.map (e.symm : M₂ →ₛₗ[τ₂₁] M) := (map_equiv_eq_comap_symm e.symm K).symm lemma comap_le_comap_smul (fₗ : N →ₗ[R] N₂) (c : R) : comap fₗ qₗ ≤ comap (c • fₗ) qₗ := begin rw set_like.le_def, intros m h, change c • (fₗ m) ∈ qₗ, change fₗ m ∈ qₗ at h, apply qₗ.smul_mem _ h, end lemma inf_comap_le_comap_add (f₁ f₂ : M →ₛₗ[τ₁₂] M₂) : comap f₁ q ⊓ comap f₂ q ≤ comap (f₁ + f₂) q := begin rw set_like.le_def, intros m h, change f₁ m + f₂ m ∈ q, change f₁ m ∈ q ∧ f₂ m ∈ q at h, apply q.add_mem h.1 h.2, end /-- Given modules `M`, `M₂` over a commutative ring, together with submodules `p ⊆ M`, `q ⊆ M₂`, the set of maps $\{f ∈ Hom(M, M₂) | f(p) ⊆ q \}$ is a submodule of `Hom(M, M₂)`. -/ def compatible_maps : submodule R (N →ₗ[R] N₂) := { carrier := {fₗ | pₗ ≤ comap fₗ qₗ}, zero_mem' := by { change pₗ ≤ comap 0 qₗ, rw comap_zero, refine le_top, }, add_mem' := λ f₁ f₂ h₁ h₂, by { apply le_trans _ (inf_comap_le_comap_add qₗ f₁ f₂), rw le_inf_iff, exact ⟨h₁, h₂⟩, }, smul_mem' := λ c fₗ h, le_trans h (comap_le_comap_smul qₗ fₗ c), } end submodule namespace equiv variables [semiring R] [add_comm_monoid M] [module R M] [add_comm_monoid M₂] [module R M₂] /-- An equivalence whose underlying function is linear is a linear equivalence. -/ def to_linear_equiv (e : M ≃ M₂) (h : is_linear_map R (e : M → M₂)) : M ≃ₗ[R] M₂ := { .. e, .. h.mk' e} end equiv namespace add_equiv variables [semiring R] [add_comm_monoid M] [module R M] [add_comm_monoid M₂] [module R M₂] /-- An additive equivalence whose underlying function preserves `smul` is a linear equivalence. -/ def to_linear_equiv (e : M ≃+ M₂) (h : ∀ (c : R) x, e (c • x) = c • e x) : M ≃ₗ[R] M₂ := { map_smul' := h, .. e, } @[simp] lemma coe_to_linear_equiv (e : M ≃+ M₂) (h : ∀ (c : R) x, e (c • x) = c • e x) : ⇑(e.to_linear_equiv h) = e := rfl @[simp] lemma coe_to_linear_equiv_symm (e : M ≃+ M₂) (h : ∀ (c : R) x, e (c • x) = c • e x) : ⇑(e.to_linear_equiv h).symm = e.symm := rfl end add_equiv section fun_left variables (R M) [semiring R] [add_comm_monoid M] [module R M] variables {m n p : Type*} namespace linear_map /-- Given an `R`-module `M` and a function `m → n` between arbitrary types, construct a linear map `(n → M) →ₗ[R] (m → M)` -/ def fun_left (f : m → n) : (n → M) →ₗ[R] (m → M) := { to_fun := (∘ f), map_add' := λ _ _, rfl, map_smul' := λ _ _, rfl } @[simp] theorem fun_left_apply (f : m → n) (g : n → M) (i : m) : fun_left R M f g i = g (f i) := rfl @[simp] theorem fun_left_id (g : n → M) : fun_left R M _root_.id g = g := rfl theorem fun_left_comp (f₁ : n → p) (f₂ : m → n) : fun_left R M (f₁ ∘ f₂) = (fun_left R M f₂).comp (fun_left R M f₁) := rfl theorem fun_left_surjective_of_injective (f : m → n) (hf : injective f) : surjective (fun_left R M f) := begin classical, intro g, refine ⟨λ x, if h : ∃ y, f y = x then g h.some else 0, _⟩, { ext, dsimp only [fun_left_apply], split_ifs with w, { congr, exact hf w.some_spec, }, { simpa only [not_true, exists_apply_eq_apply] using w } }, end theorem fun_left_injective_of_surjective (f : m → n) (hf : surjective f) : injective (fun_left R M f) := begin obtain ⟨g, hg⟩ := hf.has_right_inverse, suffices : left_inverse (fun_left R M g) (fun_left R M f), { exact this.injective }, intro x, rw [←linear_map.comp_apply, ← fun_left_comp, hg.id, fun_left_id], end end linear_map namespace linear_equiv open _root_.linear_map /-- Given an `R`-module `M` and an equivalence `m ≃ n` between arbitrary types, construct a linear equivalence `(n → M) ≃ₗ[R] (m → M)` -/ def fun_congr_left (e : m ≃ n) : (n → M) ≃ₗ[R] (m → M) := linear_equiv.of_linear (fun_left R M e) (fun_left R M e.symm) (linear_map.ext $ λ x, funext $ λ i, by rw [id_apply, ← fun_left_comp, equiv.symm_comp_self, fun_left_id]) (linear_map.ext $ λ x, funext $ λ i, by rw [id_apply, ← fun_left_comp, equiv.self_comp_symm, fun_left_id]) @[simp] theorem fun_congr_left_apply (e : m ≃ n) (x : n → M) : fun_congr_left R M e x = fun_left R M e x := rfl @[simp] theorem fun_congr_left_id : fun_congr_left R M (equiv.refl n) = linear_equiv.refl R (n → M) := rfl @[simp] theorem fun_congr_left_comp (e₁ : m ≃ n) (e₂ : n ≃ p) : fun_congr_left R M (equiv.trans e₁ e₂) = linear_equiv.trans (fun_congr_left R M e₂) (fun_congr_left R M e₁) := rfl @[simp] lemma fun_congr_left_symm (e : m ≃ n) : (fun_congr_left R M e).symm = fun_congr_left R M e.symm := rfl end linear_equiv end fun_left namespace linear_equiv variables [semiring R] [add_comm_monoid M] [module R M] variables (R M) instance automorphism_group : group (M ≃ₗ[R] M) := { mul := λ f g, g.trans f, one := linear_equiv.refl R M, inv := λ f, f.symm, mul_assoc := λ f g h, by {ext, refl}, mul_one := λ f, by {ext, refl}, one_mul := λ f, by {ext, refl}, mul_left_inv := λ f, by {ext, exact f.left_inv x} } /-- Restriction from `R`-linear automorphisms of `M` to `R`-linear endomorphisms of `M`, promoted to a monoid hom. -/ def automorphism_group.to_linear_map_monoid_hom : (M ≃ₗ[R] M) →* (M →ₗ[R] M) := { to_fun := coe, map_one' := rfl, map_mul' := λ _ _, rfl } /-- The tautological action by `M ≃ₗ[R] M` on `M`. This generalizes `function.End.apply_mul_action`. -/ instance apply_distrib_mul_action : distrib_mul_action (M ≃ₗ[R] M) M := { smul := ($), smul_zero := linear_equiv.map_zero, smul_add := linear_equiv.map_add, one_smul := λ _, rfl, mul_smul := λ _ _ _, rfl } @[simp] protected lemma smul_def (f : M ≃ₗ[R] M) (a : M) : f • a = f a := rfl /-- `linear_equiv.apply_distrib_mul_action` is faithful. -/ instance apply_has_faithful_scalar : has_faithful_scalar (M ≃ₗ[R] M) M := ⟨λ _ _, linear_equiv.ext⟩ instance apply_smul_comm_class : smul_comm_class R (M ≃ₗ[R] M) M := { smul_comm := λ r e m, (e.map_smul r m).symm } instance apply_smul_comm_class' : smul_comm_class (M ≃ₗ[R] M) R M := { smul_comm := linear_equiv.map_smul } end linear_equiv namespace linear_map variables [semiring R] [add_comm_monoid M] [module R M] variables (R M) /-- The group of invertible linear maps from `M` to itself -/ @[reducible] def general_linear_group := units (M →ₗ[R] M) namespace general_linear_group variables {R M} instance : has_coe_to_fun (general_linear_group R M) (λ _, M → M) := by apply_instance /-- An invertible linear map `f` determines an equivalence from `M` to itself. -/ def to_linear_equiv (f : general_linear_group R M) : (M ≃ₗ[R] M) := { inv_fun := f.inv.to_fun, left_inv := λ m, show (f.inv * f.val) m = m, by erw f.inv_val; simp, right_inv := λ m, show (f.val * f.inv) m = m, by erw f.val_inv; simp, ..f.val } /-- An equivalence from `M` to itself determines an invertible linear map. -/ def of_linear_equiv (f : (M ≃ₗ[R] M)) : general_linear_group R M := { val := f, inv := (f.symm : M →ₗ[R] M), val_inv := linear_map.ext $ λ _, f.apply_symm_apply _, inv_val := linear_map.ext $ λ _, f.symm_apply_apply _ } variables (R M) /-- The general linear group on `R` and `M` is multiplicatively equivalent to the type of linear equivalences between `M` and itself. -/ def general_linear_equiv : general_linear_group R M ≃* (M ≃ₗ[R] M) := { to_fun := to_linear_equiv, inv_fun := of_linear_equiv, left_inv := λ f, by { ext, refl }, right_inv := λ f, by { ext, refl }, map_mul' := λ x y, by {ext, refl} } @[simp] lemma general_linear_equiv_to_linear_map (f : general_linear_group R M) : (general_linear_equiv R M f : M →ₗ[R] M) = f := by {ext, refl} end general_linear_group end linear_map namespace submodule variables [ring R] [add_comm_group M] [module R M] instance : is_modular_lattice (submodule R M) := ⟨λ x y z xz a ha, begin rw [mem_inf, mem_sup] at ha, rcases ha with ⟨⟨b, hb, c, hc, rfl⟩, haz⟩, rw mem_sup, refine ⟨b, hb, c, mem_inf.2 ⟨hc, _⟩, rfl⟩, rw [← add_sub_cancel c b, add_comm], apply z.sub_mem haz (xz hb), end⟩ end submodule
a2534d9f5034c62f8a19038571549d00daf7e7d0
19cc34575500ee2e3d4586c15544632aa07a8e66
/src/data/set/function.lean
4d1aa8fdc07e3fe7ac49c9a5987961abca6002cc
[ "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
25,326
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad, Andrew Zipperer, Haitao Zhang, Minchao Wu, Yury Kudryashov -/ import data.set.basic import logic.function.conjugate /-! # Functions over sets ## Main definitions ### Predicate * `eq_on f₁ f₂ s` : functions `f₁` and `f₂` are equal at every point of `s`; * `maps_to f s t` : `f` sends every point of `s` to a point of `t`; * `inj_on f s` : restriction of `f` to `s` is injective; * `surj_on f s t` : every point in `s` has a preimage in `s`; * `bij_on f s t` : `f` is a bijection between `s` and `t`; * `left_inv_on f' f s` : for every `x ∈ s` we have `f' (f x) = x`; * `right_inv_on f' f t` : for every `y ∈ t` we have `f (f' y) = y`; * `inv_on f' f s t` : `f'` is a two-side inverse of `f` on `s` and `t`, i.e. we have `left_inv_on f' f s` and `right_inv_on f' f t`. ### Functions * `restrict f s` : restrict the domain of `f` to the set `s`; * `cod_restrict f s h` : given `h : ∀ x, f x ∈ s`, restrict the codomain of `f` to the set `s`; * `maps_to.restrict f s t h`: given `h : maps_to f s t`, restrict the domain of `f` to `s` and the codomain to `t`. -/ universes u v w x y variables {α : Type u} {β : Type v} {γ : Type w} {ι : Sort x} open function namespace set /-! ### Restrict -/ /-- Restrict domain of a function `f` to a set `s`. Same as `subtype.restrict` but this version takes an argument `↥s` instead of `subtype s`. -/ def restrict (f : α → β) (s : set α) : s → β := λ x, f x lemma restrict_eq (f : α → β) (s : set α) : s.restrict f = f ∘ coe := rfl @[simp] lemma restrict_apply (f : α → β) (s : set α) (x : s) : restrict f s x = f x := rfl @[simp] lemma range_restrict (f : α → β) (s : set α) : set.range (restrict f s) = f '' s := range_comp.trans $ congr_arg (('') f) subtype.range_coe /-- Restrict codomain of a function `f` to a set `s`. Same as `subtype.coind` but this version has codomain `↥s` instead of `subtype s`. -/ def cod_restrict (f : α → β) (s : set β) (h : ∀ x, f x ∈ s) : α → s := λ x, ⟨f x, h x⟩ @[simp] lemma coe_cod_restrict_apply (f : α → β) (s : set β) (h : ∀ x, f x ∈ s) (x : α) : (cod_restrict f s h x : β) = f x := rfl variables {s s₁ s₂ : set α} {t t₁ t₂ : set β} {p : set γ} {f f₁ f₂ f₃ : α → β} {g : β → γ} {f' f₁' f₂' : β → α} {g' : γ → β} /-! ### Equality on a set -/ /-- Two functions `f₁ f₂ : α → β` are equal on `s` if `f₁ x = f₂ x` for all `x ∈ a`. -/ @[reducible] def eq_on (f₁ f₂ : α → β) (s : set α) : Prop := ∀ ⦃x⦄, x ∈ s → f₁ x = f₂ x @[symm] lemma eq_on.symm (h : eq_on f₁ f₂ s) : eq_on f₂ f₁ s := λ x hx, (h hx).symm lemma eq_on_comm : eq_on f₁ f₂ s ↔ eq_on f₂ f₁ s := ⟨eq_on.symm, eq_on.symm⟩ @[refl] lemma eq_on_refl (f : α → β) (s : set α) : eq_on f f s := λ _ _, rfl @[trans] lemma eq_on.trans (h₁ : eq_on f₁ f₂ s) (h₂ : eq_on f₂ f₃ s) : eq_on f₁ f₃ s := λ x hx, (h₁ hx).trans (h₂ hx) theorem eq_on.image_eq (heq : eq_on f₁ f₂ s) : f₁ '' s = f₂ '' s := image_congr heq lemma eq_on.mono (hs : s₁ ⊆ s₂) (hf : eq_on f₁ f₂ s₂) : eq_on f₁ f₂ s₁ := λ x hx, hf (hs hx) lemma comp_eq_of_eq_on_range {ι : Sort*} {f : ι → α} {g₁ g₂ : α → β} (h : eq_on g₁ g₂ (range f)) : g₁ ∘ f = g₂ ∘ f := funext $ λ x, h $ mem_range_self _ /-! ### maps to -/ /-- `maps_to f a b` means that the image of `a` is contained in `b`. -/ @[reducible] def maps_to (f : α → β) (s : set α) (t : set β) : Prop := ∀ ⦃x⦄, x ∈ s → f x ∈ t /-- Given a map `f` sending `s : set α` into `t : set β`, restrict domain of `f` to `s` and the codomain to `t`. Same as `subtype.map`. -/ def maps_to.restrict (f : α → β) (s : set α) (t : set β) (h : maps_to f s t) : s → t := subtype.map f h @[simp] lemma maps_to.coe_restrict_apply (h : maps_to f s t) (x : s) : (h.restrict f s t x : β) = f x := rfl theorem maps_to' : maps_to f s t ↔ f '' s ⊆ t := image_subset_iff.symm theorem maps_to_empty (f : α → β) (t : set β) : maps_to f ∅ t := empty_subset _ theorem maps_to.image_subset (h : maps_to f s t) : f '' s ⊆ t := maps_to'.1 h theorem maps_to.congr (h₁ : maps_to f₁ s t) (h : eq_on f₁ f₂ s) : maps_to f₂ s t := λ x hx, h hx ▸ h₁ hx theorem eq_on.maps_to_iff (H : eq_on f₁ f₂ s) : maps_to f₁ s t ↔ maps_to f₂ s t := ⟨λ h, h.congr H, λ h, h.congr H.symm⟩ theorem maps_to.comp (h₁ : maps_to g t p) (h₂ : maps_to f s t) : maps_to (g ∘ f) s p := λ x h, h₁ (h₂ h) theorem maps_to.iterate {f : α → α} {s : set α} (h : maps_to f s s) : ∀ n, maps_to (f^[n]) s s | 0 := λ _, id | (n+1) := (maps_to.iterate n).comp h theorem maps_to.iterate_restrict {f : α → α} {s : set α} (h : maps_to f s s) (n : ℕ) : (h.restrict f s s^[n]) = (h.iterate n).restrict _ _ _ := begin funext x, rw [subtype.ext_iff, maps_to.coe_restrict_apply], induction n with n ihn generalizing x, { refl }, { simp [nat.iterate, ihn] } end theorem maps_to.mono (hs : s₂ ⊆ s₁) (ht : t₁ ⊆ t₂) (hf : maps_to f s₁ t₁) : maps_to f s₂ t₂ := λ x hx, ht (hf $ hs hx) theorem maps_to.union_union (h₁ : maps_to f s₁ t₁) (h₂ : maps_to f s₂ t₂) : maps_to f (s₁ ∪ s₂) (t₁ ∪ t₂) := λ x hx, hx.elim (λ hx, or.inl $ h₁ hx) (λ hx, or.inr $ h₂ hx) theorem maps_to.union (h₁ : maps_to f s₁ t) (h₂ : maps_to f s₂ t) : maps_to f (s₁ ∪ s₂) t := union_self t ▸ h₁.union_union h₂ theorem maps_to.inter (h₁ : maps_to f s t₁) (h₂ : maps_to f s t₂) : maps_to f s (t₁ ∩ t₂) := λ x hx, ⟨h₁ hx, h₂ hx⟩ theorem maps_to.inter_inter (h₁ : maps_to f s₁ t₁) (h₂ : maps_to f s₂ t₂) : maps_to f (s₁ ∩ s₂) (t₁ ∩ t₂) := λ x hx, ⟨h₁ hx.1, h₂ hx.2⟩ theorem maps_to_univ (f : α → β) (s : set α) : maps_to f s univ := λ x h, trivial theorem maps_to_image (f : α → β) (s : set α) : maps_to f s (f '' s) := by rw maps_to' theorem maps_to_preimage (f : α → β) (t : set β) : maps_to f (f ⁻¹' t) t := subset.refl _ theorem maps_to_range (f : set α) (s : set α) : maps_to f s (range f) := (maps_to_image f s).mono (subset.refl s) (image_subset_range _ _) /-! ### Injectivity on a set -/ /-- `f` is injective on `a` if the restriction of `f` to `a` is injective. -/ @[reducible] def inj_on (f : α → β) (s : set α) : Prop := ∀ ⦃x₁ : α⦄, x₁ ∈ s → ∀ ⦃x₂ : α⦄, x₂ ∈ s → f x₁ = f x₂ → x₁ = x₂ theorem inj_on_empty (f : α → β) : inj_on f ∅ := λ _ h₁, false.elim h₁ theorem inj_on.congr (h₁ : inj_on f₁ s) (h : eq_on f₁ f₂ s) : inj_on f₂ s := λ x hx y hy, h hx ▸ h hy ▸ h₁ hx hy theorem eq_on.inj_on_iff (H : eq_on f₁ f₂ s) : inj_on f₁ s ↔ inj_on f₂ s := ⟨λ h, h.congr H, λ h, h.congr H.symm⟩ theorem inj_on.mono (h : s₁ ⊆ s₂) (ht : inj_on f s₂) : inj_on f s₁ := λ x hx y hy H, ht (h hx) (h hy) H theorem inj_on_insert {f : α → β} {s : set α} {a : α} (has : a ∉ s) : set.inj_on f (insert a s) ↔ set.inj_on f s ∧ f a ∉ f '' s := ⟨λ hf, ⟨hf.mono $ subset_insert a s, λ ⟨x, hxs, hx⟩, has $ mem_of_eq_of_mem (hf (or.inl rfl) (or.inr hxs) hx.symm) hxs⟩, λ ⟨h1, h2⟩ x hx y hy hfxy, or.cases_on hx (λ hxa : x = a, or.cases_on hy (λ hya : y = a, hxa.trans hya.symm) (λ hys : y ∈ s, h2.elim ⟨y, hys, hxa ▸ hfxy.symm⟩)) (λ hxs : x ∈ s, or.cases_on hy (λ hya : y = a, h2.elim ⟨x, hxs, hya ▸ hfxy⟩) (λ hys : y ∈ s, h1 hxs hys hfxy))⟩ lemma injective_iff_inj_on_univ : injective f ↔ inj_on f univ := ⟨λ h x hx y hy hxy, h hxy, λ h _ _ heq, h trivial trivial heq⟩ theorem inj_on.comp (hg : inj_on g t) (hf: inj_on f s) (h : maps_to f s t) : inj_on (g ∘ f) s := λ x hx y hy heq, hf hx hy $ hg (h hx) (h hy) heq lemma inj_on_iff_injective : inj_on f s ↔ injective (restrict f s) := ⟨λ H a b h, subtype.eq $ H a.2 b.2 h, λ H a as b bs h, congr_arg subtype.val $ @H ⟨a, as⟩ ⟨b, bs⟩ h⟩ lemma inj_on.inv_fun_on_image [nonempty α] (h : inj_on f s₂) (ht : s₁ ⊆ s₂) : (inv_fun_on f s₂) '' (f '' s₁) = s₁ := begin have : eq_on ((inv_fun_on f s₂) ∘ f) id s₁, from λz hz, inv_fun_on_eq' h (ht hz), rw [← image_comp, this.image_eq, image_id] end lemma inj_on_preimage {B : set (set β)} (hB : B ⊆ powerset (range f)) : inj_on (preimage f) B := λ s hs t ht hst, (preimage_eq_preimage' (hB hs) (hB ht)).1 hst /-! ### Surjectivity on a set -/ /-- `f` is surjective from `a` to `b` if `b` is contained in the image of `a`. -/ @[reducible] def surj_on (f : α → β) (s : set α) (t : set β) : Prop := t ⊆ f '' s theorem surj_on.subset_range (h : surj_on f s t) : t ⊆ range f := subset.trans h $ image_subset_range f s theorem surj_on_empty (f : α → β) (s : set α) : surj_on f s ∅ := empty_subset _ theorem surj_on.comap_nonempty (h : surj_on f s t) (ht : t.nonempty) : s.nonempty := (ht.mono h).of_image theorem surj_on.congr (h : surj_on f₁ s t) (H : eq_on f₁ f₂ s) : surj_on f₂ s t := by rwa [surj_on, ← H.image_eq] theorem eq_on.surj_on_iff (h : eq_on f₁ f₂ s) : surj_on f₁ s t ↔ surj_on f₂ s t := ⟨λ H, H.congr h, λ H, H.congr h.symm⟩ theorem surj_on.mono (hs : s₁ ⊆ s₂) (ht : t₁ ⊆ t₂) (hf : surj_on f s₁ t₂) : surj_on f s₂ t₁ := subset.trans ht $ subset.trans hf $ image_subset _ hs theorem surj_on.union (h₁ : surj_on f s t₁) (h₂ : surj_on f s t₂) : surj_on f s (t₁ ∪ t₂) := λ x hx, hx.elim (λ hx, h₁ hx) (λ hx, h₂ hx) theorem surj_on.union_union (h₁ : surj_on f s₁ t₁) (h₂ : surj_on f s₂ t₂) : surj_on f (s₁ ∪ s₂) (t₁ ∪ t₂) := (h₁.mono (subset_union_left _ _) (subset.refl _)).union (h₂.mono (subset_union_right _ _) (subset.refl _)) theorem surj_on.inter_inter (h₁ : surj_on f s₁ t₁) (h₂ : surj_on f s₂ t₂) (h : inj_on f (s₁ ∪ s₂)) : surj_on f (s₁ ∩ s₂) (t₁ ∩ t₂) := begin intros y hy, rcases h₁ hy.1 with ⟨x₁, hx₁, rfl⟩, rcases h₂ hy.2 with ⟨x₂, hx₂, heq⟩, have : x₁ = x₂, from h (or.inl hx₁) (or.inr hx₂) heq.symm, subst x₂, exact mem_image_of_mem f ⟨hx₁, hx₂⟩ end theorem surj_on.inter (h₁ : surj_on f s₁ t) (h₂ : surj_on f s₂ t) (h : inj_on f (s₁ ∪ s₂)) : surj_on f (s₁ ∩ s₂) t := inter_self t ▸ h₁.inter_inter h₂ h theorem surj_on.comp (hg : surj_on g t p) (hf : surj_on f s t) : surj_on (g ∘ f) s p := subset.trans hg $ subset.trans (image_subset g hf) $ (image_comp g f s) ▸ subset.refl _ lemma surjective_iff_surj_on_univ : surjective f ↔ surj_on f univ univ := by simp [surjective, surj_on, subset_def] lemma surj_on_iff_surjective : surj_on f s univ ↔ surjective (restrict f s) := ⟨λ H b, let ⟨a, as, e⟩ := @H b trivial in ⟨⟨a, as⟩, e⟩, λ H b _, let ⟨⟨a, as⟩, e⟩ := H b in ⟨a, as, e⟩⟩ lemma surj_on.image_eq_of_maps_to (h₁ : surj_on f s t) (h₂ : maps_to f s t) : f '' s = t := eq_of_subset_of_subset h₂.image_subset h₁ /-! ### Bijectivity -/ /-- `f` is bijective from `s` to `t` if `f` is injective on `s` and `f '' s = t`. -/ @[reducible] def bij_on (f : α → β) (s : set α) (t : set β) : Prop := maps_to f s t ∧ inj_on f s ∧ surj_on f s t lemma bij_on.maps_to (h : bij_on f s t) : maps_to f s t := h.left lemma bij_on.inj_on (h : bij_on f s t) : inj_on f s := h.right.left lemma bij_on.surj_on (h : bij_on f s t) : surj_on f s t := h.right.right lemma bij_on.mk (h₁ : maps_to f s t) (h₂ : inj_on f s) (h₃ : surj_on f s t) : bij_on f s t := ⟨h₁, h₂, h₃⟩ lemma bij_on_empty (f : α → β) : bij_on f ∅ ∅ := ⟨maps_to_empty f ∅, inj_on_empty f, surj_on_empty f ∅⟩ lemma bij_on.inter (h₁ : bij_on f s₁ t₁) (h₂ : bij_on f s₂ t₂) (h : inj_on f (s₁ ∪ s₂)) : bij_on f (s₁ ∩ s₂) (t₁ ∩ t₂) := ⟨h₁.maps_to.inter_inter h₂.maps_to, h₁.inj_on.mono $ inter_subset_left _ _, h₁.surj_on.inter_inter h₂.surj_on h⟩ lemma bij_on.union (h₁ : bij_on f s₁ t₁) (h₂ : bij_on f s₂ t₂) (h : inj_on f (s₁ ∪ s₂)) : bij_on f (s₁ ∪ s₂) (t₁ ∪ t₂) := ⟨h₁.maps_to.union_union h₂.maps_to, h, h₁.surj_on.union_union h₂.surj_on⟩ theorem bij_on.subset_range (h : bij_on f s t) : t ⊆ range f := h.surj_on.subset_range lemma inj_on.bij_on_image (h : inj_on f s) : bij_on f s (f '' s) := bij_on.mk (maps_to_image f s) h (subset.refl _) theorem bij_on.congr (h₁ : bij_on f₁ s t) (h : eq_on f₁ f₂ s) : bij_on f₂ s t := bij_on.mk (h₁.maps_to.congr h) (h₁.inj_on.congr h) (h₁.surj_on.congr h) theorem eq_on.bij_on_iff (H : eq_on f₁ f₂ s) : bij_on f₁ s t ↔ bij_on f₂ s t := ⟨λ h, h.congr H, λ h, h.congr H.symm⟩ lemma bij_on.image_eq (h : bij_on f s t) : f '' s = t := h.surj_on.image_eq_of_maps_to h.maps_to theorem bij_on.comp (hg : bij_on g t p) (hf : bij_on f s t) : bij_on (g ∘ f) s p := bij_on.mk (hg.maps_to.comp hf.maps_to) (hg.inj_on.comp hf.inj_on hf.maps_to) (hg.surj_on.comp hf.surj_on) lemma bijective_iff_bij_on_univ : bijective f ↔ bij_on f univ univ := iff.intro (λ h, let ⟨inj, surj⟩ := h in ⟨maps_to_univ f _, iff.mp injective_iff_inj_on_univ inj, iff.mp surjective_iff_surj_on_univ surj⟩) (λ h, let ⟨map, inj, surj⟩ := h in ⟨iff.mpr injective_iff_inj_on_univ inj, iff.mpr surjective_iff_surj_on_univ surj⟩) /-! ### left inverse -/ /-- `g` is a left inverse to `f` on `a` means that `g (f x) = x` for all `x ∈ a`. -/ @[reducible] def left_inv_on (f' : β → α) (f : α → β) (s : set α) : Prop := ∀ ⦃x⦄, x ∈ s → f' (f x) = x lemma left_inv_on.eq_on (h : left_inv_on f' f s) : eq_on (f' ∘ f) id s := h lemma left_inv_on.eq (h : left_inv_on f' f s) {x} (hx : x ∈ s) : f' (f x) = x := h hx lemma left_inv_on.congr_left (h₁ : left_inv_on f₁' f s) {t : set β} (h₁' : maps_to f s t) (heq : eq_on f₁' f₂' t) : left_inv_on f₂' f s := λ x hx, heq (h₁' hx) ▸ h₁ hx theorem left_inv_on.congr_right (h₁ : left_inv_on f₁' f₁ s) (heq : eq_on f₁ f₂ s) : left_inv_on f₁' f₂ s := λ x hx, heq hx ▸ h₁ hx theorem left_inv_on.inj_on (h : left_inv_on f₁' f s) : inj_on f s := λ x₁ h₁ x₂ h₂ heq, calc x₁ = f₁' (f x₁) : eq.symm $ h h₁ ... = f₁' (f x₂) : congr_arg f₁' heq ... = x₂ : h h₂ theorem left_inv_on.surj_on (h : left_inv_on f₁' f s) (hf : maps_to f s t) : surj_on f₁' t s := λ x hx, ⟨f x, hf hx, h hx⟩ theorem left_inv_on.comp (hf' : left_inv_on f' f s) (hg' : left_inv_on g' g t) (hf : maps_to f s t) : left_inv_on (f' ∘ g') (g ∘ f) s := λ x h, calc (f' ∘ g') ((g ∘ f) x) = f' (f x) : congr_arg f' (hg' (hf h)) ... = x : hf' h /-! ### Right inverse -/ /-- `g` is a right inverse to `f` on `b` if `f (g x) = x` for all `x ∈ b`. -/ @[reducible] def right_inv_on (f' : β → α) (f : α → β) (t : set β) : Prop := left_inv_on f f' t lemma right_inv_on.eq_on (h : right_inv_on f' f t) : eq_on (f ∘ f') id t := h lemma right_inv_on.eq (h : right_inv_on f' f t) {y} (hy : y ∈ t) : f (f' y) = y := h hy theorem right_inv_on.congr_left (h₁ : right_inv_on f₁' f t) (heq : eq_on f₁' f₂' t) : right_inv_on f₂' f t := h₁.congr_right heq theorem right_inv_on.congr_right (h₁ : right_inv_on f' f₁ t) (hg : maps_to f' t s) (heq : eq_on f₁ f₂ s) : right_inv_on f' f₂ t := left_inv_on.congr_left h₁ hg heq theorem right_inv_on.surj_on (hf : right_inv_on f' f t) (hf' : maps_to f' t s) : surj_on f s t := hf.surj_on hf' theorem right_inv_on.comp (hf : right_inv_on f' f t) (hg : right_inv_on g' g p) (g'pt : maps_to g' p t) : right_inv_on (f' ∘ g') (g ∘ f) p := hg.comp hf g'pt theorem inj_on.right_inv_on_of_left_inv_on (hf : inj_on f s) (hf' : left_inv_on f f' t) (h₁ : maps_to f s t) (h₂ : maps_to f' t s) : right_inv_on f f' s := λ x h, hf (h₂ $ h₁ h) h (hf' (h₁ h)) theorem eq_on_of_left_inv_on_of_right_inv_on (h₁ : left_inv_on f₁' f s) (h₂ : right_inv_on f₂' f t) (h : maps_to f₂' t s) : eq_on f₁' f₂' t := λ y hy, calc f₁' y = (f₁' ∘ f ∘ f₂') y : congr_arg f₁' (h₂ hy).symm ... = f₂' y : h₁ (h hy) theorem surj_on.left_inv_on_of_right_inv_on (hf : surj_on f s t) (hf' : right_inv_on f f' s) : left_inv_on f f' t := λ y hy, let ⟨x, hx, heq⟩ := hf hy in by rw [← heq, hf' hx] /-! ### Two-side inverses -/ /-- `g` is an inverse to `f` viewed as a map from `a` to `b` -/ @[reducible] def inv_on (g : β → α) (f : α → β) (s : set α) (t : set β) : Prop := left_inv_on g f s ∧ right_inv_on g f t lemma inv_on.symm (h : inv_on f' f s t) : inv_on f f' t s := ⟨h.right, h.left⟩ theorem inv_on.bij_on (h : inv_on f' f s t) (hf : maps_to f s t) (hf' : maps_to f' t s) : bij_on f s t := ⟨hf, h.left.inj_on, h.right.surj_on hf'⟩ /-! ### `inv_fun_on` is a left/right inverse -/ theorem inj_on.left_inv_on_inv_fun_on [nonempty α] (h : inj_on f s) : left_inv_on (inv_fun_on f s) f s := λ x hx, inv_fun_on_eq' h hx theorem surj_on.right_inv_on_inv_fun_on [nonempty α] (h : surj_on f s t) : right_inv_on (inv_fun_on f s) f t := λ y hy, inv_fun_on_eq $ mem_image_iff_bex.1 $ h hy theorem bij_on.inv_on_inv_fun_on [nonempty α] (h : bij_on f s t) : inv_on (inv_fun_on f s) f s t := ⟨h.inj_on.left_inv_on_inv_fun_on, h.surj_on.right_inv_on_inv_fun_on⟩ theorem surj_on.inv_on_inv_fun_on [nonempty α] (h : surj_on f s t) : inv_on (inv_fun_on f s) f (inv_fun_on f s '' t) t := begin refine ⟨_, h.right_inv_on_inv_fun_on⟩, rintros _ ⟨y, hy, rfl⟩, rw [h.right_inv_on_inv_fun_on hy] end theorem surj_on.maps_to_inv_fun_on [nonempty α] (h : surj_on f s t) : maps_to (inv_fun_on f s) t s := λ y hy, mem_preimage.2 $ inv_fun_on_mem $ mem_image_iff_bex.1 $ h hy theorem surj_on.bij_on_subset [nonempty α] (h : surj_on f s t) : bij_on f (inv_fun_on f s '' t) t := begin refine h.inv_on_inv_fun_on.bij_on _ (maps_to_image _ _), rintros _ ⟨y, hy, rfl⟩, rwa [h.right_inv_on_inv_fun_on hy] end theorem surj_on_iff_exists_bij_on_subset : surj_on f s t ↔ ∃ s' ⊆ s, bij_on f s' t := begin split, { rcases eq_empty_or_nonempty t with rfl|ht, { exact λ _, ⟨∅, empty_subset _, bij_on_empty f⟩ }, { assume h, haveI : nonempty α := ⟨classical.some (h.comap_nonempty ht)⟩, exact ⟨_, h.maps_to_inv_fun_on.image_subset, h.bij_on_subset⟩ }}, { rintros ⟨s', hs', hfs'⟩, exact hfs'.surj_on.mono hs' (subset.refl _) } end end set /-! ### Piecewise defined function -/ namespace set variables {δ : α → Sort y} (s : set α) (f g : Πi, δ i) @[simp] lemma piecewise_empty [∀i : α, decidable (i ∈ (∅ : set α))] : piecewise ∅ f g = g := by { ext i, simp [piecewise] } @[simp] lemma piecewise_univ [∀i : α, decidable (i ∈ (set.univ : set α))] : piecewise set.univ f g = f := by { ext i, simp [piecewise] } @[simp] lemma piecewise_insert_self {j : α} [∀i, decidable (i ∈ insert j s)] : (insert j s).piecewise f g j = f j := by simp [piecewise] variable [∀j, decidable (j ∈ s)] instance compl.decidable_mem (j : α) : decidable (j ∈ sᶜ) := not.decidable lemma piecewise_insert [decidable_eq α] (j : α) [∀i, decidable (i ∈ insert j s)] : (insert j s).piecewise f g = function.update (s.piecewise f g) j (f j) := begin simp [piecewise], ext i, by_cases h : i = j, { rw h, simp }, { by_cases h' : i ∈ s; simp [h, h'] } end @[simp, priority 990] lemma piecewise_eq_of_mem {i : α} (hi : i ∈ s) : s.piecewise f g i = f i := by simp [piecewise, hi] @[simp, priority 990] lemma piecewise_eq_of_not_mem {i : α} (hi : i ∉ s) : s.piecewise f g i = g i := by simp [piecewise, hi] lemma piecewise_eq_on (f g : α → β) : eq_on (s.piecewise f g) f s := λ _, piecewise_eq_of_mem _ _ _ lemma piecewise_eq_on_compl (f g : α → β) : eq_on (s.piecewise f g) g sᶜ := λ _, piecewise_eq_of_not_mem _ _ _ @[simp, priority 990] lemma piecewise_insert_of_ne {i j : α} (h : i ≠ j) [∀i, decidable (i ∈ insert j s)] : (insert j s).piecewise f g i = s.piecewise f g i := by simp [piecewise, h] @[simp] lemma piecewise_compl [∀ i, decidable (i ∈ sᶜ)] : sᶜ.piecewise f g = s.piecewise g f := funext $ λ x, if hx : x ∈ s then by simp [hx] else by simp [hx] @[simp] lemma piecewise_range_comp {ι : Sort*} (f : ι → α) [Π j, decidable (j ∈ range f)] (g₁ g₂ : α → β) : (range f).piecewise g₁ g₂ ∘ f = g₁ ∘ f := comp_eq_of_eq_on_range $ piecewise_eq_on _ _ _ lemma piecewise_preimage (f g : α → β) (t) : s.piecewise f g ⁻¹' t = s ∩ f ⁻¹' t ∪ sᶜ ∩ g ⁻¹' t := ext $ λ x, by by_cases x ∈ s; simp * lemma comp_piecewise (h : β → γ) {f g : α → β} {x : α} : h (s.piecewise f g x) = s.piecewise (h ∘ f) (h ∘ g) x := by by_cases hx : x ∈ s; simp [hx] @[simp] lemma piecewise_same : s.piecewise f f = f := by { ext x, by_cases hx : x ∈ s; simp [hx] } lemma range_piecewise (f g : α → β) : range (s.piecewise f g) = f '' s ∪ g '' sᶜ := begin ext y, split, { rintro ⟨x, rfl⟩, by_cases h : x ∈ s;[left, right]; use x; simp [h] }, { rintro (⟨x, hx, rfl⟩|⟨x, hx, rfl⟩); use x; simp * at * } end end set lemma strict_mono_incr_on.inj_on [linear_order α] [preorder β] {f : α → β} {s : set α} (H : strict_mono_incr_on f s) : s.inj_on f := λ x hx y hy hxy, show ordering.eq.compares x y, from (H.compares hx hy).1 hxy lemma strict_mono_decr_on.inj_on [linear_order α] [preorder β] {f : α → β} {s : set α} (H : strict_mono_decr_on f s) : s.inj_on f := @strict_mono_incr_on.inj_on α (order_dual β) _ _ f s H namespace function open set variables {fa : α → α} {fb : β → β} {f : α → β} {g : β → γ} {s t : set α} lemma injective.inj_on (h : injective f) (s : set α) : s.inj_on f := λ _ _ _ _ heq, h heq lemma injective.comp_inj_on (hg : injective g) (hf : s.inj_on f) : s.inj_on (g ∘ f) := (hg.inj_on univ).comp hf (maps_to_univ _ _) lemma surjective.surj_on (hf : surjective f) (s : set β) : surj_on f univ s := (surjective_iff_surj_on_univ.1 hf).mono (subset.refl _) (subset_univ _) namespace semiconj lemma maps_to_image (h : semiconj f fa fb) (ha : maps_to fa s t) : maps_to fb (f '' s) (f '' t) := λ y ⟨x, hx, hy⟩, hy ▸ ⟨fa x, ha hx, h x⟩ lemma maps_to_range (h : semiconj f fa fb) : maps_to fb (range f) (range f) := λ y ⟨x, hy⟩, hy ▸ ⟨fa x, h x⟩ lemma surj_on_image (h : semiconj f fa fb) (ha : surj_on fa s t) : surj_on fb (f '' s) (f '' t) := begin rintros y ⟨x, hxt, rfl⟩, rcases ha hxt with ⟨x, hxs, rfl⟩, rw [h x], exact mem_image_of_mem _ (mem_image_of_mem _ hxs) end lemma surj_on_range (h : semiconj f fa fb) (ha : surjective fa) : surj_on fb (range f) (range f) := by { rw ← image_univ, exact h.surj_on_image (ha.surj_on univ) } lemma inj_on_image (h : semiconj f fa fb) (ha : inj_on fa s) (hf : inj_on f (fa '' s)) : inj_on fb (f '' s) := begin rintros _ ⟨x, hx, rfl⟩ _ ⟨y, hy, rfl⟩ H, simp only [← h.eq] at H, exact congr_arg f (ha hx hy $ hf (mem_image_of_mem fa hx) (mem_image_of_mem fa hy) H) end lemma inj_on_range (h : semiconj f fa fb) (ha : injective fa) (hf : inj_on f (range fa)) : inj_on fb (range f) := by { rw ← image_univ at *, exact h.inj_on_image (ha.inj_on univ) hf } lemma bij_on_image (h : semiconj f fa fb) (ha : bij_on fa s t) (hf : inj_on f t) : bij_on fb (f '' s) (f '' t) := ⟨h.maps_to_image ha.maps_to, h.inj_on_image ha.inj_on (ha.image_eq.symm ▸ hf), h.surj_on_image ha.surj_on⟩ lemma bij_on_range (h : semiconj f fa fb) (ha : bijective fa) (hf : injective f) : bij_on fb (range f) (range f) := begin rw [← image_univ], exact h.bij_on_image (bijective_iff_bij_on_univ.1 ha) (hf.inj_on univ) end lemma maps_to_preimage (h : semiconj f fa fb) {s t : set β} (hb : maps_to fb s t) : maps_to fa (f ⁻¹' s) (f ⁻¹' t) := λ x hx, by simp only [mem_preimage, h x, hb hx] lemma inj_on_preimage (h : semiconj f fa fb) {s : set β} (hb : inj_on fb s) (hf : inj_on f (f ⁻¹' s)) : inj_on fa (f ⁻¹' s) := begin intros x hx y hy H, have := congr_arg f H, rw [h.eq, h.eq] at this, exact hf hx hy (hb hx hy this) end end semiconj lemma update_comp_eq_of_not_mem_range [decidable_eq β] (g : β → γ) {f : α → β} {i : β} (a : γ) (h : i ∉ set.range f) : (function.update g i a) ∘ f = g ∘ f := begin ext p, have : f p ≠ i, { by_contradiction H, push_neg at H, rw ← H at h, exact h (set.mem_range_self _) }, simp [this], end lemma update_comp_eq_of_injective [decidable_eq α] [decidable_eq β] (g : β → γ) {f : α → β} (hf : function.injective f) (i : α) (a : γ) : (function.update g (f i) a) ∘ f = function.update (g ∘ f) i a := begin ext j, by_cases h : j = i, { rw h, simp }, { have : f j ≠ f i := hf.ne h, simp [h, this] } end end function
376e2f9b4a8662c3eada0d18ed589521800bae26
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/Lean3Lib/init/data/unsigned/basic.lean
660ff82c8f4b07d531636a259a9df79077084887
[]
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,962
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.data.fin.basic namespace Mathlib def unsigned_sz : ℕ := Nat.succ (bit1 (bit1 (bit1 (bit1 (bit1 (bit1 (bit1 (bit1 (bit1 (bit1 (bit1 (bit1 (bit1 (bit1 (bit1 (bit1 (bit1 (bit1 (bit1 (bit1 (bit1 (bit1 (bit1 (bit1 (bit1 (bit1 (bit1 (bit1 (bit1 (bit1 (bit1 1))))))))))))))))))))))))))))))) def unsigned := fin unsigned_sz namespace unsigned /- We cannot use tactic dec_trivial here because the tactic framework has not been defined yet. -/ /- Later, we define of_nat using mod, the following version is used to define the metaprogramming system. -/ protected def of_nat' (n : ℕ) : unsigned := dite (n < unsigned_sz) (fun (h : n < unsigned_sz) => { val := n, property := h }) fun (h : ¬n < unsigned_sz) => { val := 0, property := zero_lt_unsigned_sz } def to_nat (c : unsigned) : ℕ := subtype.val c end unsigned protected instance unsigned.decidable_eq : DecidableEq unsigned := (fun (this : DecidableEq (fin unsigned_sz)) => this) (fin.decidable_eq unsigned_sz)
91ef546481f30c731491ffc05b16f5684924911d
79cc757e5e5b09c7a522f717a6c490d321d36469
/src/mywork/practice_2.lean
729c1b7e2065acbff473962cb30e05167f354420
[]
no_license
LukeMathe/cs2120f21
534c3b8868dcfdea98a9d22513180c8a062794c6
d51940b174569a8782e62ae027b108b5f099a9aa
refs/heads/main
1,693,418,664,935
1,634,585,653,000
1,634,585,653,000
403,762,076
0
0
null
1,630,963,485,000
1,630,963,485,000
null
UTF-8
Lean
false
false
13,522
lean
/- Prove the following simple logical conjectures. Give a formal and an English proof of each one. Your English language proofs should be complete in the sense that they identify all the axioms and/or theorems that you use. -/ example : true := true.intro example : false := _ -- trick question? why? /- Cannot prove false, instead prove not true-/ example : ∀ (P : Prop), P ∨ P ↔ P := begin assume P, apply iff.intro _ _, -- forward assume porp, apply or.elim porp, -- left disjunct is true assume p, exact p, -- right disjunct is true assume p, exact p, -- backwards assume p, exact or.intro_left P p, end /-Suppose P is a proposition, and we have a proof that the hyposthesis P ∨ P is true. Using the elimination rule for or, we can conclude that P is true, and thus that P implies P. We do this again for the right side of the or statement. Using the introduction rule for if and only if, we have proved the statement going forwards. Now we need to prove the statement going backwards. Here we assume the hypothesis of P is true, and thus, using the introduction rule for or from the left side, we apply this hypothesis, and prove that P ∨ P is also true. -/ example : ∀ (P : Prop), P ∧ P ↔ P := begin assume P, apply iff.intro _ _, assume p, apply and.elim_left p, assume h, apply and.intro h h, end /-Suppose P is a proposition, and we have a proof of the hypothesis that P ∧ P is true. Using the left and elimination rule, applied to this proof, we find P is true. Using the introduction rule for if and only if, we have proved that P ∧ P implies P. Now we need to prove that P implies P ∧ P. Now we assume we have a proof that the hypothesis of P is true. Using the and introduction rule, we apply this proof twice, and thus have proved that P implies P ∧ P. -/ example : ∀ (P Q : Prop), P ∨ Q ↔ Q ∨ P := begin assume P Q, apply iff.intro _ _, --forwards assume porq, apply or.elim porq _ _, assume p, apply or.intro_right, apply p, assume q, apply or.intro_left, apply q, --backwards assume qorp, apply or.elim qorp _ _, assume q, apply or.intro_right, apply q, assume p, apply or.intro_left, apply p, end /- Suppose that P and Q are propositions, and that we have a proof that P ∨ Q is true. We wand to prove that P ∨ Q implies Q ∨ P, and that Q ∨ P implies P ∨ Q. To prove this going forwards, we apply the or elimination rule to the proof of P ∨ Q, and then assume this is a proof of P we apply this proof of P using the right or introduction rule. Then we assume we have a proof of Q, also from the or elimination rule. We apply the proof of Q to the left or introduction rule, and thus have proved P ∨ Q implies Q ∨ P. To prove it backwards, we assume we have a proof that Q ∨ P is true. We apply the or elimination rule to this proof, and assume this is a proof of Q. We apply the proof of Q using the right or introduction rule. Then we assume we have a proof of P, also from the or elimination rule, and apply this proof using the left or introduction rule, and thus have proved Q ∨ P implies P ∨ Q. We apply the if and only if introduction rule to the two forwards and backwards proofs. -/ example : ∀ (P Q : Prop), P ∧ Q ↔ Q ∧ P := begin assume P Q, apply iff.intro _ _, --forwards assume pandq, apply and.intro _ _, apply and.elim_right pandq, apply and.elim_left pandq, --backwards assume qandp, apply and.intro _ _, apply and.elim_right qandp, apply and.elim_left qandp, end /- Suppose we have propositions P and Q, and that we want to prove P ∧ Q implies Q ∧ P, and vice versa. We assume we have a proof that P ∧ Q is true, and apply the right and elimination rule to this proof, and then the left and elimination rule to this proof. We then apply the and introduction rule to these two applied and elimination rules, and this proves Q ∧ P from P ∧ Q. Now to prove P ∧ Q from Q ∧ P, we assume we have a proof of Q ∧ P, and then apply the right and elimination rule to this proof, and then apply the left and elimination rule to this proof. Then we apply the and introduction rule to these two applied and elimination rules, and this proves P ∧ Q from Q ∧ P. Then we apply the if and only if introduction rule to the forward and backwards proofs. -/ example : ∀ (P Q R : Prop), P ∧ (Q ∨ R) ↔ (P ∧ Q) ∨ (P ∧ R) := begin assume P Q R, apply iff.intro, --forwards assume pandqorr, apply and.elim pandqorr, assume p, assume qorr, apply or.elim qorr _ _, assume q, apply or.intro_left _ _, apply and.intro p q, assume r, apply or.intro_right _ _, apply and.intro p r, --backwards assume pandqorpandr, apply or.elim pandqorpandr, --left assume pandq, apply and.intro _ _, apply and.elim_left pandq, apply or.intro_left _ _, apply and.elim_right pandq, --right assume pandr, apply and.intro _ _, apply and.elim_left pandr, apply or.intro_right _ _, apply and.elim_right pandr, end /- Suppose we have propositions P Q and R. We want to prove (P ∧ Q) ∨ (P ∧ R) from P ∧ (Q ∨ R) and vice versa. Then we assume we have a proof of P ∧ (Q ∨ R). Using the and elimination rule, we can break this down into two separate proofs, one of P, and one of Q ∨ R. We apply the or elimination rule to Q ∨ R, aand assume a proof of Q. Then we apply the and introduction rule to the proofs of P and Q, and apply the left or introduction rule to this. Then we assume a proof of R from the or elimination rule of Q ∨ R, and then apply the and introduction rule to the proofs of P and Q. Then we apply the right or introduction rule to this, and we have proved it forwards. To prove it backwards, we assume we have a proof of (P ∧ Q) ∨ (P ∧ R). We apply the or elimination rule to this proof, and get proofs of (P ∧ Q) and (P ∧ R). Using the proof of (P ∧ Q), we apply the left and elimination rule, to get a proof of P. Then we apply the right and elimination rule to (P ∧ Q) to get a proof of Q. Then we apply the left or introduction rule to to the proof of Q, and the and introduction rule to this, and the proof of P to prove P ∧ ( Q ∨ R). We have to prove P ∧ ( Q ∨ R) from P ∧ R now. We apply the left and elim rule, achieving a proof of P. The right and elim rule yields a proof of R. We apply the right or intro rule to the proof of R to prove Q ∨ R, and then apply the and intro rule to P and this proof to prove P ∧ ( Q ∨ R). Then we apply the if and only if intro rule to the forwards and backwards proofs. -/ example : ∀ (P Q R : Prop), P ∨ (Q ∧ R) ↔ (P ∨ Q) ∧ (P ∨ R) := begin assume P Q R, apply iff.intro _ _, --forwards assume porqandr, apply or.elim porqandr, assume p, apply and.intro _ _, apply or.intro_left _ _, apply p, apply or.intro_left, apply p, assume qandr, apply and.intro _ _, apply or.intro_right _ _, apply and.elim_left qandr, apply or.intro_right _ _, apply and.elim_right qandr, --backwards assume porqandporr, apply and.elim porqandporr, assume porq, assume porr, apply or.elim porq, assume p, apply or.intro_left _ _, apply p, assume q, apply or.elim porr, assume p, apply or.intro_left _ _, apply p, assume r, apply or.intro_right _ _, apply and.intro q r, end /- Suppose we have propositions P and Q and R. We want to prove (P ∨ Q) ∧ (P ∨ R) from P ∨ (Q ∧ R), and vice versa. We assume a proof of P ∨ (Q ∧ R). We apply the or elim rule, and assume a proof of P and a proof of (Q ∧ R) from this. We apply the left or introduction rule to the proof of P, to get a proof of (P ∨ Q). We apply the left or intro rule to the proof of P again to get a proof of (P ∨ R), and then apply the and introduction rule to these two proofs.Then, we use the proof of ( Q ∧ R) to to get a proof of Q and a proof of R, using the left and elim rule, and the right and elim rule respectively. We use the right or introduction rule on each of these proofs to get a proof of (P ∨ Q), and a proof of (P ∨ R), and then apply the and intro rule to these proofs. This concludes the forwards proof. To prove it backwards we assume a proof of (P ∨ Q) ∧ (P ∨ R) , apply the and elim rule to get proofs of (P ∨ Q) and of (P ∨ R) respectively. We apply the or elim rule to (P ∨ Q) to get a proof of P and a proof of Q. We apply the left or introduction to the proof of P to prove P ∨ (Q ∧ R). We apply the or elim rule to the proof of (P ∨ R), to get proofs of P and R. We apply the left or intro rule to the proof of P to prove P ∨ (Q ∧ R). Then we apply the and intro rule to the proofs of Q and R, and apply the right or intro rule to this. This completes the backwards proof, and then we apply the if and only if intro rule to these proofs. -/ example : ∀ (P Q : Prop), P ∧ (P ∨ Q) ↔ P := begin assume P Q, apply iff.intro _ _, --forwards assume pandporq, apply and.elim_left pandporq, --backwards assume p, apply and.intro _ _, apply p, apply or.intro_left _ _, apply p, end /- Suppose we have propositions P and Q. We want to prove P from P ∧ (P ∨ Q) and vice versa. We assume a proof of P ∧ (P ∨ Q), then apply the left and elim rule to this proof to geta proof of P. This completes the forwards proof. To prove it backwards we assume a proof of P, apply the left or introduction rule to this proof to prove P ∨ Q, and then apply the and intro rule to the proof of P and this proof to prove P ∧ (P ∨ Q). Then apply the if and only if intro rule to these proofs. -/ example : ∀ (P Q : Prop), P ∨ (P ∧ Q) ↔ P := begin assume P Q, apply iff.intro _ _, --forwards assume porpandq, apply or.elim porpandq, assume p, apply p, assume pandq, apply and.elim_left pandq, --backwards assume p, apply or.intro_left _ _, apply p, end /-Suppose we have propositions P and Q. We want to prove P ∨ (P ∧ Q) implies P and vice versa. We assume P ∨ (P ∧ Q), then apply or elimination to this to get a proof of P, and a proof of (P ∧ Q). We apply the proof of P to prove P, then apply the left and elim rule to (P ∧ Q) to prove P from both sides of the or. To prove this backwards, we assume a proof of P, then apply the left or intro rule, which proves P ∨ (P ∧ Q). Then we apply the if and only if intro rule to these proofs. -/ example : ∀ (P : Prop), P ∨ true ↔ true := begin assume P, apply iff.intro _ _, --forwards assume portrue, apply or.elim portrue, assume p, exact true.intro, assume t, apply t, --backwards assume t, apply or.intro_right _ _, apply t, end /- Suppose P is a propositon, and we want to prove P ∨ true implies true, and vice versa. We asume a proof of P ∨ true, apply or.elim to this proof, and get proofs of P and true respectively. We exact the true introduction rule on P, which proves true, and then apply the true proof, so true is proved by both sides of the or. To prove it backwards, we assume a proof of true, apply the right or intro rule to this proof, and we have then proved true implies P ∨ true. Then we apply the if and only if intro rule to these two proofs. -/ example : ∀ (P : Prop), P ∨ false ↔ P := begin assume P, apply iff.intro _ _, --forwards assume porfalse, apply or.elim porfalse, assume p, apply p, assume f, cases f, --backwards assume p, apply or.intro_left _ _, apply p, end /- Suppose we have a propositon P , and want to prove P ∨ false implies P, and vice versa. We assume a proof of P ∨ false, and apply the or elim rule to this proof to get a proof of P and a proof of false. We apply P, and then do case analysis on the false proof to prove P from a case of false. To prove it backwards, we assume a proof of P, and apply it using the left or introduction rule to prove P ∨ false. Then we apply the if and only if introduction rule to these two proofs. -/ example : ∀ (P : Prop), P ∧ true ↔ P := begin assume P, apply iff.intro _ _, --forwards assume pandtrue, apply and.elim_left pandtrue, --backwards, assume p, apply and.intro _ _, apply p, exact true.intro, end /- Suppose we have a proposition P, for which we are trying to prove P ∧ true implies P, and vice versa. First, we assume a proof of P ∧ true, and then apply the left and elim rule to this proof to prove P. To prove this backwards, we assume a proof of P, then apply the and intro rule to the proof of p and the applied true intro ruel, proving P ∧ true. Then we apply the if and only if intro rule to these two proofs. -/ example : ∀ (P : Prop), P ∧ false ↔ false := begin assume P, apply iff.intro _ _, --forwards assume pandfalse, apply and.elim_right pandfalse, --backwards assume f, apply and.intro _ _, cases f, apply f, end /- Suppose we have aproposition P, for which we are trying to prove P ∧ false implies false, and vice versa. We assume a proof of P ∧ false, and apply the right and elim rule to this proof to prove false. To prove this backwards, we assume a proof of false, then do case analysis on this proof to get a proof of P. We then apply this proof and the proof of false to the and introduction rule to prove P ∧ false. Then we apply the if and only if intro rule to these two proofs. -/
86761945b5c161f408b3b366a158f2cec0979a2e
b147e1312077cdcfea8e6756207b3fa538982e12
/order/bounded_lattice.lean
fe1974a3bf33277d2c14893f9ed1552c16f8848f
[ "Apache-2.0" ]
permissive
SzJS/mathlib
07836ee708ca27cd18347e1e11ce7dd5afb3e926
23a5591fca0d43ee5d49d89f6f0ee07a24a6ca29
refs/heads/master
1,584,980,332,064
1,532,063,841,000
1,532,063,841,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
19,643
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 Defines bounded lattice type class hierarchy. Includes the Prop and fun instances. -/ import order.lattice data.option set_option old_structure_cmd true universes u v variable {α : Type u} namespace lattice /-- Typeclass for the `⊤` (`\top`) notation -/ class has_top (α : Type u) := (top : α) /-- Typeclass for the `⊥` (`\bot`) notation -/ class has_bot (α : Type u) := (bot : α) notation `⊤` := has_top.top _ notation `⊥` := has_bot.bot _ /-- An `order_top` is a partial order with a maximal element. (We could state this on preorders, but then it wouldn't be unique so distinguishing one would seem odd.) -/ class order_top (α : Type u) extends has_top α, partial_order α := (le_top : ∀ a : α, a ≤ ⊤) section order_top variables [order_top α] {a : α} @[simp] theorem le_top : a ≤ ⊤ := order_top.le_top a theorem top_unique (h : ⊤ ≤ a) : a = ⊤ := le_antisymm le_top h -- TODO: delete in favor of the next? theorem eq_top_iff : a = ⊤ ↔ ⊤ ≤ a := ⟨assume eq, eq.symm ▸ le_refl ⊤, top_unique⟩ @[simp] theorem top_le_iff : ⊤ ≤ a ↔ a = ⊤ := ⟨top_unique, λ h, h.symm ▸ le_refl ⊤⟩ @[simp] theorem not_top_lt : ¬ ⊤ < a := assume h, lt_irrefl a (lt_of_le_of_lt le_top h) end order_top theorem order_top.ext_top {α} {A B : order_top α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : (by haveI := A; exact ⊤ : α) = ⊤ := top_unique $ by rw ← H; apply le_top theorem order_top.ext {α} {A B : order_top α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := begin haveI this := partial_order.ext H, have tt := order_top.ext_top H, cases A; cases B; injection this; congr' end /-- An `order_bot` is a partial order with a minimal element. (We could state this on preorders, but then it wouldn't be unique so distinguishing one would seem odd.) -/ class order_bot (α : Type u) extends has_bot α, partial_order α := (bot_le : ∀ a : α, ⊥ ≤ a) section order_bot variables [order_bot α] {a : α} @[simp] theorem bot_le : ⊥ ≤ a := order_bot.bot_le a theorem bot_unique (h : a ≤ ⊥) : a = ⊥ := le_antisymm h bot_le -- TODO: delete? theorem eq_bot_iff : a = ⊥ ↔ a ≤ ⊥ := ⟨assume eq, eq.symm ▸ le_refl ⊥, bot_unique⟩ @[simp] theorem le_bot_iff : a ≤ ⊥ ↔ a = ⊥ := ⟨bot_unique, assume h, h.symm ▸ le_refl ⊥⟩ @[simp] theorem not_lt_bot : ¬ a < ⊥ := assume h, lt_irrefl a (lt_of_lt_of_le h bot_le) theorem neq_bot_of_le_neq_bot {a b : α} (hb : b ≠ ⊥) (hab : b ≤ a) : a ≠ ⊥ := assume ha, hb $ bot_unique $ ha ▸ hab end order_bot theorem order_bot.ext_bot {α} {A B : order_bot α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : (by haveI := A; exact ⊥ : α) = ⊥ := bot_unique $ by rw ← H; apply bot_le theorem order_bot.ext {α} {A B : order_bot α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := begin haveI this := partial_order.ext H, have tt := order_bot.ext_bot H, cases A; cases B; injection this; congr' end /-- A `semilattice_sup_top` is a semilattice with top and join. -/ class semilattice_sup_top (α : Type u) extends order_top α, semilattice_sup α section semilattice_sup_top variables [semilattice_sup_top α] {a : α} @[simp] theorem top_sup_eq : ⊤ ⊔ a = ⊤ := sup_of_le_left le_top @[simp] theorem sup_top_eq : a ⊔ ⊤ = ⊤ := sup_of_le_right le_top end semilattice_sup_top /-- A `semilattice_sup_bot` is a semilattice with bottom and join. -/ class semilattice_sup_bot (α : Type u) extends order_bot α, semilattice_sup α section semilattice_sup_bot variables [semilattice_sup_bot α] {a b : α} @[simp] theorem bot_sup_eq : ⊥ ⊔ a = a := sup_of_le_right bot_le @[simp] theorem sup_bot_eq : a ⊔ ⊥ = a := sup_of_le_left bot_le @[simp] theorem sup_eq_bot_iff : a ⊔ b = ⊥ ↔ (a = ⊥ ∧ b = ⊥) := by rw [eq_bot_iff, sup_le_iff]; simp end semilattice_sup_bot instance nat.semilattice_sup_bot : semilattice_sup_bot ℕ := { bot := 0, bot_le := nat.zero_le, .. nat.distrib_lattice } /-- A `semilattice_inf_top` is a semilattice with top and meet. -/ class semilattice_inf_top (α : Type u) extends order_top α, semilattice_inf α section semilattice_inf_top variables [semilattice_inf_top α] {a b : α} @[simp] theorem top_inf_eq : ⊤ ⊓ a = a := inf_of_le_right le_top @[simp] theorem inf_top_eq : a ⊓ ⊤ = a := inf_of_le_left le_top @[simp] theorem inf_eq_top_iff : a ⊓ b = ⊤ ↔ (a = ⊤ ∧ b = ⊤) := by rw [eq_top_iff, le_inf_iff]; simp end semilattice_inf_top /-- A `semilattice_inf_bot` is a semilattice with bottom and meet. -/ class semilattice_inf_bot (α : Type u) extends order_bot α, semilattice_inf α section semilattice_inf_bot variables [semilattice_inf_bot α] {a : α} @[simp] theorem bot_inf_eq : ⊥ ⊓ a = ⊥ := inf_of_le_left bot_le @[simp] theorem inf_bot_eq : a ⊓ ⊥ = ⊥ := inf_of_le_right bot_le end semilattice_inf_bot /- Bounded lattices -/ /-- A bounded lattice is a lattice with a top and bottom element, denoted `⊤` and `⊥` respectively. This allows for the interpretation of all finite suprema and infima, taking `inf ∅ = ⊤` and `sup ∅ = ⊥`. -/ class bounded_lattice (α : Type u) extends lattice α, order_top α, order_bot α instance semilattice_inf_top_of_bounded_lattice (α : Type u) [bl : bounded_lattice α] : semilattice_inf_top α := { le_top := assume x, @le_top α _ x, ..bl } instance semilattice_inf_bot_of_bounded_lattice (α : Type u) [bl : bounded_lattice α] : semilattice_inf_bot α := { bot_le := assume x, @bot_le α _ x, ..bl } instance semilattice_sup_top_of_bounded_lattice (α : Type u) [bl : bounded_lattice α] : semilattice_sup_top α := { le_top := assume x, @le_top α _ x, ..bl } instance semilattice_sup_bot_of_bounded_lattice (α : Type u) [bl : bounded_lattice α] : semilattice_sup_bot α := { bot_le := assume x, @bot_le α _ x, ..bl } theorem bounded_lattice.ext {α} {A B : bounded_lattice α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := begin haveI H1 : @bounded_lattice.to_lattice α A = @bounded_lattice.to_lattice α B := lattice.ext H, haveI H2 := order_bot.ext H, haveI H3 : @bounded_lattice.to_order_top α A = @bounded_lattice.to_order_top α B := order_top.ext H, have tt := order_bot.ext_bot H, cases A; cases B; injection H1; injection H2; injection H3; congr' end /-- A bounded distributive lattice is exactly what it sounds like. -/ class bounded_distrib_lattice α extends distrib_lattice α, bounded_lattice α lemma inf_eq_bot_iff_le_compl {α : Type u} [bounded_distrib_lattice α] {a b c : α} (h₁ : b ⊔ c = ⊤) (h₂ : b ⊓ c = ⊥) : a ⊓ b = ⊥ ↔ a ≤ c := ⟨assume : a ⊓ b = ⊥, calc a ≤ a ⊓ (b ⊔ c) : by simp [h₁] ... = (a ⊓ b) ⊔ (a ⊓ c) : by simp [inf_sup_left] ... ≤ c : by simp [this, inf_le_right], assume : a ≤ c, bot_unique $ calc a ⊓ b ≤ b ⊓ c : by rw [inf_comm]; exact inf_le_inf (le_refl _) this ... = ⊥ : h₂⟩ /- Prop instance -/ instance bounded_lattice_Prop : bounded_lattice Prop := { lattice.bounded_lattice . le := λa b, a → b, le_refl := assume _, id, le_trans := assume a b c f g, g ∘ f, le_antisymm := assume a b Hab Hba, propext ⟨Hab, Hba⟩, sup := or, le_sup_left := @or.inl, le_sup_right := @or.inr, sup_le := assume a b c, or.rec, inf := and, inf_le_left := @and.left, inf_le_right := @and.right, le_inf := assume a b c Hab Hac Ha, and.intro (Hab Ha) (Hac Ha), top := true, le_top := assume a Ha, true.intro, bot := false, bot_le := @false.elim } section logic variable [preorder α] theorem monotone_and {p q : α → Prop} (m_p : monotone p) (m_q : monotone q) : monotone (λx, p x ∧ q x) := assume a b h, and.imp (m_p h) (m_q h) -- Note: by finish [monotone] doesn't work theorem monotone_or {p q : α → Prop} (m_p : monotone p) (m_q : monotone q) : monotone (λx, p x ∨ q x) := assume a b h, or.imp (m_p h) (m_q h) end logic /- Function lattices -/ /- TODO: * build up the lattice hierarchy for `fun`-functor piecewise. semilattic_*, bounded_lattice, lattice ... * can this be generalized to the dependent function space? -/ instance bounded_lattice_fun {α : Type u} {β : Type v} [bounded_lattice β] : bounded_lattice (α → β) := { sup := λf g a, f a ⊔ g a, le_sup_left := assume f g a, le_sup_left, le_sup_right := assume f g a, le_sup_right, sup_le := assume f g h Hfg Hfh a, sup_le (Hfg a) (Hfh a), inf := λf g a, f a ⊓ g a, inf_le_left := assume f g a, inf_le_left, inf_le_right := assume f g a, inf_le_right, le_inf := assume f g h Hfg Hfh a, le_inf (Hfg a) (Hfh a), top := λa, ⊤, le_top := assume f a, le_top, bot := λa, ⊥, bot_le := assume f a, bot_le, ..partial_order_fun } end lattice def with_bot (α : Type*) := option α namespace with_bot open lattice instance : has_coe_t α (with_bot α) := ⟨some⟩ instance partial_order [partial_order α] : partial_order (with_bot α) := { le := λ o₁ o₂ : option α, ∀ a ∈ o₁, ∃ b ∈ o₂, a ≤ b, le_refl := λ o a ha, ⟨a, ha, le_refl _⟩, le_trans := λ o₁ o₂ o₃ h₁ h₂ a ha, let ⟨b, hb, ab⟩ := h₁ a ha, ⟨c, hc, bc⟩ := h₂ b hb in ⟨c, hc, le_trans ab bc⟩, le_antisymm := λ o₁ o₂ h₁ h₂, begin cases o₁ with a, { cases o₂ with b, {refl}, rcases h₂ b rfl with ⟨_, ⟨⟩, _⟩ }, { rcases h₁ a rfl with ⟨b, ⟨⟩, h₁'⟩, rcases h₂ b rfl with ⟨_, ⟨⟩, h₂'⟩, rw le_antisymm h₁' h₂' } end } instance order_bot [partial_order α] : order_bot (with_bot α) := { bot := none, bot_le := λ a a' h, option.no_confusion h, ..with_bot.partial_order } @[simp] theorem coe_le_coe [partial_order α] {a b : α} : (a : with_bot α) ≤ b ↔ a ≤ b := ⟨λ h, by rcases h a rfl with ⟨_, ⟨⟩, h⟩; exact h, λ h a' e, option.some_inj.1 e ▸ ⟨b, rfl, h⟩⟩ @[simp] theorem some_le_some [partial_order α] {a b : α} : @has_le.le (with_bot α) _ (some a) (some b) ↔ a ≤ b := coe_le_coe theorem coe_le [partial_order α] {a b : α} : ∀ {o : option α}, b ∈ o → ((a : with_bot α) ≤ o ↔ a ≤ b) | _ rfl := coe_le_coe @[simp] theorem some_lt_some [partial_order α] {a b : α} : @has_lt.lt (with_bot α) _ (some a) (some b) ↔ a < b := (and_congr some_le_some (not_congr some_le_some)) .trans lt_iff_le_not_le.symm instance linear_order [linear_order α] : linear_order (with_bot α) := { le_total := λ o₁ o₂, begin cases o₁ with a, {exact or.inl bot_le}, cases o₂ with b, {exact or.inr bot_le}, simp [le_total] end, ..with_bot.partial_order } instance decidable_linear_order [decidable_linear_order α] : decidable_linear_order (with_bot α) := { decidable_le := λ a b, begin cases a with a, { exact is_true bot_le }, cases b with b, { exact is_false (mt (le_antisymm bot_le) (by simp)) }, { exact decidable_of_iff _ some_le_some } end, ..with_bot.linear_order } instance semilattice_sup [semilattice_sup α] : semilattice_sup_bot (with_bot α) := { sup := option.lift_or_get (⊔), le_sup_left := λ o₁ o₂ a ha, by cases ha; cases o₂; simp [option.lift_or_get], le_sup_right := λ o₁ o₂ a ha, by cases ha; cases o₁; simp [option.lift_or_get], sup_le := λ o₁ o₂ o₃ h₁ h₂ a ha, begin cases o₁ with b; cases o₂ with c; cases ha, { exact h₂ a rfl }, { exact h₁ a rfl }, { rcases h₁ b rfl with ⟨d, ⟨⟩, h₁'⟩, simp at h₂, exact ⟨d, rfl, sup_le h₁' h₂⟩ } end, ..with_bot.order_bot } instance semilattice_inf [semilattice_inf α] : semilattice_inf_bot (with_bot α) := { inf := λ o₁ o₂, o₁.bind (λ a, o₂.map (λ b, a ⊓ b)), inf_le_left := λ o₁ o₂ a ha, begin simp at ha, rcases ha with ⟨b, rfl, c, rfl, rfl⟩, exact ⟨_, rfl, inf_le_left⟩ end, inf_le_right := λ o₁ o₂ a ha, begin simp at ha, rcases ha with ⟨b, rfl, c, rfl, rfl⟩, exact ⟨_, rfl, inf_le_right⟩ end, le_inf := λ o₁ o₂ o₃ h₁ h₂ a ha, begin cases ha, rcases h₁ a rfl with ⟨b, ⟨⟩, ab⟩, rcases h₂ a rfl with ⟨c, ⟨⟩, ac⟩, exact ⟨_, rfl, le_inf ab ac⟩ end, ..with_bot.order_bot } instance lattice [lattice α] : lattice (with_bot α) := { ..with_bot.semilattice_sup, ..with_bot.semilattice_inf } theorem lattice_eq_DLO [decidable_linear_order α] : lattice.lattice_of_decidable_linear_order = @with_bot.lattice α _ := lattice.ext $ λ x y, iff.rfl theorem sup_eq_max [decidable_linear_order α] (x y : with_bot α) : x ⊔ y = max x y := by rw [← sup_eq_max, lattice_eq_DLO] theorem inf_eq_min [decidable_linear_order α] (x y : with_bot α) : x ⊓ y = min x y := by rw [← inf_eq_min, lattice_eq_DLO] instance order_top [order_top α] : order_top (with_bot α) := { top := some ⊤, le_top := λ o a ha, by cases ha; exact ⟨_, rfl, le_top⟩, ..with_bot.partial_order } instance bounded_lattice [bounded_lattice α] : bounded_lattice (with_bot α) := { ..with_bot.lattice, ..with_bot.order_top, ..with_bot.order_bot } lemma well_founded_lt [partial_order α] (h : well_founded ((<) : α → α → Prop)) : well_founded ((<) : with_bot α → with_bot α → Prop) := have acc_bot : acc ((<) : with_bot α → with_bot α → Prop) ⊥ := acc.intro _ (λ a ha, (not_le_of_gt ha bot_le).elim), ⟨λ a, option.rec_on a acc_bot (λ a, acc.intro _ (λ b, option.rec_on b (λ _, acc_bot) (λ b, well_founded.induction h b (show ∀ b : α, (∀ c, c < b → (c : with_bot α) < a → acc ((<) : with_bot α → with_bot α → Prop) c) → (b : with_bot α) < a → acc ((<) : with_bot α → with_bot α → Prop) b, from λ b ih hba, acc.intro _ (λ c, option.rec_on c (λ _, acc_bot) (λ c hc, ih _ (some_lt_some.1 hc) (lt_trans hc hba)))))))⟩ end with_bot --TODO(Mario): Construct using order dual on with_bot def with_top (α : Type*) := option α namespace with_top open lattice instance : has_coe_t α (with_top α) := ⟨some⟩ instance partial_order [partial_order α] : partial_order (with_top α) := { le := λ o₁ o₂ : option α, ∀ b ∈ o₂, ∃ a ∈ o₁, a ≤ b, le_refl := λ o a ha, ⟨a, ha, le_refl _⟩, le_trans := λ o₁ o₂ o₃ h₁ h₂ c hc, let ⟨b, hb, bc⟩ := h₂ c hc, ⟨a, ha, ab⟩ := h₁ b hb in ⟨a, ha, le_trans ab bc⟩, le_antisymm := λ o₁ o₂ h₁ h₂, begin cases o₂ with b, { cases o₁ with a, {refl}, rcases h₂ a rfl with ⟨_, ⟨⟩, _⟩ }, { rcases h₁ b rfl with ⟨a, ⟨⟩, h₁'⟩, rcases h₂ a rfl with ⟨_, ⟨⟩, h₂'⟩, rw le_antisymm h₁' h₂' } end } instance order_top [partial_order α] : order_top (with_top α) := { top := none, le_top := λ a a' h, option.no_confusion h, ..with_top.partial_order } @[simp] theorem coe_le_coe [partial_order α] {a b : α} : (a : with_top α) ≤ b ↔ a ≤ b := ⟨λ h, by rcases h b rfl with ⟨_, ⟨⟩, h⟩; exact h, λ h a' e, option.some_inj.1 e ▸ ⟨a, rfl, h⟩⟩ @[simp] theorem some_le_some [partial_order α] {a b : α} : @has_le.le (with_top α) _ (some a) (some b) ↔ a ≤ b := coe_le_coe theorem le_coe [partial_order α] {a b : α} : ∀ {o : option α}, a ∈ o → (@has_le.le (with_top α) _ o b ↔ a ≤ b) | _ rfl := coe_le_coe @[simp] theorem some_lt_some [partial_order α] {a b : α} : @has_lt.lt (with_top α) _ (some a) (some b) ↔ a < b := (and_congr some_le_some (not_congr some_le_some)) .trans lt_iff_le_not_le.symm instance linear_order [linear_order α] : linear_order (with_top α) := { le_total := λ o₁ o₂, begin cases o₁ with a, {exact or.inr le_top}, cases o₂ with b, {exact or.inl le_top}, simp [le_total] end, ..with_top.partial_order } instance decidable_linear_order [decidable_linear_order α] : decidable_linear_order (with_top α) := { decidable_le := λ a b, begin cases b with b, { exact is_true le_top }, cases a with a, { exact is_false (mt (le_antisymm le_top) (by simp)) }, { exact decidable_of_iff _ some_le_some } end, ..with_top.linear_order } instance semilattice_inf [semilattice_inf α] : semilattice_inf_top (with_top α) := { inf := option.lift_or_get (⊓), inf_le_left := λ o₁ o₂ a ha, by cases ha; cases o₂; simp [option.lift_or_get], inf_le_right := λ o₁ o₂ a ha, by cases ha; cases o₁; simp [option.lift_or_get], le_inf := λ o₁ o₂ o₃ h₁ h₂ a ha, begin cases o₂ with b; cases o₃ with c; cases ha, { exact h₂ a rfl }, { exact h₁ a rfl }, { rcases h₁ b rfl with ⟨d, ⟨⟩, h₁'⟩, simp at h₂, exact ⟨d, rfl, le_inf h₁' h₂⟩ } end, ..with_top.order_top } instance semilattice_sup [semilattice_sup α] : semilattice_sup_top (with_top α) := { sup := λ o₁ o₂, o₁.bind (λ a, o₂.map (λ b, a ⊔ b)), le_sup_left := λ o₁ o₂ a ha, begin simp at ha, rcases ha with ⟨b, rfl, c, rfl, rfl⟩, exact ⟨_, rfl, le_sup_left⟩ end, le_sup_right := λ o₁ o₂ a ha, begin simp at ha, rcases ha with ⟨b, rfl, c, rfl, rfl⟩, exact ⟨_, rfl, le_sup_right⟩ end, sup_le := λ o₁ o₂ o₃ h₁ h₂ a ha, begin cases ha, rcases h₁ a rfl with ⟨b, ⟨⟩, ab⟩, rcases h₂ a rfl with ⟨c, ⟨⟩, ac⟩, exact ⟨_, rfl, sup_le ab ac⟩ end, ..with_top.order_top } instance lattice [lattice α] : lattice (with_top α) := { ..with_top.semilattice_sup, ..with_top.semilattice_inf } theorem lattice_eq_DLO [decidable_linear_order α] : lattice.lattice_of_decidable_linear_order = @with_top.lattice α _ := lattice.ext $ λ x y, iff.rfl theorem sup_eq_max [decidable_linear_order α] (x y : with_top α) : x ⊔ y = max x y := by rw [← sup_eq_max, lattice_eq_DLO] theorem inf_eq_min [decidable_linear_order α] (x y : with_top α) : x ⊓ y = min x y := by rw [← inf_eq_min, lattice_eq_DLO] instance order_bot [order_bot α] : order_bot (with_top α) := { bot := some ⊥, bot_le := λ o a ha, by cases ha; exact ⟨_, rfl, bot_le⟩, ..with_top.partial_order } instance bounded_lattice [bounded_lattice α] : bounded_lattice (with_top α) := { ..with_top.lattice, ..with_top.order_top, ..with_top.order_bot } lemma well_founded_lt {α : Type*} [partial_order α] (h : well_founded ((<) : α → α → Prop)) : well_founded ((<) : with_top α → with_top α → Prop) := have acc_some : ∀ a : α, acc ((<) : with_top α → with_top α → Prop) (some a) := λ a, acc.intro _ (well_founded.induction h a (show ∀ b, (∀ c, c < b → ∀ d : with_top α, d < some c → acc (<) d) → ∀ y : with_top α, y < some b → acc (<) y, from λ b ih c, option.rec_on c (λ hc, (not_lt_of_ge lattice.le_top hc).elim) (λ c hc, acc.intro _ (ih _ (some_lt_some.1 hc))))), ⟨λ a, option.rec_on a (acc.intro _ (λ y, option.rec_on y (λ h, (lt_irrefl _ h).elim) (λ _ _, acc_some _))) acc_some⟩ end with_top
5d1993fd233abd24300741289c80a27baf091aa8
bb31430994044506fa42fd667e2d556327e18dfe
/src/data/int/cast/lemmas.lean
75356b0146c7e3c897c3c9635f514b971702aef1
[ "Apache-2.0" ]
permissive
sgouezel/mathlib
0cb4e5335a2ba189fa7af96d83a377f83270e503
00638177efd1b2534fc5269363ebf42a7871df9a
refs/heads/master
1,674,527,483,042
1,673,665,568,000
1,673,665,568,000
119,598,202
0
0
null
1,517,348,647,000
1,517,348,646,000
null
UTF-8
Lean
false
false
11,501
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.int.order.basic import data.nat.cast.basic /-! # Cast of integers (additional theorems) > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file proves additional properties about the *canonical* homomorphism from the integers into an additive group with a one (`int.cast`), particularly results involving algebraic homomorphisms or the order structure on `ℤ` which were not available in the import dependencies of `data.int.cast.basic`. ## Main declarations * `cast_add_hom`: `cast` bundled as an `add_monoid_hom`. * `cast_ring_hom`: `cast` bundled as a `ring_hom`. -/ open nat variables {F ι α β : Type*} namespace int /-- Coercion `ℕ → ℤ` as a `ring_hom`. -/ def of_nat_hom : ℕ →+* ℤ := ⟨coe, rfl, int.of_nat_mul, rfl, int.of_nat_add⟩ @[simp] theorem coe_nat_pos {n : ℕ} : (0 : ℤ) < n ↔ 0 < n := nat.cast_pos lemma coe_nat_succ_pos (n : ℕ) : 0 < (n.succ : ℤ) := int.coe_nat_pos.2 (succ_pos n) lemma to_nat_lt {a : ℤ} {b : ℕ} (hb : b ≠ 0) : a.to_nat < b ↔ a < b := by { rw [←to_nat_lt_to_nat, to_nat_coe_nat], exact coe_nat_pos.2 hb.bot_lt } lemma nat_mod_lt {a : ℤ} {b : ℕ} (hb : b ≠ 0) : a.nat_mod b < b := (to_nat_lt hb).2 $ mod_lt_of_pos _ $ coe_nat_pos.2 hb.bot_lt section cast @[simp, norm_cast] theorem cast_mul [non_assoc_ring α] : ∀ m n, ((m * n : ℤ) : α) = m * n := λ m, int.induction_on' m 0 (by simp) (λ k _ ih n, by simp [add_mul, ih]) (λ k _ ih n, by simp [sub_mul, ih]) @[simp, norm_cast] theorem cast_ite [add_group_with_one α] (P : Prop) [decidable P] (m n : ℤ) : ((ite P m n : ℤ) : α) = ite P m n := apply_ite _ _ _ _ /-- `coe : ℤ → α` as an `add_monoid_hom`. -/ def cast_add_hom (α : Type*) [add_group_with_one α] : ℤ →+ α := ⟨coe, cast_zero, cast_add⟩ @[simp] lemma coe_cast_add_hom [add_group_with_one α] : ⇑(cast_add_hom α) = coe := rfl /-- `coe : ℤ → α` as a `ring_hom`. -/ def cast_ring_hom (α : Type*) [non_assoc_ring α] : ℤ →+* α := ⟨coe, cast_one, cast_mul, cast_zero, cast_add⟩ @[simp] lemma coe_cast_ring_hom [non_assoc_ring α] : ⇑(cast_ring_hom α) = coe := rfl lemma cast_commute [non_assoc_ring α] : ∀ (m : ℤ) (x : α), commute ↑m x | (n : ℕ) x := by simpa using n.cast_commute x | -[1+ n] x := by simpa only [cast_neg_succ_of_nat, commute.neg_left_iff, commute.neg_right_iff] using (n + 1).cast_commute (-x) lemma cast_comm [non_assoc_ring α] (m : ℤ) (x : α) : (m : α) * x = x * m := (cast_commute m x).eq lemma commute_cast [non_assoc_ring α] (x : α) (m : ℤ) : commute x m := (m.cast_commute x).symm theorem cast_mono [ordered_ring α] : monotone (coe : ℤ → α) := begin intros m n h, rw ← sub_nonneg at h, lift n - m to ℕ using h with k, rw [← sub_nonneg, ← cast_sub, ← h_1, cast_coe_nat], exact k.cast_nonneg end @[simp] theorem cast_nonneg [ordered_ring α] [nontrivial α] : ∀ {n : ℤ}, (0 : α) ≤ n ↔ 0 ≤ n | (n : ℕ) := by simp | -[1+ n] := have -(n:α) < 1, from lt_of_le_of_lt (by simp) zero_lt_one, by simpa [(neg_succ_lt_zero n).not_le, ← sub_eq_add_neg, le_neg] using this.not_le @[simp, norm_cast] theorem cast_le [ordered_ring α] [nontrivial α] {m n : ℤ} : (m : α) ≤ n ↔ m ≤ n := by rw [← sub_nonneg, ← cast_sub, cast_nonneg, sub_nonneg] theorem cast_strict_mono [ordered_ring α] [nontrivial α] : strict_mono (coe : ℤ → α) := strict_mono_of_le_iff_le $ λ m n, cast_le.symm @[simp, norm_cast] theorem cast_lt [ordered_ring α] [nontrivial α] {m n : ℤ} : (m : α) < n ↔ m < n := cast_strict_mono.lt_iff_lt @[simp] theorem cast_nonpos [ordered_ring α] [nontrivial α] {n : ℤ} : (n : α) ≤ 0 ↔ n ≤ 0 := by rw [← cast_zero, cast_le] @[simp] theorem cast_pos [ordered_ring α] [nontrivial α] {n : ℤ} : (0 : α) < n ↔ 0 < n := by rw [← cast_zero, cast_lt] @[simp] theorem cast_lt_zero [ordered_ring α] [nontrivial α] {n : ℤ} : (n : α) < 0 ↔ n < 0 := by rw [← cast_zero, cast_lt] section linear_ordered_ring variables [linear_ordered_ring α] {a b : ℤ} (n : ℤ) @[simp, norm_cast] theorem cast_min : (↑(min a b) : α) = min a b := monotone.map_min cast_mono @[simp, norm_cast] theorem cast_max : (↑(max a b) : α) = max a b := monotone.map_max cast_mono @[simp, norm_cast] theorem cast_abs : ((|a| : ℤ) : α) = |a| := by simp [abs_eq_max_neg] lemma cast_one_le_of_pos (h : 0 < a) : (1 : α) ≤ a := by exact_mod_cast int.add_one_le_of_lt h lemma cast_le_neg_one_of_neg (h : a < 0) : (a : α) ≤ -1 := begin rw [← int.cast_one, ← int.cast_neg, cast_le], exact int.le_sub_one_of_lt h, end variables (α) {n} lemma cast_le_neg_one_or_one_le_cast_of_ne_zero (hn : n ≠ 0) : (n : α) ≤ -1 ∨ 1 ≤ (n : α) := hn.lt_or_lt.imp cast_le_neg_one_of_neg cast_one_le_of_pos variables {α} (n) lemma nneg_mul_add_sq_of_abs_le_one {x : α} (hx : |x| ≤ 1) : (0 : α) ≤ n * x + n * n := begin have hnx : 0 < n → 0 ≤ x + n := λ hn, by { convert add_le_add (neg_le_of_abs_le hx) (cast_one_le_of_pos hn), rw add_left_neg, }, have hnx' : n < 0 → x + n ≤ 0 := λ hn, by { convert add_le_add (le_of_abs_le hx) (cast_le_neg_one_of_neg hn), rw add_right_neg, }, rw [← mul_add, mul_nonneg_iff], rcases lt_trichotomy n 0 with h | rfl | h, { exact or.inr ⟨by exact_mod_cast h.le, hnx' h⟩, }, { simp [le_total 0 x], }, { exact or.inl ⟨by exact_mod_cast h.le, hnx h⟩, }, end lemma cast_nat_abs : (n.nat_abs : α) = |n| := begin cases n, { simp, }, { simp only [int.nat_abs, int.cast_neg_succ_of_nat, abs_neg, ← nat.cast_succ, nat.abs_cast], }, end end linear_ordered_ring lemma coe_int_dvd [comm_ring α] (m n : ℤ) (h : m ∣ n) : (m : α) ∣ (n : α) := ring_hom.map_dvd (int.cast_ring_hom α) h end cast end int open int namespace add_monoid_hom variables {A : Type*} /-- Two additive monoid homomorphisms `f`, `g` from `ℤ` to an additive monoid are equal if `f 1 = g 1`. -/ @[ext] theorem ext_int [add_monoid A] {f g : ℤ →+ A} (h1 : f 1 = g 1) : f = g := have f.comp (int.of_nat_hom : ℕ →+ ℤ) = g.comp (int.of_nat_hom : ℕ →+ ℤ) := ext_nat' _ _ h1, have ∀ n : ℕ, f n = g n := ext_iff.1 this, ext $ λ n, int.cases_on n this $ λ n, eq_on_neg _ _ (this $ n + 1) variables [add_group_with_one A] theorem eq_int_cast_hom (f : ℤ →+ A) (h1 : f 1 = 1) : f = int.cast_add_hom A := ext_int $ by simp [h1] end add_monoid_hom lemma eq_int_cast' [add_group_with_one α] [add_monoid_hom_class F ℤ α] (f : F) (h₁ : f 1 = 1) : ∀ n : ℤ, f n = n := add_monoid_hom.ext_iff.1 $ (f : ℤ →+ α).eq_int_cast_hom h₁ @[simp] lemma int.cast_add_hom_int : int.cast_add_hom ℤ = add_monoid_hom.id ℤ := ((add_monoid_hom.id ℤ).eq_int_cast_hom rfl).symm namespace monoid_hom variables {M : Type*} [monoid M] open multiplicative @[ext] theorem ext_mint {f g : multiplicative ℤ →* M} (h1 : f (of_add 1) = g (of_add 1)) : f = g := monoid_hom.ext $ add_monoid_hom.ext_iff.mp $ @add_monoid_hom.ext_int _ _ f.to_additive g.to_additive h1 /-- If two `monoid_hom`s agree on `-1` and the naturals then they are equal. -/ @[ext] theorem ext_int {f g : ℤ →* M} (h_neg_one : f (-1) = g (-1)) (h_nat : f.comp int.of_nat_hom.to_monoid_hom = g.comp int.of_nat_hom.to_monoid_hom) : f = g := begin ext (x | x), { exact (monoid_hom.congr_fun h_nat x : _), }, { rw [int.neg_succ_of_nat_eq, ← neg_one_mul, f.map_mul, g.map_mul], congr' 1, exact_mod_cast (monoid_hom.congr_fun h_nat (x + 1) : _), } end end monoid_hom namespace monoid_with_zero_hom variables {M : Type*} [monoid_with_zero M] /-- If two `monoid_with_zero_hom`s agree on `-1` and the naturals then they are equal. -/ @[ext] lemma ext_int {f g : ℤ →*₀ M} (h_neg_one : f (-1) = g (-1)) (h_nat : f.comp int.of_nat_hom.to_monoid_with_zero_hom = g.comp int.of_nat_hom.to_monoid_with_zero_hom) : f = g := to_monoid_hom_injective $ monoid_hom.ext_int h_neg_one $ monoid_hom.ext (congr_fun h_nat : _) end monoid_with_zero_hom /-- If two `monoid_with_zero_hom`s agree on `-1` and the _positive_ naturals then they are equal. -/ lemma ext_int' [monoid_with_zero α] [monoid_with_zero_hom_class F ℤ α] {f g : F} (h_neg_one : f (-1) = g (-1)) (h_pos : ∀ n : ℕ, 0 < n → f n = g n) : f = g := fun_like.ext _ _ $ λ n, by { have := fun_like.congr_fun (@monoid_with_zero_hom.ext_int _ _ (f : ℤ →*₀ α) (g : ℤ →*₀ α) h_neg_one $ monoid_with_zero_hom.ext_nat h_pos) n, exact this } section non_assoc_ring variables [non_assoc_ring α] [non_assoc_ring β] @[simp] lemma eq_int_cast [ring_hom_class F ℤ α] (f : F) (n : ℤ) : f n = n := eq_int_cast' f (map_one _) n @[simp] lemma map_int_cast [ring_hom_class F α β] (f : F) (n : ℤ) : f n = n := eq_int_cast ((f : α →+* β).comp (int.cast_ring_hom α)) n namespace ring_hom lemma eq_int_cast' (f : ℤ →+* α) : f = int.cast_ring_hom α := ring_hom.ext $ eq_int_cast f lemma ext_int {R : Type*} [non_assoc_semiring R] (f g : ℤ →+* R) : f = g := coe_add_monoid_hom_injective $ add_monoid_hom.ext_int $ f.map_one.trans g.map_one.symm instance int.subsingleton_ring_hom {R : Type*} [non_assoc_semiring R] : subsingleton (ℤ →+* R) := ⟨ring_hom.ext_int⟩ end ring_hom end non_assoc_ring @[simp, norm_cast] lemma int.cast_id (n : ℤ) : ↑n = n := (eq_int_cast (ring_hom.id ℤ) _).symm @[simp] lemma int.cast_ring_hom_int : int.cast_ring_hom ℤ = ring_hom.id ℤ := (ring_hom.id ℤ).eq_int_cast'.symm namespace pi variables {π : ι → Type*} [Π i, has_int_cast (π i)] instance : has_int_cast (Π i, π i) := by refine_struct { .. }; tactic.pi_instance_derive_field lemma int_apply (n : ℤ) (i : ι) : (n : Π i, π i) i = n := rfl @[simp] lemma coe_int (n : ℤ) : (n : Π i, π i) = λ _, n := rfl end pi lemma sum.elim_int_cast_int_cast {α β γ : Type*} [has_int_cast γ] (n : ℤ) : sum.elim (n : α → γ) (n : β → γ) = n := @sum.elim_lam_const_lam_const α β γ n namespace pi variables {π : ι → Type*} [Π i, add_group_with_one (π i)] instance : add_group_with_one (Π i, π i) := by refine_struct { .. }; tactic.pi_instance_derive_field end pi namespace mul_opposite variables [add_group_with_one α] @[simp, norm_cast] lemma op_int_cast (z : ℤ) : op (z : α) = z := rfl @[simp, norm_cast] lemma unop_int_cast (n : ℤ) : unop (n : αᵐᵒᵖ) = n := rfl end mul_opposite /-! ### Order dual -/ open order_dual instance [h : has_int_cast α] : has_int_cast αᵒᵈ := h instance [h : add_group_with_one α] : add_group_with_one αᵒᵈ := h instance [h : add_comm_group_with_one α] : add_comm_group_with_one αᵒᵈ := h @[simp] lemma to_dual_int_cast [has_int_cast α] (n : ℤ) : to_dual (n : α) = n := rfl @[simp] lemma of_dual_int_cast [has_int_cast α] (n : ℤ) : (of_dual n : α) = n := rfl /-! ### Lexicographic order -/ instance [h : has_int_cast α] : has_int_cast (lex α) := h instance [h : add_group_with_one α] : add_group_with_one (lex α) := h instance [h : add_comm_group_with_one α] : add_comm_group_with_one (lex α) := h @[simp] lemma to_lex_int_cast [has_int_cast α] (n : ℤ) : to_lex (n : α) = n := rfl @[simp] lemma of_lex_int_cast [has_int_cast α] (n : ℤ) : (of_lex n : α) = n := rfl
87c651a1e838f25939411e89eeb99ac14db0eedb
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/ring_theory/ideal/minimal_prime.lean
785a283f8026aa8bdaee2a0d7a97fa1d2305a7e5
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
8,537
lean
/- Copyright (c) 2022 Andrew Yang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Andrew Yang -/ import ring_theory.localization.at_prime import order.minimal /-! # Minimal primes We provide various results concerning the minimal primes above an ideal ## Main results - `ideal.minimal_primes`: `I.minimal_primes` is the set of ideals that are minimal primes over `I`. - `minimal_primes`: `minimal_primes R` is the set of minimal primes of `R`. - `ideal.exists_minimal_primes_le`: Every prime ideal over `I` contains a minimal prime over `I`. - `ideal.radical_minimal_primes`: The minimal primes over `I.radical` are precisely the minimal primes over `I`. - `ideal.Inf_minimal_primes`: The intersection of minimal primes over `I` is `I.radical`. - `ideal.exists_minimal_primes_comap_eq` If `p` is a minimal prime over `f ⁻¹ I`, then it is the preimage of some minimal prime over `I`. - `ideal.minimal_primes_eq_comap`: The minimal primes over `I` are precisely the preimages of minimal primes of `R ⧸ I`. -/ section variables {R S : Type*} [comm_ring R] [comm_ring S] (I J : ideal R) /-- `I.minimal_primes` is the set of ideals that are minimal primes over `I`. -/ def ideal.minimal_primes : set (ideal R) := minimals (≤) { p | p.is_prime ∧ I ≤ p } /-- `minimal_primes R` is the set of minimal primes of `R`. This is defined as `ideal.minimal_primes ⊥`. -/ def minimal_primes (R : Type*) [comm_ring R] : set (ideal R) := ideal.minimal_primes ⊥ variables {I J} lemma ideal.exists_minimal_primes_le [J.is_prime] (e : I ≤ J) : ∃ p ∈ I.minimal_primes, p ≤ J := begin suffices : ∃ m ∈ { p : (ideal R)ᵒᵈ | ideal.is_prime p ∧ I ≤ order_dual.of_dual p }, (order_dual.to_dual J) ≤ m ∧ ∀ z ∈ { p : (ideal R)ᵒᵈ | ideal.is_prime p ∧ I ≤ p }, m ≤ z → z = m, { obtain ⟨p, h₁, h₂, h₃⟩ := this, simp_rw ← @eq_comm _ p at h₃, exact ⟨p, ⟨h₁, λ a b c, (h₃ a b c).le⟩, h₂⟩ }, apply zorn_nonempty_partial_order₀, swap, { refine ⟨show J.is_prime, by apply_instance, e⟩ }, rintros (c : set (ideal R)) hc hc' J' hJ', refine ⟨order_dual.to_dual (Inf c), ⟨ideal.Inf_is_prime_of_is_chain ⟨J', hJ'⟩ hc'.symm (λ x hx, (hc hx).1), _⟩, _⟩, { rw order_dual.of_dual_to_dual, convert le_Inf _, intros x hx, exact (hc hx).2 }, { rintro z hz, rw order_dual.le_to_dual, exact Inf_le hz } end @[simp] lemma ideal.radical_minimal_primes : I.radical.minimal_primes = I.minimal_primes := begin rw [ideal.minimal_primes, ideal.minimal_primes], congr, ext p, exact ⟨λ ⟨a, b⟩, ⟨a, ideal.le_radical.trans b⟩, λ ⟨a, b⟩, ⟨a, a.radical_le_iff.mpr b⟩⟩, end @[simp] lemma ideal.Inf_minimal_primes : Inf I.minimal_primes = I.radical := begin rw I.radical_eq_Inf, apply le_antisymm, { intros x hx, rw ideal.mem_Inf at hx ⊢, rintros J ⟨e, hJ⟩, resetI, obtain ⟨p, hp, hp'⟩ := ideal.exists_minimal_primes_le e, exact hp' (hx hp) }, { apply Inf_le_Inf _, intros I hI, exact hI.1.symm }, end lemma ideal.exists_comap_eq_of_mem_minimal_primes_of_injective {f : R →+* S} (hf : function.injective f) (p ∈ minimal_primes R) : ∃ p' : ideal S, p'.is_prime ∧ p'.comap f = p := begin haveI := H.1.1, haveI : nontrivial (localization (submonoid.map f p.prime_compl)), { refine ⟨⟨1, 0, _⟩⟩, convert (is_localization.map_injective_of_injective p.prime_compl (localization.at_prime p) (localization $ p.prime_compl.map f) hf).ne one_ne_zero, { rw map_one }, { rw map_zero } }, obtain ⟨M, hM⟩ := ideal.exists_maximal (localization (submonoid.map f p.prime_compl)), resetI, refine ⟨M.comap (algebra_map S $ localization (submonoid.map f p.prime_compl)), infer_instance, _⟩, rw [ideal.comap_comap, ← @@is_localization.map_comp _ _ _ _ localization.is_localization _ p.prime_compl.le_comap_map _ localization.is_localization, ← ideal.comap_comap], suffices : _ ≤ p, { exact this.antisymm (H.2 ⟨infer_instance, bot_le⟩ this) }, intros x hx, by_contra h, apply hM.ne_top, apply M.eq_top_of_is_unit_mem hx, apply is_unit.map, apply is_localization.map_units _ (show p.prime_compl, from ⟨x, h⟩), apply_instance end lemma ideal.exists_comap_eq_of_mem_minimal_primes {I : ideal S} (f : R →+* S) (p ∈ (I.comap f).minimal_primes) : ∃ p' : ideal S, p'.is_prime ∧ I ≤ p' ∧ p'.comap f = p := begin haveI := H.1.1, let f' := I^.quotient.mk^.comp f, have e : (I^.quotient.mk^.comp f).ker = I.comap f, { ext1, exact (submodule.quotient.mk_eq_zero _) }, have : (I^.quotient.mk^.comp f).ker^.quotient.mk^.ker ≤ p, { rw [ideal.mk_ker, e], exact H.1.2 }, obtain ⟨p', hp₁, hp₂⟩ := ideal.exists_comap_eq_of_mem_minimal_primes_of_injective (I^.quotient.mk^.comp f).ker_lift_injective (p.map (I^.quotient.mk^.comp f).ker^.quotient.mk) _, { resetI, refine ⟨p'.comap I^.quotient.mk, ideal.is_prime.comap _, _, _⟩, { exact ideal.mk_ker.symm.trans_le (ideal.comap_mono bot_le) }, convert congr_arg (ideal.comap (I^.quotient.mk^.comp f).ker^.quotient.mk) hp₂, rwa [ideal.comap_map_of_surjective (I^.quotient.mk^.comp f).ker^.quotient.mk ideal.quotient.mk_surjective, eq_comm, sup_eq_left] }, refine ⟨⟨_, bot_le⟩, _⟩, { apply ideal.map_is_prime_of_surjective _ this, exact ideal.quotient.mk_surjective }, { rintro q ⟨hq, -⟩ hq', rw ← ideal.map_comap_of_surjective (I^.quotient.mk^.comp f).ker^.quotient.mk ideal.quotient.mk_surjective q, apply ideal.map_mono, resetI, apply H.2, { refine ⟨infer_instance, (ideal.mk_ker.trans e).symm.trans_le (ideal.comap_mono bot_le)⟩ }, { refine (ideal.comap_mono hq').trans _, rw ideal.comap_map_of_surjective, exacts [sup_le rfl.le this, ideal.quotient.mk_surjective] } } end lemma ideal.exists_minimal_primes_comap_eq {I : ideal S} (f : R →+* S) (p ∈ (I.comap f).minimal_primes) : ∃ p' ∈ I.minimal_primes, ideal.comap f p' = p := begin obtain ⟨p', h₁, h₂, h₃⟩ := ideal.exists_comap_eq_of_mem_minimal_primes f p H, resetI, obtain ⟨q, hq, hq'⟩ := ideal.exists_minimal_primes_le h₂, refine ⟨q, hq, eq.symm _⟩, haveI := hq.1.1, have := (ideal.comap_mono hq').trans_eq h₃, exact (H.2 ⟨infer_instance, ideal.comap_mono hq.1.2⟩ this).antisymm this end lemma ideal.mimimal_primes_comap_of_surjective {f : R →+* S} (hf : function.surjective f) {I J : ideal S} (h : J ∈ I.minimal_primes) : J.comap f ∈ (I.comap f).minimal_primes := begin haveI := h.1.1, refine ⟨⟨infer_instance, ideal.comap_mono h.1.2⟩, _⟩, rintros K ⟨hK, e₁⟩ e₂, have : f.ker ≤ K := (ideal.comap_mono bot_le).trans e₁, rw [← sup_eq_left.mpr this, ring_hom.ker_eq_comap_bot, ← ideal.comap_map_of_surjective f hf], apply ideal.comap_mono _, apply h.2 _ _, { exactI ⟨ideal.map_is_prime_of_surjective hf this, ideal.le_map_of_comap_le_of_surjective f hf e₁⟩ }, { exact ideal.map_le_of_le_comap e₂ } end lemma ideal.comap_minimal_primes_eq_of_surjective {f : R →+* S} (hf : function.surjective f) (I : ideal S) : (I.comap f).minimal_primes = ideal.comap f '' I.minimal_primes := begin ext J, split, { intro H, obtain ⟨p, h, rfl⟩ := ideal.exists_minimal_primes_comap_eq f J H, exact ⟨p, h, rfl⟩ }, { rintros ⟨J, hJ, rfl⟩, exact ideal.mimimal_primes_comap_of_surjective hf hJ } end lemma ideal.minimal_primes_eq_comap : I.minimal_primes = ideal.comap I^.quotient.mk '' minimal_primes (R ⧸ I) := begin rw [minimal_primes, ← ideal.comap_minimal_primes_eq_of_surjective ideal.quotient.mk_surjective, ← ring_hom.ker_eq_comap_bot, ideal.mk_ker], end lemma ideal.minimal_primes_eq_subsingleton (hI : I.is_primary) : I.minimal_primes = {I.radical} := begin ext J, split, { exact λ H, let e := H.1.1.radical_le_iff.mpr H.1.2 in (H.2 ⟨ideal.is_prime_radical hI, ideal.le_radical⟩ e).antisymm e }, { rintro (rfl : J = I.radical), exact ⟨⟨ideal.is_prime_radical hI, ideal.le_radical⟩, λ _ H _, H.1.radical_le_iff.mpr H.2⟩ } end lemma ideal.minimal_primes_eq_subsingleton_self [I.is_prime] : I.minimal_primes = {I} := begin ext J, split, { exact λ H, (H.2 ⟨infer_instance, rfl.le⟩ H.1.2).antisymm H.1.2 }, { unfreezingI { rintro (rfl : J = I) }, refine ⟨⟨infer_instance, rfl.le⟩, λ _ h _, h.2⟩ }, end end
0eb03acc585a1a33294673be95253ecc997fa184
0c1546a496eccfb56620165cad015f88d56190c5
/tests/lean/run/do_match_else.lean
18a71010175e150d4c3806019117d97c80f5eda3
[ "Apache-2.0" ]
permissive
Solertis/lean
491e0939957486f664498fbfb02546e042699958
84188c5aa1673fdf37a082b2de8562dddf53df3f
refs/heads/master
1,610,174,257,606
1,486,263,620,000
1,486,263,620,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
562
lean
open tactic set_option pp.all true meta def app2 (f a b : expr) := expr.app (expr.app f a) b example (a b c x y : nat) (H : nat.add (nat.add x y) y = 0) : true := by do a ← get_local `a, b ← get_local `b, c ← get_local `c, H ← get_local `H >>= infer_type, (lhs, rhs) ← match_eq H, nat_add : expr ← mk_const `nat.add, p : pattern ← mk_pattern [] [a, b] (app2 nat_add a b) [app2 nat_add b a, a, b], trace (pattern.output p), [v₁, v₂, v₃] ← match_pattern p lhs | failed, trace v₁, trace v₂, trace v₃, constructor
956fe95d1478e38b30444b96af2e292e60ebc381
54c9ed381c63410c9b6af3b0a1722c41152f037f
/Binport/ActionItem.lean
aac0eb702757bdaa8622ed04dbb254f660cf7006
[ "Apache-2.0" ]
permissive
dselsam/binport
0233f1aa961a77c4fc96f0dccc780d958c5efc6c
aef374df0e169e2c3f1dc911de240c076315805c
refs/heads/master
1,687,453,448,108
1,627,483,296,000
1,627,483,296,000
333,825,622
0
0
null
null
null
null
UTF-8
Lean
false
false
2,823
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Daniel Selsam -/ import Binport.Util import Binport.Path import Lean import Std.Data.HashSet import Std.Data.HashMap namespace Binport open Lean inductive MixfixKind | «prefix» | «infixl» | «infixr» | «postfix» | «singleton» def MixfixKind.toAttr : MixfixKind → Name | MixfixKind.prefix => `Lean.Parser.Command.prefix | MixfixKind.postfix => `Lean.Parser.Command.postfix | MixfixKind.infixl => `Lean.Parser.Command.infixl | MixfixKind.infixr => `Lean.Parser.Command.infixr | MixfixKind.singleton => `Lean.Parser.Command.notation instance : ToString MixfixKind := ⟨λ | MixfixKind.prefix => "prefix" | MixfixKind.postfix => "postfix" | MixfixKind.infixl => "infixl" | MixfixKind.infixr => "infixr" | MixfixKind.singleton => "notation"⟩ instance : BEq ReducibilityStatus := ⟨λ | ReducibilityStatus.reducible, ReducibilityStatus.reducible => true | ReducibilityStatus.semireducible, ReducibilityStatus.semireducible => true | ReducibilityStatus.irreducible, ReducibilityStatus.irreducible => true | _, _ => false⟩ structure ExportDecl : Type where currNs : Name ns : Name nsAs : Name hadExplicit : Bool renames : Array (Name × Name) exceptNames : Array Name structure ProjectionInfo : Type where -- pr_i A.. (mk A f_1 ... f_n) ==> f_i projName : Name -- pr_i ctorName : Name -- mk nParams : Nat -- |A..| index : Nat -- i fromClass : Bool deriving Repr inductive ActionItem : Type | decl : Declaration → ActionItem | «class» : (c : Name) → ActionItem | «instance» : (c i : Name) → (prio : Nat) → ActionItem | simp : (name : Name) → (prio : Nat) → ActionItem | «private» : (pretty real : Name) → ActionItem | «protected» : (name : Name) → ActionItem | «reducibility» : (name : Name) → ReducibilityStatus → ActionItem | «mixfix» : MixfixKind → Name → Nat → String → ActionItem | «export» : ExportDecl → ActionItem | «projection» : ProjectionInfo → ActionItem def ActionItem.toDecl : ActionItem → Name | ActionItem.decl d => match d.names with | [] => `nodecl | n::_ => n | ActionItem.class c => c | ActionItem.instance _ i _ => i | ActionItem.simp n _ => n | ActionItem.private _ real => real | ActionItem.protected n => n | ActionItem.reducibility n _ => n | ActionItem.mixfix _ n _ _ => n | ActionItem.export _ => `inExport | ActionItem.projection p => p.projName end Binport
334980dd7e6fe7f7dee2a2ef6bfd4d66fe947c41
4727251e0cd73359b15b664c3170e5d754078599
/src/data/nat/nth.lean
9bc9a72418d12abf55ba0cc512e7a43bda0ef53c
[ "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
15,213
lean
/- Copyright (c) 2021 Vladimir Goryachev. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies, Vladimir Goryachev, Kyle Miller, Scott Morrison, Eric Rodriguez -/ import data.nat.count import order.order_iso_nat /-! # The `n`th Number Satisfying a Predicate This file defines a function for "what is the `n`th number that satisifies a given predicate `p`", and provides lemmas that deal with this function and its connection to `nat.count`. ## Main definitions * `nth p n`: The `n`-th natural `k` (zero-indexed) such that `p k`. If there is no such natural (that is, `p` is true for at most `n` naturals), then `nth p n = 0`. ## Main results * `nat.nth_set_card`: For a fintely-often true `p`, gives the cardinality of the set of numbers satisfying `p` above particular values of `nth p` * `nat.count_nth_gc`: Establishes a Galois connection between `nth p` and `count p`. * `nat.nth_eq_order_iso_of_nat`: For an infinitely-ofter true predicate, `nth` agrees with the order-isomorphism of the subtype to the natural numbers. There has been some discussion on the subject of whether both of `nth` and `nat.subtype.order_iso_of_nat` should exist. See discussion [here](https://github.com/leanprover-community/mathlib/pull/9457#pullrequestreview-767221180). Future work should address how lemmas that use these should be written. -/ open finset namespace nat variable (p : ℕ → Prop) /-- Find the `n`-th natural number satisfying `p` (indexed from `0`, so `nth p 0` is the first natural number satisfying `p`), or `0` if there is no such number. See also `subtype.order_iso_of_nat` for the order isomorphism with ℕ when `p` is infinitely often true. -/ noncomputable def nth : ℕ → ℕ | n := Inf { i : ℕ | p i ∧ ∀ k < n, nth k < i } lemma nth_zero : nth p 0 = Inf { i : ℕ | p i } := by { rw nth, simp } @[simp] lemma nth_zero_of_zero (h : p 0) : nth p 0 = 0 := by simp [nth_zero, h] lemma nth_zero_of_exists [decidable_pred p] (h : ∃ n, p n) : nth p 0 = nat.find h := by { rw [nth_zero], convert nat.Inf_def h } lemma nth_set_card_aux {n : ℕ} (hp : (set_of p).finite) (hp' : {i : ℕ | p i ∧ ∀ t < n, nth p t < i}.finite) (hle : n ≤ hp.to_finset.card) : hp'.to_finset.card = hp.to_finset.card - n := begin unfreezingI { induction n with k hk }, { congr, simp only [forall_false_left, nat.not_lt_zero, forall_const, and_true] }, have hp'': {i : ℕ | p i ∧ ∀ t, t < k → nth p t < i}.finite, { refine hp.subset (λ x hx, _), rw set.mem_set_of_eq at hx, exact hx.left }, have hle' := nat.sub_pos_of_lt hle, specialize hk hp'' (k.le_succ.trans hle), rw [nat.sub_succ', ←hk], convert_to (finset.erase hp''.to_finset (nth p k)).card = _, { congr, ext a, simp only [set.finite.mem_to_finset, ne.def, set.mem_set_of_eq, finset.mem_erase], refine ⟨λ ⟨hp, hlt⟩, ⟨(hlt _ (lt_add_one k)).ne', ⟨hp, λ n hn, hlt n (hn.trans_le k.le_succ)⟩⟩, _⟩, rintro ⟨hak : _ ≠ _, hp, hlt⟩, refine ⟨hp, λ n hn, _⟩, rw lt_succ_iff at hn, obtain hnk | rfl := hn.lt_or_eq, { exact hlt _ hnk }, { refine lt_of_le_of_ne _ (ne.symm hak), rw nth, apply nat.Inf_le, simpa [hp] using hlt } }, apply finset.card_erase_of_mem, rw [nth, set.finite.mem_to_finset], apply Inf_mem, rwa [←set.finite.to_finset.nonempty hp'', ←finset.card_pos, hk], end lemma nth_set_card {n : ℕ} (hp : (set_of p).finite) (hp' : {i : ℕ | p i ∧ ∀ k < n, nth p k < i}.finite) : hp'.to_finset.card = hp.to_finset.card - n := begin obtain hn | hn := le_or_lt n hp.to_finset.card, { exact nth_set_card_aux p hp _ hn }, rw nat.sub_eq_zero_of_le hn.le, simp only [finset.card_eq_zero, set.finite_to_finset_eq_empty_iff, ←set.subset_empty_iff], convert_to _ ⊆ {i : ℕ | p i ∧ ∀ (k : ℕ), k < hp.to_finset.card → nth p k < i}, { symmetry, rw [←set.finite_to_finset_eq_empty_iff, ←finset.card_eq_zero, ←nat.sub_self hp.to_finset.card], { apply nth_set_card_aux p hp _ le_rfl }, { exact hp.subset (λ x hx, hx.1) } }, exact λ x hx, ⟨hx.1, λ k hk, hx.2 _ (hk.trans hn)⟩, end lemma nth_set_nonempty_of_lt_card {n : ℕ} (hp : (set_of p).finite) (hlt: n < hp.to_finset.card) : {i : ℕ | p i ∧ ∀ k < n, nth p k < i}.nonempty := begin have hp': {i : ℕ | p i ∧ ∀ (k : ℕ), k < n → nth p k < i}.finite, { exact hp.subset (λ x hx, hx.1) }, rw [←hp'^.to_finset.nonempty, ←finset.card_pos, nth_set_card p hp], exact nat.sub_pos_of_lt hlt, end lemma nth_mem_of_lt_card_finite_aux (n : ℕ) (hp : (set_of p).finite) (hlt : n < hp.to_finset.card) : nth p n ∈ {i : ℕ | p i ∧ ∀ k < n, nth p k < i} := begin rw nth, apply Inf_mem, exact nth_set_nonempty_of_lt_card _ _ hlt, end lemma nth_mem_of_lt_card_finite {n : ℕ} (hp : (set_of p).finite) (hlt : n < hp.to_finset.card) : p (nth p n) := (nth_mem_of_lt_card_finite_aux p n hp hlt).1 lemma nth_strict_mono_of_finite {m n : ℕ} (hp : (set_of p).finite) (hlt : n < hp.to_finset.card) (hmn : m < n) : nth p m < nth p n := (nth_mem_of_lt_card_finite_aux p _ hp hlt).2 _ hmn lemma nth_mem_of_infinite_aux (hp : (set_of p).infinite) (n : ℕ) : nth p n ∈ { i : ℕ | p i ∧ ∀ k < n, nth p k < i } := begin rw nth, apply Inf_mem, let s : set ℕ := ⋃ (k < n), { i : ℕ | nth p k ≥ i }, convert_to ((set_of p) \ s).nonempty, { ext i, simp }, refine (hp.diff $ (set.finite_lt_nat _).bUnion _).nonempty, exact λ k h, set.finite_le_nat _, end lemma nth_mem_of_infinite (hp : (set_of p).infinite) (n : ℕ) : p (nth p n) := (nth_mem_of_infinite_aux p hp n).1 lemma nth_strict_mono (hp : (set_of p).infinite) : strict_mono (nth p) := λ a b, (nth_mem_of_infinite_aux p hp b).2 _ lemma nth_injective_of_infinite (hp : (set_of p).infinite) : function.injective (nth p) := begin intros m n h, wlog h' : m ≤ n, rw le_iff_lt_or_eq at h', obtain (h' | rfl) := h', { simpa [h] using nth_strict_mono p hp h' }, { refl }, end lemma nth_monotone (hp : (set_of p).infinite) : monotone (nth p) := (nth_strict_mono p hp).monotone lemma nth_mono_of_finite {a b : ℕ} (hp : (set_of p).finite) (hb : b < hp.to_finset.card) (hab : a ≤ b) : nth p a ≤ nth p b := begin obtain rfl | h := hab.eq_or_lt, { exact le_rfl }, { exact (nth_strict_mono_of_finite p hp hb h).le } end lemma le_nth_of_lt_nth_succ_finite {k a : ℕ} (hp : (set_of p).finite) (hlt : k.succ < hp.to_finset.card) (h : a < nth p k.succ) (ha : p a) : a ≤ nth p k := begin by_contra' hak, refine h.not_le _, rw nth, apply nat.Inf_le, refine ⟨ha, λ n hn, lt_of_le_of_lt _ hak⟩, exact nth_mono_of_finite p hp (k.le_succ.trans_lt hlt) (le_of_lt_succ hn), end lemma le_nth_of_lt_nth_succ_infinite {k a : ℕ} (hp : (set_of p).infinite) (h : a < nth p k.succ) (ha : p a) : a ≤ nth p k := begin by_contra' hak, refine h.not_le _, rw nth, apply nat.Inf_le, exact ⟨ha, λ n hn, (nth_monotone p hp (le_of_lt_succ hn)).trans_lt hak⟩, end section count variables [decidable_pred p] @[simp] lemma count_nth_zero : count p (nth p 0) = 0 := begin rw [count_eq_card_filter_range, finset.card_eq_zero, nth_zero], ext a, simp_rw [not_mem_empty, mem_filter, mem_range, iff_false], rintro ⟨ha, hp⟩, exact ha.not_le (nat.Inf_le hp), end lemma filter_range_nth_eq_insert_of_finite (hp : (set_of p).finite) {k : ℕ} (hlt : k.succ < hp.to_finset.card) : finset.filter p (finset.range (nth p k.succ)) = insert (nth p k) (finset.filter p (finset.range (nth p k))) := begin ext a, simp_rw [mem_insert, mem_filter, mem_range], split, { rintro ⟨ha, hpa⟩, refine or_iff_not_imp_left.mpr (λ h, ⟨lt_of_le_of_ne _ h, hpa⟩), exact le_nth_of_lt_nth_succ_finite p hp hlt ha hpa }, { rintro (ha | ⟨ha, hpa⟩), { rw ha, refine ⟨nth_strict_mono_of_finite p hp hlt (lt_add_one _), _⟩, apply nth_mem_of_lt_card_finite p hp, exact (k.le_succ).trans_lt hlt }, refine ⟨ha.trans _, hpa⟩, exact nth_strict_mono_of_finite p hp hlt (lt_add_one _) } end lemma count_nth_of_lt_card_finite {n : ℕ} (hp : (set_of p).finite) (hlt : n < hp.to_finset.card) : count p (nth p n) = n := begin induction n with k hk, { exact count_nth_zero _ }, { rw [count_eq_card_filter_range, filter_range_nth_eq_insert_of_finite p hp hlt, finset.card_insert_of_not_mem, ←count_eq_card_filter_range, hk (lt_of_succ_lt hlt)], simp, }, end lemma filter_range_nth_eq_insert_of_infinite (hp : (set_of p).infinite) (k : ℕ) : (finset.range (nth p k.succ)).filter p = insert (nth p k) ((finset.range (nth p k)).filter p) := begin ext a, simp_rw [mem_insert, mem_filter, mem_range], split, { rintro ⟨ha, hpa⟩, rw nth at ha, refine or_iff_not_imp_left.mpr (λ hne, ⟨(le_of_not_lt $ λ h, _).lt_of_ne hne, hpa⟩), exact ha.not_le (nat.Inf_le ⟨hpa, λ b hb, (nth_monotone p hp (le_of_lt_succ hb)).trans_lt h⟩) }, { rintro (rfl | ⟨ha, hpa⟩), { exact ⟨nth_strict_mono p hp (lt_succ_self k), nth_mem_of_infinite p hp _⟩ }, { exact ⟨ha.trans (nth_strict_mono p hp (lt_succ_self k)), hpa⟩ } } end lemma count_nth_of_infinite (hp : (set_of p).infinite) (n : ℕ) : count p (nth p n) = n := begin induction n with k hk, { exact count_nth_zero _ }, { rw [count_eq_card_filter_range, filter_range_nth_eq_insert_of_infinite p hp, finset.card_insert_of_not_mem, ←count_eq_card_filter_range, hk], simp, }, end @[simp] lemma nth_count {n : ℕ} (hpn : p n) : nth p (count p n) = n := begin obtain hp | hp := em (set_of p).finite, { refine count_injective _ hpn _, { apply nth_mem_of_lt_card_finite p hp, exact count_lt_card hp hpn }, { exact count_nth_of_lt_card_finite _ _ (count_lt_card hp hpn) } }, { apply count_injective (nth_mem_of_infinite _ hp _) hpn, apply count_nth_of_infinite p hp } end lemma nth_count_eq_Inf {n : ℕ} : nth p (count p n) = Inf {i : ℕ | p i ∧ n ≤ i} := begin rw nth, congr, ext a, simp only [set.mem_set_of_eq, and.congr_right_iff], intro hpa, refine ⟨λ h, _, λ hn k hk, lt_of_lt_of_le _ hn⟩, { by_contra ha, simp only [not_le] at ha, have hn : nth p (count p a) < a := h _ (count_strict_mono hpa ha), rwa [nth_count p hpa, lt_self_iff_false] at hn }, { apply (count_monotone p).reflect_lt, convert hk, obtain hp | hp : (set_of p).finite ∨ (set_of p).infinite := em (set_of p).finite, { rw count_nth_of_lt_card_finite _ hp, exact hk.trans ((count_monotone _ hn).trans_lt (count_lt_card hp hpa)) }, { apply count_nth_of_infinite p hp } } end lemma nth_count_le (hp : (set_of p).infinite) (n : ℕ) : n ≤ nth p (count p n) := begin rw nth_count_eq_Inf, suffices h : Inf {i : ℕ | p i ∧ n ≤ i} ∈ {i : ℕ | p i ∧ n ≤ i}, { exact h.2 }, apply Inf_mem, obtain ⟨m, hp, hn⟩ := hp.exists_nat_lt n, exact ⟨m, hp, hn.le⟩ end lemma count_nth_gc (hp : (set_of p).infinite) : galois_connection (count p) (nth p) := begin rintro x y, rw [nth, le_cInf_iff ⟨0, λ _ _, nat.zero_le _⟩ ⟨nth p y, nth_mem_of_infinite_aux p hp y⟩], dsimp, refine ⟨_, λ h, _⟩, { rintro hy n ⟨hn, h⟩, obtain hy' | rfl := hy.lt_or_eq, { exact (nth_count_le p hp x).trans (h (count p x) hy').le }, { specialize h (count p n), replace hn : nth p (count p n) = n := nth_count _ hn, replace h : count p x ≤ count p n := by rwa [hn, lt_self_iff_false, imp_false, not_lt] at h, refine (nth_count_le p hp x).trans _, rw ← hn, exact nth_monotone p hp h }, }, { rw ←count_nth_of_infinite p hp y, exact count_monotone _ (h (nth p y) ⟨nth_mem_of_infinite p hp y, λ k hk, nth_strict_mono p hp hk⟩) } end lemma count_le_iff_le_nth (hp : (set_of p).infinite) {a b : ℕ} : count p a ≤ b ↔ a ≤ nth p b := count_nth_gc p hp _ _ lemma lt_nth_iff_count_lt (hp : (set_of p).infinite) {a b : ℕ} : a < count p b ↔ nth p a < b := lt_iff_lt_of_le_iff_le $ count_le_iff_le_nth p hp lemma nth_lt_of_lt_count (n k : ℕ) (h : k < count p n) : nth p k < n := begin obtain hp | hp := em (set_of p).finite, { refine (count_monotone p).reflect_lt _, rwa count_nth_of_lt_card_finite p hp, refine h.trans_le _, rw count_eq_card_filter_range, exact finset.card_le_of_subset (λ x hx, hp.mem_to_finset.2 (mem_filter.1 hx).2) }, { rwa ← lt_nth_iff_count_lt _ hp } end lemma le_nth_of_count_le (n k : ℕ) (h: n ≤ nth p k) : count p n ≤ k := begin by_contra hc, apply not_lt.mpr h, apply nth_lt_of_lt_count, simpa using hc end end count lemma nth_zero_of_nth_zero (h₀ : ¬p 0) {a b : ℕ} (hab : a ≤ b) (ha : nth p a = 0) : nth p b = 0 := begin rw [nth, Inf_eq_zero] at ⊢ ha, cases ha, { exact (h₀ ha.1).elim }, { refine or.inr (set.eq_empty_of_subset_empty $ λ x hx, _), rw ←ha, exact ⟨hx.1, λ k hk, hx.2 k $ hk.trans_le hab⟩ } end /-- When `p` is true infinitely often, `nth` agrees with `nat.subtype.order_iso_of_nat`. -/ lemma nth_eq_order_iso_of_nat [decidable_pred p] (i : infinite (set_of p)) (n : ℕ) : nth p n = nat.subtype.order_iso_of_nat (set_of p) n := begin have hi := set.infinite_coe_iff.mp i, induction n with k hk; simp only [subtype.order_iso_of_nat_apply, subtype.of_nat, nat_zero_eq_zero], { rw [nat.subtype.coe_bot, nth_zero_of_exists], }, { simp only [nat.subtype.succ, set.mem_set_of_eq, subtype.coe_mk, subtype.val_eq_coe], rw [subtype.order_iso_of_nat_apply] at hk, set b := nth p k.succ - nth p k - 1 with hb, replace hb : p (↑(subtype.of_nat (set_of p) k) + b + 1), { rw [hb, ←hk, tsub_right_comm], have hn11: nth p k.succ - 1 + 1 = nth p k.succ, { rw tsub_add_cancel_iff_le, exact succ_le_of_lt (pos_of_gt (nth_strict_mono p hi (lt_add_one k))), }, rw add_tsub_cancel_of_le, { rw hn11, apply nth_mem_of_infinite p hi }, { rw [← lt_succ_iff, ← nat.add_one, hn11], apply nth_strict_mono p hi, exact lt_add_one k } }, have H : (∃ n: ℕ , p (↑(subtype.of_nat (set_of p) k) + n + 1)) := ⟨b, hb⟩, set t := nat.find H with ht, obtain ⟨hp, hmin⟩ := (nat.find_eq_iff _).mp ht, rw [←ht, ←hk] at hp hmin ⊢, rw [nth, Inf_def ⟨_, nth_mem_of_infinite_aux p hi k.succ⟩, nat.find_eq_iff], refine ⟨⟨by convert hp, λ r hr, _⟩, λ n hn, _⟩, { rw lt_succ_iff at ⊢ hr, exact (nth_monotone p hi hr).trans (by simp) }, simp only [exists_prop, not_and, not_lt, set.mem_set_of_eq, not_forall], refine λ hpn, ⟨k, lt_add_one k, _⟩, by_contra' hlt, replace hn : n - nth p k - 1 < t, { rw tsub_lt_iff_left, { rw tsub_lt_iff_left hlt.le, convert hn using 1, ac_refl }, exact le_tsub_of_add_le_left (succ_le_of_lt hlt) }, refine hmin (n - nth p k - 1) hn _, convert hpn, have hn11 : n - 1 + 1 = n := nat.sub_add_cancel (pos_of_gt hlt), rwa [tsub_right_comm, add_tsub_cancel_of_le], rwa [←hn11, lt_succ_iff] at hlt }, end end nat
bd3ce4b086609e0dea54be531ee36af8e313bc80
4727251e0cd73359b15b664c3170e5d754078599
/src/linear_algebra/special_linear_group.lean
36209babd43d43a5a311967eb993b57b1a9b4b63
[ "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
8,632
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.adjugate import linear_algebra.matrix.to_lin /-! # The Special Linear group $SL(n, R)$ This file defines the elements of the Special Linear group `special_linear_group n R`, consisting of all square `R`-matrices with determinant `1` on the fintype `n` by `n`. In addition, we define the group structure on `special_linear_group n R` and the embedding into the general linear group `general_linear_group R (n → R)`. ## Main definitions * `matrix.special_linear_group` is the type of matrices with determinant 1 * `matrix.special_linear_group.group` gives the group structure (under multiplication) * `matrix.special_linear_group.to_GL` is the embedding `SLₙ(R) → GLₙ(R)` ## Notation For `m : ℕ`, we introduce the notation `SL(m,R)` for the special linear group on the fintype `n = fin m`, in the locale `matrix_groups`. ## Implementation notes The inverse operation in the `special_linear_group` is defined to be the adjugate matrix, so that `special_linear_group n R` has a group structure for all `comm_ring R`. We define the elements of `special_linear_group` to be matrices, since we need to compute their determinant. This is in contrast with `general_linear_group R M`, which consists of invertible `R`-linear maps on `M`. We provide `matrix.special_linear_group.has_coe_to_fun` for convenience, but do not state any lemmas about it, and use `matrix.special_linear_group.coe_fn_eq_coe` to eliminate it `⇑` in favor of a regular `↑` coercion. ## References * https://en.wikipedia.org/wiki/Special_linear_group ## Tags matrix group, group, matrix inverse -/ namespace matrix universes u v open_locale matrix open linear_map section variables (n : Type u) [decidable_eq n] [fintype n] (R : Type v) [comm_ring R] /-- `special_linear_group n R` is the group of `n` by `n` `R`-matrices with determinant equal to 1. -/ def special_linear_group := { A : matrix n n R // A.det = 1 } end localized "notation `SL(` n `,` R `)`:= matrix.special_linear_group (fin n) R" in matrix_groups namespace special_linear_group variables {n : Type u} [decidable_eq n] [fintype n] {R : Type v} [comm_ring R] instance has_coe_to_matrix : has_coe (special_linear_group n R) (matrix n n R) := ⟨λ A, A.val⟩ /- In this file, Lean often has a hard time working out the values of `n` and `R` for an expression like `det ↑A`. Rather than writing `(A : matrix n n R)` everywhere in this file which is annoyingly verbose, or `A.val` which is not the simp-normal form for subtypes, we create a local notation `↑ₘA`. This notation references the local `n` and `R` variables, so is not valid as a global notation. -/ local prefix `↑ₘ`:1024 := @coe _ (matrix n n R) _ lemma ext_iff (A B : special_linear_group n R) : A = B ↔ (∀ i j, ↑ₘA i j = ↑ₘB i j) := subtype.ext_iff.trans matrix.ext_iff.symm @[ext] lemma ext (A B : special_linear_group n R) : (∀ i j, ↑ₘA i j = ↑ₘB i j) → A = B := (special_linear_group.ext_iff A B).mpr instance has_inv : has_inv (special_linear_group n R) := ⟨λ A, ⟨adjugate A, by rw [det_adjugate, A.prop, one_pow]⟩⟩ instance has_mul : has_mul (special_linear_group n R) := ⟨λ A B, ⟨A.1 ⬝ B.1, by erw [det_mul, A.2, B.2, one_mul]⟩⟩ instance has_one : has_one (special_linear_group n R) := ⟨⟨1, det_one⟩⟩ instance : has_pow (special_linear_group n R) ℕ := { pow := λ x n, ⟨x ^ n, (det_pow _ _).trans $ x.prop.symm ▸ one_pow _⟩} instance : inhabited (special_linear_group n R) := ⟨1⟩ section coe_lemmas variables (A B : special_linear_group n R) @[simp] lemma coe_mk (A : matrix n n R) (h : det A = 1) : ↑(⟨A, h⟩ : special_linear_group n R) = A := rfl @[simp] lemma coe_inv : ↑ₘ(A⁻¹) = adjugate A := rfl @[simp] lemma coe_mul : ↑ₘ(A * B) = ↑ₘA ⬝ ↑ₘB := rfl @[simp] lemma coe_one : ↑ₘ(1 : special_linear_group n R) = (1 : matrix n n R) := rfl @[simp] lemma det_coe : det ↑ₘA = 1 := A.2 @[simp] lemma coe_pow (m : ℕ) : ↑ₘ(A ^ m) = ↑ₘA ^ m := rfl lemma det_ne_zero [nontrivial R] (g : special_linear_group n R) : det ↑ₘg ≠ 0 := by { rw g.det_coe, norm_num } lemma row_ne_zero [nontrivial R] (g : special_linear_group n R) (i : n): ↑ₘg i ≠ 0 := λ h, g.det_ne_zero $ det_eq_zero_of_row_eq_zero i $ by simp [h] end coe_lemmas instance : monoid (special_linear_group n R) := function.injective.monoid coe subtype.coe_injective coe_one coe_mul coe_pow instance : group (special_linear_group n R) := { mul_left_inv := λ A, by { ext1, simp [adjugate_mul] }, ..special_linear_group.monoid, ..special_linear_group.has_inv } /-- A version of `matrix.to_lin' A` that produces linear equivalences. -/ def to_lin' : special_linear_group n R →* (n → R) ≃ₗ[R] (n → R) := { to_fun := λ A, linear_equiv.of_linear (matrix.to_lin' ↑ₘA) (matrix.to_lin' ↑ₘ(A⁻¹)) (by rw [←to_lin'_mul, ←coe_mul, mul_right_inv, coe_one, to_lin'_one]) (by rw [←to_lin'_mul, ←coe_mul, mul_left_inv, coe_one, to_lin'_one]), map_one' := linear_equiv.to_linear_map_injective matrix.to_lin'_one, map_mul' := λ A B, linear_equiv.to_linear_map_injective $ matrix.to_lin'_mul A B } lemma to_lin'_apply (A : special_linear_group n R) (v : n → R) : special_linear_group.to_lin' A v = matrix.to_lin' ↑ₘA v := rfl lemma to_lin'_to_linear_map (A : special_linear_group n R) : ↑(special_linear_group.to_lin' A) = matrix.to_lin' ↑ₘA := rfl lemma to_lin'_symm_apply (A : special_linear_group n R) (v : n → R) : A.to_lin'.symm v = matrix.to_lin' ↑ₘ(A⁻¹) v := rfl lemma to_lin'_symm_to_linear_map (A : special_linear_group n R) : ↑(A.to_lin'.symm) = matrix.to_lin' ↑ₘ(A⁻¹) := rfl lemma to_lin'_injective : function.injective ⇑(to_lin' : special_linear_group n R →* (n → R) ≃ₗ[R] (n → R)) := λ A B h, subtype.coe_injective $ matrix.to_lin'.injective $ linear_equiv.to_linear_map_injective.eq_iff.mpr h /-- `to_GL` is the map from the special linear group to the general linear group -/ def to_GL : special_linear_group n R →* general_linear_group R (n → R) := (general_linear_group.general_linear_equiv _ _).symm.to_monoid_hom.comp to_lin' lemma coe_to_GL (A : special_linear_group n R) : ↑A.to_GL = A.to_lin'.to_linear_map := rfl variables {S : Type*} [comm_ring S] /-- A ring homomorphism from `R` to `S` induces a group homomorphism from `special_linear_group n R` to `special_linear_group n S`. -/ @[simps] def map (f : R →+* S) : special_linear_group n R →* special_linear_group n S := { to_fun := λ g, ⟨f.map_matrix ↑g, by { rw ← f.map_det, simp [g.2] }⟩, map_one' := subtype.ext $ f.map_matrix.map_one, map_mul' := λ x y, subtype.ext $ f.map_matrix.map_mul x y } section cast /-- Coercion of SL `n` `ℤ` to SL `n` `R` for a commutative ring `R`. -/ instance : has_coe (special_linear_group n ℤ) (special_linear_group n R) := ⟨λ x, map (int.cast_ring_hom R) x⟩ @[simp] lemma coe_matrix_coe (g : special_linear_group n ℤ) : ↑(g : special_linear_group n R) = (↑g : matrix n n ℤ).map (int.cast_ring_hom R) := map_apply_coe (int.cast_ring_hom R) g end cast section has_neg variables [fact (even (fintype.card n))] /-- Formal operation of negation on special linear group on even cardinality `n` given by negating each element. -/ instance : has_neg (special_linear_group n R) := ⟨λ g, ⟨- g, by simpa [(fact.out $ even $ fintype.card n).neg_one_pow, g.det_coe] using det_smul ↑ₘg (-1)⟩⟩ @[simp] lemma coe_neg (g : special_linear_group n R) : ↑(- g) = - (↑g : matrix n n R) := rfl instance : has_distrib_neg (special_linear_group n R) := { neg := has_neg.neg, neg_neg := λ x, subtype.ext $ neg_neg _, neg_mul := λ x y, subtype.ext $ neg_mul _ _, mul_neg := λ x y, subtype.ext $ mul_neg _ _ } @[simp] lemma coe_int_neg (g : (special_linear_group n ℤ)) : ↑(-g) = (-↑g : special_linear_group n R) := subtype.ext $ (@ring_hom.map_matrix n _ _ _ _ _ _ (int.cast_ring_hom R)).map_neg ↑g end has_neg -- this section should be last to ensure we do not use it in lemmas section coe_fn_instance /-- This instance is here for convenience, but is not the simp-normal form. -/ instance : has_coe_to_fun (special_linear_group n R) (λ _, n → n → R) := { coe := λ A, A.val } @[simp] lemma coe_fn_eq_coe (s : special_linear_group n R) : ⇑s = ↑ₘs := rfl end coe_fn_instance end special_linear_group end matrix
8adf3c632d49921c7471c3f5e4f57237328d9c88
4d3f29a7b2eff44af8fd0d3176232e039acb9ee3
/LAMR/Examples/using_lean/examples5.lean
62b19467c20d4aa1d0a5add4c425c33fac39c5cd
[]
no_license
marijnheule/lamr
5fc5d69d326ff92e321242cfd7f72e78d7f99d7e
28cc4114c7361059bb54f407fa312bf38b48728b
refs/heads/main
1,689,338,013,620
1,630,359,632,000
1,630,359,632,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,213
lean
import Init -- textbook: showSums def showSums : IO Unit := do let mut sum := 0 for i in [0:100] do sum := sum + i IO.println s!"i: {i}, sum: {sum}" #eval showSums -- end textbook: showSums -- textbook: isPrime def isPrime (n : Nat) : Bool := do if n < 2 then false else for i in [2:n] do if n % i = 0 then return false if i * i > n then return true true -- end textbook: isPrime -- textbook: list of primes #eval (List.range 10000).filter isPrime -- end textbook: list of primes -- textbook: primes def primes (n : Nat) : Array Nat := do let mut result := #[] for i in [2:n] do if isPrime i then result := result.push i result #eval (primes 10000).size -- end textbook: primes -- textbook: mulTable def mulTable (n : Nat) : Array (Array Nat) := do let mut table := #[] for i in [:n] do let mut row := #[] for j in [:n] do row := row.push ((i + 1) * (j + 1)) table := table.push row table #eval mulTable 10 def printMulTable (n : Nat) : IO Unit := do let t := mulTable n for i in [:n] do for j in [:n] do IO.print s!"{t[i][j]} " IO.println "" #eval printMulTable 10 -- end textbook: mulTable
ef1cad2bfe57deafd98c48cffc1c62f1fe5f43f1
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/empty_match.lean
1fdac3894be18be4c4f55100fa232414f1080fa2
[ "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
117
lean
open nat definition not_lt_zero (a : nat) : ¬ a < zero := assume H : a < zero, match H with end check not_lt_zero
89bd21f4b210b2dbd59180ac59e0e78bec77802a
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebra/order/ring/abs.lean
4dcdeda4b64ddc9afc2a0c679a4605cb3e3794a5
[ "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,688
lean
/- Copyright (c) 2016 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura, Mario Carneiro -/ import algebra.order.ring.defs import algebra.ring.divisibility import algebra.order.group.abs /-! # Absolute values in linear ordered rings. > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. -/ variables {α : Type*} section linear_ordered_ring variables [linear_ordered_ring α] {a b c : α} @[simp] lemma abs_one : |(1 : α)| = 1 := abs_of_pos zero_lt_one @[simp] lemma abs_two : |(2 : α)| = 2 := abs_of_pos zero_lt_two lemma abs_mul (a b : α) : |a * b| = |a| * |b| := begin rw [abs_eq (mul_nonneg (abs_nonneg a) (abs_nonneg b))], cases le_total a 0 with ha ha; cases le_total b 0 with hb hb; simp only [abs_of_nonpos, abs_of_nonneg, true_or, or_true, eq_self_iff_true, neg_mul, mul_neg, neg_neg, *] end /-- `abs` as a `monoid_with_zero_hom`. -/ def abs_hom : α →*₀ α := ⟨abs, abs_zero, abs_one, abs_mul⟩ @[simp] lemma abs_mul_abs_self (a : α) : |a| * |a| = a * a := abs_by_cases (λ x, x * x = a * a) rfl (neg_mul_neg a a) @[simp] lemma abs_mul_self (a : α) : |a * a| = a * a := by rw [abs_mul, abs_mul_abs_self] @[simp] lemma abs_eq_self : |a| = a ↔ 0 ≤ a := by simp [abs_eq_max_neg] @[simp] lemma abs_eq_neg_self : |a| = -a ↔ a ≤ 0 := by simp [abs_eq_max_neg] /-- For an element `a` of a linear ordered ring, either `abs a = a` and `0 ≤ a`, or `abs a = -a` and `a < 0`. Use cases on this lemma to automate linarith in inequalities -/ lemma abs_cases (a : α) : (|a| = a ∧ 0 ≤ a) ∨ (|a| = -a ∧ a < 0) := begin by_cases 0 ≤ a, { left, exact ⟨abs_eq_self.mpr h, h⟩ }, { right, push_neg at h, exact ⟨abs_eq_neg_self.mpr (le_of_lt h), h⟩ } end @[simp] lemma max_zero_add_max_neg_zero_eq_abs_self (a : α) : max a 0 + max (-a) 0 = |a| := begin symmetry, rcases le_total 0 a with ha|ha; simp [ha], end lemma abs_eq_iff_mul_self_eq : |a| = |b| ↔ a * a = b * b := begin rw [← abs_mul_abs_self, ← abs_mul_abs_self b], exact (mul_self_inj (abs_nonneg a) (abs_nonneg b)).symm, end lemma abs_lt_iff_mul_self_lt : |a| < |b| ↔ a * a < b * b := begin rw [← abs_mul_abs_self, ← abs_mul_abs_self b], exact mul_self_lt_mul_self_iff (abs_nonneg a) (abs_nonneg b) end lemma abs_le_iff_mul_self_le : |a| ≤ |b| ↔ a * a ≤ b * b := begin rw [← abs_mul_abs_self, ← abs_mul_abs_self b], exact mul_self_le_mul_self_iff (abs_nonneg a) (abs_nonneg b) end lemma abs_le_one_iff_mul_self_le_one : |a| ≤ 1 ↔ a * a ≤ 1 := by simpa only [abs_one, one_mul] using @abs_le_iff_mul_self_le α _ a 1 end linear_ordered_ring section linear_ordered_comm_ring variables [linear_ordered_comm_ring α] {a b c d : α} lemma abs_sub_sq (a b : α) : |a - b| * |a - b| = a * a + b * b - (1 + 1) * a * b := begin rw abs_mul_abs_self, simp only [mul_add, add_comm, add_left_comm, mul_comm, sub_eq_add_neg, mul_one, mul_neg, neg_add_rev, neg_neg], end end linear_ordered_comm_ring section variables [ring α] [linear_order α] {a b : α} @[simp] lemma abs_dvd (a b : α) : |a| ∣ b ↔ a ∣ b := by { cases abs_choice a with h h; simp only [h, neg_dvd] } lemma abs_dvd_self (a : α) : |a| ∣ a := (abs_dvd a a).mpr (dvd_refl a) @[simp] lemma dvd_abs (a b : α) : a ∣ |b| ↔ a ∣ b := by { cases abs_choice b with h h; simp only [h, dvd_neg] } lemma self_dvd_abs (a : α) : a ∣ |a| := (dvd_abs a a).mpr (dvd_refl a) lemma abs_dvd_abs (a b : α) : |a| ∣ |b| ↔ a ∣ b := (abs_dvd _ _).trans (dvd_abs _ _) end
764a9e8a49909fcd54445c6692702ad5be59e471
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/typeOf.lean
20f9f672a69ec31a13fb3cf8c70984855ebcdee3
[ "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
626
lean
-- def f1 (x : Nat) (b : Bool) : type_of% x := let r : type_of% (x+1) := x+1; r + 1 theorem ex1 : f1 1 true = 3 := rfl def f2 (x : Nat) (b : Bool) : type_of% x := let r : type_of% b := x+1; -- error r + 1 def f3 (x : Nat) (b : Bool) : type_of% b := let r (x!1 : type_of% x) : type_of% b := x > 1; r x def f4 (x : Nat) : Nat := let y : Nat := x let y := ensure_type_of% y "invalid reassignment, term" y == 1 -- error y + 1 def f5 (x : Nat) : Nat := let y : Nat := x let y := ensure_type_of% y "invalid reassignment, term" (y+1) y + 1 def f6 (x : Nat) : Nat := ensure_expected_type% "natural number expected, value" true
8e640ac7f25d11dcbc2ef6c2b8324866a3d1ee1b
6094e25ea0b7699e642463b48e51b2ead6ddc23f
/tests/lean/run/new_obtain3.lean
0bcae0cd7684af7c3f493303bcf93f090f65d2df
[ "Apache-2.0" ]
permissive
gbaz/lean
a7835c4e3006fbbb079e8f8ffe18aacc45adebfb
a501c308be3acaa50a2c0610ce2e0d71becf8032
refs/heads/master
1,611,198,791,433
1,451,339,111,000
1,451,339,111,000
48,713,797
0
0
null
1,451,338,939,000
1,451,338,939,000
null
UTF-8
Lean
false
false
604
lean
import data.set open set function eq.ops variables {X Y Z : Type} lemma image_compose (f : Y → X) (g : X → Y) (a : set X) : (f ∘ g) '[a] = f '[g '[a]] := ext (take z, iff.intro (assume Hz : z ∈ (f ∘ g) '[a], obtain x (Hx₁ : x ∈ a) (Hx₂ : f (g x) = z), from Hz, have Hgx : g x ∈ g '[a], from mem_image Hx₁ rfl, show z ∈ f '[g '[a]], from mem_image Hgx Hx₂) (assume Hz : z ∈ f '[g '[a]], obtain y [x (Hz₁ : x ∈ a) (Hz₂ : g x = y)] (Hy₂ : f y = z), from Hz, show z ∈ (f ∘ g) '[a], from mem_image Hz₁ (Hz₂⁻¹ ▸ Hy₂)))
5b97dc24b48285728601f31ec9d6c39c5a337cf0
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/group_theory/group_action/conj_act.lean
a6fedd77833b8f934b0da01182ebc1a88429aa28
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
6,183
lean
/- Copyright (c) 2021 . All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import group_theory.group_action.basic import group_theory.subgroup.basic /-! # Conjugation action of a group on itself This file defines the conjugation action of a group on itself. See also `mul_aut.conj` for the definition of conjugation as a homomorphism into the automorphism group. ## Main definitions A type alias `conj_act G` is introduced for a group `G`. The group `conj_act G` acts on `G` by conjugation. The group `conj_act G` also acts on any normal subgroup of `G` by conjugation. ## Implementation Notes The scalar action in defined in this file can also be written using `mul_aut.conj g • h`. This has the advantage of not using the type alias `conj_act`, but the downside of this approach is that some theorems about the group actions will not apply when since this `mul_aut.conj g • h` describes an action of `mul_aut G` on `G`, and not an action of `G`. -/ variables (G : Type*) /-- A type alias for a group `G`. `conj_act G` acts on `G` by conjugation -/ def conj_act : Type* := G namespace conj_act open mul_action subgroup variable {G} instance : Π [group G], group (conj_act G) := id instance : Π [div_inv_monoid G], div_inv_monoid (conj_act G) := id instance : Π [group_with_zero G], group_with_zero (conj_act G) := id instance : Π [fintype G], fintype (conj_act G) := id @[simp] lemma card [fintype G] : fintype.card (conj_act G) = fintype.card G := rfl section div_inv_monoid variable [div_inv_monoid G] instance : inhabited (conj_act G) := ⟨1⟩ /-- Reinterpret `g : conj_act G` as an element of `G`. -/ def of_conj_act : conj_act G ≃* G := ⟨id, id, λ _, rfl, λ _, rfl, λ _ _, rfl⟩ /-- Reinterpret `g : G` as an element of `conj_act G`. -/ def to_conj_act : G ≃* conj_act G := of_conj_act.symm /-- A recursor for `conj_act`, for use as `induction x using conj_act.rec` when `x : conj_act G`. -/ protected def rec {C : conj_act G → Sort*} (h : Π g, C (to_conj_act g)) : Π g, C g := h @[simp] lemma of_mul_symm_eq : (@of_conj_act G _).symm = to_conj_act := rfl @[simp] lemma to_mul_symm_eq : (@to_conj_act G _).symm = of_conj_act := rfl @[simp] lemma to_conj_act_of_conj_act (x : conj_act G) : to_conj_act (of_conj_act x) = x := rfl @[simp] lemma of_conj_act_to_conj_act (x : G) : of_conj_act (to_conj_act x) = x := rfl @[simp] lemma of_conj_act_one : of_conj_act (1 : conj_act G) = 1 := rfl @[simp] lemma to_conj_act_one : to_conj_act (1 : G) = 1 := rfl @[simp] lemma of_conj_act_inv (x : conj_act G) : of_conj_act (x⁻¹) = (of_conj_act x)⁻¹ := rfl @[simp] lemma to_conj_act_inv (x : G) : to_conj_act (x⁻¹) = (to_conj_act x)⁻¹ := rfl @[simp] lemma of_conj_act_mul (x y : conj_act G) : of_conj_act (x * y) = of_conj_act x * of_conj_act y := rfl @[simp] lemma to_conj_act_mul (x y : G) : to_conj_act (x * y) = to_conj_act x * to_conj_act y := rfl instance : has_scalar (conj_act G) G := { smul := λ g h, of_conj_act g * h * (of_conj_act g)⁻¹ } lemma smul_def (g : conj_act G) (h : G) : g • h = of_conj_act g * h * (of_conj_act g)⁻¹ := rfl @[simp] lemma «forall» (p : conj_act G → Prop) : (∀ (x : conj_act G), p x) ↔ ∀ x : G, p (to_conj_act x) := iff.rfl end div_inv_monoid section group_with_zero variable [group_with_zero G] @[simp] lemma of_conj_act_zero : of_conj_act (0 : conj_act G) = 0 := rfl @[simp] lemma to_conj_act_zero : to_conj_act (0 : G) = 0 := rfl instance : mul_action (conj_act G) G := { smul := (•), one_smul := by simp [smul_def], mul_smul := by simp [smul_def, mul_assoc, mul_inv_rev₀] } end group_with_zero variables [group G] instance : mul_distrib_mul_action (conj_act G) G := { smul := (•), smul_mul := by simp [smul_def, mul_assoc], smul_one := by simp [smul_def], one_smul := by simp [smul_def], mul_smul := by simp [smul_def, mul_assoc] } lemma smul_eq_mul_aut_conj (g : conj_act G) (h : G) : g • h = mul_aut.conj (of_conj_act g) h := rfl /-- The set of fixed points of the conjugation action of `G` on itself is the center of `G`. -/ lemma fixed_points_eq_center : fixed_points (conj_act G) G = center G := begin ext x, simp [mem_center_iff, smul_def, mul_inv_eq_iff_eq_mul] end /-- As normal subgroups are closed under conjugation, they inherit the conjugation action of the underlying group. -/ instance subgroup.conj_action {H : subgroup G} [hH : H.normal] : has_scalar (conj_act G) H := ⟨λ g h, ⟨g • h, hH.conj_mem h.1 h.2 (of_conj_act g)⟩⟩ lemma subgroup.coe_conj_smul {H : subgroup G} [hH : H.normal] (g : conj_act G) (h : H) : ↑(g • h) = g • (h : G) := rfl instance subgroup.conj_mul_distrib_mul_action {H : subgroup G} [hH : H.normal] : mul_distrib_mul_action (conj_act G) H := (subtype.coe_injective).mul_distrib_mul_action H.subtype subgroup.coe_conj_smul /-- Group conjugation on a normal subgroup. Analogous to `mul_aut.conj`. -/ def _root_.mul_aut.conj_normal {H : subgroup G} [hH : H.normal] : G →* mul_aut H := (mul_distrib_mul_action.to_mul_aut (conj_act G) H).comp to_conj_act.to_monoid_hom @[simp] lemma _root_.mul_aut.conj_normal_apply {H : subgroup G} [H.normal] (g : G) (h : H) : ↑(mul_aut.conj_normal g h) = g * h * g⁻¹ := rfl @[simp] lemma _root_.mul_aut.conj_normal_symm_apply {H : subgroup G} [H.normal] (g : G) (h : H) : ↑((mul_aut.conj_normal g).symm h) = g⁻¹ * h * g := by { change _ * (_)⁻¹⁻¹ = _, rw inv_inv, refl } @[simp] lemma _root_.mul_aut.conj_normal_inv_apply {H : subgroup G} [H.normal] (g : G) (h : H) : ↑((mul_aut.conj_normal g)⁻¹ h) = g⁻¹ * h * g := mul_aut.conj_normal_symm_apply g h lemma _root_.mul_aut.conj_normal_coe {H : subgroup G} [H.normal] {h : H} : mul_aut.conj_normal ↑h = mul_aut.conj h := mul_equiv.ext (λ x, rfl) instance normal_of_characteristic_of_normal {H : subgroup G} [hH : H.normal] {K : subgroup H} [h : K.characteristic] : (K.map H.subtype).normal := ⟨λ a ha b, by { obtain ⟨a, ha, rfl⟩ := ha, exact K.apply_coe_mem_map H.subtype ⟨_, ((set_like.ext_iff.mp (h.fixed (mul_aut.conj_normal b)) a).mpr ha)⟩ }⟩ end conj_act
63ff1eac1122771c0f0a47e3c9669bddc71acc32
122543640bfbfedbcee1318bfdbd466ead2716a7
/src/p2.lean
acea66a207a7bc2fb6e21da93b08ab89e546d83c
[]
no_license
jsm28/bmo2-2020-lean
f038489093312c97b9cae3cdb9410b2683ccb11f
ff87ce51ed080d462e63c5549d5f2b377ad83204
refs/heads/master
1,692,783,059,184
1,689,807,657,000
1,689,807,657,000
239,362,030
9
0
null
null
null
null
UTF-8
Lean
false
false
19,156
lean
-- BMO2 2020 problem 2. -- Choices made for formalization: the original problem refers to -- "collections", which we take as meaning sets. import geometry.euclidean.monge_point noncomputable theory open_locale classical open affine affine_subspace finite_dimensional euclidean_geometry variables {V : Type*} {P : Type*} [normed_add_comm_group V] [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] -- Properties of sets of points in the problem. def at_least_four_points (s : set P) : Prop := 4 ≤ cardinal.mk s include V def no_three_points_collinear (s : set P) : Prop := ∀ p : fin 3 → P, function.injective p → set.range p ⊆ s → ¬ collinear ℝ (set.range p) lemma no_three_points_collinear_iff (s : set P) : no_three_points_collinear s ↔ ∀ p : fin 3 → P, function.injective p → set.range p ⊆ s → affine_independent ℝ p := begin simp_rw affine_independent_iff_not_collinear, refl end def same_circumradius (s : set P) : Prop := ∃ r : ℝ, ∀ t : triangle ℝ P, set.range t.points ⊆ s → t.circumradius = r -- The description given in the problem. def p2_problem_desc (s : set P) : Prop := at_least_four_points s ∧ no_three_points_collinear s ∧ same_circumradius s -- The description given as an answer to the problem. def p2_answer_desc (s : set P) : Prop := at_least_four_points s ∧ (cospherical s ∨ orthocentric_system s) -- Given three points in a set with no three collinear, pairwise -- unequal, they are affinely independent. theorem p2_affine_independent_of_ne {s : set P} (hn3 : no_three_points_collinear s) {p1 p2 p3 : P} (h1 : p1 ∈ s) (h2 : p2 ∈ s) (h3 : p3 ∈ s) (h12 : p1 ≠ p2) (h13 : p1 ≠ p3) (h23 : p2 ≠ p3) : affine_independent ℝ ![p1, p2, p3] := begin rw no_three_points_collinear_iff at hn3, have hi : function.injective ![p1, p2, p3], { intros i1 i2 hi12, fin_cases i1; fin_cases i2; simpa [h12, h13, h23, h12.symm, h13.symm, h23.symm] using hi12 }, have hps : set.range ![p1, p2, p3] ⊆ s, { rw set.range_subset_iff, intro i, fin_cases i; simp [h1, h2, h3] }, exact hn3 _ hi hps end -- Given three points in a set with no three collinear, pairwise -- unequal, the triangle with those as vertices. def p2_triangle_of_ne {s : set P} (hn3 : no_three_points_collinear s) {p1 p2 p3 : P} (h1 : p1 ∈ s) (h2 : p2 ∈ s) (h3 : p3 ∈ s) (h12 : p1 ≠ p2) (h13 : p1 ≠ p3) (h23 : p2 ≠ p3) : triangle ℝ P := ⟨![p1, p2, p3], p2_affine_independent_of_ne hn3 h1 h2 h3 h12 h13 h23⟩ -- Given three points in a set with no three collinear, pairwise -- unequal, the triangle with those as vertices has vertices in the -- set. lemma p2_triangle_of_ne_range_subset {s : set P} (hn3 : no_three_points_collinear s) {p1 p2 p3 : P} (h1 : p1 ∈ s) (h2 : p2 ∈ s) (h3 : p3 ∈ s) (h12 : p1 ≠ p2) (h13 : p1 ≠ p3) (h23 : p2 ≠ p3) : set.range (p2_triangle_of_ne hn3 h1 h2 h3 h12 h13 h23).points ⊆ s := begin rw set.range_subset_iff, intro i, fin_cases i; simp [p2_triangle_of_ne, h1, h2, h3] end -- Any set with at least four points, no three collinear, contains a -- triangle. theorem p2_contains_triangle {s : set P} (h4 : at_least_four_points s) (hn3 : no_three_points_collinear s) : ∃ t : triangle ℝ P, set.range t.points ⊆ s := begin unfold at_least_four_points at h4, rw cardinal.le_mk_iff_exists_subset at h4, rcases h4 with ⟨s', hs', h4⟩, have hf : s'.finite, { refine cardinal.lt_aleph_0_iff_set_finite.1 _, rw h4, simp }, haveI : fintype s' := hf.fintype, rw [cardinal.mk_fintype, ←finset.card_univ] at h4, norm_cast at h4, obtain ⟨p1', hp1'⟩ : (finset.univ : finset s').nonempty, { simp [←finset.card_pos, h4] }, let s3 : finset s' := finset.univ.erase p1', obtain ⟨p2', hp2'⟩ : s3.nonempty, { simp [←finset.card_pos, h4, finset.card_erase_of_mem] }, have h12 : p1' ≠ p2' := (finset.ne_of_mem_erase hp2').symm, let s2 : finset s' := s3.erase p2', obtain ⟨p3', hp3'⟩ : s2.nonempty, { simp [←finset.card_pos, h4, finset.card_erase_of_mem, hp2'] }, have h23 : p2' ≠ p3' := (finset.ne_of_mem_erase hp3').symm, have h13 : p1' ≠ p3' := (finset.ne_of_mem_erase (finset.mem_of_mem_erase hp3')).symm, cases p1' with p1 hp1s', cases p2' with p2 hp2s', cases p3' with p3 hp3s', rw [ne.def, subtype.ext_iff, subtype.coe_mk, subtype.coe_mk, ←ne.def] at h12, rw [ne.def, subtype.ext_iff, subtype.coe_mk, subtype.coe_mk, ←ne.def] at h23, rw [ne.def, subtype.ext_iff, subtype.coe_mk, subtype.coe_mk, ←ne.def] at h13, let t := p2_triangle_of_ne hn3 (hs' hp1s') (hs' hp2s') (hs' hp3s') h12 h13 h23, use [t, p2_triangle_of_ne_range_subset hn3 (hs' hp1s') (hs' hp2s') (hs' hp3s') h12 h13 h23] end variables [finite_dimensional ℝ V] -- Given a triangle in a set with the properties of the problem, any -- point in that set that is not on the circumcircle of the triangle -- must have distance to the reflection of the circumcentre in a side -- equal to the circumradius. theorem p2_dist_reflection_circumcentre {s : set P} (hd2 : finrank ℝ V = 2) (hn3 : no_three_points_collinear s) {t0 : triangle ℝ P} {p : P} (ht0s : set.range t0.points ⊆ s) (hr : ∀ (t : triangle ℝ P), set.range t.points ⊆ s → t.circumradius = t0.circumradius) (hp : p ∈ s) (hpn : dist p t0.circumcenter ≠ t0.circumradius) {i1 i2 : fin 3} (hi12 : i1 ≠ i2) : dist p (reflection (affine_span ℝ (t0.points '' ↑({i1, i2} : finset (fin 3)))) t0.circumcenter) = t0.circumradius := begin -- Let i3 be the index of the third vertex of t0. obtain ⟨i3, h13, h23, heq⟩ : ∃ i3, i1 ≠ i3 ∧ i2 ≠ i3 ∧ ∀ i, i ∈ ({i3, i1, i2} : finset (fin 3)), { dec_trivial! }, rw ←finset.eq_univ_iff_forall at heq, -- Construct the triangle t1 whose vertices are vertices i1 and i2 -- of t0, together with p. have h0s : ∀ i : fin 3, t0.points i ∈ s, { rwa set.range_subset_iff at ht0s }, have h12 := t0.independent.injective.ne hi12, have hnp : ∀ i : fin 3, t0.points i ≠ p, { intros i he, rw ←he at hpn, exact hpn (t0.dist_circumcenter_eq_circumradius _) }, let t1 := p2_triangle_of_ne hn3 (h0s i1) (h0s i2) hp h12 (hnp i1) (hnp i2), -- t1 has the same circumradius as t0, but different circumcenter. have ht1cr := hr t1 (p2_triangle_of_ne_range_subset hn3 (h0s i1) (h0s i2) hp h12 (hnp i1) (hnp i2)), have ht1cc : t1.circumcenter ≠ t0.circumcenter, { intro h, have hpc : dist p t1.circumcenter = t1.circumradius := t1.dist_circumcenter_eq_circumradius 2, rw [h, ht1cr] at hpc, exact hpn hpc }, -- Consider the side with vertices i1 and i2 as a 1-simplex. let t12 : simplex ℝ P 1 := ⟨![t0.points i1, t0.points i2], affine_independent_of_ne ℝ h12⟩, -- Vertex i3 together with those of t12 spans the whole space. have hu2f : (finset.univ : finset (fin 2)) = {0, 1}, { dec_trivial }, have hu2 : (set.univ : set (fin 2)) = {0, 1}, { rw [←finset.coe_univ, hu2f], simp }, have hu3 : (set.univ : set (fin 3)) = {i3, i1, i2}, { rw [←finset.coe_univ, ←heq], simp }, have h123 : affine_span ℝ (insert (t0.points i3) (set.range t12.points)) = ⊤, { have ht0span : affine_span ℝ (set.range t0.points) = ⊤, { refine t0.independent.affine_span_eq_top_iff_card_eq_finrank_add_one.mpr _, simp [hd2] }, rw ←ht0span, congr, rw [←set.image_univ, ←set.image_univ, hu2, hu3, set.image_insert_eq, set.image_singleton, set.image_insert_eq, set.image_insert_eq, set.image_singleton], refl }, -- So the circumcentres of t1 and t2 are in that span. have hc0s : t0.circumcenter ∈ affine_span ℝ (insert (t0.points i3) (set.range t12.points)), { rw h123, exact affine_subspace.mem_top _ _ _ }, have hc1s : t1.circumcenter ∈ affine_span ℝ (insert (t0.points i3) (set.range t12.points)), { rw h123, exact affine_subspace.mem_top _ _ _ }, -- All points of t12 have distance from the circumcentres of t0 and -- t1 equal to the circumradius of t1. have hr0 : ∀ i, dist (t12.points i) t0.circumcenter = t0.circumradius, { intro i, fin_cases i; simp [t12] }, have hr1 : ∀ i, dist (t12.points i) t1.circumcenter = t0.circumradius, { intro i, fin_cases i, { change dist (t1.points 0) _ = _, simp [←ht1cr] }, { change dist (t1.points 1) _ = _, simp [←ht1cr] } }, -- So the circumcentres are the same or reflections of each other. cases eq_or_eq_reflection_of_dist_eq hc1s hc0s hr1 hr0, { exact false.elim (ht1cc h) }, { have hr : affine_span ℝ (t0.points '' ↑({i1, i2} : finset (fin 3))) = affine_span ℝ (set.range t12.points), { rw [←set.image_univ, hu2], simp [t12, set.image_insert_eq] }, rw [eq_reflection_of_eq_subspace hr, ←h], change dist (t1.points 2) _ = _, simp [ht1cr] } end -- Given a triangle in a set with the properties of the problem, any -- point in that set that is not on the circumcircle of the triangle -- must be its orthocentre. theorem p2_eq_orthocentre {s : set P} (hd2 : finrank ℝ V = 2) (hn3 : no_three_points_collinear s) {t0 : triangle ℝ P} {p : P} (ht0s : set.range t0.points ⊆ s) (hr : ∀ (t : triangle ℝ P), set.range t.points ⊆ s → t.circumradius = t0.circumradius) (hp : p ∈ s) (hpn : dist p t0.circumcenter ≠ t0.circumradius) : p = t0.orthocenter := begin -- First find a vertex not equal to the orthocentre. obtain ⟨i1 : fin 3, hi1o⟩ := t0.independent.injective.exists_ne t0.orthocenter, obtain ⟨i2, i3, h12, h23, h13, hc12, hc13, h1213⟩ : ∃ i2 i3, i1 ≠ i2 ∧ i2 ≠ i3 ∧ i1 ≠ i3 ∧ finset.card ({i1, i2} : finset (fin 3)) = 2 ∧ finset.card ({i1, i3} : finset (fin 3)) = 2 ∧ ({i1, i2} : finset (fin 3)) ≠ {i1, i3}, { clear hi1o, dec_trivial! }, -- We have the distance of p from the reflection of the circumcentre -- in the relevant sides. have hp12 := p2_dist_reflection_circumcentre hd2 hn3 ht0s hr hp hpn h12, have hp13 := p2_dist_reflection_circumcentre hd2 hn3 ht0s hr hp hpn h13, -- Also the distance of vertex i1 from those reflections. have hi12 : dist (t0.points i1) (reflection (affine_span ℝ (t0.points '' ↑({i1, i2} : finset (fin 3)))) t0.circumcenter) = t0.circumradius, { rw dist_reflection_eq_of_mem _ (mem_affine_span ℝ (set.mem_image_of_mem _ (finset.mem_coe.2 (finset.mem_insert_self _ _)))), exact t0.dist_circumcenter_eq_circumradius i1 }, have hi13 : dist (t0.points i1) (reflection (affine_span ℝ (t0.points '' ↑({i1, i3} : finset (fin 3)))) t0.circumcenter) = t0.circumradius, { rw dist_reflection_eq_of_mem _ (mem_affine_span ℝ (set.mem_image_of_mem _ (finset.mem_coe.2 (finset.mem_insert_self _ _)))), exact t0.dist_circumcenter_eq_circumradius i1 }, -- Also the distance of the orthocentre from those reflection. have ho2 := affine.triangle.dist_orthocenter_reflection_circumcenter_finset t0 h12, have ho3 := affine.triangle.dist_orthocenter_reflection_circumcenter_finset t0 h13, -- The reflections of the circumcentre in the relevant sides are not -- the same point. have hrne : reflection (affine_span ℝ (t0.points '' ↑({i1, i2} : finset (fin 3)))) t0.circumcenter ≠ reflection (affine_span ℝ (t0.points '' ↑({i1, i3} : finset (fin 3)))) t0.circumcenter, { intro h, have hf12 : affine_span ℝ (t0.points '' ↑({i1, i2} : finset (fin 3))) = affine_span ℝ (set.range (t0.face hc12).points), { simp }, have hf13 : affine_span ℝ (t0.points '' ↑({i1, i3} : finset (fin 3))) = affine_span ℝ (set.range (t0.face hc13).points), { simp }, rw [eq_reflection_of_eq_subspace hf12, eq_reflection_of_eq_subspace hf13, reflection_eq_iff_orthogonal_projection_eq, ←affine.simplex.orthogonal_projection_span, ←affine.simplex.orthogonal_projection_span, t0.orthogonal_projection_circumcenter hc12, t0.orthogonal_projection_circumcenter hc13, (t0.face hc12).circumcenter_eq_centroid, (t0.face hc13).circumcenter_eq_centroid, t0.face_centroid_eq_iff] at h, exact h1213 h }, -- Thus p is either vertex i1 or the orthocentre. have hpeq := eq_of_dist_eq_of_dist_eq_of_finrank_eq_two hd2 hrne hi1o hi12 ho2 hp12 hi13 ho3 hp13, cases hpeq, { rw [hpeq, t0.dist_circumcenter_eq_circumradius] at hpn, exact false.elim (hpn rfl) }, { exact hpeq } end -- Given p on the circumcircle of t0, not a vertex, not the -- orthocentre, the orthocentre not on the circumcircle; derive a -- contradiction. theorem p2_orthocentre_extra {s : set P} (hd2 : finrank ℝ V = 2) (hn3 : no_three_points_collinear s) {t0 : triangle ℝ P} (ht0s : set.range t0.points ⊆ s) (hr : ∀ (t : triangle ℝ P), set.range t.points ⊆ s → t.circumradius = t0.circumradius) (hos : t0.orthocenter ∈ s) (hor : dist t0.orthocenter t0.circumcenter ≠ t0.circumradius) {p : P} (hp : p ∈ s) (hpno : p ≠ t0.orthocenter) (hpnt0 : p ∉ set.range t0.points) (hpr : dist p t0.circumcenter = t0.circumradius) : false := begin -- Consider a triangle t1 made of two of the vertices of t0 plus the -- orthocentre of t0. have h0s : ∀ (i : fin 3), t0.points i ∈ s, { rwa set.range_subset_iff at ht0s }, have h0no : ∀ (i : fin 3), t0.points i ≠ t0.orthocenter, { intros i h, rw ←h at hor, apply hor, simp }, have h0np : ∀ (i : fin 3), t0.points i ≠ p, { intros i h, apply hpnt0, rw set.mem_range, exact ⟨i, h⟩ }, have h01 : t0.points 0 ≠ t0.points 1, { intro h, have hi := t0.independent.injective h, exact fin.ne_of_vne dec_trivial hi }, let t1 : triangle ℝ P := p2_triangle_of_ne hn3 (h0s 0) (h0s 1) hos h01 (h0no 0) (h0no 1), have ht1s : set.range t1.points ⊆ s := p2_triangle_of_ne_range_subset hn3 (h0s 0) (h0s 1) hos h01 (h0no 0) (h0no 1), -- Then the two circumcircles meet only at the two shared vertices, -- so p1 does not lie on the circumcircle of t1, so must be its -- orthocentre, but that is the third vertex of t0. have hpt1 : dist p t1.circumcenter ≠ t1.circumradius, { intro heq, let t2 : triangle ℝ P := p2_triangle_of_ne hn3 (h0s 0) (h0s 1) hp h01 (h0np 0) (h0np 1), have ht2s : set.range t2.points ⊆ s := p2_triangle_of_ne_range_subset hn3 (h0s 0) (h0s 1) hp h01 (h0np 0) (h0np 1), have ht0span : affine_span ℝ (set.range t0.points) = ⊤, { refine t0.independent.affine_span_eq_top_iff_card_eq_finrank_add_one.mpr _, simp [hd2] }, have ht1span : affine_span ℝ (set.range t1.points) = ⊤, { refine t1.independent.affine_span_eq_top_iff_card_eq_finrank_add_one.mpr _, simp [hd2] }, have ht2span : affine_span ℝ (set.range t2.points) = ⊤, { refine t2.independent.affine_span_eq_top_iff_card_eq_finrank_add_one.mpr _, simp [hd2] }, have ht02cc : t0.circumcenter = t2.circumcenter, { have h : ∀ (i : fin 3), dist (t2.points i) t0.circumcenter = t0.circumradius, { intro i, fin_cases i; simp [t2, p2_triangle_of_ne, hpr] }, exact t2.eq_circumcenter_of_dist_eq (ht2span.symm ▸ mem_top ℝ V _) h }, have ht12cc : t1.circumcenter = t2.circumcenter, { have h : ∀ (i : fin 3), dist (t2.points i) t1.circumcenter = t1.circumradius, { intro i, fin_cases i, { change dist (t1.points 0) _ = _, simp }, { change dist (t1.points 1) _ = _, simp }, { simp [t2, p2_triangle_of_ne, heq] } }, exact t2.eq_circumcenter_of_dist_eq (ht2span.symm ▸ mem_top ℝ V _) h }, rw [ht02cc, ←ht12cc, ←hr t1 ht1s] at hor, change dist (t1.points 2) _ ≠ _ at hor, simpa using hor }, have hpt1o : p = t1.orthocenter, { refine p2_eq_orthocentre hd2 hn3 ht1s _ hp hpt1, intros t ht, rw [hr t ht, hr t1 ht1s] }, let s' := insert t0.orthocenter (set.range t0.points), have hs'o : orthocentric_system s', { refine ⟨t0, _, rfl⟩, intro h, rw set.mem_range at h, rcases h with ⟨i, hi⟩, exact h0no i hi }, have ht1s' : set.range t1.points ⊆ s', { rw set.range_subset_iff, intro i, fin_cases i; simp [t1, p2_triangle_of_ne] }, have hs' := hs'o.eq_insert_orthocenter ht1s', rw ←hpt1o at hs', have hps' : p ∈ insert t0.orthocenter (set.range t0.points), { change p ∈ s', rw hs', exact set.mem_insert _ _ }, simpa [hpno, h0np] using hps' end -- The main part of the solution: a set with the given property is as -- described. theorem p2_result_main {s : set P} (hd2 : finrank ℝ V = 2) (h4 : at_least_four_points s) (hn3 : no_three_points_collinear s) {r : ℝ} (hr : ∀ (t : triangle ℝ P), set.range t.points ⊆ s → simplex.circumradius t = r) : cospherical s ∨ orthocentric_system s := begin obtain ⟨t0, ht0s⟩ := p2_contains_triangle h4 hn3, -- TODO: consider subsequent rework using bundled circumcircles. by_cases hc : ∀ p ∈ s, dist p t0.circumcenter = t0.circumradius, { -- The easier case: all points lie on the circumcircle of t0. left, exact ⟨t0.circumcenter, t0.circumradius, hc⟩ }, { -- The harder case: some point does not lie on the circumcircle of -- t0. right, use t0, push_neg at hc, simp_rw ←hr t0 ht0s at hr, rcases hc with ⟨p, hps, hpr⟩, have hpo := p2_eq_orthocentre hd2 hn3 ht0s hr hps hpr, split, { rw ←hpo, rintros ⟨i, rfl⟩, apply hpr, simp }, { have hsub : insert t0.orthocenter (set.range t0.points) ⊆ s, { rw [←hpo, set.insert_subset], exact ⟨hps, ht0s⟩ }, refine set.subset.antisymm _ hsub, rw set.subset_def, rintros p1 hp1, rw set.mem_insert_iff, by_contradiction hp1c, push_neg at hp1c, rcases hp1c with ⟨hp1no, hp1nt0⟩, by_cases hp1r : dist p1 t0.circumcenter = t0.circumradius, { rw hpo at hpr hps, exact p2_orthocentre_extra hd2 hn3 ht0s hr hps hpr hp1 hp1no hp1nt0 hp1r }, { exact hp1no (p2_eq_orthocentre hd2 hn3 ht0s hr hp1 hp1r) } } } end -- The result of the problem. theorem p2_result (s : set P) (hd2 : finrank ℝ V = 2) : p2_problem_desc s ↔ p2_answer_desc s := begin unfold p2_problem_desc p2_answer_desc, rw and.congr_right_iff, intro h4, split, { -- The main part of the solution: a set with the given property is -- as described. rintro ⟨hn3, r, hr⟩, exact p2_result_main hd2 h4 hn3 hr }, { -- The easy part of the solution: a set as described satisfies the -- conditions of the problem. rintro (hc | ho), { split, { rw no_three_points_collinear_iff, exact λ p hpi hps, hc.affine_independent hps hpi }, { exact exists_circumradius_eq_of_cospherical hd2 hc } }, { split, { rw no_three_points_collinear_iff, exact λ p hpi hps, ho.affine_independent hps hpi }, { exact ho.exists_circumradius_eq } } } end
90de3c82e4b3590e2806660e52b136892f26848e
2eab05920d6eeb06665e1a6df77b3157354316ad
/src/computability/turing_machine.lean
405bd17944b8c9c11f06dc673b84db6bdb3f0159
[ "Apache-2.0" ]
permissive
ayush1801/mathlib
78949b9f789f488148142221606bf15c02b960d2
ce164e28f262acbb3de6281b3b03660a9f744e3c
refs/heads/master
1,692,886,907,941
1,635,270,866,000
1,635,270,866,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
109,959
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.fintype.basic import data.pfun import logic.function.iterate import order.basic import tactic.apply_fun /-! # Turing machines This file defines a sequence of simple machine languages, starting with Turing machines and working up to more complex languages based on Wang B-machines. ## Naming conventions Each model of computation in this file shares a naming convention for the elements of a model of computation. These are the parameters for the language: * `Γ` is the alphabet on the tape. * `Λ` is the set of labels, or internal machine states. * `σ` is the type of internal memory, not on the tape. This does not exist in the TM0 model, and later models achieve this by mixing it into `Λ`. * `K` is used in the TM2 model, which has multiple stacks, and denotes the number of such stacks. All of these variables denote "essentially finite" types, but for technical reasons it is convenient to allow them to be infinite anyway. When using an infinite type, we will be interested to prove that only finitely many values of the type are ever interacted with. Given these parameters, there are a few common structures for the model that arise: * `stmt` is the set of all actions that can be performed in one step. For the TM0 model this set is finite, and for later models it is an infinite inductive type representing "possible program texts". * `cfg` is the set of instantaneous configurations, that is, the state of the machine together with its environment. * `machine` is the set of all machines in the model. Usually this is approximately a function `Λ → stmt`, although different models have different ways of halting and other actions. * `step : cfg → option cfg` is the function that describes how the state evolves over one step. If `step c = none`, then `c` is a terminal state, and the result of the computation is read off from `c`. Because of the type of `step`, these models are all deterministic by construction. * `init : input → cfg` sets up the initial state. The type `input` depends on the model; in most cases it is `list Γ`. * `eval : machine → input → part output`, given a machine `M` and input `i`, starts from `init i`, runs `step` until it reaches an output, and then applies a function `cfg → output` to the final state to obtain the result. The type `output` depends on the model. * `supports : machine → finset Λ → Prop` asserts that a machine `M` starts in `S : finset Λ`, and can only ever jump to other states inside `S`. This implies that the behavior of `M` on any input cannot depend on its values outside `S`. We use this to allow `Λ` to be an infinite set when convenient, and prove that only finitely many of these states are actually accessible. This formalizes "essentially finite" mentioned above. -/ open relation open nat (iterate) open function (update iterate_succ iterate_succ_apply iterate_succ' iterate_succ_apply' iterate_zero_apply) namespace turing /-- The `blank_extends` partial order holds of `l₁` and `l₂` if `l₂` is obtained by adding blanks (`default Γ`) to the end of `l₁`. -/ def blank_extends {Γ} [inhabited Γ] (l₁ l₂ : list Γ) : Prop := ∃ n, l₂ = l₁ ++ list.repeat (default Γ) n @[refl] theorem blank_extends.refl {Γ} [inhabited Γ] (l : list Γ) : blank_extends l l := ⟨0, by simp⟩ @[trans] theorem blank_extends.trans {Γ} [inhabited Γ] {l₁ l₂ l₃ : list Γ} : blank_extends l₁ l₂ → blank_extends l₂ l₃ → blank_extends l₁ l₃ := by rintro ⟨i, rfl⟩ ⟨j, rfl⟩; exact ⟨i+j, by simp [list.repeat_add]⟩ theorem blank_extends.below_of_le {Γ} [inhabited Γ] {l l₁ l₂ : list Γ} : blank_extends l l₁ → blank_extends l l₂ → l₁.length ≤ l₂.length → blank_extends l₁ l₂ := begin rintro ⟨i, rfl⟩ ⟨j, rfl⟩ h, use j - i, simp only [list.length_append, add_le_add_iff_left, list.length_repeat] at h, simp only [← list.repeat_add, add_tsub_cancel_of_le h, list.append_assoc], end /-- Any two extensions by blank `l₁,l₂` of `l` have a common join (which can be taken to be the longer of `l₁` and `l₂`). -/ def blank_extends.above {Γ} [inhabited Γ] {l l₁ l₂ : list Γ} (h₁ : blank_extends l l₁) (h₂ : blank_extends l l₂) : {l' // blank_extends l₁ l' ∧ blank_extends l₂ l'} := if h : l₁.length ≤ l₂.length then ⟨l₂, h₁.below_of_le h₂ h, blank_extends.refl _⟩ else ⟨l₁, blank_extends.refl _, h₂.below_of_le h₁ (le_of_not_ge h)⟩ theorem blank_extends.above_of_le {Γ} [inhabited Γ] {l l₁ l₂ : list Γ} : blank_extends l₁ l → blank_extends l₂ l → l₁.length ≤ l₂.length → blank_extends l₁ l₂ := begin rintro ⟨i, rfl⟩ ⟨j, e⟩ h, use i - j, refine list.append_right_cancel (e.symm.trans _), rw [list.append_assoc, ← list.repeat_add, tsub_add_cancel_of_le], apply_fun list.length at e, simp only [list.length_append, list.length_repeat] at e, rwa [← add_le_add_iff_left, e, add_le_add_iff_right] end /-- `blank_rel` is the symmetric closure of `blank_extends`, turning it into an equivalence relation. Two lists are related by `blank_rel` if one extends the other by blanks. -/ def blank_rel {Γ} [inhabited Γ] (l₁ l₂ : list Γ) : Prop := blank_extends l₁ l₂ ∨ blank_extends l₂ l₁ @[refl] theorem blank_rel.refl {Γ} [inhabited Γ] (l : list Γ) : blank_rel l l := or.inl (blank_extends.refl _) @[symm] theorem blank_rel.symm {Γ} [inhabited Γ] {l₁ l₂ : list Γ} : blank_rel l₁ l₂ → blank_rel l₂ l₁ := or.symm @[trans] theorem blank_rel.trans {Γ} [inhabited Γ] {l₁ l₂ l₃ : list Γ} : blank_rel l₁ l₂ → blank_rel l₂ l₃ → blank_rel l₁ l₃ := begin rintro (h₁|h₁) (h₂|h₂), { exact or.inl (h₁.trans h₂) }, { cases le_total l₁.length l₃.length with h h, { exact or.inl (h₁.above_of_le h₂ h) }, { exact or.inr (h₂.above_of_le h₁ h) } }, { cases le_total l₁.length l₃.length with h h, { exact or.inl (h₁.below_of_le h₂ h) }, { exact or.inr (h₂.below_of_le h₁ h) } }, { exact or.inr (h₂.trans h₁) }, end /-- Given two `blank_rel` lists, there exists (constructively) a common join. -/ def blank_rel.above {Γ} [inhabited Γ] {l₁ l₂ : list Γ} (h : blank_rel l₁ l₂) : {l // blank_extends l₁ l ∧ blank_extends l₂ l} := begin refine if hl : l₁.length ≤ l₂.length then ⟨l₂, or.elim h id (λ h', _), blank_extends.refl _⟩ else ⟨l₁, blank_extends.refl _, or.elim h (λ h', _) id⟩, exact (blank_extends.refl _).above_of_le h' hl, exact (blank_extends.refl _).above_of_le h' (le_of_not_ge hl) end /-- Given two `blank_rel` lists, there exists (constructively) a common meet. -/ def blank_rel.below {Γ} [inhabited Γ] {l₁ l₂ : list Γ} (h : blank_rel l₁ l₂) : {l // blank_extends l l₁ ∧ blank_extends l l₂} := begin refine if hl : l₁.length ≤ l₂.length then ⟨l₁, blank_extends.refl _, or.elim h id (λ h', _)⟩ else ⟨l₂, or.elim h (λ h', _) id, blank_extends.refl _⟩, exact (blank_extends.refl _).above_of_le h' hl, exact (blank_extends.refl _).above_of_le h' (le_of_not_ge hl) end theorem blank_rel.equivalence (Γ) [inhabited Γ] : equivalence (@blank_rel Γ _) := ⟨blank_rel.refl, @blank_rel.symm _ _, @blank_rel.trans _ _⟩ /-- Construct a setoid instance for `blank_rel`. -/ def blank_rel.setoid (Γ) [inhabited Γ] : setoid (list Γ) := ⟨_, blank_rel.equivalence _⟩ /-- A `list_blank Γ` is a quotient of `list Γ` by extension by blanks at the end. This is used to represent half-tapes of a Turing machine, so that we can pretend that the list continues infinitely with blanks. -/ def list_blank (Γ) [inhabited Γ] := quotient (blank_rel.setoid Γ) instance list_blank.inhabited {Γ} [inhabited Γ] : inhabited (list_blank Γ) := ⟨quotient.mk' []⟩ instance list_blank.has_emptyc {Γ} [inhabited Γ] : has_emptyc (list_blank Γ) := ⟨quotient.mk' []⟩ /-- A modified version of `quotient.lift_on'` specialized for `list_blank`, with the stronger precondition `blank_extends` instead of `blank_rel`. -/ @[elab_as_eliminator, reducible] protected def list_blank.lift_on {Γ} [inhabited Γ] {α} (l : list_blank Γ) (f : list Γ → α) (H : ∀ a b, blank_extends a b → f a = f b) : α := l.lift_on' f $ by rintro a b (h|h); [exact H _ _ h, exact (H _ _ h).symm] /-- The quotient map turning a `list` into a `list_blank`. -/ def list_blank.mk {Γ} [inhabited Γ] : list Γ → list_blank Γ := quotient.mk' @[elab_as_eliminator] protected lemma list_blank.induction_on {Γ} [inhabited Γ] {p : list_blank Γ → Prop} (q : list_blank Γ) (h : ∀ a, p (list_blank.mk a)) : p q := quotient.induction_on' q h /-- The head of a `list_blank` is well defined. -/ def list_blank.head {Γ} [inhabited Γ] (l : list_blank Γ) : Γ := l.lift_on list.head begin rintro _ _ ⟨i, rfl⟩, cases a, {cases i; refl}, refl end @[simp] theorem list_blank.head_mk {Γ} [inhabited Γ] (l : list Γ) : list_blank.head (list_blank.mk l) = l.head := rfl /-- The tail of a `list_blank` is well defined (up to the tail of blanks). -/ def list_blank.tail {Γ} [inhabited Γ] (l : list_blank Γ) : list_blank Γ := l.lift_on (λ l, list_blank.mk l.tail) begin rintro _ _ ⟨i, rfl⟩, refine quotient.sound' (or.inl _), cases a; [{cases i; [exact ⟨0, rfl⟩, exact ⟨i, rfl⟩]}, exact ⟨i, rfl⟩] end @[simp] theorem list_blank.tail_mk {Γ} [inhabited Γ] (l : list Γ) : list_blank.tail (list_blank.mk l) = list_blank.mk l.tail := rfl /-- We can cons an element onto a `list_blank`. -/ def list_blank.cons {Γ} [inhabited Γ] (a : Γ) (l : list_blank Γ) : list_blank Γ := l.lift_on (λ l, list_blank.mk (list.cons a l)) begin rintro _ _ ⟨i, rfl⟩, exact quotient.sound' (or.inl ⟨i, rfl⟩), end @[simp] theorem list_blank.cons_mk {Γ} [inhabited Γ] (a : Γ) (l : list Γ) : list_blank.cons a (list_blank.mk l) = list_blank.mk (a :: l) := rfl @[simp] theorem list_blank.head_cons {Γ} [inhabited Γ] (a : Γ) : ∀ (l : list_blank Γ), (l.cons a).head = a := quotient.ind' $ by exact λ l, rfl @[simp] theorem list_blank.tail_cons {Γ} [inhabited Γ] (a : Γ) : ∀ (l : list_blank Γ), (l.cons a).tail = l := quotient.ind' $ by exact λ l, rfl /-- The `cons` and `head`/`tail` functions are mutually inverse, unlike in the case of `list` where this only holds for nonempty lists. -/ @[simp] theorem list_blank.cons_head_tail {Γ} [inhabited Γ] : ∀ (l : list_blank Γ), l.tail.cons l.head = l := quotient.ind' begin refine (λ l, quotient.sound' (or.inr _)), cases l, {exact ⟨1, rfl⟩}, {refl}, end /-- The `cons` and `head`/`tail` functions are mutually inverse, unlike in the case of `list` where this only holds for nonempty lists. -/ theorem list_blank.exists_cons {Γ} [inhabited Γ] (l : list_blank Γ) : ∃ a l', l = list_blank.cons a l' := ⟨_, _, (list_blank.cons_head_tail _).symm⟩ /-- The n-th element of a `list_blank` is well defined for all `n : ℕ`, unlike in a `list`. -/ def list_blank.nth {Γ} [inhabited Γ] (l : list_blank Γ) (n : ℕ) : Γ := l.lift_on (λ l, list.inth l n) begin rintro l _ ⟨i, rfl⟩, simp only [list.inth], cases lt_or_le _ _ with h h, {rw list.nth_append h}, rw list.nth_len_le h, cases le_or_lt _ _ with h₂ h₂, {rw list.nth_len_le h₂}, rw [list.nth_le_nth h₂, list.nth_le_append_right h, list.nth_le_repeat] end @[simp] theorem list_blank.nth_mk {Γ} [inhabited Γ] (l : list Γ) (n : ℕ) : (list_blank.mk l).nth n = l.inth n := rfl @[simp] theorem list_blank.nth_zero {Γ} [inhabited Γ] (l : list_blank Γ) : l.nth 0 = l.head := begin conv {to_lhs, rw [← list_blank.cons_head_tail l]}, exact quotient.induction_on' l.tail (λ l, rfl) end @[simp] theorem list_blank.nth_succ {Γ} [inhabited Γ] (l : list_blank Γ) (n : ℕ) : l.nth (n + 1) = l.tail.nth n := begin conv {to_lhs, rw [← list_blank.cons_head_tail l]}, exact quotient.induction_on' l.tail (λ l, rfl) end @[ext] theorem list_blank.ext {Γ} [inhabited Γ] {L₁ L₂ : list_blank Γ} : (∀ i, L₁.nth i = L₂.nth i) → L₁ = L₂ := list_blank.induction_on L₁ $ λ l₁, list_blank.induction_on L₂ $ λ l₂ H, begin wlog h : l₁.length ≤ l₂.length using l₁ l₂, swap, { exact (this $ λ i, (H i).symm).symm }, refine quotient.sound' (or.inl ⟨l₂.length - l₁.length, _⟩), refine list.ext_le _ (λ i h h₂, eq.symm _), { simp only [add_tsub_cancel_of_le h, list.length_append, list.length_repeat] }, simp at H, cases lt_or_le i l₁.length with h' h', { simpa only [list.nth_le_append _ h', list.nth_le_nth h, list.nth_le_nth h', option.iget] using H i }, { simpa only [list.nth_le_append_right h', list.nth_le_repeat, list.nth_le_nth h, list.nth_len_le h', option.iget] using H i }, end /-- Apply a function to a value stored at the nth position of the list. -/ @[simp] def list_blank.modify_nth {Γ} [inhabited Γ] (f : Γ → Γ) : ℕ → list_blank Γ → list_blank Γ | 0 L := L.tail.cons (f L.head) | (n+1) L := (L.tail.modify_nth n).cons L.head theorem list_blank.nth_modify_nth {Γ} [inhabited Γ] (f : Γ → Γ) (n i) (L : list_blank Γ) : (L.modify_nth f n).nth i = if i = n then f (L.nth i) else L.nth i := begin induction n with n IH generalizing i L, { cases i; simp only [list_blank.nth_zero, if_true, list_blank.head_cons, list_blank.modify_nth, eq_self_iff_true, list_blank.nth_succ, if_false, list_blank.tail_cons] }, { cases i, { rw if_neg (nat.succ_ne_zero _).symm, simp only [list_blank.nth_zero, list_blank.head_cons, list_blank.modify_nth] }, { simp only [IH, list_blank.modify_nth, list_blank.nth_succ, list_blank.tail_cons], congr } } end /-- A pointed map of `inhabited` types is a map that sends one default value to the other. -/ structure {u v} pointed_map (Γ : Type u) (Γ' : Type v) [inhabited Γ] [inhabited Γ'] : Type (max u v) := (f : Γ → Γ') (map_pt' : f (default _) = default _) instance {Γ Γ'} [inhabited Γ] [inhabited Γ'] : inhabited (pointed_map Γ Γ') := ⟨⟨λ _, default _, rfl⟩⟩ instance {Γ Γ'} [inhabited Γ] [inhabited Γ'] : has_coe_to_fun (pointed_map Γ Γ') (λ _, Γ → Γ') := ⟨pointed_map.f⟩ @[simp] theorem pointed_map.mk_val {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : Γ → Γ') (pt) : (pointed_map.mk f pt : Γ → Γ') = f := rfl @[simp] theorem pointed_map.map_pt {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') : f (default _) = default _ := pointed_map.map_pt' _ @[simp] theorem pointed_map.head_map {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (l : list Γ) : (l.map f).head = f l.head := by cases l; [exact (pointed_map.map_pt f).symm, refl] /-- The `map` function on lists is well defined on `list_blank`s provided that the map is pointed. -/ def list_blank.map {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (l : list_blank Γ) : list_blank Γ' := l.lift_on (λ l, list_blank.mk (list.map f l)) begin rintro l _ ⟨i, rfl⟩, refine quotient.sound' (or.inl ⟨i, _⟩), simp only [pointed_map.map_pt, list.map_append, list.map_repeat], end @[simp] theorem list_blank.map_mk {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (l : list Γ) : (list_blank.mk l).map f = list_blank.mk (l.map f) := rfl @[simp] theorem list_blank.head_map {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (l : list_blank Γ) : (l.map f).head = f l.head := begin conv {to_lhs, rw [← list_blank.cons_head_tail l]}, exact quotient.induction_on' l (λ a, rfl) end @[simp] theorem list_blank.tail_map {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (l : list_blank Γ) : (l.map f).tail = l.tail.map f := begin conv {to_lhs, rw [← list_blank.cons_head_tail l]}, exact quotient.induction_on' l (λ a, rfl) end @[simp] theorem list_blank.map_cons {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (l : list_blank Γ) (a : Γ) : (l.cons a).map f = (l.map f).cons (f a) := begin refine (list_blank.cons_head_tail _).symm.trans _, simp only [list_blank.head_map, list_blank.head_cons, list_blank.tail_map, list_blank.tail_cons] end @[simp] theorem list_blank.nth_map {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (l : list_blank Γ) (n : ℕ) : (l.map f).nth n = f (l.nth n) := l.induction_on begin intro l, simp only [list.nth_map, list_blank.map_mk, list_blank.nth_mk, list.inth], cases l.nth n, {exact f.2.symm}, {refl} end /-- The `i`-th projection as a pointed map. -/ def proj {ι : Type*} {Γ : ι → Type*} [∀ i, inhabited (Γ i)] (i : ι) : pointed_map (∀ i, Γ i) (Γ i) := ⟨λ a, a i, rfl⟩ theorem proj_map_nth {ι : Type*} {Γ : ι → Type*} [∀ i, inhabited (Γ i)] (i : ι) (L n) : (list_blank.map (@proj ι Γ _ i) L).nth n = L.nth n i := by rw list_blank.nth_map; refl theorem list_blank.map_modify_nth {Γ Γ'} [inhabited Γ] [inhabited Γ'] (F : pointed_map Γ Γ') (f : Γ → Γ) (f' : Γ' → Γ') (H : ∀ x, F (f x) = f' (F x)) (n) (L : list_blank Γ) : (L.modify_nth f n).map F = (L.map F).modify_nth f' n := by induction n with n IH generalizing L; simp only [*, list_blank.head_map, list_blank.modify_nth, list_blank.map_cons, list_blank.tail_map] /-- Append a list on the left side of a list_blank. -/ @[simp] def list_blank.append {Γ} [inhabited Γ] : list Γ → list_blank Γ → list_blank Γ | [] L := L | (a :: l) L := list_blank.cons a (list_blank.append l L) @[simp] theorem list_blank.append_mk {Γ} [inhabited Γ] (l₁ l₂ : list Γ) : list_blank.append l₁ (list_blank.mk l₂) = list_blank.mk (l₁ ++ l₂) := by induction l₁; simp only [*, list_blank.append, list.nil_append, list.cons_append, list_blank.cons_mk] theorem list_blank.append_assoc {Γ} [inhabited Γ] (l₁ l₂ : list Γ) (l₃ : list_blank Γ) : list_blank.append (l₁ ++ l₂) l₃ = list_blank.append l₁ (list_blank.append l₂ l₃) := l₃.induction_on $ by intro; simp only [list_blank.append_mk, list.append_assoc] /-- The `bind` function on lists is well defined on `list_blank`s provided that the default element is sent to a sequence of default elements. -/ def list_blank.bind {Γ Γ'} [inhabited Γ] [inhabited Γ'] (l : list_blank Γ) (f : Γ → list Γ') (hf : ∃ n, f (default _) = list.repeat (default _) n) : list_blank Γ' := l.lift_on (λ l, list_blank.mk (list.bind l f)) begin rintro l _ ⟨i, rfl⟩, cases hf with n e, refine quotient.sound' (or.inl ⟨i * n, _⟩), rw [list.bind_append, mul_comm], congr, induction i with i IH, refl, simp only [IH, e, list.repeat_add, nat.mul_succ, add_comm, list.repeat_succ, list.cons_bind], end @[simp] lemma list_blank.bind_mk {Γ Γ'} [inhabited Γ] [inhabited Γ'] (l : list Γ) (f : Γ → list Γ') (hf) : (list_blank.mk l).bind f hf = list_blank.mk (l.bind f) := rfl @[simp] lemma list_blank.cons_bind {Γ Γ'} [inhabited Γ] [inhabited Γ'] (a : Γ) (l : list_blank Γ) (f : Γ → list Γ') (hf) : (l.cons a).bind f hf = (l.bind f hf).append (f a) := l.induction_on $ by intro; simp only [list_blank.append_mk, list_blank.bind_mk, list_blank.cons_mk, list.cons_bind] /-- The tape of a Turing machine is composed of a head element (which we imagine to be the current position of the head), together with two `list_blank`s denoting the portions of the tape going off to the left and right. When the Turing machine moves right, an element is pulled from the right side and becomes the new head, while the head element is consed onto the left side. -/ structure tape (Γ : Type*) [inhabited Γ] := (head : Γ) (left : list_blank Γ) (right : list_blank Γ) instance tape.inhabited {Γ} [inhabited Γ] : inhabited (tape Γ) := ⟨by constructor; apply default⟩ /-- A direction for the turing machine `move` command, either left or right. -/ @[derive decidable_eq, derive inhabited] inductive dir | left | right /-- The "inclusive" left side of the tape, including both `left` and `head`. -/ def tape.left₀ {Γ} [inhabited Γ] (T : tape Γ) : list_blank Γ := T.left.cons T.head /-- The "inclusive" right side of the tape, including both `right` and `head`. -/ def tape.right₀ {Γ} [inhabited Γ] (T : tape Γ) : list_blank Γ := T.right.cons T.head /-- Move the tape in response to a motion of the Turing machine. Note that `T.move dir.left` makes `T.left` smaller; the Turing machine is moving left and the tape is moving right. -/ def tape.move {Γ} [inhabited Γ] : dir → tape Γ → tape Γ | dir.left ⟨a, L, R⟩ := ⟨L.head, L.tail, R.cons a⟩ | dir.right ⟨a, L, R⟩ := ⟨R.head, L.cons a, R.tail⟩ @[simp] theorem tape.move_left_right {Γ} [inhabited Γ] (T : tape Γ) : (T.move dir.left).move dir.right = T := by cases T; simp [tape.move] @[simp] theorem tape.move_right_left {Γ} [inhabited Γ] (T : tape Γ) : (T.move dir.right).move dir.left = T := by cases T; simp [tape.move] /-- Construct a tape from a left side and an inclusive right side. -/ def tape.mk' {Γ} [inhabited Γ] (L R : list_blank Γ) : tape Γ := ⟨R.head, L, R.tail⟩ @[simp] theorem tape.mk'_left {Γ} [inhabited Γ] (L R : list_blank Γ) : (tape.mk' L R).left = L := rfl @[simp] theorem tape.mk'_head {Γ} [inhabited Γ] (L R : list_blank Γ) : (tape.mk' L R).head = R.head := rfl @[simp] theorem tape.mk'_right {Γ} [inhabited Γ] (L R : list_blank Γ) : (tape.mk' L R).right = R.tail := rfl @[simp] theorem tape.mk'_right₀ {Γ} [inhabited Γ] (L R : list_blank Γ) : (tape.mk' L R).right₀ = R := list_blank.cons_head_tail _ @[simp] theorem tape.mk'_left_right₀ {Γ} [inhabited Γ] (T : tape Γ) : tape.mk' T.left T.right₀ = T := by cases T; simp only [tape.right₀, tape.mk', list_blank.head_cons, list_blank.tail_cons, eq_self_iff_true, and_self] theorem tape.exists_mk' {Γ} [inhabited Γ] (T : tape Γ) : ∃ L R, T = tape.mk' L R := ⟨_, _, (tape.mk'_left_right₀ _).symm⟩ @[simp] theorem tape.move_left_mk' {Γ} [inhabited Γ] (L R : list_blank Γ) : (tape.mk' L R).move dir.left = tape.mk' L.tail (R.cons L.head) := by simp only [tape.move, tape.mk', list_blank.head_cons, eq_self_iff_true, list_blank.cons_head_tail, and_self, list_blank.tail_cons] @[simp] theorem tape.move_right_mk' {Γ} [inhabited Γ] (L R : list_blank Γ) : (tape.mk' L R).move dir.right = tape.mk' (L.cons R.head) R.tail := by simp only [tape.move, tape.mk', list_blank.head_cons, eq_self_iff_true, list_blank.cons_head_tail, and_self, list_blank.tail_cons] /-- Construct a tape from a left side and an inclusive right side. -/ def tape.mk₂ {Γ} [inhabited Γ] (L R : list Γ) : tape Γ := tape.mk' (list_blank.mk L) (list_blank.mk R) /-- Construct a tape from a list, with the head of the list at the TM head and the rest going to the right. -/ def tape.mk₁ {Γ} [inhabited Γ] (l : list Γ) : tape Γ := tape.mk₂ [] l /-- The `nth` function of a tape is integer-valued, with index `0` being the head, negative indexes on the left and positive indexes on the right. (Picture a number line.) -/ def tape.nth {Γ} [inhabited Γ] (T : tape Γ) : ℤ → Γ | 0 := T.head | (n+1:ℕ) := T.right.nth n | -[1+ n] := T.left.nth n @[simp] theorem tape.nth_zero {Γ} [inhabited Γ] (T : tape Γ) : T.nth 0 = T.1 := rfl theorem tape.right₀_nth {Γ} [inhabited Γ] (T : tape Γ) (n : ℕ) : T.right₀.nth n = T.nth n := by cases n; simp only [tape.nth, tape.right₀, int.coe_nat_zero, list_blank.nth_zero, list_blank.nth_succ, list_blank.head_cons, list_blank.tail_cons] @[simp] theorem tape.mk'_nth_nat {Γ} [inhabited Γ] (L R : list_blank Γ) (n : ℕ) : (tape.mk' L R).nth n = R.nth n := by rw [← tape.right₀_nth, tape.mk'_right₀] @[simp] theorem tape.move_left_nth {Γ} [inhabited Γ] : ∀ (T : tape Γ) (i : ℤ), (T.move dir.left).nth i = T.nth (i-1) | ⟨a, L, R⟩ -[1+ n] := (list_blank.nth_succ _ _).symm | ⟨a, L, R⟩ 0 := (list_blank.nth_zero _).symm | ⟨a, L, R⟩ 1 := (list_blank.nth_zero _).trans (list_blank.head_cons _ _) | ⟨a, L, R⟩ ((n+1:ℕ)+1) := begin rw add_sub_cancel, change (R.cons a).nth (n+1) = R.nth n, rw [list_blank.nth_succ, list_blank.tail_cons] end @[simp] theorem tape.move_right_nth {Γ} [inhabited Γ] (T : tape Γ) (i : ℤ) : (T.move dir.right).nth i = T.nth (i+1) := by conv {to_rhs, rw ← T.move_right_left}; rw [tape.move_left_nth, add_sub_cancel] @[simp] theorem tape.move_right_n_head {Γ} [inhabited Γ] (T : tape Γ) (i : ℕ) : ((tape.move dir.right)^[i] T).head = T.nth i := by induction i generalizing T; [refl, simp only [*, tape.move_right_nth, int.coe_nat_succ, iterate_succ]] /-- Replace the current value of the head on the tape. -/ def tape.write {Γ} [inhabited Γ] (b : Γ) (T : tape Γ) : tape Γ := {head := b, ..T} @[simp] theorem tape.write_self {Γ} [inhabited Γ] : ∀ (T : tape Γ), T.write T.1 = T := by rintro ⟨⟩; refl @[simp] theorem tape.write_nth {Γ} [inhabited Γ] (b : Γ) : ∀ (T : tape Γ) {i : ℤ}, (T.write b).nth i = if i = 0 then b else T.nth i | ⟨a, L, R⟩ 0 := rfl | ⟨a, L, R⟩ (n+1:ℕ) := rfl | ⟨a, L, R⟩ -[1+ n] := rfl @[simp] theorem tape.write_mk' {Γ} [inhabited Γ] (a b : Γ) (L R : list_blank Γ) : (tape.mk' L (R.cons a)).write b = tape.mk' L (R.cons b) := by simp only [tape.write, tape.mk', list_blank.head_cons, list_blank.tail_cons, eq_self_iff_true, and_self] /-- Apply a pointed map to a tape to change the alphabet. -/ def tape.map {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (T : tape Γ) : tape Γ' := ⟨f T.1, T.2.map f, T.3.map f⟩ @[simp] theorem tape.map_fst {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') : ∀ (T : tape Γ), (T.map f).1 = f T.1 := by rintro ⟨⟩; refl @[simp] theorem tape.map_write {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (b : Γ) : ∀ (T : tape Γ), (T.write b).map f = (T.map f).write (f b) := by rintro ⟨⟩; refl @[simp] theorem tape.write_move_right_n {Γ} [inhabited Γ] (f : Γ → Γ) (L R : list_blank Γ) (n : ℕ) : ((tape.move dir.right)^[n] (tape.mk' L R)).write (f (R.nth n)) = ((tape.move dir.right)^[n] (tape.mk' L (R.modify_nth f n))) := begin induction n with n IH generalizing L R, { simp only [list_blank.nth_zero, list_blank.modify_nth, iterate_zero_apply], rw [← tape.write_mk', list_blank.cons_head_tail] }, simp only [list_blank.head_cons, list_blank.nth_succ, list_blank.modify_nth, tape.move_right_mk', list_blank.tail_cons, iterate_succ_apply, IH] end theorem tape.map_move {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (T : tape Γ) (d) : (T.move d).map f = (T.map f).move d := by cases T; cases d; simp only [tape.move, tape.map, list_blank.head_map, eq_self_iff_true, list_blank.map_cons, and_self, list_blank.tail_map] theorem tape.map_mk' {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (L R : list_blank Γ) : (tape.mk' L R).map f = tape.mk' (L.map f) (R.map f) := by simp only [tape.mk', tape.map, list_blank.head_map, eq_self_iff_true, and_self, list_blank.tail_map] theorem tape.map_mk₂ {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (L R : list Γ) : (tape.mk₂ L R).map f = tape.mk₂ (L.map f) (R.map f) := by simp only [tape.mk₂, tape.map_mk', list_blank.map_mk] theorem tape.map_mk₁ {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (l : list Γ) : (tape.mk₁ l).map f = tape.mk₁ (l.map f) := tape.map_mk₂ _ _ _ /-- Run a state transition function `σ → option σ` "to completion". The return value is the last state returned before a `none` result. If the state transition function always returns `some`, then the computation diverges, returning `part.none`. -/ def eval {σ} (f : σ → option σ) : σ → part σ := pfun.fix (λ s, part.some $ (f s).elim (sum.inl s) sum.inr) /-- The reflexive transitive closure of a state transition function. `reaches f a b` means there is a finite sequence of steps `f a = some a₁`, `f a₁ = some a₂`, ... such that `aₙ = b`. This relation permits zero steps of the state transition function. -/ def reaches {σ} (f : σ → option σ) : σ → σ → Prop := refl_trans_gen (λ a b, b ∈ f a) /-- The transitive closure of a state transition function. `reaches₁ f a b` means there is a nonempty finite sequence of steps `f a = some a₁`, `f a₁ = some a₂`, ... such that `aₙ = b`. This relation does not permit zero steps of the state transition function. -/ def reaches₁ {σ} (f : σ → option σ) : σ → σ → Prop := trans_gen (λ a b, b ∈ f a) theorem reaches₁_eq {σ} {f : σ → option σ} {a b c} (h : f a = f b) : reaches₁ f a c ↔ reaches₁ f b c := trans_gen.head'_iff.trans (trans_gen.head'_iff.trans $ by rw h).symm theorem reaches_total {σ} {f : σ → option σ} {a b c} (hab : reaches f a b) (hac : reaches f a c) : reaches f b c ∨ reaches f c b := refl_trans_gen.total_of_right_unique (λ _ _ _, option.mem_unique) hab hac theorem reaches₁_fwd {σ} {f : σ → option σ} {a b c} (h₁ : reaches₁ f a c) (h₂ : b ∈ f a) : reaches f b c := begin rcases trans_gen.head'_iff.1 h₁ with ⟨b', hab, hbc⟩, cases option.mem_unique hab h₂, exact hbc end /-- A variation on `reaches`. `reaches₀ f a b` holds if whenever `reaches₁ f b c` then `reaches₁ f a c`. This is a weaker property than `reaches` and is useful for replacing states with equivalent states without taking a step. -/ def reaches₀ {σ} (f : σ → option σ) (a b : σ) : Prop := ∀ c, reaches₁ f b c → reaches₁ f a c theorem reaches₀.trans {σ} {f : σ → option σ} {a b c : σ} (h₁ : reaches₀ f a b) (h₂ : reaches₀ f b c) : reaches₀ f a c | d h₃ := h₁ _ (h₂ _ h₃) @[refl] theorem reaches₀.refl {σ} {f : σ → option σ} (a : σ) : reaches₀ f a a | b h := h theorem reaches₀.single {σ} {f : σ → option σ} {a b : σ} (h : b ∈ f a) : reaches₀ f a b | c h₂ := h₂.head h theorem reaches₀.head {σ} {f : σ → option σ} {a b c : σ} (h : b ∈ f a) (h₂ : reaches₀ f b c) : reaches₀ f a c := (reaches₀.single h).trans h₂ theorem reaches₀.tail {σ} {f : σ → option σ} {a b c : σ} (h₁ : reaches₀ f a b) (h : c ∈ f b) : reaches₀ f a c := h₁.trans (reaches₀.single h) theorem reaches₀_eq {σ} {f : σ → option σ} {a b} (e : f a = f b) : reaches₀ f a b | d h := (reaches₁_eq e).2 h theorem reaches₁.to₀ {σ} {f : σ → option σ} {a b : σ} (h : reaches₁ f a b) : reaches₀ f a b | c h₂ := h.trans h₂ theorem reaches.to₀ {σ} {f : σ → option σ} {a b : σ} (h : reaches f a b) : reaches₀ f a b | c h₂ := h₂.trans_right h theorem reaches₀.tail' {σ} {f : σ → option σ} {a b c : σ} (h : reaches₀ f a b) (h₂ : c ∈ f b) : reaches₁ f a c := h _ (trans_gen.single h₂) /-- (co-)Induction principle for `eval`. If a property `C` holds of any point `a` evaluating to `b` which is either terminal (meaning `a = b`) or where the next point also satisfies `C`, then it holds of any point where `eval f a` evaluates to `b`. This formalizes the notion that if `eval f a` evaluates to `b` then it reaches terminal state `b` in finitely many steps. -/ @[elab_as_eliminator] def eval_induction {σ} {f : σ → option σ} {b : σ} {C : σ → Sort*} {a : σ} (h : b ∈ eval f a) (H : ∀ a, b ∈ eval f a → (∀ a', b ∈ eval f a' → f a = some a' → C a') → C a) : C a := pfun.fix_induction h (λ a' ha' h', H _ ha' $ λ b' hb' e, h' _ hb' $ part.mem_some_iff.2 $ by rw e; refl) theorem mem_eval {σ} {f : σ → option σ} {a b} : b ∈ eval f a ↔ reaches f a b ∧ f b = none := ⟨λ h, begin refine eval_induction h (λ a h IH, _), cases e : f a with a', { rw part.mem_unique h (pfun.mem_fix_iff.2 $ or.inl $ part.mem_some_iff.2 $ by rw e; refl), exact ⟨refl_trans_gen.refl, e⟩ }, { rcases pfun.mem_fix_iff.1 h with h | ⟨_, h, h'⟩; rw e at h; cases part.mem_some_iff.1 h, cases IH a' h' (by rwa e) with h₁ h₂, exact ⟨refl_trans_gen.head e h₁, h₂⟩ } end, λ ⟨h₁, h₂⟩, begin refine refl_trans_gen.head_induction_on h₁ _ (λ a a' h _ IH, _), { refine pfun.mem_fix_iff.2 (or.inl _), rw h₂, apply part.mem_some }, { refine pfun.mem_fix_iff.2 (or.inr ⟨_, _, IH⟩), rw show f a = _, from h, apply part.mem_some } end⟩ theorem eval_maximal₁ {σ} {f : σ → option σ} {a b} (h : b ∈ eval f a) (c) : ¬ reaches₁ f b c | bc := let ⟨ab, b0⟩ := mem_eval.1 h, ⟨b', h', _⟩ := trans_gen.head'_iff.1 bc in by cases b0.symm.trans h' theorem eval_maximal {σ} {f : σ → option σ} {a b} (h : b ∈ eval f a) {c} : reaches f b c ↔ c = b := let ⟨ab, b0⟩ := mem_eval.1 h in refl_trans_gen_iff_eq $ λ b' h', by cases b0.symm.trans h' theorem reaches_eval {σ} {f : σ → option σ} {a b} (ab : reaches f a b) : eval f a = eval f b := part.ext $ λ c, ⟨λ h, let ⟨ac, c0⟩ := mem_eval.1 h in mem_eval.2 ⟨(or_iff_left_of_imp $ by exact λ cb, (eval_maximal h).1 cb ▸ refl_trans_gen.refl).1 (reaches_total ab ac), c0⟩, λ h, let ⟨bc, c0⟩ := mem_eval.1 h in mem_eval.2 ⟨ab.trans bc, c0⟩,⟩ /-- Given a relation `tr : σ₁ → σ₂ → Prop` between state spaces, and state transition functions `f₁ : σ₁ → option σ₁` and `f₂ : σ₂ → option σ₂`, `respects f₁ f₂ tr` means that if `tr a₁ a₂` holds initially and `f₁` takes a step to `a₂` then `f₂` will take one or more steps before reaching a state `b₂` satisfying `tr a₂ b₂`, and if `f₁ a₁` terminates then `f₂ a₂` also terminates. Such a relation `tr` is also known as a refinement. -/ def respects {σ₁ σ₂} (f₁ : σ₁ → option σ₁) (f₂ : σ₂ → option σ₂) (tr : σ₁ → σ₂ → Prop) := ∀ ⦃a₁ a₂⦄, tr a₁ a₂ → (match f₁ a₁ with | some b₁ := ∃ b₂, tr b₁ b₂ ∧ reaches₁ f₂ a₂ b₂ | none := f₂ a₂ = none end : Prop) theorem tr_reaches₁ {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop} (H : respects f₁ f₂ tr) {a₁ a₂} (aa : tr a₁ a₂) {b₁} (ab : reaches₁ f₁ a₁ b₁) : ∃ b₂, tr b₁ b₂ ∧ reaches₁ f₂ a₂ b₂ := begin induction ab with c₁ ac c₁ d₁ ac cd IH, { have := H aa, rwa (show f₁ a₁ = _, from ac) at this }, { rcases IH with ⟨c₂, cc, ac₂⟩, have := H cc, rw (show f₁ c₁ = _, from cd) at this, rcases this with ⟨d₂, dd, cd₂⟩, exact ⟨_, dd, ac₂.trans cd₂⟩ } end theorem tr_reaches {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop} (H : respects f₁ f₂ tr) {a₁ a₂} (aa : tr a₁ a₂) {b₁} (ab : reaches f₁ a₁ b₁) : ∃ b₂, tr b₁ b₂ ∧ reaches f₂ a₂ b₂ := begin rcases refl_trans_gen_iff_eq_or_trans_gen.1 ab with rfl | ab, { exact ⟨_, aa, refl_trans_gen.refl⟩ }, { exact let ⟨b₂, bb, h⟩ := tr_reaches₁ H aa ab in ⟨b₂, bb, h.to_refl⟩ } end theorem tr_reaches_rev {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop} (H : respects f₁ f₂ tr) {a₁ a₂} (aa : tr a₁ a₂) {b₂} (ab : reaches f₂ a₂ b₂) : ∃ c₁ c₂, reaches f₂ b₂ c₂ ∧ tr c₁ c₂ ∧ reaches f₁ a₁ c₁ := begin induction ab with c₂ d₂ ac cd IH, { exact ⟨_, _, refl_trans_gen.refl, aa, refl_trans_gen.refl⟩ }, { rcases IH with ⟨e₁, e₂, ce, ee, ae⟩, rcases refl_trans_gen.cases_head ce with rfl | ⟨d', cd', de⟩, { have := H ee, revert this, cases eg : f₁ e₁ with g₁; simp only [respects, and_imp, exists_imp_distrib], { intro c0, cases cd.symm.trans c0 }, { intros g₂ gg cg, rcases trans_gen.head'_iff.1 cg with ⟨d', cd', dg⟩, cases option.mem_unique cd cd', exact ⟨_, _, dg, gg, ae.tail eg⟩ } }, { cases option.mem_unique cd cd', exact ⟨_, _, de, ee, ae⟩ } } end theorem tr_eval {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop} (H : respects f₁ f₂ tr) {a₁ b₁ a₂} (aa : tr a₁ a₂) (ab : b₁ ∈ eval f₁ a₁) : ∃ b₂, tr b₁ b₂ ∧ b₂ ∈ eval f₂ a₂ := begin cases mem_eval.1 ab with ab b0, rcases tr_reaches H aa ab with ⟨b₂, bb, ab⟩, refine ⟨_, bb, mem_eval.2 ⟨ab, _⟩⟩, have := H bb, rwa b0 at this end theorem tr_eval_rev {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop} (H : respects f₁ f₂ tr) {a₁ b₂ a₂} (aa : tr a₁ a₂) (ab : b₂ ∈ eval f₂ a₂) : ∃ b₁, tr b₁ b₂ ∧ b₁ ∈ eval f₁ a₁ := begin cases mem_eval.1 ab with ab b0, rcases tr_reaches_rev H aa ab with ⟨c₁, c₂, bc, cc, ac⟩, cases (refl_trans_gen_iff_eq (by exact option.eq_none_iff_forall_not_mem.1 b0)).1 bc, refine ⟨_, cc, mem_eval.2 ⟨ac, _⟩⟩, have := H cc, cases f₁ c₁ with d₁, {refl}, rcases this with ⟨d₂, dd, bd⟩, rcases trans_gen.head'_iff.1 bd with ⟨e, h, _⟩, cases b0.symm.trans h end theorem tr_eval_dom {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop} (H : respects f₁ f₂ tr) {a₁ a₂} (aa : tr a₁ a₂) : (eval f₂ a₂).dom ↔ (eval f₁ a₁).dom := ⟨λ h, let ⟨b₂, tr, h, _⟩ := tr_eval_rev H aa ⟨h, rfl⟩ in h, λ h, let ⟨b₂, tr, h, _⟩ := tr_eval H aa ⟨h, rfl⟩ in h⟩ /-- A simpler version of `respects` when the state transition relation `tr` is a function. -/ def frespects {σ₁ σ₂} (f₂ : σ₂ → option σ₂) (tr : σ₁ → σ₂) (a₂ : σ₂) : option σ₁ → Prop | (some b₁) := reaches₁ f₂ a₂ (tr b₁) | none := f₂ a₂ = none theorem frespects_eq {σ₁ σ₂} {f₂ : σ₂ → option σ₂} {tr : σ₁ → σ₂} {a₂ b₂} (h : f₂ a₂ = f₂ b₂) : ∀ {b₁}, frespects f₂ tr a₂ b₁ ↔ frespects f₂ tr b₂ b₁ | (some b₁) := reaches₁_eq h | none := by unfold frespects; rw h theorem fun_respects {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂} : respects f₁ f₂ (λ a b, tr a = b) ↔ ∀ ⦃a₁⦄, frespects f₂ tr (tr a₁) (f₁ a₁) := forall_congr $ λ a₁, by cases f₁ a₁; simp only [frespects, respects, exists_eq_left', forall_eq'] theorem tr_eval' {σ₁ σ₂} (f₁ : σ₁ → option σ₁) (f₂ : σ₂ → option σ₂) (tr : σ₁ → σ₂) (H : respects f₁ f₂ (λ a b, tr a = b)) (a₁) : eval f₂ (tr a₁) = tr <$> eval f₁ a₁ := part.ext $ λ b₂, ⟨λ h, let ⟨b₁, bb, hb⟩ := tr_eval_rev H rfl h in (part.mem_map_iff _).2 ⟨b₁, hb, bb⟩, λ h, begin rcases (part.mem_map_iff _).1 h with ⟨b₁, ab, bb⟩, rcases tr_eval H rfl ab with ⟨_, rfl, h⟩, rwa bb at h end⟩ /-! ## The TM0 model A TM0 turing machine is essentially a Post-Turing machine, adapted for type theory. A Post-Turing machine with symbol type `Γ` and label type `Λ` is a function `Λ → Γ → option (Λ × stmt)`, where a `stmt` can be either `move left`, `move right` or `write a` for `a : Γ`. The machine works over a "tape", a doubly-infinite sequence of elements of `Γ`, and an instantaneous configuration, `cfg`, is a label `q : Λ` indicating the current internal state of the machine, and a `tape Γ` (which is essentially `ℤ →₀ Γ`). The evolution is described by the `step` function: * If `M q T.head = none`, then the machine halts. * If `M q T.head = some (q', s)`, then the machine performs action `s : stmt` and then transitions to state `q'`. The initial state takes a `list Γ` and produces a `tape Γ` where the head of the list is the head of the tape and the rest of the list extends to the right, with the left side all blank. The final state takes the entire right side of the tape right or equal to the current position of the machine. (This is actually a `list_blank Γ`, not a `list Γ`, because we don't know, at this level of generality, where the output ends. If equality to `default Γ` is decidable we can trim the list to remove the infinite tail of blanks.) -/ namespace TM0 section parameters (Γ : Type*) [inhabited Γ] -- type of tape symbols parameters (Λ : Type*) [inhabited Λ] -- type of "labels" or TM states /-- A Turing machine "statement" is just a command to either move left or right, or write a symbol on the tape. -/ inductive stmt | move : dir → stmt | write : Γ → stmt instance stmt.inhabited : inhabited stmt := ⟨stmt.write (default _)⟩ /-- A Post-Turing machine with symbol type `Γ` and label type `Λ` is a function which, given the current state `q : Λ` and the tape head `a : Γ`, either halts (returns `none`) or returns a new state `q' : Λ` and a `stmt` describing what to do, either a move left or right, or a write command. Both `Λ` and `Γ` are required to be inhabited; the default value for `Γ` is the "blank" tape value, and the default value of `Λ` is the initial state. -/ @[nolint unused_arguments] -- [inhabited Λ]: this is a deliberate addition, see comment def machine := Λ → Γ → option (Λ × stmt) instance machine.inhabited : inhabited machine := by unfold machine; apply_instance /-- The configuration state of a Turing machine during operation consists of a label (machine state), and a tape, represented in the form `(a, L, R)` meaning the tape looks like `L.rev ++ [a] ++ R` with the machine currently reading the `a`. The lists are automatically extended with blanks as the machine moves around. -/ structure cfg := (q : Λ) (tape : tape Γ) instance cfg.inhabited : inhabited cfg := ⟨⟨default _, default _⟩⟩ parameters {Γ Λ} /-- Execution semantics of the Turing machine. -/ def step (M : machine) : cfg → option cfg | ⟨q, T⟩ := (M q T.1).map (λ ⟨q', a⟩, ⟨q', match a with | stmt.move d := T.move d | stmt.write a := T.write a end⟩) /-- The statement `reaches M s₁ s₂` means that `s₂` is obtained starting from `s₁` after a finite number of steps from `s₂`. -/ def reaches (M : machine) : cfg → cfg → Prop := refl_trans_gen (λ a b, b ∈ step M a) /-- The initial configuration. -/ def init (l : list Γ) : cfg := ⟨default Λ, tape.mk₁ l⟩ /-- Evaluate a Turing machine on initial input to a final state, if it terminates. -/ def eval (M : machine) (l : list Γ) : part (list_blank Γ) := (eval (step M) (init l)).map (λ c, c.tape.right₀) /-- The raw definition of a Turing machine does not require that `Γ` and `Λ` are finite, and in practice we will be interested in the infinite `Λ` case. We recover instead a notion of "effectively finite" Turing machines, which only make use of a finite subset of their states. We say that a set `S ⊆ Λ` supports a Turing machine `M` if `S` is closed under the transition function and contains the initial state. -/ def supports (M : machine) (S : set Λ) := default Λ ∈ S ∧ ∀ {q a q' s}, (q', s) ∈ M q a → q ∈ S → q' ∈ S theorem step_supports (M : machine) {S} (ss : supports M S) : ∀ {c c' : cfg}, c' ∈ step M c → c.q ∈ S → c'.q ∈ S | ⟨q, T⟩ c' h₁ h₂ := begin rcases option.map_eq_some'.1 h₁ with ⟨⟨q', a⟩, h, rfl⟩, exact ss.2 h h₂, end theorem univ_supports (M : machine) : supports M set.univ := ⟨trivial, λ q a q' s h₁ h₂, trivial⟩ end section variables {Γ : Type*} [inhabited Γ] variables {Γ' : Type*} [inhabited Γ'] variables {Λ : Type*} [inhabited Λ] variables {Λ' : Type*} [inhabited Λ'] /-- Map a TM statement across a function. This does nothing to move statements and maps the write values. -/ def stmt.map (f : pointed_map Γ Γ') : stmt Γ → stmt Γ' | (stmt.move d) := stmt.move d | (stmt.write a) := stmt.write (f a) /-- Map a configuration across a function, given `f : Γ → Γ'` a map of the alphabets and `g : Λ → Λ'` a map of the machine states. -/ def cfg.map (f : pointed_map Γ Γ') (g : Λ → Λ') : cfg Γ Λ → cfg Γ' Λ' | ⟨q, T⟩ := ⟨g q, T.map f⟩ variables (M : machine Γ Λ) (f₁ : pointed_map Γ Γ') (f₂ : pointed_map Γ' Γ) (g₁ : Λ → Λ') (g₂ : Λ' → Λ) /-- Because the state transition function uses the alphabet and machine states in both the input and output, to map a machine from one alphabet and machine state space to another we need functions in both directions, essentially an `equiv` without the laws. -/ def machine.map : machine Γ' Λ' | q l := (M (g₂ q) (f₂ l)).map (prod.map g₁ (stmt.map f₁)) theorem machine.map_step {S : set Λ} (f₂₁ : function.right_inverse f₁ f₂) (g₂₁ : ∀ q ∈ S, g₂ (g₁ q) = q) : ∀ c : cfg Γ Λ, c.q ∈ S → (step M c).map (cfg.map f₁ g₁) = step (M.map f₁ f₂ g₁ g₂) (cfg.map f₁ g₁ c) | ⟨q, T⟩ h := begin unfold step machine.map cfg.map, simp only [turing.tape.map_fst, g₂₁ q h, f₂₁ _], rcases M q T.1 with _|⟨q', d|a⟩, {refl}, { simp only [step, cfg.map, option.map_some', tape.map_move f₁], refl }, { simp only [step, cfg.map, option.map_some', tape.map_write], refl } end theorem map_init (g₁ : pointed_map Λ Λ') (l : list Γ) : (init l).map f₁ g₁ = init (l.map f₁) := congr (congr_arg cfg.mk g₁.map_pt) (tape.map_mk₁ _ _) theorem machine.map_respects (g₁ : pointed_map Λ Λ') (g₂ : Λ' → Λ) {S} (ss : supports M S) (f₂₁ : function.right_inverse f₁ f₂) (g₂₁ : ∀ q ∈ S, g₂ (g₁ q) = q) : respects (step M) (step (M.map f₁ f₂ g₁ g₂)) (λ a b, a.q ∈ S ∧ cfg.map f₁ g₁ a = b) | c _ ⟨cs, rfl⟩ := begin cases e : step M c with c'; unfold respects, { rw [← M.map_step f₁ f₂ g₁ g₂ f₂₁ g₂₁ _ cs, e], refl }, { refine ⟨_, ⟨step_supports M ss e cs, rfl⟩, trans_gen.single _⟩, rw [← M.map_step f₁ f₂ g₁ g₂ f₂₁ g₂₁ _ cs, e], exact rfl } end end end TM0 /-! ## The TM1 model The TM1 model is a simplification and extension of TM0 (Post-Turing model) in the direction of Wang B-machines. The machine's internal state is extended with a (finite) store `σ` of variables that may be accessed and updated at any time. A machine is given by a `Λ` indexed set of procedures or functions. Each function has a body which is a `stmt`. Most of the regular commands are allowed to use the current value `a` of the local variables and the value `T.head` on the tape to calculate what to write or how to change local state, but the statements themselves have a fixed structure. The `stmt`s can be as follows: * `move d q`: move left or right, and then do `q` * `write (f : Γ → σ → Γ) q`: write `f a T.head` to the tape, then do `q` * `load (f : Γ → σ → σ) q`: change the internal state to `f a T.head` * `branch (f : Γ → σ → bool) qtrue qfalse`: If `f a T.head` is true, do `qtrue`, else `qfalse` * `goto (f : Γ → σ → Λ)`: Go to label `f a T.head` * `halt`: Transition to the halting state, which halts on the following step Note that here most statements do not have labels; `goto` commands can only go to a new function. Only the `goto` and `halt` statements actually take a step; the rest is done by recursion on statements and so take 0 steps. (There is a uniform bound on many statements can be executed before the next `goto`, so this is an `O(1)` speedup with the constant depending on the machine.) The `halt` command has a one step stutter before actually halting so that any changes made before the halt have a chance to be "committed", since the `eval` relation uses the final configuration before the halt as the output, and `move` and `write` etc. take 0 steps in this model. -/ namespace TM1 section parameters (Γ : Type*) [inhabited Γ] -- Type of tape symbols parameters (Λ : Type*) -- Type of function labels parameters (σ : Type*) -- Type of variable settings /-- The TM1 model is a simplification and extension of TM0 (Post-Turing model) in the direction of Wang B-machines. The machine's internal state is extended with a (finite) store `σ` of variables that may be accessed and updated at any time. A machine is given by a `Λ` indexed set of procedures or functions. Each function has a body which is a `stmt`, which can either be a `move` or `write` command, a `branch` (if statement based on the current tape value), a `load` (set the variable value), a `goto` (call another function), or `halt`. Note that here most statements do not have labels; `goto` commands can only go to a new function. All commands have access to the variable value and current tape value. -/ inductive stmt | move : dir → stmt → stmt | write : (Γ → σ → Γ) → stmt → stmt | load : (Γ → σ → σ) → stmt → stmt | branch : (Γ → σ → bool) → stmt → stmt → stmt | goto : (Γ → σ → Λ) → stmt | halt : stmt open stmt instance stmt.inhabited : inhabited stmt := ⟨halt⟩ /-- The configuration of a TM1 machine is given by the currently evaluating statement, the variable store value, and the tape. -/ structure cfg := (l : option Λ) (var : σ) (tape : tape Γ) instance cfg.inhabited [inhabited σ] : inhabited cfg := ⟨⟨default _, default _, default _⟩⟩ parameters {Γ Λ σ} /-- The semantics of TM1 evaluation. -/ def step_aux : stmt → σ → tape Γ → cfg | (move d q) v T := step_aux q v (T.move d) | (write a q) v T := step_aux q v (T.write (a T.1 v)) | (load s q) v T := step_aux q (s T.1 v) T | (branch p q₁ q₂) v T := cond (p T.1 v) (step_aux q₁ v T) (step_aux q₂ v T) | (goto l) v T := ⟨some (l T.1 v), v, T⟩ | halt v T := ⟨none, v, T⟩ /-- The state transition function. -/ def step (M : Λ → stmt) : cfg → option cfg | ⟨none, v, T⟩ := none | ⟨some l, v, T⟩ := some (step_aux (M l) v T) /-- A set `S` of labels supports the statement `q` if all the `goto` statements in `q` refer only to other functions in `S`. -/ def supports_stmt (S : finset Λ) : stmt → Prop | (move d q) := supports_stmt q | (write a q) := supports_stmt q | (load s q) := supports_stmt q | (branch p q₁ q₂) := supports_stmt q₁ ∧ supports_stmt q₂ | (goto l) := ∀ a v, l a v ∈ S | halt := true open_locale classical /-- The subterm closure of a statement. -/ noncomputable def stmts₁ : stmt → finset stmt | Q@(move d q) := insert Q (stmts₁ q) | Q@(write a q) := insert Q (stmts₁ q) | Q@(load s q) := insert Q (stmts₁ q) | Q@(branch p q₁ q₂) := insert Q (stmts₁ q₁ ∪ stmts₁ q₂) | Q := {Q} theorem stmts₁_self {q} : q ∈ stmts₁ q := by cases q; apply_rules [finset.mem_insert_self, finset.mem_singleton_self] theorem stmts₁_trans {q₁ q₂} : q₁ ∈ stmts₁ q₂ → stmts₁ q₁ ⊆ stmts₁ q₂ := begin intros h₁₂ q₀ h₀₁, induction q₂ with _ q IH _ q IH _ q IH; simp only [stmts₁] at h₁₂ ⊢; simp only [finset.mem_insert, finset.mem_union, finset.mem_singleton] at h₁₂, iterate 3 { rcases h₁₂ with rfl | h₁₂, { unfold stmts₁ at h₀₁, exact h₀₁ }, { exact finset.mem_insert_of_mem (IH h₁₂) } }, case TM1.stmt.branch : p q₁ q₂ IH₁ IH₂ { rcases h₁₂ with rfl | h₁₂ | h₁₂, { unfold stmts₁ at h₀₁, exact h₀₁ }, { exact finset.mem_insert_of_mem (finset.mem_union_left _ $ IH₁ h₁₂) }, { exact finset.mem_insert_of_mem (finset.mem_union_right _ $ IH₂ h₁₂) } }, case TM1.stmt.goto : l { subst h₁₂, exact h₀₁ }, case TM1.stmt.halt { subst h₁₂, exact h₀₁ } end theorem stmts₁_supports_stmt_mono {S q₁ q₂} (h : q₁ ∈ stmts₁ q₂) (hs : supports_stmt S q₂) : supports_stmt S q₁ := begin induction q₂ with _ q IH _ q IH _ q IH; simp only [stmts₁, supports_stmt, finset.mem_insert, finset.mem_union, finset.mem_singleton] at h hs, iterate 3 { rcases h with rfl | h; [exact hs, exact IH h hs] }, case TM1.stmt.branch : p q₁ q₂ IH₁ IH₂ { rcases h with rfl | h | h, exacts [hs, IH₁ h hs.1, IH₂ h hs.2] }, case TM1.stmt.goto : l { subst h, exact hs }, case TM1.stmt.halt { subst h, trivial } end /-- The set of all statements in a turing machine, plus one extra value `none` representing the halt state. This is used in the TM1 to TM0 reduction. -/ noncomputable def stmts (M : Λ → stmt) (S : finset Λ) : finset (option stmt) := (S.bUnion (λ q, stmts₁ (M q))).insert_none theorem stmts_trans {M : Λ → stmt} {S q₁ q₂} (h₁ : q₁ ∈ stmts₁ q₂) : some q₂ ∈ stmts M S → some q₁ ∈ stmts M S := by simp only [stmts, finset.mem_insert_none, finset.mem_bUnion, option.mem_def, forall_eq', exists_imp_distrib]; exact λ l ls h₂, ⟨_, ls, stmts₁_trans h₂ h₁⟩ variable [inhabited Λ] /-- A set `S` of labels supports machine `M` if all the `goto` statements in the functions in `S` refer only to other functions in `S`. -/ def supports (M : Λ → stmt) (S : finset Λ) := default Λ ∈ S ∧ ∀ q ∈ S, supports_stmt S (M q) theorem stmts_supports_stmt {M : Λ → stmt} {S q} (ss : supports M S) : some q ∈ stmts M S → supports_stmt S q := by simp only [stmts, finset.mem_insert_none, finset.mem_bUnion, option.mem_def, forall_eq', exists_imp_distrib]; exact λ l ls h, stmts₁_supports_stmt_mono h (ss.2 _ ls) theorem step_supports (M : Λ → stmt) {S} (ss : supports M S) : ∀ {c c' : cfg}, c' ∈ step M c → c.l ∈ S.insert_none → c'.l ∈ S.insert_none | ⟨some l₁, v, T⟩ c' h₁ h₂ := begin replace h₂ := ss.2 _ (finset.some_mem_insert_none.1 h₂), simp only [step, option.mem_def] at h₁, subst c', revert h₂, induction M l₁ with _ q IH _ q IH _ q IH generalizing v T; intro hs, iterate 3 { exact IH _ _ hs }, case TM1.stmt.branch : p q₁' q₂' IH₁ IH₂ { unfold step_aux, cases p T.1 v, { exact IH₂ _ _ hs.2 }, { exact IH₁ _ _ hs.1 } }, case TM1.stmt.goto { exact finset.some_mem_insert_none.2 (hs _ _) }, case TM1.stmt.halt { apply multiset.mem_cons_self } end variable [inhabited σ] /-- The initial state, given a finite input that is placed on the tape starting at the TM head and going to the right. -/ def init (l : list Γ) : cfg := ⟨some (default _), default _, tape.mk₁ l⟩ /-- Evaluate a TM to completion, resulting in an output list on the tape (with an indeterminate number of blanks on the end). -/ def eval (M : Λ → stmt) (l : list Γ) : part (list_blank Γ) := (eval (step M) (init l)).map (λ c, c.tape.right₀) end end TM1 /-! ## TM1 emulator in TM0 To prove that TM1 computable functions are TM0 computable, we need to reduce each TM1 program to a TM0 program. So suppose a TM1 program is given. We take the following: * The alphabet `Γ` is the same for both TM1 and TM0 * The set of states `Λ'` is defined to be `option stmt₁ × σ`, that is, a TM1 statement or `none` representing halt, and the possible settings of the internal variables. Note that this is an infinite set, because `stmt₁` is infinite. This is okay because we assume that from the initial TM1 state, only finitely many other labels are reachable, and there are only finitely many statements that appear in all of these functions. Even though `stmt₁` contains a statement called `halt`, we must separate it from `none` (`some halt` steps to `none` and `none` actually halts) because there is a one step stutter in the TM1 semantics. -/ namespace TM1to0 section parameters {Γ : Type*} [inhabited Γ] parameters {Λ : Type*} [inhabited Λ] parameters {σ : Type*} [inhabited σ] local notation `stmt₁` := TM1.stmt Γ Λ σ local notation `cfg₁` := TM1.cfg Γ Λ σ local notation `stmt₀` := TM0.stmt Γ parameters (M : Λ → stmt₁) include M /-- The base machine state space is a pair of an `option stmt₁` representing the current program to be executed, or `none` for the halt state, and a `σ` which is the local state (stored in the TM, not the tape). Because there are an infinite number of programs, this state space is infinite, but for a finitely supported TM1 machine and a finite type `σ`, only finitely many of these states are reachable. -/ @[nolint unused_arguments] -- [inhabited Λ] [inhabited σ] (M : Λ → stmt₁): We need the M assumption -- because of the inhabited instance, but we could avoid the inhabited instances on Λ and σ here. -- But they are parameters so we cannot easily skip them for just this definition. def Λ' := option stmt₁ × σ instance : inhabited Λ' := ⟨(some (M (default _)), default _)⟩ open TM0.stmt /-- The core TM1 → TM0 translation function. Here `s` is the current value on the tape, and the `stmt₁` is the TM1 statement to translate, with local state `v : σ`. We evaluate all regular instructions recursively until we reach either a `move` or `write` command, or a `goto`; in the latter case we emit a dummy `write s` step and transition to the new target location. -/ def tr_aux (s : Γ) : stmt₁ → σ → Λ' × stmt₀ | (TM1.stmt.move d q) v := ((some q, v), move d) | (TM1.stmt.write a q) v := ((some q, v), write (a s v)) | (TM1.stmt.load a q) v := tr_aux q (a s v) | (TM1.stmt.branch p q₁ q₂) v := cond (p s v) (tr_aux q₁ v) (tr_aux q₂ v) | (TM1.stmt.goto l) v := ((some (M (l s v)), v), write s) | TM1.stmt.halt v := ((none, v), write s) local notation `cfg₀` := TM0.cfg Γ Λ' /-- The translated TM0 machine (given the TM1 machine input). -/ def tr : TM0.machine Γ Λ' | (none, v) s := none | (some q, v) s := some (tr_aux s q v) /-- Translate configurations from TM1 to TM0. -/ def tr_cfg : cfg₁ → cfg₀ | ⟨l, v, T⟩ := ⟨(l.map M, v), T⟩ theorem tr_respects : respects (TM1.step M) (TM0.step tr) (λ c₁ c₂, tr_cfg c₁ = c₂) := fun_respects.2 $ λ ⟨l₁, v, T⟩, begin cases l₁ with l₁, {exact rfl}, unfold tr_cfg TM1.step frespects option.map function.comp option.bind, induction M l₁ with _ q IH _ q IH _ q IH generalizing v T, case TM1.stmt.move : d q IH { exact trans_gen.head rfl (IH _ _) }, case TM1.stmt.write : a q IH { exact trans_gen.head rfl (IH _ _) }, case TM1.stmt.load : a q IH { exact (reaches₁_eq (by refl)).2 (IH _ _) }, case TM1.stmt.branch : p q₁ q₂ IH₁ IH₂ { unfold TM1.step_aux, cases e : p T.1 v, { exact (reaches₁_eq (by simp only [TM0.step, tr, tr_aux, e]; refl)).2 (IH₂ _ _) }, { exact (reaches₁_eq (by simp only [TM0.step, tr, tr_aux, e]; refl)).2 (IH₁ _ _) } }, iterate 2 { exact trans_gen.single (congr_arg some (congr (congr_arg TM0.cfg.mk rfl) (tape.write_self T))) } end theorem tr_eval (l : list Γ) : TM0.eval tr l = TM1.eval M l := (congr_arg _ (tr_eval' _ _ _ tr_respects ⟨some _, _, _⟩)).trans begin rw [part.map_eq_map, part.map_map, TM1.eval], congr' with ⟨⟩, refl end variables [fintype σ] /-- Given a finite set of accessible `Λ` machine states, there is a finite set of accessible machine states in the target (even though the type `Λ'` is infinite). -/ noncomputable def tr_stmts (S : finset Λ) : finset Λ' := (TM1.stmts M S).product finset.univ open_locale classical local attribute [simp] TM1.stmts₁_self theorem tr_supports {S : finset Λ} (ss : TM1.supports M S) : TM0.supports tr (↑(tr_stmts S)) := ⟨finset.mem_product.2 ⟨finset.some_mem_insert_none.2 (finset.mem_bUnion.2 ⟨_, ss.1, TM1.stmts₁_self⟩), finset.mem_univ _⟩, λ q a q' s h₁ h₂, begin rcases q with ⟨_|q, v⟩, {cases h₁}, cases q' with q' v', simp only [tr_stmts, finset.mem_coe, finset.mem_product, finset.mem_univ, and_true] at h₂ ⊢, cases q', {exact multiset.mem_cons_self _ _}, simp only [tr, option.mem_def] at h₁, have := TM1.stmts_supports_stmt ss h₂, revert this, induction q generalizing v; intro hs, case TM1.stmt.move : d q { cases h₁, refine TM1.stmts_trans _ h₂, unfold TM1.stmts₁, exact finset.mem_insert_of_mem TM1.stmts₁_self }, case TM1.stmt.write : b q { cases h₁, refine TM1.stmts_trans _ h₂, unfold TM1.stmts₁, exact finset.mem_insert_of_mem TM1.stmts₁_self }, case TM1.stmt.load : b q IH { refine IH (TM1.stmts_trans _ h₂) _ h₁ hs, unfold TM1.stmts₁, exact finset.mem_insert_of_mem TM1.stmts₁_self }, case TM1.stmt.branch : p q₁ q₂ IH₁ IH₂ { change cond (p a v) _ _ = ((some q', v'), s) at h₁, cases p a v, { refine IH₂ (TM1.stmts_trans _ h₂) _ h₁ hs.2, unfold TM1.stmts₁, exact finset.mem_insert_of_mem (finset.mem_union_right _ TM1.stmts₁_self) }, { refine IH₁ (TM1.stmts_trans _ h₂) _ h₁ hs.1, unfold TM1.stmts₁, exact finset.mem_insert_of_mem (finset.mem_union_left _ TM1.stmts₁_self) } }, case TM1.stmt.goto : l { cases h₁, exact finset.some_mem_insert_none.2 (finset.mem_bUnion.2 ⟨_, hs _ _, TM1.stmts₁_self⟩) }, case TM1.stmt.halt { cases h₁ } end⟩ end end TM1to0 /-! ## TM1(Γ) emulator in TM1(bool) The most parsimonious Turing machine model that is still Turing complete is `TM0` with `Γ = bool`. Because our construction in the previous section reducing `TM1` to `TM0` doesn't change the alphabet, we can do the alphabet reduction on `TM1` instead of `TM0` directly. The basic idea is to use a bijection between `Γ` and a subset of `vector bool n`, where `n` is a fixed constant. Each tape element is represented as a block of `n` bools. Whenever the machine wants to read a symbol from the tape, it traverses over the block, performing `n` `branch` instructions to each any of the `2^n` results. For the `write` instruction, we have to use a `goto` because we need to follow a different code path depending on the local state, which is not available in the TM1 model, so instead we jump to a label computed using the read value and the local state, which performs the writing and returns to normal execution. Emulation overhead is `O(1)`. If not for the above `write` behavior it would be 1-1 because we are exploiting the 0-step behavior of regular commands to avoid taking steps, but there are nevertheless a bounded number of `write` calls between `goto` statements because TM1 statements are finitely long. -/ namespace TM1to1 open TM1 section parameters {Γ : Type*} [inhabited Γ] theorem exists_enc_dec [fintype Γ] : ∃ n (enc : Γ → vector bool n) (dec : vector bool n → Γ), enc (default _) = vector.repeat ff n ∧ ∀ a, dec (enc a) = a := begin letI := classical.dec_eq Γ, let n := fintype.card Γ, obtain ⟨F⟩ := fintype.trunc_equiv_fin Γ, let G : fin n ↪ fin n → bool := ⟨λ a b, a = b, λ a b h, of_to_bool_true $ (congr_fun h b).trans $ to_bool_tt rfl⟩, let H := (F.to_embedding.trans G).trans (equiv.vector_equiv_fin _ _).symm.to_embedding, classical, let enc := H.set_value (default _) (vector.repeat ff n), exact ⟨_, enc, function.inv_fun enc, H.set_value_eq _ _, function.left_inverse_inv_fun enc.2⟩ end parameters {Λ : Type*} [inhabited Λ] parameters {σ : Type*} [inhabited σ] local notation `stmt₁` := stmt Γ Λ σ local notation `cfg₁` := cfg Γ Λ σ /-- The configuration state of the TM. -/ inductive Λ' : Type (max u_1 u_2 u_3) | normal : Λ → Λ' | write : Γ → stmt₁ → Λ' instance : inhabited Λ' := ⟨Λ'.normal (default _)⟩ local notation `stmt'` := stmt bool Λ' σ local notation `cfg'` := cfg bool Λ' σ /-- Read a vector of length `n` from the tape. -/ def read_aux : ∀ n, (vector bool n → stmt') → stmt' | 0 f := f vector.nil | (i+1) f := stmt.branch (λ a s, a) (stmt.move dir.right $ read_aux i (λ v, f (tt ::ᵥ v))) (stmt.move dir.right $ read_aux i (λ v, f (ff ::ᵥ v))) parameters {n : ℕ} (enc : Γ → vector bool n) (dec : vector bool n → Γ) /-- A move left or right corresponds to `n` moves across the super-cell. -/ def move (d : dir) (q : stmt') : stmt' := (stmt.move d)^[n] q /-- To read a symbol from the tape, we use `read_aux` to traverse the symbol, then return to the original position with `n` moves to the left. -/ def read (f : Γ → stmt') : stmt' := read_aux n (λ v, move dir.left $ f (dec v)) /-- Write a list of bools on the tape. -/ def write : list bool → stmt' → stmt' | [] q := q | (a :: l) q := stmt.write (λ _ _, a) $ stmt.move dir.right $ write l q /-- Translate a normal instruction. For the `write` command, we use a `goto` indirection so that we can access the current value of the tape. -/ def tr_normal : stmt₁ → stmt' | (stmt.move d q) := move d $ tr_normal q | (stmt.write f q) := read $ λ a, stmt.goto $ λ _ s, Λ'.write (f a s) q | (stmt.load f q) := read $ λ a, stmt.load (λ _ s, f a s) $ tr_normal q | (stmt.branch p q₁ q₂) := read $ λ a, stmt.branch (λ _ s, p a s) (tr_normal q₁) (tr_normal q₂) | (stmt.goto l) := read $ λ a, stmt.goto $ λ _ s, Λ'.normal (l a s) | stmt.halt := stmt.halt theorem step_aux_move (d q v T) : step_aux (move d q) v T = step_aux q v ((tape.move d)^[n] T) := begin suffices : ∀ i, step_aux (stmt.move d^[i] q) v T = step_aux q v (tape.move d^[i] T), from this n, intro, induction i with i IH generalizing T, {refl}, rw [iterate_succ', step_aux, IH, iterate_succ] end theorem supports_stmt_move {S d q} : supports_stmt S (move d q) = supports_stmt S q := suffices ∀ {i}, supports_stmt S (stmt.move d^[i] q) = _, from this, by intro; induction i generalizing q; simp only [*, iterate]; refl theorem supports_stmt_write {S l q} : supports_stmt S (write l q) = supports_stmt S q := by induction l with a l IH; simp only [write, supports_stmt, *] theorem supports_stmt_read {S} : ∀ {f : Γ → stmt'}, (∀ a, supports_stmt S (f a)) → supports_stmt S (read f) := suffices ∀ i (f : vector bool i → stmt'), (∀ v, supports_stmt S (f v)) → supports_stmt S (read_aux i f), from λ f hf, this n _ (by intro; simp only [supports_stmt_move, hf]), λ i f hf, begin induction i with i IH, {exact hf _}, split; apply IH; intro; apply hf, end parameter (enc0 : enc (default _) = vector.repeat ff n) section parameter {enc} include enc0 /-- The low level tape corresponding to the given tape over alphabet `Γ`. -/ def tr_tape' (L R : list_blank Γ) : tape bool := begin refine tape.mk' (L.bind (λ x, (enc x).to_list.reverse) ⟨n, _⟩) (R.bind (λ x, (enc x).to_list) ⟨n, _⟩); simp only [enc0, vector.repeat, list.reverse_repeat, bool.default_bool, vector.to_list_mk] end /-- The low level tape corresponding to the given tape over alphabet `Γ`. -/ def tr_tape (T : tape Γ) : tape bool := tr_tape' T.left T.right₀ theorem tr_tape_mk' (L R : list_blank Γ) : tr_tape (tape.mk' L R) = tr_tape' L R := by simp only [tr_tape, tape.mk'_left, tape.mk'_right₀] end parameters (M : Λ → stmt₁) /-- The top level program. -/ def tr : Λ' → stmt' | (Λ'.normal l) := tr_normal (M l) | (Λ'.write a q) := write (enc a).to_list $ move dir.left $ tr_normal q /-- The machine configuration translation. -/ def tr_cfg : cfg₁ → cfg' | ⟨l, v, T⟩ := ⟨l.map Λ'.normal, v, tr_tape T⟩ parameter {enc} include enc0 theorem tr_tape'_move_left (L R) : (tape.move dir.left)^[n] (tr_tape' L R) = (tr_tape' L.tail (R.cons L.head)) := begin obtain ⟨a, L, rfl⟩ := L.exists_cons, simp only [tr_tape', list_blank.cons_bind, list_blank.head_cons, list_blank.tail_cons], suffices : ∀ {L' R' l₁ l₂} (e : vector.to_list (enc a) = list.reverse_core l₁ l₂), tape.move dir.left^[l₁.length] (tape.mk' (list_blank.append l₁ L') (list_blank.append l₂ R')) = tape.mk' L' (list_blank.append (vector.to_list (enc a)) R'), { simpa only [list.length_reverse, vector.to_list_length] using this (list.reverse_reverse _).symm }, intros, induction l₁ with b l₁ IH generalizing l₂, { cases e, refl }, simp only [list.length, list.cons_append, iterate_succ_apply], convert IH e, simp only [list_blank.tail_cons, list_blank.append, tape.move_left_mk', list_blank.head_cons] end theorem tr_tape'_move_right (L R) : (tape.move dir.right)^[n] (tr_tape' L R) = (tr_tape' (L.cons R.head) R.tail) := begin suffices : ∀ i L, (tape.move dir.right)^[i] ((tape.move dir.left)^[i] L) = L, { refine (eq.symm _).trans (this n _), simp only [tr_tape'_move_left, list_blank.cons_head_tail, list_blank.head_cons, list_blank.tail_cons] }, intros, induction i with i IH, {refl}, rw [iterate_succ_apply, iterate_succ_apply', tape.move_left_right, IH] end theorem step_aux_write (q v a b L R) : step_aux (write (enc a).to_list q) v (tr_tape' L (list_blank.cons b R)) = step_aux q v (tr_tape' (list_blank.cons a L) R) := begin simp only [tr_tape', list.cons_bind, list.append_assoc], suffices : ∀ {L' R'} (l₁ l₂ l₂' : list bool) (e : l₂'.length = l₂.length), step_aux (write l₂ q) v (tape.mk' (list_blank.append l₁ L') (list_blank.append l₂' R')) = step_aux q v (tape.mk' (L'.append (list.reverse_core l₂ l₁)) R'), { convert this [] _ _ ((enc b).2.trans (enc a).2.symm); rw list_blank.cons_bind; refl }, clear a b L R, intros, induction l₂ with a l₂ IH generalizing l₁ l₂', { cases list.length_eq_zero.1 e, refl }, cases l₂' with b l₂'; injection e with e, dunfold write step_aux, convert IH _ _ e using 1, simp only [list_blank.head_cons, list_blank.tail_cons, list_blank.append, tape.move_right_mk', tape.write_mk'] end parameters (encdec : ∀ a, dec (enc a) = a) include encdec theorem step_aux_read (f v L R) : step_aux (read f) v (tr_tape' L R) = step_aux (f R.head) v (tr_tape' L R) := begin suffices : ∀ f, step_aux (read_aux n f) v (tr_tape' enc0 L R) = step_aux (f (enc R.head)) v (tr_tape' enc0 (L.cons R.head) R.tail), { rw [read, this, step_aux_move, encdec, tr_tape'_move_left enc0], simp only [list_blank.head_cons, list_blank.cons_head_tail, list_blank.tail_cons] }, obtain ⟨a, R, rfl⟩ := R.exists_cons, simp only [list_blank.head_cons, list_blank.tail_cons, tr_tape', list_blank.cons_bind, list_blank.append_assoc], suffices : ∀ i f L' R' l₁ l₂ h, step_aux (read_aux i f) v (tape.mk' (list_blank.append l₁ L') (list_blank.append l₂ R')) = step_aux (f ⟨l₂, h⟩) v (tape.mk' (list_blank.append (l₂.reverse_core l₁) L') R'), { intro f, convert this n f _ _ _ _ (enc a).2; simp }, clear f L a R, intros, subst i, induction l₂ with a l₂ IH generalizing l₁, {refl}, transitivity step_aux (read_aux l₂.length (λ v, f (a ::ᵥ v))) v (tape.mk' ((L'.append l₁).cons a) (R'.append l₂)), { dsimp [read_aux, step_aux], simp, cases a; refl }, rw [← list_blank.append, IH], refl end theorem tr_respects : respects (step M) (step tr) (λ c₁ c₂, tr_cfg c₁ = c₂) := fun_respects.2 $ λ ⟨l₁, v, T⟩, begin obtain ⟨L, R, rfl⟩ := T.exists_mk', cases l₁ with l₁, {exact rfl}, suffices : ∀ q R, reaches (step (tr enc dec M)) (step_aux (tr_normal dec q) v (tr_tape' enc0 L R)) (tr_cfg enc0 (step_aux q v (tape.mk' L R))), { refine trans_gen.head' rfl _, rw tr_tape_mk', exact this _ R }, clear R l₁, intros, induction q with _ q IH _ q IH _ q IH generalizing v L R, case TM1.stmt.move : d q IH { cases d; simp only [tr_normal, iterate, step_aux_move, step_aux, list_blank.head_cons, tape.move_left_mk', list_blank.cons_head_tail, list_blank.tail_cons, tr_tape'_move_left enc0, tr_tape'_move_right enc0]; apply IH }, case TM1.stmt.write : f q IH { simp only [tr_normal, step_aux_read dec enc0 encdec, step_aux], refine refl_trans_gen.head rfl _, obtain ⟨a, R, rfl⟩ := R.exists_cons, rw [tr, tape.mk'_head, step_aux_write, list_blank.head_cons, step_aux_move, tr_tape'_move_left enc0, list_blank.head_cons, list_blank.tail_cons, tape.write_mk'], apply IH }, case TM1.stmt.load : a q IH { simp only [tr_normal, step_aux_read dec enc0 encdec], apply IH }, case TM1.stmt.branch : p q₁ q₂ IH₁ IH₂ { simp only [tr_normal, step_aux_read dec enc0 encdec, step_aux], cases p R.head v; [apply IH₂, apply IH₁] }, case TM1.stmt.goto : l { simp only [tr_normal, step_aux_read dec enc0 encdec, step_aux, tr_cfg, tr_tape_mk'], apply refl_trans_gen.refl }, case TM1.stmt.halt { simp only [tr_normal, step_aux, tr_cfg, step_aux_move, tr_tape'_move_left enc0, tr_tape'_move_right enc0, tr_tape_mk'], apply refl_trans_gen.refl } end omit enc0 encdec open_locale classical parameters [fintype Γ] /-- The set of accessible `Λ'.write` machine states. -/ noncomputable def writes : stmt₁ → finset Λ' | (stmt.move d q) := writes q | (stmt.write f q) := finset.univ.image (λ a, Λ'.write a q) ∪ writes q | (stmt.load f q) := writes q | (stmt.branch p q₁ q₂) := writes q₁ ∪ writes q₂ | (stmt.goto l) := ∅ | stmt.halt := ∅ /-- The set of accessible machine states, assuming that the input machine is supported on `S`, are the normal states embedded from `S`, plus all write states accessible from these states. -/ noncomputable def tr_supp (S : finset Λ) : finset Λ' := S.bUnion (λ l, insert (Λ'.normal l) (writes (M l))) theorem tr_supports {S} (ss : supports M S) : supports tr (tr_supp S) := ⟨finset.mem_bUnion.2 ⟨_, ss.1, finset.mem_insert_self _ _⟩, λ q h, begin suffices : ∀ q, supports_stmt S q → (∀ q' ∈ writes q, q' ∈ tr_supp M S) → supports_stmt (tr_supp M S) (tr_normal dec q) ∧ ∀ q' ∈ writes q, supports_stmt (tr_supp M S) (tr enc dec M q'), { rcases finset.mem_bUnion.1 h with ⟨l, hl, h⟩, have := this _ (ss.2 _ hl) (λ q' hq, finset.mem_bUnion.2 ⟨_, hl, finset.mem_insert_of_mem hq⟩), rcases finset.mem_insert.1 h with rfl | h, exacts [this.1, this.2 _ h] }, intros q hs hw, induction q, case TM1.stmt.move : d q IH { unfold writes at hw ⊢, replace IH := IH hs hw, refine ⟨_, IH.2⟩, cases d; simp only [tr_normal, iterate, supports_stmt_move, IH] }, case TM1.stmt.write : f q IH { unfold writes at hw ⊢, simp only [finset.mem_image, finset.mem_union, finset.mem_univ, exists_prop, true_and] at hw ⊢, replace IH := IH hs (λ q hq, hw q (or.inr hq)), refine ⟨supports_stmt_read _ $ λ a _ s, hw _ (or.inl ⟨_, rfl⟩), λ q' hq, _⟩, rcases hq with ⟨a, q₂, rfl⟩ | hq, { simp only [tr, supports_stmt_write, supports_stmt_move, IH.1] }, { exact IH.2 _ hq } }, case TM1.stmt.load : a q IH { unfold writes at hw ⊢, replace IH := IH hs hw, refine ⟨supports_stmt_read _ (λ a, IH.1), IH.2⟩ }, case TM1.stmt.branch : p q₁ q₂ IH₁ IH₂ { unfold writes at hw ⊢, simp only [finset.mem_union] at hw ⊢, replace IH₁ := IH₁ hs.1 (λ q hq, hw q (or.inl hq)), replace IH₂ := IH₂ hs.2 (λ q hq, hw q (or.inr hq)), exact ⟨supports_stmt_read _ (λ a, ⟨IH₁.1, IH₂.1⟩), λ q, or.rec (IH₁.2 _) (IH₂.2 _)⟩ }, case TM1.stmt.goto : l { refine ⟨_, λ _, false.elim⟩, refine supports_stmt_read _ (λ a _ s, _), exact finset.mem_bUnion.2 ⟨_, hs _ _, finset.mem_insert_self _ _⟩ }, case TM1.stmt.halt { refine ⟨_, λ _, false.elim⟩, simp only [supports_stmt, supports_stmt_move, tr_normal] } end⟩ end end TM1to1 /-! ## TM0 emulator in TM1 To establish that TM0 and TM1 are equivalent computational models, we must also have a TM0 emulator in TM1. The main complication here is that TM0 allows an action to depend on the value at the head and local state, while TM1 doesn't (in order to have more programming language-like semantics). So we use a computed `goto` to go to a state that performes the desired action and then returns to normal execution. One issue with this is that the `halt` instruction is supposed to halt immediately, not take a step to a halting state. To resolve this we do a check for `halt` first, then `goto` (with an unreachable branch). -/ namespace TM0to1 section parameters {Γ : Type*} [inhabited Γ] parameters {Λ : Type*} [inhabited Λ] /-- The machine states for a TM1 emulating a TM0 machine. States of the TM0 machine are embedded as `normal q` states, but the actual operation is split into two parts, a jump to `act s q` followed by the action and a jump to the next `normal` state. -/ inductive Λ' | normal : Λ → Λ' | act : TM0.stmt Γ → Λ → Λ' instance : inhabited Λ' := ⟨Λ'.normal (default _)⟩ local notation `cfg₀` := TM0.cfg Γ Λ local notation `stmt₁` := TM1.stmt Γ Λ' unit local notation `cfg₁` := TM1.cfg Γ Λ' unit parameters (M : TM0.machine Γ Λ) open TM1.stmt /-- The program. -/ def tr : Λ' → stmt₁ | (Λ'.normal q) := branch (λ a _, (M q a).is_none) halt $ goto (λ a _, match M q a with | none := default _ -- unreachable | some (q', s) := Λ'.act s q' end) | (Λ'.act (TM0.stmt.move d) q) := move d $ goto (λ _ _, Λ'.normal q) | (Λ'.act (TM0.stmt.write a) q) := write (λ _ _, a) $ goto (λ _ _, Λ'.normal q) /-- The configuration translation. -/ def tr_cfg : cfg₀ → cfg₁ | ⟨q, T⟩ := ⟨cond (M q T.1).is_some (some (Λ'.normal q)) none, (), T⟩ theorem tr_respects : respects (TM0.step M) (TM1.step tr) (λ a b, tr_cfg a = b) := fun_respects.2 $ λ ⟨q, T⟩, begin cases e : M q T.1, { simp only [TM0.step, tr_cfg, e]; exact eq.refl none }, cases val with q' s, simp only [frespects, TM0.step, tr_cfg, e, option.is_some, cond, option.map_some'], have : TM1.step (tr M) ⟨some (Λ'.act s q'), (), T⟩ = some ⟨some (Λ'.normal q'), (), TM0.step._match_1 T s⟩, { cases s with d a; refl }, refine trans_gen.head _ (trans_gen.head' this _), { unfold TM1.step TM1.step_aux tr has_mem.mem, rw e, refl }, cases e' : M q' _, { apply refl_trans_gen.single, unfold TM1.step TM1.step_aux tr has_mem.mem, rw e', refl }, { refl } end end end TM0to1 /-! ## The TM2 model The TM2 model removes the tape entirely from the TM1 model, replacing it with an arbitrary (finite) collection of stacks, each with elements of different types (the alphabet of stack `k : K` is `Γ k`). The statements are: * `push k (f : σ → Γ k) q` puts `f a` on the `k`-th stack, then does `q`. * `pop k (f : σ → option (Γ k) → σ) q` changes the state to `f a (S k).head`, where `S k` is the value of the `k`-th stack, and removes this element from the stack, then does `q`. * `peek k (f : σ → option (Γ k) → σ) q` changes the state to `f a (S k).head`, where `S k` is the value of the `k`-th stack, then does `q`. * `load (f : σ → σ) q` reads nothing but applies `f` to the internal state, then does `q`. * `branch (f : σ → bool) qtrue qfalse` does `qtrue` or `qfalse` according to `f a`. * `goto (f : σ → Λ)` jumps to label `f a`. * `halt` halts on the next step. The configuration is a tuple `(l, var, stk)` where `l : option Λ` is the current label to run or `none` for the halting state, `var : σ` is the (finite) internal state, and `stk : ∀ k, list (Γ k)` is the collection of stacks. (Note that unlike the `TM0` and `TM1` models, these are not `list_blank`s, they have definite ends that can be detected by the `pop` command.) Given a designated stack `k` and a value `L : list (Γ k)`, the initial configuration has all the stacks empty except the designated "input" stack; in `eval` this designated stack also functions as the output stack. -/ namespace TM2 section parameters {K : Type*} [decidable_eq K] -- Index type of stacks parameters (Γ : K → Type*) -- Type of stack elements parameters (Λ : Type*) -- Type of function labels parameters (σ : Type*) -- Type of variable settings /-- The TM2 model removes the tape entirely from the TM1 model, replacing it with an arbitrary (finite) collection of stacks. The operation `push` puts an element on one of the stacks, and `pop` removes an element from a stack (and modifying the internal state based on the result). `peek` modifies the internal state but does not remove an element. -/ inductive stmt | push : ∀ k, (σ → Γ k) → stmt → stmt | peek : ∀ k, (σ → option (Γ k) → σ) → stmt → stmt | pop : ∀ k, (σ → option (Γ k) → σ) → stmt → stmt | load : (σ → σ) → stmt → stmt | branch : (σ → bool) → stmt → stmt → stmt | goto : (σ → Λ) → stmt | halt : stmt open stmt instance stmt.inhabited : inhabited stmt := ⟨halt⟩ /-- A configuration in the TM2 model is a label (or `none` for the halt state), the state of local variables, and the stacks. (Note that the stacks are not `list_blank`s, they have a definite size.) -/ structure cfg := (l : option Λ) (var : σ) (stk : ∀ k, list (Γ k)) instance cfg.inhabited [inhabited σ] : inhabited cfg := ⟨⟨default _, default _, default _⟩⟩ parameters {Γ Λ σ K} /-- The step function for the TM2 model. -/ @[simp] def step_aux : stmt → σ → (∀ k, list (Γ k)) → cfg | (push k f q) v S := step_aux q v (update S k (f v :: S k)) | (peek k f q) v S := step_aux q (f v (S k).head') S | (pop k f q) v S := step_aux q (f v (S k).head') (update S k (S k).tail) | (load a q) v S := step_aux q (a v) S | (branch f q₁ q₂) v S := cond (f v) (step_aux q₁ v S) (step_aux q₂ v S) | (goto f) v S := ⟨some (f v), v, S⟩ | halt v S := ⟨none, v, S⟩ /-- The step function for the TM2 model. -/ @[simp] def step (M : Λ → stmt) : cfg → option cfg | ⟨none, v, S⟩ := none | ⟨some l, v, S⟩ := some (step_aux (M l) v S) /-- The (reflexive) reachability relation for the TM2 model. -/ def reaches (M : Λ → stmt) : cfg → cfg → Prop := refl_trans_gen (λ a b, b ∈ step M a) /-- Given a set `S` of states, `support_stmt S q` means that `q` only jumps to states in `S`. -/ def supports_stmt (S : finset Λ) : stmt → Prop | (push k f q) := supports_stmt q | (peek k f q) := supports_stmt q | (pop k f q) := supports_stmt q | (load a q) := supports_stmt q | (branch f q₁ q₂) := supports_stmt q₁ ∧ supports_stmt q₂ | (goto l) := ∀ v, l v ∈ S | halt := true open_locale classical /-- The set of subtree statements in a statement. -/ noncomputable def stmts₁ : stmt → finset stmt | Q@(push k f q) := insert Q (stmts₁ q) | Q@(peek k f q) := insert Q (stmts₁ q) | Q@(pop k f q) := insert Q (stmts₁ q) | Q@(load a q) := insert Q (stmts₁ q) | Q@(branch f q₁ q₂) := insert Q (stmts₁ q₁ ∪ stmts₁ q₂) | Q@(goto l) := {Q} | Q@halt := {Q} theorem stmts₁_self {q} : q ∈ stmts₁ q := by cases q; apply_rules [finset.mem_insert_self, finset.mem_singleton_self] theorem stmts₁_trans {q₁ q₂} : q₁ ∈ stmts₁ q₂ → stmts₁ q₁ ⊆ stmts₁ q₂ := begin intros h₁₂ q₀ h₀₁, induction q₂ with _ _ q IH _ _ q IH _ _ q IH _ q IH; simp only [stmts₁] at h₁₂ ⊢; simp only [finset.mem_insert, finset.mem_singleton, finset.mem_union] at h₁₂, iterate 4 { rcases h₁₂ with rfl | h₁₂, { unfold stmts₁ at h₀₁, exact h₀₁ }, { exact finset.mem_insert_of_mem (IH h₁₂) } }, case TM2.stmt.branch : f q₁ q₂ IH₁ IH₂ { rcases h₁₂ with rfl | h₁₂ | h₁₂, { unfold stmts₁ at h₀₁, exact h₀₁ }, { exact finset.mem_insert_of_mem (finset.mem_union_left _ (IH₁ h₁₂)) }, { exact finset.mem_insert_of_mem (finset.mem_union_right _ (IH₂ h₁₂)) } }, case TM2.stmt.goto : l { subst h₁₂, exact h₀₁ }, case TM2.stmt.halt { subst h₁₂, exact h₀₁ } end theorem stmts₁_supports_stmt_mono {S q₁ q₂} (h : q₁ ∈ stmts₁ q₂) (hs : supports_stmt S q₂) : supports_stmt S q₁ := begin induction q₂ with _ _ q IH _ _ q IH _ _ q IH _ q IH; simp only [stmts₁, supports_stmt, finset.mem_insert, finset.mem_union, finset.mem_singleton] at h hs, iterate 4 { rcases h with rfl | h; [exact hs, exact IH h hs] }, case TM2.stmt.branch : f q₁ q₂ IH₁ IH₂ { rcases h with rfl | h | h, exacts [hs, IH₁ h hs.1, IH₂ h hs.2] }, case TM2.stmt.goto : l { subst h, exact hs }, case TM2.stmt.halt { subst h, trivial } end /-- The set of statements accessible from initial set `S` of labels. -/ noncomputable def stmts (M : Λ → stmt) (S : finset Λ) : finset (option stmt) := (S.bUnion (λ q, stmts₁ (M q))).insert_none theorem stmts_trans {M : Λ → stmt} {S q₁ q₂} (h₁ : q₁ ∈ stmts₁ q₂) : some q₂ ∈ stmts M S → some q₁ ∈ stmts M S := by simp only [stmts, finset.mem_insert_none, finset.mem_bUnion, option.mem_def, forall_eq', exists_imp_distrib]; exact λ l ls h₂, ⟨_, ls, stmts₁_trans h₂ h₁⟩ variable [inhabited Λ] /-- Given a TM2 machine `M` and a set `S` of states, `supports M S` means that all states in `S` jump only to other states in `S`. -/ def supports (M : Λ → stmt) (S : finset Λ) := default Λ ∈ S ∧ ∀ q ∈ S, supports_stmt S (M q) theorem stmts_supports_stmt {M : Λ → stmt} {S q} (ss : supports M S) : some q ∈ stmts M S → supports_stmt S q := by simp only [stmts, finset.mem_insert_none, finset.mem_bUnion, option.mem_def, forall_eq', exists_imp_distrib]; exact λ l ls h, stmts₁_supports_stmt_mono h (ss.2 _ ls) theorem step_supports (M : Λ → stmt) {S} (ss : supports M S) : ∀ {c c' : cfg}, c' ∈ step M c → c.l ∈ S.insert_none → c'.l ∈ S.insert_none | ⟨some l₁, v, T⟩ c' h₁ h₂ := begin replace h₂ := ss.2 _ (finset.some_mem_insert_none.1 h₂), simp only [step, option.mem_def] at h₁, subst c', revert h₂, induction M l₁ with _ _ q IH _ _ q IH _ _ q IH _ q IH generalizing v T; intro hs, iterate 4 { exact IH _ _ hs }, case TM2.stmt.branch : p q₁' q₂' IH₁ IH₂ { unfold step_aux, cases p v, { exact IH₂ _ _ hs.2 }, { exact IH₁ _ _ hs.1 } }, case TM2.stmt.goto { exact finset.some_mem_insert_none.2 (hs _) }, case TM2.stmt.halt { apply multiset.mem_cons_self } end variable [inhabited σ] /-- The initial state of the TM2 model. The input is provided on a designated stack. -/ def init (k) (L : list (Γ k)) : cfg := ⟨some (default _), default _, update (λ _, []) k L⟩ /-- Evaluates a TM2 program to completion, with the output on the same stack as the input. -/ def eval (M : Λ → stmt) (k) (L : list (Γ k)) : part (list (Γ k)) := (eval (step M) (init k L)).map $ λ c, c.stk k end end TM2 /-! ## TM2 emulator in TM1 To prove that TM2 computable functions are TM1 computable, we need to reduce each TM2 program to a TM1 program. So suppose a TM2 program is given. This program has to maintain a whole collection of stacks, but we have only one tape, so we must "multiplex" them all together. Pictorially, if stack 1 contains `[a, b]` and stack 2 contains `[c, d, e, f]` then the tape looks like this: ``` bottom: ... | _ | T | _ | _ | _ | _ | ... stack 1: ... | _ | b | a | _ | _ | _ | ... stack 2: ... | _ | f | e | d | c | _ | ... ``` where a tape element is a vertical slice through the diagram. Here the alphabet is `Γ' := bool × ∀ k, option (Γ k)`, where: * `bottom : bool` is marked only in one place, the initial position of the TM, and represents the tail of all stacks. It is never modified. * `stk k : option (Γ k)` is the value of the `k`-th stack, if in range, otherwise `none` (which is the blank value). Note that the head of the stack is at the far end; this is so that push and pop don't have to do any shifting. In "resting" position, the TM is sitting at the position marked `bottom`. For non-stack actions, it operates in place, but for the stack actions `push`, `peek`, and `pop`, it must shuttle to the end of the appropriate stack, make its changes, and then return to the bottom. So the states are: * `normal (l : Λ)`: waiting at `bottom` to execute function `l` * `go k (s : st_act k) (q : stmt₂)`: travelling to the right to get to the end of stack `k` in order to perform stack action `s`, and later continue with executing `q` * `ret (q : stmt₂)`: travelling to the left after having performed a stack action, and executing `q` once we arrive Because of the shuttling, emulation overhead is `O(n)`, where `n` is the current maximum of the length of all stacks. Therefore a program that takes `k` steps to run in TM2 takes `O((m+k)k)` steps to run when emulated in TM1, where `m` is the length of the input. -/ namespace TM2to1 -- A displaced lemma proved in unnecessary generality theorem stk_nth_val {K : Type*} {Γ : K → Type*} {L : list_blank (∀ k, option (Γ k))} {k S} (n) (hL : list_blank.map (proj k) L = list_blank.mk (list.map some S).reverse) : L.nth n k = S.reverse.nth n := begin rw [← proj_map_nth, hL, ← list.map_reverse, list_blank.nth_mk, list.inth, list.nth_map], cases S.reverse.nth n; refl end section parameters {K : Type*} [decidable_eq K] parameters {Γ : K → Type*} parameters {Λ : Type*} [inhabited Λ] parameters {σ : Type*} [inhabited σ] local notation `stmt₂` := TM2.stmt Γ Λ σ local notation `cfg₂` := TM2.cfg Γ Λ σ /-- The alphabet of the TM2 simulator on TM1 is a marker for the stack bottom, plus a vector of stack elements for each stack, or none if the stack does not extend this far. -/ @[nolint unused_arguments] -- [decidable_eq K]: Because K is a parameter, we cannot easily skip -- the decidable_eq assumption, and this is a local definition anyway so it's not important. def Γ' := bool × ∀ k, option (Γ k) instance Γ'.inhabited : inhabited Γ' := ⟨⟨ff, λ _, none⟩⟩ instance Γ'.fintype [fintype K] [∀ k, fintype (Γ k)] : fintype Γ' := prod.fintype _ _ /-- The bottom marker is fixed throughout the calculation, so we use the `add_bottom` function to express the program state in terms of a tape with only the stacks themselves. -/ def add_bottom (L : list_blank (∀ k, option (Γ k))) : list_blank Γ' := list_blank.cons (tt, L.head) (L.tail.map ⟨prod.mk ff, rfl⟩) theorem add_bottom_map (L) : (add_bottom L).map ⟨prod.snd, rfl⟩ = L := begin simp only [add_bottom, list_blank.map_cons]; convert list_blank.cons_head_tail _, generalize : list_blank.tail L = L', refine L'.induction_on _, intro l, simp, rw (_ : _ ∘ _ = id), {simp}, funext a, refl end theorem add_bottom_modify_nth (f : (∀ k, option (Γ k)) → (∀ k, option (Γ k))) (L n) : (add_bottom L).modify_nth (λ a, (a.1, f a.2)) n = add_bottom (L.modify_nth f n) := begin cases n; simp only [add_bottom, list_blank.head_cons, list_blank.modify_nth, list_blank.tail_cons], congr, symmetry, apply list_blank.map_modify_nth, intro, refl end theorem add_bottom_nth_snd (L n) : ((add_bottom L).nth n).2 = L.nth n := by conv {to_rhs, rw [← add_bottom_map L, list_blank.nth_map]}; refl theorem add_bottom_nth_succ_fst (L n) : ((add_bottom L).nth (n+1)).1 = ff := by rw [list_blank.nth_succ, add_bottom, list_blank.tail_cons, list_blank.nth_map]; refl theorem add_bottom_head_fst (L) : (add_bottom L).head.1 = tt := by rw [add_bottom, list_blank.head_cons]; refl /-- A stack action is a command that interacts with the top of a stack. Our default position is at the bottom of all the stacks, so we have to hold on to this action while going to the end to modify the stack. -/ inductive st_act (k : K) | push : (σ → Γ k) → st_act | peek : (σ → option (Γ k) → σ) → st_act | pop : (σ → option (Γ k) → σ) → st_act instance st_act.inhabited {k} : inhabited (st_act k) := ⟨st_act.peek (λ s _, s)⟩ section open st_act /-- The TM2 statement corresponding to a stack action. -/ @[nolint unused_arguments] -- [inhabited Λ]: as this is a local definition it is more trouble than -- it is worth to omit the typeclass assumption without breaking the parameters def st_run {k : K} : st_act k → stmt₂ → stmt₂ | (push f) := TM2.stmt.push k f | (peek f) := TM2.stmt.peek k f | (pop f) := TM2.stmt.pop k f /-- The effect of a stack action on the local variables, given the value of the stack. -/ def st_var {k : K} (v : σ) (l : list (Γ k)) : st_act k → σ | (push f) := v | (peek f) := f v l.head' | (pop f) := f v l.head' /-- The effect of a stack action on the stack. -/ def st_write {k : K} (v : σ) (l : list (Γ k)) : st_act k → list (Γ k) | (push f) := f v :: l | (peek f) := l | (pop f) := l.tail /-- We have partitioned the TM2 statements into "stack actions", which require going to the end of the stack, and all other actions, which do not. This is a modified recursor which lumps the stack actions into one. -/ @[elab_as_eliminator] def {l} stmt_st_rec {C : stmt₂ → Sort l} (H₁ : Π k (s : st_act k) q (IH : C q), C (st_run s q)) (H₂ : Π a q (IH : C q), C (TM2.stmt.load a q)) (H₃ : Π p q₁ q₂ (IH₁ : C q₁) (IH₂ : C q₂), C (TM2.stmt.branch p q₁ q₂)) (H₄ : Π l, C (TM2.stmt.goto l)) (H₅ : C TM2.stmt.halt) : ∀ n, C n | (TM2.stmt.push k f q) := H₁ _ (push f) _ (stmt_st_rec q) | (TM2.stmt.peek k f q) := H₁ _ (peek f) _ (stmt_st_rec q) | (TM2.stmt.pop k f q) := H₁ _ (pop f) _ (stmt_st_rec q) | (TM2.stmt.load a q) := H₂ _ _ (stmt_st_rec q) | (TM2.stmt.branch a q₁ q₂) := H₃ _ _ _ (stmt_st_rec q₁) (stmt_st_rec q₂) | (TM2.stmt.goto l) := H₄ _ | TM2.stmt.halt := H₅ theorem supports_run (S : finset Λ) {k} (s : st_act k) (q) : TM2.supports_stmt S (st_run s q) ↔ TM2.supports_stmt S q := by rcases s with _|_|_; refl end /-- The machine states of the TM2 emulator. We can either be in a normal state when waiting for the next TM2 action, or we can be in the "go" and "return" states to go to the top of the stack and return to the bottom, respectively. -/ inductive Λ' : Type (max u_1 u_2 u_3 u_4) | normal : Λ → Λ' | go (k) : st_act k → stmt₂ → Λ' | ret : stmt₂ → Λ' open Λ' instance Λ'.inhabited : inhabited Λ' := ⟨normal (default _)⟩ local notation `stmt₁` := TM1.stmt Γ' Λ' σ local notation `cfg₁` := TM1.cfg Γ' Λ' σ open TM1.stmt /-- The program corresponding to state transitions at the end of a stack. Here we start out just after the top of the stack, and should end just after the new top of the stack. -/ def tr_st_act {k} (q : stmt₁) : st_act k → stmt₁ | (st_act.push f) := write (λ a s, (a.1, update a.2 k $ some $ f s)) $ move dir.right q | (st_act.peek f) := move dir.left $ load (λ a s, f s (a.2 k)) $ move dir.right q | (st_act.pop f) := branch (λ a _, a.1) ( load (λ a s, f s none) q ) ( move dir.left $ load (λ a s, f s (a.2 k)) $ write (λ a s, (a.1, update a.2 k none)) q ) /-- The initial state for the TM2 emulator, given an initial TM2 state. All stacks start out empty except for the input stack, and the stack bottom mark is set at the head. -/ def tr_init (k) (L : list (Γ k)) : list Γ' := let L' : list Γ' := L.reverse.map (λ a, (ff, update (λ _, none) k a)) in (tt, L'.head.2) :: L'.tail theorem step_run {k : K} (q v S) : ∀ s : st_act k, TM2.step_aux (st_run s q) v S = TM2.step_aux q (st_var v (S k) s) (update S k (st_write v (S k) s)) | (st_act.push f) := rfl | (st_act.peek f) := by unfold st_write; rw function.update_eq_self; refl | (st_act.pop f) := rfl /-- The translation of TM2 statements to TM1 statements. regular actions have direct equivalents, but stack actions are deferred by going to the corresponding `go` state, so that we can find the appropriate stack top. -/ def tr_normal : stmt₂ → stmt₁ | (TM2.stmt.push k f q) := goto (λ _ _, go k (st_act.push f) q) | (TM2.stmt.peek k f q) := goto (λ _ _, go k (st_act.peek f) q) | (TM2.stmt.pop k f q) := goto (λ _ _, go k (st_act.pop f) q) | (TM2.stmt.load a q) := load (λ _, a) (tr_normal q) | (TM2.stmt.branch f q₁ q₂) := branch (λ a, f) (tr_normal q₁) (tr_normal q₂) | (TM2.stmt.goto l) := goto (λ a s, normal (l s)) | TM2.stmt.halt := halt theorem tr_normal_run {k} (s q) : tr_normal (st_run s q) = goto (λ _ _, go k s q) := by rcases s with _|_|_; refl open_locale classical /-- The set of machine states accessible from an initial TM2 statement. -/ noncomputable def tr_stmts₁ : stmt₂ → finset Λ' | Q@(TM2.stmt.push k f q) := {go k (st_act.push f) q, ret q} ∪ tr_stmts₁ q | Q@(TM2.stmt.peek k f q) := {go k (st_act.peek f) q, ret q} ∪ tr_stmts₁ q | Q@(TM2.stmt.pop k f q) := {go k (st_act.pop f) q, ret q} ∪ tr_stmts₁ q | Q@(TM2.stmt.load a q) := tr_stmts₁ q | Q@(TM2.stmt.branch f q₁ q₂) := tr_stmts₁ q₁ ∪ tr_stmts₁ q₂ | _ := ∅ theorem tr_stmts₁_run {k s q} : tr_stmts₁ (st_run s q) = {go k s q, ret q} ∪ tr_stmts₁ q := by rcases s with _|_|_; unfold tr_stmts₁ st_run theorem tr_respects_aux₂ {k q v} {S : Π k, list (Γ k)} {L : list_blank (∀ k, option (Γ k))} (hL : ∀ k, L.map (proj k) = list_blank.mk ((S k).map some).reverse) (o) : let v' := st_var v (S k) o, Sk' := st_write v (S k) o, S' := update S k Sk' in ∃ (L' : list_blank (∀ k, option (Γ k))), (∀ k, L'.map (proj k) = list_blank.mk ((S' k).map some).reverse) ∧ TM1.step_aux (tr_st_act q o) v ((tape.move dir.right)^[(S k).length] (tape.mk' ∅ (add_bottom L))) = TM1.step_aux q v' ((tape.move dir.right)^[(S' k).length] (tape.mk' ∅ (add_bottom L'))) := begin dsimp only, simp, cases o; simp only [st_write, st_var, tr_st_act, TM1.step_aux], case TM2to1.st_act.push : f { have := tape.write_move_right_n (λ a : Γ', (a.1, update a.2 k (some (f v)))), dsimp only at this, refine ⟨_, λ k', _, by rw [ tape.move_right_n_head, list.length, tape.mk'_nth_nat, this, add_bottom_modify_nth (λ a, update a k (some (f v))), nat.add_one, iterate_succ']⟩, refine list_blank.ext (λ i, _), rw [list_blank.nth_map, list_blank.nth_modify_nth, proj, pointed_map.mk_val], by_cases h' : k' = k, { subst k', split_ifs; simp only [list.reverse_cons, function.update_same, list_blank.nth_mk, list.inth, list.map], { rw [list.nth_le_nth, list.nth_le_append_right]; simp only [h, list.nth_le_singleton, list.length_map, list.length_reverse, nat.succ_pos', list.length_append, lt_add_iff_pos_right, list.length] }, rw [← proj_map_nth, hL, list_blank.nth_mk, list.inth], cases lt_or_gt_of_ne h with h h, { rw list.nth_append, simpa only [list.length_map, list.length_reverse] using h }, { rw gt_iff_lt at h, rw [list.nth_len_le, list.nth_len_le]; simp only [nat.add_one_le_iff, h, list.length, le_of_lt, list.length_reverse, list.length_append, list.length_map] } }, { split_ifs; rw [function.update_noteq h', ← proj_map_nth, hL], rw function.update_noteq h' } }, case TM2to1.st_act.peek : f { rw function.update_eq_self, use [L, hL], rw [tape.move_left_right], congr, cases e : S k, {refl}, rw [list.length_cons, iterate_succ', tape.move_right_left, tape.move_right_n_head, tape.mk'_nth_nat, add_bottom_nth_snd, stk_nth_val _ (hL k), e, list.reverse_cons, ← list.length_reverse, list.nth_concat_length], refl }, case TM2to1.st_act.pop : f { cases e : S k, { simp only [tape.mk'_head, list_blank.head_cons, tape.move_left_mk', list.length, tape.write_mk', list.head', iterate_zero_apply, list.tail_nil], rw [← e, function.update_eq_self], exact ⟨L, hL, by rw [add_bottom_head_fst, cond]⟩ }, { refine ⟨_, λ k', _, by rw [ list.length_cons, tape.move_right_n_head, tape.mk'_nth_nat, add_bottom_nth_succ_fst, cond, iterate_succ', tape.move_right_left, tape.move_right_n_head, tape.mk'_nth_nat, tape.write_move_right_n (λ a:Γ', (a.1, update a.2 k none)), add_bottom_modify_nth (λ a, update a k none), add_bottom_nth_snd, stk_nth_val _ (hL k), e, show (list.cons hd tl).reverse.nth tl.length = some hd, by rw [list.reverse_cons, ← list.length_reverse, list.nth_concat_length]; refl, list.head', list.tail]⟩, refine list_blank.ext (λ i, _), rw [list_blank.nth_map, list_blank.nth_modify_nth, proj, pointed_map.mk_val], by_cases h' : k' = k, { subst k', split_ifs; simp only [ function.update_same, list_blank.nth_mk, list.tail, list.inth], { rw [list.nth_len_le], {refl}, rw [h, list.length_reverse, list.length_map] }, rw [← proj_map_nth, hL, list_blank.nth_mk, list.inth, e, list.map, list.reverse_cons], cases lt_or_gt_of_ne h with h h, { rw list.nth_append, simpa only [list.length_map, list.length_reverse] using h }, { rw gt_iff_lt at h, rw [list.nth_len_le, list.nth_len_le]; simp only [nat.add_one_le_iff, h, list.length, le_of_lt, list.length_reverse, list.length_append, list.length_map] } }, { split_ifs; rw [function.update_noteq h', ← proj_map_nth, hL], rw function.update_noteq h' } } }, end parameters (M : Λ → stmt₂) include M /-- The TM2 emulator machine states written as a TM1 program. This handles the `go` and `ret` states, which shuttle to and from a stack top. -/ def tr : Λ' → stmt₁ | (normal q) := tr_normal (M q) | (go k s q) := branch (λ a s, (a.2 k).is_none) (tr_st_act (goto (λ _ _, ret q)) s) (move dir.right $ goto (λ _ _, go k s q)) | (ret q) := branch (λ a s, a.1) (tr_normal q) (move dir.left $ goto (λ _ _, ret q)) local attribute [pp_using_anonymous_constructor] turing.TM1.cfg /-- The relation between TM2 configurations and TM1 configurations of the TM2 emulator. -/ inductive tr_cfg : cfg₂ → cfg₁ → Prop | mk {q v} {S : ∀ k, list (Γ k)} (L : list_blank (∀ k, option (Γ k))) : (∀ k, L.map (proj k) = list_blank.mk ((S k).map some).reverse) → tr_cfg ⟨q, v, S⟩ ⟨q.map normal, v, tape.mk' ∅ (add_bottom L)⟩ theorem tr_respects_aux₁ {k} (o q v) {S : list (Γ k)} {L : list_blank (∀ k, option (Γ k))} (hL : L.map (proj k) = list_blank.mk (S.map some).reverse) (n ≤ S.length) : reaches₀ (TM1.step tr) ⟨some (go k o q), v, (tape.mk' ∅ (add_bottom L))⟩ ⟨some (go k o q), v, (tape.move dir.right)^[n] (tape.mk' ∅ (add_bottom L))⟩ := begin induction n with n IH, {refl}, apply (IH (le_of_lt H)).tail, rw iterate_succ_apply', simp only [TM1.step, TM1.step_aux, tr, tape.mk'_nth_nat, tape.move_right_n_head, add_bottom_nth_snd, option.mem_def], rw [stk_nth_val _ hL, list.nth_le_nth], refl, rwa list.length_reverse end theorem tr_respects_aux₃ {q v} {L : list_blank (∀ k, option (Γ k))} (n) : reaches₀ (TM1.step tr) ⟨some (ret q), v, (tape.move dir.right)^[n] (tape.mk' ∅ (add_bottom L))⟩ ⟨some (ret q), v, (tape.mk' ∅ (add_bottom L))⟩ := begin induction n with n IH, {refl}, refine reaches₀.head _ IH, rw [option.mem_def, TM1.step, tr, TM1.step_aux, tape.move_right_n_head, tape.mk'_nth_nat, add_bottom_nth_succ_fst, TM1.step_aux, iterate_succ', tape.move_right_left], refl, end theorem tr_respects_aux {q v T k} {S : Π k, list (Γ k)} (hT : ∀ k, list_blank.map (proj k) T = list_blank.mk ((S k).map some).reverse) (o : st_act k) (IH : ∀ {v : σ} {S : Π (k : K), list (Γ k)} {T : list_blank (∀ k, option (Γ k))}, (∀ k, list_blank.map (proj k) T = list_blank.mk ((S k).map some).reverse) → (∃ b, tr_cfg (TM2.step_aux q v S) b ∧ reaches (TM1.step tr) (TM1.step_aux (tr_normal q) v (tape.mk' ∅ (add_bottom T))) b)) : ∃ b, tr_cfg (TM2.step_aux (st_run o q) v S) b ∧ reaches (TM1.step tr) (TM1.step_aux (tr_normal (st_run o q)) v (tape.mk' ∅ (add_bottom T))) b := begin simp only [tr_normal_run, step_run], have hgo := tr_respects_aux₁ M o q v (hT k) _ (le_refl _), obtain ⟨T', hT', hrun⟩ := tr_respects_aux₂ hT o, have hret := tr_respects_aux₃ M _, have := hgo.tail' rfl, rw [tr, TM1.step_aux, tape.move_right_n_head, tape.mk'_nth_nat, add_bottom_nth_snd, stk_nth_val _ (hT k), list.nth_len_le (le_of_eq (list.length_reverse _)), option.is_none, cond, hrun, TM1.step_aux] at this, obtain ⟨c, gc, rc⟩ := IH hT', refine ⟨c, gc, (this.to₀.trans hret c (trans_gen.head' rfl _)).to_refl⟩, rw [tr, TM1.step_aux, tape.mk'_head, add_bottom_head_fst], exact rc, end local attribute [simp] respects TM2.step TM2.step_aux tr_normal theorem tr_respects : respects (TM2.step M) (TM1.step tr) tr_cfg := λ c₁ c₂ h, begin cases h with l v S L hT, clear h, cases l, {constructor}, simp only [TM2.step, respects, option.map_some'], suffices : ∃ b, _ ∧ reaches (TM1.step (tr M)) _ _, from let ⟨b, c, r⟩ := this in ⟨b, c, trans_gen.head' rfl r⟩, rw [tr], revert v S L hT, refine stmt_st_rec _ _ _ _ _ (M l); intros, { exact tr_respects_aux M hT s @IH }, { exact IH _ hT }, { unfold TM2.step_aux tr_normal TM1.step_aux, cases p v; [exact IH₂ _ hT, exact IH₁ _ hT] }, { exact ⟨_, ⟨_, hT⟩, refl_trans_gen.refl⟩ }, { exact ⟨_, ⟨_, hT⟩, refl_trans_gen.refl⟩ } end theorem tr_cfg_init (k) (L : list (Γ k)) : tr_cfg (TM2.init k L) (TM1.init (tr_init k L)) := begin rw (_ : TM1.init _ = _), { refine ⟨list_blank.mk (L.reverse.map $ λ a, update (default _) k (some a)), λ k', _⟩, refine list_blank.ext (λ i, _), rw [list_blank.map_mk, list_blank.nth_mk, list.inth, list.map_map, (∘), list.nth_map, proj, pointed_map.mk_val], by_cases k' = k, { subst k', simp only [function.update_same], rw [list_blank.nth_mk, list.inth, ← list.map_reverse, list.nth_map] }, { simp only [function.update_noteq h], rw [list_blank.nth_mk, list.inth, list.map, list.reverse_nil, list.nth], cases L.reverse.nth i; refl } }, { rw [tr_init, TM1.init], dsimp only, congr; cases L.reverse; try {refl}, simp only [list.map_map, list.tail_cons, list.map], refl } end theorem tr_eval_dom (k) (L : list (Γ k)) : (TM1.eval tr (tr_init k L)).dom ↔ (TM2.eval M k L).dom := tr_eval_dom tr_respects (tr_cfg_init _ _) theorem tr_eval (k) (L : list (Γ k)) {L₁ L₂} (H₁ : L₁ ∈ TM1.eval tr (tr_init k L)) (H₂ : L₂ ∈ TM2.eval M k L) : ∃ (S : ∀ k, list (Γ k)) (L' : list_blank (∀ k, option (Γ k))), add_bottom L' = L₁ ∧ (∀ k, L'.map (proj k) = list_blank.mk ((S k).map some).reverse) ∧ S k = L₂ := begin obtain ⟨c₁, h₁, rfl⟩ := (part.mem_map_iff _).1 H₁, obtain ⟨c₂, h₂, rfl⟩ := (part.mem_map_iff _).1 H₂, obtain ⟨_, ⟨q, v, S, L', hT⟩, h₃⟩ := tr_eval (tr_respects M) (tr_cfg_init M k L) h₂, cases part.mem_unique h₁ h₃, exact ⟨S, L', by simp only [tape.mk'_right₀], hT, rfl⟩ end /-- The support of a set of TM2 states in the TM2 emulator. -/ noncomputable def tr_supp (S : finset Λ) : finset Λ' := S.bUnion (λ l, insert (normal l) (tr_stmts₁ (M l))) theorem tr_supports {S} (ss : TM2.supports M S) : TM1.supports tr (tr_supp S) := ⟨finset.mem_bUnion.2 ⟨_, ss.1, finset.mem_insert.2 $ or.inl rfl⟩, λ l' h, begin suffices : ∀ q (ss' : TM2.supports_stmt S q) (sub : ∀ x ∈ tr_stmts₁ q, x ∈ tr_supp M S), TM1.supports_stmt (tr_supp M S) (tr_normal q) ∧ (∀ l' ∈ tr_stmts₁ q, TM1.supports_stmt (tr_supp M S) (tr M l')), { rcases finset.mem_bUnion.1 h with ⟨l, lS, h⟩, have := this _ (ss.2 l lS) (λ x hx, finset.mem_bUnion.2 ⟨_, lS, finset.mem_insert_of_mem hx⟩), rcases finset.mem_insert.1 h with rfl | h; [exact this.1, exact this.2 _ h] }, clear h l', refine stmt_st_rec _ _ _ _ _; intros, { -- stack op rw TM2to1.supports_run at ss', simp only [TM2to1.tr_stmts₁_run, finset.mem_union, finset.mem_insert, finset.mem_singleton] at sub, have hgo := sub _ (or.inl $ or.inl rfl), have hret := sub _ (or.inl $ or.inr rfl), cases IH ss' (λ x hx, sub x $ or.inr hx) with IH₁ IH₂, refine ⟨by simp only [tr_normal_run, TM1.supports_stmt]; intros; exact hgo, λ l h, _⟩, rw [tr_stmts₁_run] at h, simp only [TM2to1.tr_stmts₁_run, finset.mem_union, finset.mem_insert, finset.mem_singleton] at h, rcases h with ⟨rfl | rfl⟩ | h, { unfold TM1.supports_stmt TM2to1.tr, rcases s with _|_|_, { exact ⟨λ _ _, hret, λ _ _, hgo⟩ }, { exact ⟨λ _ _, hret, λ _ _, hgo⟩ }, { exact ⟨⟨λ _ _, hret, λ _ _, hret⟩, λ _ _, hgo⟩ } }, { unfold TM1.supports_stmt TM2to1.tr, exact ⟨IH₁, λ _ _, hret⟩ }, { exact IH₂ _ h } }, { -- load unfold TM2to1.tr_stmts₁ at ss' sub ⊢, exact IH ss' sub }, { -- branch unfold TM2to1.tr_stmts₁ at sub, cases IH₁ ss'.1 (λ x hx, sub x $ finset.mem_union_left _ hx) with IH₁₁ IH₁₂, cases IH₂ ss'.2 (λ x hx, sub x $ finset.mem_union_right _ hx) with IH₂₁ IH₂₂, refine ⟨⟨IH₁₁, IH₂₁⟩, λ l h, _⟩, rw [tr_stmts₁] at h, rcases finset.mem_union.1 h with h | h; [exact IH₁₂ _ h, exact IH₂₂ _ h] }, { -- goto rw tr_stmts₁, unfold TM2to1.tr_normal TM1.supports_stmt, unfold TM2.supports_stmt at ss', exact ⟨λ _ v, finset.mem_bUnion.2 ⟨_, ss' v, finset.mem_insert_self _ _⟩, λ _, false.elim⟩ }, { exact ⟨trivial, λ _, false.elim⟩ } -- halt end⟩ end end TM2to1 end turing
9212edd5e366569cc8afafa43880eb439d4d57ab
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/measure_theory/measure/haar/normed_space.lean
f4cae461859496b6165750f017dfd6f2f0b08090
[ "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
8,550
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, Sébastien Gouëzel -/ import measure_theory.measure.lebesgue.eq_haar import measure_theory.integral.bochner /-! # Basic properties of Haar measures on real vector spaces > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. -/ noncomputable theory open_locale nnreal ennreal pointwise big_operators topology open has_inv set function measure_theory.measure filter open measure finite_dimensional namespace measure_theory namespace measure /- The instance `is_add_haar_measure.has_no_atoms` applies in particular to show that an additive Haar measure on a nontrivial finite-dimensional real vector space has no atom. -/ example {E : Type*} [normed_add_comm_group E] [normed_space ℝ E] [nontrivial E] [finite_dimensional ℝ E] [measurable_space E] [borel_space E] (μ : measure E) [is_add_haar_measure μ] : has_no_atoms μ := by apply_instance section continuous_linear_equiv variables {𝕜 G H : Type*} [measurable_space G] [measurable_space H] [nontrivially_normed_field 𝕜] [topological_space G] [topological_space H] [add_comm_group G] [add_comm_group H] [topological_add_group G] [topological_add_group H] [module 𝕜 G] [module 𝕜 H] (μ : measure G) [is_add_haar_measure μ] [borel_space G] [borel_space H] [t2_space H] instance map_continuous_linear_equiv.is_add_haar_measure (e : G ≃L[𝕜] H) : is_add_haar_measure (μ.map e) := e.to_add_equiv.is_add_haar_measure_map _ e.continuous e.symm.continuous variables [complete_space 𝕜] [t2_space G] [finite_dimensional 𝕜 G] [has_continuous_smul 𝕜 G] [has_continuous_smul 𝕜 H] instance map_linear_equiv.is_add_haar_measure (e : G ≃ₗ[𝕜] H) : is_add_haar_measure (μ.map e) := map_continuous_linear_equiv.is_add_haar_measure _ e.to_continuous_linear_equiv end continuous_linear_equiv variables {E : Type*} [normed_add_comm_group E] [normed_space ℝ E] [measurable_space E] [borel_space E] [finite_dimensional ℝ E] (μ : measure E) [is_add_haar_measure μ] {F : Type*} [normed_add_comm_group F] [normed_space ℝ F] [complete_space F] variables (μ) {s : set E} /-- The integral of `f (R • x)` with respect to an additive Haar measure is a multiple of the integral of `f`. The formula we give works even when `f` is not integrable or `R = 0` thanks to the convention that a non-integrable function has integral zero. -/ lemma integral_comp_smul (f : E → F) (R : ℝ) : ∫ x, f (R • x) ∂μ = |(R ^ finrank ℝ E)⁻¹| • ∫ x, f x ∂μ := begin rcases eq_or_ne R 0 with rfl|hR, { simp only [zero_smul, integral_const], rcases nat.eq_zero_or_pos (finrank ℝ E) with hE|hE, { haveI : subsingleton E, from finrank_zero_iff.1 hE, have : f = (λ x, f 0), { ext x, rw subsingleton.elim x 0 }, conv_rhs { rw this }, simp only [hE, pow_zero, inv_one, abs_one, one_smul, integral_const] }, { haveI : nontrivial E, from finrank_pos_iff.1 hE, simp only [zero_pow hE, measure_univ_of_is_add_left_invariant, ennreal.top_to_real, zero_smul, inv_zero, abs_zero]} }, { calc ∫ x, f (R • x) ∂μ = ∫ y, f y ∂(measure.map (λ x, R • x) μ) : (integral_map_equiv (homeomorph.smul (is_unit_iff_ne_zero.2 hR).unit) .to_measurable_equiv f).symm ... = |(R ^ finrank ℝ E)⁻¹| • ∫ x, f x ∂μ : by simp only [map_add_haar_smul μ hR, integral_smul_measure, ennreal.to_real_of_real, abs_nonneg] } end /-- The integral of `f (R • x)` with respect to an additive Haar measure is a multiple of the integral of `f`. The formula we give works even when `f` is not integrable or `R = 0` thanks to the convention that a non-integrable function has integral zero. -/ lemma integral_comp_smul_of_nonneg (f : E → F) (R : ℝ) {hR : 0 ≤ R} : ∫ x, f (R • x) ∂μ = (R ^ finrank ℝ E)⁻¹ • ∫ x, f x ∂μ := by rw [integral_comp_smul μ f R, abs_of_nonneg (inv_nonneg.2 (pow_nonneg hR _))] /-- The integral of `f (R⁻¹ • x)` with respect to an additive Haar measure is a multiple of the integral of `f`. The formula we give works even when `f` is not integrable or `R = 0` thanks to the convention that a non-integrable function has integral zero. -/ lemma integral_comp_inv_smul (f : E → F) (R : ℝ) : ∫ x, f (R⁻¹ • x) ∂μ = |(R ^ finrank ℝ E)| • ∫ x, f x ∂μ := by rw [integral_comp_smul μ f (R⁻¹), inv_pow, inv_inv] /-- The integral of `f (R⁻¹ • x)` with respect to an additive Haar measure is a multiple of the integral of `f`. The formula we give works even when `f` is not integrable or `R = 0` thanks to the convention that a non-integrable function has integral zero. -/ lemma integral_comp_inv_smul_of_nonneg (f : E → F) {R : ℝ} (hR : 0 ≤ R) : ∫ x, f (R⁻¹ • x) ∂μ = R ^ finrank ℝ E • ∫ x, f x ∂μ := by rw [integral_comp_inv_smul μ f R, abs_of_nonneg ((pow_nonneg hR _))] lemma integral_comp_mul_left (g : ℝ → F) (a : ℝ) : ∫ x : ℝ, g (a * x) = |a⁻¹| • ∫ y : ℝ, g y := by simp_rw [←smul_eq_mul, measure.integral_comp_smul, finite_dimensional.finrank_self, pow_one] lemma integral_comp_inv_mul_left (g : ℝ → F) (a : ℝ) : ∫ x : ℝ, g (a⁻¹ * x) = |a| • ∫ y : ℝ, g y := by simp_rw [←smul_eq_mul, measure.integral_comp_inv_smul, finite_dimensional.finrank_self, pow_one] lemma integral_comp_mul_right (g : ℝ → F) (a : ℝ) : ∫ x : ℝ, g (x * a) = |a⁻¹| • ∫ y : ℝ, g y := by simpa only [mul_comm] using integral_comp_mul_left g a lemma integral_comp_inv_mul_right (g : ℝ → F) (a : ℝ) : ∫ x : ℝ, g (x * a⁻¹) = |a| • ∫ y : ℝ, g y := by simpa only [mul_comm] using integral_comp_inv_mul_left g a lemma integral_comp_div (g : ℝ → F) (a : ℝ) : ∫ x : ℝ, g (x / a) = |a| • ∫ y : ℝ, g y := integral_comp_inv_mul_right g a end measure variables {F : Type*} [normed_add_comm_group F] lemma integrable_comp_smul_iff {E : Type*} [normed_add_comm_group E] [normed_space ℝ E] [measurable_space E] [borel_space E] [finite_dimensional ℝ E] (μ : measure E) [is_add_haar_measure μ] (f : E → F) {R : ℝ} (hR : R ≠ 0) : integrable (λ x, f (R • x)) μ ↔ integrable f μ := begin -- reduce to one-way implication suffices : ∀ {g : E → F} (hg : integrable g μ) {S : ℝ} (hS : S ≠ 0), integrable (λ x, g (S • x)) μ, { refine ⟨λ hf, _, λ hf, this hf hR⟩, convert this hf (inv_ne_zero hR), ext1 x, rw [←mul_smul, mul_inv_cancel hR, one_smul], }, -- now prove intros g hg S hS, let t := ((homeomorph.smul (is_unit_iff_ne_zero.2 hS).unit).to_measurable_equiv : E ≃ᵐ E), refine (integrable_map_equiv t g).mp (_ : integrable g (map (has_smul.smul S) μ)), rwa [map_add_haar_smul μ hS, integrable_smul_measure _ ennreal.of_real_ne_top], simpa only [ne.def, ennreal.of_real_eq_zero, not_le, abs_pos] using inv_ne_zero (pow_ne_zero _ hS), end lemma integrable.comp_smul {E : Type*} [normed_add_comm_group E] [normed_space ℝ E] [measurable_space E] [borel_space E] [finite_dimensional ℝ E] {μ : measure E} [is_add_haar_measure μ] {f : E → F} (hf : integrable f μ) {R : ℝ} (hR : R ≠ 0) : integrable (λ x, f (R • x)) μ := (integrable_comp_smul_iff μ f hR).2 hf lemma integrable_comp_mul_left_iff (g : ℝ → F) {R : ℝ} (hR : R ≠ 0) : integrable (λ x, g (R * x)) ↔ integrable g := by simpa only [smul_eq_mul] using integrable_comp_smul_iff volume g hR lemma integrable.comp_mul_left' {g : ℝ → F} (hg : integrable g) {R : ℝ} (hR : R ≠ 0) : integrable (λ x, g (R * x)) := (integrable_comp_mul_left_iff g hR).2 hg lemma integrable_comp_mul_right_iff (g : ℝ → F) {R : ℝ} (hR : R ≠ 0) : integrable (λ x, g (x * R)) ↔ integrable g := by simpa only [mul_comm] using integrable_comp_mul_left_iff g hR lemma integrable.comp_mul_right' {g : ℝ → F} (hg : integrable g) {R : ℝ} (hR : R ≠ 0) : integrable (λ x, g (x * R)) := (integrable_comp_mul_right_iff g hR).2 hg lemma integrable_comp_div_iff (g : ℝ → F) {R : ℝ} (hR : R ≠ 0) : integrable (λ x, g (x / R)) ↔ integrable g := integrable_comp_mul_right_iff g (inv_ne_zero hR) lemma integrable.comp_div {g : ℝ → F} (hg : integrable g) {R : ℝ} (hR : R ≠ 0) : integrable (λ x, g (x / R)) := (integrable_comp_div_iff g hR).2 hg end measure_theory
ef6a61b7b7bcd55da9cf0f2a7fcd79859510b059
27a31d06bcfc7c5d379fd04a08a9f5ed3f5302d4
/src/Lean/Data/KVMap.lean
fee7652bcea6e977c900f1b38249d3f1ddc31691
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
joehendrix/lean4
0d1486945f7ca9fe225070374338f4f7e74bab03
1221bdd3c7d5395baa451ce8fdd2c2f8a00cbc8f
refs/heads/master
1,640,573,727,861
1,639,662,710,000
1,639,665,515,000
198,893,504
0
0
Apache-2.0
1,564,084,645,000
1,564,084,644,000
null
UTF-8
Lean
false
false
6,092
lean
/- Copyright (c) 2018 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Data.Name namespace Lean inductive DataValue where | ofString (v : String) | ofBool (v : Bool) | ofName (v : Name) | ofNat (v : Nat) | ofInt (v : Int) deriving Inhabited, BEq @[export lean_mk_bool_data_value] def mkBoolDataValueEx (b : Bool) : DataValue := DataValue.ofBool b @[export lean_data_value_bool] def DataValue.getBoolEx : DataValue → Bool | DataValue.ofBool b => b | _ => false def DataValue.sameCtor : DataValue → DataValue → Bool | DataValue.ofString _, DataValue.ofString _ => true | DataValue.ofBool _, DataValue.ofBool _ => true | DataValue.ofName _, DataValue.ofName _ => true | DataValue.ofNat _, DataValue.ofNat _ => true | DataValue.ofInt _, DataValue.ofInt _ => true | _, _ => false @[export lean_data_value_to_string] def DataValue.str : DataValue → String | DataValue.ofString v => v | DataValue.ofBool v => toString v | DataValue.ofName v => toString v | DataValue.ofNat v => toString v | DataValue.ofInt v => toString v instance : ToString DataValue := ⟨DataValue.str⟩ instance : Coe String DataValue := ⟨DataValue.ofString⟩ instance : Coe Bool DataValue := ⟨DataValue.ofBool⟩ instance : Coe Name DataValue := ⟨DataValue.ofName⟩ instance : Coe Nat DataValue := ⟨DataValue.ofNat⟩ instance : Coe Int DataValue := ⟨DataValue.ofInt⟩ /- Remark: we do not use RBMap here because we need to manipulate KVMap objects in C++ and RBMap is implemented in Lean. So, we use just a List until we can generate C++ code from Lean code. -/ structure KVMap where entries : List (Name × DataValue) := [] deriving Inhabited namespace KVMap instance : ToString KVMap := ⟨fun m => toString m.entries⟩ def empty : KVMap := {} def isEmpty : KVMap → Bool | ⟨m⟩ => m.isEmpty def size (m : KVMap) : Nat := m.entries.length def findCore : List (Name × DataValue) → Name → Option DataValue | [], k' => none | (k,v)::m, k' => if k == k' then some v else findCore m k' def find : KVMap → Name → Option DataValue | ⟨m⟩, k => findCore m k def findD (m : KVMap) (k : Name) (d₀ : DataValue) : DataValue := (m.find k).getD d₀ def insertCore : List (Name × DataValue) → Name → DataValue → List (Name × DataValue) | [], k', v' => [(k',v')] | (k,v)::m, k', v' => if k == k' then (k, v') :: m else (k, v) :: insertCore m k' v' def insert : KVMap → Name → DataValue → KVMap | ⟨m⟩, k, v => ⟨insertCore m k v⟩ def contains (m : KVMap) (n : Name) : Bool := (m.find n).isSome def getString (m : KVMap) (k : Name) (defVal := "") : String := match m.find k with | some (DataValue.ofString v) => v | _ => defVal def getNat (m : KVMap) (k : Name) (defVal := 0) : Nat := match m.find k with | some (DataValue.ofNat v) => v | _ => defVal def getInt (m : KVMap) (k : Name) (defVal : Int := 0) : Int := match m.find k with | some (DataValue.ofInt v) => v | _ => defVal def getBool (m : KVMap) (k : Name) (defVal := false) : Bool := match m.find k with | some (DataValue.ofBool v) => v | _ => defVal def getName (m : KVMap) (k : Name) (defVal := Name.anonymous) : Name := match m.find k with | some (DataValue.ofName v) => v | _ => defVal def setString (m : KVMap) (k : Name) (v : String) : KVMap := m.insert k (DataValue.ofString v) def setNat (m : KVMap) (k : Name) (v : Nat) : KVMap := m.insert k (DataValue.ofNat v) def setInt (m : KVMap) (k : Name) (v : Int) : KVMap := m.insert k (DataValue.ofInt v) def setBool (m : KVMap) (k : Name) (v : Bool) : KVMap := m.insert k (DataValue.ofBool v) def setName (m : KVMap) (k : Name) (v : Name) : KVMap := m.insert k (DataValue.ofName v) @[inline] protected def forIn.{w, w'} {δ : Type w} {m : Type w → Type w'} [Monad m] (kv : KVMap) (init : δ) (f : Name × DataValue → δ → m (ForInStep δ)) : m δ := kv.entries.forIn init f instance : ForIn m KVMap (Name × DataValue) where forIn := KVMap.forIn def subsetAux : List (Name × DataValue) → KVMap → Bool | [], m₂ => true | (k, v₁)::m₁, m₂ => match m₂.find k with | some v₂ => v₁ == v₂ && subsetAux m₁ m₂ | none => false def subset : KVMap → KVMap → Bool | ⟨m₁⟩, m₂ => subsetAux m₁ m₂ def eqv (m₁ m₂ : KVMap) : Bool := subset m₁ m₂ && subset m₂ m₁ instance : BEq KVMap where beq := eqv class Value (α : Type) where toDataValue : α → DataValue ofDataValue? : DataValue → Option α @[inline] def get? {α : Type} [s : Value α] (m : KVMap) (k : Name) : Option α := m.find k |>.bind Value.ofDataValue? @[inline] def get {α : Type} [s : Value α] (m : KVMap) (k : Name) (defVal : α) : α := m.get? k |>.getD defVal @[inline] def set {α : Type} [s : Value α] (m : KVMap) (k : Name) (v : α) : KVMap := m.insert k (Value.toDataValue v) instance : Value DataValue where toDataValue := id ofDataValue? := some instance : Value Bool where toDataValue := DataValue.ofBool ofDataValue? | DataValue.ofBool b => some b | _ => none instance : Value Nat where toDataValue := DataValue.ofNat ofDataValue? | DataValue.ofNat n => some n | _ => none instance : Value Int where toDataValue := DataValue.ofInt ofDataValue? | DataValue.ofInt i => some i | _ => none instance : Value Name where toDataValue := DataValue.ofName ofDataValue? | DataValue.ofName n => some n | _ => none instance : Value String where toDataValue := DataValue.ofString ofDataValue? | DataValue.ofString n => some n | _ => none end Lean.KVMap
24b5f0da6e5217575b78a284be23058b62394365
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/set/accumulate.lean
11dcfe4dd42c6f960ddf44787dd27e7c9b880c6b
[]
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
2,101
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 -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.set.lattice import Mathlib.PostPort universes u_1 u_2 namespace Mathlib /-! # Accumulate The function `accumulate` takes a set `s` and returns `⋃ y ≤ x, s y`. -/ namespace set /-- `accumulate s` is the union of `s y` for `y ≤ x`. -/ def accumulate {α : Type u_1} {β : Type u_2} [HasLessEq α] (s : α → set β) (x : α) : set β := Union fun (y : α) => Union fun (H : y ≤ x) => s y theorem accumulate_def {α : Type u_1} {β : Type u_2} {s : α → set β} [HasLessEq α] {x : α} : accumulate s x = Union fun (y : α) => Union fun (H : y ≤ x) => s y := rfl @[simp] theorem mem_accumulate {α : Type u_1} {β : Type u_2} {s : α → set β} [HasLessEq α] {x : α} {z : β} : z ∈ accumulate s x ↔ ∃ (y : α), ∃ (H : y ≤ x), z ∈ s y := mem_bUnion_iff theorem subset_accumulate {α : Type u_1} {β : Type u_2} {s : α → set β} [preorder α] {x : α} : s x ⊆ accumulate s x := fun (z : β) => mem_bUnion le_rfl theorem monotone_accumulate {α : Type u_1} {β : Type u_2} {s : α → set β} [preorder α] : monotone (accumulate s) := fun (x y : α) (hxy : x ≤ y) => bUnion_subset_bUnion_left fun (z : α) (hz : z ∈ fun (y : α) => preorder.le y x) => le_trans hz hxy theorem bUnion_accumulate {α : Type u_1} {β : Type u_2} {s : α → set β} [preorder α] (x : α) : (Union fun (y : α) => Union fun (H : y ≤ x) => accumulate s y) = Union fun (y : α) => Union fun (H : y ≤ x) => s y := subset.antisymm (bUnion_subset fun (x_1 : α) (hx : x_1 ∈ fun (y : α) => preorder.le y x) => monotone_accumulate hx) (bUnion_subset_bUnion_right fun (x_1 : α) (hx : x_1 ∈ fun (y : α) => preorder.le y x) => subset_accumulate) theorem Union_accumulate {α : Type u_1} {β : Type u_2} {s : α → set β} [preorder α] : (Union fun (x : α) => accumulate s x) = Union fun (x : α) => s x := sorry
563684aeb3e68c675bc64e6b1c53778af62642d6
ea4aee6b11f86433e69bb5e50d0259e056d0ae61
/src/tidy/auto_cast.lean
f2465cc3e4d224a5058d3b955ae6986cbf4a14b2
[]
no_license
timjb/lean-tidy
e18feff0b7f0aad08c614fb4d34aaf527bf21e20
e767e259bf76c69edfd4ab8af1b76e6f1ed67f48
refs/heads/master
1,624,861,693,182
1,504,411,006,000
1,504,411,006,000
103,740,824
0
0
null
1,505,553,968,000
1,505,553,968,000
null
UTF-8
Lean
false
false
466
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 .smt open tactic @[reducible] def {u} auto_cast {α β : Sort u} {h : α = β} (a : α) := cast h a @[simp] lemma {u} auto_cast_identity {α : Sort u} (a : α) : @auto_cast α α (by smt_ematch) a = a := begin unfold auto_cast, trivial, end notation `⟦` p `⟧` := @auto_cast _ _ (by smt_ematch) p
a6a4286eb31caad258ce67060e9d99feed0759d2
1b8f093752ba748c5ca0083afef2959aaa7dace5
/src/category_theory/universal/comma_categories.lean
23b2b66ba3712713092edc0af023546fac85d273
[]
no_license
khoek/lean-category-theory
7ec4cda9cc64a5a4ffeb84712ac7d020dbbba386
63dcb598e9270a3e8b56d1769eb4f825a177cd95
refs/heads/master
1,585,251,725,759
1,539,344,445,000
1,539,344,445,000
145,281,070
0
0
null
1,534,662,376,000
1,534,662,376,000
null
UTF-8
Lean
false
false
5,147
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_theory.functor_category import category_theory.walking import category_theory.discrete_category -- FIXME why do we need this here? @[obviously] meta def obviously_5 := tactic.tidy { tactics := extended_tidy_tactics } open category_theory open category_theory.walking namespace category_theory.comma universes j u₁ v₁ u₂ v₂ u₃ v₃ section variables (J : Type u₁) [𝒥 : category.{u₁ v₁} J] (C : Type u₂) [𝒞 : category.{u₂ v₂} C] include 𝒥 𝒞 -- The diagonal functor sends X to the constant functor that sends everything to X. def DiagonalFunctor : C ⥤ (J ⥤ C) := { obj := λ X, { obj := λ _, X, map' := λ _ _ _, 𝟙 X }, map' := λ X Y f, { app := λ _, f } } @[simp] lemma DiagonalFunctor_map_app {X Y : C} (f : X ⟶ Y) (j : J) : ((DiagonalFunctor J C).map f) j = f := rfl end def ObjectAsFunctor {C : Type u₃} [category.{u₃ v₃} C] (X : C) : functor.{u₃ v₃ u₃ v₃} punit C := { obj := λ _, X, map' := λ _ _ _, 𝟙 X } @[simp] lemma ObjectAsFunctor_map {C : Type u₃} [category.{u₃ v₃} C] (X : C) (P Q : punit) (h : @category.hom.{u₃ v₃} punit _ P Q) : @category_theory.functor.map _ _ _ _ (ObjectAsFunctor.{u₃ v₃} X) P Q h = 𝟙 X := rfl section local attribute [search] subtype.property variables {A : Type u₁} [𝒜 : category.{u₁ v₁} A] {B : Type u₂} [ℬ : category.{u₂ v₂} B] {C : Type u₃} [𝒞 : category.{u₃ v₃} C] include 𝒜 ℬ 𝒞 def comma (S : A ⥤ C) (T : B ⥤ C) : Type (max u₁ u₂ v₃) := Σ p : A × B, (S p.1) ⟶ (T p.2) structure comma_morphism {S : A ⥤ C} {T : B ⥤ C} (p q : comma S T) : Type (max v₁ v₂):= (left : p.1.1 ⟶ q.1.1) (right : p.1.2 ⟶ q.1.2) (condition' : (S.map left) ≫ q.2 = p.2 ≫ (T.map right) . obviously) restate_axiom comma_morphism.condition' attribute [search] comma_morphism.condition @[extensionality] lemma comma_morphism_equal {S : A ⥤ C} {T : B ⥤ C} {p q : comma S T} (f g : comma_morphism p q) (wl : f.left = g.left) (wr : f.right = g.right) : f = g := begin induction f, induction g, tidy, end instance CommaCategory (S : A ⥤ C) (T : B ⥤ C) : category.{(max u₁ u₂ v₃) (max v₁ v₂)} (comma S T) := { hom := λ p q, comma_morphism p q, id := λ p, ⟨ 𝟙 p.1.1, 𝟙 p.1.2, by obviously ⟩, comp := λ p q r f g, ⟨ f.left ≫ g.left, f.right ≫ g.right, by obviously ⟩ } -- cf Leinster Remark 2.3.2 def CommaCategory_left_projection (S : A ⥤ C) (T : B ⥤ C) : (comma S T) ⥤ A := { obj := λ X, X.1.1, map' := λ _ _ f, f.left } def CommaCategory_right_projection (S : A ⥤ C) (T : B ⥤ C) : (comma S T) ⥤ B := { obj := λ X, X.1.2, map' := λ _ _ f, f.right } def CommaCategory_projection_transformation (S : A ⥤ C) (T : B ⥤ C) : ((CommaCategory_left_projection S T) ⋙ S) ⟹ ((CommaCategory_right_projection S T) ⋙ T) := { app := λ X, X.2 } -- TODO show these agree with the explicitly defined `over` and `under` categories. -- Notice that if C is large, these are large, and if C is small, these are small. def SliceCategory (X : C) : category.{(max u₃ v₃) v₃} (comma (functor.id C) (ObjectAsFunctor X)) := by apply_instance def CosliceCategory (X : C) : category.{(max u₃ v₃) v₃} (comma (ObjectAsFunctor X) (functor.id C)) := by apply_instance end -- In Cones, we have -- A = C -- B = . -- C = FunctorCategory J C variable {J : Type v₁} variable [small_category J] variable {C : Type u₁} variable [𝒞 : category.{u₁ v₁} C] include 𝒞 def Cone (F : J ⥤ C) := (comma (DiagonalFunctor.{v₁ v₁ u₁ v₁} J C) (ObjectAsFunctor F)) def Cocone (F : J ⥤ C) := (comma (ObjectAsFunctor F) (DiagonalFunctor.{v₁ v₁ u₁ v₁} J C)). @[search] lemma Cone.pointwise_condition {F : J ⥤ C} (X Y : Cone F) (f : comma_morphism X Y) (j : J) : f.left ≫ (Y.snd) j = (X.snd) j := begin have p := f.condition, have p' := congr_arg nat_trans.app p, have p'' := congr_fun p' j, simp at p'', erw category.comp_id at p'', exact p'' end @[simp] lemma Cone_comma_unit (F : J ⥤ C) (X : Cone F) : X.1.2 = punit.star := by obviously @[simp] lemma Cocone_comma_unit (F : J ⥤ C) (X : Cocone F) : X.1.1 = punit.star := by obviously instance Cones (F : J ⥤ C) : category (Cone F) := begin unfold Cone, apply_instance end instance Cocones (F : J ⥤ C) : category (Cocone F) := begin unfold Cocone, apply_instance end -- def Limit (F: J ⥤ C) := terminal_object (Cone F) -- def Colimit (F: J ⥤ C) := initial_object (Cocone F) -- def BinaryProduct (α β : C) := Limit (Pair_functor.{u₁ v₁} α β) -- def BinaryCoproduct (α β : C) := Colimit (Pair_functor α β) -- def Equalizer {α β : C} (f g : α ⟶ β) := Limit (ParallelPair_functor f g) -- def Coequalizer {α β : C} (f g : α ⟶ β) := Colimit (ParallelPair_functor f g) end category_theory.comma
9799382a1d558c7cc0f23b3bd844370e642debe0
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/analysis/calculus/deriv/mul.lean
3a21aef1819eb4dd90d1a962fd5fce1d7e38c7cf
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
15,862
lean
/- Copyright (c) 2019 Gabriel Ebner. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner, Anatole Dedecker, Yury Kudryashov -/ import analysis.calculus.deriv.basic import analysis.calculus.fderiv.mul import analysis.calculus.fderiv.add /-! # Derivative of `f x * g x` > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file we prove formulas for `(f x * g x)'` and `(f x • g x)'`. For a more detailed overview of one-dimensional derivatives in mathlib, see the module docstring of `analysis/calculus/deriv/basic`. ## Keywords derivative, multiplication -/ universes u v w noncomputable theory open_locale classical topology big_operators filter ennreal open filter asymptotics set open continuous_linear_map (smul_right smul_right_one_eq_iff) variables {𝕜 : Type u} [nontrivially_normed_field 𝕜] variables {F : Type v} [normed_add_comm_group F] [normed_space 𝕜 F] variables {E : Type w} [normed_add_comm_group E] [normed_space 𝕜 E] variables {f f₀ f₁ g : 𝕜 → F} variables {f' f₀' f₁' g' : F} variables {x : 𝕜} variables {s t : set 𝕜} variables {L L₁ L₂ : filter 𝕜} section smul /-! ### Derivative of the multiplication of a scalar function and a vector function -/ variables {𝕜' : Type*} [nontrivially_normed_field 𝕜'] [normed_algebra 𝕜 𝕜'] [normed_space 𝕜' F] [is_scalar_tower 𝕜 𝕜' F] {c : 𝕜 → 𝕜'} {c' : 𝕜'} theorem has_deriv_within_at.smul (hc : has_deriv_within_at c c' s x) (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ y, c y • f y) (c x • f' + c' • f x) s x := by simpa using (has_fderiv_within_at.smul hc hf).has_deriv_within_at theorem has_deriv_at.smul (hc : has_deriv_at c c' x) (hf : has_deriv_at f f' x) : has_deriv_at (λ y, c y • f y) (c x • f' + c' • f x) x := begin rw [← has_deriv_within_at_univ] at *, exact hc.smul hf end theorem has_strict_deriv_at.smul (hc : has_strict_deriv_at c c' x) (hf : has_strict_deriv_at f f' x) : has_strict_deriv_at (λ y, c y • f y) (c x • f' + c' • f x) x := by simpa using (hc.smul hf).has_strict_deriv_at lemma deriv_within_smul (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (hf : differentiable_within_at 𝕜 f s x) : deriv_within (λ y, c y • f y) s x = c x • deriv_within f s x + (deriv_within c s x) • f x := (hc.has_deriv_within_at.smul hf.has_deriv_within_at).deriv_within hxs lemma deriv_smul (hc : differentiable_at 𝕜 c x) (hf : differentiable_at 𝕜 f x) : deriv (λ y, c y • f y) x = c x • deriv f x + (deriv c x) • f x := (hc.has_deriv_at.smul hf.has_deriv_at).deriv theorem has_strict_deriv_at.smul_const (hc : has_strict_deriv_at c c' x) (f : F) : has_strict_deriv_at (λ y, c y • f) (c' • f) x := begin have := hc.smul (has_strict_deriv_at_const x f), rwa [smul_zero, zero_add] at this, end theorem has_deriv_within_at.smul_const (hc : has_deriv_within_at c c' s x) (f : F) : has_deriv_within_at (λ y, c y • f) (c' • f) s x := begin have := hc.smul (has_deriv_within_at_const x s f), rwa [smul_zero, zero_add] at this end theorem has_deriv_at.smul_const (hc : has_deriv_at c c' x) (f : F) : has_deriv_at (λ y, c y • f) (c' • f) x := begin rw [← has_deriv_within_at_univ] at *, exact hc.smul_const f end lemma deriv_within_smul_const (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (f : F) : deriv_within (λ y, c y • f) s x = (deriv_within c s x) • f := (hc.has_deriv_within_at.smul_const f).deriv_within hxs lemma deriv_smul_const (hc : differentiable_at 𝕜 c x) (f : F) : deriv (λ y, c y • f) x = (deriv c x) • f := (hc.has_deriv_at.smul_const f).deriv end smul section const_smul variables {R : Type*} [semiring R] [module R F] [smul_comm_class 𝕜 R F] [has_continuous_const_smul R F] theorem has_strict_deriv_at.const_smul (c : R) (hf : has_strict_deriv_at f f' x) : has_strict_deriv_at (λ y, c • f y) (c • f') x := by simpa using (hf.const_smul c).has_strict_deriv_at theorem has_deriv_at_filter.const_smul (c : R) (hf : has_deriv_at_filter f f' x L) : has_deriv_at_filter (λ y, c • f y) (c • f') x L := by simpa using (hf.const_smul c).has_deriv_at_filter theorem has_deriv_within_at.const_smul (c : R) (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ y, c • f y) (c • f') s x := hf.const_smul c theorem has_deriv_at.const_smul (c : R) (hf : has_deriv_at f f' x) : has_deriv_at (λ y, c • f y) (c • f') x := hf.const_smul c lemma deriv_within_const_smul (hxs : unique_diff_within_at 𝕜 s x) (c : R) (hf : differentiable_within_at 𝕜 f s x) : deriv_within (λ y, c • f y) s x = c • deriv_within f s x := (hf.has_deriv_within_at.const_smul c).deriv_within hxs lemma deriv_const_smul (c : R) (hf : differentiable_at 𝕜 f x) : deriv (λ y, c • f y) x = c • deriv f x := (hf.has_deriv_at.const_smul c).deriv end const_smul section mul /-! ### Derivative of the multiplication of two functions -/ variables {𝕜' 𝔸 : Type*} [normed_field 𝕜'] [normed_ring 𝔸] [normed_algebra 𝕜 𝕜'] [normed_algebra 𝕜 𝔸] {c d : 𝕜 → 𝔸} {c' d' : 𝔸} {u v : 𝕜 → 𝕜'} theorem has_deriv_within_at.mul (hc : has_deriv_within_at c c' s x) (hd : has_deriv_within_at d d' s x) : has_deriv_within_at (λ y, c y * d y) (c' * d x + c x * d') s x := begin have := (has_fderiv_within_at.mul' hc hd).has_deriv_within_at, rwa [continuous_linear_map.add_apply, continuous_linear_map.smul_apply, continuous_linear_map.smul_right_apply, continuous_linear_map.smul_right_apply, continuous_linear_map.smul_right_apply, continuous_linear_map.one_apply, one_smul, one_smul, add_comm] at this, end theorem has_deriv_at.mul (hc : has_deriv_at c c' x) (hd : has_deriv_at d d' x) : has_deriv_at (λ y, c y * d y) (c' * d x + c x * d') x := begin rw [← has_deriv_within_at_univ] at *, exact hc.mul hd end theorem has_strict_deriv_at.mul (hc : has_strict_deriv_at c c' x) (hd : has_strict_deriv_at d d' x) : has_strict_deriv_at (λ y, c y * d y) (c' * d x + c x * d') x := begin have := (has_strict_fderiv_at.mul' hc hd).has_strict_deriv_at, rwa [continuous_linear_map.add_apply, continuous_linear_map.smul_apply, continuous_linear_map.smul_right_apply, continuous_linear_map.smul_right_apply, continuous_linear_map.smul_right_apply, continuous_linear_map.one_apply, one_smul, one_smul, add_comm] at this, end lemma deriv_within_mul (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (hd : differentiable_within_at 𝕜 d s x) : deriv_within (λ y, c y * d y) s x = deriv_within c s x * d x + c x * deriv_within d s x := (hc.has_deriv_within_at.mul hd.has_deriv_within_at).deriv_within hxs @[simp] lemma deriv_mul (hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) : deriv (λ y, c y * d y) x = deriv c x * d x + c x * deriv d x := (hc.has_deriv_at.mul hd.has_deriv_at).deriv theorem has_deriv_within_at.mul_const (hc : has_deriv_within_at c c' s x) (d : 𝔸) : has_deriv_within_at (λ y, c y * d) (c' * d) s x := begin convert hc.mul (has_deriv_within_at_const x s d), rw [mul_zero, add_zero] end theorem has_deriv_at.mul_const (hc : has_deriv_at c c' x) (d : 𝔸) : has_deriv_at (λ y, c y * d) (c' * d) x := begin rw [← has_deriv_within_at_univ] at *, exact hc.mul_const d end theorem has_deriv_at_mul_const (c : 𝕜) : has_deriv_at (λ x, x * c) c x := by simpa only [one_mul] using (has_deriv_at_id' x).mul_const c theorem has_strict_deriv_at.mul_const (hc : has_strict_deriv_at c c' x) (d : 𝔸) : has_strict_deriv_at (λ y, c y * d) (c' * d) x := begin convert hc.mul (has_strict_deriv_at_const x d), rw [mul_zero, add_zero] end lemma deriv_within_mul_const (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (d : 𝔸) : deriv_within (λ y, c y * d) s x = deriv_within c s x * d := (hc.has_deriv_within_at.mul_const d).deriv_within hxs lemma deriv_mul_const (hc : differentiable_at 𝕜 c x) (d : 𝔸) : deriv (λ y, c y * d) x = deriv c x * d := (hc.has_deriv_at.mul_const d).deriv lemma deriv_mul_const_field (v : 𝕜') : deriv (λ y, u y * v) x = deriv u x * v := begin by_cases hu : differentiable_at 𝕜 u x, { exact deriv_mul_const hu v }, { rw [deriv_zero_of_not_differentiable_at hu, zero_mul], rcases eq_or_ne v 0 with rfl|hd, { simp only [mul_zero, deriv_const] }, { refine deriv_zero_of_not_differentiable_at (mt (λ H, _) hu), simpa only [mul_inv_cancel_right₀ hd] using H.mul_const v⁻¹ } } end @[simp] lemma deriv_mul_const_field' (v : 𝕜') : deriv (λ x, u x * v) = λ x, deriv u x * v := funext $ λ _, deriv_mul_const_field v theorem has_deriv_within_at.const_mul (c : 𝔸) (hd : has_deriv_within_at d d' s x) : has_deriv_within_at (λ y, c * d y) (c * d') s x := begin convert (has_deriv_within_at_const x s c).mul hd, rw [zero_mul, zero_add] end theorem has_deriv_at.const_mul (c : 𝔸) (hd : has_deriv_at d d' x) : has_deriv_at (λ y, c * d y) (c * d') x := begin rw [← has_deriv_within_at_univ] at *, exact hd.const_mul c end theorem has_strict_deriv_at.const_mul (c : 𝔸) (hd : has_strict_deriv_at d d' x) : has_strict_deriv_at (λ y, c * d y) (c * d') x := begin convert (has_strict_deriv_at_const _ _).mul hd, rw [zero_mul, zero_add] end lemma deriv_within_const_mul (hxs : unique_diff_within_at 𝕜 s x) (c : 𝔸) (hd : differentiable_within_at 𝕜 d s x) : deriv_within (λ y, c * d y) s x = c * deriv_within d s x := (hd.has_deriv_within_at.const_mul c).deriv_within hxs lemma deriv_const_mul (c : 𝔸) (hd : differentiable_at 𝕜 d x) : deriv (λ y, c * d y) x = c * deriv d x := (hd.has_deriv_at.const_mul c).deriv lemma deriv_const_mul_field (u : 𝕜') : deriv (λ y, u * v y) x = u * deriv v x := by simp only [mul_comm u, deriv_mul_const_field] @[simp] lemma deriv_const_mul_field' (u : 𝕜') : deriv (λ x, u * v x) = λ x, u * deriv v x := funext (λ x, deriv_const_mul_field u) end mul section div variables {𝕜' : Type*} [nontrivially_normed_field 𝕜'] [normed_algebra 𝕜 𝕜'] {c d : 𝕜 → 𝕜'} {c' d' : 𝕜'} lemma has_deriv_at.div_const (hc : has_deriv_at c c' x) (d : 𝕜') : has_deriv_at (λ x, c x / d) (c' / d) x := by simpa only [div_eq_mul_inv] using hc.mul_const d⁻¹ lemma has_deriv_within_at.div_const (hc : has_deriv_within_at c c' s x) (d : 𝕜') : has_deriv_within_at (λ x, c x / d) (c' / d) s x := by simpa only [div_eq_mul_inv] using hc.mul_const d⁻¹ lemma has_strict_deriv_at.div_const (hc : has_strict_deriv_at c c' x) (d : 𝕜') : has_strict_deriv_at (λ x, c x / d) (c' / d) x := by simpa only [div_eq_mul_inv] using hc.mul_const d⁻¹ lemma differentiable_within_at.div_const (hc : differentiable_within_at 𝕜 c s x) (d : 𝕜') : differentiable_within_at 𝕜 (λx, c x / d) s x := (hc.has_deriv_within_at.div_const _).differentiable_within_at @[simp] lemma differentiable_at.div_const (hc : differentiable_at 𝕜 c x) (d : 𝕜') : differentiable_at 𝕜 (λ x, c x / d) x := (hc.has_deriv_at.div_const _).differentiable_at lemma differentiable_on.div_const (hc : differentiable_on 𝕜 c s) (d : 𝕜') : differentiable_on 𝕜 (λx, c x / d) s := λ x hx, (hc x hx).div_const d @[simp] lemma differentiable.div_const (hc : differentiable 𝕜 c) (d : 𝕜') : differentiable 𝕜 (λx, c x / d) := λ x, (hc x).div_const d lemma deriv_within_div_const (hc : differentiable_within_at 𝕜 c s x) (d : 𝕜') (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λx, c x / d) s x = (deriv_within c s x) / d := by simp [div_eq_inv_mul, deriv_within_const_mul, hc, hxs] @[simp] lemma deriv_div_const (d : 𝕜') : deriv (λx, c x / d) x = (deriv c x) / d := by simp only [div_eq_mul_inv, deriv_mul_const_field] end div section clm_comp_apply /-! ### Derivative of the pointwise composition/application of continuous linear maps -/ open continuous_linear_map variables {G : Type*} [normed_add_comm_group G] [normed_space 𝕜 G] {c : 𝕜 → F →L[𝕜] G} {c' : F →L[𝕜] G} {d : 𝕜 → E →L[𝕜] F} {d' : E →L[𝕜] F} {u : 𝕜 → F} {u' : F} lemma has_strict_deriv_at.clm_comp (hc : has_strict_deriv_at c c' x) (hd : has_strict_deriv_at d d' x) : has_strict_deriv_at (λ y, (c y).comp (d y)) (c'.comp (d x) + (c x).comp d') x := begin have := (hc.has_strict_fderiv_at.clm_comp hd.has_strict_fderiv_at).has_strict_deriv_at, rwa [add_apply, comp_apply, comp_apply, smul_right_apply, smul_right_apply, one_apply, one_smul, one_smul, add_comm] at this, end lemma has_deriv_within_at.clm_comp (hc : has_deriv_within_at c c' s x) (hd : has_deriv_within_at d d' s x) : has_deriv_within_at (λ y, (c y).comp (d y)) (c'.comp (d x) + (c x).comp d') s x := begin have := (hc.has_fderiv_within_at.clm_comp hd.has_fderiv_within_at).has_deriv_within_at, rwa [add_apply, comp_apply, comp_apply, smul_right_apply, smul_right_apply, one_apply, one_smul, one_smul, add_comm] at this, end lemma has_deriv_at.clm_comp (hc : has_deriv_at c c' x) (hd : has_deriv_at d d' x) : has_deriv_at (λ y, (c y).comp (d y)) (c'.comp (d x) + (c x).comp d') x := begin rw [← has_deriv_within_at_univ] at *, exact hc.clm_comp hd end lemma deriv_within_clm_comp (hc : differentiable_within_at 𝕜 c s x) (hd : differentiable_within_at 𝕜 d s x) (hxs : unique_diff_within_at 𝕜 s x): deriv_within (λ y, (c y).comp (d y)) s x = ((deriv_within c s x).comp (d x) + (c x).comp (deriv_within d s x)) := (hc.has_deriv_within_at.clm_comp hd.has_deriv_within_at).deriv_within hxs lemma deriv_clm_comp (hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) : deriv (λ y, (c y).comp (d y)) x = ((deriv c x).comp (d x) + (c x).comp (deriv d x)) := (hc.has_deriv_at.clm_comp hd.has_deriv_at).deriv lemma has_strict_deriv_at.clm_apply (hc : has_strict_deriv_at c c' x) (hu : has_strict_deriv_at u u' x) : has_strict_deriv_at (λ y, (c y) (u y)) (c' (u x) + c x u') x := begin have := (hc.has_strict_fderiv_at.clm_apply hu.has_strict_fderiv_at).has_strict_deriv_at, rwa [add_apply, comp_apply, flip_apply, smul_right_apply, smul_right_apply, one_apply, one_smul, one_smul, add_comm] at this, end lemma has_deriv_within_at.clm_apply (hc : has_deriv_within_at c c' s x) (hu : has_deriv_within_at u u' s x) : has_deriv_within_at (λ y, (c y) (u y)) (c' (u x) + c x u') s x := begin have := (hc.has_fderiv_within_at.clm_apply hu.has_fderiv_within_at).has_deriv_within_at, rwa [add_apply, comp_apply, flip_apply, smul_right_apply, smul_right_apply, one_apply, one_smul, one_smul, add_comm] at this, end lemma has_deriv_at.clm_apply (hc : has_deriv_at c c' x) (hu : has_deriv_at u u' x) : has_deriv_at (λ y, (c y) (u y)) (c' (u x) + c x u') x := begin have := (hc.has_fderiv_at.clm_apply hu.has_fderiv_at).has_deriv_at, rwa [add_apply, comp_apply, flip_apply, smul_right_apply, smul_right_apply, one_apply, one_smul, one_smul, add_comm] at this, end lemma deriv_within_clm_apply (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (hu : differentiable_within_at 𝕜 u s x) : deriv_within (λ y, (c y) (u y)) s x = (deriv_within c s x (u x) + c x (deriv_within u s x)) := (hc.has_deriv_within_at.clm_apply hu.has_deriv_within_at).deriv_within hxs lemma deriv_clm_apply (hc : differentiable_at 𝕜 c x) (hu : differentiable_at 𝕜 u x) : deriv (λ y, (c y) (u y)) x = (deriv c x (u x) + c x (deriv u x)) := (hc.has_deriv_at.clm_apply hu.has_deriv_at).deriv end clm_comp_apply
f640acdc19fc5eff6ac36adcdb1153401c19a871
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/linear_algebra/lagrange.lean
8c6f35b50203c330b20b1e9ba4a5fb8b0773e027
[ "Apache-2.0" ]
permissive
waynemunro/mathlib
e3fd4ff49f4cb43d4a8ded59d17be407bc5ee552
065a70810b5480d584033f7bbf8e0409480c2118
refs/heads/master
1,693,417,182,397
1,634,644,781,000
1,634,644,781,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
7,257
lean
/- Copyright (c) 2020 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import ring_theory.polynomial import algebra.big_operators.basic /-! # Lagrange interpolation ## Main definitions * `lagrange.basis s x` where `s : finset F` and `x : F`: the Lagrange basis polynomial that evaluates to `1` at `x` and `0` at other elements of `s`. * `lagrange.interpolate s f` where `s : finset F` and `f : s → F`: the Lagrange interpolant that evaluates to `f x` at `x` for `x ∈ s`. -/ noncomputable theory open_locale big_operators classical universe u namespace lagrange variables {F : Type u} [decidable_eq F] [field F] (s : finset F) variables {F' : Type u} [field F'] (s' : finset F') open polynomial /-- Lagrange basis polynomials that evaluate to 1 at `x` and 0 at other elements of `s`. -/ def basis (x : F) : polynomial F := ∏ y in s.erase x, C (x - y)⁻¹ * (X - C y) @[simp] theorem basis_empty (x : F) : basis ∅ x = 1 := rfl @[simp] theorem eval_basis_self (x : F) : (basis s x).eval x = 1 := begin rw [basis, ← coe_eval_ring_hom, (eval_ring_hom x).map_prod, coe_eval_ring_hom, finset.prod_eq_one], intros y hy, simp_rw [eval_mul, eval_sub, eval_C, eval_X], exact inv_mul_cancel (sub_ne_zero_of_ne (finset.ne_of_mem_erase hy).symm) end @[simp] theorem eval_basis_ne (x y : F) (h1 : y ∈ s) (h2 : y ≠ x) : (basis s x).eval y = 0 := begin rw [basis, ← coe_eval_ring_hom, (eval_ring_hom y).map_prod, coe_eval_ring_hom, finset.prod_eq_zero (finset.mem_erase.2 ⟨h2, h1⟩)], simp_rw [eval_mul, eval_sub, eval_C, eval_X, sub_self, mul_zero] end theorem eval_basis (x y : F) (h : y ∈ s) : (basis s x).eval y = if y = x then 1 else 0 := by { split_ifs with H, { subst H, apply eval_basis_self }, { exact eval_basis_ne s x y h H } } @[simp] theorem nat_degree_basis (x : F) (hx : x ∈ s) : (basis s x).nat_degree = s.card - 1 := begin unfold basis, generalize hsx : s.erase x = sx, have : x ∉ sx := hsx ▸ finset.not_mem_erase x s, rw [← finset.insert_erase hx, hsx, finset.card_insert_of_not_mem this, nat.add_sub_cancel], clear hx hsx s, revert this, apply sx.induction_on, { intros hx, rw [finset.prod_empty, nat_degree_one], refl }, { intros y s hys ih hx, rw [finset.mem_insert, not_or_distrib] at hx, have h1 : C (x - y)⁻¹ ≠ C 0 := λ h, hx.1 (eq_of_sub_eq_zero $ inv_eq_zero.1 $ C_inj.1 h), have h2 : X ^ 1 - C y ≠ 0 := by convert X_pow_sub_C_ne_zero zero_lt_one y, rw C_0 at h1, rw pow_one at h2, rw [finset.prod_insert hys, nat_degree_mul (mul_ne_zero h1 h2), ih hx.2, finset.card_insert_of_not_mem hys, nat_degree_mul h1 h2, nat_degree_C, zero_add, nat_degree, degree_X_sub_C, add_comm], refl, rw [ne, finset.prod_eq_zero_iff], rintro ⟨z, hzs, hz⟩, rw mul_eq_zero at hz, cases hz with hz hz, { rw [← C_0, C_inj, inv_eq_zero, sub_eq_zero] at hz, exact hx.2 (hz.symm ▸ hzs) }, { rw ← pow_one (X : polynomial F) at hz, exact X_pow_sub_C_ne_zero zero_lt_one _ hz } } end variables (f : s → F) /-- Lagrange interpolation: given a finset `s` and a function `f : s → F`, `interpolate s f` is the unique polynomial of degree `< s.card` that takes value `f x` on all `x` in `s`. -/ def interpolate : polynomial F := ∑ x in s.attach, C (f x) * basis s x @[simp] theorem interpolate_empty (f) : interpolate (∅ : finset F) f = 0 := rfl @[simp] theorem eval_interpolate (x) (H : x ∈ s) : eval x (interpolate s f) = f ⟨x, H⟩ := begin rw [interpolate, ← coe_eval_ring_hom, (eval_ring_hom x).map_sum, coe_eval_ring_hom, finset.sum_eq_single (⟨x, H⟩ : { x // x ∈ s })], { rw [eval_mul, eval_C, subtype.coe_mk, eval_basis_self, mul_one] }, { rintros ⟨y, hy⟩ _ hyx, rw [eval_mul, subtype.coe_mk, eval_basis_ne s y x H, mul_zero], { rintros rfl, exact hyx rfl } }, { intro h, exact absurd (finset.mem_attach _ _) h } end theorem degree_interpolate_lt : (interpolate s f).degree < s.card := if H : s = ∅ then by { subst H, rw [interpolate_empty, degree_zero], exact with_bot.bot_lt_coe _ } else (degree_sum_le _ _).trans_lt $ (finset.sup_lt_iff $ with_bot.bot_lt_coe s.card).2 $ λ b _, calc (C (f b) * basis s b).degree ≤ (C (f b)).degree + (basis s b).degree : degree_mul_le _ _ ... ≤ 0 + (basis s b).degree : add_le_add_right degree_C_le _ ... = (basis s b).degree : zero_add _ ... ≤ (basis s b).nat_degree : degree_le_nat_degree ... = (s.card - 1 : ℕ) : by { rw nat_degree_basis s b b.2 } ... < s.card : with_bot.coe_lt_coe.2 (nat.pred_lt $ mt finset.card_eq_zero.1 H) /-- Linear version of `interpolate`. -/ def linterpolate : (s → F) →ₗ[F] polynomial F := { to_fun := interpolate s, map_add' := λ f g, by { simp_rw [interpolate, ← finset.sum_add_distrib, ← add_mul, ← C_add], refl }, map_smul' := λ c f, by { simp_rw [interpolate, finset.smul_sum, C_mul', smul_smul], refl } } @[simp] lemma interpolate_add (f g) : interpolate s (f + g) = interpolate s f + interpolate s g := (linterpolate s).map_add f g @[simp] lemma interpolate_zero : interpolate s 0 = 0 := (linterpolate s).map_zero @[simp] lemma interpolate_neg (f) : interpolate s (-f) = -interpolate s f := (linterpolate s).map_neg f @[simp] lemma interpolate_sub (f g) : interpolate s (f - g) = interpolate s f - interpolate s g := (linterpolate s).map_sub f g @[simp] lemma interpolate_smul (c : F) (f) : interpolate s (c • f) = c • interpolate s f := (linterpolate s).map_smul c f theorem eq_zero_of_eval_eq_zero {f : polynomial F'} (hf1 : f.degree < s'.card) (hf2 : ∀ x ∈ s', f.eval x = 0) : f = 0 := by_contradiction $ λ hf3, not_le_of_lt hf1 $ calc (s'.card : with_bot ℕ) ≤ f.roots.to_finset.card : with_bot.coe_le_coe.2 $ finset.card_le_of_subset $ λ x hx, (multiset.mem_to_finset).mpr $ (mem_roots hf3).2 $ hf2 x hx ... ≤ f.roots.card : with_bot.coe_le_coe.2 $ f.roots.to_finset_card_le ... ≤ f.degree : card_roots hf3 theorem eq_of_eval_eq {f g : polynomial F'} (hf : f.degree < s'.card) (hg : g.degree < s'.card) (hfg : ∀ x ∈ s', f.eval x = g.eval x) : f = g := eq_of_sub_eq_zero $ eq_zero_of_eval_eq_zero s' (lt_of_le_of_lt (degree_sub_le f g) $ max_lt hf hg) (λ x hx, by rw [eval_sub, hfg x hx, sub_self]) theorem eq_interpolate (f : polynomial F) (hf : f.degree < s.card) : interpolate s (λ x, f.eval x) = f := eq_of_eval_eq s (degree_interpolate_lt s _) hf $ λ x hx, eval_interpolate s _ x hx /-- Lagrange interpolation induces isomorphism between functions from `s` and polynomials of degree less than `s.card`. -/ def fun_equiv_degree_lt : degree_lt F s.card ≃ₗ[F] (s → F) := { to_fun := λ f x, f.1.eval x, map_add' := λ f g, funext $ λ x, eval_add, map_smul' := λ c f, funext $ λ x, by { change eval ↑x (c • f).val = (c • λ (x : s), eval ↑x f.val) x, rw [pi.smul_apply, smul_eq_mul, ← @eval_C F c _ x, ← eval_mul, eval_C, C_mul'], refl }, inv_fun := λ f, ⟨interpolate s f, mem_degree_lt.2 $ degree_interpolate_lt s f⟩, left_inv := λ f, subtype.eq $ eq_interpolate s f $ mem_degree_lt.1 f.2, right_inv := λ f, funext $ λ ⟨x, hx⟩, eval_interpolate s f x hx } end lagrange
4d3659cfe67c967acde362b80590358b299fe9cb
ce89339993655da64b6ccb555c837ce6c10f9ef4
/zeptometer/topprover/2.lean
81859f871f14b730a056ae7ec5276f0e233c7ada
[]
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
96
lean
theorem plus_comm : ∀ n m : nat, n + m = m + n := begin intros, apply nat.add_comm end
d565e5dbeb47ce751b52dfb8247db592a4d67f8a
27a31d06bcfc7c5d379fd04a08a9f5ed3f5302d4
/stage0/src/Leanpkg.lean
c98207e652cf7b1c33027abb99cb59c8e363375c
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
joehendrix/lean4
0d1486945f7ca9fe225070374338f4f7e74bab03
1221bdd3c7d5395baa451ce8fdd2c2f8a00cbc8f
refs/heads/master
1,640,573,727,861
1,639,662,710,000
1,639,665,515,000
198,893,504
0
0
Apache-2.0
1,564,084,645,000
1,564,084,644,000
null
UTF-8
Lean
false
false
8,982
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner, Sebastian Ullrich -/ import Leanpkg.Resolve import Leanpkg.Git import Leanpkg.Build import Lean.Util.Paths open System namespace Leanpkg def readManifest : IO Manifest := do let m ← Manifest.fromFile leanpkgTomlFn if m.leanVersion ≠ leanVersionString then IO.eprintln $ "\nWARNING: Lean version mismatch: installed version is " ++ leanVersionString ++ ", but package requires " ++ m.leanVersion ++ "\n" return m def writeManifest (manifest : Lean.Syntax) (fn : FilePath) : IO Unit := do IO.FS.writeFile fn manifest.reprint.get! def lockFileName : System.FilePath := ⟨".leanpkg-lock"⟩ partial def withLockFile (x : IO α) : IO α := do acquire try x finally IO.FS.removeFile lockFileName where acquire (firstTime := true) := try -- TODO: lock file should ideally contain PID if !System.Platform.isWindows then discard <| IO.FS.Handle.mkPrim lockFileName "wx" else -- `x` mode doesn't seem to work on Windows even though it's listed at -- https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/fopen-wfopen?view=msvc-160 -- ...? Let's use the slightly racy approach then. if ← lockFileName.pathExists then throw <| IO.Error.alreadyExists none 0 "" discard <| IO.FS.Handle.mk lockFileName IO.FS.Mode.write catch | IO.Error.alreadyExists .. => do if firstTime then IO.eprintln s!"Waiting for prior leanpkg invocation to finish... (remove '{lockFileName}' if stuck)" IO.sleep (ms := 300) acquire (firstTime := false) | e => throw e def getRootPart (pkg : FilePath := ".") : IO Lean.Name := do let entries ← pkg.readDir match entries.filter (FilePath.extension ·.fileName == "lean") with | #[rootFile] => FilePath.withExtension rootFile.fileName "" |>.toString | #[] => throw <| IO.userError s!"no '.lean' file found in {← IO.FS.realPath "."}" | _ => throw <| IO.userError s!"{← IO.FS.realPath "."} must contain a unique '.lean' file as the package root" structure Configuration extends Lean.LeanPaths := moreDeps : List FilePath def configure : IO Configuration := do let d ← readManifest IO.eprintln $ "configuring " ++ d.name ++ " " ++ d.version let assg ← solveDeps d let paths ← constructPath assg let mut moreDeps := [leanpkgTomlFn] for path in paths do unless path == FilePath.mk "." / "." do -- build recursively -- TODO: share build of common dependencies execCmd { cmd := (← IO.appPath).toString cwd := path args := #["build"] } moreDeps := (path / Build.buildPath / (← getRootPart path).toString |>.withExtension "olean") :: moreDeps return { oleanPath := paths.map (· / Build.buildPath) srcPath := paths moreDeps } def execMake (makeArgs : List String) (cfg : Build.Config) : IO Unit := withLockFile do let manifest ← readManifest let leanArgs := (match manifest.timeout with | some t => ["-T", toString t] | none => []) ++ cfg.leanArgs let mut spawnArgs := { cmd := "sh" cwd := manifest.effectivePath args := #["-c", s!"\"{← IO.appDir}/leanmake\" PKG={cfg.pkg} LEAN_OPTS=\"{" ".intercalate leanArgs}\" LEAN_PATH=\"{cfg.leanPath}\" {" ".intercalate makeArgs} MORE_DEPS+=\"{" ".intercalate (cfg.moreDeps.map toString)}\" >&2"] } execCmd spawnArgs def buildImports (imports : List String) (leanArgs : List String) : IO UInt32 := do unless ← leanpkgTomlFn.pathExists do return 2 let manifest ← readManifest let cfg ← configure let imports := imports.map (·.toName) let root ← getRootPart let localImports := imports.filter (·.getRoot == root) if localImports != [] then let buildCfg : Build.Config := { pkg := root, leanArgs, leanPath := cfg.oleanPath.toString, moreDeps := cfg.moreDeps } if ← FilePath.pathExists "Makefile" then let oleans := localImports.map fun i => Lean.modToFilePath "build" i "olean" |>.toString execMake oleans buildCfg else Build.buildModules buildCfg localImports IO.println <| Lean.Json.compress <| Lean.toJson cfg.toLeanPaths return 0 def build (makeArgs leanArgs : List String) : IO Unit := do let cfg ← configure let root ← getRootPart let buildCfg : Build.Config := { pkg := root, leanArgs, leanPath := cfg.oleanPath.toString, moreDeps := cfg.moreDeps } if makeArgs != [] || (← FilePath.pathExists "Makefile") then execMake makeArgs buildCfg else Build.buildModules buildCfg [root] def initGitignoreContents := "/build " def initPkg (n : String) (fromNew : Bool) : IO Unit := do IO.FS.writeFile leanpkgTomlFn s!"[package] name = \"{n}\" version = \"0.1\" lean_version = \"{leanVersionString}\" " IO.FS.writeFile ⟨s!"{n.capitalize}.lean"⟩ "def main : IO Unit := IO.println \"Hello, world!\" " let h ← IO.FS.Handle.mk ⟨".gitignore"⟩ IO.FS.Mode.append (bin := false) h.putStr initGitignoreContents unless ← System.FilePath.isDir ⟨".git"⟩ do (do execCmd {cmd := "git", args := #["init", "-q"]} unless upstreamGitBranch = "master" do execCmd {cmd := "git", args := #["checkout", "-B", upstreamGitBranch]} ) <|> IO.eprintln "WARNING: failed to initialize git repository" def init (n : String) := initPkg n false def usage := "Lean package manager, version " ++ uiLeanVersionString ++ " Usage: leanpkg <command> init <name> create a Lean package in the current directory configure download and build dependencies build [<args>] configure and build *.olean files See `leanpkg help <command>` for more information on a specific command." def main : (cmd : String) → (leanpkgArgs leanArgs : List String) → IO UInt32 | "init", [Name], [] => init Name *> pure 0 | "configure", [], [] => configure *> pure 0 | "print-paths", leanpkgArgs, leanArgs => buildImports leanpkgArgs leanArgs | "build", makeArgs, leanArgs => build makeArgs leanArgs *> pure 0 | "help", ["configure"], [] => IO.println "Download dependencies Usage: leanpkg configure This command sets up the `build/deps` directory. For each (transitive) git dependency, the specified commit is checked out into a sub-directory of `build/deps`. If there are dependencies on multiple versions of the same package, the version materialized is undefined. No copy is made of local dependencies." *> pure 0 | "help", ["build"], [] => IO.println "download dependencies and build *.olean files Usage: leanpkg build [<leanmake-args>] [-- <lean-args>] This command invokes `leanpkg configure` followed by `leanmake <leanmake-args> LEAN_OPTS=<lean-args>`. If defined, the `package.timeout` configuration value is passed to Lean via its `-T` parameter. If no <lean-args> are given, only .olean files will be produced in `build/`. If `lib` or `bin` is passed instead, the extracted C code is compiled with `c++` and a static library in `build/lib` or an executable in `build/bin`, respectively, is created. `leanpkg build bin` requires a declaration of name `main` in the root namespace, which must return `IO Unit` or `IO UInt32` (the exit code) and may accept the program's command line arguments as a `List String` parameter. NOTE: building and linking dependent libraries currently has to be done manually, e.g. ``` $ (cd a; leanpkg build lib) $ (cd b; leanpkg build bin LINK_OPTS=../a/build/lib/libA.a) ```" *> pure 0 | "help", ["init"], [] => IO.println "Create a new Lean package in the current directory Usage: leanpkg init <name> This command creates a new Lean package with the given name in the current directory." *> pure 0 | "help", _, [] => IO.println usage *> pure 0 | _, _, _ => throw <| IO.userError usage private def splitCmdlineArgsCore : List String → List String × List String | [] => ([], []) | (arg::args) => if arg == "--" then ([], args) else let (outerArgs, innerArgs) := splitCmdlineArgsCore args (arg::outerArgs, innerArgs) def splitCmdlineArgs : List String → IO (String × List String × List String) | [] => throw <| IO.userError usage | [cmd] => return (cmd, [], []) | (cmd::rest) => let (outerArgs, innerArgs) := splitCmdlineArgsCore rest return (cmd, outerArgs, innerArgs) end Leanpkg def main (args : List String) : IO UInt32 := do try Lean.enableInitializersExecution Lean.initSearchPath (← Lean.getBuildDir) let (cmd, outerArgs, innerArgs) ← Leanpkg.splitCmdlineArgs args Leanpkg.main cmd outerArgs innerArgs catch e => IO.eprintln e -- avoid "uncaught exception: ..." pure 1
bc3f9d5223580ebd0df6713b7c9d44dab79c0f18
07c6143268cfb72beccd1cc35735d424ebcb187b
/src/tactic/ring.lean
e186b07b195b00ef7d58cb1db44bdae91a1eca5f
[ "Apache-2.0" ]
permissive
khoek/mathlib
bc49a842910af13a3c372748310e86467d1dc766
aa55f8b50354b3e11ba64792dcb06cccb2d8ee28
refs/heads/master
1,588,232,063,837
1,587,304,803,000
1,587,304,803,000
176,688,517
0
0
Apache-2.0
1,553,070,585,000
1,553,070,585,000
null
UTF-8
Lean
false
false
22,044
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import algebra.group_power tactic.norm_num import tactic.converter.interactive /-! # `ring` Evaluate expressions in the language of commutative (semi)rings. Based on <http://www.cs.ru.nl/~freek/courses/tt-2014/read/10.1.1.61.3041.pdf> . -/ namespace tactic namespace ring def horner {α} [comm_semiring α] (a x : α) (n : ℕ) (b : α) := a * x ^ n + b meta structure cache := (α : expr) (univ : level) (comm_semiring_inst : expr) (red : transparency) meta def ring_m (α : Type) : Type := reader_t cache (state_t (buffer expr) tactic) α meta instance : monad ring_m := by dunfold ring_m; apply_instance meta instance : alternative ring_m := by dunfold ring_m; apply_instance meta def get_cache : ring_m cache := reader_t.read meta def get_atom (n : ℕ) : ring_m expr := reader_t.lift $ (λ es : buffer expr, es.read' n) <$> state_t.get meta def get_transparency : ring_m transparency := cache.red <$> get_cache meta def add_atom (e : expr) : ring_m ℕ := do red ← get_transparency, reader_t.lift ⟨λ es, (do n ← es.iterate failed (λ n e' t, t <|> (is_def_eq e e' red $> n)), return (n, es)) <|> return (es.size, es.push_back e)⟩ meta def lift {α} (m : tactic α) : ring_m α := reader_t.lift (state_t.lift m) meta def ring_m.run (red : transparency) (e : expr) {α} (m : ring_m α) : tactic α := do α ← infer_type e, c ← mk_app ``comm_semiring [α] >>= mk_instance, u ← mk_meta_univ, infer_type α >>= unify (expr.sort (level.succ u)), u ← get_univ_assignment u, prod.fst <$> state_t.run (reader_t.run m ⟨α, u, c, red⟩) mk_buffer meta def cache.cs_app (c : cache) (n : name) : list expr → expr := (@expr.const tt n [c.univ] c.α c.comm_semiring_inst).mk_app meta def ring_m.mk_app (n inst : name) (l : list expr) : ring_m expr := do c ← get_cache, m ← lift $ mk_instance ((expr.const inst [c.univ] : expr) c.α), return $ (@expr.const tt n [c.univ] c.α m).mk_app l meta inductive horner_expr : Type | const (e : expr) : horner_expr | xadd (e : expr) (a : horner_expr) (x : expr × ℕ) (n : expr × ℕ) (b : horner_expr) : horner_expr meta def horner_expr.e : horner_expr → expr | (horner_expr.const e) := e | (horner_expr.xadd e _ _ _ _) := e meta instance : has_coe horner_expr expr := ⟨horner_expr.e⟩ meta instance : has_coe_to_fun horner_expr := ⟨_, λ e, ((e : expr) : expr → expr)⟩ meta def horner_expr.xadd' (c : cache) (a : horner_expr) (x : expr × ℕ) (n : expr × ℕ) (b : horner_expr) : horner_expr := horner_expr.xadd (c.cs_app ``horner [a, x.1, n.1, b]) a x n b open horner_expr meta def horner_expr.to_string : horner_expr → string | (const e) := to_string e | (xadd e a x (_, n) b) := "(" ++ a.to_string ++ ") * (" ++ to_string x.1 ++ ")^" ++ to_string n ++ " + " ++ b.to_string meta def horner_expr.pp : horner_expr → tactic format | (const e) := pp e | (xadd e a x (_, n) b) := do pa ← a.pp, pb ← b.pp, px ← pp x.1, return $ "(" ++ pa ++ ") * (" ++ px ++ ")^" ++ to_string n ++ " + " ++ pb meta instance : has_to_tactic_format horner_expr := ⟨horner_expr.pp⟩ meta def horner_expr.refl_conv (e : horner_expr) : ring_m (horner_expr × expr) := do p ← lift $ mk_eq_refl e, return (e, p) theorem zero_horner {α} [comm_semiring α] (x n b) : @horner α _ 0 x n b = b := by simp [horner] theorem horner_horner {α} [comm_semiring α] (a₁ x n₁ n₂ b n') (h : n₁ + n₂ = n') : @horner α _ (horner a₁ x n₁ 0) x n₂ b = horner a₁ x n' b := by simp [h.symm, horner, pow_add, mul_assoc] meta def eval_horner : horner_expr → expr × ℕ → expr × ℕ → horner_expr → ring_m (horner_expr × expr) | ha@(const a) x n b := do c ← get_cache, if a.to_nat = some 0 then return (b, c.cs_app ``zero_horner [x.1, n.1, b]) else (xadd' c ha x n b).refl_conv | ha@(xadd a a₁ x₁ n₁ b₁) x n b := do c ← get_cache, if x₁.2 = x.2 ∧ b₁.e.to_nat = some 0 then do (n', h) ← lift $ mk_app ``has_add.add [n₁.1, n.1] >>= norm_num, return (xadd' c a₁ x (n', n₁.2 + n.2) b, c.cs_app ``horner_horner [a₁, x.1, n₁.1, n.1, b, n', h]) else (xadd' c ha x n b).refl_conv theorem const_add_horner {α} [comm_semiring α] (k a x n b b') (h : k + b = b') : k + @horner α _ a x n b = horner a x n b' := by simp [h.symm, horner]; cc theorem horner_add_const {α} [comm_semiring α] (a x n b k b') (h : b + k = b') : @horner α _ a x n b + k = horner a x n b' := by simp [h.symm, horner] theorem horner_add_horner_lt {α} [comm_semiring α] (a₁ x n₁ b₁ a₂ n₂ b₂ k a' b') (h₁ : n₁ + k = n₂) (h₂ : (a₁ + horner a₂ x k 0 : α) = a') (h₃ : b₁ + b₂ = b') : @horner α _ a₁ x n₁ b₁ + horner a₂ x n₂ b₂ = horner a' x n₁ b' := by simp [h₂.symm, h₃.symm, h₁.symm, horner, pow_add, mul_add, mul_comm, mul_left_comm]; cc theorem horner_add_horner_gt {α} [comm_semiring α] (a₁ x n₁ b₁ a₂ n₂ b₂ k a' b') (h₁ : n₂ + k = n₁) (h₂ : (horner a₁ x k 0 + a₂ : α) = a') (h₃ : b₁ + b₂ = b') : @horner α _ a₁ x n₁ b₁ + horner a₂ x n₂ b₂ = horner a' x n₂ b' := by simp [h₂.symm, h₃.symm, h₁.symm, horner, pow_add, mul_add, mul_comm, mul_left_comm]; cc -- set_option trace.class_instances true -- set_option class.instance_max_depth 128 theorem horner_add_horner_eq {α} [comm_semiring α] (a₁ x n b₁ a₂ b₂ a' b' t) (h₁ : a₁ + a₂ = a') (h₂ : b₁ + b₂ = b') (h₃ : horner a' x n b' = t) : @horner α _ a₁ x n b₁ + horner a₂ x n b₂ = t := by simp [h₃.symm, h₂.symm, h₁.symm, horner, add_mul, mul_comm]; cc meta def eval_add : horner_expr → horner_expr → ring_m (horner_expr × expr) | (const e₁) (const e₂) := do (e, p) ← lift $ mk_app ``has_add.add [e₁, e₂] >>= norm_num, return (const e, p) | he₁@(const e₁) he₂@(xadd e₂ a x n b) := do c ← get_cache, if e₁.to_nat = some 0 then do p ← lift $ mk_app ``zero_add [e₂], return (he₂, p) else do (b', h) ← eval_add he₁ b, return (xadd' c a x n b', c.cs_app ``const_add_horner [e₁, a, x.1, n.1, b, b', h]) | he₁@(xadd e₁ a x n b) he₂@(const e₂) := do c ← get_cache, if e₂.to_nat = some 0 then do p ← lift $ mk_app ``add_zero [e₁], return (he₁, p) else do (b', h) ← eval_add b he₂, return (xadd' c a x n b', c.cs_app ``horner_add_const [a, x.1, n.1, b, e₂, b', h]) | he₁@(xadd e₁ a₁ x₁ n₁ b₁) he₂@(xadd e₂ a₂ x₂ n₂ b₂) := do c ← get_cache, if x₁.2 < x₂.2 then do (b', h) ← eval_add b₁ he₂, return (xadd' c a₁ x₁ n₁ b', c.cs_app ``horner_add_const [a₁, x₁.1, n₁.1, b₁, e₂, b', h]) else if x₁.2 ≠ x₂.2 then do (b', h) ← eval_add he₁ b₂, return (xadd' c a₂ x₂ n₂ b', c.cs_app ``const_add_horner [e₁, a₂, x₂.1, n₂.1, b₂, b', h]) else if n₁.2 < n₂.2 then do let k := n₂.2 - n₁.2, ek ← lift $ expr.of_nat (expr.const `nat []) k, (_, h₁) ← lift $ mk_app ``has_add.add [n₁.1, ek] >>= norm_num, α0 ← lift $ expr.of_nat c.α 0, (a', h₂) ← eval_add a₁ (xadd' c a₂ x₁ (ek, k) (const α0)), (b', h₃) ← eval_add b₁ b₂, return (xadd' c a' x₁ n₁ b', c.cs_app ``horner_add_horner_lt [a₁, x₁.1, n₁.1, b₁, a₂, n₂.1, b₂, ek, a', b', h₁, h₂, h₃]) else if n₁.2 ≠ n₂.2 then do let k := n₁.2 - n₂.2, ek ← lift $ expr.of_nat (expr.const `nat []) k, (_, h₁) ← lift $ mk_app ``has_add.add [n₂.1, ek] >>= norm_num, α0 ← lift $ expr.of_nat c.α 0, (a', h₂) ← eval_add (xadd' c a₁ x₁ (ek, k) (const α0)) a₂, (b', h₃) ← eval_add b₁ b₂, return (xadd' c a' x₁ n₂ b', c.cs_app ``horner_add_horner_gt [a₁, x₁.1, n₁.1, b₁, a₂, n₂.1, b₂, ek, a', b', h₁, h₂, h₃]) else do (a', h₁) ← eval_add a₁ a₂, (b', h₂) ← eval_add b₁ b₂, (t, h₃) ← eval_horner a' x₁ n₁ b', return (t, c.cs_app ``horner_add_horner_eq [a₁, x₁.1, n₁.1, b₁, a₂, b₂, a', b', t, h₁, h₂, h₃]) theorem horner_neg {α} [comm_ring α] (a x n b a' b') (h₁ : -a = a') (h₂ : -b = b') : -@horner α _ a x n b = horner a' x n b' := by simp [h₂.symm, h₁.symm, horner]; cc meta def eval_neg : horner_expr → ring_m (horner_expr × expr) | (const e) := do (e', p) ← lift $ mk_app ``has_neg.neg [e] >>= norm_num, return (const e', p) | (xadd e a x n b) := do c ← get_cache, (a', h₁) ← eval_neg a, (b', h₂) ← eval_neg b, p ← ring_m.mk_app ``horner_neg ``comm_ring [a, x.1, n.1, b, a', b', h₁, h₂], return (xadd' c a' x n b', p) theorem horner_const_mul {α} [comm_semiring α] (c a x n b a' b') (h₁ : c * a = a') (h₂ : c * b = b') : c * @horner α _ a x n b = horner a' x n b' := by simp [h₂.symm, h₁.symm, horner, mul_add, mul_assoc] theorem horner_mul_const {α} [comm_semiring α] (a x n b c a' b') (h₁ : a * c = a') (h₂ : b * c = b') : @horner α _ a x n b * c = horner a' x n b' := by simp [h₂.symm, h₁.symm, horner, add_mul, mul_right_comm] meta def eval_const_mul (k : expr) : horner_expr → ring_m (horner_expr × expr) | (const e) := do (e', p) ← lift $ mk_app ``has_mul.mul [k, e] >>= norm_num, return (const e', p) | (xadd e a x n b) := do c ← get_cache, (a', h₁) ← eval_const_mul a, (b', h₂) ← eval_const_mul b, return (xadd' c a' x n b', c.cs_app ``horner_const_mul [k, a, x.1, n.1, b, a', b', h₁, h₂]) theorem horner_mul_horner_zero {α} [comm_semiring α] (a₁ x n₁ b₁ a₂ n₂ aa t) (h₁ : @horner α _ a₁ x n₁ b₁ * a₂ = aa) (h₂ : horner aa x n₂ 0 = t) : horner a₁ x n₁ b₁ * horner a₂ x n₂ 0 = t := by rw [← h₂, ← h₁]; simp [horner, mul_add, mul_comm, mul_left_comm, mul_assoc] theorem horner_mul_horner {α} [comm_semiring α] (a₁ x n₁ b₁ a₂ n₂ b₂ aa haa ab bb t) (h₁ : @horner α _ a₁ x n₁ b₁ * a₂ = aa) (h₂ : horner aa x n₂ 0 = haa) (h₃ : a₁ * b₂ = ab) (h₄ : b₁ * b₂ = bb) (H : haa + horner ab x n₁ bb = t) : horner a₁ x n₁ b₁ * horner a₂ x n₂ b₂ = t := by rw [← H, ← h₂, ← h₁, ← h₃, ← h₄]; simp [horner, mul_add, mul_comm, mul_left_comm, mul_assoc] meta def eval_mul : horner_expr → horner_expr → ring_m (horner_expr × expr) | (const e₁) (const e₂) := do (e', p) ← lift $ mk_app ``has_mul.mul [e₁, e₂] >>= norm_num, return (const e', p) | (const e₁) e₂ := match e₁.to_nat with | (some 0) := do c ← get_cache, α0 ← lift $ expr.of_nat c.α 0, p ← lift $ mk_app ``zero_mul [e₂], return (const α0, p) | (some 1) := do p ← lift $ mk_app ``one_mul [e₂], return (e₂, p) | _ := eval_const_mul e₁ e₂ end | e₁ he₂@(const e₂) := do p₁ ← lift $ mk_app ``mul_comm [e₁, e₂], (e', p₂) ← eval_mul he₂ e₁, p ← lift $ mk_eq_trans p₁ p₂, return (e', p) | he₁@(xadd e₁ a₁ x₁ n₁ b₁) he₂@(xadd e₂ a₂ x₂ n₂ b₂) := do c ← get_cache, if x₁.2 < x₂.2 then do (a', h₁) ← eval_mul a₁ he₂, (b', h₂) ← eval_mul b₁ he₂, return (xadd' c a' x₁ n₁ b', c.cs_app ``horner_mul_const [a₁, x₁.1, n₁.1, b₁, e₂, a', b', h₁, h₂]) else if x₁.2 ≠ x₂.2 then do (a', h₁) ← eval_mul he₁ a₂, (b', h₂) ← eval_mul he₁ b₂, return (xadd' c a' x₂ n₂ b', c.cs_app ``horner_const_mul [e₁, a₂, x₂.1, n₂.1, b₂, a', b', h₁, h₂]) else do (aa, h₁) ← eval_mul he₁ a₂, α0 ← lift $ expr.of_nat c.α 0, (haa, h₂) ← eval_horner aa x₁ n₂ (const α0), if b₂.e.to_nat = some 0 then return (haa, c.cs_app ``horner_mul_horner_zero [a₁, x₁.1, n₁.1, b₁, a₂, n₂.1, aa, haa, h₁, h₂]) else do (ab, h₃) ← eval_mul a₁ b₂, (bb, h₄) ← eval_mul b₁ b₂, (t, H) ← eval_add haa (xadd' c ab x₁ n₁ bb), return (t, c.cs_app ``horner_mul_horner [a₁, x₁.1, n₁.1, b₁, a₂, n₂.1, b₂, aa, haa, ab, bb, t, h₁, h₂, h₃, h₄, H]) theorem horner_pow {α} [comm_semiring α] (a x n m n' a') (h₁ : n * m = n') (h₂ : a ^ m = a') : @horner α _ a x n 0 ^ m = horner a' x n' 0 := by simp [h₁.symm, h₂.symm, horner, mul_pow, pow_mul] meta def eval_pow : horner_expr → expr × ℕ → ring_m (horner_expr × expr) | e (_, 0) := do c ← get_cache, α1 ← lift $ expr.of_nat c.α 1, p ← lift $ mk_app ``pow_zero [e], return (const α1, p) | e (_, 1) := do p ← lift $ mk_app ``pow_one [e], return (e, p) | (const e) (e₂, m) := do (e', p) ← lift $ mk_app ``monoid.pow [e, e₂] >>= norm_num.derive', return (const e', p) | he@(xadd e a x n b) m := do c ← get_cache, let N : expr := expr.const `nat [], match b.e.to_nat with | some 0 := do (n', h₁) ← lift $ mk_app ``has_mul.mul [n.1, m.1] >>= norm_num.derive', (a', h₂) ← eval_pow a m, α0 ← lift $ expr.of_nat c.α 0, return (xadd' c a' x (n', n.2 * m.2) (const α0), c.cs_app ``horner_pow [a, x.1, n.1, m.1, n', a', h₁, h₂]) | _ := do e₂ ← lift $ expr.of_nat N (m.2-1), l ← lift $ mk_app ``monoid.pow [e, e₂], (tl, hl) ← eval_pow he (e₂, m.2-1), (t, p₂) ← eval_mul tl he, hr ← lift $ mk_eq_refl e, p₂ ← ring_m.mk_app ``norm_num.subst_into_prod ``has_mul [l, e, tl, e, t, hl, hr, p₂], p₁ ← lift $ mk_app ``pow_succ' [e, e₂], p ← lift $ mk_eq_trans p₁ p₂, return (t, p) end theorem horner_atom {α} [comm_semiring α] (x : α) : x = horner 1 x 1 0 := by simp [horner] meta def eval_atom (e : expr) : ring_m (horner_expr × expr) := do c ← get_cache, i ← add_atom e, α0 ← lift $ expr.of_nat c.α 0, α1 ← lift $ expr.of_nat c.α 1, n1 ← lift $ expr.of_nat (expr.const `nat []) 1, return (xadd' c (const α1) (e, i) (n1, 1) (const α0), c.cs_app ``horner_atom [e]) lemma subst_into_pow {α} [monoid α] (l r tl tr t) (prl : (l : α) = tl) (prr : (r : ℕ) = tr) (prt : tl ^ tr = t) : l ^ r = t := by simp [prl, prr, prt] lemma unfold_sub {α} [add_group α] (a b c : α) (h : a + -b = c) : a - b = c := h lemma unfold_div {α} [division_ring α] (a b c : α) (h : a * b⁻¹ = c) : a / b = c := h meta def eval : expr → ring_m (horner_expr × expr) | `(%%e₁ + %%e₂) := do (e₁', p₁) ← eval e₁, (e₂', p₂) ← eval e₂, (e', p') ← eval_add e₁' e₂', p ← ring_m.mk_app ``norm_num.subst_into_sum ``has_add [e₁, e₂, e₁', e₂', e', p₁, p₂, p'], return (e', p) | e@`(@has_sub.sub %%α %%P %%e₁ %%e₂) := mcond (succeeds (lift $ mk_app ``comm_ring [α] >>= mk_instance)) (do e₂' ← lift $ mk_app ``has_neg.neg [e₂], e ← lift $ mk_app ``has_add.add [e₁, e₂'], (e', p) ← eval e, p' ← ring_m.mk_app ``unfold_sub ``add_group [e₁, e₂, e', p], return (e', p')) (eval_atom e) | `(- %%e) := do (e₁, p₁) ← eval e, (e₂, p₂) ← eval_neg e₁, p ← ring_m.mk_app ``norm_num.subst_into_neg ``has_neg [e, e₁, e₂, p₁, p₂], return (e₂, p) | `(%%e₁ * %%e₂) := do (e₁', p₁) ← eval e₁, (e₂', p₂) ← eval e₂, (e', p') ← eval_mul e₁' e₂', p ← ring_m.mk_app ``norm_num.subst_into_prod ``has_mul [e₁, e₂, e₁', e₂', e', p₁, p₂, p'], return (e', p) | e@`(has_inv.inv %%_) := (do (e', p) ← lift $ norm_num.derive e <|> refl_conv e, lift $ e'.to_rat, return (const e', p)) <|> eval_atom e | e@`(@has_div.div _ %%inst %%e₁ %%e₂) := mcond (succeeds (do inst' ← ring_m.mk_app ``division_ring_has_div ``division_ring [], lift $ is_def_eq inst inst')) (do e₂' ← lift $ mk_app ``has_inv.inv [e₂], e ← lift $ mk_app ``has_mul.mul [e₁, e₂'], (e', p) ← eval e, p' ← ring_m.mk_app ``unfold_div ``division_ring [e₁, e₂, e', p], return (e', p')) (eval_atom e) | e@`(@has_pow.pow _ _ %%P %%e₁ %%e₂) := do (e₂', p₂) ← lift $ norm_num.derive e₂ <|> refl_conv e₂, match e₂'.to_nat, P with | some k, `(monoid.has_pow) := do (e₁', p₁) ← eval e₁, (e', p') ← eval_pow e₁' (e₂, k), p ← ring_m.mk_app ``subst_into_pow ``monoid [e₁, e₂, e₁', e₂', e', p₁, p₂, p'], return (e', p) | some k, `(nat.has_pow) := do (e₁', p₁) ← eval e₁, (e', p') ← eval_pow e₁' (e₂, k), p₃ ← ring_m.mk_app ``subst_into_pow ``monoid [e₁, e₂, e₁', e₂', e', p₁, p₂, p'], p₄ ← lift $ mk_app ``nat.pow_eq_pow [e₁, e₂] >>= mk_eq_symm, p ← lift $ mk_eq_trans p₄ p₃, return (e', p) | _, _ := eval_atom e end | e := match e.to_nat with | some n := (const e).refl_conv | none := eval_atom e end meta def eval' (red : transparency) (e : expr) : tactic (expr × expr) := ring_m.run red e $ do (e', p) ← eval e, return (e', p) theorem horner_def' {α} [comm_semiring α] (a x n b) : @horner α _ a x n b = x ^ n * a + b := by simp [horner, mul_comm] theorem mul_assoc_rev {α} [semigroup α] (a b c : α) : a * (b * c) = a * b * c := by simp [mul_assoc] theorem pow_add_rev {α} [monoid α] (a : α) (m n : ℕ) : a ^ m * a ^ n = a ^ (m + n) := by simp [pow_add] theorem pow_add_rev_right {α} [monoid α] (a b : α) (m n : ℕ) : b * a ^ m * a ^ n = b * a ^ (m + n) := by simp [pow_add, mul_assoc] theorem add_neg_eq_sub {α} [add_group α] (a b : α) : a + -b = a - b := rfl @[derive has_reflect] inductive normalize_mode | raw | SOP | horner instance : inhabited normalize_mode := ⟨normalize_mode.horner⟩ meta def normalize (red : transparency) (mode := normalize_mode.horner) (e : expr) : tactic (expr × expr) := do pow_lemma ← simp_lemmas.mk.add_simp ``pow_one, let lemmas := match mode with | normalize_mode.SOP := [``horner_def', ``add_zero, ``mul_one, ``mul_add, ``mul_sub, ``mul_assoc_rev, ``pow_add_rev, ``pow_add_rev_right, ``mul_neg_eq_neg_mul_symm, ``add_neg_eq_sub] | normalize_mode.horner := [``horner.equations._eqn_1, ``add_zero, ``one_mul, ``pow_one, ``neg_mul_eq_neg_mul_symm, ``add_neg_eq_sub] | _ := [] end, lemmas ← lemmas.mfoldl simp_lemmas.add_simp simp_lemmas.mk, (_, e', pr) ← ext_simplify_core () {} simp_lemmas.mk (λ _, failed) (λ _ _ _ _ e, do (new_e, pr) ← match mode with | normalize_mode.raw := eval' red | normalize_mode.horner := trans_conv (eval' red) (simplify lemmas []) | normalize_mode.SOP := trans_conv (eval' red) $ trans_conv (simplify lemmas []) $ simp_bottom_up' (λ e, norm_num e <|> pow_lemma.rewrite e) end e, guard (¬ new_e =ₐ e), return ((), new_e, some pr, ff)) (λ _ _ _ _ _, failed) `eq e, return (e', pr) end ring namespace interactive open interactive interactive.types lean.parser open tactic.ring local postfix `?`:9001 := optional /-- Tactic for solving equations in the language of *commutative* (semi)rings. This version of `ring` fails if the target is not an equality that is provable by the axioms of commutative (semi)rings. -/ meta def ring1 (red : parse (tk "!")?) : tactic unit := let transp := if red.is_some then semireducible else reducible in do `(%%e₁ = %%e₂) ← target, ((e₁', p₁), (e₂', p₂)) ← ring_m.run transp e₁ $ prod.mk <$> eval e₁ <*> eval e₂, is_def_eq e₁' e₂', p ← mk_eq_symm p₂ >>= mk_eq_trans p₁, tactic.exact p meta def ring.mode : lean.parser ring.normalize_mode := with_desc "(SOP|raw|horner)?" $ do mode ← ident?, match mode with | none := return ring.normalize_mode.horner | some `horner := return ring.normalize_mode.horner | some `SOP := return ring.normalize_mode.SOP | some `raw := return ring.normalize_mode.raw | _ := failed end /-- Tactic for solving equations in the language of *commutative* (semi)rings. Attempts to prove the goal outright if there is no `at` specifier and the target is an equality, but if this fails it falls back to rewriting all ring expressions into a normal form. When writing a normal form, `ring SOP` will use sum-of-products form instead of horner form. `ring!` will use a more aggressive reducibility setting to identify atoms. Based on [Proving Equalities in a Commutative Ring Done Right in Coq](http://www.cs.ru.nl/~freek/courses/tt-2014/read/10.1.1.61.3041.pdf) by Benjamin Grégoire and Assia Mahboubi. -/ meta def ring (red : parse (tk "!")?) (SOP : parse ring.mode) (loc : parse location) : tactic unit := match loc with | interactive.loc.ns [none] := instantiate_mvars_in_target >> ring1 red | _ := failed end <|> do ns ← loc.get_locals, let transp := if red.is_some then semireducible else reducible, tt ← tactic.replace_at (normalize transp SOP) ns loc.include_goal | fail "ring failed to simplify", when loc.include_goal $ try tactic.reflexivity add_hint_tactic "ring" add_tactic_doc { name := "ring", category := doc_category.tactic, decl_names := [`tactic.interactive.ring], tags := ["arithmetic", "simplification", "decision procedure"] } end interactive end tactic namespace conv.interactive open conv interactive open tactic tactic.interactive (ring.mode ring1) open tactic.ring (normalize) local postfix `?`:9001 := optional /-- Normalises expressions in commutative (semi-)rings inside of a `conv` block using the tactic `ring`. -/ meta def ring (red : parse (lean.parser.tk "!")?) (SOP : parse ring.mode) : conv unit := let transp := if red.is_some then semireducible else reducible in discharge_eq_lhs (ring1 red) <|> replace_lhs (normalize transp SOP) <|> fail "ring failed to simplify" end conv.interactive
c0f2c39b43d3b121a8634b5c73f51423c0e3802c
5ae26df177f810c5006841e9c73dc56e01b978d7
/src/category_theory/equivalence.lean
4698c1780dd2542fc4340ab59a72e294571a763b
[ "Apache-2.0" ]
permissive
ChrisHughes24/mathlib
98322577c460bc6b1fe5c21f42ce33ad1c3e5558
a2a867e827c2a6702beb9efc2b9282bd801d5f9a
refs/heads/master
1,583,848,251,477
1,565,164,247,000
1,565,164,247,000
129,409,993
0
1
Apache-2.0
1,565,164,817,000
1,523,628,059,000
Lean
UTF-8
Lean
false
false
14,256
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.fully_faithful import category_theory.whiskering import category_theory.natural_isomorphism import tactic.slice import tactic.converter.interactive namespace category_theory open category_theory.functor nat_iso category universes v₁ v₂ v₃ u₁ u₂ u₃ -- declare the `v`'s first; see `category_theory.category` for an explanation /-- We define an equivalence as a (half)-adjoint equivalence, a pair of functors with a unit and counit which are natural isomorphisms and the triangle law `Fη ≫ εF = 1`, or in other words the composite `F ⟶ FGF ⟶ F` is the identity. The triangle equation is written as a family of equalities between morphisms, it is more complicated if we write it as an equality of natural transformations, because then we would have to insert natural transformations like `F ⟶ F1`. -/ structure equivalence (C : Type u₁) [category.{v₁} C] (D : Type u₂) [category.{v₂} D] := mk' :: (functor : C ⥤ D) (inverse : D ⥤ C) (unit_iso : 𝟭 C ≅ functor ⋙ inverse) (counit_iso : inverse ⋙ functor ≅ 𝟭 D) (functor_unit_iso_comp' : ∀(X : C), functor.map ((unit_iso.hom : 𝟭 C ⟶ functor ⋙ inverse).app X) ≫ counit_iso.hom.app (functor.obj X) = 𝟙 (functor.obj X) . obviously) restate_axiom equivalence.functor_unit_iso_comp' infixr ` ≌ `:10 := equivalence variables {C : Type u₁} [𝒞 : category.{v₁} C] {D : Type u₂} [𝒟 : category.{v₂} D] include 𝒞 𝒟 namespace equivalence @[simp] def unit (e : C ≌ D) : 𝟭 C ⟶ e.functor ⋙ e.inverse := e.unit_iso.hom @[simp] def counit (e : C ≌ D) : e.inverse ⋙ e.functor ⟶ 𝟭 D := e.counit_iso.hom @[simp] def unit_inv (e : C ≌ D) : e.functor ⋙ e.inverse ⟶ 𝟭 C := e.unit_iso.inv @[simp] def counit_inv (e : C ≌ D) : 𝟭 D ⟶ e.inverse ⋙ e.functor := e.counit_iso.inv lemma unit_def (e : C ≌ D) : e.unit_iso.hom = e.unit := rfl lemma counit_def (e : C ≌ D) : e.counit_iso.hom = e.counit := rfl lemma unit_inv_def (e : C ≌ D) : e.unit_iso.inv = e.unit_inv := rfl lemma counit_inv_def (e : C ≌ D) : e.counit_iso.inv = e.counit_inv := rfl @[simp] lemma functor_unit_comp (e : C ≌ D) (X : C) : e.functor.map (e.unit.app X) ≫ e.counit.app (e.functor.obj X) = 𝟙 (e.functor.obj X) := e.functor_unit_iso_comp X @[simp] lemma counit_inv_functor_comp (e : C ≌ D) (X : C) : e.counit_inv.app (e.functor.obj X) ≫ e.functor.map (e.unit_inv.app X) = 𝟙 (e.functor.obj X) := begin erw [iso.inv_eq_inv (e.functor.map_iso (e.unit_iso.app X) ≪≫ e.counit_iso.app (e.functor.obj X)) (iso.refl _)], exact e.functor_unit_comp X end lemma functor_unit (e : C ≌ D) (X : C) : e.functor.map (e.unit.app X) = e.counit_inv.app (e.functor.obj X) := by { erw [←iso.comp_hom_eq_id (e.counit_iso.app _), functor_unit_comp], refl } lemma counit_functor (e : C ≌ D) (X : C) : e.counit.app (e.functor.obj X) = e.functor.map (e.unit_inv.app X) := by { erw [←iso.hom_comp_eq_id (e.functor.map_iso (e.unit_iso.app X)), functor_unit_comp], refl } /-- The other triangle equality. The proof follows the following proof in Globular: http://globular.science/1905.001 -/ @[simp] lemma unit_inverse_comp (e : C ≌ D) (Y : D) : e.unit.app (e.inverse.obj Y) ≫ e.inverse.map (e.counit.app Y) = 𝟙 (e.inverse.obj Y) := begin rw [←id_comp _ (e.inverse.map _), ←map_id e.inverse, ←counit_inv_functor_comp, map_comp, ←iso.hom_inv_id_assoc (e.unit_iso.app _) (e.inverse.map (e.functor.map _)), app_hom, app_inv, unit_def, unit_inv_def], slice_lhs 2 3 { erw [e.unit.naturality] }, slice_lhs 1 2 { erw [e.unit.naturality] }, slice_lhs 4 4 { rw [←iso.hom_inv_id_assoc (e.inverse.map_iso (e.counit_iso.app _)) (e.unit_inv.app _)] }, slice_lhs 3 4 { erw [←map_comp e.inverse, e.counit.naturality], erw [(e.counit_iso.app _).hom_inv_id, map_id] }, erw [id_comp], slice_lhs 2 3 { erw [←map_comp e.inverse, e.counit_iso.inv.naturality, map_comp] }, slice_lhs 3 4 { erw [e.unit_inv.naturality] }, slice_lhs 4 5 { erw [←map_comp (e.functor ⋙ e.inverse), (e.unit_iso.app _).hom_inv_id, map_id] }, erw [id_comp], slice_lhs 3 4 { erw [←e.unit_inv.naturality] }, slice_lhs 2 3 { erw [←map_comp e.inverse, ←e.counit_iso.inv.naturality, (e.counit_iso.app _).hom_inv_id, map_id] }, erw [id_comp, (e.unit_iso.app _).hom_inv_id], refl end @[simp] lemma inverse_counit_inv_comp (e : C ≌ D) (Y : D) : e.inverse.map (e.counit_inv.app Y) ≫ e.unit_inv.app (e.inverse.obj Y) = 𝟙 (e.inverse.obj Y) := begin erw [iso.inv_eq_inv (e.unit_iso.app (e.inverse.obj Y) ≪≫ e.inverse.map_iso (e.counit_iso.app Y)) (iso.refl _)], exact e.unit_inverse_comp Y end lemma unit_inverse (e : C ≌ D) (Y : D) : e.unit.app (e.inverse.obj Y) = e.inverse.map (e.counit_inv.app Y) := by { erw [←iso.comp_hom_eq_id (e.inverse.map_iso (e.counit_iso.app Y)), unit_inverse_comp], refl } lemma inverse_counit (e : C ≌ D) (Y : D) : e.inverse.map (e.counit.app Y) = e.unit_inv.app (e.inverse.obj Y) := by { erw [←iso.hom_comp_eq_id (e.unit_iso.app _), unit_inverse_comp], refl } @[simp] lemma fun_inv_map (e : C ≌ D) (X Y : D) (f : X ⟶ Y) : e.functor.map (e.inverse.map f) = e.counit.app X ≫ f ≫ e.counit_inv.app Y := (nat_iso.naturality_2 (e.counit_iso) f).symm @[simp] lemma inv_fun_map (e : C ≌ D) (X Y : C) (f : X ⟶ Y) : e.inverse.map (e.functor.map f) = e.unit_inv.app X ≫ f ≫ e.unit.app Y := (nat_iso.naturality_1 (e.unit_iso) f).symm section -- In this section we convert an arbitrary equivalence to a half-adjoint equivalence. variables {F : C ⥤ D} {G : D ⥤ C} (η : 𝟭 C ≅ F ⋙ G) (ε : G ⋙ F ≅ 𝟭 D) def adjointify_η : 𝟭 C ≅ F ⋙ G := calc 𝟭 C ≅ F ⋙ G : η ... ≅ F ⋙ (𝟭 D ⋙ G) : iso_whisker_left F (left_unitor G).symm ... ≅ F ⋙ ((G ⋙ F) ⋙ G) : iso_whisker_left F (iso_whisker_right ε.symm G) ... ≅ F ⋙ (G ⋙ (F ⋙ G)) : iso_whisker_left F (associator G F G) ... ≅ (F ⋙ G) ⋙ (F ⋙ G) : (associator F G (F ⋙ G)).symm ... ≅ 𝟭 C ⋙ (F ⋙ G) : iso_whisker_right η.symm (F ⋙ G) ... ≅ F ⋙ G : left_unitor (F ⋙ G) lemma adjointify_η_ε (X : C) : F.map ((adjointify_η η ε).hom.app X) ≫ ε.hom.app (F.obj X) = 𝟙 (F.obj X) := begin dsimp [adjointify_η], simp, have := ε.hom.naturality (F.map (η.inv.app X)), dsimp at this, rw [this], clear this, rw [assoc_symm _ _ (F.map _)], have := ε.hom.naturality (ε.inv.app $ F.obj X), dsimp at this, rw [this], clear this, have := (ε.app $ F.obj X).hom_inv_id, dsimp at this, rw [this], clear this, rw [id_comp], have := (F.map_iso $ η.app X).hom_inv_id, dsimp at this, rw [this] end end protected definition mk (F : C ⥤ D) (G : D ⥤ C) (η : 𝟭 C ≅ F ⋙ G) (ε : G ⋙ F ≅ 𝟭 D) : C ≌ D := ⟨F, G, adjointify_η η ε, ε, adjointify_η_ε η ε⟩ omit 𝒟 @[refl] def refl : C ≌ C := equivalence.mk (𝟭 C) (𝟭 C) (iso.refl _) (iso.refl _) include 𝒟 @[symm] def symm (e : C ≌ D) : D ≌ C := ⟨e.inverse, e.functor, e.counit_iso.symm, e.unit_iso.symm, e.inverse_counit_inv_comp⟩ variables {E : Type u₃} [ℰ : category.{v₃} E] include ℰ @[trans] def trans (e : C ≌ D) (f : D ≌ E) : C ≌ E := begin apply equivalence.mk (e.functor ⋙ f.functor) (f.inverse ⋙ e.inverse), { refine iso.trans e.unit_iso _, exact iso_whisker_left e.functor (iso_whisker_right f.unit_iso e.inverse) }, { refine iso.trans _ f.counit_iso, exact iso_whisker_left f.inverse (iso_whisker_right e.counit_iso f.functor) } end def fun_inv_id_assoc (e : C ≌ D) (F : C ⥤ E) : e.functor ⋙ e.inverse ⋙ F ≅ F := (functor.associator _ _ _).symm ≪≫ iso_whisker_right e.unit_iso.symm F ≪≫ F.left_unitor @[simp] lemma fun_inv_id_assoc_hom_app (e : C ≌ D) (F : C ⥤ E) (X : C) : (fun_inv_id_assoc e F).hom.app X = F.map (e.unit_inv.app X) := by { dsimp [fun_inv_id_assoc], tidy } @[simp] lemma fun_inv_id_assoc_inv_app (e : C ≌ D) (F : C ⥤ E) (X : C) : (fun_inv_id_assoc e F).inv.app X = F.map (e.unit.app X) := by { dsimp [fun_inv_id_assoc], tidy } def inv_fun_id_assoc (e : C ≌ D) (F : D ⥤ E) : e.inverse ⋙ e.functor ⋙ F ≅ F := (functor.associator _ _ _).symm ≪≫ iso_whisker_right e.counit_iso F ≪≫ F.left_unitor @[simp] lemma inv_fun_id_assoc_hom_app (e : C ≌ D) (F : D ⥤ E) (X : D) : (inv_fun_id_assoc e F).hom.app X = F.map (e.counit.app X) := by { dsimp [inv_fun_id_assoc], tidy } @[simp] lemma inv_fun_id_assoc_inv_app (e : C ≌ D) (F : D ⥤ E) (X : D) : (inv_fun_id_assoc e F).inv.app X = F.map (e.counit_inv.app X) := by { dsimp [inv_fun_id_assoc], tidy } end equivalence /-- A functor that is part of a (half) adjoint equivalence -/ class is_equivalence (F : C ⥤ D) := mk' :: (inverse : D ⥤ C) (unit_iso : 𝟭 C ≅ F ⋙ inverse) (counit_iso : inverse ⋙ F ≅ 𝟭 D) (functor_unit_iso_comp' : ∀ (X : C), F.map ((unit_iso.hom : 𝟭 C ⟶ F ⋙ inverse).app X) ≫ counit_iso.hom.app (F.obj X) = 𝟙 (F.obj X) . obviously) restate_axiom is_equivalence.functor_unit_iso_comp' namespace is_equivalence instance of_equivalence (F : C ≌ D) : is_equivalence F.functor := { ..F } instance of_equivalence_inverse (F : C ≌ D) : is_equivalence F.inverse := is_equivalence.of_equivalence F.symm open equivalence protected definition mk {F : C ⥤ D} (G : D ⥤ C) (η : 𝟭 C ≅ F ⋙ G) (ε : G ⋙ F ≅ 𝟭 D) : is_equivalence F := ⟨G, adjointify_η η ε, ε, adjointify_η_ε η ε⟩ end is_equivalence namespace functor def as_equivalence (F : C ⥤ D) [is_equivalence F] : C ≌ D := ⟨F, is_equivalence.inverse F, is_equivalence.unit_iso F, is_equivalence.counit_iso F, is_equivalence.functor_unit_iso_comp F⟩ omit 𝒟 instance is_equivalence_refl : is_equivalence (functor.id C) := is_equivalence.of_equivalence equivalence.refl include 𝒟 def inv (F : C ⥤ D) [is_equivalence F] : D ⥤ C := is_equivalence.inverse F instance is_equivalence_inv (F : C ⥤ D) [is_equivalence F] : is_equivalence F.inv := is_equivalence.of_equivalence F.as_equivalence.symm def fun_inv_id (F : C ⥤ D) [is_equivalence F] : F ⋙ F.inv ≅ functor.id C := (is_equivalence.unit_iso F).symm def inv_fun_id (F : C ⥤ D) [is_equivalence F] : F.inv ⋙ F ≅ functor.id D := is_equivalence.counit_iso F variables {E : Type u₃} [ℰ : category.{v₃} E] include ℰ instance is_equivalence_trans (F : C ⥤ D) (G : D ⥤ E) [is_equivalence F] [is_equivalence G] : is_equivalence (F ⋙ G) := is_equivalence.of_equivalence (equivalence.trans (as_equivalence F) (as_equivalence G)) end functor namespace is_equivalence @[simp] lemma fun_inv_map (F : C ⥤ D) [is_equivalence F] (X Y : D) (f : X ⟶ Y) : F.map (F.inv.map f) = (F.inv_fun_id.hom.app X) ≫ f ≫ (F.inv_fun_id.inv.app Y) := begin erw [nat_iso.naturality_2], refl end @[simp] lemma inv_fun_map (F : C ⥤ D) [is_equivalence F] (X Y : C) (f : X ⟶ Y) : F.inv.map (F.map f) = (F.fun_inv_id.hom.app X) ≫ f ≫ (F.fun_inv_id.inv.app Y) := begin erw [nat_iso.naturality_2], refl end -- We should probably restate many of the lemmas about `equivalence` for `is_equivalence`, -- but these are the only ones I need for now. @[simp] lemma functor_unit_comp (E : C ⥤ D) [is_equivalence E] (Y) : E.map (((is_equivalence.unit_iso E).hom).app Y) ≫ ((is_equivalence.counit_iso E).hom).app (E.obj Y) = 𝟙 _ := equivalence.functor_unit_comp (E.as_equivalence) Y @[simp] lemma counit_inv_functor_comp (E : C ⥤ D) [is_equivalence E] (Y) : ((is_equivalence.counit_iso E).inv).app (E.obj Y) ≫ E.map (((is_equivalence.unit_iso E).inv).app Y) = 𝟙 _ := eq_of_inv_eq_inv (functor_unit_comp _ _) end is_equivalence class ess_surj (F : C ⥤ D) := (obj_preimage (d : D) : C) (iso' (d : D) : F.obj (obj_preimage d) ≅ d . obviously) restate_axiom ess_surj.iso' namespace functor def obj_preimage (F : C ⥤ D) [ess_surj F] (d : D) : C := ess_surj.obj_preimage.{v₁ v₂} F d def fun_obj_preimage_iso (F : C ⥤ D) [ess_surj F] (d : D) : F.obj (F.obj_preimage d) ≅ d := ess_surj.iso F d end functor namespace equivalence def ess_surj_of_equivalence (F : C ⥤ D) [is_equivalence F] : ess_surj F := ⟨ λ Y : D, F.inv.obj Y, λ Y : D, (F.inv_fun_id.app Y) ⟩ instance faithful_of_equivalence (F : C ⥤ D) [is_equivalence F] : faithful F := { injectivity' := λ X Y f g w, begin have p := congr_arg (@category_theory.functor.map _ _ _ _ F.inv _ _) w, simpa only [cancel_epi, cancel_mono, is_equivalence.inv_fun_map] using p end }. instance full_of_equivalence (F : C ⥤ D) [is_equivalence F] : full F := { preimage := λ X Y f, (F.fun_inv_id.app X).inv ≫ (F.inv.map f) ≫ (F.fun_inv_id.app Y).hom, witness' := λ X Y f, begin apply F.inv.injectivity, /- obviously can finish from here... -/ dsimp, simp, dsimp, slice_lhs 4 6 { rw [←functor.map_comp, ←functor.map_comp], rw [←is_equivalence.fun_inv_map], }, slice_lhs 1 2 { simp }, dsimp, simp, slice_lhs 2 4 { rw [←functor.map_comp, ←functor.map_comp], erw [nat_iso.naturality_2], }, erw [nat_iso.naturality_1], refl end }. @[simp] private def equivalence_inverse (F : C ⥤ D) [full F] [faithful F] [ess_surj F] : D ⥤ C := { obj := λ X, F.obj_preimage X, map := λ X Y f, F.preimage ((F.fun_obj_preimage_iso X).hom ≫ f ≫ (F.fun_obj_preimage_iso Y).inv), map_id' := λ X, begin apply F.injectivity, tidy end, map_comp' := λ X Y Z f g, by apply F.injectivity; simp }. def equivalence_of_fully_faithfully_ess_surj (F : C ⥤ D) [full F] [faithful F] [ess_surj F] : is_equivalence F := is_equivalence.mk (equivalence_inverse F) (nat_iso.of_components (λ X, (preimage_iso $ F.fun_obj_preimage_iso $ F.obj X).symm) (λ X Y f, by { apply F.injectivity, obviously })) (nat_iso.of_components (λ Y, F.fun_obj_preimage_iso Y) (by obviously)) end equivalence end category_theory
20dc22b664c2535d81a6ae454ff65ee7ae2bb8ee
94096349332b0a0e223a22a3917c8f253cd39235
/src/game/world2/level3.lean
71e3580bb674eb26b6f3465dcfe9a25ce428e94d
[]
no_license
robertylewis/natural_number_game
26156e10ef7b45248549915cc4d1ab3d8c3afc85
b210c05cd627242f791db1ee3f365ee7829674c9
refs/heads/master
1,598,964,725,038
1,572,602,236,000
1,572,602,236,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,562
lean
import mynat.definition -- hide import mynat.add -- hide import game.world2.level2 -- hide namespace mynat -- hide /- # World 2 -- addition world ## Level 3 : `succ_add` ## You are equipped with: * `add_zero (a : mynat) : a + 0 = a` * `add_succ (a b : mynat) : a + succ(b) = succ(a + b)` * `zero_add` (a : mynat) : 0 + a = a` * `add_assoc (a b c : mynat) : (a + b) + c = a + (b + c)` Oh no! On the way to `add_comm`, a wild `succ_add` appears. `succ_add` is the statement that `succ(a) + b = succ(a + b)` for `a` and `b` in your natural number type. You will need this theorem to prove `a + b = b + a` so you'd better prove it first. NB: think about why computer scientists called this result `succ_add` . There is a logic to all the names. Note that if you want to be more precise about exactly where you want to rewrite something like `add_succ`, you can do things like `rw add_succ (succ a)` or `rw add_succ (succ a) d`, telling Lean explicitly what to use for the input variables for the function `add_succ`. Indeed, `add_succ` is a function -- it takes as input two variables `a` and `b` and outputs a proof that `a + succ(b) = succ(a + b)`. The tactic `rw add_succ` just says to Lean "guess what the variables are". -/ /- Lemma For all natural numbers $a, b$, we have $$ \operatorname{succ}(a) + b = \operatorname{succ}(a + b). $$ -/ lemma succ_add (a b : mynat) : succ a + b = succ (a + b) := begin [less_leaky] induction b with d hd, { refl }, { rw add_succ, rw hd, rw add_succ, refl } end end mynat -- hide
7704b9c21a11c753ac403e63068c3a32b280f8b0
4c06d0726f5a71477566b5375c127fa204c6c583
/proofs-after.lean
26ef8a223e3649c505e9709aa78370a8a913d73e
[]
no_license
skaslev/proofs-talk
d2e990c889ee0b3fe015fa391011078a63dba0d5
b8019ae7506def5f8d657c35c8c4ee685a015796
refs/heads/master
1,585,996,863,406
1,541,627,234,000
1,541,627,234,000
155,862,265
1
0
null
null
null
null
UTF-8
Lean
false
false
3,495
lean
attribute [simp] function.comp section intro variables {a b c d e : Type} def modus_ponens (x : a) (f : a → b) : b := f x def modus_tollens (h : b → empty) (f : a → b) : a → empty := h ∘ f def ex_falso_quodlibet (x : empty) : a := x.rec _ def eagle (x₁ : a → d → c) (x₂ : a) (x₃ : b → e → d) (x₄ : b) (x₅ : e) : c := x₁ x₂ (x₃ x₄ x₅) def batman (h : ((a → empty) → empty) → empty) (x : a) : empty := h (λ y, y x) end intro -------------------------------------------------------------------------------- section fix variable fix {a : Type} : (a → a) → a def wtf : empty := fix id end fix -------------------------------------------------------------------------------- section funext def foo : (λ x, 2 * x) = (λ x, x + x) := begin funext, induction x with n ih, { refl }, { simp [has_mul.mul, nat.mul] at *, rw ih, rw nat.succ_eq_add_one, simp } end end funext -------------------------------------------------------------------------------- structure {u v} iso (α : Type u) (β : Type v) := (f : α → β) (g : β → α) (gf : Π x, g (f x) = x) (fg : Π x, f (g x) = x) namespace iso def inv {α β} (i : iso α β) : iso β α := ⟨i.g, i.f, i.fg, i.gf⟩ def comp {α β γ} (i : iso α β) (j : iso β γ) : iso α γ := ⟨j.f ∘ i.f, i.g ∘ j.g, by simp [j.gf, i.gf], by simp [i.fg, j.fg]⟩ end iso -------------------------------------------------------------------------------- def fiber {α β} (f : α → β) (y : β) := Σ' x : α, f x = y def iscontr (α : Type) := Σ' x : α, Π y : α, x = y structure eqv (α β : Type) := (f : α → β) (h : Π y : β, iscontr (fiber f y)) -------------------------------------------------------------------------------- def ran (g h : Type → Type) (α : Type) := Π β, (α → g β) → h β def lan (g h : Type → Type) (α : Type) := Σ β, (g β → α) × h β -------------------------------------------------------------------------------- section balanced def iter {α} (g : α → α) : ℕ → α → α | 0 := id | (n + 1) := iter n ∘ g def diter {β : Type → Type 1} {γ : Type → Type} (g : Π {α}, β (γ α) → β α) : Π (n : ℕ) {α}, β (iter γ n α) → β α | 0 α := id | (n + 1) α := g ∘ diter n -- Perfectly Balanced Tree inductive F (g : Type → Type) : Type → Type 1 | F₀ : Π {α}, α → F α | F₁ : Π {α}, F (g α) → F α -- `F G` is a general balanced tree (arbitrary branching factor at each node) inductive G (α : Type) : Type | G₀ : α → G | G₁ : α → G → G -- `F G₂₃` is balanced 2-3-tree inductive G₂₃ (α : Type) : Type | G₂ : α → α → G₂₃ | G₃ : α → α → α → G₂₃ def S (g : Type → Type) (α : Type) := Σ n : ℕ, iter g n α def from_s {g α} (x : S g α) : F g α := diter (@F.F₁ g) x.1 (F.F₀ g x.2) def to_s {g α} (x : F g α) : S g α := F.rec (λ α a, ⟨0, a⟩) (λ α a ih, ⟨ih.1 + 1, ih.2⟩) x def to_s_from_s {g α} (x : S g α) : to_s (from_s x) = x := begin simp [to_s, from_s], induction x with n x, induction n with m ih generalizing α, { dsimp [diter], refl }, { dsimp [diter], rw ih } end def from_s_to_s {g α} (x : F g α) : from_s (to_s x) = x := begin simp [to_s, from_s], induction x with β x β x ih, { dsimp [diter], refl }, { dsimp [diter], rw ih } end def sf_iso {g α} : iso (S g α) (F g α) := ⟨from_s, to_s, to_s_from_s, from_s_to_s⟩ end balanced
417750bf780aac23a2392d53608fdb3121f57162
d9d511f37a523cd7659d6f573f990e2a0af93c6f
/src/algebra/ordered_field.lean
472c2d9c02b65c52b1556fd5927a911b342d3123
[ "Apache-2.0" ]
permissive
hikari0108/mathlib
b7ea2b7350497ab1a0b87a09d093ecc025a50dfa
a9e7d333b0cfd45f13a20f7b96b7d52e19fa2901
refs/heads/master
1,690,483,608,260
1,631,541,580,000
1,631,541,580,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
28,226
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, Mario Carneiro, Floris van Doorn -/ import algebra.ordered_ring import algebra.field import tactic.monotonicity.basic import algebra.group_power.order import order.order_dual /-! # Linear ordered fields A linear ordered field is a field equipped with a linear order such that * addition respects the order: `a ≤ b → c + a ≤ c + b`; * multiplication of positives is positive: `0 < a → 0 < b → 0 < a * b`; * `0 < 1`. ## Main Definitions * `linear_ordered_field`: the class of linear ordered fields. -/ set_option old_structure_cmd true variable {α : Type*} /-- A linear ordered field is a field with a linear order respecting the operations. -/ @[protect_proj] class linear_ordered_field (α : Type*) extends linear_ordered_comm_ring α, field α section linear_ordered_field variables [linear_ordered_field α] {a b c d e : α} section /-- `equiv.mul_left'` as an order_iso. -/ @[simps {simp_rhs := tt}] def order_iso.mul_left' (a : α) (ha : 0 < a) : α ≃o α := { map_rel_iff' := λ _ _, mul_le_mul_left ha, ..equiv.mul_left' a ha.ne' } /-- `equiv.mul_right'` as an order_iso. -/ @[simps {simp_rhs := tt}] def order_iso.mul_right' (a : α) (ha : 0 < a) : α ≃o α := { map_rel_iff' := λ _ _, mul_le_mul_right ha, ..equiv.mul_right' a ha.ne' } end /-! ### Lemmas about pos, nonneg, nonpos, neg -/ @[simp] lemma inv_pos : 0 < a⁻¹ ↔ 0 < a := suffices ∀ a : α, 0 < a → 0 < a⁻¹, from ⟨λ h, inv_inv' a ▸ this _ h, this a⟩, assume a ha, flip lt_of_mul_lt_mul_left ha.le $ by simp [ne_of_gt ha, zero_lt_one] @[simp] lemma inv_nonneg : 0 ≤ a⁻¹ ↔ 0 ≤ a := by simp only [le_iff_eq_or_lt, inv_pos, zero_eq_inv] @[simp] lemma inv_lt_zero : a⁻¹ < 0 ↔ a < 0 := by simp only [← not_le, inv_nonneg] @[simp] lemma inv_nonpos : a⁻¹ ≤ 0 ↔ a ≤ 0 := by simp only [← not_lt, inv_pos] lemma one_div_pos : 0 < 1 / a ↔ 0 < a := inv_eq_one_div a ▸ inv_pos lemma one_div_neg : 1 / a < 0 ↔ a < 0 := inv_eq_one_div a ▸ inv_lt_zero lemma one_div_nonneg : 0 ≤ 1 / a ↔ 0 ≤ a := inv_eq_one_div a ▸ inv_nonneg lemma one_div_nonpos : 1 / a ≤ 0 ↔ a ≤ 0 := inv_eq_one_div a ▸ inv_nonpos lemma div_pos_iff : 0 < a / b ↔ 0 < a ∧ 0 < b ∨ a < 0 ∧ b < 0 := by simp [division_def, mul_pos_iff] lemma div_neg_iff : a / b < 0 ↔ 0 < a ∧ b < 0 ∨ a < 0 ∧ 0 < b := by simp [division_def, mul_neg_iff] lemma div_nonneg_iff : 0 ≤ a / b ↔ 0 ≤ a ∧ 0 ≤ b ∨ a ≤ 0 ∧ b ≤ 0 := by simp [division_def, mul_nonneg_iff] lemma div_nonpos_iff : a / b ≤ 0 ↔ 0 ≤ a ∧ b ≤ 0 ∨ a ≤ 0 ∧ 0 ≤ b := by simp [division_def, mul_nonpos_iff] lemma div_pos (ha : 0 < a) (hb : 0 < b) : 0 < a / b := div_pos_iff.2 $ or.inl ⟨ha, hb⟩ lemma div_pos_of_neg_of_neg (ha : a < 0) (hb : b < 0) : 0 < a / b := div_pos_iff.2 $ or.inr ⟨ha, hb⟩ lemma div_neg_of_neg_of_pos (ha : a < 0) (hb : 0 < b) : a / b < 0 := div_neg_iff.2 $ or.inr ⟨ha, hb⟩ lemma div_neg_of_pos_of_neg (ha : 0 < a) (hb : b < 0) : a / b < 0 := div_neg_iff.2 $ or.inl ⟨ha, hb⟩ lemma div_nonneg (ha : 0 ≤ a) (hb : 0 ≤ b) : 0 ≤ a / b := div_nonneg_iff.2 $ or.inl ⟨ha, hb⟩ lemma div_nonneg_of_nonpos (ha : a ≤ 0) (hb : b ≤ 0) : 0 ≤ a / b := div_nonneg_iff.2 $ or.inr ⟨ha, hb⟩ lemma div_nonpos_of_nonpos_of_nonneg (ha : a ≤ 0) (hb : 0 ≤ b) : a / b ≤ 0 := div_nonpos_iff.2 $ or.inr ⟨ha, hb⟩ lemma div_nonpos_of_nonneg_of_nonpos (ha : 0 ≤ a) (hb : b ≤ 0) : a / b ≤ 0 := div_nonpos_iff.2 $ or.inl ⟨ha, hb⟩ /-! ### Relating one division with another term. -/ lemma le_div_iff (hc : 0 < c) : a ≤ b / c ↔ a * c ≤ b := ⟨λ h, div_mul_cancel b (ne_of_lt hc).symm ▸ mul_le_mul_of_nonneg_right h hc.le, λ h, calc a = a * c * (1 / c) : mul_mul_div a (ne_of_lt hc).symm ... ≤ b * (1 / c) : mul_le_mul_of_nonneg_right h (one_div_pos.2 hc).le ... = b / c : (div_eq_mul_one_div b c).symm⟩ lemma le_div_iff' (hc : 0 < c) : a ≤ b / c ↔ c * a ≤ b := by rw [mul_comm, le_div_iff hc] lemma div_le_iff (hb : 0 < b) : a / b ≤ c ↔ a ≤ c * b := ⟨λ h, calc a = a / b * b : by rw (div_mul_cancel _ (ne_of_lt hb).symm) ... ≤ c * b : mul_le_mul_of_nonneg_right h hb.le, λ h, calc a / b = a * (1 / b) : div_eq_mul_one_div a b ... ≤ (c * b) * (1 / b) : mul_le_mul_of_nonneg_right h (one_div_pos.2 hb).le ... = (c * b) / b : (div_eq_mul_one_div (c * b) b).symm ... = c : by refine (div_eq_iff (ne_of_gt hb)).mpr rfl⟩ lemma div_le_iff' (hb : 0 < b) : a / b ≤ c ↔ a ≤ b * c := by rw [mul_comm, div_le_iff hb] lemma lt_div_iff (hc : 0 < c) : a < b / c ↔ a * c < b := lt_iff_lt_of_le_iff_le $ div_le_iff hc lemma lt_div_iff' (hc : 0 < c) : a < b / c ↔ c * a < b := by rw [mul_comm, lt_div_iff hc] lemma div_lt_iff (hc : 0 < c) : b / c < a ↔ b < a * c := lt_iff_lt_of_le_iff_le (le_div_iff hc) lemma div_lt_iff' (hc : 0 < c) : b / c < a ↔ b < c * a := by rw [mul_comm, div_lt_iff hc] lemma inv_mul_le_iff (h : 0 < b) : b⁻¹ * a ≤ c ↔ a ≤ b * c := begin rw [inv_eq_one_div, mul_comm, ← div_eq_mul_one_div], exact div_le_iff' h, end lemma inv_mul_le_iff' (h : 0 < b) : b⁻¹ * a ≤ c ↔ a ≤ c * b := by rw [inv_mul_le_iff h, mul_comm] lemma mul_inv_le_iff (h : 0 < b) : a * b⁻¹ ≤ c ↔ a ≤ b * c := by rw [mul_comm, inv_mul_le_iff h] lemma mul_inv_le_iff' (h : 0 < b) : a * b⁻¹ ≤ c ↔ a ≤ c * b := by rw [mul_comm, inv_mul_le_iff' h] lemma inv_mul_lt_iff (h : 0 < b) : b⁻¹ * a < c ↔ a < b * c := begin rw [inv_eq_one_div, mul_comm, ← div_eq_mul_one_div], exact div_lt_iff' h, end lemma inv_mul_lt_iff' (h : 0 < b) : b⁻¹ * a < c ↔ a < c * b := by rw [inv_mul_lt_iff h, mul_comm] lemma mul_inv_lt_iff (h : 0 < b) : a * b⁻¹ < c ↔ a < b * c := by rw [mul_comm, inv_mul_lt_iff h] lemma mul_inv_lt_iff' (h : 0 < b) : a * b⁻¹ < c ↔ a < c * b := by rw [mul_comm, inv_mul_lt_iff' h] lemma inv_pos_le_iff_one_le_mul (ha : 0 < a) : a⁻¹ ≤ b ↔ 1 ≤ b * a := by { rw [inv_eq_one_div], exact div_le_iff ha } lemma inv_pos_le_iff_one_le_mul' (ha : 0 < a) : a⁻¹ ≤ b ↔ 1 ≤ a * b := by { rw [inv_eq_one_div], exact div_le_iff' ha } lemma inv_pos_lt_iff_one_lt_mul (ha : 0 < a) : a⁻¹ < b ↔ 1 < b * a := by { rw [inv_eq_one_div], exact div_lt_iff ha } lemma inv_pos_lt_iff_one_lt_mul' (ha : 0 < a) : a⁻¹ < b ↔ 1 < a * b := by { rw [inv_eq_one_div], exact div_lt_iff' ha } lemma div_le_iff_of_neg (hc : c < 0) : b / c ≤ a ↔ a * c ≤ b := ⟨λ h, div_mul_cancel b (ne_of_lt hc) ▸ mul_le_mul_of_nonpos_right h hc.le, λ h, calc a = a * c * (1 / c) : mul_mul_div a (ne_of_lt hc) ... ≥ b * (1 / c) : mul_le_mul_of_nonpos_right h (one_div_neg.2 hc).le ... = b / c : (div_eq_mul_one_div b c).symm⟩ lemma div_le_iff_of_neg' (hc : c < 0) : b / c ≤ a ↔ c * a ≤ b := by rw [mul_comm, div_le_iff_of_neg hc] lemma le_div_iff_of_neg (hc : c < 0) : a ≤ b / c ↔ b ≤ a * c := by rw [← neg_neg c, mul_neg_eq_neg_mul_symm, div_neg, le_neg, div_le_iff (neg_pos.2 hc), neg_mul_eq_neg_mul_symm] lemma le_div_iff_of_neg' (hc : c < 0) : a ≤ b / c ↔ b ≤ c * a := by rw [mul_comm, le_div_iff_of_neg hc] lemma div_lt_iff_of_neg (hc : c < 0) : b / c < a ↔ a * c < b := lt_iff_lt_of_le_iff_le $ le_div_iff_of_neg hc lemma div_lt_iff_of_neg' (hc : c < 0) : b / c < a ↔ c * a < b := by rw [mul_comm, div_lt_iff_of_neg hc] lemma lt_div_iff_of_neg (hc : c < 0) : a < b / c ↔ b < a * c := lt_iff_lt_of_le_iff_le $ div_le_iff_of_neg hc lemma lt_div_iff_of_neg' (hc : c < 0) : a < b / c ↔ b < c * a := by rw [mul_comm, lt_div_iff_of_neg hc] /-- One direction of `div_le_iff` where `b` is allowed to be `0` (but `c` must be nonnegative) -/ lemma div_le_of_nonneg_of_le_mul (hb : 0 ≤ b) (hc : 0 ≤ c) (h : a ≤ c * b) : a / b ≤ c := by { rcases eq_or_lt_of_le hb with rfl|hb', simp [hc], rwa [div_le_iff hb'] } lemma div_le_one_of_le (h : a ≤ b) (hb : 0 ≤ b) : a / b ≤ 1 := div_le_of_nonneg_of_le_mul hb zero_le_one $ by rwa one_mul /-! ### Bi-implications of inequalities using inversions -/ lemma inv_le_inv_of_le (ha : 0 < a) (h : a ≤ b) : b⁻¹ ≤ a⁻¹ := by rwa [← one_div a, le_div_iff' ha, ← div_eq_mul_inv, div_le_iff (ha.trans_le h), one_mul] /-- See `inv_le_inv_of_le` for the implication from right-to-left with one fewer assumption. -/ lemma inv_le_inv (ha : 0 < a) (hb : 0 < b) : a⁻¹ ≤ b⁻¹ ↔ b ≤ a := by rw [← one_div, div_le_iff ha, ← div_eq_inv_mul, le_div_iff hb, one_mul] /-- In a linear ordered field, for positive `a` and `b` we have `a⁻¹ ≤ b ↔ b⁻¹ ≤ a`. See also `inv_le_of_inv_le` for a one-sided implication with one fewer assumption. -/ lemma inv_le (ha : 0 < a) (hb : 0 < b) : a⁻¹ ≤ b ↔ b⁻¹ ≤ a := by rw [← inv_le_inv hb (inv_pos.2 ha), inv_inv'] lemma inv_le_of_inv_le (ha : 0 < a) (h : a⁻¹ ≤ b) : b⁻¹ ≤ a := (inv_le ha ((inv_pos.2 ha).trans_le h)).1 h lemma le_inv (ha : 0 < a) (hb : 0 < b) : a ≤ b⁻¹ ↔ b ≤ a⁻¹ := by rw [← inv_le_inv (inv_pos.2 hb) ha, inv_inv'] lemma inv_lt_inv (ha : 0 < a) (hb : 0 < b) : a⁻¹ < b⁻¹ ↔ b < a := lt_iff_lt_of_le_iff_le (inv_le_inv hb ha) /-- In a linear ordered field, for positive `a` and `b` we have `a⁻¹ < b ↔ b⁻¹ < a`. See also `inv_lt_of_inv_lt` for a one-sided implication with one fewer assumption. -/ lemma inv_lt (ha : 0 < a) (hb : 0 < b) : a⁻¹ < b ↔ b⁻¹ < a := lt_iff_lt_of_le_iff_le (le_inv hb ha) lemma inv_lt_of_inv_lt (ha : 0 < a) (h : a⁻¹ < b) : b⁻¹ < a := (inv_lt ha ((inv_pos.2 ha).trans h)).1 h lemma lt_inv (ha : 0 < a) (hb : 0 < b) : a < b⁻¹ ↔ b < a⁻¹ := lt_iff_lt_of_le_iff_le (inv_le hb ha) lemma inv_le_inv_of_neg (ha : a < 0) (hb : b < 0) : a⁻¹ ≤ b⁻¹ ↔ b ≤ a := by rw [← one_div, div_le_iff_of_neg ha, ← div_eq_inv_mul, div_le_iff_of_neg hb, one_mul] lemma inv_le_of_neg (ha : a < 0) (hb : b < 0) : a⁻¹ ≤ b ↔ b⁻¹ ≤ a := by rw [← inv_le_inv_of_neg hb (inv_lt_zero.2 ha), inv_inv'] lemma le_inv_of_neg (ha : a < 0) (hb : b < 0) : a ≤ b⁻¹ ↔ b ≤ a⁻¹ := by rw [← inv_le_inv_of_neg (inv_lt_zero.2 hb) ha, inv_inv'] lemma inv_lt_inv_of_neg (ha : a < 0) (hb : b < 0) : a⁻¹ < b⁻¹ ↔ b < a := lt_iff_lt_of_le_iff_le (inv_le_inv_of_neg hb ha) lemma inv_lt_of_neg (ha : a < 0) (hb : b < 0) : a⁻¹ < b ↔ b⁻¹ < a := lt_iff_lt_of_le_iff_le (le_inv_of_neg hb ha) lemma lt_inv_of_neg (ha : a < 0) (hb : b < 0) : a < b⁻¹ ↔ b < a⁻¹ := lt_iff_lt_of_le_iff_le (inv_le_of_neg hb ha) lemma inv_lt_one (ha : 1 < a) : a⁻¹ < 1 := by rwa [inv_lt ((@zero_lt_one α _ _).trans ha) zero_lt_one, inv_one] lemma one_lt_inv (h₁ : 0 < a) (h₂ : a < 1) : 1 < a⁻¹ := by rwa [lt_inv (@zero_lt_one α _ _) h₁, inv_one] lemma inv_le_one (ha : 1 ≤ a) : a⁻¹ ≤ 1 := by rwa [inv_le ((@zero_lt_one α _ _).trans_le ha) zero_lt_one, inv_one] lemma one_le_inv (h₁ : 0 < a) (h₂ : a ≤ 1) : 1 ≤ a⁻¹ := by rwa [le_inv (@zero_lt_one α _ _) h₁, inv_one] lemma inv_lt_one_iff_of_pos (h₀ : 0 < a) : a⁻¹ < 1 ↔ 1 < a := ⟨λ h₁, inv_inv' a ▸ one_lt_inv (inv_pos.2 h₀) h₁, inv_lt_one⟩ lemma inv_lt_one_iff : a⁻¹ < 1 ↔ a ≤ 0 ∨ 1 < a := begin cases le_or_lt a 0 with ha ha, { simp [ha, (inv_nonpos.2 ha).trans_lt zero_lt_one] }, { simp only [ha.not_le, false_or, inv_lt_one_iff_of_pos ha] } end lemma one_lt_inv_iff : 1 < a⁻¹ ↔ 0 < a ∧ a < 1 := ⟨λ h, ⟨inv_pos.1 (zero_lt_one.trans h), inv_inv' a ▸ inv_lt_one h⟩, and_imp.2 one_lt_inv⟩ lemma inv_le_one_iff : a⁻¹ ≤ 1 ↔ a ≤ 0 ∨ 1 ≤ a := begin rcases em (a = 1) with (rfl|ha), { simp [le_rfl] }, { simp only [ne.le_iff_lt (ne.symm ha), ne.le_iff_lt (mt inv_eq_one'.1 ha), inv_lt_one_iff] } end lemma one_le_inv_iff : 1 ≤ a⁻¹ ↔ 0 < a ∧ a ≤ 1 := ⟨λ h, ⟨inv_pos.1 (zero_lt_one.trans_le h), inv_inv' a ▸ inv_le_one h⟩, and_imp.2 one_le_inv⟩ /-! ### Relating two divisions. -/ @[mono] lemma div_le_div_of_le (hc : 0 ≤ c) (h : a ≤ b) : a / c ≤ b / c := begin rw [div_eq_mul_one_div a c, div_eq_mul_one_div b c], exact mul_le_mul_of_nonneg_right h (one_div_nonneg.2 hc) end @[mono] lemma div_le_div_of_le_left (ha : 0 ≤ a) (hc : 0 < c) (h : c ≤ b) : a / b ≤ a / c := begin rw [div_eq_mul_inv, div_eq_mul_inv], exact mul_le_mul_of_nonneg_left ((inv_le_inv (hc.trans_le h) hc).mpr h) ha end lemma div_le_div_of_le_of_nonneg (hab : a ≤ b) (hc : 0 ≤ c) : a / c ≤ b / c := div_le_div_of_le hc hab lemma div_le_div_of_nonpos_of_le (hc : c ≤ 0) (h : b ≤ a) : a / c ≤ b / c := begin rw [div_eq_mul_one_div a c, div_eq_mul_one_div b c], exact mul_le_mul_of_nonpos_right h (one_div_nonpos.2 hc) end lemma div_lt_div_of_lt (hc : 0 < c) (h : a < b) : a / c < b / c := begin rw [div_eq_mul_one_div a c, div_eq_mul_one_div b c], exact mul_lt_mul_of_pos_right h (one_div_pos.2 hc) end lemma div_lt_div_of_neg_of_lt (hc : c < 0) (h : b < a) : a / c < b / c := begin rw [div_eq_mul_one_div a c, div_eq_mul_one_div b c], exact mul_lt_mul_of_neg_right h (one_div_neg.2 hc) end lemma div_le_div_right (hc : 0 < c) : a / c ≤ b / c ↔ a ≤ b := ⟨le_imp_le_of_lt_imp_lt $ div_lt_div_of_lt hc, div_le_div_of_le $ hc.le⟩ lemma div_le_div_right_of_neg (hc : c < 0) : a / c ≤ b / c ↔ b ≤ a := ⟨le_imp_le_of_lt_imp_lt $ div_lt_div_of_neg_of_lt hc, div_le_div_of_nonpos_of_le $ hc.le⟩ lemma div_lt_div_right (hc : 0 < c) : a / c < b / c ↔ a < b := lt_iff_lt_of_le_iff_le $ div_le_div_right hc lemma div_lt_div_right_of_neg (hc : c < 0) : a / c < b / c ↔ b < a := lt_iff_lt_of_le_iff_le $ div_le_div_right_of_neg hc lemma div_lt_div_left (ha : 0 < a) (hb : 0 < b) (hc : 0 < c) : a / b < a / c ↔ c < b := by simp only [div_eq_mul_inv, mul_lt_mul_left ha, inv_lt_inv hb hc] lemma div_le_div_left (ha : 0 < a) (hb : 0 < b) (hc : 0 < c) : a / b ≤ a / c ↔ c ≤ b := le_iff_le_iff_lt_iff_lt.2 (div_lt_div_left ha hc hb) lemma div_lt_div_iff (b0 : 0 < b) (d0 : 0 < d) : a / b < c / d ↔ a * d < c * b := by rw [lt_div_iff d0, div_mul_eq_mul_div, div_lt_iff b0] lemma div_le_div_iff (b0 : 0 < b) (d0 : 0 < d) : a / b ≤ c / d ↔ a * d ≤ c * b := by rw [le_div_iff d0, div_mul_eq_mul_div, div_le_iff b0] @[mono] lemma div_le_div (hc : 0 ≤ c) (hac : a ≤ c) (hd : 0 < d) (hbd : d ≤ b) : a / b ≤ c / d := by { rw div_le_div_iff (hd.trans_le hbd) hd, exact mul_le_mul hac hbd hd.le hc } lemma div_lt_div (hac : a < c) (hbd : d ≤ b) (c0 : 0 ≤ c) (d0 : 0 < d) : a / b < c / d := (div_lt_div_iff (d0.trans_le hbd) d0).2 (mul_lt_mul hac hbd d0 c0) lemma div_lt_div' (hac : a ≤ c) (hbd : d < b) (c0 : 0 < c) (d0 : 0 < d) : a / b < c / d := (div_lt_div_iff (d0.trans hbd) d0).2 (mul_lt_mul' hac hbd d0.le c0) lemma div_lt_div_of_lt_left (hb : 0 < b) (h : b < a) (hc : 0 < c) : c / a < c / b := (div_lt_div_left hc (hb.trans h) hb).mpr h /-! ### Relating one division and involving `1` -/ lemma one_le_div (hb : 0 < b) : 1 ≤ a / b ↔ b ≤ a := by rw [le_div_iff hb, one_mul] lemma div_le_one (hb : 0 < b) : a / b ≤ 1 ↔ a ≤ b := by rw [div_le_iff hb, one_mul] lemma one_lt_div (hb : 0 < b) : 1 < a / b ↔ b < a := by rw [lt_div_iff hb, one_mul] lemma div_lt_one (hb : 0 < b) : a / b < 1 ↔ a < b := by rw [div_lt_iff hb, one_mul] lemma one_le_div_of_neg (hb : b < 0) : 1 ≤ a / b ↔ a ≤ b := by rw [le_div_iff_of_neg hb, one_mul] lemma div_le_one_of_neg (hb : b < 0) : a / b ≤ 1 ↔ b ≤ a := by rw [div_le_iff_of_neg hb, one_mul] lemma one_lt_div_of_neg (hb : b < 0) : 1 < a / b ↔ a < b := by rw [lt_div_iff_of_neg hb, one_mul] lemma div_lt_one_of_neg (hb : b < 0) : a / b < 1 ↔ b < a := by rw [div_lt_iff_of_neg hb, one_mul] lemma one_div_le (ha : 0 < a) (hb : 0 < b) : 1 / a ≤ b ↔ 1 / b ≤ a := by simpa using inv_le ha hb lemma one_div_lt (ha : 0 < a) (hb : 0 < b) : 1 / a < b ↔ 1 / b < a := by simpa using inv_lt ha hb lemma le_one_div (ha : 0 < a) (hb : 0 < b) : a ≤ 1 / b ↔ b ≤ 1 / a := by simpa using le_inv ha hb lemma lt_one_div (ha : 0 < a) (hb : 0 < b) : a < 1 / b ↔ b < 1 / a := by simpa using lt_inv ha hb lemma one_div_le_of_neg (ha : a < 0) (hb : b < 0) : 1 / a ≤ b ↔ 1 / b ≤ a := by simpa using inv_le_of_neg ha hb lemma one_div_lt_of_neg (ha : a < 0) (hb : b < 0) : 1 / a < b ↔ 1 / b < a := by simpa using inv_lt_of_neg ha hb lemma le_one_div_of_neg (ha : a < 0) (hb : b < 0) : a ≤ 1 / b ↔ b ≤ 1 / a := by simpa using le_inv_of_neg ha hb lemma lt_one_div_of_neg (ha : a < 0) (hb : b < 0) : a < 1 / b ↔ b < 1 / a := by simpa using lt_inv_of_neg ha hb lemma one_lt_div_iff : 1 < a / b ↔ 0 < b ∧ b < a ∨ b < 0 ∧ a < b := begin rcases lt_trichotomy b 0 with (hb|rfl|hb), { simp [hb, hb.not_lt, one_lt_div_of_neg] }, { simp [lt_irrefl, zero_le_one] }, { simp [hb, hb.not_lt, one_lt_div] } end lemma one_le_div_iff : 1 ≤ a / b ↔ 0 < b ∧ b ≤ a ∨ b < 0 ∧ a ≤ b := begin rcases lt_trichotomy b 0 with (hb|rfl|hb), { simp [hb, hb.not_lt, one_le_div_of_neg] }, { simp [lt_irrefl, zero_lt_one.not_le, zero_lt_one] }, { simp [hb, hb.not_lt, one_le_div] } end lemma div_lt_one_iff : a / b < 1 ↔ 0 < b ∧ a < b ∨ b = 0 ∨ b < 0 ∧ b < a := begin rcases lt_trichotomy b 0 with (hb|rfl|hb), { simp [hb, hb.not_lt, hb.ne, div_lt_one_of_neg] }, { simp [zero_lt_one], }, { simp [hb, hb.not_lt, div_lt_one, hb.ne.symm] } end lemma div_le_one_iff : a / b ≤ 1 ↔ 0 < b ∧ a ≤ b ∨ b = 0 ∨ b < 0 ∧ b ≤ a := begin rcases lt_trichotomy b 0 with (hb|rfl|hb), { simp [hb, hb.not_lt, hb.ne, div_le_one_of_neg] }, { simp [zero_le_one], }, { simp [hb, hb.not_lt, div_le_one, hb.ne.symm] } end /-! ### Relating two divisions, involving `1` -/ lemma one_div_le_one_div_of_le (ha : 0 < a) (h : a ≤ b) : 1 / b ≤ 1 / a := by simpa using inv_le_inv_of_le ha h lemma one_div_lt_one_div_of_lt (ha : 0 < a) (h : a < b) : 1 / b < 1 / a := by rwa [lt_div_iff' ha, ← div_eq_mul_one_div, div_lt_one (ha.trans h)] lemma one_div_le_one_div_of_neg_of_le (hb : b < 0) (h : a ≤ b) : 1 / b ≤ 1 / a := by rwa [div_le_iff_of_neg' hb, ← div_eq_mul_one_div, div_le_one_of_neg (h.trans_lt hb)] lemma one_div_lt_one_div_of_neg_of_lt (hb : b < 0) (h : a < b) : 1 / b < 1 / a := by rwa [div_lt_iff_of_neg' hb, ← div_eq_mul_one_div, div_lt_one_of_neg (h.trans hb)] lemma le_of_one_div_le_one_div (ha : 0 < a) (h : 1 / a ≤ 1 / b) : b ≤ a := le_imp_le_of_lt_imp_lt (one_div_lt_one_div_of_lt ha) h lemma lt_of_one_div_lt_one_div (ha : 0 < a) (h : 1 / a < 1 / b) : b < a := lt_imp_lt_of_le_imp_le (one_div_le_one_div_of_le ha) h lemma le_of_neg_of_one_div_le_one_div (hb : b < 0) (h : 1 / a ≤ 1 / b) : b ≤ a := le_imp_le_of_lt_imp_lt (one_div_lt_one_div_of_neg_of_lt hb) h lemma lt_of_neg_of_one_div_lt_one_div (hb : b < 0) (h : 1 / a < 1 / b) : b < a := lt_imp_lt_of_le_imp_le (one_div_le_one_div_of_neg_of_le hb) h /-- For the single implications with fewer assumptions, see `one_div_le_one_div_of_le` and `le_of_one_div_le_one_div` -/ lemma one_div_le_one_div (ha : 0 < a) (hb : 0 < b) : 1 / a ≤ 1 / b ↔ b ≤ a := div_le_div_left zero_lt_one ha hb /-- For the single implications with fewer assumptions, see `one_div_lt_one_div_of_lt` and `lt_of_one_div_lt_one_div` -/ lemma one_div_lt_one_div (ha : 0 < a) (hb : 0 < b) : 1 / a < 1 / b ↔ b < a := div_lt_div_left zero_lt_one ha hb /-- For the single implications with fewer assumptions, see `one_div_lt_one_div_of_neg_of_lt` and `lt_of_one_div_lt_one_div` -/ lemma one_div_le_one_div_of_neg (ha : a < 0) (hb : b < 0) : 1 / a ≤ 1 / b ↔ b ≤ a := by simpa [one_div] using inv_le_inv_of_neg ha hb /-- For the single implications with fewer assumptions, see `one_div_lt_one_div_of_lt` and `lt_of_one_div_lt_one_div` -/ lemma one_div_lt_one_div_of_neg (ha : a < 0) (hb : b < 0) : 1 / a < 1 / b ↔ b < a := lt_iff_lt_of_le_iff_le (one_div_le_one_div_of_neg hb ha) lemma one_lt_one_div (h1 : 0 < a) (h2 : a < 1) : 1 < 1 / a := by rwa [lt_one_div (@zero_lt_one α _ _) h1, one_div_one] lemma one_le_one_div (h1 : 0 < a) (h2 : a ≤ 1) : 1 ≤ 1 / a := by rwa [le_one_div (@zero_lt_one α _ _) h1, one_div_one] lemma one_div_lt_neg_one (h1 : a < 0) (h2 : -1 < a) : 1 / a < -1 := suffices 1 / a < 1 / -1, by rwa one_div_neg_one_eq_neg_one at this, one_div_lt_one_div_of_neg_of_lt h1 h2 lemma one_div_le_neg_one (h1 : a < 0) (h2 : -1 ≤ a) : 1 / a ≤ -1 := suffices 1 / a ≤ 1 / -1, by rwa one_div_neg_one_eq_neg_one at this, one_div_le_one_div_of_neg_of_le h1 h2 /-! ### Results about halving. The equalities also hold in fields of characteristic `0`. -/ lemma add_halves (a : α) : a / 2 + a / 2 = a := by rw [div_add_div_same, ← two_mul, mul_div_cancel_left a two_ne_zero] lemma sub_self_div_two (a : α) : a - a / 2 = a / 2 := suffices a / 2 + a / 2 - a / 2 = a / 2, by rwa add_halves at this, by rw [add_sub_cancel] lemma div_two_sub_self (a : α) : a / 2 - a = - (a / 2) := suffices a / 2 - (a / 2 + a / 2) = - (a / 2), by rwa add_halves at this, by rw [sub_add_eq_sub_sub, sub_self, zero_sub] lemma add_self_div_two (a : α) : (a + a) / 2 = a := by rw [← mul_two, mul_div_cancel a two_ne_zero] lemma half_pos (h : 0 < a) : 0 < a / 2 := div_pos h zero_lt_two lemma one_half_pos : (0:α) < 1 / 2 := half_pos zero_lt_one lemma div_two_lt_of_pos (h : 0 < a) : a / 2 < a := by { rw [div_lt_iff (@zero_lt_two α _ _)], exact lt_mul_of_one_lt_right h one_lt_two } lemma half_lt_self : 0 < a → a / 2 < a := div_two_lt_of_pos lemma half_le_self (ha_nonneg : 0 ≤ a) : a / 2 ≤ a := begin by_cases h0 : a = 0, { simp [h0], }, { rw ← ne.def at h0, exact (half_lt_self (lt_of_le_of_ne ha_nonneg h0.symm)).le, }, end lemma one_half_lt_one : (1 / 2 : α) < 1 := half_lt_self zero_lt_one lemma add_sub_div_two_lt (h : a < b) : a + (b - a) / 2 < b := begin rwa [← div_sub_div_same, sub_eq_add_neg, add_comm (b/2), ← add_assoc, ← sub_eq_add_neg, ← lt_sub_iff_add_lt, sub_self_div_two, sub_self_div_two, div_lt_div_right (@zero_lt_two α _ _)] end /-- An inequality involving `2`. -/ lemma sub_one_div_inv_le_two (a2 : 2 ≤ a) : (1 - 1 / a)⁻¹ ≤ 2 := begin -- Take inverses on both sides to obtain `2⁻¹ ≤ 1 - 1 / a` refine trans (inv_le_inv_of_le (inv_pos.mpr zero_lt_two) _) (inv_inv' (2 : α)).le, -- move `1 / a` to the left and `1 - 1 / 2 = 1 / 2` to the right to obtain `1 / a ≤ ⅟ 2` refine trans ((le_sub_iff_add_le.mpr ((_ : _ + 2⁻¹ = _ ).le))) ((sub_le_sub_iff_left 1).mpr _), { -- show 2⁻¹ + 2⁻¹ = 1 exact trans (two_mul _).symm (mul_inv_cancel two_ne_zero) }, { -- take inverses on both sides and use the assumption `2 ≤ a`. exact (one_div a).le.trans (inv_le_inv_of_le zero_lt_two a2) } end /-! ### Miscellaneous lemmas -/ /-- Pullback a `linear_ordered_field` under an injective map. See note [reducible non-instances]. -/ @[reducible] def function.injective.linear_ordered_field {β : Type*} [has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β] [has_sub β] [has_inv β] [has_div β] [nontrivial β] (f : β → α) (hf : function.injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (neg : ∀ x, f (-x) = -f x) (sub : ∀ x y, f (x - y) = f x - f y) (inv : ∀ x, f (x⁻¹) = (f x)⁻¹) (div : ∀ x y, f (x / y) = f x / f y) : linear_ordered_field β := { ..hf.linear_ordered_ring f zero one add mul neg sub, ..hf.field f zero one add mul neg sub inv div} lemma mul_sub_mul_div_mul_neg_iff (hc : c ≠ 0) (hd : d ≠ 0) : (a * d - b * c) / (c * d) < 0 ↔ a / c < b / d := by rw [mul_comm b c, ← div_sub_div _ _ hc hd, sub_lt_zero] alias mul_sub_mul_div_mul_neg_iff ↔ div_lt_div_of_mul_sub_mul_div_neg mul_sub_mul_div_mul_neg lemma mul_sub_mul_div_mul_nonpos_iff (hc : c ≠ 0) (hd : d ≠ 0) : (a * d - b * c) / (c * d) ≤ 0 ↔ a / c ≤ b / d := by rw [mul_comm b c, ← div_sub_div _ _ hc hd, sub_nonpos] alias mul_sub_mul_div_mul_nonpos_iff ↔ div_le_div_of_mul_sub_mul_div_nonpos mul_sub_mul_div_mul_nonpos lemma mul_le_mul_of_mul_div_le (h : a * (b / c) ≤ d) (hc : 0 < c) : b * a ≤ d * c := begin rw [← mul_div_assoc] at h, rwa [mul_comm b, ← div_le_iff hc], end lemma div_mul_le_div_mul_of_div_le_div (h : a / b ≤ c / d) (he : 0 ≤ e) : a / (b * e) ≤ c / (d * e) := begin rw [div_mul_eq_div_mul_one_div, div_mul_eq_div_mul_one_div], exact mul_le_mul_of_nonneg_right h (one_div_nonneg.2 he) end lemma exists_add_lt_and_pos_of_lt (h : b < a) : ∃ c : α, b + c < a ∧ 0 < c := ⟨(a - b) / 2, add_sub_div_two_lt h, div_pos (sub_pos_of_lt h) zero_lt_two⟩ lemma le_of_forall_sub_le (h : ∀ ε > 0, b - ε ≤ a) : b ≤ a := begin contrapose! h, simpa only [and_comm ((0 : α) < _), lt_sub_iff_add_lt, gt_iff_lt] using exists_add_lt_and_pos_of_lt h, end lemma monotone.div_const {β : Type*} [preorder β] {f : β → α} (hf : monotone f) {c : α} (hc : 0 ≤ c) : monotone (λ x, (f x) / c) := by simpa only [div_eq_mul_inv] using hf.mul_const (inv_nonneg.2 hc) lemma strict_mono.div_const {β : Type*} [preorder β] {f : β → α} (hf : strict_mono f) {c : α} (hc : 0 < c) : strict_mono (λ x, (f x) / c) := by simpa only [div_eq_mul_inv] using hf.mul_const (inv_pos.2 hc) @[priority 100] -- see Note [lower instance priority] instance linear_ordered_field.to_densely_ordered : densely_ordered α := { dense := λ a₁ a₂ h, ⟨(a₁ + a₂) / 2, calc a₁ = (a₁ + a₁) / 2 : (add_self_div_two a₁).symm ... < (a₁ + a₂) / 2 : div_lt_div_of_lt zero_lt_two (add_lt_add_left h _), calc (a₁ + a₂) / 2 < (a₂ + a₂) / 2 : div_lt_div_of_lt zero_lt_two (add_lt_add_right h _) ... = a₂ : add_self_div_two a₂⟩ } lemma mul_self_inj_of_nonneg (a0 : 0 ≤ a) (b0 : 0 ≤ b) : a * a = b * b ↔ a = b := mul_self_eq_mul_self_iff.trans $ or_iff_left_of_imp $ λ h, by { subst a, have : b = 0 := le_antisymm (neg_nonneg.1 a0) b0, rw [this, neg_zero] } lemma min_div_div_right {c : α} (hc : 0 ≤ c) (a b : α) : min (a / c) (b / c) = (min a b) / c := eq.symm $ monotone.map_min (λ x y, div_le_div_of_le hc) lemma max_div_div_right {c : α} (hc : 0 ≤ c) (a b : α) : max (a / c) (b / c) = (max a b) / c := eq.symm $ monotone.map_max (λ x y, div_le_div_of_le hc) lemma min_div_div_right_of_nonpos {c : α} (hc : c ≤ 0) (a b : α) : min (a / c) (b / c) = (max a b) / c := eq.symm $ @monotone.map_max α (order_dual α) _ _ _ _ _ (λ x y, div_le_div_of_nonpos_of_le hc) lemma max_div_div_right_of_nonpos {c : α} (hc : c ≤ 0) (a b : α) : max (a / c) (b / c) = (min a b) / c := eq.symm $ @monotone.map_min α (order_dual α) _ _ _ _ _ (λ x y, div_le_div_of_nonpos_of_le hc) lemma abs_div (a b : α) : abs (a / b) = abs a / abs b := (abs_hom : monoid_with_zero_hom α α).map_div a b lemma abs_one_div (a : α) : abs (1 / a) = 1 / abs a := by rw [abs_div, abs_one] lemma abs_inv (a : α) : abs a⁻¹ = (abs a)⁻¹ := (abs_hom : monoid_with_zero_hom α α).map_inv' a -- TODO: add lemmas with `a⁻¹`. lemma one_div_strict_mono_decr_on : strict_mono_decr_on (λ x : α, 1 / x) (set.Ioi 0) := λ x x1 y y1 xy, (one_div_lt_one_div (set.mem_Ioi.mp y1) (set.mem_Ioi.mp x1)).mpr xy lemma one_div_pow_le_one_div_pow_of_le (a1 : 1 ≤ a) {m n : ℕ} (mn : m ≤ n) : 1 / a ^ n ≤ 1 / a ^ m := by refine (one_div_le_one_div _ _).mpr (pow_le_pow a1 mn); exact pow_pos (zero_lt_one.trans_le a1) _ lemma one_div_pow_lt_one_div_pow_of_lt (a1 : 1 < a) {m n : ℕ} (mn : m < n) : 1 / a ^ n < 1 / a ^ m := by refine (one_div_lt_one_div _ _).mpr (pow_lt_pow a1 mn); exact pow_pos (trans zero_lt_one a1) _ lemma one_div_pow_mono (a1 : 1 ≤ a) : monotone (λ n : ℕ, order_dual.to_dual 1 / a ^ n) := λ m n, one_div_pow_le_one_div_pow_of_le a1 lemma one_div_pow_strict_mono (a1 : 1 < a) : strict_mono (λ n : ℕ, order_dual.to_dual 1 / a ^ n) := λ m n, one_div_pow_lt_one_div_pow_of_lt a1 end linear_ordered_field
49f3e208fd7fbe969e20f76c6f8ab5ccbfbd361f
82e44445c70db0f03e30d7be725775f122d72f3e
/src/analysis/normed_space/normed_group_hom.lean
e1942200aeb911049c649b8c97e48335eedb2888
[ "Apache-2.0" ]
permissive
stjordanis/mathlib
51e286d19140e3788ef2c470bc7b953e4991f0c9
2568d41bca08f5d6bf39d915434c8447e21f42ee
refs/heads/master
1,631,748,053,501
1,627,938,886,000
1,627,938,886,000
228,728,358
0
0
Apache-2.0
1,576,630,588,000
1,576,630,587,000
null
UTF-8
Lean
false
false
26,742
lean
/- Copyright (c) 2021 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import analysis.normed_space.basic /-! # Normed groups homomorphisms This file gathers definitions and elementary constructions about bounded group homomorphisms between normed (abelian) groups (abbreviated to "normed group homs"). The main lemmas relate the boundedness condition to continuity and Lipschitzness. The main construction is to endow the type of normed group homs between two given normed groups with a group structure and a norm, giving rise to a normed group structure. We provide several simple constructions for normed group homs, like kernel, range and equalizer. Some easy other constructions are related to subgroups of normed groups. Since a lot of elementary properties don't require `∥x∥ = 0 → x = 0` we start setting up the theory of `semi_normed_group_hom` and we specialize to `normed_group_hom` when needed. -/ noncomputable theory open_locale nnreal big_operators /-- A morphism of seminormed abelian groups is a bounded group homomorphism. -/ structure normed_group_hom (V W : Type*) [semi_normed_group V] [semi_normed_group W] := (to_fun : V → W) (map_add' : ∀ v₁ v₂, to_fun (v₁ + v₂) = to_fun v₁ + to_fun v₂) (bound' : ∃ C, ∀ v, ∥to_fun v∥ ≤ C * ∥v∥) namespace add_monoid_hom variables {V W : Type*} [semi_normed_group V] [semi_normed_group W] {f g : normed_group_hom V W} /-- Associate to a group homomorphism a bounded group homomorphism under a norm control condition. See `add_monoid_hom.mk_normed_group_hom'` for a version that uses `ℝ≥0` for the bound. -/ def mk_normed_group_hom (f : V →+ W) (C : ℝ) (h : ∀ v, ∥f v∥ ≤ C * ∥v∥) : normed_group_hom V W := { bound' := ⟨C, h⟩, ..f } /-- Associate to a group homomorphism a bounded group homomorphism under a norm control condition. See `add_monoid_hom.mk_normed_group_hom` for a version that uses `ℝ` for the bound. -/ def mk_normed_group_hom' (f : V →+ W) (C : ℝ≥0) (hC : ∀ x, nnnorm (f x) ≤ C * nnnorm x) : normed_group_hom V W := { bound' := ⟨C, hC⟩ .. f} end add_monoid_hom lemma exists_pos_bound_of_bound {V W : Type*} [semi_normed_group V] [semi_normed_group W] {f : V → W} (M : ℝ) (h : ∀x, ∥f x∥ ≤ M * ∥x∥) : ∃ N, 0 < N ∧ ∀x, ∥f x∥ ≤ N * ∥x∥ := ⟨max M 1, lt_of_lt_of_le zero_lt_one (le_max_right _ _), λx, calc ∥f x∥ ≤ M * ∥x∥ : h x ... ≤ max M 1 * ∥x∥ : mul_le_mul_of_nonneg_right (le_max_left _ _) (norm_nonneg _) ⟩ namespace normed_group_hom variables {V V₁ V₂ V₃ : Type*} variables [semi_normed_group V] [semi_normed_group V₁] [semi_normed_group V₂] [semi_normed_group V₃] variables {f g : normed_group_hom V₁ V₂} instance : has_coe_to_fun (normed_group_hom V₁ V₂) := ⟨_, normed_group_hom.to_fun⟩ initialize_simps_projections normed_group_hom (to_fun → apply) lemma coe_inj (H : ⇑f = g) : f = g := by cases f; cases g; congr'; exact funext H lemma coe_injective : @function.injective (normed_group_hom V₁ V₂) (V₁ → V₂) coe_fn := by apply coe_inj lemma coe_inj_iff : f = g ↔ ⇑f = g := ⟨congr_arg _, coe_inj⟩ @[ext] lemma ext (H : ∀ x, f x = g x) : f = g := coe_inj $ funext H lemma ext_iff : f = g ↔ ∀ x, f x = g x := ⟨by rintro rfl x; refl, ext⟩ variables (f g) @[simp] lemma to_fun_eq_coe : f.to_fun = f := rfl @[simp] lemma coe_mk (f) (h₁) (h₂) (h₃) : ⇑(⟨f, h₁, h₂, h₃⟩ : normed_group_hom V₁ V₂) = f := rfl @[simp] lemma coe_mk_normed_group_hom (f : V₁ →+ V₂) (C) (hC) : ⇑(f.mk_normed_group_hom C hC) = f := rfl @[simp] lemma coe_mk_normed_group_hom' (f : V₁ →+ V₂) (C) (hC) : ⇑(f.mk_normed_group_hom' C hC) = f := rfl /-- The group homomorphism underlying a bounded group homomorphism. -/ def to_add_monoid_hom (f : normed_group_hom V₁ V₂) : V₁ →+ V₂ := add_monoid_hom.mk' f f.map_add' @[simp] lemma coe_to_add_monoid_hom : ⇑f.to_add_monoid_hom = f := rfl lemma to_add_monoid_hom_injective : function.injective (@normed_group_hom.to_add_monoid_hom V₁ V₂ _ _) := λ f g h, coe_inj $ show ⇑f.to_add_monoid_hom = g, by { rw h, refl } @[simp] lemma mk_to_add_monoid_hom (f) (h₁) (h₂) : (⟨f, h₁, h₂⟩ : normed_group_hom V₁ V₂).to_add_monoid_hom = add_monoid_hom.mk' f h₁ := rfl @[simp] lemma map_zero : f 0 = 0 := f.to_add_monoid_hom.map_zero @[simp] lemma map_add (x y) : f (x + y) = f x + f y := f.to_add_monoid_hom.map_add _ _ @[simp] lemma map_sum {ι : Type*} (v : ι → V₁) (s : finset ι) : f (∑ i in s, v i) = ∑ i in s, f (v i) := f.to_add_monoid_hom.map_sum _ _ @[simp] lemma map_sub (x y) : f (x - y) = f x - f y := f.to_add_monoid_hom.map_sub _ _ @[simp] lemma map_neg (x) : f (-x) = -(f x) := f.to_add_monoid_hom.map_neg _ lemma bound : ∃ C, 0 < C ∧ ∀ x, ∥f x∥ ≤ C * ∥x∥ := let ⟨C, hC⟩ := f.bound' in exists_pos_bound_of_bound _ hC theorem antilipschitz_of_norm_ge {K : ℝ≥0} (h : ∀ x, ∥x∥ ≤ K * ∥f x∥) : antilipschitz_with K f := antilipschitz_with.of_le_mul_dist $ λ x y, by simpa only [dist_eq_norm, f.map_sub] using h (x - y) /-! ### The operator norm -/ /-- The operator norm of a seminormed group homomorphism is the inf of all its bounds. -/ def op_norm (f : normed_group_hom V₁ V₂) := Inf {c | 0 ≤ c ∧ ∀ x, ∥f x∥ ≤ c * ∥x∥} instance has_op_norm : has_norm (normed_group_hom V₁ V₂) := ⟨op_norm⟩ lemma norm_def : ∥f∥ = Inf {c | 0 ≤ c ∧ ∀ x, ∥f x∥ ≤ c * ∥x∥} := rfl -- So that invocations of `real.Inf_le` make sense: we show that the set of -- bounds is nonempty and bounded below. lemma bounds_nonempty {f : normed_group_hom V₁ V₂} : ∃ c, c ∈ { c | 0 ≤ c ∧ ∀ x, ∥f x∥ ≤ c * ∥x∥ } := let ⟨M, hMp, hMb⟩ := f.bound in ⟨M, le_of_lt hMp, hMb⟩ lemma bounds_bdd_below {f : normed_group_hom V₁ V₂} : bdd_below {c | 0 ≤ c ∧ ∀ x, ∥f x∥ ≤ c * ∥x∥} := ⟨0, λ _ ⟨hn, _⟩, hn⟩ lemma op_norm_nonneg : 0 ≤ ∥f∥ := real.lb_le_Inf _ bounds_nonempty (λ _ ⟨hx, _⟩, hx) /-- The fundamental property of the operator norm: `∥f x∥ ≤ ∥f∥ * ∥x∥`. -/ theorem le_op_norm (x : V₁) : ∥f x∥ ≤ ∥f∥ * ∥x∥ := begin obtain ⟨C, Cpos, hC⟩ := f.bound, replace hC := hC x, by_cases h : ∥x∥ = 0, { rwa [h, mul_zero] at ⊢ hC }, have hlt : 0 < ∥x∥ := lt_of_le_of_ne (norm_nonneg x) (ne.symm h), exact (div_le_iff hlt).mp ((real.le_Inf _ bounds_nonempty bounds_bdd_below).2 (λ c ⟨_, hc⟩, (div_le_iff hlt).mpr $ by { apply hc })), end theorem le_op_norm_of_le {c : ℝ} {x} (h : ∥x∥ ≤ c) : ∥f x∥ ≤ ∥f∥ * c := le_trans (f.le_op_norm x) (mul_le_mul_of_nonneg_left h f.op_norm_nonneg) theorem le_of_op_norm_le {c : ℝ} (h : ∥f∥ ≤ c) (x : V₁) : ∥f x∥ ≤ c * ∥x∥ := (f.le_op_norm x).trans (mul_le_mul_of_nonneg_right h (norm_nonneg x)) /-- continuous linear maps are Lipschitz continuous. -/ theorem lipschitz : lipschitz_with ⟨∥f∥, op_norm_nonneg f⟩ f := lipschitz_with.of_dist_le_mul $ λ x y, by { rw [dist_eq_norm, dist_eq_norm, ←map_sub], apply le_op_norm } protected lemma uniform_continuous (f : normed_group_hom V₁ V₂) : uniform_continuous f := f.lipschitz.uniform_continuous @[continuity] protected lemma continuous (f : normed_group_hom V₁ V₂) : continuous f := f.uniform_continuous.continuous lemma ratio_le_op_norm (x : V₁) : ∥f x∥ / ∥x∥ ≤ ∥f∥ := div_le_of_nonneg_of_le_mul (norm_nonneg _) f.op_norm_nonneg (le_op_norm _ _) /-- If one controls the norm of every `f x`, then one controls the norm of `f`. -/ lemma op_norm_le_bound {M : ℝ} (hMp: 0 ≤ M) (hM : ∀ x, ∥f x∥ ≤ M * ∥x∥) : ∥f∥ ≤ M := real.Inf_le _ bounds_bdd_below ⟨hMp, hM⟩ theorem op_norm_le_of_lipschitz {f : normed_group_hom V₁ V₂} {K : ℝ≥0} (hf : lipschitz_with K f) : ∥f∥ ≤ K := f.op_norm_le_bound K.2 $ λ x, by simpa only [dist_zero_right, f.map_zero] using hf.dist_le_mul x 0 /-- If a bounded group homomorphism map is constructed from a group homomorphism via the constructor `mk_normed_group_hom`, then its norm is bounded by the bound given to the constructor if it is nonnegative. -/ lemma mk_normed_group_hom_norm_le (f : V₁ →+ V₂) {C : ℝ} (hC : 0 ≤ C) (h : ∀x, ∥f x∥ ≤ C * ∥x∥) : ∥f.mk_normed_group_hom C h∥ ≤ C := op_norm_le_bound _ hC h /-- If a bounded group homomorphism map is constructed from a group homomorphism via the constructor `mk_normed_group_hom`, then its norm is bounded by the bound given to the constructor or zero if this bound is negative. -/ lemma mk_normed_group_hom_norm_le' (f : V₁ →+ V₂) {C : ℝ} (h : ∀x, ∥f x∥ ≤ C * ∥x∥) : ∥f.mk_normed_group_hom C h∥ ≤ max C 0 := op_norm_le_bound _ (le_max_right _ _) $ λ x, (h x).trans $ mul_le_mul_of_nonneg_right (le_max_left _ _) (norm_nonneg x) alias mk_normed_group_hom_norm_le ← add_monoid_hom.mk_normed_group_hom_norm_le alias mk_normed_group_hom_norm_le' ← add_monoid_hom.mk_normed_group_hom_norm_le' /-! ### Addition of normed group homs -/ /-- Addition of normed group homs. -/ instance : has_add (normed_group_hom V₁ V₂) := ⟨λ f g, (f.to_add_monoid_hom + g.to_add_monoid_hom).mk_normed_group_hom (∥f∥ + ∥g∥) $ λ v, calc ∥f v + g v∥ ≤ ∥f v∥ + ∥g v∥ : norm_add_le _ _ ... ≤ ∥f∥ * ∥v∥ + ∥g∥ * ∥v∥ : add_le_add (le_op_norm f v) (le_op_norm g v) ... = (∥f∥ + ∥g∥) * ∥v∥ : by rw add_mul⟩ /-- The operator norm satisfies the triangle inequality. -/ theorem op_norm_add_le : ∥f + g∥ ≤ ∥f∥ + ∥g∥ := mk_normed_group_hom_norm_le _ (add_nonneg (op_norm_nonneg _) (op_norm_nonneg _)) _ /-- Terms containing `@has_add.add (has_coe_to_fun.F ...) pi.has_add` seem to cause leanchecker to [crash due to an out-of-memory condition](https://github.com/leanprover-community/lean/issues/543). As a workaround, we add a type annotation: `(f + g : V₁ → V₂)` -/ library_note "addition on function coercions" -- see Note [addition on function coercions] @[simp] lemma coe_add (f g : normed_group_hom V₁ V₂) : ⇑(f + g) = (f + g : V₁ → V₂) := rfl @[simp] lemma add_apply (f g : normed_group_hom V₁ V₂) (v : V₁) : (f + g : normed_group_hom V₁ V₂) v = f v + g v := rfl /-! ### The zero normed group hom -/ instance : has_zero (normed_group_hom V₁ V₂) := ⟨(0 : V₁ →+ V₂).mk_normed_group_hom 0 (by simp)⟩ instance : inhabited (normed_group_hom V₁ V₂) := ⟨0⟩ /-- The norm of the `0` operator is `0`. -/ theorem op_norm_zero : ∥(0 : normed_group_hom V₁ V₂)∥ = 0 := le_antisymm (real.Inf_le _ bounds_bdd_below ⟨ge_of_eq rfl, λ _, le_of_eq (by { rw [zero_mul], exact norm_zero })⟩) (op_norm_nonneg _) /-- For normed groups, an operator is zero iff its norm vanishes. -/ theorem op_norm_zero_iff {V₁ V₂ : Type*} [normed_group V₁] [normed_group V₂] {f : normed_group_hom V₁ V₂} : ∥f∥ = 0 ↔ f = 0 := iff.intro (λ hn, ext (λ x, norm_le_zero_iff.1 (calc _ ≤ ∥f∥ * ∥x∥ : le_op_norm _ _ ... = _ : by rw [hn, zero_mul]))) (λ hf, by rw [hf, op_norm_zero] ) -- see Note [addition on function coercions] @[simp] lemma coe_zero : ⇑(0 : normed_group_hom V₁ V₂) = (0 : V₁ → V₂) := rfl @[simp] lemma zero_apply (v : V₁) : (0 : normed_group_hom V₁ V₂) v = 0 := rfl variables {f g} /-! ### The identity normed group hom -/ variable (V) /-- The identity as a continuous normed group hom. -/ @[simps] def id : normed_group_hom V V := (add_monoid_hom.id V).mk_normed_group_hom 1 (by simp [le_refl]) /-- The norm of the identity is at most `1`. It is in fact `1`, except when the norm of every element vanishes, where it is `0`. (Since we are working with seminorms this can happen even if the space is non-trivial.) It means that one can not do better than an inequality in general. -/ lemma norm_id_le : ∥(id V : normed_group_hom V V)∥ ≤ 1 := op_norm_le_bound _ zero_le_one (λx, by simp) /-- If there is an element with norm different from `0`, then the norm of the identity equals `1`. (Since we are working with seminorms supposing that the space is non-trivial is not enough.) -/ lemma norm_id_of_nontrivial_seminorm (h : ∃ (x : V), ∥x∥ ≠ 0 ) : ∥(id V)∥ = 1 := le_antisymm (norm_id_le V) $ let ⟨x, hx⟩ := h in have _ := (id V).ratio_le_op_norm x, by rwa [id_apply, div_self hx] at this /-- If a normed space is non-trivial, then the norm of the identity equals `1`. -/ lemma norm_id {V : Type*} [normed_group V] [nontrivial V] : ∥(id V)∥ = 1 := begin refine norm_id_of_nontrivial_seminorm V _, obtain ⟨x, hx⟩ := exists_ne (0 : V), exact ⟨x, ne_of_gt (norm_pos_iff.2 hx)⟩, end lemma coe_id : ((normed_group_hom.id V) : V → V) = (_root_.id : V → V) := rfl /-! ### The negation of a normed group hom -/ /-- Opposite of a normed group hom. -/ instance : has_neg (normed_group_hom V₁ V₂) := ⟨λ f, (-f.to_add_monoid_hom).mk_normed_group_hom (∥f∥) (λ v, by simp [le_op_norm f v])⟩ -- see Note [addition on function coercions] @[simp] lemma coe_neg (f : normed_group_hom V₁ V₂) : ⇑(-f) = (-f : V₁ → V₂) := rfl @[simp] lemma neg_apply (f : normed_group_hom V₁ V₂) (v : V₁) : (-f : normed_group_hom V₁ V₂) v = - (f v) := rfl lemma op_norm_neg (f : normed_group_hom V₁ V₂) : ∥-f∥ = ∥f∥ := by simp only [norm_def, coe_neg, norm_neg, pi.neg_apply] /-! ### Subtraction of normed group homs -/ /-- Subtraction of normed group homs. -/ instance : has_sub (normed_group_hom V₁ V₂) := ⟨λ f g, { bound' := begin simp only [add_monoid_hom.sub_apply, add_monoid_hom.to_fun_eq_coe, sub_eq_add_neg], exact (f + -g).bound' end, .. (f.to_add_monoid_hom - g.to_add_monoid_hom) }⟩ -- see Note [addition on function coercions] @[simp] lemma coe_sub (f g : normed_group_hom V₁ V₂) : ⇑(f - g) = (f - g : V₁ → V₂) := rfl @[simp] lemma sub_apply (f g : normed_group_hom V₁ V₂) (v : V₁) : (f - g : normed_group_hom V₁ V₂) v = f v - g v := rfl /-! ### Normed group structure on normed group homs -/ /-- Homs between two given normed groups form a commutative additive group. -/ instance : add_comm_group (normed_group_hom V₁ V₂) := coe_injective.add_comm_group _ rfl (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) /-- Normed group homomorphisms themselves form a seminormed group with respect to the operator norm. -/ instance to_semi_normed_group : semi_normed_group (normed_group_hom V₁ V₂) := semi_normed_group.of_core _ ⟨op_norm_zero, op_norm_add_le, op_norm_neg⟩ /-- Normed group homomorphisms themselves form a normed group with respect to the operator norm. -/ instance to_normed_group {V₁ V₂ : Type*} [normed_group V₁] [normed_group V₂] : normed_group (normed_group_hom V₁ V₂) := normed_group.of_core _ ⟨λ f, op_norm_zero_iff, op_norm_add_le, op_norm_neg⟩ /-- Coercion of a `normed_group_hom` is an `add_monoid_hom`. Similar to `add_monoid_hom.coe_fn` -/ @[simps] def coe_fn_add_hom : normed_group_hom V₁ V₂ →+ (V₁ → V₂) := { to_fun := coe_fn, map_zero' := coe_zero, map_add' := coe_add} @[simp] lemma coe_sum {ι : Type*} (s : finset ι) (f : ι → normed_group_hom V₁ V₂) : ⇑(∑ i in s, f i) = ∑ i in s, (f i) := (coe_fn_add_hom : _ →+ (V₁ → V₂)).map_sum f s lemma sum_apply {ι : Type*} (s : finset ι) (f : ι → normed_group_hom V₁ V₂) (v : V₁) : (∑ i in s, f i) v = ∑ i in s, (f i v) := by simp only [coe_sum, finset.sum_apply] /-! ### Composition of normed group homs -/ /-- The composition of continuous normed group homs. -/ @[simps] protected def comp (g : normed_group_hom V₂ V₃) (f : normed_group_hom V₁ V₂) : normed_group_hom V₁ V₃ := (g.to_add_monoid_hom.comp f.to_add_monoid_hom).mk_normed_group_hom (∥g∥ * ∥f∥) $ λ v, calc ∥g (f v)∥ ≤ ∥g∥ * ∥f v∥ : le_op_norm _ _ ... ≤ ∥g∥ * (∥f∥ * ∥v∥) : mul_le_mul_of_nonneg_left (le_op_norm _ _) (op_norm_nonneg _) ... = ∥g∥ * ∥f∥ * ∥v∥ : by rw mul_assoc lemma norm_comp_le (g : normed_group_hom V₂ V₃) (f : normed_group_hom V₁ V₂) : ∥g.comp f∥ ≤ ∥g∥ * ∥f∥ := mk_normed_group_hom_norm_le _ (mul_nonneg (op_norm_nonneg _) (op_norm_nonneg _)) _ lemma norm_comp_le_of_le {g : normed_group_hom V₂ V₃} {C₁ C₂ : ℝ} (hg : ∥g∥ ≤ C₂) (hf : ∥f∥ ≤ C₁) : ∥g.comp f∥ ≤ C₂ * C₁ := le_trans (norm_comp_le g f) $ mul_le_mul hg hf (norm_nonneg _) (le_trans (norm_nonneg _) hg) lemma norm_comp_le_of_le' {g : normed_group_hom V₂ V₃} (C₁ C₂ C₃ : ℝ) (h : C₃ = C₂ * C₁) (hg : ∥g∥ ≤ C₂) (hf : ∥f∥ ≤ C₁) : ∥g.comp f∥ ≤ C₃ := by { rw h, exact norm_comp_le_of_le hg hf } /-- Composition of normed groups hom as an additive group morphism. -/ def comp_hom : (normed_group_hom V₂ V₃) →+ (normed_group_hom V₁ V₂) →+ (normed_group_hom V₁ V₃) := add_monoid_hom.mk' (λ g, add_monoid_hom.mk' (λ f, g.comp f) (by { intros, ext, exact g.map_add _ _ })) (by { intros, ext, simp only [comp_apply, pi.add_apply, function.comp_app, add_monoid_hom.add_apply, add_monoid_hom.mk'_apply, coe_add] }) @[simp] lemma comp_zero (f : normed_group_hom V₂ V₃) : f.comp (0 : normed_group_hom V₁ V₂) = 0 := by { ext, exact f.map_zero } @[simp] lemma zero_comp (f : normed_group_hom V₁ V₂) : (0 : normed_group_hom V₂ V₃).comp f = 0 := by { ext, refl } lemma comp_assoc {V₄: Type* } [semi_normed_group V₄] (h : normed_group_hom V₃ V₄) (g : normed_group_hom V₂ V₃) (f : normed_group_hom V₁ V₂) : (h.comp g).comp f = h.comp (g.comp f) := by { ext, refl } lemma coe_comp (f : normed_group_hom V₁ V₂) (g : normed_group_hom V₂ V₃) : (g.comp f : V₁ → V₃) = (g : V₂ → V₃) ∘ (f : V₁ → V₂) := rfl end normed_group_hom namespace normed_group_hom variables {V W V₁ V₂ V₃ : Type*} variables [semi_normed_group V] [semi_normed_group W] [semi_normed_group V₁] [semi_normed_group V₂] [semi_normed_group V₃] /-- The inclusion of an `add_subgroup`, as bounded group homomorphism. -/ @[simps] def incl (s : add_subgroup V) : normed_group_hom s V := { to_fun := (coe : s → V), map_add' := λ v w, add_subgroup.coe_add _ _ _, bound' := ⟨1, λ v, by { rw [one_mul], refl }⟩ } lemma norm_incl {V' : add_subgroup V} (x : V') : ∥incl _ x∥ = ∥x∥ := rfl /-!### Kernel -/ section kernels variables (f : normed_group_hom V₁ V₂) (g : normed_group_hom V₂ V₃) /-- The kernel of a bounded group homomorphism. Naturally endowed with a `semi_normed_group` instance. -/ def ker : add_subgroup V₁ := f.to_add_monoid_hom.ker lemma mem_ker (v : V₁) : v ∈ f.ker ↔ f v = 0 := by { erw f.to_add_monoid_hom.mem_ker, refl } /-- Given a normed group hom `f : V₁ → V₂` satisfying `g.comp f = 0` for some `g : V₂ → V₃`, the corestriction of `f` to the kernel of `g`. -/ @[simps] def ker.lift (h : g.comp f = 0) : normed_group_hom V₁ g.ker := { to_fun := λ v, ⟨f v, by { erw g.mem_ker, show (g.comp f) v = 0, rw h, refl }⟩, map_add' := λ v w, by { simp only [map_add], refl }, bound' := f.bound' } @[simp] lemma ker.incl_comp_lift (h : g.comp f = 0) : (incl g.ker).comp (ker.lift f g h) = f := by { ext, refl } @[simp] lemma ker_zero : (0 : normed_group_hom V₁ V₂).ker = ⊤ := by { ext, simp [mem_ker] } lemma coe_ker : (f.ker : set V₁) = (f : V₁ → V₂) ⁻¹' {0} := rfl lemma is_closed_ker {V₂ : Type*} [normed_group V₂] (f : normed_group_hom V₁ V₂) : is_closed (f.ker : set V₁) := f.coe_ker ▸ is_closed.preimage f.continuous (t1_space.t1 0) end kernels /-! ### Range -/ section range variables (f : normed_group_hom V₁ V₂) (g : normed_group_hom V₂ V₃) /-- The image of a bounded group homomorphism. Naturally endowed with a `semi_normed_group` instance. -/ def range : add_subgroup V₂ := f.to_add_monoid_hom.range lemma mem_range (v : V₂) : v ∈ f.range ↔ ∃ w, f w = v := by { rw [range, add_monoid_hom.mem_range], refl } lemma comp_range : (g.comp f).range = add_subgroup.map g.to_add_monoid_hom f.range := by { erw add_monoid_hom.map_range, refl } lemma incl_range (s : add_subgroup V₁) : (incl s).range = s := by { ext x, exact ⟨λ ⟨y, hy⟩, by { rw ← hy; simp }, λ hx, ⟨⟨x, hx⟩, by simp⟩⟩ } @[simp] lemma range_comp_incl_top : (f.comp (incl (⊤ : add_subgroup V₁))).range = f.range := by simpa [comp_range, incl_range, ← add_monoid_hom.range_eq_map] end range variables {f : normed_group_hom V W} /-- A `normed_group_hom` is *norm-nonincreasing* if `∥f v∥ ≤ ∥v∥` for all `v`. -/ def norm_noninc (f : normed_group_hom V W) : Prop := ∀ v, ∥f v∥ ≤ ∥v∥ namespace norm_noninc lemma norm_noninc_iff_norm_le_one : f.norm_noninc ↔ ∥f∥ ≤ 1 := begin refine ⟨λ h, _, λ h, λ v, _⟩, { refine op_norm_le_bound _ (zero_le_one) (λ v, _), simpa [one_mul] using h v }, { simpa using le_of_op_norm_le f h v } end lemma zero : (0 : normed_group_hom V₁ V₂).norm_noninc := λ v, by simp lemma id : (id V).norm_noninc := λ v, le_rfl lemma comp {g : normed_group_hom V₂ V₃} {f : normed_group_hom V₁ V₂} (hg : g.norm_noninc) (hf : f.norm_noninc) : (g.comp f).norm_noninc := λ v, (hg (f v)).trans (hf v) end norm_noninc section isometry lemma isometry_iff_norm (f : normed_group_hom V W) : isometry f ↔ ∀ v, ∥f v∥ = ∥v∥ := add_monoid_hom.isometry_iff_norm f.to_add_monoid_hom lemma isometry_of_norm (f : normed_group_hom V W) (hf : ∀ v, ∥f v∥ = ∥v∥) : isometry f := f.isometry_iff_norm.mpr hf lemma norm_eq_of_isometry {f : normed_group_hom V W} (hf : isometry f) (v : V) : ∥f v∥ = ∥v∥ := f.isometry_iff_norm.mp hf v lemma isometry_id : @isometry V V _ _ (id V) := isometry_id lemma isometry_comp {g : normed_group_hom V₂ V₃} {f : normed_group_hom V₁ V₂} (hg : isometry g) (hf : isometry f) : isometry (g.comp f) := hg.comp hf lemma norm_noninc_of_isometry (hf : isometry f) : f.norm_noninc := λ v, le_of_eq $ norm_eq_of_isometry hf v end isometry variables {W₁ W₂ W₃ : Type*} [semi_normed_group W₁] [semi_normed_group W₂] [semi_normed_group W₃] variables (f) (g : normed_group_hom V W) variables {f₁ g₁ : normed_group_hom V₁ W₁} variables {f₂ g₂ : normed_group_hom V₂ W₂} variables {f₃ g₃ : normed_group_hom V₃ W₃} /-- The equalizer of two morphisms `f g : normed_group_hom V W`. -/ def equalizer := (f - g).ker namespace equalizer /-- The inclusion of `f.equalizer g` as a `normed_group_hom`. -/ def ι : normed_group_hom (f.equalizer g) V := incl _ lemma comp_ι_eq : f.comp (ι f g) = g.comp (ι f g) := by { ext, rw [comp_apply, comp_apply, ← sub_eq_zero, ← normed_group_hom.sub_apply], exact x.2 } variables {f g} /-- If `φ : normed_group_hom V₁ V` is such that `f.comp φ = g.comp φ`, the induced morphism `normed_group_hom V₁ (f.equalizer g)`. -/ @[simps] def lift (φ : normed_group_hom V₁ V) (h : f.comp φ = g.comp φ) : normed_group_hom V₁ (f.equalizer g) := { to_fun := λ v, ⟨φ v, show (f - g) (φ v) = 0, by rw [normed_group_hom.sub_apply, sub_eq_zero, ← comp_apply, h, comp_apply]⟩, map_add' := λ v₁ v₂, by { ext, simp only [map_add, add_subgroup.coe_add, subtype.coe_mk] }, bound' := by { obtain ⟨C, C_pos, hC⟩ := φ.bound, exact ⟨C, hC⟩ } } @[simp] lemma ι_comp_lift (φ : normed_group_hom V₁ V) (h : f.comp φ = g.comp φ) : (ι _ _).comp (lift φ h) = φ := by { ext, refl } /-- The lifting property of the equalizer as an equivalence. -/ @[simps] def lift_equiv : {φ : normed_group_hom V₁ V // f.comp φ = g.comp φ} ≃ normed_group_hom V₁ (f.equalizer g) := { to_fun := λ φ, lift φ φ.prop, inv_fun := λ ψ, ⟨(ι f g).comp ψ, by { rw [← comp_assoc, ← comp_assoc, comp_ι_eq] }⟩, left_inv := λ φ, by simp, right_inv := λ ψ, by { ext, refl } } /-- Given `φ : normed_group_hom V₁ V₂` and `ψ : normed_group_hom W₁ W₂` such that `ψ.comp f₁ = f₂.comp φ` and `ψ.comp g₁ = g₂.comp φ`, the induced morphism `normed_group_hom (f₁.equalizer g₁) (f₂.equalizer g₂)`. -/ def map (φ : normed_group_hom V₁ V₂) (ψ : normed_group_hom W₁ W₂) (hf : ψ.comp f₁ = f₂.comp φ) (hg : ψ.comp g₁ = g₂.comp φ) : normed_group_hom (f₁.equalizer g₁) (f₂.equalizer g₂) := lift (φ.comp $ ι _ _) $ by { simp only [← comp_assoc, ← hf, ← hg], simp only [comp_assoc, comp_ι_eq] } variables {φ : normed_group_hom V₁ V₂} {ψ : normed_group_hom W₁ W₂} variables {φ' : normed_group_hom V₂ V₃} {ψ' : normed_group_hom W₂ W₃} @[simp] lemma ι_comp_map (hf : ψ.comp f₁ = f₂.comp φ) (hg : ψ.comp g₁ = g₂.comp φ) : (ι f₂ g₂).comp (map φ ψ hf hg) = φ.comp (ι _ _) := ι_comp_lift _ _ @[simp] lemma map_id : map (id V₁) (id W₁) rfl rfl = id (f₁.equalizer g₁) := by { ext, refl } lemma comm_sq₂ (hf : ψ.comp f₁ = f₂.comp φ) (hf' : ψ'.comp f₂ = f₃.comp φ') : (ψ'.comp ψ).comp f₁ = f₃.comp (φ'.comp φ) := by rw [comp_assoc, hf, ← comp_assoc, hf', comp_assoc] lemma map_comp_map (hf : ψ.comp f₁ = f₂.comp φ) (hg : ψ.comp g₁ = g₂.comp φ) (hf' : ψ'.comp f₂ = f₃.comp φ') (hg' : ψ'.comp g₂ = g₃.comp φ') : (map φ' ψ' hf' hg').comp (map φ ψ hf hg) = map (φ'.comp φ) (ψ'.comp ψ) (comm_sq₂ hf hf') (comm_sq₂ hg hg') := by { ext, refl } lemma ι_norm_noninc : (ι f g).norm_noninc := λ v, le_rfl /-- The lifting of a norm nonincreasing morphism is norm nonincreasing. -/ lemma lift_norm_noninc (φ : normed_group_hom V₁ V) (h : f.comp φ = g.comp φ) (hφ : φ.norm_noninc) : (lift φ h).norm_noninc := hφ /-- If `φ` satisfies `∥φ∥ ≤ C`, then the same is true for the lifted morphism. -/ lemma norm_lift_le (φ : normed_group_hom V₁ V) (h : f.comp φ = g.comp φ) (C : ℝ) (hφ : ∥φ∥ ≤ C) : ∥(lift φ h)∥ ≤ C := hφ lemma map_norm_noninc (hf : ψ.comp f₁ = f₂.comp φ) (hg : ψ.comp g₁ = g₂.comp φ) (hφ : φ.norm_noninc) : (map φ ψ hf hg).norm_noninc := lift_norm_noninc _ _ $ hφ.comp ι_norm_noninc lemma norm_map_le (hf : ψ.comp f₁ = f₂.comp φ) (hg : ψ.comp g₁ = g₂.comp φ) (C : ℝ) (hφ : ∥φ.comp (ι f₁ g₁)∥ ≤ C) : ∥map φ ψ hf hg∥ ≤ C := norm_lift_le _ _ _ hφ end equalizer end normed_group_hom
2b572b8969aca96eac220629d5f985c744d942bd
ff5230333a701471f46c57e8c115a073ebaaa448
/library/data/rbtree/insert.lean
2c89dfaf991569bda2fd417e3ce449ba6781dfc5
[ "Apache-2.0" ]
permissive
stanford-cs242/lean
f81721d2b5d00bc175f2e58c57b710d465e6c858
7bd861261f4a37326dcf8d7a17f1f1f330e4548c
refs/heads/master
1,600,957,431,849
1,576,465,093,000
1,576,465,093,000
225,779,423
0
3
Apache-2.0
1,575,433,936,000
1,575,433,935,000
null
UTF-8
Lean
false
false
33,438
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 -/ import data.rbtree.find universes u v local attribute [simp] rbnode.lift namespace rbnode variables {α : Type u} open color @[simp] lemma balance1_eq₁ (l : rbnode α) (x r₁ y r₂ v t) : balance1 (red_node l x r₁) y r₂ v t = red_node (black_node l x r₁) y (black_node r₂ v t) := begin cases r₂; refl end @[simp] lemma balance1_eq₂ (l₁ : rbnode α) (y l₂ x r v t) : get_color l₁ ≠ red → balance1 l₁ y (red_node l₂ x r) v t = red_node (black_node l₁ y l₂) x (black_node r v t) := begin cases l₁; simp [get_color, balance1] end @[simp] lemma balance1_eq₃ (l : rbnode α) (y r v t) : get_color l ≠ red → get_color r ≠ red → balance1 l y r v t = black_node (red_node l y r) v t := begin cases l; cases r; simp [get_color, balance1] end @[simp] lemma balance2_eq₁ (l : rbnode α) (x₁ r₁ y r₂ v t) : balance2 (red_node l x₁ r₁) y r₂ v t = red_node (black_node t v l) x₁ (black_node r₁ y r₂) := by cases r₂; refl @[simp] lemma balance2_eq₂ (l₁ : rbnode α) (y l₂ x₂ r₂ v t) : get_color l₁ ≠ red → balance2 l₁ y (red_node l₂ x₂ r₂) v t = red_node (black_node t v l₁) y (black_node l₂ x₂ r₂) := begin cases l₁; simp [get_color, balance2] end @[simp] lemma balance2_eq₃ (l : rbnode α) (y r v t) : get_color l ≠ red → get_color r ≠ red → balance2 l y r v t = black_node t v (red_node l y r) := begin cases l; cases r; simp [get_color, balance2] end /- We can use the same induction principle for balance1 and balance2 -/ lemma balance.cases {p : rbnode α → α → rbnode α → Prop} (l y r) (red_left : ∀ l x r₁ y r₂, p (red_node l x r₁) y r₂) (red_right : ∀ l₁ y l₂ x r, get_color l₁ ≠ red → p l₁ y (red_node l₂ x r)) (other : ∀ l y r, get_color l ≠ red → get_color r ≠ red → p l y r) : p l y r := begin cases l; cases r, any_goals { apply red_left }, any_goals { apply red_right; simp [get_color]; contradiction; done }, any_goals { apply other; simp [get_color]; contradiction; done }, end lemma balance1_ne_leaf (l : rbnode α) (x r v t) : balance1 l x r v t ≠ leaf := by apply balance.cases l x r; intros; simp [*]; contradiction lemma balance1_node_ne_leaf {s : rbnode α} (a : α) (t : rbnode α) : s ≠ leaf → balance1_node s a t ≠ leaf := begin intro h, cases s, { contradiction }, all_goals { simp [balance1_node], apply balance1_ne_leaf } end lemma balance2_ne_leaf (l : rbnode α) (x r v t) : balance2 l x r v t ≠ leaf := by apply balance.cases l x r; intros; simp [*]; contradiction lemma balance2_node_ne_leaf {s : rbnode α} (a : α) (t : rbnode α) : s ≠ leaf → balance2_node s a t ≠ leaf := begin intro h, cases s, { contradiction }, all_goals { simp [balance2_node], apply balance2_ne_leaf } end variables (lt : α → α → Prop) [decidable_rel lt] @[elab_as_eliminator] lemma ins.induction {p : rbnode α → Prop} (t x) (is_leaf : p leaf) (is_red_lt : ∀ a y b (hc : cmp_using lt x y = ordering.lt) (ih : p a), p (red_node a y b)) (is_red_eq : ∀ a y b (hc : cmp_using lt x y = ordering.eq), p (red_node a y b)) (is_red_gt : ∀ a y b (hc : cmp_using lt x y = ordering.gt) (ih : p b), p (red_node a y b)) (is_black_lt_red : ∀ a y b (hc : cmp_using lt x y = ordering.lt) (hr : get_color a = red) (ih : p a), p (black_node a y b)) (is_black_lt_not_red : ∀ a y b (hc : cmp_using lt x y = ordering.lt) (hnr : get_color a ≠ red) (ih : p a), p (black_node a y b)) (is_black_eq : ∀ a y b (hc : cmp_using lt x y = ordering.eq), p (black_node a y b)) (is_black_gt_red : ∀ a y b (hc : cmp_using lt x y = ordering.gt) (hr : get_color b = red) (ih : p b), p (black_node a y b)) (is_black_gt_not_red : ∀ a y b (hc : cmp_using lt x y = ordering.gt) (hnr : get_color b ≠ red) (ih : p b), p (black_node a y b)) : p t := begin induction t, case leaf { apply is_leaf }, case red_node : a y b { cases h : cmp_using lt x y, case ordering.lt { apply is_red_lt; assumption }, case ordering.eq { apply is_red_eq; assumption }, case ordering.gt { apply is_red_gt; assumption }, }, case black_node : a y b { cases h : cmp_using lt x y, case ordering.lt { by_cases get_color a = red, { apply is_black_lt_red; assumption }, { apply is_black_lt_not_red; assumption }, }, case ordering.eq { apply is_black_eq; assumption }, case ordering.gt { by_cases get_color b = red, { apply is_black_gt_red; assumption }, { apply is_black_gt_not_red; assumption }, } } end lemma is_searchable_balance1 {l y r v t lo hi} : is_searchable lt l lo (some y) → is_searchable lt r (some y) (some v) → is_searchable lt t (some v) hi → is_searchable lt (balance1 l y r v t) lo hi := by apply balance.cases l y r; intros; simp [*]; is_searchable_tactic lemma is_searchable_balance1_node {t} [is_trans α lt] : ∀ {y s lo hi}, is_searchable lt t lo (some y) → is_searchable lt s (some y) hi → is_searchable lt (balance1_node t y s) lo hi := begin cases t; simp!; intros; is_searchable_tactic, { cases lo, { apply is_searchable_none_low_of_is_searchable_some_low, assumption }, { simp at *, apply is_searchable_some_low_of_is_searchable_of_lt; assumption } }, all_goals { apply is_searchable_balance1; assumption } end lemma is_searchable_balance2 {l y r v t lo hi} : is_searchable lt t lo (some v) → is_searchable lt l (some v) (some y) → is_searchable lt r (some y) hi → is_searchable lt (balance2 l y r v t) lo hi := by apply balance.cases l y r; intros; simp [*]; is_searchable_tactic lemma is_searchable_balance2_node {t} [is_trans α lt] : ∀ {y s lo hi}, is_searchable lt s lo (some y) → is_searchable lt t (some y) hi → is_searchable lt (balance2_node t y s) lo hi := begin induction t; simp!; intros; is_searchable_tactic, { cases hi, { apply is_searchable_none_high_of_is_searchable_some_high, assumption }, { simp at *, apply is_searchable_some_high_of_is_searchable_of_lt, assumption' } }, all_goals { apply is_searchable_balance2, assumption' } end lemma is_searchable_ins {t x} [is_strict_weak_order α lt] : ∀ {lo hi} (h : is_searchable lt t lo hi), lift lt lo (some x) → lift lt (some x) hi → is_searchable lt (ins lt t x) lo hi := begin with_cases { apply ins.induction lt t x; intros; simp! [*] at * {eta := ff}; is_searchable_tactic }, case is_red_lt { apply ih h_hs₁, assumption, simp [*] }, case is_red_eq hs₁ { apply is_searchable_of_is_searchable_of_incomp hc, assumption }, case is_red_eq hs₂ { apply is_searchable_of_incomp_of_is_searchable hc, assumption }, case is_red_gt { apply ih h_hs₂, cases hi; simp [*], assumption }, case is_black_lt_red { apply is_searchable_balance1_node, apply ih h_hs₁, assumption, simp [*], assumption }, case is_black_lt_not_red { apply ih h_hs₁, assumption, simp [*] }, case is_black_eq hs₁ { apply is_searchable_of_is_searchable_of_incomp hc, assumption }, case is_black_eq hs₂ { apply is_searchable_of_incomp_of_is_searchable hc, assumption }, case is_black_gt_red { apply is_searchable_balance2_node, assumption, apply ih h_hs₂, simp [*], assumption }, case is_black_gt_not_red { apply ih h_hs₂, assumption, simp [*] } end lemma is_searchable_mk_insert_result {c t} : is_searchable lt t none none → is_searchable lt (mk_insert_result c t) none none := begin cases c; cases t; simp [mk_insert_result], any_goals { exact id }, { intro h, is_searchable_tactic } end lemma is_searchable_insert {t x} [is_strict_weak_order α lt] : is_searchable lt t none none → is_searchable lt (insert lt t x) none none := begin intro h, simp [insert], apply is_searchable_mk_insert_result, apply is_searchable_ins; { assumption <|> simp } end end rbnode namespace rbnode section membership_lemmas parameters {α : Type u} (lt : α → α → Prop) [decidable_rel lt] local attribute [simp] mem balance1_node balance2_node local infix `∈` := mem lt lemma mem_balance1_node_of_mem_left {x s} (v) (t : rbnode α) : x ∈ s → x ∈ balance1_node s v t := begin cases s; simp, all_goals { apply balance.cases s_lchild s_val s_rchild; intros; simp at *; blast_disjs; simp [*] } end lemma mem_balance2_node_of_mem_left {x s} (v) (t : rbnode α) : x ∈ s → x ∈ balance2_node s v t := begin cases s; simp, all_goals { apply balance.cases s_lchild s_val s_rchild; intros; simp at *; blast_disjs; simp [*] } end lemma mem_balance1_node_of_mem_right {x t} (v) (s : rbnode α) : x ∈ t → x ∈ balance1_node s v t := begin intros, cases s; simp [*], all_goals { apply balance.cases s_lchild s_val s_rchild; intros; simp [*] } end lemma mem_balance2_node_of_mem_right {x t} (v) (s : rbnode α) : x ∈ t → x ∈ balance2_node s v t := begin intros, cases s; simp [*], all_goals { apply balance.cases s_lchild s_val s_rchild; intros; simp [*] } end lemma mem_balance1_node_of_incomp {x v} (s t) : (¬ lt x v ∧ ¬ lt v x) → s ≠ leaf → x ∈ balance1_node s v t := begin intros, cases s; simp, { contradiction }, all_goals { apply balance.cases s_lchild s_val s_rchild; intros; simp [*] } end lemma mem_balance2_node_of_incomp {x v} (s t) : (¬ lt v x ∧ ¬ lt x v) → s ≠ leaf → x ∈ balance2_node s v t := begin intros, cases s; simp, { contradiction }, all_goals { apply balance.cases s_lchild s_val s_rchild; intros; simp [*] } end lemma ins_ne_leaf (t : rbnode α) (x : α) : t.ins lt x ≠ leaf := begin apply ins.induction lt t x, any_goals { intros, simp [ins, *] }, { intros, apply balance1_node_ne_leaf, assumption }, { intros, apply balance2_node_ne_leaf, assumption }, end lemma insert_ne_leaf (t : rbnode α) (x : α) : insert lt t x ≠ leaf := begin simp [insert], cases he : ins lt t x; cases get_color t; simp [mk_insert_result], { have := ins_ne_leaf lt t x, contradiction }, { exact absurd he (ins_ne_leaf _ _ _) } end lemma mem_ins_of_incomp (t : rbnode α) {x y : α} : ∀ h : ¬ lt x y ∧ ¬ lt y x, x ∈ t.ins lt y := begin with_cases { apply ins.induction lt t y; intros; simp [ins, *] }, case is_black_lt_red { have := ih h, apply mem_balance1_node_of_mem_left, assumption }, case is_black_gt_red { have := ih h, apply mem_balance2_node_of_mem_left, assumption } end lemma mem_ins_of_mem [is_strict_weak_order α lt] {t : rbnode α} (z : α) : ∀ {x} (h : x ∈ t), x ∈ t.ins lt z := begin with_cases { apply ins.induction lt t z; intros; simp [ins, *] at *; try { contradiction }; blast_disjs }, case is_red_eq or.inr or.inl { have := incomp_trans_of lt h ⟨hc.2, hc.1⟩, simp [this] }, case is_black_lt_red or.inl { apply mem_balance1_node_of_mem_left, apply ih h }, case is_black_lt_red or.inr or.inl { have := ins_ne_leaf lt a z, apply mem_balance1_node_of_incomp, cases h, all_goals { simp [*] } }, case is_black_lt_red or.inr or.inr { apply mem_balance1_node_of_mem_right, assumption }, case is_black_eq or.inr or.inl { have := incomp_trans_of lt hc ⟨h.2, h.1⟩, simp [this] }, case is_black_gt_red or.inl { apply mem_balance2_node_of_mem_right, assumption }, case is_black_gt_red or.inr or.inl { have := ins_ne_leaf lt a z, apply mem_balance2_node_of_incomp, cases h, simp [*], apply ins_ne_leaf }, case is_black_gt_red or.inr or.inr { apply mem_balance2_node_of_mem_left, apply ih h }, -- remaining cases are easy any_goals { intros, simp [h], done }, all_goals { intros, simp [ih h], done }, end lemma mem_mk_insert_result {a t} (c) : mem lt a t → mem lt a (mk_insert_result c t) := by intros; cases c; cases t; simp [mk_insert_result, mem, *] at * lemma mem_of_mem_mk_insert_result {a t c} : mem lt a (mk_insert_result c t) → mem lt a t := by cases t; cases c; simp [mk_insert_result, mem]; intros; assumption lemma mem_insert_of_incomp (t : rbnode α) {x y : α} : ∀ h : ¬ lt x y ∧ ¬ lt y x, x ∈ t.insert lt y := by intros; unfold insert; apply mem_mk_insert_result; apply mem_ins_of_incomp; assumption lemma mem_insert_of_mem [is_strict_weak_order α lt] {t x} (z) : x ∈ t → x ∈ t.insert lt z := by intros; apply mem_mk_insert_result; apply mem_ins_of_mem; assumption lemma of_mem_balance1_node [is_strict_weak_order α lt] {x s v t} : x ∈ balance1_node s v t → x ∈ s ∨ (¬ lt x v ∧ ¬ lt v x) ∨ x ∈ t := begin cases s; simp, { intros, simp [*] }, all_goals { apply balance.cases s_lchild s_val s_rchild; intros; simp [*] at *; blast_disjs; simp [*] } end lemma of_mem_balance2_node [is_strict_weak_order α lt] {x s v t} : x ∈ balance2_node s v t → x ∈ s ∨ (¬ lt x v ∧ ¬ lt v x) ∨ x ∈ t := begin cases s; simp, { intros, simp [*] }, all_goals { apply balance.cases s_lchild s_val s_rchild; intros; simp [*] at *; blast_disjs; simp [*] } end lemma equiv_or_mem_of_mem_ins [is_strict_weak_order α lt] {t : rbnode α} {x z} : ∀ (h : x ∈ t.ins lt z), x ≈[lt] z ∨ x ∈ t := begin with_cases { apply ins.induction lt t z; intros; simp [ins, strict_weak_order.equiv, *] at *; blast_disjs }, case is_black_lt_red { have h' := of_mem_balance1_node lt h, blast_disjs, have := ih h', blast_disjs, all_goals { simp [h, *] } }, case is_black_gt_red { have h' := of_mem_balance2_node lt h, blast_disjs, have := ih h', blast_disjs, all_goals { simp [h, *] }}, -- All other goals can be solved by the following tactics any_goals { intros, simp [h] }, all_goals { intros, have ih := ih h, cases ih; simp [*], done }, end lemma equiv_or_mem_of_mem_insert [is_strict_weak_order α lt] {t : rbnode α} {x z} : ∀ (h : x ∈ t.insert lt z), x ≈[lt] z ∨ x ∈ t := begin simp [insert], intros, apply equiv_or_mem_of_mem_ins, exact mem_of_mem_mk_insert_result lt h end local attribute [simp] mem_exact lemma mem_exact_balance1_node_of_mem_exact {x s} (v) (t : rbnode α) : mem_exact x s → mem_exact x (balance1_node s v t) := begin cases s; simp, all_goals { apply balance.cases s_lchild s_val s_rchild; intros; simp [*] at *; blast_disjs; simp [*] } end lemma mem_exact_balance2_node_of_mem_exact {x s} (v) (t : rbnode α) : mem_exact x s → mem_exact x (balance2_node s v t) := begin cases s; simp, all_goals { apply balance.cases s_lchild s_val s_rchild; intros; simp [*] at *; blast_disjs; simp [*] } end lemma find_balance1_node [is_strict_weak_order α lt] {x y z t s} : ∀ {lo hi}, is_searchable lt t lo (some z) → is_searchable lt s (some z) hi → find lt t y = some x → y ≈[lt] x → find lt (balance1_node t z s) y = some x := begin intros _ _ hs₁ hs₂ heq heqv, have hs := is_searchable_balance1_node lt hs₁ hs₂, have := eq.trans (find_eq_find_of_eqv hs₁ heqv.symm) heq, have := iff.mpr (find_correct_exact hs₁) this, have := mem_exact_balance1_node_of_mem_exact z s this, have := iff.mp (find_correct_exact hs) this, exact eq.trans (find_eq_find_of_eqv hs heqv) this end lemma find_balance2_node [is_strict_weak_order α lt] {x y z s t} [is_trans α lt] : ∀ {lo hi}, is_searchable lt s lo (some z) → is_searchable lt t (some z) hi → find lt t y = some x → y ≈[lt] x → find lt (balance2_node t z s) y = some x := begin intros _ _ hs₁ hs₂ heq heqv, have hs := is_searchable_balance2_node lt hs₁ hs₂, have := eq.trans (find_eq_find_of_eqv hs₂ heqv.symm) heq, have := iff.mpr (find_correct_exact hs₂) this, have := mem_exact_balance2_node_of_mem_exact z s this, have := iff.mp (find_correct_exact hs) this, exact eq.trans (find_eq_find_of_eqv hs heqv) this end /- Auxiliary lemma -/ lemma ite_eq_of_not_lt [is_strict_order α lt] {a b} {β : Type v} (t s : β) (h : lt b a) : (if lt a b then t else s) = s := begin have := not_lt_of_lt h, simp [*] end local attribute [simp] ite_eq_of_not_lt private meta def simp_fi : tactic unit := `[simp [find, ins, *, cmp_using]] lemma find_ins_of_eqv [is_strict_weak_order α lt] {x y : α} {t : rbnode α} (he : x ≈[lt] y) : ∀ {lo hi} (hs : is_searchable lt t lo hi) (hlt₁ : lift lt lo (some x)) (hlt₂ : lift lt (some x) hi), find lt (ins lt t x) y = some x := begin simp [strict_weak_order.equiv] at he, apply ins.induction lt t x; intros, { simp_fi }, all_goals { simp at hc, cases hs }, { have := lt_of_incomp_of_lt he.swap hc, have := ih hs_hs₁ hlt₁ hc, simp_fi }, { simp_fi }, { have := lt_of_lt_of_incomp hc he, have := ih hs_hs₂ hc hlt₂, simp_fi }, { simp_fi, have := is_searchable_ins lt hs_hs₁ hlt₁ hc, apply find_balance1_node lt this hs_hs₂ (ih hs_hs₁ hlt₁ hc) he.symm }, { have := lt_of_incomp_of_lt he.swap hc, have := ih hs_hs₁ hlt₁ hc, simp_fi }, { simp_fi }, { simp_fi, have := is_searchable_ins lt hs_hs₂ hc hlt₂, apply find_balance2_node lt hs_hs₁ this (ih hs_hs₂ hc hlt₂) he.symm }, { have := lt_of_lt_of_incomp hc he, have := ih hs_hs₂ hc hlt₂, simp_fi } end lemma find_mk_insert_result (c : color) (t : rbnode α) (x : α) : find lt (mk_insert_result c t) x = find lt t x := begin cases t; cases c; simp [mk_insert_result], { simp [find], cases cmp_using lt x t_val; simp [find] } end lemma find_insert_of_eqv [is_strict_weak_order α lt] {x y : α} {t : rbnode α} (he : x ≈[lt] y) : is_searchable lt t none none → find lt (insert lt t x) y = some x := begin intro hs, simp [insert, find_mk_insert_result], apply find_ins_of_eqv lt he hs; simp end lemma weak_trichotomous (x y) {p : Prop} (is_lt : ∀ h : lt x y, p) (is_eqv : ∀ h : ¬ lt x y ∧ ¬ lt y x, p) (is_gt : ∀ h : lt y x, p) : p := begin by_cases lt x y; by_cases lt y x, any_goals { apply is_lt; assumption }, any_goals { apply is_gt; assumption }, any_goals { apply is_eqv, constructor; assumption } end section find_ins_of_not_eqv section simp_aux_lemmas lemma find_black_eq_find_red {l y r x} : find lt (black_node l y r) x = find lt (red_node l y r) x := begin simp [find], all_goals { cases cmp_using lt x y; simp [find] } end lemma find_red_of_lt {l y r x} (h : lt x y) : find lt (red_node l y r) x = find lt l x := by simp [find, cmp_using, *] lemma find_red_of_gt [is_strict_order α lt] {l y r x} (h : lt y x) : find lt (red_node l y r) x = find lt r x := begin have := not_lt_of_lt h, simp [find, cmp_using, *] end lemma find_red_of_incomp {l y r x} (h : ¬ lt x y ∧ ¬ lt y x) : find lt (red_node l y r) x = some y := by simp [find, cmp_using, *] end simp_aux_lemmas local attribute [simp] find_black_eq_find_red find_red_of_lt find_red_of_lt find_red_of_gt find_red_of_incomp variable [is_strict_weak_order α lt] lemma find_balance1_lt {l r t v x y lo hi} (h : lt x y) (hl : is_searchable lt l lo (some v)) (hr : is_searchable lt r (some v) (some y)) (ht : is_searchable lt t (some y) hi) : find lt (balance1 l v r y t) x = find lt (red_node l v r) x := begin with_cases { revert hl hr ht, apply balance.cases l v r; intros; simp [*]; is_searchable_tactic }, case red_left : _ _ _ z r { apply weak_trichotomous lt z x; intros; simp [*] }, case red_right : l_left l_val l_right z r { with_cases { apply weak_trichotomous lt z x; intro h' }, case is_lt { have := trans_of lt (lo_lt_hi hr_hs₁) h', simp [*] }, case is_eqv { have : lt l_val x := lt_of_lt_of_incomp (lo_lt_hi hr_hs₁) h', simp [*] }, case is_gt { apply weak_trichotomous lt l_val x; intros; simp [*] } } end meta def ins_ne_leaf_tac := `[apply ins_ne_leaf] lemma find_balance1_node_lt {t s x y lo hi} (hlt : lt y x) (ht : is_searchable lt t lo (some x)) (hs : is_searchable lt s (some x) hi) (hne : t ≠ leaf . ins_ne_leaf_tac) : find lt (balance1_node t x s) y = find lt t y := begin cases t; simp [balance1_node], { contradiction }, all_goals { intros, is_searchable_tactic, apply find_balance1_lt, assumption' } end lemma find_balance1_gt {l r t v x y lo hi} (h : lt y x) (hl : is_searchable lt l lo (some v)) (hr : is_searchable lt r (some v) (some y)) (ht : is_searchable lt t (some y) hi) : find lt (balance1 l v r y t) x = find lt t x := begin with_cases { revert hl hr ht, apply balance.cases l v r; intros; simp [*]; is_searchable_tactic }, case red_left : _ _ _ z { have := trans_of lt (lo_lt_hi hr) h, simp [*] }, case red_right : _ _ _ z { have := trans_of lt (lo_lt_hi hr_hs₂) h, simp [*] } end lemma find_balance1_node_gt {t s x y lo hi} (h : lt x y) (ht : is_searchable lt t lo (some x)) (hs : is_searchable lt s (some x) hi) (hne : t ≠ leaf . ins_ne_leaf_tac) : find lt (balance1_node t x s) y = find lt s y := begin cases t; simp [balance1_node], all_goals { intros, is_searchable_tactic, apply find_balance1_gt, assumption' } end lemma find_balance1_eqv {l r t v x y lo hi} (h : ¬ lt x y ∧ ¬ lt y x) (hl : is_searchable lt l lo (some v)) (hr : is_searchable lt r (some v) (some y)) (ht : is_searchable lt t (some y) hi) : find lt (balance1 l v r y t) x = some y := begin with_cases { revert hl hr ht, apply balance.cases l v r; intros; simp [*]; is_searchable_tactic }, case red_left : _ _ _ z { have : lt z x := lt_of_lt_of_incomp (lo_lt_hi hr) h.swap, simp [*] }, case red_right : _ _ _ z { have : lt z x := lt_of_lt_of_incomp (lo_lt_hi hr_hs₂) h.swap, simp [*] } end lemma find_balance1_node_eqv {t s x y lo hi} (h : ¬ lt x y ∧ ¬ lt y x) (ht : is_searchable lt t lo (some y)) (hs : is_searchable lt s (some y) hi) (hne : t ≠ leaf . ins_ne_leaf_tac) : find lt (balance1_node t y s) x = some y := begin cases t; simp [balance1_node], { contradiction }, all_goals { intros, is_searchable_tactic, apply find_balance1_eqv, assumption' } end lemma find_balance2_lt {l v r t x y lo hi} (h : lt x y) (hl : is_searchable lt l (some y) (some v)) (hr : is_searchable lt r (some v) hi) (ht : is_searchable lt t lo (some y)) : find lt (balance2 l v r y t) x = find lt t x := begin with_cases { revert hl hr ht, apply balance.cases l v r; intros; simp [*]; is_searchable_tactic }, case red_left { have := trans h (lo_lt_hi hl_hs₁), simp [*] }, case red_right { have := trans h (lo_lt_hi hl), simp [*] } end lemma find_balance2_node_lt {s t x y lo hi} (h : lt x y) (ht : is_searchable lt t (some y) hi) (hs : is_searchable lt s lo (some y)) (hne : t ≠ leaf . ins_ne_leaf_tac) : find lt (balance2_node t y s) x = find lt s x := begin cases t; simp [balance2_node], all_goals { intros, is_searchable_tactic, apply find_balance2_lt, assumption' } end lemma find_balance2_gt {l v r t x y lo hi} (h : lt y x) (hl : is_searchable lt l (some y) (some v)) (hr : is_searchable lt r (some v) hi) (ht : is_searchable lt t lo (some y)) : find lt (balance2 l v r y t) x = find lt (red_node l v r) x := begin with_cases { revert hl hr ht, apply balance.cases l v r; intros; simp [*]; is_searchable_tactic }, case red_left : _ val _ z { with_cases { apply weak_trichotomous lt val x; intro h'; simp [*] }, case is_lt { apply weak_trichotomous lt z x; intros; simp [*] }, case is_eqv { have : lt x z := lt_of_incomp_of_lt h'.swap (lo_lt_hi hl_hs₂), simp [*] }, case is_gt { have := trans h' (lo_lt_hi hl_hs₂), simp [*] } }, case red_right : _ val { apply weak_trichotomous lt val x; intros; simp [*] } end lemma find_balance2_node_gt {s t x y lo hi} (h : lt y x) (ht : is_searchable lt t (some y) hi) (hs : is_searchable lt s lo (some y)) (hne : t ≠ leaf . ins_ne_leaf_tac) : find lt (balance2_node t y s) x = find lt t x := begin cases t; simp [balance2_node], { contradiction }, all_goals { intros, is_searchable_tactic, apply find_balance2_gt, assumption' } end lemma find_balance2_eqv {l v r t x y lo hi} (h : ¬ lt x y ∧ ¬ lt y x) (hl : is_searchable lt l (some y) (some v)) (hr : is_searchable lt r (some v) hi) (ht : is_searchable lt t lo (some y)) : find lt (balance2 l v r y t) x = some y := begin with_cases { revert hl hr ht, apply balance.cases l v r; intros; simp [*]; is_searchable_tactic }, case red_left { have := lt_of_incomp_of_lt h (lo_lt_hi hl_hs₁), simp [*] }, case red_right { have := lt_of_incomp_of_lt h (lo_lt_hi hl), simp [*] } end lemma find_balance2_node_eqv {t s x y lo hi} (h : ¬ lt x y ∧ ¬ lt y x) (ht : is_searchable lt t (some y) hi) (hs : is_searchable lt s lo (some y)) (hne : t ≠ leaf . ins_ne_leaf_tac) : find lt (balance2_node t y s) x = some y := begin cases t; simp [balance2_node], { contradiction }, all_goals { intros, is_searchable_tactic, apply find_balance2_eqv, assumption' } end lemma find_ins_of_disj {x y : α} {t : rbnode α} (hn : lt x y ∨ lt y x) : ∀ {lo hi} (hs : is_searchable lt t lo hi) (hlt₁ : lift lt lo (some x)) (hlt₂ : lift lt (some x) hi), find lt (ins lt t x) y = find lt t y := begin apply ins.induction lt t x; intros, { cases hn, all_goals { simp [find, ins, cmp_using, *] } }, all_goals { simp at hc, cases hs }, { have := ih hs_hs₁ hlt₁ hc, simp_fi }, { cases hn, { have := lt_of_incomp_of_lt hc.symm hn, simp_fi }, { have := lt_of_lt_of_incomp hn hc, simp_fi } }, { have := ih hs_hs₂ hc hlt₂, cases hn, { have := trans hc hn, simp_fi }, { simp_fi } }, { have ih := ih hs_hs₁ hlt₁ hc, cases hn, { cases hc' : cmp_using lt y y_1; simp at hc', { have hsi := is_searchable_ins lt hs_hs₁ hlt₁ (trans_of lt hn hc'), have := find_balance1_node_lt lt hc' hsi hs_hs₂, simp_fi }, { have hlt := lt_of_lt_of_incomp hn hc', have hsi := is_searchable_ins lt hs_hs₁ hlt₁ hlt, have := find_balance1_node_eqv lt hc' hsi hs_hs₂, simp_fi }, { have hsi := is_searchable_ins lt hs_hs₁ hlt₁ hc, have := find_balance1_node_gt lt hc' hsi hs_hs₂, simp [*], simp_fi } }, { have hlt := trans hn hc, have hsi := is_searchable_ins lt hs_hs₁ hlt₁ hc, have := find_balance1_node_lt lt hlt hsi hs_hs₂, simp_fi } }, { have := ih hs_hs₁ hlt₁ hc, simp_fi }, { cases hn, { have := lt_of_incomp_of_lt hc.swap hn, simp_fi }, { have := lt_of_lt_of_incomp hn hc, simp_fi } }, { have ih := ih hs_hs₂ hc hlt₂, cases hn, { have hlt := trans hc hn, simp_fi, have hsi := is_searchable_ins lt hs_hs₂ hc hlt₂, have := find_balance2_node_gt lt hlt hsi hs_hs₁, simp_fi }, { simp_fi, cases hc' : cmp_using lt y y_1; simp at hc', { have hsi := is_searchable_ins lt hs_hs₂ hc hlt₂, have := find_balance2_node_lt lt hc' hsi hs_hs₁, simp_fi }, { have hlt := lt_of_incomp_of_lt hc'.swap hn, have hsi := is_searchable_ins lt hs_hs₂ hlt hlt₂, have := find_balance2_node_eqv lt hc' hsi hs_hs₁, simp_fi }, { have hsi := is_searchable_ins lt hs_hs₂ hc hlt₂, have := find_balance2_node_gt lt hc' hsi hs_hs₁, simp_fi } } }, { cases hn, { have := trans hc hn, have := ih hs_hs₂ hc hlt₂, simp_fi }, { have ih := ih hs_hs₂ hc hlt₂, simp_fi } } end end find_ins_of_not_eqv lemma find_insert_of_disj [is_strict_weak_order α lt] {x y : α} {t : rbnode α} (hd : lt x y ∨ lt y x) : is_searchable lt t none none → find lt (insert lt t x) y = find lt t y := begin intro hs, simp [insert, find_mk_insert_result], apply find_ins_of_disj lt hd hs; simp end lemma find_insert_of_not_eqv [is_strict_weak_order α lt] {x y : α} {t : rbnode α} (hn : ¬ x ≈[lt] y) : is_searchable lt t none none → find lt (insert lt t x) y = find lt t y := begin intro hs, simp [insert, find_mk_insert_result], have he : lt x y ∨ lt y x, { simp [strict_weak_order.equiv, decidable.not_and_iff_or_not, decidable.not_not_iff] at hn, assumption }, apply find_ins_of_disj lt he hs; simp end end membership_lemmas section is_red_black variables {α : Type u} open nat color inductive is_bad_red_black : rbnode α → nat → Prop | bad_red {c₁ c₂ n l r v} (rb_l : is_red_black l c₁ n) (rb_r : is_red_black r c₂ n) : is_bad_red_black (red_node l v r) n lemma balance1_rb {l r t : rbnode α} {y v : α} {c_l c_r c_t n} : is_red_black l c_l n → is_red_black r c_r n → is_red_black t c_t n → ∃ c, is_red_black (balance1 l y r v t) c (succ n) := by intros h₁ h₂ _; cases h₁; cases h₂; repeat { assumption <|> constructor } lemma balance2_rb {l r t : rbnode α} {y v : α} {c_l c_r c_t n} : is_red_black l c_l n → is_red_black r c_r n → is_red_black t c_t n → ∃ c, is_red_black (balance2 l y r v t) c (succ n) := by intros h₁ h₂ _; cases h₁; cases h₂; repeat { assumption <|> constructor } lemma balance1_node_rb {t s : rbnode α} {y : α} {c n} : is_bad_red_black t n → is_red_black s c n → ∃ c, is_red_black (balance1_node t y s) c (succ n) := by intros h _; cases h; simp [balance1_node]; apply balance1_rb; assumption' lemma balance2_node_rb {t s : rbnode α} {y : α} {c n} : is_bad_red_black t n → is_red_black s c n → ∃ c, is_red_black (balance2_node t y s) c (succ n) := by intros h _; cases h; simp [balance2_node]; apply balance2_rb; assumption' def ins_rb_result : rbnode α → color → nat → Prop | t red n := is_bad_red_black t n | t black n := ∃ c, is_red_black t c n variables {lt : α → α → Prop} [decidable_rel lt] lemma of_get_color_eq_red {t : rbnode α} {c n} : get_color t = red → is_red_black t c n → c = red := begin intros h₁ h₂, cases h₂; simp [get_color] at h₁; contradiction end lemma of_get_color_ne_red {t : rbnode α} {c n} : get_color t ≠ red → is_red_black t c n → c = black := begin intros h₁ h₂, cases h₂; simp [get_color] at h₁; contradiction end variable (lt) lemma ins_rb {t : rbnode α} (x) : ∀ {c n} (h : is_red_black t c n), ins_rb_result (ins lt t x) c n := begin apply ins.induction lt t x; intros; cases h; simp [ins, *, ins_rb_result], { repeat { constructor } }, { specialize ih h_rb_l, cases ih, constructor; assumption }, { constructor; assumption }, { specialize ih h_rb_r, cases ih, constructor; assumption }, { specialize ih h_rb_l, have := of_get_color_eq_red hr h_rb_l, subst h_c₁, simp [ins_rb_result] at ih, apply balance1_node_rb; assumption }, { specialize ih h_rb_l, have := of_get_color_ne_red hnr h_rb_l, subst h_c₁, simp [ins_rb_result] at ih, cases ih, constructor, constructor; assumption }, { constructor, constructor; assumption }, { specialize ih h_rb_r, have := of_get_color_eq_red hr h_rb_r, subst h_c₂, simp [ins_rb_result] at ih, apply balance2_node_rb; assumption }, { specialize ih h_rb_r, have := of_get_color_ne_red hnr h_rb_r, subst h_c₂, simp [ins_rb_result] at ih, cases ih, constructor, constructor; assumption } end def insert_rb_result : rbnode α → color → nat → Prop | t red n := is_red_black t black (succ n) | t black n := ∃ c, is_red_black t c n lemma insert_rb {t : rbnode α} (x) {c n} (h : is_red_black t c n) : insert_rb_result (insert lt t x) c n := begin simp [insert], have hi := ins_rb lt x h, generalize he : ins lt t x = r, simp [he] at hi, cases h; simp [get_color, ins_rb_result, insert_rb_result, mk_insert_result] at *, assumption', { cases hi, simp [mk_insert_result], constructor; assumption } end lemma insert_is_red_black {t : rbnode α} {c n} (x) : is_red_black t c n → ∃ c n, is_red_black (insert lt t x) c n := begin intro h, have := insert_rb lt x h, cases c; simp [insert_rb_result] at this, { constructor, constructor, assumption }, { cases this, constructor, constructor, assumption } end end is_red_black end rbnode
5c35de0f69168fddfcc1a388939e0c1dab0688e5
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/data/polynomial/inductions.lean
44eee76787ed821cac75fe3af5a701900f13987a
[ "Apache-2.0" ]
permissive
AntoineChambert-Loir/mathlib
64aabb896129885f12296a799818061bc90da1ff
07be904260ab6e36a5769680b6012f03a4727134
refs/heads/master
1,693,187,631,771
1,636,719,886,000
1,636,719,886,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
5,018
lean
/- Copyright (c) 2021 Damiano Testa. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Johannes Hölzl, Scott Morrison, Damiano Testa, Jens Wagemaker -/ import data.nat.interval import data.polynomial.degree.definitions /-! # Induction on polynomials This file contains lemmas dealing with different flavours of induction on polynomials. -/ noncomputable theory open_locale classical big_operators open finset namespace polynomial universes u v w z variables {R : Type u} {S : Type v} {T : Type w} {A : Type z} {a b : R} {n : ℕ} section semiring variables [semiring R] {p q : polynomial R} /-- `div_X p` returns a polynomial `q` such that `q * X + C (p.coeff 0) = p`. It can be used in a semiring where the usual division algorithm is not possible -/ def div_X (p : polynomial R) : polynomial R := ∑ n in Ico 0 p.nat_degree, monomial n (p.coeff (n + 1)) @[simp] lemma coeff_div_X : (div_X p).coeff n = p.coeff (n+1) := begin simp only [div_X, coeff_monomial, true_and, finset_sum_coeff, not_lt, mem_Ico, zero_le, finset.sum_ite_eq', ite_eq_left_iff], intro h, rw coeff_eq_zero_of_nat_degree_lt (nat.lt_succ_of_le h) end lemma div_X_mul_X_add (p : polynomial R) : div_X p * X + C (p.coeff 0) = p := ext $ by rintro ⟨_|_⟩; simp [coeff_C, nat.succ_ne_zero, coeff_mul_X] @[simp] lemma div_X_C (a : R) : div_X (C a) = 0 := ext $ λ n, by cases n; simp [div_X, coeff_C]; simp [coeff] lemma div_X_eq_zero_iff : div_X p = 0 ↔ p = C (p.coeff 0) := ⟨λ h, by simpa [eq_comm, h] using div_X_mul_X_add p, λ h, by rw [h, div_X_C]⟩ lemma div_X_add : div_X (p + q) = div_X p + div_X q := ext $ by simp lemma degree_div_X_lt (hp0 : p ≠ 0) : (div_X p).degree < p.degree := by haveI := nontrivial.of_polynomial_ne hp0; calc (div_X p).degree < (div_X p * X + C (p.coeff 0)).degree : if h : degree p ≤ 0 then begin have h' : C (p.coeff 0) ≠ 0, by rwa [← eq_C_of_degree_le_zero h], rw [eq_C_of_degree_le_zero h, div_X_C, degree_zero, zero_mul, zero_add], exact lt_of_le_of_ne bot_le (ne.symm (mt degree_eq_bot.1 $ by simp [h'])), end else have hXp0 : div_X p ≠ 0, by simpa [div_X_eq_zero_iff, -not_le, degree_le_zero_iff] using h, have leading_coeff (div_X p) * leading_coeff X ≠ 0, by simpa, have degree (C (p.coeff 0)) < degree (div_X p * X), from calc degree (C (p.coeff 0)) ≤ 0 : degree_C_le ... < 1 : dec_trivial ... = degree (X : polynomial R) : degree_X.symm ... ≤ degree (div_X p * X) : by rw [← zero_add (degree X), degree_mul' this]; exact add_le_add (by rw [zero_le_degree_iff, ne.def, div_X_eq_zero_iff]; exact λ h0, h (h0.symm ▸ degree_C_le)) (le_refl _), by rw [degree_add_eq_left_of_degree_lt this]; exact degree_lt_degree_mul_X hXp0 ... = p.degree : congr_arg _ (div_X_mul_X_add _) /-- An induction principle for polynomials, valued in Sort* instead of Prop. -/ @[elab_as_eliminator] noncomputable def rec_on_horner {M : polynomial R → Sort*} : Π (p : polynomial R), M 0 → (Π p a, coeff p 0 = 0 → a ≠ 0 → M p → M (p + C a)) → (Π p, p ≠ 0 → M p → M (p * X)) → M p | p := λ M0 MC MX, if hp : p = 0 then eq.rec_on hp.symm M0 else have wf : degree (div_X p) < degree p, from degree_div_X_lt hp, by rw [← div_X_mul_X_add p] at *; exact if hcp0 : coeff p 0 = 0 then by rw [hcp0, C_0, add_zero]; exact MX _ (λ h : div_X p = 0, by simpa [h, hcp0] using hp) (rec_on_horner _ M0 MC MX) else MC _ _ (coeff_mul_X_zero _) hcp0 (if hpX0 : div_X p = 0 then show M (div_X p * X), by rw [hpX0, zero_mul]; exact M0 else MX (div_X p) hpX0 (rec_on_horner _ M0 MC MX)) using_well_founded {dec_tac := tactic.assumption} /-- A property holds for all polynomials of positive `degree` with coefficients in a semiring `R` if it holds for * `a * X`, with `a ∈ R`, * `p * X`, with `p ∈ R[X]`, * `p + a`, with `a ∈ R`, `p ∈ R[X]`, with appropriate restrictions on each term. See `nat_degree_ne_zero_induction_on` for a similar statement involving no explicit multiplication. -/ @[elab_as_eliminator] lemma degree_pos_induction_on {P : polynomial R → Prop} (p : polynomial R) (h0 : 0 < degree p) (hC : ∀ {a}, a ≠ 0 → P (C a * X)) (hX : ∀ {p}, 0 < degree p → P p → P (p * X)) (hadd : ∀ {p} {a}, 0 < degree p → P p → P (p + C a)) : P p := rec_on_horner p (λ h, by rw degree_zero at h; exact absurd h dec_trivial) (λ p a _ _ ih h0, have 0 < degree p, from lt_of_not_ge (λ h, (not_lt_of_ge degree_C_le) $ by rwa [eq_C_of_degree_le_zero h, ← C_add] at h0), hadd this (ih this)) (λ p _ ih h0', if h0 : 0 < degree p then hX h0 (ih h0) else by rw [eq_C_of_degree_le_zero (le_of_not_gt h0)] at *; exact hC (λ h : coeff p 0 = 0, by simpa [h, nat.not_lt_zero] using h0')) h0 end semiring end polynomial
b6f92e26f4ea8a3c01b4269f763c7a7a76977bfb
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebra/lie/skew_adjoint.lean
c9f78e816a6d0bc373e9397c726620f7999d30ea
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
7,312
lean
/- Copyright (c) 2020 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Oliver Nash -/ import algebra.lie.matrix import linear_algebra.matrix.bilinear_form /-! # Lie algebras of skew-adjoint endomorphisms of a bilinear form > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. When a module carries a bilinear form, the Lie algebra of endomorphisms of the module contains a distinguished Lie subalgebra: the skew-adjoint endomorphisms. Such subalgebras are important because they provide a simple, explicit construction of the so-called classical Lie algebras. This file defines the Lie subalgebra of skew-adjoint endomorphims cut out by a bilinear form on a module and proves some basic related results. It also provides the corresponding definitions and results for the Lie algebra of square matrices. ## Main definitions * `skew_adjoint_lie_subalgebra` * `skew_adjoint_lie_subalgebra_equiv` * `skew_adjoint_matrices_lie_subalgebra` * `skew_adjoint_matrices_lie_subalgebra_equiv` ## Tags lie algebra, skew-adjoint, bilinear form -/ universes u v w w₁ section skew_adjoint_endomorphisms open bilin_form variables {R : Type u} {M : Type v} [comm_ring R] [add_comm_group M] [module R M] variables (B : bilin_form R M) lemma bilin_form.is_skew_adjoint_bracket (f g : module.End R M) (hf : f ∈ B.skew_adjoint_submodule) (hg : g ∈ B.skew_adjoint_submodule) : ⁅f, g⁆ ∈ B.skew_adjoint_submodule := begin rw mem_skew_adjoint_submodule at *, have hfg : is_adjoint_pair B B (f * g) (g * f), { rw ←neg_mul_neg g f, exact hf.mul hg, }, have hgf : is_adjoint_pair B B (g * f) (f * g), { rw ←neg_mul_neg f g, exact hg.mul hf, }, change bilin_form.is_adjoint_pair B B (f * g - g * f) (-(f * g - g * f)), rw neg_sub, exact hfg.sub hgf, end /-- Given an `R`-module `M`, equipped with a bilinear form, the skew-adjoint endomorphisms form a Lie subalgebra of the Lie algebra of endomorphisms. -/ def skew_adjoint_lie_subalgebra : lie_subalgebra R (module.End R M) := { lie_mem' := B.is_skew_adjoint_bracket, ..B.skew_adjoint_submodule } variables {N : Type w} [add_comm_group N] [module R N] (e : N ≃ₗ[R] M) /-- An equivalence of modules with bilinear forms gives equivalence of Lie algebras of skew-adjoint endomorphisms. -/ def skew_adjoint_lie_subalgebra_equiv : skew_adjoint_lie_subalgebra (B.comp (↑e : N →ₗ[R] M) ↑e) ≃ₗ⁅R⁆ skew_adjoint_lie_subalgebra B := begin apply lie_equiv.of_subalgebras _ _ e.lie_conj, ext f, simp only [lie_subalgebra.mem_coe, submodule.mem_map_equiv, lie_subalgebra.mem_map_submodule, coe_coe], exact (bilin_form.is_pair_self_adjoint_equiv (-B) B e f).symm, end @[simp] lemma skew_adjoint_lie_subalgebra_equiv_apply (f : skew_adjoint_lie_subalgebra (B.comp ↑e ↑e)) : ↑(skew_adjoint_lie_subalgebra_equiv B e f) = e.lie_conj f := by simp [skew_adjoint_lie_subalgebra_equiv] @[simp] lemma skew_adjoint_lie_subalgebra_equiv_symm_apply (f : skew_adjoint_lie_subalgebra B) : ↑((skew_adjoint_lie_subalgebra_equiv B e).symm f) = e.symm.lie_conj f := by simp [skew_adjoint_lie_subalgebra_equiv] end skew_adjoint_endomorphisms section skew_adjoint_matrices open_locale matrix variables {R : Type u} {n : Type w} [comm_ring R] [decidable_eq n] [fintype n] variables (J : matrix n n R) lemma matrix.lie_transpose (A B : matrix n n R) : ⁅A, B⁆ᵀ = ⁅Bᵀ, Aᵀ⁆ := show (A * B - B * A)ᵀ = (Bᵀ * Aᵀ - Aᵀ * Bᵀ), by simp lemma matrix.is_skew_adjoint_bracket (A B : matrix n n R) (hA : A ∈ skew_adjoint_matrices_submodule J) (hB : B ∈ skew_adjoint_matrices_submodule J) : ⁅A, B⁆ ∈ skew_adjoint_matrices_submodule J := begin simp only [mem_skew_adjoint_matrices_submodule] at *, change ⁅A, B⁆ᵀ ⬝ J = J ⬝ -⁅A, B⁆, change Aᵀ ⬝ J = J ⬝ -A at hA, change Bᵀ ⬝ J = J ⬝ -B at hB, simp only [←matrix.mul_eq_mul] at *, rw [matrix.lie_transpose, lie_ring.of_associative_ring_bracket, lie_ring.of_associative_ring_bracket, sub_mul, mul_assoc, mul_assoc, hA, hB, ←mul_assoc, ←mul_assoc, hA, hB], noncomm_ring, end /-- The Lie subalgebra of skew-adjoint square matrices corresponding to a square matrix `J`. -/ def skew_adjoint_matrices_lie_subalgebra : lie_subalgebra R (matrix n n R) := { lie_mem' := J.is_skew_adjoint_bracket, ..(skew_adjoint_matrices_submodule J) } @[simp] lemma mem_skew_adjoint_matrices_lie_subalgebra (A : matrix n n R) : A ∈ skew_adjoint_matrices_lie_subalgebra J ↔ A ∈ skew_adjoint_matrices_submodule J := iff.rfl /-- An invertible matrix `P` gives a Lie algebra equivalence between those endomorphisms that are skew-adjoint with respect to a square matrix `J` and those with respect to `PᵀJP`. -/ def skew_adjoint_matrices_lie_subalgebra_equiv (P : matrix n n R) (h : invertible P) : skew_adjoint_matrices_lie_subalgebra J ≃ₗ⁅R⁆ skew_adjoint_matrices_lie_subalgebra (Pᵀ ⬝ J ⬝ P) := lie_equiv.of_subalgebras _ _ (P.lie_conj h).symm begin ext A, suffices : P.lie_conj h A ∈ skew_adjoint_matrices_submodule J ↔ A ∈ skew_adjoint_matrices_submodule (Pᵀ ⬝ J ⬝ P), { simp only [lie_subalgebra.mem_coe, submodule.mem_map_equiv, lie_subalgebra.mem_map_submodule, coe_coe], exact this, }, simp [matrix.is_skew_adjoint, J.is_adjoint_pair_equiv' _ _ P (is_unit_of_invertible P)], end lemma skew_adjoint_matrices_lie_subalgebra_equiv_apply (P : matrix n n R) (h : invertible P) (A : skew_adjoint_matrices_lie_subalgebra J) : ↑(skew_adjoint_matrices_lie_subalgebra_equiv J P h A) = P⁻¹ ⬝ ↑A ⬝ P := by simp [skew_adjoint_matrices_lie_subalgebra_equiv] /-- An equivalence of matrix algebras commuting with the transpose endomorphisms restricts to an equivalence of Lie algebras of skew-adjoint matrices. -/ def skew_adjoint_matrices_lie_subalgebra_equiv_transpose {m : Type w} [decidable_eq m] [fintype m] (e : matrix n n R ≃ₐ[R] matrix m m R) (h : ∀ A, (e A)ᵀ = e (Aᵀ)) : skew_adjoint_matrices_lie_subalgebra J ≃ₗ⁅R⁆ skew_adjoint_matrices_lie_subalgebra (e J) := lie_equiv.of_subalgebras _ _ e.to_lie_equiv begin ext A, suffices : J.is_skew_adjoint (e.symm A) ↔ (e J).is_skew_adjoint A, by simpa [this], simp [matrix.is_skew_adjoint, matrix.is_adjoint_pair, ← matrix.mul_eq_mul, ← h, ← function.injective.eq_iff e.injective], end @[simp] lemma skew_adjoint_matrices_lie_subalgebra_equiv_transpose_apply {m : Type w} [decidable_eq m] [fintype m] (e : matrix n n R ≃ₐ[R] matrix m m R) (h : ∀ A, (e A)ᵀ = e (Aᵀ)) (A : skew_adjoint_matrices_lie_subalgebra J) : (skew_adjoint_matrices_lie_subalgebra_equiv_transpose J e h A : matrix m m R) = e A := rfl lemma mem_skew_adjoint_matrices_lie_subalgebra_unit_smul (u : Rˣ) (J A : matrix n n R) : A ∈ skew_adjoint_matrices_lie_subalgebra (u • J) ↔ A ∈ skew_adjoint_matrices_lie_subalgebra J := begin change A ∈ skew_adjoint_matrices_submodule (u • J) ↔ A ∈ skew_adjoint_matrices_submodule J, simp only [mem_skew_adjoint_matrices_submodule, matrix.is_skew_adjoint, matrix.is_adjoint_pair], split; intros h, { simpa using congr_arg (λ B, u⁻¹ • B) h, }, { simp [h], }, end end skew_adjoint_matrices
04fdbfa2103086f22ef40e79a7a707240abd68e3
367134ba5a65885e863bdc4507601606690974c1
/src/data/real/basic.lean
026b37aa748d3c79b047a3bdca8f5c1bb0f80a42
[ "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
20,995
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Floris van Doorn The (classical) real numbers ℝ. This is a direct construction from Cauchy sequences. -/ import order.conditionally_complete_lattice import data.real.cau_seq_completion import algebra.archimedean import algebra.star.basic /-- The type `ℝ` of real numbers constructed as equivalence classes of Cauchy sequences of rational numbers. -/ structure real := of_cauchy :: (cauchy : @cau_seq.completion.Cauchy ℚ _ _ _ abs _) notation `ℝ` := real attribute [pp_using_anonymous_constructor] real namespace real open cau_seq cau_seq.completion variables {x y : ℝ} lemma ext_cauchy_iff : ∀ {x y : real}, x = y ↔ x.cauchy = y.cauchy | ⟨a⟩ ⟨b⟩ := by split; cc lemma ext_cauchy {x y : real} : x.cauchy = y.cauchy → x = y := ext_cauchy_iff.2 /-- The real numbers are isomorphic to the quotient of Cauchy sequences on the rationals. -/ def equiv_Cauchy : ℝ ≃ cau_seq.completion.Cauchy := ⟨real.cauchy, real.of_cauchy, λ ⟨_⟩, rfl, λ _, rfl⟩ -- irreducible doesn't work for instances: https://github.com/leanprover-community/lean/issues/511 @[irreducible] private def zero : ℝ := ⟨0⟩ @[irreducible] private def one : ℝ := ⟨1⟩ @[irreducible] private def add : ℝ → ℝ → ℝ | ⟨a⟩ ⟨b⟩ := ⟨a + b⟩ @[irreducible] private def neg : ℝ → ℝ | ⟨a⟩ := ⟨-a⟩ @[irreducible] private def mul : ℝ → ℝ → ℝ | ⟨a⟩ ⟨b⟩ := ⟨a * b⟩ instance : has_zero ℝ := ⟨zero⟩ instance : has_one ℝ := ⟨one⟩ instance : has_add ℝ := ⟨add⟩ instance : has_neg ℝ := ⟨neg⟩ instance : has_mul ℝ := ⟨mul⟩ lemma zero_cauchy : (⟨0⟩ : ℝ) = 0 := show _ = zero, by rw zero lemma one_cauchy : (⟨1⟩ : ℝ) = 1 := show _ = one, by rw one lemma add_cauchy {a b} : (⟨a⟩ + ⟨b⟩ : ℝ) = ⟨a + b⟩ := show add _ _ = _, by rw add lemma neg_cauchy {a} : (-⟨a⟩ : ℝ) = ⟨-a⟩ := show neg _ = _, by rw neg lemma mul_cauchy {a b} : (⟨a⟩ * ⟨b⟩ : ℝ) = ⟨a * b⟩ := show mul _ _ = _, by rw mul instance : comm_ring ℝ := begin refine_struct { zero := 0, one := 1, mul := (*), add := (+), neg := @has_neg.neg ℝ _, sub := λ a b, a + (-b) }, all_goals { repeat { rintro ⟨_⟩, }, simp [← zero_cauchy, ← one_cauchy, add_cauchy, neg_cauchy, mul_cauchy], apply add_assoc <|> apply add_comm <|> apply mul_assoc <|> apply mul_comm <|> apply left_distrib <|> apply right_distrib <|> apply sub_eq_add_neg <|> skip }, end /- Extra instances to short-circuit type class resolution -/ instance : ring ℝ := by apply_instance instance : comm_semiring ℝ := by apply_instance instance : semiring ℝ := by apply_instance instance : add_comm_group ℝ := by apply_instance instance : add_group ℝ := by apply_instance instance : add_comm_monoid ℝ := by apply_instance instance : add_monoid ℝ := by apply_instance instance : add_left_cancel_semigroup ℝ := by apply_instance instance : add_right_cancel_semigroup ℝ := by apply_instance instance : add_comm_semigroup ℝ := by apply_instance instance : add_semigroup ℝ := by apply_instance instance : comm_monoid ℝ := by apply_instance instance : monoid ℝ := by apply_instance instance : comm_semigroup ℝ := by apply_instance instance : semigroup ℝ := by apply_instance instance : has_sub ℝ := by apply_instance instance : inhabited ℝ := ⟨0⟩ /-- The real numbers are a `*`-ring, with the trivial `*`-structure. -/ instance : star_ring ℝ := star_ring_of_comm /-- Coercion `ℚ` → `ℝ` as a `ring_hom`. Note that this is `cau_seq.completion.of_rat`, not `rat.cast`. -/ def of_rat : ℚ →+* ℝ := by refine_struct { to_fun := of_cauchy ∘ of_rat }; simp [of_rat_one, of_rat_zero, of_rat_mul, of_rat_add, one_cauchy, zero_cauchy, ← mul_cauchy, ← add_cauchy] lemma of_rat_apply (x : ℚ) : of_rat x = of_cauchy (cau_seq.completion.of_rat x) := rfl /-- Make a real number from a Cauchy sequence of rationals (by taking the equivalence class). -/ def mk (x : cau_seq ℚ abs) : ℝ := ⟨cau_seq.completion.mk x⟩ theorem mk_eq {f g : cau_seq ℚ abs} : mk f = mk g ↔ f ≈ g := ext_cauchy_iff.trans mk_eq @[irreducible] private def lt : ℝ → ℝ → Prop | ⟨x⟩ ⟨y⟩ := quotient.lift_on₂ x y (<) $ λ f₁ g₁ f₂ g₂ hf hg, propext $ ⟨λ h, lt_of_eq_of_lt (setoid.symm hf) (lt_of_lt_of_eq h hg), λ h, lt_of_eq_of_lt hf (lt_of_lt_of_eq h (setoid.symm hg))⟩ instance : has_lt ℝ := ⟨lt⟩ lemma lt_cauchy {f g} : (⟨⟦f⟧⟩ : ℝ) < ⟨⟦g⟧⟩ ↔ f < g := show lt _ _ ↔ _, by rw lt; refl @[simp] theorem mk_lt {f g : cau_seq ℚ abs} : mk f < mk g ↔ f < g := lt_cauchy lemma mk_zero : mk 0 = 0 := by rw ← zero_cauchy; refl lemma mk_one : mk 1 = 1 := by rw ← one_cauchy; refl lemma mk_add {f g : cau_seq ℚ abs} : mk (f + g) = mk f + mk g := by simp [mk, add_cauchy] lemma mk_mul {f g : cau_seq ℚ abs} : mk (f * g) = mk f * mk g := by simp [mk, mul_cauchy] lemma mk_neg {f : cau_seq ℚ abs} : mk (-f) = -mk f := by simp [mk, neg_cauchy] @[simp] theorem mk_pos {f : cau_seq ℚ abs} : 0 < mk f ↔ pos f := by rw [← mk_zero, mk_lt]; exact iff_of_eq (congr_arg pos (sub_zero f)) @[irreducible] private def le (x y : ℝ) : Prop := x < y ∨ x = y instance : has_le ℝ := ⟨le⟩ private lemma le_def {x y : ℝ} : x ≤ y ↔ x < y ∨ x = y := show le _ _ ↔ _, by rw le @[simp] theorem mk_le {f g : cau_seq ℚ abs} : mk f ≤ mk g ↔ f ≤ g := by simp [le_def, mk_eq]; refl @[elab_as_eliminator] protected lemma ind_mk {C : real → Prop} (x : real) (h : ∀ y, C (mk y)) : C x := begin cases x with x, induction x using quot.induction_on with x, exact h x end theorem add_lt_add_iff_left {a b : ℝ} (c : ℝ) : c + a < c + b ↔ a < b := begin induction a using real.ind_mk, induction b using real.ind_mk, induction c using real.ind_mk, simp only [mk_lt, ← mk_add], show pos _ ↔ pos _, rw add_sub_add_left_eq_sub end instance : partial_order ℝ := { le := (≤), lt := (<), lt_iff_le_not_le := λ a b, real.ind_mk a $ λ a, real.ind_mk b $ λ b, by simpa using lt_iff_le_not_le, le_refl := λ a, a.ind_mk (by intro a; rw mk_le), le_trans := λ a b c, real.ind_mk a $ λ a, real.ind_mk b $ λ b, real.ind_mk c $ λ c, by simpa using le_trans, lt_iff_le_not_le := λ a b, real.ind_mk a $ λ a, real.ind_mk b $ λ b, by simpa using lt_iff_le_not_le, le_antisymm := λ a b, real.ind_mk a $ λ a, real.ind_mk b $ λ b, by simpa [mk_eq] using @cau_seq.le_antisymm _ _ a b } instance : preorder ℝ := by apply_instance theorem of_rat_lt {x y : ℚ} : of_rat x < of_rat y ↔ x < y := begin rw [mk_lt] {md := tactic.transparency.semireducible}, exact const_lt end protected theorem zero_lt_one : (0 : ℝ) < 1 := by convert of_rat_lt.2 zero_lt_one; simp protected theorem mul_pos {a b : ℝ} : 0 < a → 0 < b → 0 < a * b := begin induction a using real.ind_mk with a, induction b using real.ind_mk with b, simpa only [mk_lt, mk_pos, ← mk_mul] using cau_seq.mul_pos end instance : ordered_ring ℝ := { add_le_add_left := begin simp only [le_iff_eq_or_lt], rintros a b ⟨rfl, h⟩, { simp }, { exact λ c, or.inr ((add_lt_add_iff_left c).2 ‹_›) } end, zero_le_one := le_of_lt real.zero_lt_one, mul_pos := @real.mul_pos, .. real.comm_ring, .. real.partial_order, .. real.semiring } instance : ordered_semiring ℝ := by apply_instance instance : ordered_add_comm_group ℝ := by apply_instance instance : ordered_cancel_add_comm_monoid ℝ := by apply_instance instance : ordered_add_comm_monoid ℝ := by apply_instance instance : nontrivial ℝ := ⟨⟨0, 1, ne_of_lt real.zero_lt_one⟩⟩ open_locale classical noncomputable instance : linear_order ℝ := { le_total := begin intros a b, induction a using real.ind_mk with a, induction b using real.ind_mk with b, simpa using le_total a b, end, decidable_le := by apply_instance, .. real.partial_order } noncomputable instance : linear_ordered_comm_ring ℝ := { .. real.nontrivial, .. real.ordered_ring, .. real.comm_ring, .. real.linear_order } /- Extra instances to short-circuit type class resolution -/ noncomputable instance : linear_ordered_ring ℝ := by apply_instance noncomputable instance : linear_ordered_semiring ℝ := by apply_instance instance : domain ℝ := { .. real.nontrivial, .. real.comm_ring, .. linear_ordered_ring.to_domain } /-- The real numbers are an ordered `*`-ring, with the trivial `*`-structure. -/ instance : star_ordered_ring ℝ := { star_mul_self_nonneg := λ r, mul_self_nonneg r, } @[irreducible] private noncomputable def inv' : ℝ → ℝ | ⟨a⟩ := ⟨a⁻¹⟩ noncomputable instance : has_inv ℝ := ⟨inv'⟩ lemma inv_cauchy {f} : (⟨f⟩ : ℝ)⁻¹ = ⟨f⁻¹⟩ := show inv' _ = _, by rw inv' noncomputable instance : linear_ordered_field ℝ := { inv := has_inv.inv, mul_inv_cancel := begin rintros ⟨a⟩ h, rw mul_comm, simp only [inv_cauchy, mul_cauchy, ← one_cauchy, ← zero_cauchy, ne.def] at *, exact cau_seq.completion.inv_mul_cancel h, end, inv_zero := by simp [← zero_cauchy, inv_cauchy], ..real.linear_ordered_comm_ring, ..real.domain } /- Extra instances to short-circuit type class resolution -/ noncomputable instance : linear_ordered_add_comm_group ℝ := by apply_instance noncomputable instance field : field ℝ := by apply_instance noncomputable instance : division_ring ℝ := by apply_instance noncomputable instance : integral_domain ℝ := by apply_instance noncomputable instance : distrib_lattice ℝ := by apply_instance noncomputable instance : lattice ℝ := by apply_instance noncomputable instance : semilattice_inf ℝ := by apply_instance noncomputable instance : semilattice_sup ℝ := by apply_instance noncomputable instance : has_inf ℝ := by apply_instance noncomputable instance : has_sup ℝ := by apply_instance noncomputable instance decidable_lt (a b : ℝ) : decidable (a < b) := by apply_instance noncomputable instance decidable_le (a b : ℝ) : decidable (a ≤ b) := by apply_instance noncomputable instance decidable_eq (a b : ℝ) : decidable (a = b) := by apply_instance open rat @[simp] theorem of_rat_eq_cast : ∀ x : ℚ, of_rat x = x := of_rat.eq_rat_cast theorem le_mk_of_forall_le {f : cau_seq ℚ abs} : (∃ i, ∀ j ≥ i, x ≤ f j) → x ≤ mk f := begin intro h, induction x using real.ind_mk with x, apply le_of_not_lt, rw mk_lt, rintro ⟨K, K0, hK⟩, obtain ⟨i, H⟩ := exists_forall_ge_and h (exists_forall_ge_and hK (f.cauchy₃ $ half_pos K0)), apply not_lt_of_le (H _ (le_refl _)).1, rw ← of_rat_eq_cast, rw [mk_lt] {md := tactic.transparency.semireducible}, refine ⟨_, half_pos K0, i, λ j ij, _⟩, have := add_le_add (H _ ij).2.1 (le_of_lt (abs_lt.1 $ (H _ (le_refl _)).2.2 _ ij).1), rwa [← sub_eq_add_neg, sub_self_div_two, sub_apply, sub_add_sub_cancel] at this end theorem mk_le_of_forall_le {f : cau_seq ℚ abs} {x : ℝ} (h : ∃ i, ∀ j ≥ i, (f j : ℝ) ≤ x) : mk f ≤ x := begin cases h with i H, rw [← neg_le_neg_iff, ← mk_neg], exact le_mk_of_forall_le ⟨i, λ j ij, by simp [H _ ij]⟩ end theorem mk_near_of_forall_near {f : cau_seq ℚ abs} {x : ℝ} {ε : ℝ} (H : ∃ i, ∀ j ≥ i, abs ((f j : ℝ) - x) ≤ ε) : abs (mk f - x) ≤ ε := abs_sub_le_iff.2 ⟨sub_le_iff_le_add'.2 $ mk_le_of_forall_le $ H.imp $ λ i h j ij, sub_le_iff_le_add'.1 (abs_sub_le_iff.1 $ h j ij).1, sub_le.1 $ le_mk_of_forall_le $ H.imp $ λ i h j ij, sub_le.1 (abs_sub_le_iff.1 $ h j ij).2⟩ instance : archimedean ℝ := archimedean_iff_rat_le.2 $ λ x, real.ind_mk x $ λ f, let ⟨M, M0, H⟩ := f.bounded' 0 in ⟨M, mk_le_of_forall_le ⟨0, λ i _, rat.cast_le.2 $ le_of_lt (abs_lt.1 (H i)).2⟩⟩ noncomputable instance : floor_ring ℝ := archimedean.floor_ring _ theorem is_cau_seq_iff_lift {f : ℕ → ℚ} : is_cau_seq abs f ↔ is_cau_seq abs (λ i, (f i : ℝ)) := ⟨λ H ε ε0, let ⟨δ, δ0, δε⟩ := exists_pos_rat_lt ε0 in (H _ δ0).imp $ λ i hi j ij, lt_trans (by simpa using (@rat.cast_lt ℝ _ _ _).2 (hi _ ij)) δε, λ H ε ε0, (H _ (rat.cast_pos.2 ε0)).imp $ λ i hi j ij, (@rat.cast_lt ℝ _ _ _).1 $ by simpa using hi _ ij⟩ theorem of_near (f : ℕ → ℚ) (x : ℝ) (h : ∀ ε > 0, ∃ i, ∀ j ≥ i, abs ((f j : ℝ) - x) < ε) : ∃ h', real.mk ⟨f, h'⟩ = x := ⟨is_cau_seq_iff_lift.2 (of_near _ (const abs x) h), sub_eq_zero.1 $ abs_eq_zero.1 $ eq_of_le_of_forall_le_of_dense (abs_nonneg _) $ λ ε ε0, mk_near_of_forall_near $ (h _ ε0).imp (λ i h j ij, le_of_lt (h j ij))⟩ theorem exists_floor (x : ℝ) : ∃ (ub : ℤ), (ub:ℝ) ≤ x ∧ ∀ (z : ℤ), (z:ℝ) ≤ x → z ≤ ub := int.exists_greatest_of_bdd (let ⟨n, hn⟩ := exists_int_gt x in ⟨n, λ z h', int.cast_le.1 $ le_trans h' $ le_of_lt hn⟩) (let ⟨n, hn⟩ := exists_int_lt x in ⟨n, le_of_lt hn⟩) theorem exists_sup (S : set ℝ) : (∃ x, x ∈ S) → (∃ x, ∀ y ∈ S, y ≤ x) → ∃ x, ∀ y, x ≤ y ↔ ∀ z ∈ S, z ≤ y | ⟨L, hL⟩ ⟨U, hU⟩ := begin choose f hf using begin refine λ d : ℕ, @int.exists_greatest_of_bdd (λ n, ∃ y ∈ S, (n:ℝ) ≤ y * d) _ _, { cases exists_int_gt U with k hk, refine ⟨k * d, λ z h, _⟩, rcases h with ⟨y, yS, hy⟩, refine int.cast_le.1 (le_trans hy _), simp, exact mul_le_mul_of_nonneg_right (le_trans (hU _ yS) (le_of_lt hk)) (nat.cast_nonneg _) }, { exact ⟨⌊L * d⌋, L, hL, floor_le _⟩ } end, have hf₁ : ∀ n > 0, ∃ y ∈ S, ((f n / n:ℚ):ℝ) ≤ y := λ n n0, let ⟨y, yS, hy⟩ := (hf n).1 in ⟨y, yS, by simpa using (div_le_iff ((nat.cast_pos.2 n0):((_:ℝ) < _))).2 hy⟩, have hf₂ : ∀ (n > 0) (y ∈ S), (y - (n:ℕ)⁻¹ : ℝ) < (f n / n:ℚ), { intros n n0 y yS, have := lt_of_lt_of_le (sub_one_lt_floor _) (int.cast_le.2 $ (hf n).2 _ ⟨y, yS, floor_le _⟩), simp [-sub_eq_add_neg], rwa [lt_div_iff ((nat.cast_pos.2 n0):((_:ℝ) < _)), sub_mul, _root_.inv_mul_cancel], exact ne_of_gt (nat.cast_pos.2 n0) }, suffices hg, let g : cau_seq ℚ abs := ⟨λ n, f n / n, hg⟩, refine ⟨mk g, λ y, ⟨λ h x xS, le_trans _ h, λ h, _⟩⟩, { refine le_of_forall_ge_of_dense (λ z xz, _), cases exists_nat_gt (x - z)⁻¹ with K hK, refine le_mk_of_forall_le ⟨K, λ n nK, _⟩, replace xz := sub_pos.2 xz, replace hK := le_trans (le_of_lt hK) (nat.cast_le.2 nK), have n0 : 0 < n := nat.cast_pos.1 (lt_of_lt_of_le (inv_pos.2 xz) hK), refine le_trans _ (le_of_lt $ hf₂ _ n0 _ xS), rwa [le_sub, inv_le ((nat.cast_pos.2 n0):((_:ℝ) < _)) xz] }, { exact mk_le_of_forall_le ⟨1, λ n n1, let ⟨x, xS, hx⟩ := hf₁ _ n1 in le_trans hx (h _ xS)⟩ }, intros ε ε0, suffices : ∀ j k ≥ nat_ceil ε⁻¹, (f j / j - f k / k : ℚ) < ε, { refine ⟨_, λ j ij, abs_lt.2 ⟨_, this _ _ ij (le_refl _)⟩⟩, rw [neg_lt, neg_sub], exact this _ _ (le_refl _) ij }, intros j k ij ik, replace ij := le_trans (le_nat_ceil _) (nat.cast_le.2 ij), replace ik := le_trans (le_nat_ceil _) (nat.cast_le.2 ik), have j0 := nat.cast_pos.1 (lt_of_lt_of_le (inv_pos.2 ε0) ij), have k0 := nat.cast_pos.1 (lt_of_lt_of_le (inv_pos.2 ε0) ik), rcases hf₁ _ j0 with ⟨y, yS, hy⟩, refine lt_of_lt_of_le ((@rat.cast_lt ℝ _ _ _).1 _) ((inv_le ε0 (nat.cast_pos.2 k0)).1 ik), simpa using sub_lt_iff_lt_add'.2 (lt_of_le_of_lt hy $ sub_lt_iff_lt_add.1 $ hf₂ _ k0 _ yS) end noncomputable instance : has_Sup ℝ := ⟨λ S, if h : (∃ x, x ∈ S) ∧ (∃ x, ∀ y ∈ S, y ≤ x) then classical.some (exists_sup S h.1 h.2) else 0⟩ lemma Sup_def (S : set ℝ) : Sup S = if h : (∃ x, x ∈ S) ∧ (∃ x, ∀ y ∈ S, y ≤ x) then classical.some (exists_sup S h.1 h.2) else 0 := rfl theorem Sup_le (S : set ℝ) (h₁ : ∃ x, x ∈ S) (h₂ : ∃ x, ∀ y ∈ S, y ≤ x) {y} : Sup S ≤ y ↔ ∀ z ∈ S, z ≤ y := by simp [Sup_def, h₁, h₂]; exact classical.some_spec (exists_sup S h₁ h₂) y theorem lt_Sup (S : set ℝ) (h₁ : ∃ x, x ∈ S) (h₂ : ∃ x, ∀ y ∈ S, y ≤ x) {y} : y < Sup S ↔ ∃ z ∈ S, y < z := by simpa [not_forall] using not_congr (@Sup_le S h₁ h₂ y) theorem le_Sup (S : set ℝ) (h₂ : ∃ x, ∀ y ∈ S, y ≤ x) {x} (xS : x ∈ S) : x ≤ Sup S := (Sup_le S ⟨_, xS⟩ h₂).1 (le_refl _) _ xS theorem Sup_le_ub (S : set ℝ) (h₁ : ∃ x, x ∈ S) {ub} (h₂ : ∀ y ∈ S, y ≤ ub) : Sup S ≤ ub := (Sup_le S h₁ ⟨_, h₂⟩).2 h₂ protected lemma is_lub_Sup {s : set ℝ} {a b : ℝ} (ha : a ∈ s) (hb : b ∈ upper_bounds s) : is_lub s (Sup s) := ⟨λ x xs, real.le_Sup s ⟨_, hb⟩ xs, λ u h, real.Sup_le_ub _ ⟨_, ha⟩ h⟩ noncomputable instance : has_Inf ℝ := ⟨λ S, -Sup {x | -x ∈ S}⟩ lemma Inf_def (S : set ℝ) : Inf S = -Sup {x | -x ∈ S} := rfl theorem le_Inf (S : set ℝ) (h₁ : ∃ x, x ∈ S) (h₂ : ∃ x, ∀ y ∈ S, x ≤ y) {y} : y ≤ Inf S ↔ ∀ z ∈ S, y ≤ z := begin refine le_neg.trans ((Sup_le _ _ _).trans _), { cases h₁ with x xS, exact ⟨-x, by simp [xS]⟩ }, { cases h₂ with ub h, exact ⟨-ub, λ y hy, le_neg.1 $ h _ hy⟩ }, split; intros H z hz, { exact neg_le_neg_iff.1 (H _ $ by simp [hz]) }, { exact le_neg.2 (H _ hz) } end section -- this proof times out without this local attribute [instance, priority 1000] classical.prop_decidable theorem Inf_lt (S : set ℝ) (h₁ : ∃ x, x ∈ S) (h₂ : ∃ x, ∀ y ∈ S, x ≤ y) {y} : Inf S < y ↔ ∃ z ∈ S, z < y := by simpa [not_forall] using not_congr (@le_Inf S h₁ h₂ y) end theorem Inf_le (S : set ℝ) (h₂ : ∃ x, ∀ y ∈ S, x ≤ y) {x} (xS : x ∈ S) : Inf S ≤ x := (le_Inf S ⟨_, xS⟩ h₂).1 (le_refl _) _ xS theorem lb_le_Inf (S : set ℝ) (h₁ : ∃ x, x ∈ S) {lb} (h₂ : ∀ y ∈ S, lb ≤ y) : lb ≤ Inf S := (le_Inf S h₁ ⟨_, h₂⟩).2 h₂ noncomputable instance : conditionally_complete_linear_order ℝ := { Sup := has_Sup.Sup, Inf := has_Inf.Inf, le_cSup := assume (s : set ℝ) (a : ℝ) (_ : bdd_above s) (_ : a ∈ s), show a ≤ Sup s, from le_Sup s ‹bdd_above s› ‹a ∈ s›, cSup_le := assume (s : set ℝ) (a : ℝ) (_ : s.nonempty) (H : ∀b∈s, b ≤ a), show Sup s ≤ a, from Sup_le_ub s ‹s.nonempty› H, cInf_le := assume (s : set ℝ) (a : ℝ) (_ : bdd_below s) (_ : a ∈ s), show Inf s ≤ a, from Inf_le s ‹bdd_below s› ‹a ∈ s›, le_cInf := assume (s : set ℝ) (a : ℝ) (_ : s.nonempty) (H : ∀b∈s, a ≤ b), show a ≤ Inf s, from lb_le_Inf s ‹s.nonempty› H, ..real.linear_order, ..real.lattice} theorem Sup_empty : Sup (∅ : set ℝ) = 0 := dif_neg $ by simp theorem Sup_of_not_bdd_above {s : set ℝ} (hs : ¬ bdd_above s) : Sup s = 0 := dif_neg $ assume h, hs h.2 theorem Sup_univ : Sup (@set.univ ℝ) = 0 := real.Sup_of_not_bdd_above $ λ ⟨x, h⟩, not_le_of_lt (lt_add_one _) $ h (set.mem_univ _) theorem Inf_empty : Inf (∅ : set ℝ) = 0 := by simp [Inf_def, Sup_empty] theorem Inf_of_not_bdd_below {s : set ℝ} (hs : ¬ bdd_below s) : Inf s = 0 := have bdd_above {x | -x ∈ s} → bdd_below s, from assume ⟨b, hb⟩, ⟨-b, assume x hxs, neg_le.2 $ hb $ by simp [hxs]⟩, have ¬ bdd_above {x | -x ∈ s}, from mt this hs, neg_eq_zero.2 $ Sup_of_not_bdd_above $ this theorem cau_seq_converges (f : cau_seq ℝ abs) : ∃ x, f ≈ const abs x := begin let S := {x : ℝ | const abs x < f}, have lb : ∃ x, x ∈ S := exists_lt f, have ub' : ∀ x, f < const abs x → ∀ y ∈ S, y ≤ x := λ x h y yS, le_of_lt $ const_lt.1 $ cau_seq.lt_trans yS h, have ub : ∃ x, ∀ y ∈ S, y ≤ x := (exists_gt f).imp ub', refine ⟨Sup S, ((lt_total _ _).resolve_left (λ h, _)).resolve_right (λ h, _)⟩, { rcases h with ⟨ε, ε0, i, ih⟩, refine not_lt_of_le (Sup_le_ub S lb (ub' _ _)) (sub_lt_self _ (half_pos ε0)), refine ⟨_, half_pos ε0, i, λ j ij, _⟩, rw [sub_apply, const_apply, sub_right_comm, le_sub_iff_add_le, add_halves], exact ih _ ij }, { rcases h with ⟨ε, ε0, i, ih⟩, refine not_lt_of_le (le_Sup S ub _) ((lt_add_iff_pos_left _).2 (half_pos ε0)), refine ⟨_, half_pos ε0, i, λ j ij, _⟩, rw [sub_apply, const_apply, add_comm, ← sub_sub, le_sub_iff_add_le, add_halves], exact ih _ ij } end noncomputable instance : cau_seq.is_complete ℝ abs := ⟨cau_seq_converges⟩ end real
853e975a2fb0904dd80f84bda39559dfdf7bbfc3
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/ring_theory/ideal/over.lean
e9a5a86776ecf08c13917fcc1d0ce39f6bc29afd
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
18,026
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 ring_theory.algebraic import ring_theory.localization.at_prime import ring_theory.localization.integral /-! # Ideals over/under ideals > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file concerns ideals lying over other ideals. Let `f : R →+* S` be a ring homomorphism (typically a ring extension), `I` an ideal of `R` and `J` an ideal of `S`. We say `J` lies over `I` (and `I` under `J`) if `I` is the `f`-preimage of `J`. This is expressed here by writing `I = J.comap f`. ## Implementation notes The proofs of the `comap_ne_bot` and `comap_lt_comap` families use an approach specific for their situation: we construct an element in `I.comap f` from the coefficients of a minimal polynomial. Once mathlib has more material on the localization at a prime ideal, the results can be proven using more general going-up/going-down theory. -/ variables {R : Type*} [comm_ring R] namespace ideal open polynomial open_locale polynomial open submodule section comm_ring variables {S : Type*} [comm_ring S] {f : R →+* S} {I J : ideal S} lemma coeff_zero_mem_comap_of_root_mem_of_eval_mem {r : S} (hr : r ∈ I) {p : R[X]} (hp : p.eval₂ f r ∈ I) : p.coeff 0 ∈ I.comap f := begin rw [←p.div_X_mul_X_add, eval₂_add, eval₂_C, eval₂_mul, eval₂_X] at hp, refine mem_comap.mpr ((I.add_mem_iff_right _).mp hp), exact I.mul_mem_left _ hr end lemma coeff_zero_mem_comap_of_root_mem {r : S} (hr : r ∈ I) {p : R[X]} (hp : p.eval₂ f r = 0) : p.coeff 0 ∈ I.comap f := coeff_zero_mem_comap_of_root_mem_of_eval_mem hr (hp.symm ▸ I.zero_mem) lemma exists_coeff_ne_zero_mem_comap_of_non_zero_divisor_root_mem {r : S} (r_non_zero_divisor : ∀ {x}, x * r = 0 → x = 0) (hr : r ∈ I) {p : R[X]} : ∀ (p_ne_zero : p ≠ 0) (hp : p.eval₂ f r = 0), ∃ i, p.coeff i ≠ 0 ∧ p.coeff i ∈ I.comap f := begin refine p.rec_on_horner _ _ _, { intro h, contradiction }, { intros p a coeff_eq_zero a_ne_zero ih p_ne_zero hp, refine ⟨0, _, coeff_zero_mem_comap_of_root_mem hr hp⟩, simp [coeff_eq_zero, a_ne_zero] }, { intros p p_nonzero ih mul_nonzero hp, rw [eval₂_mul, eval₂_X] at hp, obtain ⟨i, hi, mem⟩ := ih p_nonzero (r_non_zero_divisor hp), refine ⟨i + 1, _, _⟩; simp [hi, mem] } end /-- Let `P` be an ideal in `R[x]`. The map `R[x]/P → (R / (P ∩ R))[x] / (P / (P ∩ R))` is injective. -/ lemma injective_quotient_le_comap_map (P : ideal R[X]) : function.injective ((map (map_ring_hom (quotient.mk (P.comap (C : R →+* R[X])))) P).quotient_map (map_ring_hom (quotient.mk (P.comap (C : R →+* R[X])))) le_comap_map) := begin refine quotient_map_injective' (le_of_eq _), rw comap_map_of_surjective (map_ring_hom (quotient.mk (P.comap (C : R →+* R[X])))) (map_surjective (quotient.mk (P.comap (C : R →+* R[X]))) quotient.mk_surjective), refine le_antisymm (sup_le le_rfl _) (le_sup_of_le_left le_rfl), refine λ p hp, polynomial_mem_ideal_of_coeff_mem_ideal P p (λ n, quotient.eq_zero_iff_mem.mp _), simpa only [coeff_map, coe_map_ring_hom] using ext_iff.mp (ideal.mem_bot.mp (mem_comap.mp hp)) n, end /-- The identity in this lemma asserts that the "obvious" square ``` R → (R / (P ∩ R)) ↓ ↓ R[x] / P → (R / (P ∩ R))[x] / (P / (P ∩ R)) ``` commutes. It is used, for instance, in the proof of `quotient_mk_comp_C_is_integral_of_jacobson`, in the file `ring_theory/jacobson`. -/ lemma quotient_mk_maps_eq (P : ideal R[X]) : ((quotient.mk (map (map_ring_hom (quotient.mk (P.comap (C : R →+* R[X])))) P)).comp C).comp (quotient.mk (P.comap (C : R →+* R[X]))) = ((map (map_ring_hom (quotient.mk (P.comap (C : R →+* R[X])))) P).quotient_map (map_ring_hom (quotient.mk (P.comap (C : R →+* R[X])))) le_comap_map).comp ((quotient.mk P).comp C) := begin refine ring_hom.ext (λ x, _), repeat { rw [ring_hom.coe_comp, function.comp_app] }, rw [quotient_map_mk, coe_map_ring_hom, map_C], end /-- This technical lemma asserts the existence of a polynomial `p` in an ideal `P ⊂ R[x]` that is non-zero in the quotient `R / (P ∩ R) [x]`. The assumptions are equivalent to `P ≠ 0` and `P ∩ R = (0)`. -/ lemma exists_nonzero_mem_of_ne_bot {P : ideal R[X]} (Pb : P ≠ ⊥) (hP : ∀ (x : R), C x ∈ P → x = 0) : ∃ p : R[X], p ∈ P ∧ (polynomial.map (quotient.mk (P.comap (C : R →+* R[X]))) p) ≠ 0 := begin obtain ⟨m, hm⟩ := submodule.nonzero_mem_of_bot_lt (bot_lt_iff_ne_bot.mpr Pb), refine ⟨m, submodule.coe_mem m, λ pp0, hm (submodule.coe_eq_zero.mp _)⟩, refine (injective_iff_map_eq_zero (polynomial.map_ring_hom (quotient.mk (P.comap (C : R →+* R[X]))))).mp _ _ pp0, refine map_injective _ ((quotient.mk (P.comap C)).injective_iff_ker_eq_bot.mpr _), rw [mk_ker], exact (submodule.eq_bot_iff _).mpr (λ x hx, hP x (mem_comap.mp hx)), end variables {p : ideal R} {P : ideal S} /-- If there is an injective map `R/p → S/P` such that following diagram commutes: ``` R → S ↓ ↓ R/p → S/P ``` then `P` lies over `p`. -/ lemma comap_eq_of_scalar_tower_quotient [algebra R S] [algebra (R ⧸ p) (S ⧸ P)] [is_scalar_tower R (R ⧸ p) (S ⧸ P)] (h : function.injective (algebra_map (R ⧸ p) (S ⧸ P))) : comap (algebra_map R S) P = p := begin ext x, split; rw [mem_comap, ← quotient.eq_zero_iff_mem, ← quotient.eq_zero_iff_mem, quotient.mk_algebra_map, is_scalar_tower.algebra_map_apply _ (R ⧸ p), quotient.algebra_map_eq], { intro hx, exact (injective_iff_map_eq_zero (algebra_map (R ⧸ p) (S ⧸ P))).mp h _ hx }, { intro hx, rw [hx, ring_hom.map_zero] }, end /-- If `P` lies over `p`, then `R / p` has a canonical map to `S / P`. -/ def quotient.algebra_quotient_of_le_comap (h : p ≤ comap f P) : algebra (R ⧸ p) (S ⧸ P) := ring_hom.to_algebra $ quotient_map _ f h /-- `R / p` has a canonical map to `S / pS`. -/ instance quotient.algebra_quotient_map_quotient : algebra (R ⧸ p) (S ⧸ map f p) := by exact quotient.algebra_quotient_of_le_comap le_comap_map @[simp] lemma quotient.algebra_map_quotient_map_quotient (x : R) : algebra_map (R ⧸ p) (S ⧸ map f p) (quotient.mk p x) = quotient.mk _ (f x) := rfl @[simp] lemma quotient.mk_smul_mk_quotient_map_quotient (x : R) (y : S) : quotient.mk p x • quotient.mk (map f p) y = quotient.mk _ (f x * y) := rfl instance quotient.tower_quotient_map_quotient [algebra R S] : is_scalar_tower R (R ⧸ p) (S ⧸ map (algebra_map R S) p) := is_scalar_tower.of_algebra_map_eq $ λ x, by rw [quotient.algebra_map_eq, quotient.algebra_map_quotient_map_quotient, quotient.mk_algebra_map] instance quotient_map_quotient.is_noetherian [algebra R S] [is_noetherian R S] (I : ideal R) : is_noetherian (R ⧸ I) (S ⧸ ideal.map (algebra_map R S) I) := is_noetherian_of_tower R $ is_noetherian_of_surjective S (ideal.quotient.mkₐ R _).to_linear_map $ linear_map.range_eq_top.mpr ideal.quotient.mk_surjective end comm_ring section is_domain variables {S : Type*} [comm_ring S] {f : R →+* S} {I J : ideal S} lemma exists_coeff_ne_zero_mem_comap_of_root_mem [is_domain S] {r : S} (r_ne_zero : r ≠ 0) (hr : r ∈ I) {p : R[X]} : ∀ (p_ne_zero : p ≠ 0) (hp : p.eval₂ f r = 0), ∃ i, p.coeff i ≠ 0 ∧ p.coeff i ∈ I.comap f := exists_coeff_ne_zero_mem_comap_of_non_zero_divisor_root_mem (λ _ h, or.resolve_right (mul_eq_zero.mp h) r_ne_zero) hr lemma exists_coeff_mem_comap_sdiff_comap_of_root_mem_sdiff [is_prime I] (hIJ : I ≤ J) {r : S} (hr : r ∈ (J : set S) \ I) {p : R[X]} (p_ne_zero : p.map (quotient.mk (I.comap f)) ≠ 0) (hpI : p.eval₂ f r ∈ I) : ∃ i, p.coeff i ∈ (J.comap f : set R) \ (I.comap f) := begin obtain ⟨hrJ, hrI⟩ := hr, have rbar_ne_zero : quotient.mk I r ≠ 0 := mt (quotient.mk_eq_zero I).mp hrI, have rbar_mem_J : quotient.mk I r ∈ J.map (quotient.mk I) := mem_map_of_mem _ hrJ, have quotient_f : ∀ x ∈ I.comap f, (quotient.mk I).comp f x = 0, { simp [quotient.eq_zero_iff_mem] }, have rbar_root : (p.map (quotient.mk (I.comap f))).eval₂ (quotient.lift (I.comap f) _ quotient_f) (quotient.mk I r) = 0, { convert quotient.eq_zero_iff_mem.mpr hpI, exact trans (eval₂_map _ _ _) (hom_eval₂ p f (quotient.mk I) r).symm }, obtain ⟨i, ne_zero, mem⟩ := exists_coeff_ne_zero_mem_comap_of_root_mem rbar_ne_zero rbar_mem_J p_ne_zero rbar_root, rw coeff_map at ne_zero mem, refine ⟨i, (mem_quotient_iff_mem hIJ).mp _, mt _ ne_zero⟩, { simpa using mem }, simp [quotient.eq_zero_iff_mem], end lemma comap_lt_comap_of_root_mem_sdiff [I.is_prime] (hIJ : I ≤ J) {r : S} (hr : r ∈ (J : set S) \ I) {p : R[X]} (p_ne_zero : p.map (quotient.mk (I.comap f)) ≠ 0) (hp : p.eval₂ f r ∈ I) : I.comap f < J.comap f := let ⟨i, hJ, hI⟩ := exists_coeff_mem_comap_sdiff_comap_of_root_mem_sdiff hIJ hr p_ne_zero hp in set_like.lt_iff_le_and_exists.mpr ⟨comap_mono hIJ, p.coeff i, hJ, hI⟩ lemma mem_of_one_mem (h : (1 : S) ∈ I) (x) : x ∈ I := (I.eq_top_iff_one.mpr h).symm ▸ mem_top lemma comap_lt_comap_of_integral_mem_sdiff [algebra R S] [hI : I.is_prime] (hIJ : I ≤ J) {x : S} (mem : x ∈ (J : set S) \ I) (integral : is_integral R x) : I.comap (algebra_map R S) < J.comap (algebra_map R S) := begin obtain ⟨p, p_monic, hpx⟩ := integral, refine comap_lt_comap_of_root_mem_sdiff hIJ mem _ _, swap, { apply map_monic_ne_zero p_monic, apply quotient.nontrivial, apply mt comap_eq_top_iff.mp, apply hI.1 }, convert I.zero_mem end lemma comap_ne_bot_of_root_mem [is_domain S] {r : S} (r_ne_zero : r ≠ 0) (hr : r ∈ I) {p : R[X]} (p_ne_zero : p ≠ 0) (hp : p.eval₂ f r = 0) : I.comap f ≠ ⊥ := λ h, let ⟨i, hi, mem⟩ := exists_coeff_ne_zero_mem_comap_of_root_mem r_ne_zero hr p_ne_zero hp in absurd (mem_bot.mp (eq_bot_iff.mp h mem)) hi lemma is_maximal_of_is_integral_of_is_maximal_comap [algebra R S] (hRS : algebra.is_integral R S) (I : ideal S) [I.is_prime] (hI : is_maximal (I.comap (algebra_map R S))) : is_maximal I := ⟨⟨mt comap_eq_top_iff.mpr hI.1.1, λ J I_lt_J, let ⟨I_le_J, x, hxJ, hxI⟩ := set_like.lt_iff_le_and_exists.mp I_lt_J in comap_eq_top_iff.1 $ hI.1.2 _ (comap_lt_comap_of_integral_mem_sdiff I_le_J ⟨hxJ, hxI⟩ (hRS x))⟩⟩ lemma is_maximal_of_is_integral_of_is_maximal_comap' (f : R →+* S) (hf : f.is_integral) (I : ideal S) [hI' : I.is_prime] (hI : is_maximal (I.comap f)) : is_maximal I := @is_maximal_of_is_integral_of_is_maximal_comap R _ S _ f.to_algebra hf I hI' hI variables [algebra R S] lemma comap_ne_bot_of_algebraic_mem [is_domain S] {x : S} (x_ne_zero : x ≠ 0) (x_mem : x ∈ I) (hx : is_algebraic R x) : I.comap (algebra_map R S) ≠ ⊥ := let ⟨p, p_ne_zero, hp⟩ := hx in comap_ne_bot_of_root_mem x_ne_zero x_mem p_ne_zero hp lemma comap_ne_bot_of_integral_mem [nontrivial R] [is_domain S] {x : S} (x_ne_zero : x ≠ 0) (x_mem : x ∈ I) (hx : is_integral R x) : I.comap (algebra_map R S) ≠ ⊥ := comap_ne_bot_of_algebraic_mem x_ne_zero x_mem (hx.is_algebraic R) lemma eq_bot_of_comap_eq_bot [nontrivial R] [is_domain S] (hRS : algebra.is_integral R S) (hI : I.comap (algebra_map R S) = ⊥) : I = ⊥ := begin refine eq_bot_iff.2 (λ x hx, _), by_cases hx0 : x = 0, { exact hx0.symm ▸ ideal.zero_mem ⊥ }, { exact absurd hI (comap_ne_bot_of_integral_mem hx0 hx (hRS x)) } end lemma is_maximal_comap_of_is_integral_of_is_maximal (hRS : algebra.is_integral R S) (I : ideal S) [hI : I.is_maximal] : is_maximal (I.comap (algebra_map R S)) := begin refine quotient.maximal_of_is_field _ _, haveI : is_prime (I.comap (algebra_map R S)) := comap_is_prime _ _, exact is_field_of_is_integral_of_is_field (is_integral_quotient_of_is_integral hRS) algebra_map_quotient_injective (by rwa ← quotient.maximal_ideal_iff_is_field_quotient), end lemma is_maximal_comap_of_is_integral_of_is_maximal' {R S : Type*} [comm_ring R] [comm_ring S] (f : R →+* S) (hf : f.is_integral) (I : ideal S) (hI : I.is_maximal) : is_maximal (I.comap f) := @is_maximal_comap_of_is_integral_of_is_maximal R _ S _ f.to_algebra hf I hI section is_integral_closure variables (S) {A : Type*} [comm_ring A] variables [algebra R A] [algebra A S] [is_scalar_tower R A S] [is_integral_closure A R S] lemma is_integral_closure.comap_lt_comap {I J : ideal A} [I.is_prime] (I_lt_J : I < J) : I.comap (algebra_map R A) < J.comap (algebra_map R A) := let ⟨I_le_J, x, hxJ, hxI⟩ := set_like.lt_iff_le_and_exists.mp I_lt_J in comap_lt_comap_of_integral_mem_sdiff I_le_J ⟨hxJ, hxI⟩ (is_integral_closure.is_integral R S x) lemma is_integral_closure.is_maximal_of_is_maximal_comap (I : ideal A) [I.is_prime] (hI : is_maximal (I.comap (algebra_map R A))) : is_maximal I := is_maximal_of_is_integral_of_is_maximal_comap (λ x, is_integral_closure.is_integral R S x) I hI variables [is_domain A] lemma is_integral_closure.comap_ne_bot [nontrivial R] {I : ideal A} (I_ne_bot : I ≠ ⊥) : I.comap (algebra_map R A) ≠ ⊥ := let ⟨x, x_mem, x_ne_zero⟩ := I.ne_bot_iff.mp I_ne_bot in comap_ne_bot_of_integral_mem x_ne_zero x_mem (is_integral_closure.is_integral R S x) lemma is_integral_closure.eq_bot_of_comap_eq_bot [nontrivial R] {I : ideal A} : I.comap (algebra_map R A) = ⊥ → I = ⊥ := imp_of_not_imp_not _ _ (is_integral_closure.comap_ne_bot S) end is_integral_closure lemma integral_closure.comap_lt_comap {I J : ideal (integral_closure R S)} [I.is_prime] (I_lt_J : I < J) : I.comap (algebra_map R (integral_closure R S)) < J.comap (algebra_map R (integral_closure R S)) := is_integral_closure.comap_lt_comap S I_lt_J lemma integral_closure.is_maximal_of_is_maximal_comap (I : ideal (integral_closure R S)) [I.is_prime] (hI : is_maximal (I.comap (algebra_map R (integral_closure R S)))) : is_maximal I := is_integral_closure.is_maximal_of_is_maximal_comap S I hI section variables [is_domain S] lemma integral_closure.comap_ne_bot [nontrivial R] {I : ideal (integral_closure R S)} (I_ne_bot : I ≠ ⊥) : I.comap (algebra_map R (integral_closure R S)) ≠ ⊥ := is_integral_closure.comap_ne_bot S I_ne_bot lemma integral_closure.eq_bot_of_comap_eq_bot [nontrivial R] {I : ideal (integral_closure R S)} : I.comap (algebra_map R (integral_closure R S)) = ⊥ → I = ⊥ := is_integral_closure.eq_bot_of_comap_eq_bot S /-- `comap (algebra_map R S)` is a surjection from the prime spec of `R` to prime spec of `S`. `hP : (algebra_map R S).ker ≤ P` is a slight generalization of the extension being injective -/ lemma exists_ideal_over_prime_of_is_integral' (H : algebra.is_integral R S) (P : ideal R) [is_prime P] (hP : (algebra_map R S).ker ≤ P) : ∃ (Q : ideal S), is_prime Q ∧ Q.comap (algebra_map R S) = P := begin have hP0 : (0 : S) ∉ algebra.algebra_map_submonoid S P.prime_compl, { rintro ⟨x, ⟨hx, x0⟩⟩, exact absurd (hP x0) hx }, let Rₚ := localization P.prime_compl, let Sₚ := localization (algebra.algebra_map_submonoid S P.prime_compl), letI : is_domain (localization (algebra.algebra_map_submonoid S P.prime_compl)) := is_localization.is_domain_localization (le_non_zero_divisors_of_no_zero_divisors hP0), obtain ⟨Qₚ : ideal Sₚ, Qₚ_maximal⟩ := exists_maximal Sₚ, haveI Qₚ_max : is_maximal (comap _ Qₚ) := @is_maximal_comap_of_is_integral_of_is_maximal Rₚ _ Sₚ _ (localization_algebra P.prime_compl S) (is_integral_localization H) _ Qₚ_maximal, refine ⟨comap (algebra_map S Sₚ) Qₚ, ⟨comap_is_prime _ Qₚ, _⟩⟩, convert localization.at_prime.comap_maximal_ideal, rw [comap_comap, ← local_ring.eq_maximal_ideal Qₚ_max, ← is_localization.map_comp _], refl end end /-- More general going-up theorem than `exists_ideal_over_prime_of_is_integral'`. TODO: Version of going-up theorem with arbitrary length chains (by induction on this)? Not sure how best to write an ascending chain in Lean -/ theorem exists_ideal_over_prime_of_is_integral (H : algebra.is_integral R S) (P : ideal R) [is_prime P] (I : ideal S) [is_prime I] (hIP : I.comap (algebra_map R S) ≤ P) : ∃ Q ≥ I, is_prime Q ∧ Q.comap (algebra_map R S) = P := begin let quot := (R ⧸ I.comap (algebra_map R S)), obtain ⟨Q' : ideal (S ⧸ I), ⟨Q'_prime, hQ'⟩⟩ := @exists_ideal_over_prime_of_is_integral' quot _ (S ⧸ I) _ ideal.quotient_algebra _ (is_integral_quotient_of_is_integral H) (map (quotient.mk (I.comap (algebra_map R S))) P) (map_is_prime_of_surjective quotient.mk_surjective (by simp [hIP])) (le_trans (le_of_eq ((ring_hom.injective_iff_ker_eq_bot _).1 algebra_map_quotient_injective)) bot_le), haveI := Q'_prime, refine ⟨Q'.comap _, le_trans (le_of_eq mk_ker.symm) (ker_le_comap _), ⟨comap_is_prime _ Q', _⟩⟩, rw comap_comap, refine trans _ (trans (congr_arg (comap (quotient.mk (comap (algebra_map R S) I))) hQ') _), { simpa [comap_comap] }, { refine trans (comap_map_of_surjective _ quotient.mk_surjective _) (sup_eq_left.2 _), simpa [← ring_hom.ker_eq_comap_bot] using hIP}, end /-- `comap (algebra_map R S)` is a surjection from the max spec of `S` to max spec of `R`. `hP : (algebra_map R S).ker ≤ P` is a slight generalization of the extension being injective -/ lemma exists_ideal_over_maximal_of_is_integral [is_domain S] (H : algebra.is_integral R S) (P : ideal R) [P_max : is_maximal P] (hP : (algebra_map R S).ker ≤ P) : ∃ (Q : ideal S), is_maximal Q ∧ Q.comap (algebra_map R S) = P := begin obtain ⟨Q, ⟨Q_prime, hQ⟩⟩ := exists_ideal_over_prime_of_is_integral' H P hP, haveI : Q.is_prime := Q_prime, exact ⟨Q, is_maximal_of_is_integral_of_is_maximal_comap H _ (hQ.symm ▸ P_max), hQ⟩, end end is_domain end ideal
9d23cb85a8c68128d1426e197a348c3e04dbdeef
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/topology/algebra/group/basic.lean
a9088e29754f0b1b71f8b442c5efb56c1c846101
[ "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
67,440
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Patrick Massot -/ import group_theory.group_action.conj_act import group_theory.group_action.quotient import group_theory.quotient_group import topology.algebra.monoid import topology.algebra.constructions /-! # Topological groups > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines the following typeclasses: * `topological_group`, `topological_add_group`: multiplicative and additive topological groups, i.e., groups with continuous `(*)` and `(⁻¹)` / `(+)` and `(-)`; * `has_continuous_sub G` means that `G` has a continuous subtraction operation. There is an instance deducing `has_continuous_sub` from `topological_group` but we use a separate typeclass because, e.g., `ℕ` and `ℝ≥0` have continuous subtraction but are not additive groups. We also define `homeomorph` versions of several `equiv`s: `homeomorph.mul_left`, `homeomorph.mul_right`, `homeomorph.inv`, and prove a few facts about neighbourhood filters in groups. ## Tags topological space, group, topological group -/ open classical set filter topological_space function open_locale classical topology filter pointwise universes u v w x variables {α : Type u} {β : Type v} {G : Type w} {H : Type x} section continuous_mul_group /-! ### Groups with continuous multiplication In this section we prove a few statements about groups with continuous `(*)`. -/ variables [topological_space G] [group G] [has_continuous_mul G] /-- Multiplication from the left in a topological group as a homeomorphism. -/ @[to_additive "Addition from the left in a topological additive group as a homeomorphism."] protected def homeomorph.mul_left (a : G) : G ≃ₜ G := { continuous_to_fun := continuous_const.mul continuous_id, continuous_inv_fun := continuous_const.mul continuous_id, .. equiv.mul_left a } @[simp, to_additive] lemma homeomorph.coe_mul_left (a : G) : ⇑(homeomorph.mul_left a) = (*) a := rfl @[to_additive] lemma homeomorph.mul_left_symm (a : G) : (homeomorph.mul_left a).symm = homeomorph.mul_left a⁻¹ := by { ext, refl } @[to_additive] lemma is_open_map_mul_left (a : G) : is_open_map (λ x, a * x) := (homeomorph.mul_left a).is_open_map @[to_additive is_open.left_add_coset] lemma is_open.left_coset {U : set G} (h : is_open U) (x : G) : is_open (left_coset x U) := is_open_map_mul_left x _ h @[to_additive] lemma is_closed_map_mul_left (a : G) : is_closed_map (λ x, a * x) := (homeomorph.mul_left a).is_closed_map @[to_additive is_closed.left_add_coset] lemma is_closed.left_coset {U : set G} (h : is_closed U) (x : G) : is_closed (left_coset x U) := is_closed_map_mul_left x _ h /-- Multiplication from the right in a topological group as a homeomorphism. -/ @[to_additive "Addition from the right in a topological additive group as a homeomorphism."] protected def homeomorph.mul_right (a : G) : G ≃ₜ G := { continuous_to_fun := continuous_id.mul continuous_const, continuous_inv_fun := continuous_id.mul continuous_const, .. equiv.mul_right a } @[simp, to_additive] lemma homeomorph.coe_mul_right (a : G) : ⇑(homeomorph.mul_right a) = λ g, g * a := rfl @[to_additive] lemma homeomorph.mul_right_symm (a : G) : (homeomorph.mul_right a).symm = homeomorph.mul_right a⁻¹ := by { ext, refl } @[to_additive] lemma is_open_map_mul_right (a : G) : is_open_map (λ x, x * a) := (homeomorph.mul_right a).is_open_map @[to_additive is_open.right_add_coset] lemma is_open.right_coset {U : set G} (h : is_open U) (x : G) : is_open (right_coset U x) := is_open_map_mul_right x _ h @[to_additive] lemma is_closed_map_mul_right (a : G) : is_closed_map (λ x, x * a) := (homeomorph.mul_right a).is_closed_map @[to_additive is_closed.right_add_coset] lemma is_closed.right_coset {U : set G} (h : is_closed U) (x : G) : is_closed (right_coset U x) := is_closed_map_mul_right x _ h @[to_additive] lemma discrete_topology_of_open_singleton_one (h : is_open ({1} : set G)) : discrete_topology G := begin rw ← singletons_open_iff_discrete, intro g, suffices : {g} = (λ (x : G), g⁻¹ * x) ⁻¹' {1}, { rw this, exact (continuous_mul_left (g⁻¹)).is_open_preimage _ h, }, simp only [mul_one, set.preimage_mul_left_singleton, eq_self_iff_true, inv_inv, set.singleton_eq_singleton_iff], end @[to_additive] lemma discrete_topology_iff_open_singleton_one : discrete_topology G ↔ is_open ({1} : set G) := ⟨λ h, forall_open_iff_discrete.mpr h {1}, discrete_topology_of_open_singleton_one⟩ end continuous_mul_group /-! ### `has_continuous_inv` and `has_continuous_neg` -/ /-- Basic hypothesis to talk about a topological additive group. A topological additive group over `M`, for example, is obtained by requiring the instances `add_group M` and `has_continuous_add M` and `has_continuous_neg M`. -/ class has_continuous_neg (G : Type u) [topological_space G] [has_neg G] : Prop := (continuous_neg : continuous (λ a : G, -a)) /-- Basic hypothesis to talk about a topological group. A topological group over `M`, for example, is obtained by requiring the instances `group M` and `has_continuous_mul M` and `has_continuous_inv M`. -/ @[to_additive] class has_continuous_inv (G : Type u) [topological_space G] [has_inv G] : Prop := (continuous_inv : continuous (λ a : G, a⁻¹)) export has_continuous_inv (continuous_inv) export has_continuous_neg (continuous_neg) section continuous_inv variables [topological_space G] [has_inv G] [has_continuous_inv G] @[to_additive] lemma continuous_on_inv {s : set G} : continuous_on has_inv.inv s := continuous_inv.continuous_on @[to_additive] lemma continuous_within_at_inv {s : set G} {x : G} : continuous_within_at has_inv.inv s x := continuous_inv.continuous_within_at @[to_additive] lemma continuous_at_inv {x : G} : continuous_at has_inv.inv x := continuous_inv.continuous_at @[to_additive] lemma tendsto_inv (a : G) : tendsto has_inv.inv (𝓝 a) (𝓝 (a⁻¹)) := continuous_at_inv /-- If a function converges to a value in a multiplicative topological group, then its inverse converges to the inverse of this value. For the version in normed fields assuming additionally that the limit is nonzero, use `tendsto.inv'`. -/ @[to_additive "If a function converges to a value in an additive topological group, then its negation converges to the negation of this value."] lemma filter.tendsto.inv {f : α → G} {l : filter α} {y : G} (h : tendsto f l (𝓝 y)) : tendsto (λ x, (f x)⁻¹) l (𝓝 y⁻¹) := (continuous_inv.tendsto y).comp h variables [topological_space α] {f : α → G} {s : set α} {x : α} @[continuity, to_additive] lemma continuous.inv (hf : continuous f) : continuous (λx, (f x)⁻¹) := continuous_inv.comp hf @[to_additive] lemma continuous_at.inv (hf : continuous_at f x) : continuous_at (λ x, (f x)⁻¹) x := continuous_at_inv.comp hf @[to_additive] lemma continuous_on.inv (hf : continuous_on f s) : continuous_on (λx, (f x)⁻¹) s := continuous_inv.comp_continuous_on hf @[to_additive] lemma continuous_within_at.inv (hf : continuous_within_at f s x) : continuous_within_at (λ x, (f x)⁻¹) s x := hf.inv @[to_additive] instance [topological_space H] [has_inv H] [has_continuous_inv H] : has_continuous_inv (G × H) := ⟨continuous_inv.fst'.prod_mk continuous_inv.snd'⟩ variable {ι : Type*} @[to_additive] instance pi.has_continuous_inv {C : ι → Type*} [∀ i, topological_space (C i)] [∀ i, has_inv (C i)] [∀ i, has_continuous_inv (C i)] : has_continuous_inv (Π i, C i) := { continuous_inv := continuous_pi (λ i, (continuous_apply i).inv) } /-- A version of `pi.has_continuous_inv` for non-dependent functions. It is needed because sometimes Lean fails to use `pi.has_continuous_inv` for non-dependent functions. -/ @[to_additive "A version of `pi.has_continuous_neg` for non-dependent functions. It is needed because sometimes Lean fails to use `pi.has_continuous_neg` for non-dependent functions."] instance pi.has_continuous_inv' : has_continuous_inv (ι → G) := pi.has_continuous_inv @[priority 100, to_additive] instance has_continuous_inv_of_discrete_topology [topological_space H] [has_inv H] [discrete_topology H] : has_continuous_inv H := ⟨continuous_of_discrete_topology⟩ section pointwise_limits variables (G₁ G₂ : Type*) [topological_space G₂] [t2_space G₂] @[to_additive] lemma is_closed_set_of_map_inv [has_inv G₁] [has_inv G₂] [has_continuous_inv G₂] : is_closed {f : G₁ → G₂ | ∀ x, f x⁻¹ = (f x)⁻¹ } := begin simp only [set_of_forall], refine is_closed_Inter (λ i, is_closed_eq (continuous_apply _) (continuous_apply _).inv), end end pointwise_limits instance [topological_space H] [has_inv H] [has_continuous_inv H] : has_continuous_neg (additive H) := { continuous_neg := @continuous_inv H _ _ _ } instance [topological_space H] [has_neg H] [has_continuous_neg H] : has_continuous_inv (multiplicative H) := { continuous_inv := @continuous_neg H _ _ _ } end continuous_inv section continuous_involutive_inv variables [topological_space G] [has_involutive_inv G] [has_continuous_inv G] {s : set G} @[to_additive] lemma is_compact.inv (hs : is_compact s) : is_compact s⁻¹ := by { rw [← image_inv], exact hs.image continuous_inv } variables (G) /-- Inversion in a topological group as a homeomorphism. -/ @[to_additive "Negation in a topological group as a homeomorphism."] protected def homeomorph.inv (G : Type*) [topological_space G] [has_involutive_inv G] [has_continuous_inv G] : G ≃ₜ G := { continuous_to_fun := continuous_inv, continuous_inv_fun := continuous_inv, .. equiv.inv G } @[to_additive] lemma is_open_map_inv : is_open_map (has_inv.inv : G → G) := (homeomorph.inv _).is_open_map @[to_additive] lemma is_closed_map_inv : is_closed_map (has_inv.inv : G → G) := (homeomorph.inv _).is_closed_map variables {G} @[to_additive] lemma is_open.inv (hs : is_open s) : is_open s⁻¹ := hs.preimage continuous_inv @[to_additive] lemma is_closed.inv (hs : is_closed s) : is_closed s⁻¹ := hs.preimage continuous_inv @[to_additive] lemma inv_closure : ∀ s : set G, (closure s)⁻¹ = closure s⁻¹ := (homeomorph.inv G).preimage_closure end continuous_involutive_inv section lattice_ops variables {ι' : Sort*} [has_inv G] @[to_additive] lemma has_continuous_inv_Inf {ts : set (topological_space G)} (h : Π t ∈ ts, @has_continuous_inv G t _) : @has_continuous_inv G (Inf ts) _ := { continuous_inv := continuous_Inf_rng.2 (λ t ht, continuous_Inf_dom ht (@has_continuous_inv.continuous_inv G t _ (h t ht))) } @[to_additive] lemma has_continuous_inv_infi {ts' : ι' → topological_space G} (h' : Π i, @has_continuous_inv G (ts' i) _) : @has_continuous_inv G (⨅ i, ts' i) _ := by {rw ← Inf_range, exact has_continuous_inv_Inf (set.forall_range_iff.mpr h')} @[to_additive] lemma has_continuous_inv_inf {t₁ t₂ : topological_space G} (h₁ : @has_continuous_inv G t₁ _) (h₂ : @has_continuous_inv G t₂ _) : @has_continuous_inv G (t₁ ⊓ t₂) _ := by { rw inf_eq_infi, refine has_continuous_inv_infi (λ b, _), cases b; assumption } end lattice_ops @[to_additive] lemma inducing.has_continuous_inv {G H : Type*} [has_inv G] [has_inv H] [topological_space G] [topological_space H] [has_continuous_inv H] {f : G → H} (hf : inducing f) (hf_inv : ∀ x, f x⁻¹ = (f x)⁻¹) : has_continuous_inv G := ⟨hf.continuous_iff.2 $ by simpa only [(∘), hf_inv] using hf.continuous.inv⟩ section topological_group /-! ### Topological groups A topological group is a group in which the multiplication and inversion operations are continuous. Topological additive groups are defined in the same way. Equivalently, we can require that the division operation `λ x y, x * y⁻¹` (resp., subtraction) is continuous. -/ /-- A topological (additive) group is a group in which the addition and negation operations are continuous. -/ class topological_add_group (G : Type u) [topological_space G] [add_group G] extends has_continuous_add G, has_continuous_neg G : Prop /-- A topological group is a group in which the multiplication and inversion operations are continuous. When you declare an instance that does not already have a `uniform_space` instance, you should also provide an instance of `uniform_space` and `uniform_group` using `topological_group.to_uniform_space` and `topological_comm_group_is_uniform`. -/ @[to_additive] class topological_group (G : Type*) [topological_space G] [group G] extends has_continuous_mul G, has_continuous_inv G : Prop section conj instance conj_act.units_has_continuous_const_smul {M} [monoid M] [topological_space M] [has_continuous_mul M] : has_continuous_const_smul (conj_act Mˣ) M := ⟨λ m, (continuous_const.mul continuous_id).mul continuous_const⟩ /-- we slightly weaken the type class assumptions here so that it will also apply to `ennreal`, but we nevertheless leave it in the `topological_group` namespace. -/ variables [topological_space G] [has_inv G] [has_mul G] [has_continuous_mul G] /-- Conjugation is jointly continuous on `G × G` when both `mul` and `inv` are continuous. -/ @[to_additive "Conjugation is jointly continuous on `G × G` when both `mul` and `inv` are continuous."] lemma topological_group.continuous_conj_prod [has_continuous_inv G] : continuous (λ g : G × G, g.fst * g.snd * g.fst⁻¹) := continuous_mul.mul (continuous_inv.comp continuous_fst) /-- Conjugation by a fixed element is continuous when `mul` is continuous. -/ @[to_additive "Conjugation by a fixed element is continuous when `add` is continuous."] lemma topological_group.continuous_conj (g : G) : continuous (λ (h : G), g * h * g⁻¹) := (continuous_mul_right g⁻¹).comp (continuous_mul_left g) /-- Conjugation acting on fixed element of the group is continuous when both `mul` and `inv` are continuous. -/ @[to_additive "Conjugation acting on fixed element of the additive group is continuous when both `add` and `neg` are continuous."] lemma topological_group.continuous_conj' [has_continuous_inv G] (h : G) : continuous (λ (g : G), g * h * g⁻¹) := (continuous_mul_right h).mul continuous_inv end conj variables [topological_space G] [group G] [topological_group G] [topological_space α] {f : α → G} {s : set α} {x : α} section zpow @[continuity, to_additive] lemma continuous_zpow : ∀ z : ℤ, continuous (λ a : G, a ^ z) | (int.of_nat n) := by simpa using continuous_pow n | -[1+n] := by simpa using (continuous_pow (n + 1)).inv instance add_group.has_continuous_const_smul_int {A} [add_group A] [topological_space A] [topological_add_group A] : has_continuous_const_smul ℤ A := ⟨continuous_zsmul⟩ instance add_group.has_continuous_smul_int {A} [add_group A] [topological_space A] [topological_add_group A] : has_continuous_smul ℤ A := ⟨continuous_uncurry_of_discrete_topology continuous_zsmul⟩ @[continuity, to_additive] lemma continuous.zpow {f : α → G} (h : continuous f) (z : ℤ) : continuous (λ b, (f b) ^ z) := (continuous_zpow z).comp h @[to_additive] lemma continuous_on_zpow {s : set G} (z : ℤ) : continuous_on (λ x, x ^ z) s := (continuous_zpow z).continuous_on @[to_additive] lemma continuous_at_zpow (x : G) (z : ℤ) : continuous_at (λ x, x ^ z) x := (continuous_zpow z).continuous_at @[to_additive] lemma filter.tendsto.zpow {α} {l : filter α} {f : α → G} {x : G} (hf : tendsto f l (𝓝 x)) (z : ℤ) : tendsto (λ x, f x ^ z) l (𝓝 (x ^ z)) := (continuous_at_zpow _ _).tendsto.comp hf @[to_additive] lemma continuous_within_at.zpow {f : α → G} {x : α} {s : set α} (hf : continuous_within_at f s x) (z : ℤ) : continuous_within_at (λ x, f x ^ z) s x := hf.zpow z @[to_additive] lemma continuous_at.zpow {f : α → G} {x : α} (hf : continuous_at f x) (z : ℤ) : continuous_at (λ x, f x ^ z) x := hf.zpow z @[to_additive continuous_on.zsmul] lemma continuous_on.zpow {f : α → G} {s : set α} (hf : continuous_on f s) (z : ℤ) : continuous_on (λ x, f x ^ z) s := λ x hx, (hf x hx).zpow z end zpow section ordered_comm_group variables [topological_space H] [ordered_comm_group H] [has_continuous_inv H] @[to_additive] lemma tendsto_inv_nhds_within_Ioi {a : H} : tendsto has_inv.inv (𝓝[>] a) (𝓝[<] (a⁻¹)) := (continuous_inv.tendsto a).inf $ by simp [tendsto_principal_principal] @[to_additive] lemma tendsto_inv_nhds_within_Iio {a : H} : tendsto has_inv.inv (𝓝[<] a) (𝓝[>] (a⁻¹)) := (continuous_inv.tendsto a).inf $ by simp [tendsto_principal_principal] @[to_additive] lemma tendsto_inv_nhds_within_Ioi_inv {a : H} : tendsto has_inv.inv (𝓝[>] (a⁻¹)) (𝓝[<] a) := by simpa only [inv_inv] using @tendsto_inv_nhds_within_Ioi _ _ _ _ (a⁻¹) @[to_additive] lemma tendsto_inv_nhds_within_Iio_inv {a : H} : tendsto has_inv.inv (𝓝[<] (a⁻¹)) (𝓝[>] a) := by simpa only [inv_inv] using @tendsto_inv_nhds_within_Iio _ _ _ _ (a⁻¹) @[to_additive] lemma tendsto_inv_nhds_within_Ici {a : H} : tendsto has_inv.inv (𝓝[≥] a) (𝓝[≤] (a⁻¹)) := (continuous_inv.tendsto a).inf $ by simp [tendsto_principal_principal] @[to_additive] lemma tendsto_inv_nhds_within_Iic {a : H} : tendsto has_inv.inv (𝓝[≤] a) (𝓝[≥] (a⁻¹)) := (continuous_inv.tendsto a).inf $ by simp [tendsto_principal_principal] @[to_additive] lemma tendsto_inv_nhds_within_Ici_inv {a : H} : tendsto has_inv.inv (𝓝[≥] (a⁻¹)) (𝓝[≤] a) := by simpa only [inv_inv] using @tendsto_inv_nhds_within_Ici _ _ _ _ (a⁻¹) @[to_additive] lemma tendsto_inv_nhds_within_Iic_inv {a : H} : tendsto has_inv.inv (𝓝[≤] (a⁻¹)) (𝓝[≥] a) := by simpa only [inv_inv] using @tendsto_inv_nhds_within_Iic _ _ _ _ (a⁻¹) end ordered_comm_group @[instance, to_additive] instance [topological_space H] [group H] [topological_group H] : topological_group (G × H) := { continuous_inv := continuous_inv.prod_map continuous_inv } @[to_additive] instance pi.topological_group {C : β → Type*} [∀ b, topological_space (C b)] [∀ b, group (C b)] [∀ b, topological_group (C b)] : topological_group (Π b, C b) := { continuous_inv := continuous_pi (λ i, (continuous_apply i).inv) } open mul_opposite @[to_additive] instance [has_inv α] [has_continuous_inv α] : has_continuous_inv αᵐᵒᵖ := op_homeomorph.symm.inducing.has_continuous_inv unop_inv /-- If multiplication is continuous in `α`, then it also is in `αᵐᵒᵖ`. -/ @[to_additive "If addition is continuous in `α`, then it also is in `αᵃᵒᵖ`."] instance [group α] [topological_group α] : topological_group αᵐᵒᵖ := { } variable (G) @[to_additive] lemma nhds_one_symm : comap has_inv.inv (𝓝 (1 : G)) = 𝓝 (1 : G) := ((homeomorph.inv G).comap_nhds_eq _).trans (congr_arg nhds inv_one) @[to_additive] lemma nhds_one_symm' : map has_inv.inv (𝓝 (1 : G)) = 𝓝 (1 : G) := ((homeomorph.inv G).map_nhds_eq _).trans (congr_arg nhds inv_one) @[to_additive] lemma inv_mem_nhds_one {S : set G} (hS : S ∈ (𝓝 1 : filter G)) : S⁻¹ ∈ (𝓝 (1 : G)) := by rwa [← nhds_one_symm'] at hS /-- The map `(x, y) ↦ (x, xy)` as a homeomorphism. This is a shear mapping. -/ @[to_additive "The map `(x, y) ↦ (x, x + y)` as a homeomorphism. This is a shear mapping."] protected def homeomorph.shear_mul_right : G × G ≃ₜ G × G := { continuous_to_fun := continuous_fst.prod_mk continuous_mul, continuous_inv_fun := continuous_fst.prod_mk $ continuous_fst.inv.mul continuous_snd, .. equiv.prod_shear (equiv.refl _) equiv.mul_left } @[simp, to_additive] lemma homeomorph.shear_mul_right_coe : ⇑(homeomorph.shear_mul_right G) = λ z : G × G, (z.1, z.1 * z.2) := rfl @[simp, to_additive] lemma homeomorph.shear_mul_right_symm_coe : ⇑(homeomorph.shear_mul_right G).symm = λ z : G × G, (z.1, z.1⁻¹ * z.2) := rfl variables {G} @[to_additive] protected lemma inducing.topological_group {F : Type*} [group H] [topological_space H] [monoid_hom_class F H G] (f : F) (hf : inducing f) : topological_group H := { to_has_continuous_mul := hf.has_continuous_mul _, to_has_continuous_inv := hf.has_continuous_inv (map_inv f) } @[to_additive] protected lemma topological_group_induced {F : Type*} [group H] [monoid_hom_class F H G] (f : F) : @topological_group H (induced f ‹_›) _ := by { letI := induced f ‹_›, exact inducing.topological_group f ⟨rfl⟩ } namespace subgroup @[to_additive] instance (S : subgroup G) : topological_group S := inducing.topological_group S.subtype inducing_coe end subgroup /-- The (topological-space) closure of a subgroup of a space `M` with `has_continuous_mul` is itself a subgroup. -/ @[to_additive "The (topological-space) closure of an additive subgroup of a space `M` with `has_continuous_add` is itself an additive subgroup."] def subgroup.topological_closure (s : subgroup G) : subgroup G := { carrier := closure (s : set G), inv_mem' := λ g m, by simpa [←set.mem_inv, inv_closure] using m, ..s.to_submonoid.topological_closure } @[simp, to_additive] lemma subgroup.topological_closure_coe {s : subgroup G} : (s.topological_closure : set G) = closure s := rfl @[to_additive] lemma subgroup.le_topological_closure (s : subgroup G) : s ≤ s.topological_closure := subset_closure @[to_additive] lemma subgroup.is_closed_topological_closure (s : subgroup G) : is_closed (s.topological_closure : set G) := by convert is_closed_closure @[to_additive] lemma subgroup.topological_closure_minimal (s : subgroup G) {t : subgroup G} (h : s ≤ t) (ht : is_closed (t : set G)) : s.topological_closure ≤ t := closure_minimal h ht @[to_additive] lemma dense_range.topological_closure_map_subgroup [group H] [topological_space H] [topological_group H] {f : G →* H} (hf : continuous f) (hf' : dense_range f) {s : subgroup G} (hs : s.topological_closure = ⊤) : (s.map f).topological_closure = ⊤ := begin rw set_like.ext'_iff at hs ⊢, simp only [subgroup.topological_closure_coe, subgroup.coe_top, ← dense_iff_closure_eq] at hs ⊢, exact hf'.dense_image hf hs end /-- The topological closure of a normal subgroup is normal.-/ @[to_additive "The topological closure of a normal additive subgroup is normal."] lemma subgroup.is_normal_topological_closure {G : Type*} [topological_space G] [group G] [topological_group G] (N : subgroup G) [N.normal] : (subgroup.topological_closure N).normal := { conj_mem := λ n hn g, begin apply map_mem_closure (topological_group.continuous_conj g) hn, exact λ m hm, subgroup.normal.conj_mem infer_instance m hm g end } @[to_additive] lemma mul_mem_connected_component_one {G : Type*} [topological_space G] [mul_one_class G] [has_continuous_mul G] {g h : G} (hg : g ∈ connected_component (1 : G)) (hh : h ∈ connected_component (1 : G)) : g * h ∈ connected_component (1 : G) := begin rw connected_component_eq hg, have hmul: g ∈ connected_component (g*h), { apply continuous.image_connected_component_subset (continuous_mul_left g), rw ← connected_component_eq hh, exact ⟨(1 : G), mem_connected_component, by simp only [mul_one]⟩ }, simpa [← connected_component_eq hmul] using (mem_connected_component) end @[to_additive] lemma inv_mem_connected_component_one {G : Type*} [topological_space G] [group G] [topological_group G] {g : G} (hg : g ∈ connected_component (1 : G)) : g⁻¹ ∈ connected_component (1 : G) := begin rw ← inv_one, exact continuous.image_connected_component_subset continuous_inv _ ((set.mem_image _ _ _).mp ⟨g, hg, rfl⟩) end /-- The connected component of 1 is a subgroup of `G`. -/ @[to_additive "The connected component of 0 is a subgroup of `G`."] def subgroup.connected_component_of_one (G : Type*) [topological_space G] [group G] [topological_group G] : subgroup G := { carrier := connected_component (1 : G), one_mem' := mem_connected_component, mul_mem' := λ g h hg hh, mul_mem_connected_component_one hg hh, inv_mem' := λ g hg, inv_mem_connected_component_one hg } /-- If a subgroup of a topological group is commutative, then so is its topological closure. -/ @[to_additive "If a subgroup of an additive topological group is commutative, then so is its topological closure."] def subgroup.comm_group_topological_closure [t2_space G] (s : subgroup G) (hs : ∀ (x y : s), x * y = y * x) : comm_group s.topological_closure := { ..s.topological_closure.to_group, ..s.to_submonoid.comm_monoid_topological_closure hs } @[to_additive exists_nhds_half_neg] lemma exists_nhds_split_inv {s : set G} (hs : s ∈ 𝓝 (1 : G)) : ∃ V ∈ 𝓝 (1 : G), ∀ (v ∈ V) (w ∈ V), v / w ∈ s := have ((λp : G × G, p.1 * p.2⁻¹) ⁻¹' s) ∈ 𝓝 ((1, 1) : G × G), from continuous_at_fst.mul continuous_at_snd.inv (by simpa), by simpa only [div_eq_mul_inv, nhds_prod_eq, mem_prod_self_iff, prod_subset_iff, mem_preimage] using this @[to_additive] lemma nhds_translation_mul_inv (x : G) : comap (λ y : G, y * x⁻¹) (𝓝 1) = 𝓝 x := ((homeomorph.mul_right x⁻¹).comap_nhds_eq 1).trans $ show 𝓝 (1 * x⁻¹⁻¹) = 𝓝 x, by simp @[simp, to_additive] lemma map_mul_left_nhds (x y : G) : map ((*) x) (𝓝 y) = 𝓝 (x * y) := (homeomorph.mul_left x).map_nhds_eq y @[to_additive] lemma map_mul_left_nhds_one (x : G) : map ((*) x) (𝓝 1) = 𝓝 x := by simp @[simp, to_additive] lemma map_mul_right_nhds (x y : G) : map (λ z, z * x) (𝓝 y) = 𝓝 (y * x) := (homeomorph.mul_right x).map_nhds_eq y @[to_additive] lemma map_mul_right_nhds_one (x : G) : map (λ y, y * x) (𝓝 1) = 𝓝 x := by simp @[to_additive] lemma filter.has_basis.nhds_of_one {ι : Sort*} {p : ι → Prop} {s : ι → set G} (hb : has_basis (𝓝 1 : filter G) p s) (x : G) : has_basis (𝓝 x) p (λ i, {y | y / x ∈ s i}) := begin rw ← nhds_translation_mul_inv, simp_rw [div_eq_mul_inv], exact hb.comap _ end @[to_additive] lemma mem_closure_iff_nhds_one {x : G} {s : set G} : x ∈ closure s ↔ ∀ U ∈ (𝓝 1 : filter G), ∃ y ∈ s, y / x ∈ U := begin rw mem_closure_iff_nhds_basis ((𝓝 1 : filter G).basis_sets.nhds_of_one x), refl end /-- A monoid homomorphism (a bundled morphism of a type that implements `monoid_hom_class`) from a topological group to a topological monoid is continuous provided that it is continuous at one. See also `uniform_continuous_of_continuous_at_one`. -/ @[to_additive "An additive monoid homomorphism (a bundled morphism of a type that implements `add_monoid_hom_class`) from an additive topological group to an additive topological monoid is continuous provided that it is continuous at zero. See also `uniform_continuous_of_continuous_at_zero`."] lemma continuous_of_continuous_at_one {M hom : Type*} [mul_one_class M] [topological_space M] [has_continuous_mul M] [monoid_hom_class hom G M] (f : hom) (hf : continuous_at f 1) : continuous f := continuous_iff_continuous_at.2 $ λ x, by simpa only [continuous_at, ← map_mul_left_nhds_one x, tendsto_map'_iff, (∘), map_mul, map_one, mul_one] using hf.tendsto.const_mul (f x) @[to_additive] lemma topological_group.ext {G : Type*} [group G] {t t' : topological_space G} (tg : @topological_group G t _) (tg' : @topological_group G t' _) (h : @nhds G t 1 = @nhds G t' 1) : t = t' := eq_of_nhds_eq_nhds $ λ x, by rw [← @nhds_translation_mul_inv G t _ _ x , ← @nhds_translation_mul_inv G t' _ _ x , ← h] @[to_additive] lemma topological_group.ext_iff {G : Type*} [group G] {t t' : topological_space G} (tg : @topological_group G t _) (tg' : @topological_group G t' _) : t = t' ↔ @nhds G t 1 = @nhds G t' 1 := ⟨λ h, h ▸ rfl, tg.ext tg'⟩ @[to_additive] lemma has_continuous_inv.of_nhds_one {G : Type*} [group G] [topological_space G] (hinv : tendsto (λ (x : G), x⁻¹) (𝓝 1) (𝓝 1)) (hleft : ∀ (x₀ : G), 𝓝 x₀ = map (λ (x : G), x₀ * x) (𝓝 1)) (hconj : ∀ (x₀ : G), tendsto (λ (x : G), x₀ * x * x₀⁻¹) (𝓝 1) (𝓝 1)) : has_continuous_inv G := begin refine ⟨continuous_iff_continuous_at.2 $ λ x₀, _⟩, have : tendsto (λ x, x₀⁻¹ * (x₀ * x⁻¹ * x₀⁻¹)) (𝓝 1) (map ((*) x₀⁻¹) (𝓝 1)), from (tendsto_map.comp $ hconj x₀).comp hinv, simpa only [continuous_at, hleft x₀, hleft x₀⁻¹, tendsto_map'_iff, (∘), mul_assoc, mul_inv_rev, inv_mul_cancel_left] using this end @[to_additive] lemma topological_group.of_nhds_one' {G : Type u} [group G] [topological_space G] (hmul : tendsto (uncurry ((*) : G → G → G)) ((𝓝 1) ×ᶠ 𝓝 1) (𝓝 1)) (hinv : tendsto (λ x : G, x⁻¹) (𝓝 1) (𝓝 1)) (hleft : ∀ x₀ : G, 𝓝 x₀ = map (λ x, x₀*x) (𝓝 1)) (hright : ∀ x₀ : G, 𝓝 x₀ = map (λ x, x*x₀) (𝓝 1)) : topological_group G := { to_has_continuous_mul := has_continuous_mul.of_nhds_one hmul hleft hright, to_has_continuous_inv := has_continuous_inv.of_nhds_one hinv hleft $ λ x₀, le_of_eq begin rw [show (λ x, x₀ * x * x₀⁻¹) = (λ x, x * x₀⁻¹) ∘ (λ x, x₀ * x), from rfl, ← map_map, ← hleft, hright, map_map], simp [(∘)] end } @[to_additive] lemma topological_group.of_nhds_one {G : Type u} [group G] [topological_space G] (hmul : tendsto (uncurry ((*) : G → G → G)) ((𝓝 1) ×ᶠ 𝓝 1) (𝓝 1)) (hinv : tendsto (λ x : G, x⁻¹) (𝓝 1) (𝓝 1)) (hleft : ∀ x₀ : G, 𝓝 x₀ = map (λ x, x₀*x) (𝓝 1)) (hconj : ∀ x₀ : G, tendsto (λ x, x₀*x*x₀⁻¹) (𝓝 1) (𝓝 1)) : topological_group G := begin refine topological_group.of_nhds_one' hmul hinv hleft (λ x₀, _), replace hconj : ∀ x₀ : G, map (λ x, x₀ * x * x₀⁻¹) (𝓝 1) = 𝓝 1, from λ x₀, map_eq_of_inverse (λ x, x₀⁻¹ * x * x₀⁻¹⁻¹) (by { ext, simp [mul_assoc] }) (hconj _) (hconj _), rw [← hconj x₀], simpa [(∘)] using hleft _ end @[to_additive] lemma topological_group.of_comm_of_nhds_one {G : Type u} [comm_group G] [topological_space G] (hmul : tendsto (uncurry ((*) : G → G → G)) ((𝓝 1) ×ᶠ 𝓝 1) (𝓝 1)) (hinv : tendsto (λ x : G, x⁻¹) (𝓝 1) (𝓝 1)) (hleft : ∀ x₀ : G, 𝓝 x₀ = map (λ x, x₀*x) (𝓝 1)) : topological_group G := topological_group.of_nhds_one hmul hinv hleft (by simpa using tendsto_id) end topological_group section quotient_topological_group variables [topological_space G] [group G] [topological_group G] (N : subgroup G) (n : N.normal) @[to_additive] instance quotient_group.quotient.topological_space {G : Type*} [group G] [topological_space G] (N : subgroup G) : topological_space (G ⧸ N) := quotient.topological_space open quotient_group @[to_additive] lemma quotient_group.is_open_map_coe : is_open_map (coe : G → G ⧸ N) := begin intros s s_op, change is_open ((coe : G → G ⧸ N) ⁻¹' (coe '' s)), rw quotient_group.preimage_image_coe N s, exact is_open_Union (λ n, (continuous_mul_right _).is_open_preimage s s_op) end @[to_additive] instance topological_group_quotient [N.normal] : topological_group (G ⧸ N) := { continuous_mul := begin have cont : continuous ((coe : G → G ⧸ N) ∘ (λ (p : G × G), p.fst * p.snd)) := continuous_quot_mk.comp continuous_mul, have quot : quotient_map (λ p : G × G, ((p.1 : G ⧸ N), (p.2 : G ⧸ N))), { apply is_open_map.to_quotient_map, { exact (quotient_group.is_open_map_coe N).prod (quotient_group.is_open_map_coe N) }, { exact continuous_quot_mk.prod_map continuous_quot_mk }, { exact (surjective_quot_mk _).prod_map (surjective_quot_mk _) } }, exact (quotient_map.continuous_iff quot).2 cont, end, continuous_inv := by convert (@continuous_inv G _ _ _).quotient_map' _ } /-- Neighborhoods in the quotient are precisely the map of neighborhoods in the prequotient. -/ @[to_additive "Neighborhoods in the quotient are precisely the map of neighborhoods in the prequotient."] lemma quotient_group.nhds_eq (x : G) : 𝓝 (x : G ⧸ N) = map coe (𝓝 x) := le_antisymm ((quotient_group.is_open_map_coe N).nhds_le x) continuous_quot_mk.continuous_at variables (G) [first_countable_topology G] /-- Any first countable topological group has an antitone neighborhood basis `u : ℕ → set G` for which `(u (n + 1)) ^ 2 ⊆ u n`. The existence of such a neighborhood basis is a key tool for `quotient_group.complete_space` -/ @[to_additive "Any first countable topological additive group has an antitone neighborhood basis `u : ℕ → set G` for which `u (n + 1) + u (n + 1) ⊆ u n`. The existence of such a neighborhood basis is a key tool for `quotient_add_group.complete_space`"] lemma topological_group.exists_antitone_basis_nhds_one : ∃ (u : ℕ → set G), (𝓝 1).has_antitone_basis u ∧ (∀ n, u (n + 1) * u (n + 1) ⊆ u n) := begin rcases (𝓝 (1 : G)).exists_antitone_basis with ⟨u, hu, u_anti⟩, have := ((hu.prod_nhds hu).tendsto_iff hu).mp (by simpa only [mul_one] using continuous_mul.tendsto ((1, 1) : G × G)), simp only [and_self, mem_prod, and_imp, prod.forall, exists_true_left, prod.exists, forall_true_left] at this, have event_mul : ∀ n : ℕ, ∀ᶠ m in at_top, u m * u m ⊆ u n, { intros n, rcases this n with ⟨j, k, h⟩, refine at_top_basis.eventually_iff.mpr ⟨max j k, true.intro, λ m hm, _⟩, rintro - ⟨a, b, ha, hb, rfl⟩, exact h a b (u_anti ((le_max_left _ _).trans hm) ha) (u_anti ((le_max_right _ _).trans hm) hb)}, obtain ⟨φ, -, hφ, φ_anti_basis⟩ := has_antitone_basis.subbasis_with_rel ⟨hu, u_anti⟩ event_mul, exact ⟨u ∘ φ, φ_anti_basis, λ n, hφ n.lt_succ_self⟩, end include n /-- In a first countable topological group `G` with normal subgroup `N`, `1 : G ⧸ N` has a countable neighborhood basis. -/ @[to_additive "In a first countable topological additive group `G` with normal additive subgroup `N`, `0 : G ⧸ N` has a countable neighborhood basis."] instance quotient_group.nhds_one_is_countably_generated : (𝓝 (1 : G ⧸ N)).is_countably_generated := (quotient_group.nhds_eq N 1).symm ▸ map.is_countably_generated _ _ end quotient_topological_group /-- A typeclass saying that `λ p : G × G, p.1 - p.2` is a continuous function. This property automatically holds for topological additive groups but it also holds, e.g., for `ℝ≥0`. -/ class has_continuous_sub (G : Type*) [topological_space G] [has_sub G] : Prop := (continuous_sub : continuous (λ p : G × G, p.1 - p.2)) /-- A typeclass saying that `λ p : G × G, p.1 / p.2` is a continuous function. This property automatically holds for topological groups. Lemmas using this class have primes. The unprimed version is for `group_with_zero`. -/ @[to_additive] class has_continuous_div (G : Type*) [topological_space G] [has_div G] : Prop := (continuous_div' : continuous (λ p : G × G, p.1 / p.2)) @[priority 100, to_additive] -- see Note [lower instance priority] instance topological_group.to_has_continuous_div [topological_space G] [group G] [topological_group G] : has_continuous_div G := ⟨by { simp only [div_eq_mul_inv], exact continuous_fst.mul continuous_snd.inv }⟩ export has_continuous_sub (continuous_sub) export has_continuous_div (continuous_div') section has_continuous_div variables [topological_space G] [has_div G] [has_continuous_div G] @[to_additive sub] lemma filter.tendsto.div' {f g : α → G} {l : filter α} {a b : G} (hf : tendsto f l (𝓝 a)) (hg : tendsto g l (𝓝 b)) : tendsto (λ x, f x / g x) l (𝓝 (a / b)) := (continuous_div'.tendsto (a, b)).comp (hf.prod_mk_nhds hg) @[to_additive const_sub] lemma filter.tendsto.const_div' (b : G) {c : G} {f : α → G} {l : filter α} (h : tendsto f l (𝓝 c)) : tendsto (λ k : α, b / f k) l (𝓝 (b / c)) := tendsto_const_nhds.div' h @[to_additive sub_const] lemma filter.tendsto.div_const' {c : G} {f : α → G} {l : filter α} (h : tendsto f l (𝓝 c)) (b : G) : tendsto (λ k : α, f k / b) l (𝓝 (c / b)) := h.div' tendsto_const_nhds variables [topological_space α] {f g : α → G} {s : set α} {x : α} @[continuity, to_additive sub] lemma continuous.div' (hf : continuous f) (hg : continuous g) : continuous (λ x, f x / g x) := continuous_div'.comp (hf.prod_mk hg : _) @[to_additive continuous_sub_left] lemma continuous_div_left' (a : G) : continuous (λ b : G, a / b) := continuous_const.div' continuous_id @[to_additive continuous_sub_right] lemma continuous_div_right' (a : G) : continuous (λ b : G, b / a) := continuous_id.div' continuous_const @[to_additive sub] lemma continuous_at.div' {f g : α → G} {x : α} (hf : continuous_at f x) (hg : continuous_at g x) : continuous_at (λx, f x / g x) x := hf.div' hg @[to_additive sub] lemma continuous_within_at.div' (hf : continuous_within_at f s x) (hg : continuous_within_at g s x) : continuous_within_at (λ x, f x / g x) s x := hf.div' hg @[to_additive sub] lemma continuous_on.div' (hf : continuous_on f s) (hg : continuous_on g s) : continuous_on (λx, f x / g x) s := λ x hx, (hf x hx).div' (hg x hx) end has_continuous_div section div_in_topological_group variables [group G] [topological_space G] [topological_group G] /-- A version of `homeomorph.mul_left a b⁻¹` that is defeq to `a / b`. -/ @[to_additive /-" A version of `homeomorph.add_left a (-b)` that is defeq to `a - b`. "-/, simps {simp_rhs := tt}] def homeomorph.div_left (x : G) : G ≃ₜ G := { continuous_to_fun := continuous_const.div' continuous_id, continuous_inv_fun := continuous_inv.mul continuous_const, .. equiv.div_left x } @[to_additive] lemma is_open_map_div_left (a : G) : is_open_map ((/) a) := (homeomorph.div_left _).is_open_map @[to_additive] lemma is_closed_map_div_left (a : G) : is_closed_map ((/) a) := (homeomorph.div_left _).is_closed_map /-- A version of `homeomorph.mul_right a⁻¹ b` that is defeq to `b / a`. -/ @[to_additive /-" A version of `homeomorph.add_right (-a) b` that is defeq to `b - a`. "-/, simps {simp_rhs := tt}] def homeomorph.div_right (x : G) : G ≃ₜ G := { continuous_to_fun := continuous_id.div' continuous_const, continuous_inv_fun := continuous_id.mul continuous_const, .. equiv.div_right x } @[to_additive] lemma is_open_map_div_right (a : G) : is_open_map (λ x, x / a) := (homeomorph.div_right a).is_open_map @[to_additive] lemma is_closed_map_div_right (a : G) : is_closed_map (λ x, x / a) := (homeomorph.div_right a).is_closed_map @[to_additive] lemma tendsto_div_nhds_one_iff {α : Type*} {l : filter α} {x : G} {u : α → G} : tendsto (λ n, u n / x) l (𝓝 1) ↔ tendsto u l (𝓝 x) := begin have A : tendsto (λ (n : α), x) l (𝓝 x) := tendsto_const_nhds, exact ⟨λ h, by simpa using h.mul A, λ h, by simpa using h.div' A⟩ end @[to_additive] lemma nhds_translation_div (x : G) : comap (/ x) (𝓝 1) = 𝓝 x := by simpa only [div_eq_mul_inv] using nhds_translation_mul_inv x end div_in_topological_group /-! ### Topological operations on pointwise sums and products A few results about interior and closure of the pointwise addition/multiplication of sets in groups with continuous addition/multiplication. See also `submonoid.top_closure_mul_self_eq` in `topology.algebra.monoid`. -/ section has_continuous_const_smul variables [topological_space β] [group α] [mul_action α β] [has_continuous_const_smul α β] {s : set α} {t : set β} @[to_additive] lemma is_open.smul_left (ht : is_open t) : is_open (s • t) := by { rw ←bUnion_smul_set, exact is_open_bUnion (λ a _, ht.smul _) } @[to_additive] lemma subset_interior_smul_right : s • interior t ⊆ interior (s • t) := interior_maximal (set.smul_subset_smul_left interior_subset) is_open_interior.smul_left @[to_additive] lemma smul_mem_nhds (a : α) {x : β} (ht : t ∈ 𝓝 x) : a • t ∈ 𝓝 (a • x) := begin rcases mem_nhds_iff.1 ht with ⟨u, ut, u_open, hu⟩, exact mem_nhds_iff.2 ⟨a • u, smul_set_mono ut, u_open.smul a, smul_mem_smul_set hu⟩, end variables [topological_space α] @[to_additive] lemma subset_interior_smul : interior s • interior t ⊆ interior (s • t) := (set.smul_subset_smul_right interior_subset).trans subset_interior_smul_right end has_continuous_const_smul section has_continuous_const_smul variables [topological_space α] [group α] [has_continuous_const_smul α α] {s t : set α} @[to_additive] lemma is_open.mul_left : is_open t → is_open (s * t) := is_open.smul_left @[to_additive] lemma subset_interior_mul_right : s * interior t ⊆ interior (s * t) := subset_interior_smul_right @[to_additive] lemma subset_interior_mul : interior s * interior t ⊆ interior (s * t) := subset_interior_smul @[to_additive] lemma singleton_mul_mem_nhds (a : α) {b : α} (h : s ∈ 𝓝 b) : {a} * s ∈ 𝓝 (a * b) := by { have := smul_mem_nhds a h, rwa ← singleton_smul at this } @[to_additive] lemma singleton_mul_mem_nhds_of_nhds_one (a : α) (h : s ∈ 𝓝 (1 : α)) : {a} * s ∈ 𝓝 a := by simpa only [mul_one] using singleton_mul_mem_nhds a h end has_continuous_const_smul section has_continuous_const_smul_op variables [topological_space α] [group α] [has_continuous_const_smul αᵐᵒᵖ α] {s t : set α} @[to_additive] lemma is_open.mul_right (hs : is_open s) : is_open (s * t) := by { rw ←bUnion_op_smul_set, exact is_open_bUnion (λ a _, hs.smul _) } @[to_additive] lemma subset_interior_mul_left : interior s * t ⊆ interior (s * t) := interior_maximal (set.mul_subset_mul_right interior_subset) is_open_interior.mul_right @[to_additive] lemma subset_interior_mul' : interior s * interior t ⊆ interior (s * t) := (set.mul_subset_mul_left interior_subset).trans subset_interior_mul_left @[to_additive] lemma mul_singleton_mem_nhds (a : α) {b : α} (h : s ∈ 𝓝 b) : s * {a} ∈ 𝓝 (b * a) := begin simp only [←bUnion_op_smul_set, mem_singleton_iff, Union_Union_eq_left], exact smul_mem_nhds _ h, end @[to_additive] lemma mul_singleton_mem_nhds_of_nhds_one (a : α) (h : s ∈ 𝓝 (1 : α)) : s * {a} ∈ 𝓝 a := by simpa only [one_mul] using mul_singleton_mem_nhds a h end has_continuous_const_smul_op section topological_group variables [topological_space α] [group α] [topological_group α] {s t : set α} @[to_additive] lemma is_open.div_left (ht : is_open t) : is_open (s / t) := by { rw ←Union_div_left_image, exact is_open_bUnion (λ a ha, is_open_map_div_left a t ht) } @[to_additive] lemma is_open.div_right (hs : is_open s) : is_open (s / t) := by { rw ←Union_div_right_image, exact is_open_bUnion (λ a ha, is_open_map_div_right a s hs) } @[to_additive] lemma subset_interior_div_left : interior s / t ⊆ interior (s / t) := interior_maximal (div_subset_div_right interior_subset) is_open_interior.div_right @[to_additive] lemma subset_interior_div_right : s / interior t ⊆ interior (s / t) := interior_maximal (div_subset_div_left interior_subset) is_open_interior.div_left @[to_additive] lemma subset_interior_div : interior s / interior t ⊆ interior (s / t) := (div_subset_div_left interior_subset).trans subset_interior_div_left @[to_additive] lemma is_open.mul_closure (hs : is_open s) (t : set α) : s * closure t = s * t := begin refine (mul_subset_iff.2 $ λ a ha b hb, _).antisymm (mul_subset_mul_left subset_closure), rw mem_closure_iff at hb, have hbU : b ∈ s⁻¹ * {a * b} := ⟨a⁻¹, a * b, set.inv_mem_inv.2 ha, rfl, inv_mul_cancel_left _ _⟩, obtain ⟨_, ⟨c, d, hc, (rfl : d = _), rfl⟩, hcs⟩ := hb _ hs.inv.mul_right hbU, exact ⟨c⁻¹, _, hc, hcs, inv_mul_cancel_left _ _⟩, end @[to_additive] lemma is_open.closure_mul (ht : is_open t) (s : set α) : closure s * t = s * t := by rw [←inv_inv (closure s * t), mul_inv_rev, inv_closure, ht.inv.mul_closure, mul_inv_rev, inv_inv, inv_inv] @[to_additive] lemma is_open.div_closure (hs : is_open s) (t : set α) : s / closure t = s / t := by simp_rw [div_eq_mul_inv, inv_closure, hs.mul_closure] @[to_additive] lemma is_open.closure_div (ht : is_open t) (s : set α) : closure s / t = s / t := by simp_rw [div_eq_mul_inv, ht.inv.closure_mul] end topological_group /-- additive group with a neighbourhood around 0. Only used to construct a topology and uniform space. This is currently only available for commutative groups, but it can be extended to non-commutative groups too. -/ class add_group_with_zero_nhd (G : Type u) extends add_comm_group G := (Z [] : filter G) (zero_Z : pure 0 ≤ Z) (sub_Z : tendsto (λp:G×G, p.1 - p.2) (Z ×ᶠ Z) Z) section filter_mul section variables (G) [topological_space G] [group G] [has_continuous_mul G] @[to_additive] lemma topological_group.t1_space (h : @is_closed G _ {1}) : t1_space G := ⟨assume x, by { convert is_closed_map_mul_right x _ h, simp }⟩ end section variables (G) [topological_space G] [group G] [topological_group G] @[priority 100, to_additive] instance topological_group.regular_space : regular_space G := begin refine regular_space.of_exists_mem_nhds_is_closed_subset (λ a s hs, _), have : tendsto (λ p : G × G, p.1 * p.2) (𝓝 (a, 1)) (𝓝 a), from continuous_mul.tendsto' _ _ (mul_one a), rcases mem_nhds_prod_iff.mp (this hs) with ⟨U, hU, V, hV, hUV⟩, rw [← image_subset_iff, image_prod] at hUV, refine ⟨closure U, mem_of_superset hU subset_closure, is_closed_closure, _⟩, calc closure U ⊆ closure U * interior V : subset_mul_left _ (mem_interior_iff_mem_nhds.2 hV) ... = U * interior V : is_open_interior.closure_mul U ... ⊆ U * V : mul_subset_mul_left interior_subset ... ⊆ s : hUV end @[to_additive] lemma topological_group.t3_space [t0_space G] : t3_space G := ⟨⟩ @[to_additive] lemma topological_group.t2_space [t0_space G] : t2_space G := by { haveI := topological_group.t3_space G, apply_instance } variables {G} (S : subgroup G) [subgroup.normal S] [is_closed (S : set G)] @[to_additive] instance subgroup.t3_quotient_of_is_closed (S : subgroup G) [subgroup.normal S] [hS : is_closed (S : set G)] : t3_space (G ⧸ S) := begin rw ← quotient_group.ker_mk S at hS, haveI := topological_group.t1_space (G ⧸ S) (quotient_map_quotient_mk.is_closed_preimage.mp hS), exact topological_group.t3_space _, end /-- A subgroup `S` of a topological group `G` acts on `G` properly discontinuously on the left, if it is discrete in the sense that `S ∩ K` is finite for all compact `K`. (See also `discrete_topology`.) -/ @[to_additive "A subgroup `S` of an additive topological group `G` acts on `G` properly discontinuously on the left, if it is discrete in the sense that `S ∩ K` is finite for all compact `K`. (See also `discrete_topology`."] lemma subgroup.properly_discontinuous_smul_of_tendsto_cofinite (S : subgroup G) (hS : tendsto S.subtype cofinite (cocompact G)) : properly_discontinuous_smul S G := { finite_disjoint_inter_image := begin intros K L hK hL, have H : set.finite _ := hS ((hL.prod hK).image continuous_div').compl_mem_cocompact, rw [preimage_compl, compl_compl] at H, convert H, ext x, simpa only [image_smul, mem_image, prod.exists] using set.smul_inter_ne_empty_iff', end } local attribute [semireducible] mul_opposite /-- A subgroup `S` of a topological group `G` acts on `G` properly discontinuously on the right, if it is discrete in the sense that `S ∩ K` is finite for all compact `K`. (See also `discrete_topology`.) If `G` is Hausdorff, this can be combined with `t2_space_of_properly_discontinuous_smul_of_t2_space` to show that the quotient group `G ⧸ S` is Hausdorff. -/ @[to_additive "A subgroup `S` of an additive topological group `G` acts on `G` properly discontinuously on the right, if it is discrete in the sense that `S ∩ K` is finite for all compact `K`. (See also `discrete_topology`.) If `G` is Hausdorff, this can be combined with `t2_space_of_properly_discontinuous_vadd_of_t2_space` to show that the quotient group `G ⧸ S` is Hausdorff."] lemma subgroup.properly_discontinuous_smul_opposite_of_tendsto_cofinite (S : subgroup G) (hS : tendsto S.subtype cofinite (cocompact G)) : properly_discontinuous_smul S.opposite G := { finite_disjoint_inter_image := begin intros K L hK hL, have : continuous (λ p : G × G, (p.1⁻¹, p.2)) := continuous_inv.prod_map continuous_id, have H : set.finite _ := hS ((hK.prod hL).image (continuous_mul.comp this)).compl_mem_cocompact, rw [preimage_compl, compl_compl] at H, convert H, ext x, simpa only [image_smul, mem_image, prod.exists] using set.op_smul_inter_ne_empty_iff, end } end section /-! Some results about an open set containing the product of two sets in a topological group. -/ variables [topological_space G] [mul_one_class G] [has_continuous_mul G] /-- Given a compact set `K` inside an open set `U`, there is a open neighborhood `V` of `1` such that `K * V ⊆ U`. -/ @[to_additive "Given a compact set `K` inside an open set `U`, there is a open neighborhood `V` of `0` such that `K + V ⊆ U`."] lemma compact_open_separated_mul_right {K U : set G} (hK : is_compact K) (hU : is_open U) (hKU : K ⊆ U) : ∃ V ∈ 𝓝 (1 : G), K * V ⊆ U := begin apply hK.induction_on, { exact ⟨univ, by simp⟩ }, { rintros s t hst ⟨V, hV, hV'⟩, exact ⟨V, hV, (mul_subset_mul_right hst).trans hV'⟩ }, { rintros s t ⟨V, V_in, hV'⟩ ⟨W, W_in, hW'⟩, use [V ∩ W, inter_mem V_in W_in], rw union_mul, exact union_subset ((mul_subset_mul_left (V.inter_subset_left W)).trans hV') ((mul_subset_mul_left (V.inter_subset_right W)).trans hW') }, { intros x hx, have := tendsto_mul (show U ∈ 𝓝 (x * 1), by simpa using hU.mem_nhds (hKU hx)), rw [nhds_prod_eq, mem_map, mem_prod_iff] at this, rcases this with ⟨t, ht, s, hs, h⟩, rw [← image_subset_iff, image_mul_prod] at h, exact ⟨t, mem_nhds_within_of_mem_nhds ht, s, hs, h⟩ } end open mul_opposite /-- Given a compact set `K` inside an open set `U`, there is a open neighborhood `V` of `1` such that `V * K ⊆ U`. -/ @[to_additive "Given a compact set `K` inside an open set `U`, there is a open neighborhood `V` of `0` such that `V + K ⊆ U`."] lemma compact_open_separated_mul_left {K U : set G} (hK : is_compact K) (hU : is_open U) (hKU : K ⊆ U) : ∃ V ∈ 𝓝 (1 : G), V * K ⊆ U := begin rcases compact_open_separated_mul_right (hK.image continuous_op) (op_homeomorph.is_open_map U hU) (image_subset op hKU) with ⟨V, (hV : V ∈ 𝓝 (op (1 : G))), hV' : op '' K * V ⊆ op '' U⟩, refine ⟨op ⁻¹' V, continuous_op.continuous_at hV, _⟩, rwa [← image_preimage_eq V op_surjective, ← image_op_mul, image_subset_iff, preimage_image_eq _ op_injective] at hV' end end section variables [topological_space G] [group G] [topological_group G] /-- A compact set is covered by finitely many left multiplicative translates of a set with non-empty interior. -/ @[to_additive "A compact set is covered by finitely many left additive translates of a set with non-empty interior."] lemma compact_covered_by_mul_left_translates {K V : set G} (hK : is_compact K) (hV : (interior V).nonempty) : ∃ t : finset G, K ⊆ ⋃ g ∈ t, (λ h, g * h) ⁻¹' V := begin obtain ⟨t, ht⟩ : ∃ t : finset G, K ⊆ ⋃ x ∈ t, interior (((*) x) ⁻¹' V), { refine hK.elim_finite_subcover (λ x, interior $ ((*) x) ⁻¹' V) (λ x, is_open_interior) _, cases hV with g₀ hg₀, refine λ g hg, mem_Union.2 ⟨g₀ * g⁻¹, _⟩, refine preimage_interior_subset_interior_preimage (continuous_const.mul continuous_id) _, rwa [mem_preimage, inv_mul_cancel_right] }, exact ⟨t, subset.trans ht $ Union₂_mono $ λ g hg, interior_subset⟩ end /-- Every locally compact separable topological group is σ-compact. Note: this is not true if we drop the topological group hypothesis. -/ @[priority 100, to_additive separable_locally_compact_add_group.sigma_compact_space "Every locally compact separable topological group is σ-compact. Note: this is not true if we drop the topological group hypothesis."] instance separable_locally_compact_group.sigma_compact_space [separable_space G] [locally_compact_space G] : sigma_compact_space G := begin obtain ⟨L, hLc, hL1⟩ := exists_compact_mem_nhds (1 : G), refine ⟨⟨λ n, (λ x, x * dense_seq G n) ⁻¹' L, _, _⟩⟩, { intro n, exact (homeomorph.mul_right _).is_compact_preimage.mpr hLc }, { refine Union_eq_univ_iff.2 (λ x, _), obtain ⟨_, ⟨n, rfl⟩, hn⟩ : (range (dense_seq G) ∩ (λ y, x * y) ⁻¹' L).nonempty, { rw [← (homeomorph.mul_left x).apply_symm_apply 1] at hL1, exact (dense_range_dense_seq G).inter_nhds_nonempty ((homeomorph.mul_left x).continuous.continuous_at $ hL1) }, exact ⟨n, hn⟩ } end /-- Given two compact sets in a noncompact topological group, there is a translate of the second one that is disjoint from the first one. -/ @[to_additive "Given two compact sets in a noncompact additive topological group, there is a translate of the second one that is disjoint from the first one."] lemma exists_disjoint_smul_of_is_compact [noncompact_space G] {K L : set G} (hK : is_compact K) (hL : is_compact L) : ∃ (g : G), disjoint K (g • L) := begin have A : ¬ (K * L⁻¹ = univ), from (hK.mul hL.inv).ne_univ, obtain ⟨g, hg⟩ : ∃ g, g ∉ K * L⁻¹, { contrapose! A, exact eq_univ_iff_forall.2 A }, refine ⟨g, _⟩, apply disjoint_left.2 (λ a ha h'a, hg _), rcases h'a with ⟨b, bL, rfl⟩, refine ⟨g * b, b⁻¹, ha, by simpa only [set.mem_inv, inv_inv] using bL, _⟩, simp only [smul_eq_mul, mul_inv_cancel_right] end /-- In a locally compact group, any neighborhood of the identity contains a compact closed neighborhood of the identity, even without separation assumptions on the space. -/ @[to_additive "In a locally compact additive group, any neighborhood of the identity contains a compact closed neighborhood of the identity, even without separation assumptions on the space."] lemma local_is_compact_is_closed_nhds_of_group [locally_compact_space G] {U : set G} (hU : U ∈ 𝓝 (1 : G)) : ∃ (K : set G), is_compact K ∧ is_closed K ∧ K ⊆ U ∧ (1 : G) ∈ interior K := begin obtain ⟨L, Lint, LU, Lcomp⟩ : ∃ (L : set G) (H : L ∈ 𝓝 (1 : G)), L ⊆ U ∧ is_compact L, from local_compact_nhds hU, obtain ⟨V, Vnhds, hV⟩ : ∃ V ∈ 𝓝 (1 : G), ∀ (v ∈ V) (w ∈ V), v * w ∈ L, { have : ((λ p : G × G, p.1 * p.2) ⁻¹' L) ∈ 𝓝 ((1, 1) : G × G), { refine continuous_at_fst.mul continuous_at_snd _, simpa only [mul_one] using Lint }, simpa only [div_eq_mul_inv, nhds_prod_eq, mem_prod_self_iff, prod_subset_iff, mem_preimage] }, have VL : closure V ⊆ L, from calc closure V = {(1 : G)} * closure V : by simp only [singleton_mul, one_mul, image_id'] ... ⊆ interior V * closure V : mul_subset_mul_right (by simpa only [singleton_subset_iff] using mem_interior_iff_mem_nhds.2 Vnhds) ... = interior V * V : is_open_interior.mul_closure _ ... ⊆ V * V : mul_subset_mul_right interior_subset ... ⊆ L : by { rintros x ⟨y, z, yv, zv, rfl⟩, exact hV _ yv _ zv }, exact ⟨closure V, is_compact_of_is_closed_subset Lcomp is_closed_closure VL, is_closed_closure, VL.trans LU, interior_mono subset_closure (mem_interior_iff_mem_nhds.2 Vnhds)⟩, end end section variables [topological_space G] [group G] [topological_group G] @[to_additive] lemma nhds_mul (x y : G) : 𝓝 (x * y) = 𝓝 x * 𝓝 y := calc 𝓝 (x * y) = map ((*) x) (map (λ a, a * y) (𝓝 1 * 𝓝 1)) : by simp ... = map₂ (λ a b, x * (a * b * y)) (𝓝 1) (𝓝 1) : by rw [← map₂_mul, map_map₂, map_map₂] ... = map₂ (λ a b, x * a * (b * y)) (𝓝 1) (𝓝 1) : by simp only [mul_assoc] ... = 𝓝 x * 𝓝 y : by rw [← map_mul_left_nhds_one x, ← map_mul_right_nhds_one y, ← map₂_mul, map₂_map_left, map₂_map_right] /-- On a topological group, `𝓝 : G → filter G` can be promoted to a `mul_hom`. -/ @[to_additive "On an additive topological group, `𝓝 : G → filter G` can be promoted to an `add_hom`.", simps] def nhds_mul_hom : G →ₙ* (filter G) := { to_fun := 𝓝, map_mul' := λ_ _, nhds_mul _ _ } end end filter_mul instance {G} [topological_space G] [group G] [topological_group G] : topological_add_group (additive G) := { continuous_neg := @continuous_inv G _ _ _ } instance {G} [topological_space G] [add_group G] [topological_add_group G] : topological_group (multiplicative G) := { continuous_inv := @continuous_neg G _ _ _ } section quotient variables [group G] [topological_space G] [has_continuous_mul G] {Γ : subgroup G} @[to_additive] instance quotient_group.has_continuous_const_smul : has_continuous_const_smul G (G ⧸ Γ) := { continuous_const_smul := λ g, by convert ((@continuous_const _ _ _ _ g).mul continuous_id).quotient_map' _ } @[to_additive] lemma quotient_group.continuous_smul₁ (x : G ⧸ Γ) : continuous (λ g : G, g • x) := begin induction x using quotient_group.induction_on, exact continuous_quotient_mk.comp (continuous_mul_right x) end /-- The quotient of a second countable topological group by a subgroup is second countable. -/ @[to_additive "The quotient of a second countable additive topological group by a subgroup is second countable."] instance quotient_group.second_countable_topology [second_countable_topology G] : second_countable_topology (G ⧸ Γ) := has_continuous_const_smul.second_countable_topology end quotient /-- If `G` is a group with topological `⁻¹`, then it is homeomorphic to its units. -/ @[to_additive " If `G` is an additive group with topological negation, then it is homeomorphic to its additive units."] def to_units_homeomorph [group G] [topological_space G] [has_continuous_inv G] : G ≃ₜ Gˣ := { to_equiv := to_units.to_equiv, continuous_to_fun := units.continuous_iff.2 ⟨continuous_id, continuous_inv⟩, continuous_inv_fun := units.continuous_coe } namespace units open mul_opposite (continuous_op continuous_unop) variables [monoid α] [topological_space α] [monoid β] [topological_space β] @[to_additive] instance [has_continuous_mul α] : topological_group αˣ := { continuous_inv := units.continuous_iff.2 $ ⟨continuous_coe_inv, continuous_coe⟩ } /-- The topological group isomorphism between the units of a product of two monoids, and the product of the units of each monoid. -/ @[to_additive "The topological group isomorphism between the additive units of a product of two additive monoids, and the product of the additive units of each additive monoid."] def homeomorph.prod_units : (α × β)ˣ ≃ₜ (αˣ × βˣ) := { continuous_to_fun := (continuous_fst.units_map (monoid_hom.fst α β)).prod_mk (continuous_snd.units_map (monoid_hom.snd α β)), continuous_inv_fun := units.continuous_iff.2 ⟨continuous_coe.fst'.prod_mk continuous_coe.snd', continuous_coe_inv.fst'.prod_mk continuous_coe_inv.snd'⟩, to_equiv := mul_equiv.prod_units.to_equiv } end units section lattice_ops variables {ι : Sort*} [group G] @[to_additive] lemma topological_group_Inf {ts : set (topological_space G)} (h : ∀ t ∈ ts, @topological_group G t _) : @topological_group G (Inf ts) _ := { to_has_continuous_inv := @has_continuous_inv_Inf _ _ _ $ λ t ht, @topological_group.to_has_continuous_inv G t _ $ h t ht, to_has_continuous_mul := @has_continuous_mul_Inf _ _ _ $ λ t ht, @topological_group.to_has_continuous_mul G t _ $ h t ht } @[to_additive] lemma topological_group_infi {ts' : ι → topological_space G} (h' : ∀ i, @topological_group G (ts' i) _) : @topological_group G (⨅ i, ts' i) _ := by { rw ← Inf_range, exact topological_group_Inf (set.forall_range_iff.mpr h') } @[to_additive] lemma topological_group_inf {t₁ t₂ : topological_space G} (h₁ : @topological_group G t₁ _) (h₂ : @topological_group G t₂ _) : @topological_group G (t₁ ⊓ t₂) _ := by { rw inf_eq_infi, refine topological_group_infi (λ b, _), cases b; assumption } end lattice_ops /-! ### Lattice of group topologies We define a type class `group_topology α` which endows a group `α` with a topology such that all group operations are continuous. Group topologies on a fixed group `α` are ordered, by reverse inclusion. They form a complete lattice, with `⊥` the discrete topology and `⊤` the indiscrete topology. Any function `f : α → β` induces `coinduced f : topological_space α → group_topology β`. The additive version `add_group_topology α` and corresponding results are provided as well. -/ /-- A group topology on a group `α` is a topology for which multiplication and inversion are continuous. -/ structure group_topology (α : Type u) [group α] extends topological_space α, topological_group α : Type u /-- An additive group topology on an additive group `α` is a topology for which addition and negation are continuous. -/ structure add_group_topology (α : Type u) [add_group α] extends topological_space α, topological_add_group α : Type u attribute [to_additive] group_topology namespace group_topology variables [group α] /-- A version of the global `continuous_mul` suitable for dot notation. -/ @[to_additive "A version of the global `continuous_add` suitable for dot notation."] lemma continuous_mul' (g : group_topology α) : by haveI := g.to_topological_space; exact continuous (λ p : α × α, p.1 * p.2) := begin letI := g.to_topological_space, haveI := g.to_topological_group, exact continuous_mul, end /-- A version of the global `continuous_inv` suitable for dot notation. -/ @[to_additive "A version of the global `continuous_neg` suitable for dot notation."] lemma continuous_inv' (g : group_topology α) : by haveI := g.to_topological_space; exact continuous (has_inv.inv : α → α) := begin letI := g.to_topological_space, haveI := g.to_topological_group, exact continuous_inv, end @[to_additive] lemma to_topological_space_injective : function.injective (to_topological_space : group_topology α → topological_space α):= λ f g h, by { cases f, cases g, congr' } @[ext, to_additive] lemma ext' {f g : group_topology α} (h : f.is_open = g.is_open) : f = g := to_topological_space_injective $ topological_space_eq h /-- The ordering on group topologies on the group `γ`. `t ≤ s` if every set open in `s` is also open in `t` (`t` is finer than `s`). -/ @[to_additive "The ordering on group topologies on the group `γ`. `t ≤ s` if every set open in `s` is also open in `t` (`t` is finer than `s`)."] instance : partial_order (group_topology α) := partial_order.lift to_topological_space to_topological_space_injective @[simp, to_additive] lemma to_topological_space_le {x y : group_topology α} : x.to_topological_space ≤ y.to_topological_space ↔ x ≤ y := iff.rfl @[to_additive] instance : has_top (group_topology α) := ⟨{to_topological_space := ⊤, continuous_mul := continuous_top, continuous_inv := continuous_top}⟩ @[simp, to_additive] lemma to_topological_space_top : (⊤ : group_topology α).to_topological_space = ⊤ := rfl @[to_additive] instance : has_bot (group_topology α) := ⟨{to_topological_space := ⊥, continuous_mul := by { letI : topological_space α := ⊥, haveI := discrete_topology_bot α, continuity }, continuous_inv := continuous_bot}⟩ @[simp, to_additive] lemma to_topological_space_bot : (⊥ : group_topology α).to_topological_space = ⊥ := rfl @[to_additive] instance : bounded_order (group_topology α) := { top := ⊤, le_top := λ x, show x.to_topological_space ≤ ⊤, from le_top, bot := ⊥, bot_le := λ x, show ⊥ ≤ x.to_topological_space, from bot_le } @[to_additive] instance : has_inf (group_topology α) := { inf := λ x y, ⟨x.1 ⊓ y.1, topological_group_inf x.2 y.2⟩ } @[simp, to_additive] lemma to_topological_space_inf (x y : group_topology α) : (x ⊓ y).to_topological_space = x.to_topological_space ⊓ y.to_topological_space := rfl @[to_additive] instance : semilattice_inf (group_topology α) := to_topological_space_injective.semilattice_inf _ to_topological_space_inf @[to_additive] instance : inhabited (group_topology α) := ⟨⊤⟩ local notation `cont` := @continuous _ _ /-- Infimum of a collection of group topologies. -/ @[to_additive "Infimum of a collection of additive group topologies"] instance : has_Inf (group_topology α) := { Inf := λ S, ⟨Inf (to_topological_space '' S), topological_group_Inf $ ball_image_iff.2 $ λ t ht, t.2⟩ } @[simp, to_additive] lemma to_topological_space_Inf (s : set (group_topology α)) : (Inf s).to_topological_space = Inf (to_topological_space '' s) := rfl @[simp, to_additive] lemma to_topological_space_infi {ι} (s : ι → group_topology α) : (⨅ i, s i).to_topological_space = ⨅ i, (s i).to_topological_space := congr_arg Inf (range_comp _ _).symm /-- Group topologies on `γ` form a complete lattice, with `⊥` the discrete topology and `⊤` the indiscrete topology. The infimum of a collection of group topologies is the topology generated by all their open sets (which is a group topology). The supremum of two group topologies `s` and `t` is the infimum of the family of all group topologies contained in the intersection of `s` and `t`. -/ @[to_additive "Group topologies on `γ` form a complete lattice, with `⊥` the discrete topology and `⊤` the indiscrete topology. The infimum of a collection of group topologies is the topology generated by all their open sets (which is a group topology). The supremum of two group topologies `s` and `t` is the infimum of the family of all group topologies contained in the intersection of `s` and `t`."] instance : complete_semilattice_Inf (group_topology α) := { Inf_le := λ S a haS, to_topological_space_le.1 $ Inf_le ⟨a, haS, rfl⟩, le_Inf := begin intros S a hab, apply topological_space.complete_lattice.le_Inf, rintros _ ⟨b, hbS, rfl⟩, exact hab b hbS, end, ..group_topology.has_Inf, ..group_topology.partial_order } @[to_additive] instance : complete_lattice (group_topology α) := { inf := (⊓), top := ⊤, bot := ⊥, ..group_topology.bounded_order, ..group_topology.semilattice_inf, ..complete_lattice_of_complete_semilattice_Inf _ } /-- Given `f : α → β` and a topology on `α`, the coinduced group topology on `β` is the finest topology such that `f` is continuous and `β` is a topological group. -/ @[to_additive "Given `f : α → β` and a topology on `α`, the coinduced additive group topology on `β` is the finest topology such that `f` is continuous and `β` is a topological additive group."] def coinduced {α β : Type*} [t : topological_space α] [group β] (f : α → β) : group_topology β := Inf {b : group_topology β | (topological_space.coinduced f t) ≤ b.to_topological_space} @[to_additive] lemma coinduced_continuous {α β : Type*} [t : topological_space α] [group β] (f : α → β) : cont t (coinduced f).to_topological_space f := begin rw [continuous_Inf_rng], rintros _ ⟨t', ht', rfl⟩, exact continuous_iff_coinduced_le.2 ht' end end group_topology
8d9a5ef4a6416e8451b44b85a739857f54f23c62
2a70b774d16dbdf5a533432ee0ebab6838df0948
/_target/deps/mathlib/src/linear_algebra/finite_dimensional.lean
ca5c330cd40eb8cb1fb2521ba32e385b634de2cf
[ "Apache-2.0" ]
permissive
hjvromen/lewis
40b035973df7c77ebf927afab7878c76d05ff758
105b675f73630f028ad5d890897a51b3c1146fb0
refs/heads/master
1,677,944,636,343
1,676,555,301,000
1,676,555,301,000
327,553,599
0
0
null
null
null
null
UTF-8
Lean
false
false
53,733
lean
/- Copyright (c) 2019 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import linear_algebra.dimension import ring_theory.principal_ideal_domain import algebra.algebra.subalgebra /-! # Finite dimensional vector spaces Definition and basic properties of finite dimensional vector spaces, of their dimensions, and of linear maps on such spaces. ## Main definitions Assume `V` is a vector space over a field `K`. There are (at least) three equivalent definitions of finite-dimensionality of `V`: - it admits a finite basis. - it is finitely generated. - it is noetherian, i.e., every subspace is finitely generated. We introduce a typeclass `finite_dimensional K V` capturing this property. For ease of transfer of proof, it is defined using the third point of view, i.e., as `is_noetherian`. However, we prove that all these points of view are equivalent, with the following lemmas (in the namespace `finite_dimensional`): - `exists_is_basis_finite` states that a finite-dimensional vector space has a finite basis - `of_fintype_basis` states that the existence of a basis indexed by a finite type implies finite-dimensionality - `of_finset_basis` states that the existence of a basis indexed by a `finset` implies finite-dimensionality - `of_finite_basis` states that the existence of a basis indexed by a finite set implies finite-dimensionality - `iff_fg` states that the space is finite-dimensional if and only if it is finitely generated Also defined is `findim`, the dimension of a finite dimensional space, returning a `nat`, as opposed to `dim`, which returns a `cardinal`. When the space has infinite dimension, its `findim` is by convention set to `0`. Preservation of finite-dimensionality and formulas for the dimension are given for - submodules - quotients (for the dimension of a quotient, see `findim_quotient_add_findim`) - linear equivs, in `linear_equiv.finite_dimensional` and `linear_equiv.findim_eq` - image under a linear map (the rank-nullity formula is in `findim_range_add_findim_ker`) Basic properties of linear maps of a finite-dimensional vector space are given. Notably, the equivalence of injectivity and surjectivity is proved in `linear_map.injective_iff_surjective`, and the equivalence between left-inverse and right-inverse in `mul_eq_one_comm` and `comp_eq_id_comm`. ## Implementation notes Most results are deduced from the corresponding results for the general dimension (as a cardinal), in `dimension.lean`. Not all results have been ported yet. One of the characterizations of finite-dimensionality is in terms of finite generation. This property is currently defined only for submodules, so we express it through the fact that the maximal submodule (which, as a set, coincides with the whole space) is finitely generated. This is not very convenient to use, although there are some helper functions. However, this becomes very convenient when speaking of submodules which are finite-dimensional, as this notion coincides with the fact that the submodule is finitely generated (as a submodule of the whole space). This equivalence is proved in `submodule.fg_iff_finite_dimensional`. -/ universes u v v' w open_locale classical open vector_space cardinal submodule module function variables {K : Type u} {V : Type v} [field K] [add_comm_group V] [vector_space K V] {V₂ : Type v'} [add_comm_group V₂] [vector_space K V₂] /-- `finite_dimensional` vector spaces are defined to be noetherian modules. Use `finite_dimensional.iff_fg` or `finite_dimensional.of_fintype_basis` to prove finite dimension from a conventional definition. -/ @[reducible] def finite_dimensional (K V : Type*) [field K] [add_comm_group V] [vector_space K V] := is_noetherian K V namespace finite_dimensional open is_noetherian /-- A vector space is finite-dimensional if and only if its dimension (as a cardinal) is strictly less than the first infinite cardinal `omega`. -/ lemma finite_dimensional_iff_dim_lt_omega : finite_dimensional K V ↔ dim K V < omega.{v} := begin cases exists_is_basis K V with b hb, have := is_basis.mk_eq_dim hb, simp only [lift_id] at this, rw [← this, lt_omega_iff_fintype, ← @set.set_of_mem_eq _ b, ← subtype.range_coe_subtype], split, { intro, resetI, convert finite_of_linear_independent hb.1, simp }, { assume hbfinite, refine @is_noetherian_of_linear_equiv K (⊤ : submodule K V) V _ _ _ _ _ (linear_equiv.of_top _ rfl) (id _), refine is_noetherian_of_fg_of_noetherian _ ⟨set.finite.to_finset hbfinite, _⟩, rw [set.finite.coe_to_finset, ← hb.2], refl } end /-- The dimension of a finite-dimensional vector space, as a cardinal, is strictly less than the first infinite cardinal `omega`. -/ lemma dim_lt_omega (K V : Type*) [field K] [add_comm_group V] [vector_space K V] : ∀ [finite_dimensional K V], dim K V < omega.{v} := finite_dimensional_iff_dim_lt_omega.1 /-- In a finite dimensional space, there exists a finite basis. A basis is in general given as a function from an arbitrary type to the vector space. Here, we think of a basis as a set (instead of a function), and use as parametrizing type this set (and as a function the coercion `coe : s → V`). -/ variables (K V) lemma exists_is_basis_finite [finite_dimensional K V] : ∃ s : set V, (is_basis K (coe : s → V)) ∧ s.finite := begin cases exists_is_basis K V with s hs, exact ⟨s, hs, finite_of_linear_independent hs.1⟩ end /-- In a finite dimensional space, there exists a finite basis. Provides the basis as a finset. This is in contrast to `exists_is_basis_finite`, which provides a set and a `set.finite`. -/ lemma exists_is_basis_finset [finite_dimensional K V] : ∃ b : finset V, is_basis K (coe : (↑b : set V) → V) := begin obtain ⟨s, s_basis, s_finite⟩ := exists_is_basis_finite K V, refine ⟨s_finite.to_finset, _⟩, rw set.finite.coe_to_finset, exact s_basis, end /-- A finite dimensional vector space over a finite field is finite -/ noncomputable def fintype_of_fintype [fintype K] [finite_dimensional K V] : fintype V := module.fintype_of_fintype (classical.some_spec (finite_dimensional.exists_is_basis_finset K V) : _) variables {K V} /-- A vector space is finite-dimensional if and only if it is finitely generated. As the finitely-generated property is a property of submodules, we formulate this in terms of the maximal submodule, equal to the whole space as a set by definition.-/ lemma iff_fg : finite_dimensional K V ↔ (⊤ : submodule K V).fg := begin split, { introI h, rcases exists_is_basis_finite K V with ⟨s, s_basis, s_finite⟩, exact ⟨s_finite.to_finset, by { convert s_basis.2, simp }⟩ }, { rintros ⟨s, hs⟩, rw [finite_dimensional_iff_dim_lt_omega, ← dim_top, ← hs], exact lt_of_le_of_lt (dim_span_le _) (lt_omega_iff_finite.2 (set.finite_mem_finset s)) } end /-- If a vector space has a finite basis, then it is finite-dimensional. -/ lemma of_fintype_basis {ι : Type w} [fintype ι] {b : ι → V} (h : is_basis K b) : finite_dimensional K V := iff_fg.2 $ ⟨finset.univ.image b, by {convert h.2, simp} ⟩ /-- If a vector space has a basis indexed by elements of a finite set, then it is finite-dimensional. -/ lemma of_finite_basis {ι} {s : set ι} {b : s → V} (h : is_basis K b) (hs : set.finite s) : finite_dimensional K V := by haveI := hs.fintype; exact of_fintype_basis h /-- If a vector space has a finite basis, then it is finite-dimensional, finset style. -/ lemma of_finset_basis {ι} {s : finset ι} {b : (↑s : set ι) → V} (h : is_basis K b) : finite_dimensional K V := of_finite_basis h s.finite_to_set /-- A subspace of a finite-dimensional space is also finite-dimensional. -/ instance finite_dimensional_submodule [finite_dimensional K V] (S : submodule K V) : finite_dimensional K S := finite_dimensional_iff_dim_lt_omega.2 (lt_of_le_of_lt (dim_submodule_le _) (dim_lt_omega K V)) /-- A quotient of a finite-dimensional space is also finite-dimensional. -/ instance finite_dimensional_quotient [finite_dimensional K V] (S : submodule K V) : finite_dimensional K (quotient S) := finite_dimensional_iff_dim_lt_omega.2 (lt_of_le_of_lt (dim_quotient_le _) (dim_lt_omega K V)) /-- The dimension of a finite-dimensional vector space as a natural number. Defined by convention to be `0` if the space is infinite-dimensional. -/ noncomputable def findim (K V : Type*) [field K] [add_comm_group V] [vector_space K V] : ℕ := if h : dim K V < omega.{v} then classical.some (lt_omega.1 h) else 0 /-- In a finite-dimensional space, its dimension (seen as a cardinal) coincides with its `findim`. -/ lemma findim_eq_dim (K : Type u) (V : Type v) [field K] [add_comm_group V] [vector_space K V] [finite_dimensional K V] : (findim K V : cardinal.{v}) = dim K V := begin have : findim K V = classical.some (lt_omega.1 (dim_lt_omega K V)) := dif_pos (dim_lt_omega K V), rw this, exact (classical.some_spec (lt_omega.1 (dim_lt_omega K V))).symm end lemma findim_of_infinite_dimensional {K V : Type*} [field K] [add_comm_group V] [vector_space K V] (h : ¬finite_dimensional K V) : findim K V = 0 := dif_neg $ mt finite_dimensional_iff_dim_lt_omega.2 h /-- If a vector space has a finite basis, then its dimension (seen as a cardinal) is equal to the cardinality of the basis. -/ lemma dim_eq_card_basis {ι : Type w} [fintype ι] {b : ι → V} (h : is_basis K b) : dim K V = fintype.card ι := by rw [←h.mk_range_eq_dim, cardinal.fintype_card, set.card_range_of_injective h.injective] /-- If a vector space has a finite basis, then its dimension is equal to the cardinality of the basis. -/ lemma findim_eq_card_basis {ι : Type w} [fintype ι] {b : ι → V} (h : is_basis K b) : findim K V = fintype.card ι := begin haveI : finite_dimensional K V := of_fintype_basis h, have := dim_eq_card_basis h, rw ← findim_eq_dim at this, exact_mod_cast this end /-- If a vector space is finite-dimensional, then the cardinality of any basis is equal to its `findim`. -/ lemma findim_eq_card_basis' [finite_dimensional K V] {ι : Type w} {b : ι → V} (h : is_basis K b) : (findim K V : cardinal.{w}) = cardinal.mk ι := begin rcases exists_is_basis_finite K V with ⟨s, s_basis, s_finite⟩, letI: fintype s := s_finite.fintype, have A : cardinal.mk s = fintype.card s := fintype_card _, have B : findim K V = fintype.card s := findim_eq_card_basis s_basis, have C : cardinal.lift.{w v} (cardinal.mk ι) = cardinal.lift.{v w} (cardinal.mk s) := mk_eq_mk_of_basis h s_basis, rw [A, ← B, lift_nat_cast] at C, have : cardinal.lift.{w v} (cardinal.mk ι) = cardinal.lift.{w v} (findim K V), by { simp, exact C }, exact (lift_inj.mp this).symm end /-- If a vector space has a finite basis, then its dimension is equal to the cardinality of the basis. This lemma uses a `finset` instead of indexed types. -/ lemma findim_eq_card_finset_basis {b : finset V} (h : is_basis K (subtype.val : (↑b : set V) -> V)) : findim K V = finset.card b := by { rw [findim_eq_card_basis h, fintype.subtype_card], intros x, refl } lemma equiv_fin {ι : Type*} [finite_dimensional K V] {v : ι → V} (hv : is_basis K v) : ∃ g : fin (findim K V) ≃ ι, is_basis K (v ∘ g) := begin have : (cardinal.mk (fin $ findim K V)).lift = (cardinal.mk ι).lift, { simp [cardinal.mk_fin (findim K V), ← findim_eq_card_basis' hv] }, rcases cardinal.lift_mk_eq.mp this with ⟨g⟩, exact ⟨g, hv.comp _ g.bijective⟩ end variables (K V) lemma fin_basis [finite_dimensional K V] : ∃ v : fin (findim K V) → V, is_basis K v := let ⟨B, hB, B_fin⟩ := exists_is_basis_finite K V, ⟨g, hg⟩ := finite_dimensional.equiv_fin hB in ⟨coe ∘ g, hg⟩ variables {K V} lemma cardinal_mk_le_findim_of_linear_independent [finite_dimensional K V] {ι : Type w} {b : ι → V} (h : linear_independent K b) : cardinal.mk ι ≤ findim K V := begin rw ← lift_le.{_ (max v w)}, simpa [← findim_eq_dim K V] using cardinal_lift_le_dim_of_linear_independent.{_ _ _ (max v w)} h end lemma fintype_card_le_findim_of_linear_independent [finite_dimensional K V] {ι : Type*} [fintype ι] {b : ι → V} (h : linear_independent K b) : fintype.card ι ≤ findim K V := by simpa [fintype_card] using cardinal_mk_le_findim_of_linear_independent h lemma finset_card_le_findim_of_linear_independent [finite_dimensional K V] {b : finset V} (h : linear_independent K (λ x, x : (↑b : set V) → V)) : b.card ≤ findim K V := begin rw ←fintype.card_coe, exact fintype_card_le_findim_of_linear_independent h, end lemma lt_omega_of_linear_independent {ι : Type w} [finite_dimensional K V] {v : ι → V} (h : linear_independent K v) : cardinal.mk ι < cardinal.omega := begin apply cardinal.lift_lt.1, apply lt_of_le_of_lt, apply linear_independent_le_dim h, rw [←findim_eq_dim, cardinal.lift_omega, cardinal.lift_nat_cast], apply cardinal.nat_lt_omega, end lemma not_linear_independent_of_infinite {ι : Type w} [inf : infinite ι] [finite_dimensional K V] (v : ι → V) : ¬ linear_independent K v := begin intro h_lin_indep, have : ¬ omega ≤ mk ι := not_le.mpr (lt_omega_of_linear_independent h_lin_indep), have : omega ≤ mk ι := infinite_iff.mp inf, contradiction end /-- A finite dimensional space has positive `findim` iff it has a nonzero element. -/ lemma findim_pos_iff_exists_ne_zero [finite_dimensional K V] : 0 < findim K V ↔ ∃ x : V, x ≠ 0 := iff.trans (by { rw ← findim_eq_dim, norm_cast }) (@dim_pos_iff_exists_ne_zero K V _ _ _) /-- A finite dimensional space has positive `findim` iff it is nontrivial. -/ lemma findim_pos_iff [finite_dimensional K V] : 0 < findim K V ↔ nontrivial V := iff.trans (by { rw ← findim_eq_dim, norm_cast }) (@dim_pos_iff_nontrivial K V _ _ _) /-- A nontrivial finite dimensional space has positive `findim`. -/ lemma findim_pos [finite_dimensional K V] [h : nontrivial V] : 0 < findim K V := findim_pos_iff.mpr h section open_locale big_operators open finset /-- If a finset has cardinality larger than the dimension of the space, then there is a nontrivial linear relation amongst its elements. -/ lemma exists_nontrivial_relation_of_dim_lt_card [finite_dimensional K V] {t : finset V} (h : findim K V < t.card) : ∃ f : V → K, ∑ e in t, f e • e = 0 ∧ ∃ x ∈ t, f x ≠ 0 := begin have := mt finset_card_le_findim_of_linear_independent (by { simpa using h }), rw linear_dependent_iff at this, obtain ⟨s, g, sum, z, zm, nonzero⟩ := this, -- Now we have to extend `g` to all of `t`, then to all of `V`. let f : V → K := λ x, if h : x ∈ t then if (⟨x, h⟩ : (↑t : set V)) ∈ s then g ⟨x, h⟩ else 0 else 0, -- and finally clean up the mess caused by the extension. refine ⟨f, _, _⟩, { dsimp [f], rw ← sum, fapply sum_bij_ne_zero (λ v hvt _, (⟨v, hvt⟩ : {v // v ∈ t})), { intros v hvt H, dsimp, rw [dif_pos hvt] at H, contrapose! H, rw [if_neg H, zero_smul], }, { intros _ _ _ _ _ _, exact subtype.mk.inj, }, { intros b hbs hb, use b, simpa only [hbs, exists_prop, dif_pos, finset.mk_coe, and_true, if_true, finset.coe_mem, eq_self_iff_true, exists_prop_of_true, ne.def] using hb, }, { intros a h₁, dsimp, rw [dif_pos h₁], intro h₂, rw [if_pos], contrapose! h₂, rw [if_neg h₂, zero_smul], }, }, { refine ⟨z, z.2, _⟩, dsimp only [f], erw [dif_pos z.2, if_pos]; rwa [subtype.coe_eta] }, end /-- If a finset has cardinality larger than `findim + 1`, then there is a nontrivial linear relation amongst its elements, such that the coefficients of the relation sum to zero. -/ lemma exists_nontrivial_relation_sum_zero_of_dim_succ_lt_card [finite_dimensional K V] {t : finset V} (h : findim K V + 1 < t.card) : ∃ f : V → K, ∑ e in t, f e • e = 0 ∧ ∑ e in t, f e = 0 ∧ ∃ x ∈ t, f x ≠ 0 := begin -- Pick an element x₀ ∈ t, have card_pos : 0 < t.card := lt_trans (nat.succ_pos _) h, obtain ⟨x₀, m⟩ := (finset.card_pos.1 card_pos).bex, -- and apply the previous lemma to the {xᵢ - x₀} let shift : V ↪ V := ⟨λ x, x - x₀, sub_left_injective⟩, let t' := (t.erase x₀).map shift, have h' : findim K V < t'.card, { simp only [t', card_map, finset.card_erase_of_mem m], exact nat.lt_pred_iff.mpr h, }, -- to obtain a function `g`. obtain ⟨g, gsum, x₁, x₁_mem, nz⟩ := exists_nontrivial_relation_of_dim_lt_card h', -- Then obtain `f` by translating back by `x₀`, -- and setting the value of `f` at `x₀` to ensure `∑ e in t, f e = 0`. let f : V → K := λ z, if z = x₀ then - ∑ z in (t.erase x₀), g (z - x₀) else g (z - x₀), refine ⟨f, _ ,_ ,_⟩, -- After this, it's a matter of verifiying the properties, -- based on the corresponding properties for `g`. { show ∑ (e : V) in t, f e • e = 0, -- We prove this by splitting off the `x₀` term of the sum, -- which is itself a sum over `t.erase x₀`, -- combining the two sums, and -- observing that after reindexing we have exactly -- ∑ (x : V) in t', g x • x = 0. simp only [f], conv_lhs { apply_congr, skip, rw [ite_smul], }, rw [finset.sum_ite], conv { congr, congr, apply_congr, simp [filter_eq', m], }, conv { congr, congr, skip, apply_congr, simp [filter_ne'], }, rw [sum_singleton, neg_smul, add_comm, ←sub_eq_add_neg, sum_smul, ←sum_sub_distrib], simp only [←smul_sub], -- At the end we have to reindex the sum, so we use `change` to -- express the summand using `shift`. change (∑ (x : V) in t.erase x₀, (λ e, g e • e) (shift x)) = 0, rw ←sum_map _ shift, exact gsum, }, { show ∑ (e : V) in t, f e = 0, -- Again we split off the `x₀` term, -- observing that it exactly cancels the other terms. rw [← insert_erase m, sum_insert (not_mem_erase x₀ t)], dsimp [f], rw [if_pos rfl], conv_lhs { congr, skip, apply_congr, skip, rw if_neg (show x ≠ x₀, from (mem_erase.mp H).1), }, exact neg_add_self _, }, { show ∃ (x : V) (H : x ∈ t), f x ≠ 0, -- We can use x₁ + x₀. refine ⟨x₁ + x₀, _, _⟩, { rw finset.mem_map at x₁_mem, rcases x₁_mem with ⟨x₁, x₁_mem, rfl⟩, rw mem_erase at x₁_mem, simp only [x₁_mem, sub_add_cancel, function.embedding.coe_fn_mk], }, { dsimp only [f], rwa [if_neg, add_sub_cancel], rw [add_left_eq_self], rintro rfl, simpa only [sub_eq_zero, exists_prop, finset.mem_map, embedding.coe_fn_mk, eq_self_iff_true, mem_erase, not_true, exists_eq_right, ne.def, false_and] using x₁_mem, } }, end section variables {L : Type*} [linear_ordered_field L] variables {W : Type v} [add_comm_group W] [vector_space L W] /-- A slight strengthening of `exists_nontrivial_relation_sum_zero_of_dim_succ_lt_card` available when working over an ordered field: we can ensure a positive coefficient, not just a nonzero coefficient. -/ lemma exists_relation_sum_zero_pos_coefficient_of_dim_succ_lt_card [finite_dimensional L W] {t : finset W} (h : findim L W + 1 < t.card) : ∃ f : W → L, ∑ e in t, f e • e = 0 ∧ ∑ e in t, f e = 0 ∧ ∃ x ∈ t, 0 < f x := begin obtain ⟨f, sum, total, nonzero⟩ := exists_nontrivial_relation_sum_zero_of_dim_succ_lt_card h, exact ⟨f, sum, total, exists_pos_of_sum_zero_of_exists_nonzero f total nonzero⟩, end end end /-- If a submodule has maximal dimension in a finite dimensional space, then it is equal to the whole space. -/ lemma eq_top_of_findim_eq [finite_dimensional K V] {S : submodule K V} (h : findim K S = findim K V) : S = ⊤ := begin cases exists_is_basis K S with bS hbS, have : linear_independent K (subtype.val : (subtype.val '' bS : set V) → V), from @linear_independent.image_subtype _ _ _ _ _ _ _ _ _ (submodule.subtype S) hbS.1 (by simp), cases exists_subset_is_basis this with b hb, letI : fintype b := classical.choice (finite_of_linear_independent hb.2.1), letI : fintype (subtype.val '' bS) := classical.choice (finite_of_linear_independent this), letI : fintype bS := classical.choice (finite_of_linear_independent hbS.1), have : subtype.val '' bS = b, from set.eq_of_subset_of_card_le hb.1 (by rw [set.card_image_of_injective _ subtype.val_injective, ← findim_eq_card_basis hbS, ← findim_eq_card_basis hb.2, h]; apply_instance), erw [← hb.2.2, subtype.range_coe, ← this, ← subtype_eq_val, span_image], have := hbS.2, erw [subtype.range_coe] at this, rw [this, map_top (submodule.subtype S), range_subtype], end variable (K) /-- A field is one-dimensional as a vector space over itself. -/ @[simp] lemma findim_of_field : findim K K = 1 := begin have := dim_of_field K, rw [← findim_eq_dim] at this, exact_mod_cast this end /-- The vector space of functions on a fintype has finite dimension. -/ instance finite_dimensional_fintype_fun {ι : Type*} [fintype ι] : finite_dimensional K (ι → K) := by { rw [finite_dimensional_iff_dim_lt_omega, dim_fun'], exact nat_lt_omega _ } /-- The vector space of functions on a fintype ι has findim equal to the cardinality of ι. -/ @[simp] lemma findim_fintype_fun_eq_card {ι : Type v} [fintype ι] : findim K (ι → K) = fintype.card ι := begin have : vector_space.dim K (ι → K) = fintype.card ι := dim_fun', rwa [← findim_eq_dim, nat_cast_inj] at this, end /-- The vector space of functions on `fin n` has findim equal to `n`. -/ @[simp] lemma findim_fin_fun {n : ℕ} : findim K (fin n → K) = n := by simp /-- The submodule generated by a finite set is finite-dimensional. -/ theorem span_of_finite {A : set V} (hA : set.finite A) : finite_dimensional K (submodule.span K A) := is_noetherian_span_of_finite K hA /-- The submodule generated by a single element is finite-dimensional. -/ instance (x : V) : finite_dimensional K (K ∙ x) := by {apply span_of_finite, simp} end finite_dimensional section zero_dim open vector_space finite_dimensional lemma finite_dimensional_of_dim_eq_zero (h : vector_space.dim K V = 0) : finite_dimensional K V := by rw [finite_dimensional_iff_dim_lt_omega, h]; exact cardinal.omega_pos lemma finite_dimensional_of_dim_eq_one (h : vector_space.dim K V = 1) : finite_dimensional K V := by rw [finite_dimensional_iff_dim_lt_omega, h]; exact one_lt_omega lemma findim_eq_zero_of_dim_eq_zero [finite_dimensional K V] (h : vector_space.dim K V = 0) : findim K V = 0 := begin convert findim_eq_dim K V, rw h, norm_cast end variables (K V) lemma finite_dimensional_bot : finite_dimensional K (⊥ : submodule K V) := finite_dimensional_of_dim_eq_zero $ by simp @[simp] lemma findim_bot : findim K (⊥ : submodule K V) = 0 := begin haveI := finite_dimensional_bot K V, convert findim_eq_dim K (⊥ : submodule K V), rw dim_bot, norm_cast end variables {K V} lemma bot_eq_top_of_dim_eq_zero (h : vector_space.dim K V = 0) : (⊥ : submodule K V) = ⊤ := begin haveI := finite_dimensional_of_dim_eq_zero h, apply eq_top_of_findim_eq, rw [findim_bot, findim_eq_zero_of_dim_eq_zero h] end @[simp] theorem dim_eq_zero {S : submodule K V} : dim K S = 0 ↔ S = ⊥ := ⟨λ h, (submodule.eq_bot_iff _).2 $ λ x hx, congr_arg subtype.val $ ((submodule.eq_bot_iff _).1 $ eq.symm $ bot_eq_top_of_dim_eq_zero h) ⟨x, hx⟩ submodule.mem_top, λ h, by rw [h, dim_bot]⟩ @[simp] theorem findim_eq_zero {S : submodule K V} [finite_dimensional K S] : findim K S = 0 ↔ S = ⊥ := by rw [← dim_eq_zero, ← findim_eq_dim, ← @nat.cast_zero cardinal, cardinal.nat_cast_inj] end zero_dim namespace submodule open finite_dimensional /-- A submodule is finitely generated if and only if it is finite-dimensional -/ theorem fg_iff_finite_dimensional (s : submodule K V) : s.fg ↔ finite_dimensional K s := ⟨λh, is_noetherian_of_fg_of_noetherian s h, λh, by { rw ← map_subtype_top s, exact fg_map (iff_fg.1 h) }⟩ /-- A submodule contained in a finite-dimensional submodule is finite-dimensional. -/ lemma finite_dimensional_of_le {S₁ S₂ : submodule K V} [finite_dimensional K S₂] (h : S₁ ≤ S₂) : finite_dimensional K S₁ := finite_dimensional_iff_dim_lt_omega.2 (lt_of_le_of_lt (dim_le_of_submodule _ _ h) (dim_lt_omega K S₂)) /-- The inf of two submodules, the first finite-dimensional, is finite-dimensional. -/ instance finite_dimensional_inf_left (S₁ S₂ : submodule K V) [finite_dimensional K S₁] : finite_dimensional K (S₁ ⊓ S₂ : submodule K V) := finite_dimensional_of_le inf_le_left /-- The inf of two submodules, the second finite-dimensional, is finite-dimensional. -/ instance finite_dimensional_inf_right (S₁ S₂ : submodule K V) [finite_dimensional K S₂] : finite_dimensional K (S₁ ⊓ S₂ : submodule K V) := finite_dimensional_of_le inf_le_right /-- The sup of two finite-dimensional submodules is finite-dimensional. -/ instance finite_dimensional_sup (S₁ S₂ : submodule K V) [h₁ : finite_dimensional K S₁] [h₂ : finite_dimensional K S₂] : finite_dimensional K (S₁ ⊔ S₂ : submodule K V) := begin rw ←submodule.fg_iff_finite_dimensional at *, exact submodule.fg_sup h₁ h₂ end /-- In a finite-dimensional vector space, the dimensions of a submodule and of the corresponding quotient add up to the dimension of the space. -/ theorem findim_quotient_add_findim [finite_dimensional K V] (s : submodule K V) : findim K s.quotient + findim K s = findim K V := begin have := dim_quotient_add_dim s, rw [← findim_eq_dim, ← findim_eq_dim, ← findim_eq_dim] at this, exact_mod_cast this end /-- The dimension of a submodule is bounded by the dimension of the ambient space. -/ lemma findim_le [finite_dimensional K V] (s : submodule K V) : findim K s ≤ findim K V := by { rw ← s.findim_quotient_add_findim, exact nat.le_add_left _ _ } /-- The dimension of a strict submodule is strictly bounded by the dimension of the ambient space. -/ lemma findim_lt [finite_dimensional K V] {s : submodule K V} (h : s < ⊤) : findim K s < findim K V := begin rw [← s.findim_quotient_add_findim, add_comm], exact nat.lt_add_of_zero_lt_left _ _ (findim_pos_iff.mpr (quotient.nontrivial_of_lt_top _ h)) end /-- The dimension of a quotient is bounded by the dimension of the ambient space. -/ lemma findim_quotient_le [finite_dimensional K V] (s : submodule K V) : findim K s.quotient ≤ findim K V := by { rw ← s.findim_quotient_add_findim, exact nat.le_add_right _ _ } /-- The sum of the dimensions of s + t and s ∩ t is the sum of the dimensions of s and t -/ theorem dim_sup_add_dim_inf_eq (s t : submodule K V) [finite_dimensional K s] [finite_dimensional K t] : findim K ↥(s ⊔ t) + findim K ↥(s ⊓ t) = findim K ↥s + findim K ↥t := begin have key : dim K ↥(s ⊔ t) + dim K ↥(s ⊓ t) = dim K s + dim K t := dim_sup_add_dim_inf_eq s t, repeat { rw ←findim_eq_dim at key }, norm_cast at key, exact key end lemma eq_top_of_disjoint [finite_dimensional K V] (s t : submodule K V) (hdim : findim K s + findim K t = findim K V) (hdisjoint : disjoint s t) : s ⊔ t = ⊤ := begin have h_findim_inf : findim K ↥(s ⊓ t) = 0, { rw [disjoint, le_bot_iff] at hdisjoint, rw [hdisjoint, findim_bot] }, apply eq_top_of_findim_eq, rw ←hdim, convert s.dim_sup_add_dim_inf_eq t, rw h_findim_inf, refl, end end submodule namespace linear_equiv open finite_dimensional /-- Finite dimensionality is preserved under linear equivalence. -/ protected theorem finite_dimensional (f : V ≃ₗ[K] V₂) [finite_dimensional K V] : finite_dimensional K V₂ := is_noetherian_of_linear_equiv f /-- The dimension of a finite dimensional space is preserved under linear equivalence. -/ theorem findim_eq (f : V ≃ₗ[K] V₂) [finite_dimensional K V] : findim K V = findim K V₂ := begin haveI : finite_dimensional K V₂ := f.finite_dimensional, simpa [← findim_eq_dim] using f.lift_dim_eq end end linear_equiv namespace finite_dimensional /-- Two finite-dimensional vector spaces are isomorphic if they have the same (finite) dimension. -/ theorem nonempty_linear_equiv_of_findim_eq [finite_dimensional K V] [finite_dimensional K V₂] (cond : findim K V = findim K V₂) : nonempty (V ≃ₗ[K] V₂) := nonempty_linear_equiv_of_lift_dim_eq $ by simp only [← findim_eq_dim, cond, lift_nat_cast] /-- Two finite-dimensional vector spaces are isomorphic if and only if they have the same (finite) dimension. -/ theorem nonempty_linear_equiv_iff_findim_eq [finite_dimensional K V] [finite_dimensional K V₂] : nonempty (V ≃ₗ[K] V₂) ↔ findim K V = findim K V₂ := ⟨λ ⟨h⟩, h.findim_eq, λ h, nonempty_linear_equiv_of_findim_eq h⟩ section variables (V V₂) /-- Two finite-dimensional vector spaces are isomorphic if they have the same (finite) dimension. -/ noncomputable def linear_equiv.of_findim_eq [finite_dimensional K V] [finite_dimensional K V₂] (cond : findim K V = findim K V₂) : V ≃ₗ[K] V₂ := classical.choice $ nonempty_linear_equiv_of_findim_eq cond end lemma eq_of_le_of_findim_le {S₁ S₂ : submodule K V} [finite_dimensional K S₂] (hle : S₁ ≤ S₂) (hd : findim K S₂ ≤ findim K S₁) : S₁ = S₂ := begin rw ←linear_equiv.findim_eq (submodule.comap_subtype_equiv_of_le hle) at hd, exact le_antisymm hle (submodule.comap_subtype_eq_top.1 (eq_top_of_findim_eq (le_antisymm (comap (submodule.subtype S₂) S₁).findim_le hd))), end /-- If a submodule is less than or equal to a finite-dimensional submodule with the same dimension, they are equal. -/ lemma eq_of_le_of_findim_eq {S₁ S₂ : submodule K V} [finite_dimensional K S₂] (hle : S₁ ≤ S₂) (hd : findim K S₁ = findim K S₂) : S₁ = S₂ := eq_of_le_of_findim_le hle hd.ge end finite_dimensional namespace linear_map open finite_dimensional /-- On a finite-dimensional space, an injective linear map is surjective. -/ lemma surjective_of_injective [finite_dimensional K V] {f : V →ₗ[K] V} (hinj : injective f) : surjective f := begin have h := dim_eq_of_injective _ hinj, rw [← findim_eq_dim, ← findim_eq_dim, nat_cast_inj] at h, exact range_eq_top.1 (eq_top_of_findim_eq h.symm) end /-- On a finite-dimensional space, a linear map is injective if and only if it is surjective. -/ lemma injective_iff_surjective [finite_dimensional K V] {f : V →ₗ[K] V} : injective f ↔ surjective f := ⟨surjective_of_injective, λ hsurj, let ⟨g, hg⟩ := f.exists_right_inverse_of_surjective (range_eq_top.2 hsurj) in have function.right_inverse g f, from linear_map.ext_iff.1 hg, (left_inverse_of_surjective_of_right_inverse (surjective_of_injective this.injective) this).injective⟩ lemma ker_eq_bot_iff_range_eq_top [finite_dimensional K V] {f : V →ₗ[K] V} : f.ker = ⊥ ↔ f.range = ⊤ := by rw [range_eq_top, ker_eq_bot, injective_iff_surjective] /-- In a finite-dimensional space, if linear maps are inverse to each other on one side then they are also inverse to each other on the other side. -/ lemma mul_eq_one_of_mul_eq_one [finite_dimensional K V] {f g : V →ₗ[K] V} (hfg : f * g = 1) : g * f = 1 := have ginj : injective g, from has_left_inverse.injective ⟨f, (λ x, show (f * g) x = (1 : V →ₗ[K] V) x, by rw hfg; refl)⟩, let ⟨i, hi⟩ := g.exists_right_inverse_of_surjective (range_eq_top.2 (injective_iff_surjective.1 ginj)) in have f * (g * i) = f * 1, from congr_arg _ hi, by rw [← mul_assoc, hfg, one_mul, mul_one] at this; rwa ← this /-- In a finite-dimensional space, linear maps are inverse to each other on one side if and only if they are inverse to each other on the other side. -/ lemma mul_eq_one_comm [finite_dimensional K V] {f g : V →ₗ[K] V} : f * g = 1 ↔ g * f = 1 := ⟨mul_eq_one_of_mul_eq_one, mul_eq_one_of_mul_eq_one⟩ /-- In a finite-dimensional space, linear maps are inverse to each other on one side if and only if they are inverse to each other on the other side. -/ lemma comp_eq_id_comm [finite_dimensional K V] {f g : V →ₗ[K] V} : f.comp g = id ↔ g.comp f = id := mul_eq_one_comm /-- The image under an onto linear map of a finite-dimensional space is also finite-dimensional. -/ lemma finite_dimensional_of_surjective [h : finite_dimensional K V] (f : V →ₗ[K] V₂) (hf : f.range = ⊤) : finite_dimensional K V₂ := is_noetherian_of_surjective V f hf /-- The range of a linear map defined on a finite-dimensional space is also finite-dimensional. -/ instance finite_dimensional_range [h : finite_dimensional K V] (f : V →ₗ[K] V₂) : finite_dimensional K f.range := f.quot_ker_equiv_range.finite_dimensional /-- rank-nullity theorem : the dimensions of the kernel and the range of a linear map add up to the dimension of the source space. -/ theorem findim_range_add_findim_ker [finite_dimensional K V] (f : V →ₗ[K] V₂) : findim K f.range + findim K f.ker = findim K V := by { rw [← f.quot_ker_equiv_range.findim_eq], exact submodule.findim_quotient_add_findim _ } end linear_map namespace linear_equiv open finite_dimensional variables [finite_dimensional K V] /-- The linear equivalence corresponging to an injective endomorphism. -/ noncomputable def of_injective_endo (f : V →ₗ[K] V) (h_inj : f.ker = ⊥) : V ≃ₗ[K] V := (linear_equiv.of_injective f h_inj).trans (linear_equiv.of_top _ (linear_map.ker_eq_bot_iff_range_eq_top.1 h_inj)) lemma of_injective_endo_to_fun (f : V →ₗ[K] V) (h_inj : f.ker = ⊥) : (of_injective_endo f h_inj).to_fun = f := rfl lemma of_injective_endo_right_inv (f : V →ₗ[K] V) (h_inj : f.ker = ⊥) : f * (of_injective_endo f h_inj).symm = 1 := begin ext, simp only [linear_map.one_app, linear_map.mul_app], change f ((of_injective_endo f h_inj).symm x) = x, rw ← linear_equiv.inv_fun_apply (of_injective_endo f h_inj), apply (of_injective_endo f h_inj).right_inv, end lemma of_injective_endo_left_inv (f : V →ₗ[K] V) (h_inj : f.ker = ⊥) : ((of_injective_endo f h_inj).symm : V →ₗ[K] V) * f = 1 := begin ext, simp only [linear_map.one_app, linear_map.mul_app], change (of_injective_endo f h_inj).symm (f x) = x, rw ← linear_equiv.inv_fun_apply (of_injective_endo f h_inj), apply (of_injective_endo f h_inj).left_inv, end end linear_equiv namespace linear_map lemma is_unit_iff [finite_dimensional K V] (f : V →ₗ[K] V): is_unit f ↔ f.ker = ⊥ := begin split, { intro h_is_unit, rcases h_is_unit with ⟨u, hu⟩, rw [←hu, linear_map.ker_eq_bot'], intros x hx, change (1 : V →ₗ[K] V) x = 0, rw ← u.inv_val, change u.inv (u x) = 0, simp [hx] }, { intro h_inj, use ⟨f, (linear_equiv.of_injective_endo f h_inj).symm.to_linear_map, linear_equiv.of_injective_endo_right_inv f h_inj, linear_equiv.of_injective_endo_left_inv f h_inj⟩, refl } end end linear_map open vector_space finite_dimensional section top @[simp] theorem findim_top : findim K (⊤ : submodule K V) = findim K V := by { unfold findim, simp [dim_top] } end top namespace linear_map theorem injective_iff_surjective_of_findim_eq_findim [finite_dimensional K V] [finite_dimensional K V₂] (H : findim K V = findim K V₂) {f : V →ₗ[K] V₂} : function.injective f ↔ function.surjective f := begin have := findim_range_add_findim_ker f, rw [← ker_eq_bot, ← range_eq_top], refine ⟨λ h, _, λ h, _⟩, { rw [h, findim_bot, add_zero, H] at this, exact eq_top_of_findim_eq this }, { rw [h, findim_top, H] at this, exact findim_eq_zero.1 (add_right_injective _ this) } end theorem findim_le_findim_of_injective [finite_dimensional K V] [finite_dimensional K V₂] {f : V →ₗ[K] V₂} (hf : function.injective f) : findim K V ≤ findim K V₂ := calc findim K V = findim K f.range + findim K f.ker : (findim_range_add_findim_ker f).symm ... = findim K f.range : by rw [ker_eq_bot.2 hf, findim_bot, add_zero] ... ≤ findim K V₂ : submodule.findim_le _ end linear_map namespace alg_hom lemma bijective {F : Type*} [field F] {E : Type*} [field E] [algebra F E] [finite_dimensional F E] (ϕ : E →ₐ[F] E) : function.bijective ϕ := have inj : function.injective ϕ.to_linear_map := ϕ.to_ring_hom.injective, ⟨inj, (linear_map.injective_iff_surjective_of_findim_eq_findim rfl).mp inj⟩ end alg_hom /-- Bijection between algebra equivalences and algebra homomorphisms -/ noncomputable def alg_equiv_equiv_alg_hom (F : Type u) [field F] (E : Type v) [field E] [algebra F E] [finite_dimensional F E] : (E ≃ₐ[F] E) ≃ (E →ₐ[F] E) := { to_fun := λ ϕ, ϕ.to_alg_hom, inv_fun := λ ϕ, alg_equiv.of_bijective ϕ ϕ.bijective, left_inv := λ _, by {ext, refl}, right_inv := λ _, by {ext, refl} } section /-- An integral domain that is module-finite as an algebra over a field is a field. -/ noncomputable def field_of_finite_dimensional (F K : Type*) [field F] [integral_domain K] [algebra F K] [finite_dimensional F K] : field K := { inv := λ x, if H : x = 0 then 0 else classical.some $ (show function.surjective (algebra.lmul_left F x), from linear_map.injective_iff_surjective.1 $ λ _ _, (mul_right_inj' H).1) 1, mul_inv_cancel := λ x hx, show x * dite _ _ _ = _, by { rw dif_neg hx, exact classical.some_spec ((show function.surjective (algebra.lmul_left F x), from linear_map.injective_iff_surjective.1 $ λ _ _, (mul_right_inj' hx).1) 1) }, inv_zero := dif_pos rfl, .. ‹integral_domain K› } end namespace submodule lemma findim_mono [finite_dimensional K V] : monotone (λ (s : submodule K V), findim K s) := λ s t hst, calc findim K s = findim K (comap t.subtype s) : linear_equiv.findim_eq (comap_subtype_equiv_of_le hst).symm ... ≤ findim K t : submodule.findim_le _ lemma lt_of_le_of_findim_lt_findim {s t : submodule K V} (le : s ≤ t) (lt : findim K s < findim K t) : s < t := lt_of_le_of_ne le (λ h, ne_of_lt lt (by rw h)) lemma lt_top_of_findim_lt_findim {s : submodule K V} (lt : findim K s < findim K V) : s < ⊤ := begin by_cases fin : (finite_dimensional K V), { haveI := fin, rw ← @findim_top K V at lt, exact lt_of_le_of_findim_lt_findim le_top lt }, { exfalso, have : findim K V = 0 := dif_neg (mt finite_dimensional_iff_dim_lt_omega.mpr fin), rw this at lt, exact nat.not_lt_zero _ lt } end lemma findim_lt_findim_of_lt [finite_dimensional K V] {s t : submodule K V} (hst : s < t) : findim K s < findim K t := begin rw linear_equiv.findim_eq (comap_subtype_equiv_of_le (le_of_lt hst)).symm, refine findim_lt (lt_of_le_of_ne le_top _), intro h_eq_top, rw comap_subtype_eq_top at h_eq_top, apply not_le_of_lt hst h_eq_top, end end submodule section span open submodule lemma findim_span_le_card (s : set V) [fin : fintype s] : findim K (span K s) ≤ s.to_finset.card := begin haveI := span_of_finite K ⟨fin⟩, have : dim K (span K s) ≤ (mk s : cardinal) := dim_span_le s, rw [←findim_eq_dim, cardinal.fintype_card, ←set.to_finset_card] at this, exact_mod_cast this end lemma findim_span_eq_card {ι : Type*} [fintype ι] {b : ι → V} (hb : linear_independent K b) : findim K (span K (set.range b)) = fintype.card ι := begin haveI : finite_dimensional K (span K (set.range b)) := span_of_finite K (set.finite_range b), have : dim K (span K (set.range b)) = (mk (set.range b) : cardinal) := dim_span hb, rwa [←findim_eq_dim, ←lift_inj, mk_range_eq_of_injective hb.injective, cardinal.fintype_card, lift_nat_cast, lift_nat_cast, nat_cast_inj] at this, end lemma findim_span_set_eq_card (s : set V) [fin : fintype s] (hs : linear_independent K (coe : s → V)) : findim K (span K s) = s.to_finset.card := begin haveI := span_of_finite K ⟨fin⟩, have : dim K (span K s) = (mk s : cardinal) := dim_span_set hs, rw [←findim_eq_dim, cardinal.fintype_card, ←set.to_finset_card] at this, exact_mod_cast this end lemma span_lt_of_subset_of_card_lt_findim {s : set V} [fintype s] {t : submodule K V} (subset : s ⊆ t) (card_lt : s.to_finset.card < findim K t) : span K s < t := lt_of_le_of_findim_lt_findim (span_le.mpr subset) (lt_of_le_of_lt (findim_span_le_card _) card_lt) lemma span_lt_top_of_card_lt_findim {s : set V} [fintype s] (card_lt : s.to_finset.card < findim K V) : span K s < ⊤ := lt_top_of_findim_lt_findim (lt_of_le_of_lt (findim_span_le_card _) card_lt) lemma findim_span_singleton {v : V} (hv : v ≠ 0) : findim K (K ∙ v) = 1 := begin apply le_antisymm, { exact findim_span_le_card ({v} : set V) }, { rw [nat.succ_le_iff, findim_pos_iff], use [⟨v, mem_span_singleton_self v⟩, 0], simp [hv] } end end span section is_basis lemma linear_independent_of_span_eq_top_of_card_eq_findim {ι : Type*} [fintype ι] {b : ι → V} (span_eq : span K (set.range b) = ⊤) (card_eq : fintype.card ι = findim K V) : linear_independent K b := linear_independent_iff'.mpr $ λ s g dependent i i_mem_s, begin by_contra gx_ne_zero, -- We'll derive a contradiction by showing `b '' (univ \ {i})` of cardinality `n - 1` -- spans a vector space of dimension `n`. refine ne_of_lt (span_lt_top_of_card_lt_findim (show (b '' (set.univ \ {i})).to_finset.card < findim K V, from _)) _, { calc (b '' (set.univ \ {i})).to_finset.card = ((set.univ \ {i}).to_finset.image b).card : by rw [set.to_finset_card, fintype.card_of_finset] ... ≤ (set.univ \ {i}).to_finset.card : finset.card_image_le ... = (finset.univ.erase i).card : congr_arg finset.card (finset.ext (by simp [and_comm])) ... < finset.univ.card : finset.card_erase_lt_of_mem (finset.mem_univ i) ... = findim K V : card_eq }, -- We already have that `b '' univ` spans the whole space, -- so we only need to show that the span of `b '' (univ \ {i})` contains each `b j`. refine trans (le_antisymm (span_mono (set.image_subset_range _ _)) (span_le.mpr _)) span_eq, rintros _ ⟨j, rfl, rfl⟩, -- The case that `j ≠ i` is easy because `b j ∈ b '' (univ \ {i})`. by_cases j_eq : j = i, swap, { refine subset_span ⟨j, (set.mem_diff _).mpr ⟨set.mem_univ _, _⟩, rfl⟩, exact mt set.mem_singleton_iff.mp j_eq }, -- To show `b i ∈ span (b '' (univ \ {i}))`, we use that it's a weighted sum -- of the other `b j`s. rw [j_eq, mem_coe, show b i = -((g i)⁻¹ • (s.erase i).sum (λ j, g j • b j)), from _], { refine submodule.neg_mem _ (smul_mem _ _ (sum_mem _ (λ k hk, _))), obtain ⟨k_ne_i, k_mem⟩ := finset.mem_erase.mp hk, refine smul_mem _ _ (subset_span ⟨k, _, rfl⟩), simpa using k_mem }, -- To show `b i` is a weighted sum of the other `b j`s, we'll rewrite this sum -- to have the form of the assumption `dependent`. apply eq_neg_of_add_eq_zero, calc b i + (g i)⁻¹ • (s.erase i).sum (λ j, g j • b j) = (g i)⁻¹ • (g i • b i + (s.erase i).sum (λ j, g j • b j)) : by rw [smul_add, ←mul_smul, inv_mul_cancel gx_ne_zero, one_smul] ... = (g i)⁻¹ • 0 : congr_arg _ _ ... = 0 : smul_zero _, -- And then it's just a bit of manipulation with finite sums. rwa [← finset.insert_erase i_mem_s, finset.sum_insert (finset.not_mem_erase _ _)] at dependent end /-- A finite family of vectors is linearly independent if and only if its cardinality equals the dimension of its span. -/ lemma linear_independent_iff_card_eq_findim_span {ι : Type*} [fintype ι] {b : ι → V} : linear_independent K b ↔ fintype.card ι = findim K (span K (set.range b)) := begin split, { intro h, exact (findim_span_eq_card h).symm }, { intro hc, let f := (submodule.subtype (span K (set.range b))), let b' : ι → span K (set.range b) := λ i, ⟨b i, mem_span.2 (λ p hp, hp (set.mem_range_self _))⟩, have hs : span K (set.range b') = ⊤, { rw eq_top_iff', intro x, have h : span K (f '' (set.range b')) = map f (span K (set.range b')) := span_image f, have hf : f '' (set.range b') = set.range b, { ext x, simp [set.mem_image, set.mem_range] }, rw hf at h, have hx : (x : V) ∈ span K (set.range b) := x.property, conv at hx { congr, skip, rw h }, simpa [mem_map] using hx }, have hi : f.ker = ⊥ := ker_subtype _, convert (linear_independent_of_span_eq_top_of_card_eq_findim hs hc).map' _ hi } end lemma is_basis_of_span_eq_top_of_card_eq_findim {ι : Type*} [fintype ι] {b : ι → V} (span_eq : span K (set.range b) = ⊤) (card_eq : fintype.card ι = findim K V) : is_basis K b := ⟨linear_independent_of_span_eq_top_of_card_eq_findim span_eq card_eq, span_eq⟩ lemma finset_is_basis_of_span_eq_top_of_card_eq_findim {s : finset V} (span_eq : span K (↑s : set V) = ⊤) (card_eq : s.card = findim K V) : is_basis K (coe : (↑s : set V) → V) := is_basis_of_span_eq_top_of_card_eq_findim ((@subtype.range_coe_subtype _ (λ x, x ∈ s)).symm ▸ span_eq) (trans (fintype.card_coe _) card_eq) lemma set_is_basis_of_span_eq_top_of_card_eq_findim {s : set V} [fintype s] (span_eq : span K s = ⊤) (card_eq : s.to_finset.card = findim K V) : is_basis K (λ (x : s), (x : V)) := is_basis_of_span_eq_top_of_card_eq_findim ((@subtype.range_coe_subtype _ s).symm ▸ span_eq) (trans s.to_finset_card.symm card_eq) lemma span_eq_top_of_linear_independent_of_card_eq_findim {ι : Type*} [hι : nonempty ι] [fintype ι] {b : ι → V} (lin_ind : linear_independent K b) (card_eq : fintype.card ι = findim K V) : span K (set.range b) = ⊤ := begin by_cases fin : (finite_dimensional K V), { haveI := fin, by_contra ne_top, have lt_top : span K (set.range b) < ⊤ := lt_of_le_of_ne le_top ne_top, exact ne_of_lt (submodule.findim_lt lt_top) (trans (findim_span_eq_card lin_ind) card_eq) }, { exfalso, apply ne_of_lt (fintype.card_pos_iff.mpr hι), symmetry, calc fintype.card ι = findim K V : card_eq ... = 0 : dif_neg (mt finite_dimensional_iff_dim_lt_omega.mpr fin) } end lemma is_basis_of_linear_independent_of_card_eq_findim {ι : Type*} [nonempty ι] [fintype ι] {b : ι → V} (lin_ind : linear_independent K b) (card_eq : fintype.card ι = findim K V) : is_basis K b := ⟨lin_ind, span_eq_top_of_linear_independent_of_card_eq_findim lin_ind card_eq⟩ lemma finset_is_basis_of_linear_independent_of_card_eq_findim {s : finset V} (hs : s.nonempty) (lin_ind : linear_independent K (coe : (↑s : set V) → V)) (card_eq : s.card = findim K V) : is_basis K (coe : (↑s : set V) → V) := @is_basis_of_linear_independent_of_card_eq_findim _ _ _ _ _ _ ⟨(⟨hs.some, hs.some_spec⟩ : (↑s : set V))⟩ _ _ lin_ind (trans (fintype.card_coe _) card_eq) lemma set_is_basis_of_linear_independent_of_card_eq_findim {s : set V} [nonempty s] [fintype s] (lin_ind : linear_independent K (coe : s → V)) (card_eq : s.to_finset.card = findim K V) : is_basis K (coe : s → V) := is_basis_of_linear_independent_of_card_eq_findim lin_ind (trans s.to_finset_card.symm card_eq) end is_basis section subalgebra_dim open vector_space variables {F E : Type*} [field F] [field E] [algebra F E] lemma subalgebra.dim_eq_one_of_eq_bot {S : subalgebra F E} (h : S = ⊥) : dim F S = 1 := begin rw [← S.to_submodule_equiv.dim_eq, h, (linear_equiv.of_eq ↑(⊥ : subalgebra F E) _ algebra.to_submodule_bot).dim_eq, dim_span_set], exacts [mk_singleton _, linear_independent_singleton one_ne_zero] end @[simp] lemma subalgebra.dim_bot : dim F (⊥ : subalgebra F E) = 1 := subalgebra.dim_eq_one_of_eq_bot rfl lemma subalgebra_top_dim_eq_submodule_top_dim : dim F (⊤ : subalgebra F E) = dim F (⊤ : submodule F E) := by { rw ← algebra.coe_top, refl } lemma subalgebra_top_findim_eq_submodule_top_findim : findim F (⊤ : subalgebra F E) = findim F (⊤ : submodule F E) := by { rw ← algebra.coe_top, refl } lemma subalgebra.dim_top : dim F (⊤ : subalgebra F E) = dim F E := by { rw subalgebra_top_dim_eq_submodule_top_dim, exact dim_top } lemma subalgebra.finite_dimensional_bot : finite_dimensional F (⊥ : subalgebra F E) := finite_dimensional_of_dim_eq_one subalgebra.dim_bot @[simp] lemma subalgebra.findim_bot : findim F (⊥ : subalgebra F E) = 1 := begin haveI : finite_dimensional F (⊥ : subalgebra F E) := subalgebra.finite_dimensional_bot, have : dim F (⊥ : subalgebra F E) = 1 := subalgebra.dim_bot, rw ← findim_eq_dim at this, norm_cast at *, simp *, end lemma subalgebra.findim_eq_one_of_eq_bot {S : subalgebra F E} (h : S = ⊥) : findim F S = 1 := by { rw h, exact subalgebra.findim_bot } lemma subalgebra.eq_bot_of_findim_one {S : subalgebra F E} (h : findim F S = 1) : S = ⊥ := begin rw eq_bot_iff, let b : set S := {1}, have : fintype b := unique.fintype, have b_lin_ind : linear_independent F (coe : b → S) := linear_independent_singleton one_ne_zero, have b_card : fintype.card b = 1 := fintype.card_of_subsingleton _, obtain ⟨_, b_spans⟩ := set_is_basis_of_linear_independent_of_card_eq_findim b_lin_ind (by simp only [*, set.to_finset_card]), intros x hx, rw [subalgebra.mem_coe, algebra.mem_bot], have x_in_span_b : (⟨x, hx⟩ : S) ∈ submodule.span F b, { rw subtype.range_coe at b_spans, rw b_spans, exact submodule.mem_top, }, obtain ⟨a, ha⟩ := submodule.mem_span_singleton.mp x_in_span_b, replace ha : a • 1 = x := by injections with ha, exact ⟨a, by rw [← ha, algebra.smul_def, mul_one]⟩, end lemma subalgebra.eq_bot_of_dim_one {S : subalgebra F E} (h : dim F S = 1) : S = ⊥ := begin haveI : finite_dimensional F S := finite_dimensional_of_dim_eq_one h, rw ← findim_eq_dim at h, norm_cast at h, exact subalgebra.eq_bot_of_findim_one h, end @[simp] lemma subalgebra.bot_eq_top_of_dim_eq_one (h : dim F E = 1) : (⊥ : subalgebra F E) = ⊤ := begin rw [← dim_top, ← subalgebra_top_dim_eq_submodule_top_dim] at h, exact eq.symm (subalgebra.eq_bot_of_dim_one h), end @[simp] lemma subalgebra.bot_eq_top_of_findim_eq_one (h : findim F E = 1) : (⊥ : subalgebra F E) = ⊤ := begin rw [← findim_top, ← subalgebra_top_findim_eq_submodule_top_findim] at h, exact eq.symm (subalgebra.eq_bot_of_findim_one h), end @[simp] theorem subalgebra.dim_eq_one_iff {S : subalgebra F E} : dim F S = 1 ↔ S = ⊥ := ⟨subalgebra.eq_bot_of_dim_one, subalgebra.dim_eq_one_of_eq_bot⟩ @[simp] theorem subalgebra.findim_eq_one_iff {S : subalgebra F E} : findim F S = 1 ↔ S = ⊥ := ⟨subalgebra.eq_bot_of_findim_one, subalgebra.findim_eq_one_of_eq_bot⟩ end subalgebra_dim namespace module namespace End lemma exists_ker_pow_eq_ker_pow_succ [finite_dimensional K V] (f : End K V) : ∃ (k : ℕ), k ≤ findim K V ∧ (f ^ k).ker = (f ^ k.succ).ker := begin classical, by_contradiction h_contra, simp_rw [not_exists, not_and] at h_contra, have h_le_ker_pow : ∀ (n : ℕ), n ≤ (findim K V).succ → n ≤ findim K (f ^ n).ker, { intros n hn, induction n with n ih, { exact zero_le (findim _ _) }, { have h_ker_lt_ker : (f ^ n).ker < (f ^ n.succ).ker, { refine lt_of_le_of_ne _ (h_contra n (nat.le_of_succ_le_succ hn)), rw pow_succ, apply linear_map.ker_le_ker_comp }, have h_findim_lt_findim : findim K (f ^ n).ker < findim K (f ^ n.succ).ker, { apply submodule.findim_lt_findim_of_lt h_ker_lt_ker }, calc n.succ ≤ (findim K ↥(linear_map.ker (f ^ n))).succ : nat.succ_le_succ (ih (nat.le_of_succ_le hn)) ... ≤ findim K ↥(linear_map.ker (f ^ n.succ)) : nat.succ_le_of_lt h_findim_lt_findim } }, have h_le_findim_V : ∀ n, findim K (f ^ n).ker ≤ findim K V := λ n, submodule.findim_le _, have h_any_n_lt: ∀ n, n ≤ (findim K V).succ → n ≤ findim K V := λ n hn, (h_le_ker_pow n hn).trans (h_le_findim_V n), show false, from nat.not_succ_le_self _ (h_any_n_lt (findim K V).succ (findim K V).succ.le_refl), end lemma ker_pow_constant {f : End K V} {k : ℕ} (h : (f ^ k).ker = (f ^ k.succ).ker) : ∀ m, (f ^ k).ker = (f ^ (k + m)).ker | 0 := by simp | (m + 1) := begin apply le_antisymm, { rw [add_comm, pow_add], apply linear_map.ker_le_ker_comp }, { rw [ker_pow_constant m, add_comm m 1, ←add_assoc, pow_add, pow_add f k m], change linear_map.ker ((f ^ (k + 1)).comp (f ^ m)) ≤ linear_map.ker ((f ^ k).comp (f ^ m)), rw [linear_map.ker_comp, linear_map.ker_comp, h, nat.add_one], exact le_refl _, } end lemma ker_pow_eq_ker_pow_findim_of_le [finite_dimensional K V] {f : End K V} {m : ℕ} (hm : findim K V ≤ m) : (f ^ m).ker = (f ^ findim K V).ker := begin obtain ⟨k, h_k_le, hk⟩ : ∃ k, k ≤ findim K V ∧ linear_map.ker (f ^ k) = linear_map.ker (f ^ k.succ) := exists_ker_pow_eq_ker_pow_succ f, calc (f ^ m).ker = (f ^ (k + (m - k))).ker : by rw nat.add_sub_of_le (h_k_le.trans hm) ... = (f ^ k).ker : by rw ker_pow_constant hk _ ... = (f ^ (k + (findim K V - k))).ker : ker_pow_constant hk (findim K V - k) ... = (f ^ findim K V).ker : by rw nat.add_sub_of_le h_k_le end lemma ker_pow_le_ker_pow_findim [finite_dimensional K V] (f : End K V) (m : ℕ) : (f ^ m).ker ≤ (f ^ findim K V).ker := begin by_cases h_cases: m < findim K V, { rw [←nat.add_sub_of_le (nat.le_of_lt h_cases), add_comm, pow_add], apply linear_map.ker_le_ker_comp }, { rw [ker_pow_eq_ker_pow_findim_of_le (le_of_not_lt h_cases)], exact le_refl _ } end end End end module
306d9e6aebe4557212259eee766849d7527526c4
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/tactic/local_cache.lean
1a72d041c95dbb47f728a4ca90d18b2bbfca1d7d
[]
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,437
lean
/- Copyright (c) 2019 Keeley Hoek. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Keeley Hoek -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.tactic.norm_num import Mathlib.PostPort namespace Mathlib namespace tactic namespace local_cache namespace internal -- We maintain two separate caches with different scopes: -- one local to `begin ... end` or `by` blocks, and another -- for entire `def`/`lemma`s. -- Returns the name of the def used to store the contents of is cache, -- making a new one and recording this in private state if neccesary. -- Same as above but fails instead of making a new name, and never -- mutates state. -- Asks whether the namespace `ns` currently has a value-in-cache -- Clear cache associated to namespace `ns` namespace block_local -- `mk_new` gives a way to generate a new name if no current one -- exists. -- Like `get_name`, but fail if `ns` does not have a cached -- decl name (we create a new one above). end block_local namespace def_local -- Fowler-Noll-Vo hash function (FNV-1a) def FNV_OFFSET_BASIS : ℕ := sorry def FNV_PRIME : ℕ := sorry def RADIX : ℕ := sorry def hash_byte (seed : ℕ) (c : char) : ℕ := let n : ℕ := char.to_nat c; nat.lxor seed n * FNV_PRIME % RADIX def hash_string (s : string) : ℕ := list.foldl hash_byte FNV_OFFSET_BASIS (string.to_list s)
c831f26034d636f62238ade812fca656662c3e77
2385ce0e3b60d8dbea33dd439902a2070cca7a24
/library/init/meta/tactic.lean
79f394a50d585b2fc4faa2499f33ea940182e620
[ "Apache-2.0" ]
permissive
TehMillhouse/lean
68d6fdd2fb11a6c65bc28dec308d70f04dad38b4
6bbf2fbd8912617e5a973575bab8c383c9c268a1
refs/heads/master
1,620,830,893,339
1,515,592,479,000
1,515,592,997,000
116,964,828
0
0
null
1,515,592,734,000
1,515,592,734,000
null
UTF-8
Lean
false
false
51,263
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.function init.data.option.basic init.util import init.category.combinators init.category.monad init.category.alternative init.category.monad_fail import init.data.nat.div init.meta.exceptional init.meta.format init.meta.environment import init.meta.pexpr init.data.repr init.data.string.basic init.meta.interaction_monad meta constant tactic_state : Type universes u v namespace tactic_state /-- Create a tactic state with an empty local context and a dummy goal. -/ meta constant mk_empty : environment → options → tactic_state meta constant env : tactic_state → environment /-- Format the given tactic state. If `target_lhs_only` is true and the target is of the form `lhs ~ rhs`, where `~` is a simplification relation, then only the `lhs` is displayed. Remark: the parameter `target_lhs_only` is a temporary hack used to implement the `conv` monad. It will be removed in the future. -/ meta constant to_format (s : tactic_state) (target_lhs_only : bool := ff) : format /-- Format expression with respect to the main goal in the tactic state. If the tactic state does not contain any goals, then format expression using an empty local context. -/ meta constant format_expr : tactic_state → expr → format meta constant get_options : tactic_state → options meta constant set_options : tactic_state → options → tactic_state end tactic_state meta instance : has_to_format tactic_state := ⟨tactic_state.to_format⟩ meta instance : has_to_string tactic_state := ⟨λ s, (to_fmt s).to_string s.get_options⟩ @[reducible] meta def tactic := interaction_monad tactic_state @[reducible] meta def tactic_result := interaction_monad.result tactic_state namespace tactic export interaction_monad (hiding failed fail) meta def failed {α : Type} : tactic α := interaction_monad.failed meta def fail {α : Type u} {β : Type v} [has_to_format β] (msg : β) : tactic α := interaction_monad.fail msg end tactic namespace tactic_result export interaction_monad.result end tactic_result open tactic open tactic_result infixl ` >>=[tactic] `:2 := interaction_monad_bind infixl ` >>[tactic] `:2 := interaction_monad_seq meta instance : alternative tactic := { failure := @interaction_monad.failed _, orelse := @interaction_monad_orelse _, ..interaction_monad.monad } meta def {u₁ u₂} tactic.up {α : Type u₂} (t : tactic α) : tactic (ulift.{u₁} α) := λ s, match t s with | success a s' := success (ulift.up a) s' | exception t ref s := exception t ref s end meta def {u₁ u₂} tactic.down {α : Type u₂} (t : tactic (ulift.{u₁} α)) : tactic α := λ s, match t s with | success (ulift.up a) s' := success a s' | exception t ref s := exception t ref s end namespace tactic variables {α : Type u} meta def try_core (t : tactic α) : tactic (option α) := λ s, result.cases_on (t s) (λ a, success (some a)) (λ e ref s', success none s) meta def skip : tactic unit := success () meta def try (t : tactic α) : tactic unit := try_core t >>[tactic] skip meta def try_lst : list (tactic unit) → tactic unit | [] := failed | (tac :: tacs) := λ s, match tac s with | result.success _ s' := try (try_lst tacs) s' | result.exception e p s' := match try_lst tacs s' with | result.exception _ _ _ := result.exception e p s' | r := r end end meta def fail_if_success {α : Type u} (t : tactic α) : tactic unit := λ s, result.cases_on (t s) (λ a s, mk_exception "fail_if_success combinator failed, given tactic succeeded" none s) (λ e ref s', success () s) meta def success_if_fail {α : Type u} (t : tactic α) : tactic unit := λ s, match t s with | (interaction_monad.result.exception _ _ s') := success () s | (interaction_monad.result.success a s) := mk_exception "success_if_fail combinator failed, given tactic succeeded" none s end open nat /-- (iterate_at_most n t): repeat the given tactic at most n times or until t fails -/ meta def iterate_at_most : nat → tactic unit → tactic unit | 0 t := skip | (succ n) t := (do t, iterate_at_most n t) <|> skip /-- (iterate_exactly n t) : execute t n times -/ meta def iterate_exactly : nat → tactic unit → tactic unit | 0 t := skip | (succ n) t := do t, iterate_exactly n t meta def iterate : tactic unit → tactic unit := iterate_at_most 100000 meta def returnopt (e : option α) : tactic α := λ s, match e with | (some a) := success a s | none := mk_exception "failed" none s end meta instance opt_to_tac : has_coe (option α) (tactic α) := ⟨returnopt⟩ /-- Decorate t's exceptions with msg -/ meta def decorate_ex (msg : format) (t : tactic α) : tactic α := λ s, result.cases_on (t s) success (λ opt_thunk, match opt_thunk with | some e := exception (some (λ u, msg ++ format.nest 2 (format.line ++ e u))) | none := exception none end) @[inline] meta def write (s' : tactic_state) : tactic unit := λ s, success () s' @[inline] meta def read : tactic tactic_state := λ s, success s s meta def get_options : tactic options := do s ← read, return s.get_options meta def set_options (o : options) : tactic unit := do s ← read, write (s.set_options o) meta def save_options {α : Type} (t : tactic α) : tactic α := do o ← get_options, a ← t, set_options o, return a meta def returnex {α : Type} (e : exceptional α) : tactic α := λ s, match e with | exceptional.success a := success a s | exceptional.exception ._ f := match get_options s with | success opt _ := exception (some (λ u, f opt)) none s | exception _ _ _ := exception (some (λ u, f options.mk)) none s end end meta instance ex_to_tac {α : Type} : has_coe (exceptional α) (tactic α) := ⟨returnex⟩ end tactic meta def tactic_format_expr (e : expr) : tactic format := do s ← tactic.read, return (tactic_state.format_expr s e) meta class has_to_tactic_format (α : Type u) := (to_tactic_format : α → tactic format) meta instance : has_to_tactic_format expr := ⟨tactic_format_expr⟩ meta def tactic.pp {α : Type u} [has_to_tactic_format α] : α → tactic format := has_to_tactic_format.to_tactic_format open tactic format meta instance {α : Type u} [has_to_tactic_format α] : has_to_tactic_format (list α) := ⟨has_map.map to_fmt ∘ monad.mapm pp⟩ meta instance (α : Type u) (β : Type v) [has_to_tactic_format α] [has_to_tactic_format β] : has_to_tactic_format (α × β) := ⟨λ ⟨a, b⟩, to_fmt <$> (prod.mk <$> pp a <*> pp b)⟩ meta def option_to_tactic_format {α : Type u} [has_to_tactic_format α] : option α → tactic format | (some a) := do fa ← pp a, return (to_fmt "(some " ++ fa ++ ")") | none := return "none" meta instance {α : Type u} [has_to_tactic_format α] : has_to_tactic_format (option α) := ⟨option_to_tactic_format⟩ meta instance {α} (a : α) : has_to_tactic_format (reflected a) := ⟨λ h, pp h.to_expr⟩ @[priority 10] meta instance has_to_format_to_has_to_tactic_format (α : Type) [has_to_format α] : has_to_tactic_format α := ⟨(λ x, return x) ∘ to_fmt⟩ namespace tactic open tactic_state meta def get_env : tactic environment := do s ← read, return $ env s meta def get_decl (n : name) : tactic declaration := do s ← read, (env s).get n meta def trace {α : Type u} [has_to_tactic_format α] (a : α) : tactic unit := do fmt ← pp a, return $ _root_.trace_fmt fmt (λ u, ()) meta def trace_call_stack : tactic unit := assume state, _root_.trace_call_stack (success () state) meta def timetac {α : Type u} (desc : string) (t : thunk (tactic α)) : tactic α := λ s, timeit desc (t () s) meta def trace_state : tactic unit := do s ← read, trace $ to_fmt s inductive transparency | all | semireducible | instances | reducible | none export transparency (reducible semireducible) /-- (eval_expr α e) evaluates 'e' IF 'e' has type 'α'. -/ meta constant eval_expr (α : Type u) [reflected α] : expr → tactic α /-- Return the partial term/proof constructed so far. Note that the resultant expression may contain variables that are not declarate in the current main goal. -/ meta constant result : tactic expr /-- Display the partial term/proof constructed so far. This tactic is *not* equivalent to `do { r ← result, s ← read, return (format_expr s r) }` because this one will format the result with respect to the current goal, and trace_result will do it with respect to the initial goal. -/ meta constant format_result : tactic format /-- Return target type of the main goal. Fail if tactic_state does not have any goal left. -/ meta constant target : tactic expr meta constant intro_core : name → tactic expr meta constant intron : nat → tactic unit /-- Clear the given local constant. The tactic fails if the given expression is not a local constant. -/ meta constant clear : expr → tactic unit meta constant revert_lst : list expr → tactic nat /-- Return `e` in weak head normal form with respect to the given transparency setting. If `unfold_ginductive` is `tt`, then nested and/or mutually recursive inductive datatype constructors and types are unfolded. Recall that nested and mutually recursive inductive datatype declarations are compiled into primitive datatypes accepted by the Kernel. -/ meta constant whnf (e : expr) (md := semireducible) (unfold_ginductive := tt) : tactic expr /-- (head) eta expand the given expression -/ meta constant head_eta_expand : expr → tactic expr /-- (head) beta reduction -/ meta constant head_beta : expr → tactic expr /-- (head) zeta reduction -/ meta constant head_zeta : expr → tactic expr /-- zeta reduction -/ meta constant zeta : expr → tactic expr /-- (head) eta reduction -/ meta constant head_eta : expr → tactic expr /-- Succeeds if `t` and `s` can be unified using the given transparency setting. -/ meta constant unify (t s : expr) (md := semireducible) : tactic unit /-- Similar to `unify`, but it treats metavariables as constants. -/ meta constant is_def_eq (t s : expr) (md := semireducible) : tactic unit /-- Infer the type of the given expression. Remark: transparency does not affect type inference -/ meta constant infer_type : expr → tactic expr meta constant get_local : name → tactic expr /-- Resolve a name using the current local context, environment, aliases, etc. -/ meta constant resolve_name : name → tactic pexpr /-- Return the hypothesis in the main goal. Fail if tactic_state does not have any goal left. -/ meta constant local_context : tactic (list expr) meta constant get_unused_name (n : name) (i : option nat := none) : tactic name /-- Helper tactic for creating simple applications where some arguments are inferred using type inference. Example, given ``` rel.{l_1 l_2} : Pi (α : Type.{l_1}) (β : α -> Type.{l_2}), (Pi x : α, β x) -> (Pi x : α, β x) -> , Prop nat : Type real : Type vec.{l} : Pi (α : Type l) (n : nat), Type.{l1} f g : Pi (n : nat), vec real n ``` then ``` mk_app_core semireducible "rel" [f, g] ``` returns the application ``` rel.{1 2} nat (fun n : nat, vec real n) f g ``` The unification constraints due to type inference are solved using the transparency `md`. -/ meta constant mk_app (fn : name) (args : list expr) (md := semireducible) : tactic expr /-- Similar to `mk_app`, but allows to specify which arguments are explicit/implicit. Example, given `(a b : nat)` then ``` mk_mapp "ite" [some (a > b), none, none, some a, some b] ``` returns the application ``` @ite.{1} (a > b) (nat.decidable_gt a b) nat a b ``` -/ meta constant mk_mapp (fn : name) (args : list (option expr)) (md := semireducible) : tactic expr /-- (mk_congr_arg h₁ h₂) is a more efficient version of (mk_app `congr_arg [h₁, h₂]) -/ meta constant mk_congr_arg : expr → expr → tactic expr /-- (mk_congr_fun h₁ h₂) is a more efficient version of (mk_app `congr_fun [h₁, h₂]) -/ meta constant mk_congr_fun : expr → expr → tactic expr /-- (mk_congr h₁ h₂) is a more efficient version of (mk_app `congr [h₁, h₂]) -/ meta constant mk_congr : expr → expr → tactic expr /-- (mk_eq_refl h) is a more efficient version of (mk_app `eq.refl [h]) -/ meta constant mk_eq_refl : expr → tactic expr /-- (mk_eq_symm h) is a more efficient version of (mk_app `eq.symm [h]) -/ meta constant mk_eq_symm : expr → tactic expr /-- (mk_eq_trans h₁ h₂) is a more efficient version of (mk_app `eq.trans [h₁, h₂]) -/ meta constant mk_eq_trans : expr → expr → tactic expr /-- (mk_eq_mp h₁ h₂) is a more efficient version of (mk_app `eq.mp [h₁, h₂]) -/ meta constant mk_eq_mp : expr → expr → tactic expr /-- (mk_eq_mpr h₁ h₂) is a more efficient version of (mk_app `eq.mpr [h₁, h₂]) -/ meta constant mk_eq_mpr : expr → expr → tactic expr /- Given a local constant t, if t has type (lhs = rhs) apply substitution. Otherwise, try to find a local constant that has type of the form (t = t') or (t' = t). The tactic fails if the given expression is not a local constant. -/ meta constant subst : expr → tactic unit /-- Close the current goal using `e`. Fail is the type of `e` is not definitionally equal to the target type. -/ meta constant exact (e : expr) (md := semireducible) : tactic unit /-- Elaborate the given quoted expression with respect to the current main goal. If `allow_mvars` is tt, then metavariables are tolerated and become new goals if `subgoals` is tt. -/ meta constant to_expr (q : pexpr) (allow_mvars := tt) (subgoals := tt) : tactic expr /-- Return true if the given expression is a type class. -/ meta constant is_class : expr → tactic bool /-- Try to create an instance of the given type class. -/ meta constant mk_instance : expr → tactic expr /-- Change the target of the main goal. The input expression must be definitionally equal to the current target. If `check` is `ff`, then the tactic does not check whether `e` is definitionally equal to the current target. If it is not, then the error will only be detected by the kernel type checker. -/ meta constant change (e : expr) (check : bool := tt): tactic unit /-- `assert_core H T`, adds a new goal for T, and change target to `T -> target`. -/ meta constant assert_core : name → expr → tactic unit /-- `assertv_core H T P`, change target to (T -> target) if P has type T. -/ meta constant assertv_core : name → expr → expr → tactic unit /-- `define_core H T`, adds a new goal for T, and change target to `let H : T := ?M in target` in the current goal. -/ meta constant define_core : name → expr → tactic unit /-- `definev_core H T P`, change target to `let H : T := P in target` if P has type T. -/ meta constant definev_core : name → expr → expr → tactic unit /-- rotate goals to the left -/ meta constant rotate_left : nat → tactic unit meta constant get_goals : tactic (list expr) meta constant set_goals : list expr → tactic unit inductive new_goals | non_dep_first | non_dep_only | all /-- Configuration options for the `apply` tactic. - `new_goals` is the strategy for ordering new goals. - `instances` if `tt`, then `apply` tries to synthesize unresolved `[...]` arguments using type class resolution. - `auto_param` if `tt`, then `apply` tries to synthesize unresolved `(h : p . tac_id)` arguments using tactic `tac_id`. - `opt_param` if `tt`, then `apply` tries to synthesize unresolved `(a : t := v)` arguments by setting them to `v`. - `unify` if `tt`, then `apply` is free to assign existing metavariables in the goal when solving unification constraints. For example, in the goal `|- ?x < succ 0`, the tactic `apply succ_lt_succ` succeeds with the default configuration, but `apply_with succ_lt_succ {unify := ff}` doesn't since it would require Lean to assign `?x` to `succ ?y` where `?y` is a fresh metavariable. -/ structure apply_cfg := (md := semireducible) (approx := tt) (new_goals := new_goals.non_dep_first) (instances := tt) (auto_param := tt) (opt_param := tt) (unify := tt) /-- Apply the expression `e` to the main goal, the unification is performed using the transparency mode in `cfg`. If `cfg.approx` is `tt`, then fallback to first-order unification, and approximate context during unification. `cfg.new_goals` specifies which unassigned metavariables become new goals, and their order. If `cfg.instances` is `tt`, then use type class resolution to instantiate unassigned meta-variables. The fields `cfg.auto_param` and `cfg.opt_param` are ignored by this tactic (See `tactic.apply`). It returns a list of all introduced meta variables and the parameter name associated with them, even the assigned ones. -/ meta constant apply_core (e : expr) (cfg : apply_cfg := {}) : tactic (list (name × expr)) /- Create a fresh meta universe variable. -/ meta constant mk_meta_univ : tactic level /- Create a fresh meta-variable with the given type. The scope of the new meta-variable is the local context of the main goal. -/ meta constant mk_meta_var : expr → tactic expr /-- Return the value assigned to the given universe meta-variable. Fail if argument is not an universe meta-variable or if it is not assigned. -/ meta constant get_univ_assignment : level → tactic level /-- Return the value assigned to the given meta-variable. Fail if argument is not a meta-variable or if it is not assigned. -/ meta constant get_assignment : expr → tactic expr /-- Return true if the given meta-variable is assigned. Fail if argument is not a meta-variable. -/ meta constant is_assigned : expr → tactic bool meta constant mk_fresh_name : tactic name /-- Return a hash code for expr that ignores inst_implicit arguments, and proofs. -/ meta constant abstract_hash : expr → tactic nat /-- Return the "weight" of the given expr while ignoring inst_implicit arguments, and proofs. -/ meta constant abstract_weight : expr → tactic nat meta constant abstract_eq : expr → expr → tactic bool /-- Induction on `h` using recursor `rec`, names for the new hypotheses are retrieved from `ns`. If `ns` does not have sufficient names, then use the internal binder names in the recursor. It returns for each new goal the name of the constructor (if `rec_name` is a builtin recursor), a list of new hypotheses, and a list of substitutions for hypotheses depending on `h`. The substitutions map internal names to their replacement terms. If the replacement is again a hypothesis the user name stays the same. The internal names are only valid in the original goal, not in the type context of the new goal. Remark: if `rec_name` is not a builtin recursor, we use parameter names of `rec_name` instead of constructor names. If `rec` is none, then the type of `h` is inferred, if it is of the form `C ...`, tactic uses `C.rec` -/ meta constant induction (h : expr) (ns : list name := []) (rec : option name := none) (md := semireducible) : tactic (list (name × list expr × list (name × expr))) /-- Apply `cases_on` recursor, names for the new hypotheses are retrieved from `ns`. `h` must be a local constant. It returns for each new goal the name of the constructor, a list of new hypotheses, and a list of substitutions for hypotheses depending on `h`. The number of new goals may be smaller than the number of constructors. Some goals may be discarded when the indices to not match. See `induction` for information on the list of substitutions. The `cases` tactic is implemented using this one, and it relaxes the restriction of `h`. -/ meta constant cases_core (h : expr) (ns : list name := []) (md := semireducible) : tactic (list (name × list expr × list (name × expr))) /-- Similar to cases tactic, but does not revert/intro/clear hypotheses. -/ meta constant destruct (e : expr) (md := semireducible) : tactic unit /-- Generalizes the target with respect to `e`. -/ meta constant generalize (e : expr) (n : name := `_x) (md := semireducible) : tactic unit /-- instantiate assigned metavariables in the given expression -/ meta constant instantiate_mvars : expr → tactic expr /-- Add the given declaration to the environment -/ meta constant add_decl : declaration → tactic unit /-- Changes the environment to the `new_env`. `new_env` needs to be a descendant from the current environment. -/ meta constant set_env : environment → tactic unit /-- (doc_string env d k) return the doc string for d (if available) -/ meta constant doc_string : name → tactic string meta constant add_doc_string : name → string → tactic unit /-- Create an auxiliary definition with name `c` where `type` and `value` may contain local constants and meta-variables. This function collects all dependencies (universe parameters, universe metavariables, local constants (aka hypotheses) and metavariables). It updates the environment in the tactic_state, and returns an expression of the form (c.{l_1 ... l_n} a_1 ... a_m) where l_i's and a_j's are the collected dependencies. -/ meta constant add_aux_decl (c : name) (type : expr) (val : expr) (is_lemma : bool) : tactic expr meta constant module_doc_strings : tactic (list (option name × string)) /-- Set attribute `attr_name` for constant `c_name` with the given priority. If the priority is none, then use default -/ meta constant set_basic_attribute (attr_name : name) (c_name : name) (persistent := ff) (prio : option nat := none) : tactic unit /-- `unset_attribute attr_name c_name` -/ meta constant unset_attribute : name → name → tactic unit /-- `has_attribute attr_name c_name` succeeds if the declaration `decl_name` has the attribute `attr_name`. The result is the priority. -/ meta constant has_attribute : name → name → tactic nat /-- `copy_attribute attr_name c_name d_name` copy attribute `attr_name` from `src` to `tgt` if it is defined for `src` -/ meta def copy_attribute (attr_name : name) (src : name) (p : bool) (tgt : name) : tactic unit := try $ do prio ← has_attribute attr_name src, set_basic_attribute attr_name tgt p (some prio) /-- Name of the declaration currently being elaborated. -/ meta constant decl_name : tactic name /-- `save_type_info e ref` save (typeof e) at position associated with ref -/ meta constant save_type_info {elab : bool} : expr → expr elab → tactic unit meta constant save_info_thunk : pos → (unit → format) → tactic unit /-- Return list of currently open namespaces -/ meta constant open_namespaces : tactic (list name) /-- Return tt iff `t` "occurs" in `e`. The occurrence checking is performed using keyed matching with the given transparency setting. We say `t` occurs in `e` by keyed matching iff there is a subterm `s` s.t. `t` and `s` have the same head, and `is_def_eq t s md` The main idea is to minimize the number of `is_def_eq` checks performed. -/ meta constant kdepends_on (e t : expr) (md := reducible) : tactic bool /-- Abstracts all occurrences of the term `t` in `e` using keyed matching. If `unify` is `ff`, then matching is used instead of unification. That is, metavariables occurring in `e` are not assigned. -/ meta constant kabstract (e t : expr) (md := reducible) (unify := tt) : tactic expr /-- Blocks the execution of the current thread for at least `msecs` milliseconds. This tactic is used mainly for debugging purposes. -/ meta constant sleep (msecs : nat) : tactic unit /-- Type check `e` with respect to the current goal. Fails if `e` is not type correct. -/ meta constant type_check (e : expr) (md := semireducible) : tactic unit open list nat /-- Goals can be tagged using a list of names. -/ def tag : Type := list name /-- Enable/disable goal tagging -/ meta constant enable_tags (b : bool) : tactic unit /-- Return tt iff goal tagging is enabled. -/ meta constant tags_enabled : tactic bool /-- Tag goal `g` with tag `t`. It does nothing is goal tagging is disabled. Remark: `set_goal g []` removes the tag -/ meta constant set_tag (g : expr) (t : tag) : tactic unit /-- Return tag associated with `g`. Return `[]` if there is no tag. -/ meta constant get_tag (g : expr) : tactic tag meta def induction' (h : expr) (ns : list name := []) (rec : option name := none) (md := semireducible) : tactic unit := induction h ns rec md >> return () /-- Remark: set_goals will erase any solved goal -/ meta def cleanup : tactic unit := get_goals >>= set_goals /-- Auxiliary definition used to implement begin ... end blocks -/ meta def step {α : Type u} (t : tactic α) : tactic unit := t >>[tactic] cleanup meta def istep {α : Type u} (line0 col0 : ℕ) (line col : ℕ) (t : tactic α) : tactic unit := λ s, (@scope_trace _ line col (λ _, step t s)).clamp_pos line0 line col meta def is_prop (e : expr) : tactic bool := do t ← infer_type e, return (t = `(Prop)) /-- Return true iff n is the name of declaration that is a proposition. -/ meta def is_prop_decl (n : name) : tactic bool := do env ← get_env, d ← env.get n, t ← return $ d.type, is_prop t meta def is_proof (e : expr) : tactic bool := infer_type e >>= is_prop meta def whnf_no_delta (e : expr) : tactic expr := whnf e transparency.none /-- Return `e` in weak head normal form with respect to the given transparency setting, or `e` head is a generalized constructor or inductive datatype. -/ meta def whnf_ginductive (e : expr) (md := semireducible) : tactic expr := whnf e md ff meta def whnf_target : tactic unit := target >>= whnf >>= change meta def unsafe_change (e : expr) : tactic unit := change e ff meta def intro (n : name) : tactic expr := do t ← target, if expr.is_pi t ∨ expr.is_let t then intro_core n else whnf_target >> intro_core n meta def intro1 : tactic expr := intro `_ meta def intros : tactic (list expr) := do t ← target, match t with | expr.pi _ _ _ _ := do H ← intro1, Hs ← intros, return (H :: Hs) | expr.elet _ _ _ _ := do H ← intro1, Hs ← intros, return (H :: Hs) | _ := return [] end meta def intro_lst : list name → tactic (list expr) | [] := return [] | (n::ns) := do H ← intro n, Hs ← intro_lst ns, return (H :: Hs) /-- Introduces new hypotheses with forward dependencies -/ meta def intros_dep : tactic (list expr) := do t ← target, let proc (b : expr) := if b.has_var_idx 0 then do h ← intro1, hs ← intros_dep, return (h::hs) else -- body doesn't depend on new hypothesis return [], match t with | expr.pi _ _ _ b := proc b | expr.elet _ _ _ b := proc b | _ := return [] end meta def introv : list name → tactic (list expr) | [] := intros_dep | (n::ns) := do hs ← intros_dep, h ← intro n, hs' ← introv ns, return (hs ++ h :: hs') /-- Returns n fully qualified if it refers to a constant, or else fails. -/ meta def resolve_constant (n : name) : tactic name := do (expr.const n _) ← resolve_name n, pure n meta def to_expr_strict (q : pexpr) : tactic expr := to_expr q meta def revert (l : expr) : tactic nat := revert_lst [l] meta def clear_lst : list name → tactic unit | [] := skip | (n::ns) := do H ← get_local n, clear H, clear_lst ns meta def match_not (e : expr) : tactic expr := match (expr.is_not e) with | (some a) := return a | none := fail "expression is not a negation" end meta def match_and (e : expr) : tactic (expr × expr) := match (expr.is_and e) with | (some (α, β)) := return (α, β) | none := fail "expression is not a conjunction" end meta def match_or (e : expr) : tactic (expr × expr) := match (expr.is_or e) with | (some (α, β)) := return (α, β) | none := fail "expression is not a disjunction" end meta def match_iff (e : expr) : tactic (expr × expr) := match (expr.is_iff e) with | (some (lhs, rhs)) := return (lhs, rhs) | none := fail "expression is not an iff" end meta def match_eq (e : expr) : tactic (expr × expr) := match (expr.is_eq e) with | (some (lhs, rhs)) := return (lhs, rhs) | none := fail "expression is not an equality" end meta def match_ne (e : expr) : tactic (expr × expr) := match (expr.is_ne e) with | (some (lhs, rhs)) := return (lhs, rhs) | none := fail "expression is not a disequality" end meta def match_heq (e : expr) : tactic (expr × expr × expr × expr) := do match (expr.is_heq e) with | (some (α, lhs, β, rhs)) := return (α, lhs, β, rhs) | none := fail "expression is not a heterogeneous equality" end meta def match_refl_app (e : expr) : tactic (name × expr × expr) := do env ← get_env, match (environment.is_refl_app env e) with | (some (R, lhs, rhs)) := return (R, lhs, rhs) | none := fail "expression is not an application of a reflexive relation" end meta def match_app_of (e : expr) (n : name) : tactic (list expr) := guard (expr.is_app_of e n) >> return e.get_app_args meta def get_local_type (n : name) : tactic expr := get_local n >>= infer_type meta def trace_result : tactic unit := format_result >>= trace meta def rexact (e : expr) : tactic unit := exact e reducible meta def any_hyp_aux {α : Type} (f : expr → tactic α) : list expr → tactic α | [] := failed | (h :: hs) := f h <|> any_hyp_aux hs meta def any_hyp {α : Type} (f : expr → tactic α) : tactic α := local_context >>= any_hyp_aux f /-- `find_same_type t es` tries to find in es an expression with type definitionally equal to t -/ meta def find_same_type : expr → list expr → tactic expr | e [] := failed | e (H :: Hs) := do t ← infer_type H, (unify e t >> return H) <|> find_same_type e Hs meta def find_assumption (e : expr) : tactic expr := do ctx ← local_context, find_same_type e ctx meta def assumption : tactic unit := do { ctx ← local_context, t ← target, H ← find_same_type t ctx, exact H } <|> fail "assumption tactic failed" meta def save_info (p : pos) : tactic unit := do s ← read, tactic.save_info_thunk p (λ _, tactic_state.to_format s) notation `‹` p `›` := (by assumption : p) /-- Swap first two goals, do nothing if tactic state does not have at least two goals. -/ meta def swap : tactic unit := do gs ← get_goals, match gs with | (g₁ :: g₂ :: rs) := set_goals (g₂ :: g₁ :: rs) | e := skip end /-- `assert h t`, adds a new goal for t, and the hypothesis `h : t` in the current goal. -/ meta def assert (h : name) (t : expr) : tactic expr := do assert_core h t, swap, e ← intro h, swap, return e /-- `assertv h t v`, adds the hypothesis `h : t` in the current goal if v has type t. -/ meta def assertv (h : name) (t : expr) (v : expr) : tactic expr := assertv_core h t v >> intro h /-- `define h t`, adds a new goal for t, and the hypothesis `h : t := ?M` in the current goal. -/ meta def define (h : name) (t : expr) : tactic expr := do define_core h t, swap, e ← intro h, swap, return e /-- `definev h t v`, adds the hypothesis (h : t := v) in the current goal if v has type t. -/ meta def definev (h : name) (t : expr) (v : expr) : tactic expr := definev_core h t v >> intro h /-- Add `h : t := pr` to the current goal -/ meta def pose (h : name) (t : option expr := none) (pr : expr) : tactic expr := let dv := λt, definev h t pr in option.cases_on t (infer_type pr >>= dv) dv /-- Add `h : t` to the current goal, given a proof `pr : t` -/ meta def note (h : name) (t : option expr := none) (pr : expr) : tactic expr := let dv := λt, assertv h t pr in option.cases_on t (infer_type pr >>= dv) dv /-- Return the number of goals that need to be solved -/ meta def num_goals : tactic nat := do gs ← get_goals, return (length gs) /-- We have to provide the instance argument `[has_mod nat]` because mod for nat was not defined yet -/ meta def rotate_right (n : nat) [has_mod nat] : tactic unit := do ng ← num_goals, if ng = 0 then skip else rotate_left (ng - n % ng) meta def rotate : nat → tactic unit := rotate_left private meta def repeat_aux (t : tactic unit) : list expr → list expr → tactic unit | [] r := set_goals r.reverse | (g::gs) r := do ok ← try_core (set_goals [g] >> t), match ok with | none := repeat_aux gs (g::r) | _ := do gs' ← get_goals, repeat_aux (gs' ++ gs) r end /-- This tactic is applied to each goal. If the application succeeds, the tactic is applied recursively to all the generated subgoals until it eventually fails. The recursion stops in a subgoal when the tactic has failed to make progress. The tactic `repeat` never fails. -/ meta def repeat (t : tactic unit) : tactic unit := do gs ← get_goals, repeat_aux t gs [] /-- `first [t_1, ..., t_n]` applies the first tactic that doesn't fail. The tactic fails if all t_i's fail. -/ meta def first {α : Type u} : list (tactic α) → tactic α | [] := fail "first tactic failed, no more alternatives" | (t::ts) := t <|> first ts /-- Applies the given tactic to the main goal and fails if it is not solved. -/ meta def solve1 (tac : tactic unit) : tactic unit := do gs ← get_goals, match gs with | [] := fail "solve1 tactic failed, there isn't any goal left to focus" | (g::rs) := do set_goals [g], tac, gs' ← get_goals, match gs' with | [] := set_goals rs | gs := fail "solve1 tactic failed, focused goal has not been solved" end end /-- `solve [t_1, ... t_n]` applies the first tactic that solves the main goal. -/ meta def solve (ts : list (tactic unit)) : tactic unit := first $ map solve1 ts private meta def focus_aux : list (tactic unit) → list expr → list expr → tactic unit | [] [] rs := set_goals rs | (t::ts) [] rs := fail "focus tactic failed, insufficient number of goals" | tts (g::gs) rs := mcond (is_assigned g) (focus_aux tts gs rs) $ do set_goals [g], t::ts ← pure tts | fail "focus tactic failed, insufficient number of tactics", t, rs' ← get_goals, focus_aux ts gs (rs ++ rs') /-- `focus [t_1, ..., t_n]` applies t_i to the i-th goal. Fails if the number of goals is not n. -/ meta def focus (ts : list (tactic unit)) : tactic unit := do gs ← get_goals, focus_aux ts gs [] meta def focus1 {α} (tac : tactic α) : tactic α := do g::gs ← get_goals, match gs with | [] := tac | _ := do set_goals [g], a ← tac, gs' ← get_goals, set_goals (gs' ++ gs), return a end private meta def all_goals_core (tac : tactic unit) : list expr → list expr → tactic unit | [] ac := set_goals ac | (g :: gs) ac := mcond (is_assigned g) (all_goals_core gs ac) $ do set_goals [g], tac, new_gs ← get_goals, all_goals_core gs (ac ++ new_gs) /-- Apply the given tactic to all goals. -/ meta def all_goals (tac : tactic unit) : tactic unit := do gs ← get_goals, all_goals_core tac gs [] private meta def any_goals_core (tac : tactic unit) : list expr → list expr → bool → tactic unit | [] ac progress := guard progress >> set_goals ac | (g :: gs) ac progress := mcond (is_assigned g) (any_goals_core gs ac progress) $ do set_goals [g], succeeded ← try_core tac, new_gs ← get_goals, any_goals_core gs (ac ++ new_gs) (succeeded.is_some || progress) /-- Apply the given tactic to any goal where it succeeds. The tactic succeeds only if tac succeeds for at least one goal. -/ meta def any_goals (tac : tactic unit) : tactic unit := do gs ← get_goals, any_goals_core tac gs [] ff /-- LCF-style AND_THEN tactic. It applies tac1, and if succeed applies tac2 to each subgoal produced by tac1 -/ meta def seq (tac1 : tactic unit) (tac2 : tactic unit) : tactic unit := do g::gs ← get_goals, set_goals [g], tac1, all_goals tac2, gs' ← get_goals, set_goals (gs' ++ gs) meta def seq_focus (tac1 : tactic unit) (tacs2 : list (tactic unit)) : tactic unit := do g::gs ← get_goals, set_goals [g], tac1, focus tacs2, gs' ← get_goals, set_goals (gs' ++ gs) meta instance andthen_seq : has_andthen (tactic unit) (tactic unit) (tactic unit) := ⟨seq⟩ meta instance andthen_seq_focus : has_andthen (tactic unit) (list (tactic unit)) (tactic unit) := ⟨seq_focus⟩ meta constant is_trace_enabled_for : name → bool /-- Execute tac only if option trace.n is set to true. -/ meta def when_tracing (n : name) (tac : tactic unit) : tactic unit := when (is_trace_enabled_for n = tt) tac /-- Fail if there are no remaining goals. -/ meta def fail_if_no_goals : tactic unit := do n ← num_goals, when (n = 0) (fail "tactic failed, there are no goals to be solved") /-- Fail if there are unsolved goals. -/ meta def done : tactic unit := do n ← num_goals, when (n ≠ 0) (fail "done tactic failed, there are unsolved goals") meta def apply_opt_param : tactic unit := do `(opt_param %%t %%v) ← target, exact v meta def apply_auto_param : tactic unit := do `(auto_param %%type %%tac_name_expr) ← target, change type, tac_name ← eval_expr name tac_name_expr, tac ← eval_expr (tactic unit) (expr.const tac_name []), tac meta def has_opt_auto_param (ms : list expr) : tactic bool := ms.mfoldl (λ r m, do type ← infer_type m, return $ r || type.is_napp_of `opt_param 2 || type.is_napp_of `auto_param 2) ff meta def try_apply_opt_auto_param (cfg : apply_cfg) (ms : list expr) : tactic unit := when (cfg.auto_param || cfg.opt_param) $ mwhen (has_opt_auto_param ms) $ do gs ← get_goals, ms.mmap' (λ m, mwhen (bnot <$> is_assigned m) $ set_goals [m] >> when cfg.opt_param (try apply_opt_param) >> when cfg.auto_param (try apply_auto_param)), set_goals gs meta def has_opt_auto_param_for_apply (ms : list (name × expr)) : tactic bool := ms.mfoldl (λ r m, do type ← infer_type m.2, return $ r || type.is_napp_of `opt_param 2 || type.is_napp_of `auto_param 2) ff meta def try_apply_opt_auto_param_for_apply (cfg : apply_cfg) (ms : list (name × expr)) : tactic unit := mwhen (has_opt_auto_param_for_apply ms) $ do gs ← get_goals, ms.mmap' (λ m, mwhen (bnot <$> (is_assigned m.2)) $ set_goals [m.2] >> when cfg.opt_param (try apply_opt_param) >> when cfg.auto_param (try apply_auto_param)), set_goals gs meta def apply (e : expr) (cfg : apply_cfg := {}) : tactic (list (name × expr)) := do r ← apply_core e cfg, try_apply_opt_auto_param_for_apply cfg r, return r meta def fapply (e : expr) : tactic (list (name × expr)) := apply e {new_goals := new_goals.all} meta def eapply (e : expr) : tactic (list (name × expr)) := apply e {new_goals := new_goals.non_dep_only} /-- Try to solve the main goal using type class resolution. -/ meta def apply_instance : tactic unit := do tgt ← target >>= instantiate_mvars, b ← is_class tgt, if b then mk_instance tgt >>= exact else fail "apply_instance tactic fail, target is not a type class" /-- Create a list of universe meta-variables of the given size. -/ meta def mk_num_meta_univs : nat → tactic (list level) | 0 := return [] | (succ n) := do l ← mk_meta_univ, ls ← mk_num_meta_univs n, return (l::ls) /-- Return `expr.const c [l_1, ..., l_n]` where l_i's are fresh universe meta-variables. -/ meta def mk_const (c : name) : tactic expr := do env ← get_env, decl ← env.get c, let num := decl.univ_params.length, ls ← mk_num_meta_univs num, return (expr.const c ls) /-- Apply the constant `c` -/ meta def applyc (c : name) : tactic unit := do c ← mk_const c, apply c, skip meta def eapplyc (c : name) : tactic unit := do c ← mk_const c, eapply c, skip meta def save_const_type_info (n : name) {elab : bool} (ref : expr elab) : tactic unit := try (do c ← mk_const n, save_type_info c ref) /-- Create a fresh universe `?u`, a metavariable `?T : Type.{?u}`, and return metavariable `?M : ?T`. This action can be used to create a meta-variable when we don't know its type at creation time -/ meta def mk_mvar : tactic expr := do u ← mk_meta_univ, t ← mk_meta_var (expr.sort u), mk_meta_var t /-- Makes a sorry macro with a meta-variable as its type. -/ meta def mk_sorry : tactic expr := do u ← mk_meta_univ, t ← mk_meta_var (expr.sort u), return $ expr.mk_sorry t /-- Closes the main goal using sorry. -/ meta def «sorry» : tactic unit := target >>= exact ∘ expr.mk_sorry meta def mk_local' (pp_name : name) (bi : binder_info) (type : expr) : tactic expr := do uniq_name ← mk_fresh_name, return $ expr.local_const uniq_name pp_name bi type meta def mk_local_def (pp_name : name) (type : expr) : tactic expr := mk_local' pp_name binder_info.default type meta def mk_local_pis : expr → tactic (list expr × expr) | (expr.pi n bi d b) := do p ← mk_local' n bi d, (ps, r) ← mk_local_pis (expr.instantiate_var b p), return ((p :: ps), r) | e := return ([], e) private meta def get_pi_arity_aux : expr → tactic nat | (expr.pi n bi d b) := do m ← mk_fresh_name, let l := expr.local_const m n bi d, new_b ← whnf (expr.instantiate_var b l), r ← get_pi_arity_aux new_b, return (r + 1) | e := return 0 /-- Compute the arity of the given (Pi-)type -/ meta def get_pi_arity (type : expr) : tactic nat := whnf type >>= get_pi_arity_aux /-- Compute the arity of the given function -/ meta def get_arity (fn : expr) : tactic nat := infer_type fn >>= get_pi_arity meta def triv : tactic unit := mk_const `trivial >>= exact notation `dec_trivial` := of_as_true (by tactic.triv) meta def by_contradiction (H : option name := none) : tactic expr := do tgt : expr ← target, (match_not tgt >> return ()) <|> (mk_mapp `decidable.by_contradiction [some tgt, none] >>= eapply >> skip) <|> fail "tactic by_contradiction failed, target is not a negation nor a decidable proposition (remark: when 'local attribute classical.prop_decidable [instance]' is used all propositions are decidable)", match H with | some n := intro n | none := intro1 end private meta def generalizes_aux (md : transparency) : list expr → tactic unit | [] := skip | (e::es) := generalize e `x md >> generalizes_aux es meta def generalizes (es : list expr) (md := semireducible) : tactic unit := generalizes_aux md es private meta def kdependencies_core (e : expr) (md : transparency) : list expr → list expr → tactic (list expr) | [] r := return r | (h::hs) r := do type ← infer_type h, d ← kdepends_on type e md, if d then kdependencies_core hs (h::r) else kdependencies_core hs r /-- Return all hypotheses that depends on `e` The dependency test is performed using `kdepends_on` with the given transparency setting. -/ meta def kdependencies (e : expr) (md := reducible) : tactic (list expr) := do ctx ← local_context, kdependencies_core e md ctx [] /-- Revert all hypotheses that depend on `e` -/ meta def revert_kdependencies (e : expr) (md := reducible) : tactic nat := kdependencies e md >>= revert_lst meta def revert_kdeps (e : expr) (md := reducible) := revert_kdependencies e md /-- Similar to `cases_core`, but `e` doesn't need to be a hypothesis. Remark, it reverts dependencies using `revert_kdeps`. Two different transparency modes are used `md` and `dmd`. The mode `md` is used with `cases_core` and `dmd` with `generalize` and `revert_kdeps`. It returns the constructor names associated with each new goal. -/ meta def cases (e : expr) (ids : list name := []) (md := semireducible) (dmd := semireducible) : tactic (list name) := if e.is_local_constant then do r ← cases_core e ids md, return $ r.map (λ t, t.1) else do x ← mk_fresh_name, n ← revert_kdependencies e dmd, (tactic.generalize e x dmd) <|> (do t ← infer_type e, tactic.assertv x t e, get_local x >>= tactic.revert, return ()), h ← tactic.intro1, focus1 (do r ← cases_core h ids md, all_goals (intron n), return $ r.map (λ t, t.1)) meta def refine (e : pexpr) : tactic unit := do tgt : expr ← target, to_expr ``(%%e : %%tgt) tt >>= exact meta def by_cases (e : expr) (h : name) : tactic unit := do dec_e ← (mk_app `decidable [e] <|> fail "by_cases tactic failed, type is not a proposition"), inst ← (mk_instance dec_e <|> fail "by_cases tactic failed, type of given expression is not decidable"), t ← target, tm ← mk_mapp `dite [some e, some inst, some t], seq (apply tm >> skip) (intro h >> skip) meta def funext_core : list name → bool → tactic unit | [] tt := return () | ids only_ids := try $ do some (lhs, rhs) ← expr.is_eq <$> (target >>= whnf), applyc `funext, id ← if ids.empty ∨ ids.head = `_ then do (expr.lam n _ _ _) ← whnf lhs, return n else return ids.head, intro id, funext_core ids.tail only_ids meta def funext : tactic unit := funext_core [] ff meta def funext_lst (ids : list name) : tactic unit := funext_core ids tt private meta def get_undeclared_const (env : environment) (base : name) : ℕ → name | i := let n := base <.> ("_aux_" ++ repr i) in if ¬env.contains n then n else get_undeclared_const (i+1) meta def new_aux_decl_name : tactic name := do env ← get_env, n ← decl_name, return $ get_undeclared_const env n 1 private meta def mk_aux_decl_name : option name → tactic name | none := new_aux_decl_name | (some suffix) := do p ← decl_name, return $ p ++ suffix meta def abstract (tac : tactic unit) (suffix : option name := none) (zeta_reduce := tt) : tactic unit := do fail_if_no_goals, gs ← get_goals, type ← if zeta_reduce then target >>= zeta else target, is_lemma ← is_prop type, m ← mk_meta_var type, set_goals [m], tac, n ← num_goals, when (n ≠ 0) (fail "abstract tactic failed, there are unsolved goals"), set_goals gs, val ← instantiate_mvars m, val ← if zeta_reduce then zeta val else return val, c ← mk_aux_decl_name suffix, e ← add_aux_decl c type val is_lemma, exact e /-- `solve_aux type tac` synthesize an element of 'type' using tactic 'tac' -/ meta def solve_aux {α : Type} (type : expr) (tac : tactic α) : tactic (α × expr) := do m ← mk_meta_var type, gs ← get_goals, set_goals [m], a ← tac, set_goals gs, return (a, m) /-- Return tt iff 'd' is a declaration in one of the current open namespaces -/ meta def in_open_namespaces (d : name) : tactic bool := do ns ← open_namespaces, env ← get_env, return $ ns.any (λ n, n.is_prefix_of d) && env.contains d /-- Execute tac for 'max' "heartbeats". The heartbeat is approx. the maximum number of memory allocations (in thousands) performed by 'tac'. This is a deterministic way of interrupting long running tactics. -/ meta def try_for {α} (max : nat) (tac : tactic α) : tactic α := λ s, match _root_.try_for max (tac s) with | some r := r | none := mk_exception "try_for tactic failed, timeout" none s end meta def updateex_env (f : environment → exceptional environment) : tactic unit := do env ← get_env, env ← returnex $ f env, set_env env /- Add a new inductive datatype to the environment name, universe parameters, number of parameters, type, constructors (name and type), is_meta -/ meta def add_inductive (n : name) (ls : list name) (p : nat) (ty : expr) (is : list (name × expr)) (is_meta : bool := ff) : tactic unit := updateex_env $ λe, e.add_inductive n ls p ty is is_meta meta def add_meta_definition (n : name) (lvls : list name) (type value : expr) : tactic unit := add_decl (declaration.defn n lvls type value reducibility_hints.abbrev ff) meta def rename (curr : name) (new : name) : tactic unit := do h ← get_local curr, n ← revert h, intro new, intron (n - 1) /-- "Replace" hypothesis `h : type` with `h : new_type` where `eq_pr` is a proof that (type = new_type). The tactic actually creates a new hypothesis with the same user facing name, and (tries to) clear `h`. The `clear` step fails if `h` has forward dependencies. In this case, the old `h` will remain in the local context. The tactic returns the new hypothesis. -/ meta def replace_hyp (h : expr) (new_type : expr) (eq_pr : expr) : tactic expr := do h_type ← infer_type h, new_h ← assert h.local_pp_name new_type, mk_eq_mp eq_pr h >>= exact, try $ clear h, return new_h meta def main_goal : tactic expr := do g::gs ← get_goals, return g /- Goal tagging support -/ meta def with_enable_tags {α : Type} (t : tactic α) (b := tt) : tactic α := do old ← tags_enabled, enable_tags b, r ← t, enable_tags old, return r meta def get_main_tag : tactic tag := main_goal >>= get_tag meta def set_main_tag (t : tag) : tactic unit := do g ← main_goal, set_tag g t end tactic notation [parsing_only] `command`:max := tactic unit open tactic namespace list meta def for_each {α} : list α → (α → tactic unit) → tactic unit | [] fn := skip | (e::es) fn := do fn e, for_each es fn meta def any_of {α β} : list α → (α → tactic β) → tactic β | [] fn := failed | (e::es) fn := do opt_b ← try_core (fn e), match opt_b with | some b := return b | none := any_of es fn end end list /- Install monad laws tactic and use it to prove some instances. -/ meta def control_laws_tac := whnf_target >> intros >> to_expr ``(rfl) >>= exact meta def order_laws_tac := whnf_target >> intros >> to_expr ``(iff.refl _) >>= exact meta def unsafe_monad_from_pure_bind {m : Type u → Type v} (pure : Π {α : Type u}, α → m α) (bind : Π {α β : Type u}, m α → (α → m β) → m β) : monad m := {pure := @pure, bind := @bind, id_map := undefined, pure_bind := undefined, bind_assoc := undefined} meta instance : monad task := {map := @task.map, bind := @task.bind, pure := @task.pure, id_map := undefined, pure_bind := undefined, bind_assoc := undefined, bind_pure_comp_eq_map := undefined} namespace tactic meta def mk_id_proof (prop : expr) (pr : expr) : expr := expr.app (expr.app (expr.const ``id [level.zero]) prop) pr meta def mk_id_eq (lhs : expr) (rhs : expr) (pr : expr) : tactic expr := do prop ← mk_app `eq [lhs, rhs], return $ mk_id_proof prop pr meta def replace_target (new_target : expr) (pr : expr) : tactic unit := do t ← target, assert `htarget new_target, swap, ht ← get_local `htarget, locked_pr ← mk_id_eq t new_target pr, mk_eq_mpr locked_pr ht >>= exact end tactic
2c58c42b852075756616367b7b86727d4802eaeb
4727251e0cd73359b15b664c3170e5d754078599
/src/deprecated/subfield.lean
f6bce8e4397b04b1ee8a9180ffe893164dab1166
[ "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
5,784
lean
/- Copyright (c) 2018 Andreas Swerdlow. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Andreas Swerdlow -/ import deprecated.subring import algebra.group_with_zero.power /- # Unbundled subfields This file introduces the predicate `is_subfield` on `S : set F` where `F` is a field. This is *not* the preferred way to do subfields in Lean 3: in general `S : subfield F` works more smoothly. ## Main definitions `is_subfield (S : set F)` : the predicate that `S` is the underlying set of a subfield of the field `F`. Note that the bundled variant `subfield F` is preferred to this approach. ## Tags is_subfield -/ variables {F : Type*} [field F] (S : set F) structure is_subfield extends is_subring S : Prop := (inv_mem : ∀ {x : F}, x ∈ S → x⁻¹ ∈ S) lemma is_subfield.div_mem {S : set F} (hS : is_subfield S) {x y : F} (hx : x ∈ S) (hy : y ∈ S) : x / y ∈ S := by { rw div_eq_mul_inv, exact hS.to_is_subring.to_is_submonoid.mul_mem hx (hS.inv_mem hy) } lemma is_subfield.pow_mem {a : F} {n : ℤ} {s : set F} (hs : is_subfield s) (h : a ∈ s) : a ^ n ∈ s := begin cases n, { rw zpow_of_nat, exact hs.to_is_subring.to_is_submonoid.pow_mem h }, { rw zpow_neg_succ_of_nat, exact hs.inv_mem (hs.to_is_subring.to_is_submonoid.pow_mem h) }, end lemma univ.is_subfield : is_subfield (@set.univ F) := { inv_mem := by intros; trivial, ..univ.is_submonoid, ..is_add_subgroup.univ_add_subgroup } lemma preimage.is_subfield {K : Type*} [field K] (f : F →+* K) {s : set K} (hs : is_subfield s) : is_subfield (f ⁻¹' s) := { inv_mem := λ a (ha : f a ∈ s), show f a⁻¹ ∈ s, by { rw [f.map_inv], exact hs.inv_mem ha }, ..f.is_subring_preimage hs.to_is_subring } lemma image.is_subfield {K : Type*} [field K] (f : F →+* K) {s : set F} (hs : is_subfield s) : is_subfield (f '' s) := { inv_mem := λ a ⟨x, xmem, ha⟩, ⟨x⁻¹, hs.inv_mem xmem, ha ▸ f.map_inv _⟩, ..f.is_subring_image hs.to_is_subring } lemma range.is_subfield {K : Type*} [field K] (f : F →+* K) : is_subfield (set.range f) := by { rw ← set.image_univ, apply image.is_subfield _ univ.is_subfield } namespace field /-- `field.closure s` is the minimal subfield that includes `s`. -/ def closure : set F := { x | ∃ y ∈ ring.closure S, ∃ z ∈ ring.closure S, y / z = x } variables {S} theorem ring_closure_subset : ring.closure S ⊆ closure S := λ x hx, ⟨x, hx, 1, ring.closure.is_subring.to_is_submonoid.one_mem, div_one x⟩ lemma closure.is_submonoid : is_submonoid (closure S) := { mul_mem := by rintros _ _ ⟨p, hp, q, hq, hq0, rfl⟩ ⟨r, hr, s, hs, hs0, rfl⟩; exact ⟨p * r, is_submonoid.mul_mem ring.closure.is_subring.to_is_submonoid hp hr, q * s, is_submonoid.mul_mem ring.closure.is_subring.to_is_submonoid hq hs, (div_mul_div_comm _ _ _ _).symm⟩, one_mem := ring_closure_subset $ is_submonoid.one_mem ring.closure.is_subring.to_is_submonoid } lemma closure.is_subfield : is_subfield (closure S) := have h0 : (0:F) ∈ closure S, from ring_closure_subset $ ring.closure.is_subring.to_is_add_subgroup.to_is_add_submonoid.zero_mem, { add_mem := begin intros a b ha hb, rcases (id ha) with ⟨p, hp, q, hq, rfl⟩, rcases (id hb) with ⟨r, hr, s, hs, rfl⟩, classical, by_cases hq0 : q = 0, by simp [hb, hq0], by_cases hs0 : s = 0, by simp [ha, hs0], exact ⟨p * s + q * r, is_add_submonoid.add_mem ring.closure.is_subring.to_is_add_subgroup.to_is_add_submonoid (ring.closure.is_subring.to_is_submonoid.mul_mem hp hs) (ring.closure.is_subring.to_is_submonoid.mul_mem hq hr), q * s, ring.closure.is_subring.to_is_submonoid.mul_mem hq hs, (div_add_div p r hq0 hs0).symm⟩ end, zero_mem := h0, neg_mem := begin rintros _ ⟨p, hp, q, hq, rfl⟩, exact ⟨-p, ring.closure.is_subring.to_is_add_subgroup.neg_mem hp, q, hq, neg_div q p⟩ end, inv_mem := begin rintros _ ⟨p, hp, q, hq, rfl⟩, exact ⟨q, hq, p, hp, (inv_div _ _).symm⟩ end, ..closure.is_submonoid } theorem mem_closure {a : F} (ha : a ∈ S) : a ∈ closure S := ring_closure_subset $ ring.mem_closure ha theorem subset_closure : S ⊆ closure S := λ _, mem_closure theorem closure_subset {T : set F} (hT : is_subfield T) (H : S ⊆ T) : closure S ⊆ T := by rintros _ ⟨p, hp, q, hq, hq0, rfl⟩; exact hT.div_mem (ring.closure_subset hT.to_is_subring H hp) (ring.closure_subset hT.to_is_subring H hq) theorem closure_subset_iff {s t : set F} (ht : is_subfield t) : closure s ⊆ t ↔ s ⊆ t := ⟨set.subset.trans subset_closure, closure_subset ht⟩ theorem closure_mono {s t : set F} (H : s ⊆ t) : closure s ⊆ closure t := closure_subset closure.is_subfield $ set.subset.trans H subset_closure end field lemma is_subfield_Union_of_directed {ι : Type*} [hι : nonempty ι] {s : ι → set F} (hs : ∀ i, is_subfield (s i)) (directed : ∀ i j, ∃ k, s i ⊆ s k ∧ s j ⊆ s k) : is_subfield (⋃i, s i) := { inv_mem := λ x hx, let ⟨i, hi⟩ := set.mem_Union.1 hx in set.mem_Union.2 ⟨i, (hs i).inv_mem hi⟩, to_is_subring := is_subring_Union_of_directed (λ i, (hs i).to_is_subring) directed } lemma is_subfield.inter {S₁ S₂ : set F} (hS₁ : is_subfield S₁) (hS₂ : is_subfield S₂) : is_subfield (S₁ ∩ S₂) := { inv_mem := λ x hx, ⟨hS₁.inv_mem hx.1, hS₂.inv_mem hx.2⟩, ..is_subring.inter hS₁.to_is_subring hS₂.to_is_subring } lemma is_subfield.Inter {ι : Sort*} {S : ι → set F} (h : ∀ y : ι, is_subfield (S y)) : is_subfield (set.Inter S) := { inv_mem := λ x hx, set.mem_Inter.2 $ λ y, (h y).inv_mem $ set.mem_Inter.1 hx y, ..is_subring.Inter (λ y, (h y).to_is_subring) }
473d38fb3f49f585610d94a5c3d9d0b2cdfb0127
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
/src/Lean/Meta/GeneralizeTelescope.lean
719c01560b8d1c190b2cd40fd85006082c1eb3e3
[ "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
3,863
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.KAbstract namespace Lean.Meta namespace GeneralizeTelescope structure Entry where expr : Expr type : Expr modified : Bool partial def updateTypes (e eNew : Expr) (entries : Array Entry) (i : Nat) : MetaM (Array Entry) := if h : i < entries.size then let entry := entries.get ⟨i, h⟩ match entry with | ⟨_, type, _⟩ => do let typeAbst ← kabstract type e if typeAbst.hasLooseBVars then do let typeNew := typeAbst.instantiate1 eNew let entries := entries.set ⟨i, h⟩ { entry with type := typeNew, modified := true } updateTypes e eNew entries (i+1) else updateTypes e eNew entries (i+1) else pure entries partial def generalizeTelescopeAux {α} (k : Array Expr → MetaM α) (entries : Array Entry) (i : Nat) (fvars : Array Expr) : MetaM α := do if h : i < entries.size then let replace (baseUserName : Name) (e : Expr) (type : Expr) : MetaM α := do let userName ← mkFreshUserName baseUserName withLocalDeclD userName type fun x => do let entries ← updateTypes e x entries (i+1) generalizeTelescopeAux k entries (i+1) (fvars.push x) match entries.get ⟨i, h⟩ with | ⟨e@(Expr.fvar fvarId _), type, false⟩ => let localDecl ← getLocalDecl fvarId match localDecl with | LocalDecl.cdecl .. => generalizeTelescopeAux k entries (i+1) (fvars.push e) | LocalDecl.ldecl .. => replace localDecl.userName e type | ⟨e, type, modified⟩ => if modified then unless (← isTypeCorrect type) do throwError "failed to create telescope generalizing {entries.map Entry.expr}" replace `x e type else k fvars end GeneralizeTelescope open GeneralizeTelescope /-- Given expressions `es := #[e_1, e_2, ..., e_n]`, execute `k` with the free variables `(x_1 : A_1) (x_2 : A_2 [x_1]) ... (x_n : A_n [x_1, ... x_{n-1}])`. Moreover, - type of `e_1` is definitionally equal to `A_1`, - type of `e_2` is definitionally equal to `A_2[e_1]`. - ... - type of `e_n` is definitionally equal to `A_n[e_1, ..., e_{n-1}]`. This method tries to avoid the creation of new free variables. For example, if `e_i` is a free variable `x_i` and it is not a let-declaration variable, and its type does not depend on previous `e_j`s, the method will just use `x_i`. The telescope `x_1 ... x_n` can be used to create lambda and forall abstractions. Moreover, for any type correct lambda abstraction `f` constructed using `mkForall #[x_1, ..., x_n] ...`, The application `f e_1 ... e_n` is also type correct. The `kabstract` method is used to "locate" and abstract forward dependencies. That is, an occurrence of `e_i` in the of `e_j` for `j > i`. The method checks whether the abstract types `A_i` are type correct. Here is an example where `generalizeTelescope` fails to create the telescope `x_1 ... x_n`. Assume the local context contains `(n : Nat := 10) (xs : Vec Nat n) (ys : Vec Nat 10) (h : xs = ys)`. Then, assume we invoke `generalizeTelescope` with `es := #[10, xs, ys, h]` A type error is detected when processing `h`'s type. At this point, the method had successfully produced ``` (x_1 : Nat) (xs : Vec Nat n) (x_2 : Vec Nat x_1) ``` and the type for the new variable abstracting `h` is `xs = x_2` which is not type correct. -/ def generalizeTelescope {α} (es : Array Expr) (k : Array Expr → MetaM α) : MetaM α := do let es ← es.mapM fun e => do let type ← inferType e let type ← instantiateMVars type pure { expr := e, type := type, modified := false : Entry } generalizeTelescopeAux k es 0 #[] end Lean.Meta
7948a321ffa5fdfe958606ae9a1166050eb84d1a
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/order/extension.lean
ac1176a7c828837bc07163d8d2a49bda74026f09
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
3,902
lean
/- Copyright (c) 2021 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta -/ import data.set.lattice import order.zorn /-! # Extend a partial order to a linear order This file constructs a linear order which is an extension of the given partial order, using Zorn's lemma. -/ universes u open set classical open_locale classical /-- Any partial order can be extended to a linear order. -/ theorem extend_partial_order {α : Type u} (r : α → α → Prop) [is_partial_order α r] : ∃ (s : α → α → Prop) [is_linear_order α s], r ≤ s := begin let S := {s | is_partial_order α s}, have hS : ∀ c, c ⊆ S → zorn.chain (≤) c → ∀ y ∈ c, (∃ ub ∈ S, ∀ z ∈ c, z ≤ ub), { rintro c hc₁ hc₂ s hs, haveI := (hc₁ hs).1, refine ⟨Sup c, _, λ z hz, le_Sup hz⟩, refine { refl := _, trans := _, antisymm := _ }; simp_rw binary_relation_Sup_iff, { intro x, exact ⟨s, hs, refl x⟩ }, { rintro x y z ⟨s₁, h₁s₁, h₂s₁⟩ ⟨s₂, h₁s₂, h₂s₂⟩, haveI : is_partial_order _ _ := hc₁ h₁s₁, haveI : is_partial_order _ _ := hc₁ h₁s₂, cases hc₂.total_of_refl h₁s₁ h₁s₂, { exact ⟨s₂, h₁s₂, trans (h _ _ h₂s₁) h₂s₂⟩ }, { exact ⟨s₁, h₁s₁, trans h₂s₁ (h _ _ h₂s₂)⟩ } }, { rintro x y ⟨s₁, h₁s₁, h₂s₁⟩ ⟨s₂, h₁s₂, h₂s₂⟩, haveI : is_partial_order _ _ := hc₁ h₁s₁, haveI : is_partial_order _ _ := hc₁ h₁s₂, cases hc₂.total_of_refl h₁s₁ h₁s₂, { exact antisymm (h _ _ h₂s₁) h₂s₂ }, { apply antisymm h₂s₁ (h _ _ h₂s₂) } } }, obtain ⟨s, hs₁ : is_partial_order _ _, rs, hs₂⟩ := zorn.zorn_nonempty_partial_order₀ S hS r ‹_›, resetI, refine ⟨s, { total := _ }, rs⟩, intros x y, by_contra h, push_neg at h, let s' := λ x' y', s x' y' ∨ s x' x ∧ s y y', rw ←hs₂ s' _ (λ _ _, or.inl) at h, { apply h.1 (or.inr ⟨refl _, refl _⟩) }, { refine { refl := λ x, or.inl (refl _), trans := _, antisymm := _ }, { rintro a b c (ab | ⟨ax : s a x, yb : s y b⟩) (bc | ⟨bx : s b x, yc : s y c⟩), { exact or.inl (trans ab bc), }, { exact or.inr ⟨trans ab bx, yc⟩ }, { exact or.inr ⟨ax, trans yb bc⟩ }, { exact or.inr ⟨ax, yc⟩ } }, { rintro a b (ab | ⟨ax : s a x, yb : s y b⟩) (ba | ⟨bx : s b x, ya : s y a⟩), { exact antisymm ab ba }, { exact (h.2 (trans ya (trans ab bx))).elim }, { exact (h.2 (trans yb (trans ba ax))).elim }, { exact (h.2 (trans yb bx)).elim } } }, end /-- A type alias for `α`, intended to extend a partial order on `α` to a linear order. -/ def linear_extension (α : Type u) : Type u := α noncomputable instance {α : Type u} [partial_order α] : linear_order (linear_extension α) := { le := (extend_partial_order ((≤) : α → α → Prop)).some, le_refl := (extend_partial_order ((≤) : α → α → Prop)).some_spec.some.1.1.1.1, le_trans := (extend_partial_order ((≤) : α → α → Prop)).some_spec.some.1.1.2.1, le_antisymm := (extend_partial_order ((≤) : α → α → Prop)).some_spec.some.1.2.1, le_total := (extend_partial_order ((≤) : α → α → Prop)).some_spec.some.2.1, decidable_le := classical.dec_rel _ } /-- The embedding of `α` into `linear_extension α` as a relation homomorphism. -/ def to_linear_extension {α : Type u} [partial_order α] : ((≤) : α → α → Prop) →r ((≤) : linear_extension α → linear_extension α → Prop) := { to_fun := λ x, x, map_rel' := λ a b, (extend_partial_order ((≤) : α → α → Prop)).some_spec.some_spec _ _ } instance {α : Type u} [inhabited α] : inhabited (linear_extension α) := ⟨(default _ : α)⟩
29a13c87a55c3ee506128e3e476a9d9c243ee4b7
432d948a4d3d242fdfb44b81c9e1b1baacd58617
/src/data/polynomial/derivative.lean
1544b21a5dbceed8efd7e52aeae940d6a82d474a
[ "Apache-2.0" ]
permissive
JLimperg/aesop3
306cc6570c556568897ed2e508c8869667252e8a
a4a116f650cc7403428e72bd2e2c4cda300fe03f
refs/heads/master
1,682,884,916,368
1,620,320,033,000
1,620,320,033,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
13,824
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Johannes Hölzl, Scott Morrison, Jens Wagemaker -/ import data.polynomial.eval import algebra.iterate_hom /-! # The derivative map on polynomials ## Main definitions * `polynomial.derivative`: The formal derivative of polynomials, expressed as a linear map. -/ noncomputable theory local attribute [instance, priority 100] classical.prop_decidable open finsupp finset open_locale big_operators namespace polynomial universes u v w y z variables {R : Type u} {S : Type v} {T : Type w} {ι : Type y} {A : Type z} {a b : R} {n : ℕ} section derivative section semiring variables [semiring R] /-- `derivative p` is the formal derivative of the polynomial `p` -/ def derivative : polynomial R →ₗ[R] polynomial R := finsupp.total ℕ (polynomial R) R (λ n, C ↑n * X^(n - 1)) lemma derivative_apply (p : polynomial R) : derivative p = p.sum (λn a, C (a * n) * X^(n - 1)) := begin rw [derivative, total_apply], apply congr rfl, ext, simp [mul_assoc, coeff_C_mul], end lemma coeff_derivative (p : polynomial R) (n : ℕ) : coeff (derivative p) n = coeff p (n + 1) * (n + 1) := begin rw [derivative_apply], simp only [coeff_X_pow, coeff_sum, coeff_C_mul], rw [sum_def, finset.sum_eq_single (n + 1)], simp only [nat.add_succ_sub_one, add_zero, mul_one, if_true, eq_self_iff_true], norm_cast, swap, { rw [if_pos (nat.add_sub_cancel _ _).symm, mul_one, nat.cast_add, nat.cast_one, mem_support_iff], intro h, push_neg at h, simp [h], }, { assume b, cases b, { intros, rw [nat.cast_zero, mul_zero, zero_mul], }, { intros _ H, rw [nat.succ_sub_one b, if_neg (mt (congr_arg nat.succ) H.symm), mul_zero] } } end @[simp] lemma derivative_zero : derivative (0 : polynomial R) = 0 := derivative.map_zero @[simp] lemma iterate_derivative_zero {k : ℕ} : derivative^[k] (0 : polynomial R) = 0 := begin induction k with k ih, { simp, }, { simp [ih], }, end @[simp] lemma derivative_monomial (a : R) (n : ℕ) : derivative (monomial n a) = monomial (n - 1) (a * n) := (derivative_apply _).trans ((sum_single_index $ by simp).trans (C_mul_X_pow_eq_monomial _ _)) lemma derivative_C_mul_X_pow (a : R) (n : ℕ) : derivative (C a * X ^ n) = C (a * n) * X^(n - 1) := by rw [C_mul_X_pow_eq_monomial, C_mul_X_pow_eq_monomial, derivative_monomial] @[simp] lemma derivative_X_pow (n : ℕ) : derivative (X ^ n : polynomial R) = (n : polynomial R) * X ^ (n - 1) := by convert derivative_C_mul_X_pow (1 : R) n; simp @[simp] lemma derivative_C {a : R} : derivative (C a) = 0 := by simp [derivative_apply] @[simp] lemma derivative_X : derivative (X : polynomial R) = 1 := (derivative_monomial _ _).trans $ by simp @[simp] lemma derivative_one : derivative (1 : polynomial R) = 0 := derivative_C @[simp] lemma derivative_bit0 {a : polynomial R} : derivative (bit0 a) = bit0 (derivative a) := by simp [bit0] @[simp] lemma derivative_bit1 {a : polynomial R} : derivative (bit1 a) = bit0 (derivative a) := by simp [bit1] @[simp] lemma derivative_add {f g : polynomial R} : derivative (f + g) = derivative f + derivative g := derivative.map_add f g @[simp] lemma iterate_derivative_add {f g : polynomial R} {k : ℕ} : derivative^[k] (f + g) = (derivative^[k] f) + (derivative^[k] g) := derivative.to_add_monoid_hom.iterate_map_add _ _ _ @[simp] lemma derivative_neg {R : Type*} [ring R] (f : polynomial R) : derivative (-f) = - derivative f := linear_map.map_neg derivative f @[simp] lemma iterate_derivative_neg {R : Type*} [ring R] {f : polynomial R} {k : ℕ} : derivative^[k] (-f) = - (derivative^[k] f) := (@derivative R _).to_add_monoid_hom.iterate_map_neg _ _ @[simp] lemma derivative_sub {R : Type*} [ring R] {f g : polynomial R} : derivative (f - g) = derivative f - derivative g := linear_map.map_sub derivative f g @[simp] lemma iterate_derivative_sub {R : Type*} [ring R] {k : ℕ} {f g : polynomial R} : derivative^[k] (f - g) = (derivative^[k] f) - (derivative^[k] g) := begin induction k with k ih generalizing f g, { simp [nat.iterate], }, { simp [nat.iterate, ih], } end @[simp] lemma derivative_sum {s : finset ι} {f : ι → polynomial R} : derivative (∑ b in s, f b) = ∑ b in s, derivative (f b) := derivative.map_sum @[simp] lemma derivative_smul (r : R) (p : polynomial R) : derivative (r • p) = r • derivative p := derivative.map_smul _ _ @[simp] lemma iterate_derivative_smul (r : R) (p : polynomial R) (k : ℕ) : derivative^[k] (r • p) = r • (derivative^[k] p) := begin induction k with k ih generalizing p, { simp, }, { simp [ih], }, end /-- We can't use `derivative_mul` here because we want to prove this statement also for noncommutative rings.-/ @[simp] lemma derivative_C_mul (a : R) (p : polynomial R) : derivative (C a * p) = C a * derivative p := by convert derivative_smul a p; apply C_mul' @[simp] lemma iterate_derivative_C_mul (a : R) (p : polynomial R) (k : ℕ) : derivative^[k] (C a * p) = C a * (derivative^[k] p) := by convert iterate_derivative_smul a p k; apply C_mul' end semiring section comm_semiring variables [comm_semiring R] lemma derivative_eval (p : polynomial R) (x : R) : p.derivative.eval x = p.sum (λ n a, (a * n)*x^(n-1)) := by simp only [derivative_apply, eval_sum, eval_pow, eval_C, eval_X, eval_nat_cast, eval_mul] @[simp] lemma derivative_mul {f g : polynomial R} : derivative (f * g) = derivative f * g + f * derivative g := calc derivative (f * g) = f.sum (λn a, g.sum (λm b, C ((a * b) * (n + m : ℕ)) * X^((n + m) - 1))) : begin transitivity, exact derivative_sum, transitivity, { apply finset.sum_congr rfl, assume x hx, exact derivative_sum }, apply finset.sum_congr rfl, assume n hn, apply finset.sum_congr rfl, assume m hm, transitivity, { apply congr_arg, exact single_eq_C_mul_X }, exact derivative_C_mul_X_pow _ _ end ... = f.sum (λn a, g.sum (λm b, (C (a * n) * X^(n - 1)) * (C b * X^m) + (C a * X^n) * (C (b * m) * X^(m - 1)))) : sum_congr rfl $ assume n hn, sum_congr rfl $ assume m hm, by simp only [nat.cast_add, mul_add, add_mul, C_add, C_mul]; cases n; simp only [nat.succ_sub_succ, pow_zero]; cases m; simp only [nat.cast_zero, C_0, nat.succ_sub_succ, zero_mul, mul_zero, nat.sub_zero, pow_zero, pow_add, one_mul, pow_succ, mul_comm, mul_left_comm] ... = derivative f * g + f * derivative g : begin conv { to_rhs, congr, { rw [← sum_C_mul_X_eq g] }, { rw [← sum_C_mul_X_eq f] } }, simp only [finsupp.sum, sum_add_distrib, finset.mul_sum, finset.sum_mul, derivative_apply] end theorem derivative_pow_succ (p : polynomial R) (n : ℕ) : (p ^ (n + 1)).derivative = (n + 1) * (p ^ n) * p.derivative := nat.rec_on n (by rw [pow_one, nat.cast_zero, zero_add, one_mul, pow_zero, one_mul]) $ λ n ih, by rw [pow_succ', derivative_mul, ih, mul_right_comm, ← add_mul, add_mul (n.succ : polynomial R), one_mul, pow_succ', mul_assoc, n.cast_succ] theorem derivative_pow (p : polynomial R) (n : ℕ) : (p ^ n).derivative = n * (p ^ (n - 1)) * p.derivative := nat.cases_on n (by rw [pow_zero, derivative_one, nat.cast_zero, zero_mul, zero_mul]) $ λ n, by rw [p.derivative_pow_succ n, n.succ_sub_one, n.cast_succ] lemma derivative_comp (p q : polynomial R) : (p.comp q).derivative = q.derivative * p.derivative.comp q := begin apply polynomial.induction_on' p, { intros p₁ p₂ h₁ h₂, simp [h₁, h₂, mul_add], }, { intros n r, simp only [derivative_pow, derivative_mul, monomial_comp, derivative_monomial, derivative_C, zero_mul, C_eq_nat_cast, zero_add, ring_hom.map_mul], -- is there a tactic for this? (a multiplicative `abel`): rw [mul_comm (derivative q)], simp only [mul_assoc], } end @[simp] theorem derivative_map [comm_semiring S] (p : polynomial R) (f : R →+* S) : (p.map f).derivative = p.derivative.map f := polynomial.induction_on p (λ r, by rw [map_C, derivative_C, derivative_C, map_zero]) (λ p q ihp ihq, by rw [map_add, derivative_add, ihp, ihq, derivative_add, map_add]) (λ n r ih, by rw [map_mul, map_C, map_pow, map_X, derivative_mul, derivative_pow_succ, derivative_C, zero_mul, zero_add, derivative_X, mul_one, derivative_mul, derivative_pow_succ, derivative_C, zero_mul, zero_add, derivative_X, mul_one, map_mul, map_C, map_mul, map_pow, map_add, map_nat_cast, map_one, map_X]) @[simp] theorem iterate_derivative_map [comm_semiring S] (p : polynomial R) (f : R →+* S) (k : ℕ): polynomial.derivative^[k] (p.map f) = (polynomial.derivative^[k] p).map f := begin induction k with k ih generalizing p, { simp, }, { simp [ih], }, end /-- Chain rule for formal derivative of polynomials. -/ theorem derivative_eval₂_C (p q : polynomial R) : (p.eval₂ C q).derivative = p.derivative.eval₂ C q * q.derivative := polynomial.induction_on p (λ r, by rw [eval₂_C, derivative_C, eval₂_zero, zero_mul]) (λ p₁ p₂ ih₁ ih₂, by rw [eval₂_add, derivative_add, ih₁, ih₂, derivative_add, eval₂_add, add_mul]) (λ n r ih, by rw [pow_succ', ← mul_assoc, eval₂_mul, eval₂_X, derivative_mul, ih, @derivative_mul _ _ _ X, derivative_X, mul_one, eval₂_add, @eval₂_mul _ _ _ _ X, eval₂_X, add_mul, mul_right_comm]) theorem of_mem_support_derivative {p : polynomial R} {n : ℕ} (h : n ∈ p.derivative.support) : n + 1 ∈ p.support := finsupp.mem_support_iff.2 $ λ (h1 : p.coeff (n+1) = 0), finsupp.mem_support_iff.1 h $ show p.derivative.coeff n = 0, by rw [coeff_derivative, h1, zero_mul] theorem degree_derivative_lt {p : polynomial R} (hp : p ≠ 0) : p.derivative.degree < p.degree := (finset.sup_lt_iff $ bot_lt_iff_ne_bot.2 $ mt degree_eq_bot.1 hp).2 $ λ n hp, lt_of_lt_of_le (with_bot.some_lt_some.2 n.lt_succ_self) $ finset.le_sup $ of_mem_support_derivative hp theorem nat_degree_derivative_lt {p : polynomial R} (hp : p.derivative ≠ 0) : p.derivative.nat_degree < p.nat_degree := have hp1 : p ≠ 0, from λ h, hp $ by rw [h, derivative_zero], with_bot.some_lt_some.1 $ begin rw [nat_degree, option.get_or_else_of_ne_none $ mt degree_eq_bot.1 hp, nat_degree, option.get_or_else_of_ne_none $ mt degree_eq_bot.1 hp1], exact degree_derivative_lt hp1 end theorem degree_derivative_le {p : polynomial R} : p.derivative.degree ≤ p.degree := if H : p = 0 then le_of_eq $ by rw [H, derivative_zero] else le_of_lt $ degree_derivative_lt H /-- The formal derivative of polynomials, as linear homomorphism. -/ def derivative_lhom (R : Type*) [comm_ring R] : polynomial R →ₗ[R] polynomial R := { to_fun := derivative, map_add' := λ p q, derivative_add, map_smul' := λ r p, derivative_smul r p } @[simp] lemma derivative_lhom_coe {R : Type*} [comm_ring R] : (polynomial.derivative_lhom R : polynomial R → polynomial R) = polynomial.derivative := rfl @[simp] lemma derivative_cast_nat {n : ℕ} : derivative (n : polynomial R) = 0 := begin rw ← C.map_nat_cast n, exact derivative_C, end @[simp] lemma iterate_derivative_cast_nat_mul {n k : ℕ} {f : polynomial R} : derivative^[k] (n * f) = n * (derivative^[k] f) := begin induction k with k ih generalizing f, { simp [nat.iterate], }, { simp [nat.iterate, ih], } end end comm_semiring section comm_ring variables [comm_ring R] lemma derivative_comp_one_sub_X (p : polynomial R) : (p.comp (1-X)).derivative = -p.derivative.comp (1-X) := by simp [derivative_comp] @[simp] lemma iterate_derivative_comp_one_sub_X (p : polynomial R) (k : ℕ) : derivative^[k] (p.comp (1-X)) = (-1)^k * (derivative^[k] p).comp (1-X) := begin induction k with k ih generalizing p, { simp, }, { simp [ih p.derivative, iterate_derivative_neg, derivative_comp, pow_succ], }, end end comm_ring section domain variables [integral_domain R] lemma mem_support_derivative [char_zero R] (p : polynomial R) (n : ℕ) : n ∈ (derivative p).support ↔ n + 1 ∈ p.support := suffices (¬(coeff p (n + 1) = 0 ∨ ((n + 1:ℕ) : R) = 0)) ↔ coeff p (n + 1) ≠ 0, by simpa only [mem_support_iff, coeff_derivative, ne.def, mul_eq_zero], by { rw [nat.cast_eq_zero], simp only [nat.succ_ne_zero, or_false] } @[simp] lemma degree_derivative_eq [char_zero R] (p : polynomial R) (hp : 0 < nat_degree p) : degree (derivative p) = (nat_degree p - 1 : ℕ) := begin have h0 : p ≠ 0, { contrapose! hp, simp [hp] }, apply le_antisymm, { rw derivative_apply, apply le_trans (degree_sum_le _ _) (sup_le (λ n hn, _)), apply le_trans (degree_C_mul_X_pow_le _ _) (with_bot.coe_le_coe.2 (nat.sub_le_sub_right _ _)), apply le_nat_degree_of_mem_supp _ hn }, { refine le_sup _, rw [mem_support_derivative, nat.sub_add_cancel, mem_support_iff], { show ¬ leading_coeff p = 0, rw [leading_coeff_eq_zero], assume h, rw [h, nat_degree_zero] at hp, exact lt_irrefl 0 (lt_of_le_of_lt (zero_le _) hp), }, exact hp } end theorem nat_degree_eq_zero_of_derivative_eq_zero [char_zero R] {f : polynomial R} (h : f.derivative = 0) : f.nat_degree = 0 := begin by_cases hf : f = 0, { exact (congr_arg polynomial.nat_degree hf).trans rfl }, { rw nat_degree_eq_zero_iff_degree_le_zero, by_contra absurd, have f_nat_degree_pos : 0 < f.nat_degree, { rwa [not_le, ←nat_degree_pos_iff_degree_pos] at absurd }, let m := f.nat_degree - 1, have hm : m + 1 = f.nat_degree := nat.sub_add_cancel f_nat_degree_pos, have h2 := coeff_derivative f m, rw polynomial.ext_iff at h, rw [h m, coeff_zero, zero_eq_mul] at h2, cases h2, { rw [hm, ←leading_coeff, leading_coeff_eq_zero] at h2, exact hf h2, }, { norm_cast at h2 } } end end domain end derivative end polynomial
ba5a1ec7440f24b4e9317535fdb1899a297f497a
4efff1f47634ff19e2f786deadd394270a59ecd2
/src/category_theory/equivalence.lean
a54f2bb5ec9743d0ef79f929697698d37aea902d
[ "Apache-2.0" ]
permissive
agjftucker/mathlib
d634cd0d5256b6325e3c55bb7fb2403548371707
87fe50de17b00af533f72a102d0adefe4a2285e8
refs/heads/master
1,625,378,131,941
1,599,166,526,000
1,599,166,526,000
160,748,509
0
0
Apache-2.0
1,544,141,789,000
1,544,141,789,000
null
UTF-8
Lean
false
false
19,247
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.fully_faithful import category_theory.whiskering import tactic.slice namespace category_theory open category_theory.functor nat_iso category universes v₁ v₂ v₃ u₁ u₂ u₃ -- declare the `v`'s first; see `category_theory.category` for an explanation /-- We define an equivalence as a (half)-adjoint equivalence, a pair of functors with a unit and counit which are natural isomorphisms and the triangle law `Fη ≫ εF = 1`, or in other words the composite `F ⟶ FGF ⟶ F` is the identity. The triangle equation is written as a family of equalities between morphisms, it is more complicated if we write it as an equality of natural transformations, because then we would have to insert natural transformations like `F ⟶ F1`. -/ structure equivalence (C : Type u₁) [category.{v₁} C] (D : Type u₂) [category.{v₂} D] := mk' :: (functor : C ⥤ D) (inverse : D ⥤ C) (unit_iso : 𝟭 C ≅ functor ⋙ inverse) (counit_iso : inverse ⋙ functor ≅ 𝟭 D) (functor_unit_iso_comp' : ∀(X : C), functor.map ((unit_iso.hom : 𝟭 C ⟶ functor ⋙ inverse).app X) ≫ counit_iso.hom.app (functor.obj X) = 𝟙 (functor.obj X) . obviously) restate_axiom equivalence.functor_unit_iso_comp' infixr ` ≌ `:10 := equivalence variables {C : Type u₁} [category.{v₁} C] {D : Type u₂} [category.{v₂} D] namespace equivalence abbreviation unit (e : C ≌ D) : 𝟭 C ⟶ e.functor ⋙ e.inverse := e.unit_iso.hom abbreviation counit (e : C ≌ D) : e.inverse ⋙ e.functor ⟶ 𝟭 D := e.counit_iso.hom abbreviation unit_inv (e : C ≌ D) : e.functor ⋙ e.inverse ⟶ 𝟭 C := e.unit_iso.inv abbreviation counit_inv (e : C ≌ D) : 𝟭 D ⟶ e.inverse ⋙ e.functor := e.counit_iso.inv /- While these abbreviations are convenient, they also cause some trouble, preventing structure projections from unfolding. -/ @[simp] lemma equivalence_mk'_unit (functor inverse unit_iso counit_iso f) : (⟨functor, inverse, unit_iso, counit_iso, f⟩ : C ≌ D).unit = unit_iso.hom := rfl @[simp] lemma equivalence_mk'_counit (functor inverse unit_iso counit_iso f) : (⟨functor, inverse, unit_iso, counit_iso, f⟩ : C ≌ D).counit = counit_iso.hom := rfl @[simp] lemma equivalence_mk'_unit_inv (functor inverse unit_iso counit_iso f) : (⟨functor, inverse, unit_iso, counit_iso, f⟩ : C ≌ D).unit_inv = unit_iso.inv := rfl @[simp] lemma equivalence_mk'_counit_inv (functor inverse unit_iso counit_iso f) : (⟨functor, inverse, unit_iso, counit_iso, f⟩ : C ≌ D).counit_inv = counit_iso.inv := rfl @[simp] lemma functor_unit_comp (e : C ≌ D) (X : C) : e.functor.map (e.unit.app X) ≫ e.counit.app (e.functor.obj X) = 𝟙 (e.functor.obj X) := e.functor_unit_iso_comp X @[simp] lemma counit_inv_functor_comp (e : C ≌ D) (X : C) : e.counit_inv.app (e.functor.obj X) ≫ e.functor.map (e.unit_inv.app X) = 𝟙 (e.functor.obj X) := begin erw [iso.inv_eq_inv (e.functor.map_iso (e.unit_iso.app X) ≪≫ e.counit_iso.app (e.functor.obj X)) (iso.refl _)], exact e.functor_unit_comp X end lemma functor_unit (e : C ≌ D) (X : C) : e.functor.map (e.unit.app X) = e.counit_inv.app (e.functor.obj X) := by { erw [←iso.comp_hom_eq_id (e.counit_iso.app _), functor_unit_comp], refl } lemma counit_functor (e : C ≌ D) (X : C) : e.counit.app (e.functor.obj X) = e.functor.map (e.unit_inv.app X) := by { erw [←iso.hom_comp_eq_id (e.functor.map_iso (e.unit_iso.app X)), functor_unit_comp], refl } /-- The other triangle equality. The proof follows the following proof in Globular: http://globular.science/1905.001 -/ @[simp] lemma unit_inverse_comp (e : C ≌ D) (Y : D) : e.unit.app (e.inverse.obj Y) ≫ e.inverse.map (e.counit.app Y) = 𝟙 (e.inverse.obj Y) := begin rw [←id_comp (e.inverse.map _), ←map_id e.inverse, ←counit_inv_functor_comp, map_comp, ←iso.hom_inv_id_assoc (e.unit_iso.app _) (e.inverse.map (e.functor.map _)), app_hom, app_inv], slice_lhs 2 3 { erw [e.unit.naturality] }, slice_lhs 1 2 { erw [e.unit.naturality] }, slice_lhs 4 4 { rw [←iso.hom_inv_id_assoc (e.inverse.map_iso (e.counit_iso.app _)) (e.unit_inv.app _)] }, slice_lhs 3 4 { erw [←map_comp e.inverse, e.counit.naturality], erw [(e.counit_iso.app _).hom_inv_id, map_id] }, erw [id_comp], slice_lhs 2 3 { erw [←map_comp e.inverse, e.counit_iso.inv.naturality, map_comp] }, slice_lhs 3 4 { erw [e.unit_inv.naturality] }, slice_lhs 4 5 { erw [←map_comp (e.functor ⋙ e.inverse), (e.unit_iso.app _).hom_inv_id, map_id] }, erw [id_comp], slice_lhs 3 4 { erw [←e.unit_inv.naturality] }, slice_lhs 2 3 { erw [←map_comp e.inverse, ←e.counit_iso.inv.naturality, (e.counit_iso.app _).hom_inv_id, map_id] }, erw [id_comp, (e.unit_iso.app _).hom_inv_id], refl end @[simp] lemma inverse_counit_inv_comp (e : C ≌ D) (Y : D) : e.inverse.map (e.counit_inv.app Y) ≫ e.unit_inv.app (e.inverse.obj Y) = 𝟙 (e.inverse.obj Y) := begin erw [iso.inv_eq_inv (e.unit_iso.app (e.inverse.obj Y) ≪≫ e.inverse.map_iso (e.counit_iso.app Y)) (iso.refl _)], exact e.unit_inverse_comp Y end lemma unit_inverse (e : C ≌ D) (Y : D) : e.unit.app (e.inverse.obj Y) = e.inverse.map (e.counit_inv.app Y) := by { erw [←iso.comp_hom_eq_id (e.inverse.map_iso (e.counit_iso.app Y)), unit_inverse_comp], refl } lemma inverse_counit (e : C ≌ D) (Y : D) : e.inverse.map (e.counit.app Y) = e.unit_inv.app (e.inverse.obj Y) := by { erw [←iso.hom_comp_eq_id (e.unit_iso.app _), unit_inverse_comp], refl } @[simp] lemma fun_inv_map (e : C ≌ D) (X Y : D) (f : X ⟶ Y) : e.functor.map (e.inverse.map f) = e.counit.app X ≫ f ≫ e.counit_inv.app Y := (nat_iso.naturality_2 (e.counit_iso) f).symm @[simp] lemma inv_fun_map (e : C ≌ D) (X Y : C) (f : X ⟶ Y) : e.inverse.map (e.functor.map f) = e.unit_inv.app X ≫ f ≫ e.unit.app Y := (nat_iso.naturality_1 (e.unit_iso) f).symm section -- In this section we convert an arbitrary equivalence to a half-adjoint equivalence. variables {F : C ⥤ D} {G : D ⥤ C} (η : 𝟭 C ≅ F ⋙ G) (ε : G ⋙ F ≅ 𝟭 D) def adjointify_η : 𝟭 C ≅ F ⋙ G := calc 𝟭 C ≅ F ⋙ G : η ... ≅ F ⋙ (𝟭 D ⋙ G) : iso_whisker_left F (left_unitor G).symm ... ≅ F ⋙ ((G ⋙ F) ⋙ G) : iso_whisker_left F (iso_whisker_right ε.symm G) ... ≅ F ⋙ (G ⋙ (F ⋙ G)) : iso_whisker_left F (associator G F G) ... ≅ (F ⋙ G) ⋙ (F ⋙ G) : (associator F G (F ⋙ G)).symm ... ≅ 𝟭 C ⋙ (F ⋙ G) : iso_whisker_right η.symm (F ⋙ G) ... ≅ F ⋙ G : left_unitor (F ⋙ G) lemma adjointify_η_ε (X : C) : F.map ((adjointify_η η ε).hom.app X) ≫ ε.hom.app (F.obj X) = 𝟙 (F.obj X) := begin dsimp [adjointify_η], simp, have := ε.hom.naturality (F.map (η.inv.app X)), dsimp at this, rw [this], clear this, rw [←assoc _ _ (F.map _)], have := ε.hom.naturality (ε.inv.app $ F.obj X), dsimp at this, rw [this], clear this, have := (ε.app $ F.obj X).hom_inv_id, dsimp at this, rw [this], clear this, rw [id_comp], have := (F.map_iso $ η.app X).hom_inv_id, dsimp at this, rw [this] end end protected definition mk (F : C ⥤ D) (G : D ⥤ C) (η : 𝟭 C ≅ F ⋙ G) (ε : G ⋙ F ≅ 𝟭 D) : C ≌ D := ⟨F, G, adjointify_η η ε, ε, adjointify_η_ε η ε⟩ @[refl, simps] def refl : C ≌ C := ⟨𝟭 C, 𝟭 C, iso.refl _, iso.refl _, λ X, category.id_comp _⟩ @[symm, simps] def symm (e : C ≌ D) : D ≌ C := ⟨e.inverse, e.functor, e.counit_iso.symm, e.unit_iso.symm, e.inverse_counit_inv_comp⟩ variables {E : Type u₃} [category.{v₃} E] @[trans, simps] def trans (e : C ≌ D) (f : D ≌ E) : C ≌ E := { functor := e.functor ⋙ f.functor, inverse := f.inverse ⋙ e.inverse, unit_iso := begin refine iso.trans e.unit_iso _, exact iso_whisker_left e.functor (iso_whisker_right f.unit_iso e.inverse) , end, counit_iso := begin refine iso.trans _ f.counit_iso, exact iso_whisker_left f.inverse (iso_whisker_right e.counit_iso f.functor) end, -- We wouldn't have needed to give this proof if we'd used `equivalence.mk`, -- but we choose to avoid using that here, for the sake of good structure projection `simp` lemmas. functor_unit_iso_comp' := λ X, begin dsimp, rw [← f.functor.map_comp_assoc, e.functor.map_comp, functor_unit, fun_inv_map, iso.inv_hom_id_app_assoc, assoc, iso.inv_hom_id_app, counit_functor, ← functor.map_comp], erw [comp_id, iso.hom_inv_id_app, functor.map_id], end } def fun_inv_id_assoc (e : C ≌ D) (F : C ⥤ E) : e.functor ⋙ e.inverse ⋙ F ≅ F := (functor.associator _ _ _).symm ≪≫ iso_whisker_right e.unit_iso.symm F ≪≫ F.left_unitor @[simp] lemma fun_inv_id_assoc_hom_app (e : C ≌ D) (F : C ⥤ E) (X : C) : (fun_inv_id_assoc e F).hom.app X = F.map (e.unit_inv.app X) := by { dsimp [fun_inv_id_assoc], tidy } @[simp] lemma fun_inv_id_assoc_inv_app (e : C ≌ D) (F : C ⥤ E) (X : C) : (fun_inv_id_assoc e F).inv.app X = F.map (e.unit.app X) := by { dsimp [fun_inv_id_assoc], tidy } def inv_fun_id_assoc (e : C ≌ D) (F : D ⥤ E) : e.inverse ⋙ e.functor ⋙ F ≅ F := (functor.associator _ _ _).symm ≪≫ iso_whisker_right e.counit_iso F ≪≫ F.left_unitor @[simp] lemma inv_fun_id_assoc_hom_app (e : C ≌ D) (F : D ⥤ E) (X : D) : (inv_fun_id_assoc e F).hom.app X = F.map (e.counit.app X) := by { dsimp [inv_fun_id_assoc], tidy } @[simp] lemma inv_fun_id_assoc_inv_app (e : C ≌ D) (F : D ⥤ E) (X : D) : (inv_fun_id_assoc e F).inv.app X = F.map (e.counit_inv.app X) := by { dsimp [inv_fun_id_assoc], tidy } section cancellation_lemmas variables (e : C ≌ D) -- We need special forms of `cancel_nat_iso_hom_right(_assoc)` and `cancel_nat_iso_inv_right(_assoc)` -- for units and counits, because neither `simp` or `rw` will apply those lemmas in this -- setting without providing `e.unit_iso` (or similar) as an explicit argument. -- We also provide the lemmas for length four compositions, since they're occasionally useful. -- (e.g. in proving that equivalences take monos to monos) @[simp] lemma cancel_unit_right {X Y : C} (f f' : X ⟶ Y) : f ≫ e.unit.app Y = f' ≫ e.unit.app Y ↔ f = f' := by simp only [cancel_mono] @[simp] lemma cancel_unit_inv_right {X Y : C} (f f' : X ⟶ e.inverse.obj (e.functor.obj Y)) : f ≫ e.unit_inv.app Y = f' ≫ e.unit_inv.app Y ↔ f = f' := by simp only [cancel_mono] @[simp] lemma cancel_counit_right {X Y : D} (f f' : X ⟶ e.functor.obj (e.inverse.obj Y)) : f ≫ e.counit.app Y = f' ≫ e.counit.app Y ↔ f = f' := by simp only [cancel_mono] @[simp] lemma cancel_counit_inv_right {X Y : D} (f f' : X ⟶ Y) : f ≫ e.counit_inv.app Y = f' ≫ e.counit_inv.app Y ↔ f = f' := by simp only [cancel_mono] @[simp] lemma cancel_unit_right_assoc {W X X' Y : C} (f : W ⟶ X) (g : X ⟶ Y) (f' : W ⟶ X') (g' : X' ⟶ Y) : f ≫ g ≫ e.unit.app Y = f' ≫ g' ≫ e.unit.app Y ↔ f ≫ g = f' ≫ g' := by simp only [←category.assoc, cancel_mono] @[simp] lemma cancel_counit_inv_right_assoc {W X X' Y : D} (f : W ⟶ X) (g : X ⟶ Y) (f' : W ⟶ X') (g' : X' ⟶ Y) : f ≫ g ≫ e.counit_inv.app Y = f' ≫ g' ≫ e.counit_inv.app Y ↔ f ≫ g = f' ≫ g' := by simp only [←category.assoc, cancel_mono] @[simp] lemma cancel_unit_right_assoc' {W X X' Y Y' Z : C} (f : W ⟶ X) (g : X ⟶ Y) (h : Y ⟶ Z) (f' : W ⟶ X') (g' : X' ⟶ Y') (h' : Y' ⟶ Z) : f ≫ g ≫ h ≫ e.unit.app Z = f' ≫ g' ≫ h' ≫ e.unit.app Z ↔ f ≫ g ≫ h = f' ≫ g' ≫ h' := by simp only [←category.assoc, cancel_mono] @[simp] lemma cancel_counit_inv_right_assoc' {W X X' Y Y' Z : D} (f : W ⟶ X) (g : X ⟶ Y) (h : Y ⟶ Z) (f' : W ⟶ X') (g' : X' ⟶ Y') (h' : Y' ⟶ Z) : f ≫ g ≫ h ≫ e.counit_inv.app Z = f' ≫ g' ≫ h' ≫ e.counit_inv.app Z ↔ f ≫ g ≫ h = f' ≫ g' ≫ h' := by simp only [←category.assoc, cancel_mono] end cancellation_lemmas section -- There's of course a monoid structure on `C ≌ C`, -- but let's not encourage using it. -- The power structure is nevertheless useful. /-- Powers of an auto-equivalence. -/ def pow (e : C ≌ C) : ℤ → (C ≌ C) | (int.of_nat 0) := equivalence.refl | (int.of_nat 1) := e | (int.of_nat (n+2)) := e.trans (pow (int.of_nat (n+1))) | (int.neg_succ_of_nat 0) := e.symm | (int.neg_succ_of_nat (n+1)) := e.symm.trans (pow (int.neg_succ_of_nat n)) instance : has_pow (C ≌ C) ℤ := ⟨pow⟩ @[simp] lemma pow_zero (e : C ≌ C) : e^(0 : ℤ) = equivalence.refl := rfl @[simp] lemma pow_one (e : C ≌ C) : e^(1 : ℤ) = e := rfl @[simp] lemma pow_minus_one (e : C ≌ C) : e^(-1 : ℤ) = e.symm := rfl -- TODO as necessary, add the natural isomorphisms `(e^a).trans e^b ≅ e^(a+b)`. -- At this point, we haven't even defined the category of equivalences. end end equivalence /-- A functor that is part of a (half) adjoint equivalence -/ class is_equivalence (F : C ⥤ D) := mk' :: (inverse : D ⥤ C) (unit_iso : 𝟭 C ≅ F ⋙ inverse) (counit_iso : inverse ⋙ F ≅ 𝟭 D) (functor_unit_iso_comp' : ∀ (X : C), F.map ((unit_iso.hom : 𝟭 C ⟶ F ⋙ inverse).app X) ≫ counit_iso.hom.app (F.obj X) = 𝟙 (F.obj X) . obviously) restate_axiom is_equivalence.functor_unit_iso_comp' namespace is_equivalence instance of_equivalence (F : C ≌ D) : is_equivalence F.functor := { ..F } instance of_equivalence_inverse (F : C ≌ D) : is_equivalence F.inverse := is_equivalence.of_equivalence F.symm open equivalence protected definition mk {F : C ⥤ D} (G : D ⥤ C) (η : 𝟭 C ≅ F ⋙ G) (ε : G ⋙ F ≅ 𝟭 D) : is_equivalence F := ⟨G, adjointify_η η ε, ε, adjointify_η_ε η ε⟩ end is_equivalence namespace functor def as_equivalence (F : C ⥤ D) [is_equivalence F] : C ≌ D := ⟨F, is_equivalence.inverse F, is_equivalence.unit_iso, is_equivalence.counit_iso, is_equivalence.functor_unit_iso_comp⟩ instance is_equivalence_refl : is_equivalence (𝟭 C) := is_equivalence.of_equivalence equivalence.refl def inv (F : C ⥤ D) [is_equivalence F] : D ⥤ C := is_equivalence.inverse F instance is_equivalence_inv (F : C ⥤ D) [is_equivalence F] : is_equivalence F.inv := is_equivalence.of_equivalence F.as_equivalence.symm @[simp] lemma as_equivalence_functor (F : C ⥤ D) [is_equivalence F] : F.as_equivalence.functor = F := rfl @[simp] lemma as_equivalence_inverse (F : C ⥤ D) [is_equivalence F] : F.as_equivalence.inverse = inv F := rfl @[simp] lemma inv_inv (F : C ⥤ D) [is_equivalence F] : inv (inv F) = F := rfl def fun_inv_id (F : C ⥤ D) [is_equivalence F] : F ⋙ F.inv ≅ 𝟭 C := is_equivalence.unit_iso.symm def inv_fun_id (F : C ⥤ D) [is_equivalence F] : F.inv ⋙ F ≅ 𝟭 D := is_equivalence.counit_iso variables {E : Type u₃} [category.{v₃} E] instance is_equivalence_trans (F : C ⥤ D) (G : D ⥤ E) [is_equivalence F] [is_equivalence G] : is_equivalence (F ⋙ G) := is_equivalence.of_equivalence (equivalence.trans (as_equivalence F) (as_equivalence G)) end functor namespace equivalence @[simp] lemma functor_inv (E : C ≌ D) : E.functor.inv = E.inverse := rfl @[simp] lemma inverse_inv (E : C ≌ D) : E.inverse.inv = E.functor := rfl @[simp] lemma functor_as_equivalence (E : C ≌ D) : E.functor.as_equivalence = E := by { cases E, congr, } @[simp] lemma inverse_as_equivalence (E : C ≌ D) : E.inverse.as_equivalence = E.symm := by { cases E, congr, } end equivalence namespace is_equivalence @[simp] lemma fun_inv_map (F : C ⥤ D) [is_equivalence F] (X Y : D) (f : X ⟶ Y) : F.map (F.inv.map f) = F.inv_fun_id.hom.app X ≫ f ≫ F.inv_fun_id.inv.app Y := begin erw [nat_iso.naturality_2], refl end @[simp] lemma inv_fun_map (F : C ⥤ D) [is_equivalence F] (X Y : C) (f : X ⟶ Y) : F.inv.map (F.map f) = F.fun_inv_id.hom.app X ≫ f ≫ F.fun_inv_id.inv.app Y := begin erw [nat_iso.naturality_2], refl end -- We should probably restate many of the lemmas about `equivalence` for `is_equivalence`, -- but these are the only ones I need for now. @[simp] lemma functor_unit_comp (E : C ⥤ D) [is_equivalence E] (Y) : E.map (E.fun_inv_id.inv.app Y) ≫ E.inv_fun_id.hom.app (E.obj Y) = 𝟙 _ := equivalence.functor_unit_comp E.as_equivalence Y @[simp] lemma inv_fun_id_inv_comp (E : C ⥤ D) [is_equivalence E] (Y) : E.inv_fun_id.inv.app (E.obj Y) ≫ E.map (E.fun_inv_id.hom.app Y) = 𝟙 _ := eq_of_inv_eq_inv (functor_unit_comp _ _) end is_equivalence class ess_surj (F : C ⥤ D) := (obj_preimage (d : D) : C) (iso' (d : D) : F.obj (obj_preimage d) ≅ d . obviously) restate_axiom ess_surj.iso' namespace functor def obj_preimage (F : C ⥤ D) [ess_surj F] (d : D) : C := ess_surj.obj_preimage.{v₁ v₂} F d def fun_obj_preimage_iso (F : C ⥤ D) [ess_surj F] (d : D) : F.obj (F.obj_preimage d) ≅ d := ess_surj.iso d end functor namespace equivalence def ess_surj_of_equivalence (F : C ⥤ D) [is_equivalence F] : ess_surj F := ⟨ λ Y : D, F.inv.obj Y, λ Y : D, (F.inv_fun_id.app Y) ⟩ @[priority 100] -- see Note [lower instance priority] instance faithful_of_equivalence (F : C ⥤ D) [is_equivalence F] : faithful F := { map_injective' := λ X Y f g w, begin have p := congr_arg (@category_theory.functor.map _ _ _ _ F.inv _ _) w, simpa only [cancel_epi, cancel_mono, is_equivalence.inv_fun_map] using p end }. @[priority 100] -- see Note [lower instance priority] instance full_of_equivalence (F : C ⥤ D) [is_equivalence F] : full F := { preimage := λ X Y f, F.fun_inv_id.inv.app X ≫ F.inv.map f ≫ F.fun_inv_id.hom.app Y, witness' := λ X Y f, F.inv.map_injective (by simpa only [is_equivalence.inv_fun_map, assoc, iso.hom_inv_id_app_assoc, iso.hom_inv_id_app] using comp_id _) } @[simp] private def equivalence_inverse (F : C ⥤ D) [full F] [faithful F] [ess_surj F] : D ⥤ C := { obj := λ X, F.obj_preimage X, map := λ X Y f, F.preimage ((F.fun_obj_preimage_iso X).hom ≫ f ≫ (F.fun_obj_preimage_iso Y).inv), map_id' := λ X, begin apply F.map_injective, tidy end, map_comp' := λ X Y Z f g, by apply F.map_injective; simp } def equivalence_of_fully_faithfully_ess_surj (F : C ⥤ D) [full F] [faithful F] [ess_surj F] : is_equivalence F := is_equivalence.mk (equivalence_inverse F) (nat_iso.of_components (λ X, (preimage_iso $ F.fun_obj_preimage_iso $ F.obj X).symm) (λ X Y f, by { apply F.map_injective, obviously })) (nat_iso.of_components (λ Y, F.fun_obj_preimage_iso Y) (by obviously)) @[simp] lemma functor_map_inj_iff (e : C ≌ D) {X Y : C} (f g : X ⟶ Y) : e.functor.map f = e.functor.map g ↔ f = g := begin split, { intro w, apply e.functor.map_injective, exact w, }, { rintro ⟨rfl⟩, refl, } end @[simp] lemma inverse_map_inj_iff (e : C ≌ D) {X Y : D} (f g : X ⟶ Y) : e.inverse.map f = e.inverse.map g ↔ f = g := begin split, { intro w, apply e.inverse.map_injective, exact w, }, { rintro ⟨rfl⟩, refl, } end end equivalence end category_theory
2d6ae76286905d22d300782ded4a1867f9a61133
80746c6dba6a866de5431094bf9f8f841b043d77
/src/data/nat/gcd.lean
b7dd691e7473735dbd5141357d004cea8093239b
[ "Apache-2.0" ]
permissive
leanprover-fork/mathlib-backup
8b5c95c535b148fca858f7e8db75a76252e32987
0eb9db6a1a8a605f0cf9e33873d0450f9f0ae9b0
refs/heads/master
1,585,156,056,139
1,548,864,430,000
1,548,864,438,000
143,964,213
0
0
Apache-2.0
1,550,795,966,000
1,533,705,322,000
Lean
UTF-8
Lean
false
false
13,043
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 Definitions and properties of gcd, lcm, and coprime. -/ import data.nat.basic namespace nat /- gcd -/ theorem gcd_dvd (m n : ℕ) : (gcd m n ∣ m) ∧ (gcd m n ∣ n) := gcd.induction m n (λn, by rw gcd_zero_left; exact ⟨dvd_zero n, dvd_refl n⟩) (λm n npos, by rw ←gcd_rec; exact λ ⟨IH₁, IH₂⟩, ⟨IH₂, (dvd_mod_iff IH₂).1 IH₁⟩) theorem gcd_dvd_left (m n : ℕ) : gcd m n ∣ m := (gcd_dvd m n).left theorem gcd_dvd_right (m n : ℕ) : gcd m n ∣ n := (gcd_dvd m n).right theorem dvd_gcd {m n k : ℕ} : k ∣ m → k ∣ n → k ∣ gcd m n := gcd.induction m n (λn _ kn, by rw gcd_zero_left; exact kn) (λn m mpos IH H1 H2, by rw gcd_rec; exact IH ((dvd_mod_iff H1).2 H2) H1) theorem gcd_comm (m n : ℕ) : gcd m n = gcd n m := dvd_antisymm (dvd_gcd (gcd_dvd_right m n) (gcd_dvd_left m n)) (dvd_gcd (gcd_dvd_right n m) (gcd_dvd_left n m)) theorem gcd_assoc (m n k : ℕ) : gcd (gcd m n) k = gcd m (gcd n k) := dvd_antisymm (dvd_gcd (dvd.trans (gcd_dvd_left (gcd m n) k) (gcd_dvd_left m n)) (dvd_gcd (dvd.trans (gcd_dvd_left (gcd m n) k) (gcd_dvd_right m n)) (gcd_dvd_right (gcd m n) k))) (dvd_gcd (dvd_gcd (gcd_dvd_left m (gcd n k)) (dvd.trans (gcd_dvd_right m (gcd n k)) (gcd_dvd_left n k))) (dvd.trans (gcd_dvd_right m (gcd n k)) (gcd_dvd_right n k))) @[simp] theorem gcd_one_right (n : ℕ) : gcd n 1 = 1 := eq.trans (gcd_comm n 1) $ gcd_one_left n theorem gcd_mul_left (m n k : ℕ) : gcd (m * n) (m * k) = m * gcd n k := gcd.induction n k (λk, by repeat {rw mul_zero <|> rw gcd_zero_left}) (λk n H IH, by rwa [←mul_mod_mul_left, ←gcd_rec, ←gcd_rec] at IH) theorem gcd_mul_right (m n k : ℕ) : gcd (m * n) (k * n) = gcd m k * n := by rw [mul_comm m n, mul_comm k n, mul_comm (gcd m k) n, gcd_mul_left] theorem gcd_pos_of_pos_left {m : ℕ} (n : ℕ) (mpos : m > 0) : gcd m n > 0 := pos_of_dvd_of_pos (gcd_dvd_left m n) mpos theorem gcd_pos_of_pos_right (m : ℕ) {n : ℕ} (npos : n > 0) : gcd m n > 0 := pos_of_dvd_of_pos (gcd_dvd_right m n) npos theorem eq_zero_of_gcd_eq_zero_left {m n : ℕ} (H : gcd m n = 0) : m = 0 := or.elim (eq_zero_or_pos m) id (assume H1 : m > 0, absurd (eq.symm H) (ne_of_lt (gcd_pos_of_pos_left _ H1))) theorem eq_zero_of_gcd_eq_zero_right {m n : ℕ} (H : gcd m n = 0) : n = 0 := by rw gcd_comm at H; exact eq_zero_of_gcd_eq_zero_left H theorem gcd_div {m n k : ℕ} (H1 : k ∣ m) (H2 : k ∣ n) : gcd (m / k) (n / k) = gcd m n / k := or.elim (eq_zero_or_pos k) (λk0, by rw [k0, nat.div_zero, nat.div_zero, nat.div_zero, gcd_zero_right]) (λH3, nat.eq_of_mul_eq_mul_right H3 $ by rw [ nat.div_mul_cancel (dvd_gcd H1 H2), ←gcd_mul_right, nat.div_mul_cancel H1, nat.div_mul_cancel H2]) theorem gcd_dvd_gcd_of_dvd_left {m k : ℕ} (n : ℕ) (H : m ∣ k) : gcd m n ∣ gcd k n := dvd_gcd (dvd.trans (gcd_dvd_left m n) H) (gcd_dvd_right m n) theorem gcd_dvd_gcd_of_dvd_right {m k : ℕ} (n : ℕ) (H : m ∣ k) : gcd n m ∣ gcd n k := dvd_gcd (gcd_dvd_left n m) (dvd.trans (gcd_dvd_right n m) H) theorem gcd_dvd_gcd_mul_left (m n k : ℕ) : gcd m n ∣ gcd (k * m) n := gcd_dvd_gcd_of_dvd_left _ (dvd_mul_left _ _) theorem gcd_dvd_gcd_mul_right (m n k : ℕ) : gcd m n ∣ gcd (m * k) n := gcd_dvd_gcd_of_dvd_left _ (dvd_mul_right _ _) theorem gcd_dvd_gcd_mul_left_right (m n k : ℕ) : gcd m n ∣ gcd m (k * n) := gcd_dvd_gcd_of_dvd_right _ (dvd_mul_left _ _) theorem gcd_dvd_gcd_mul_right_right (m n k : ℕ) : gcd m n ∣ gcd m (n * k) := gcd_dvd_gcd_of_dvd_right _ (dvd_mul_right _ _) theorem gcd_eq_left {m n : ℕ} (H : m ∣ n) : gcd m n = m := dvd_antisymm (gcd_dvd_left _ _) (dvd_gcd (dvd_refl _) H) theorem gcd_eq_right {m n : ℕ} (H : n ∣ m) : gcd m n = n := by rw [gcd_comm, gcd_eq_left H] @[simp] lemma gcd_mul_left_left (m n : ℕ) : gcd (m * n) n = n := dvd_antisymm (gcd_dvd_right _ _) (dvd_gcd (dvd_mul_left _ _) (dvd_refl _)) @[simp] lemma gcd_mul_left_right (m n : ℕ) : gcd n (m * n) = n := by rw [gcd_comm, gcd_mul_left_left] @[simp] lemma gcd_mul_right_left (m n : ℕ) : gcd (n * m) n = n := by rw [mul_comm, gcd_mul_left_left] @[simp] lemma gcd_mul_right_right (m n : ℕ) : gcd n (n * m) = n := by rw [gcd_comm, gcd_mul_right_left] @[simp] lemma gcd_gcd_self_right_left (m n : ℕ) : gcd m (gcd m n) = gcd m n := dvd_antisymm (gcd_dvd_right _ _) (dvd_gcd (gcd_dvd_left _ _) (dvd_refl _)) @[simp] lemma gcd_gcd_self_right_right (m n : ℕ) : gcd m (gcd n m) = gcd n m := by rw [gcd_comm n m, gcd_gcd_self_right_left] @[simp] lemma gcd_gcd_self_left_right (m n : ℕ) : gcd (gcd n m) m = gcd n m := by rw [gcd_comm, gcd_gcd_self_right_right] @[simp] lemma gcd_gcd_self_left_left (m n : ℕ) : gcd (gcd m n) m = gcd m n := by rw [gcd_comm m n, gcd_gcd_self_left_right] /- lcm -/ theorem lcm_comm (m n : ℕ) : lcm m n = lcm n m := by delta lcm; rw [mul_comm, gcd_comm] theorem lcm_zero_left (m : ℕ) : lcm 0 m = 0 := by delta lcm; rw [zero_mul, nat.zero_div] theorem lcm_zero_right (m : ℕ) : lcm m 0 = 0 := lcm_comm 0 m ▸ lcm_zero_left m theorem lcm_one_left (m : ℕ) : lcm 1 m = m := by delta lcm; rw [one_mul, gcd_one_left, nat.div_one] theorem lcm_one_right (m : ℕ) : lcm m 1 = m := lcm_comm 1 m ▸ lcm_one_left m theorem lcm_self (m : ℕ) : lcm m m = m := or.elim (eq_zero_or_pos m) (λh, by rw [h, lcm_zero_left]) (λh, by delta lcm; rw [gcd_self, nat.mul_div_cancel _ h]) theorem dvd_lcm_left (m n : ℕ) : m ∣ lcm m n := dvd.intro (n / gcd m n) (nat.mul_div_assoc _ $ gcd_dvd_right m n).symm theorem dvd_lcm_right (m n : ℕ) : n ∣ lcm m n := lcm_comm n m ▸ dvd_lcm_left n m theorem gcd_mul_lcm (m n : ℕ) : gcd m n * lcm m n = m * n := by delta lcm; rw [nat.mul_div_cancel' (dvd.trans (gcd_dvd_left m n) (dvd_mul_right m n))] theorem lcm_dvd {m n k : ℕ} (H1 : m ∣ k) (H2 : n ∣ k) : lcm m n ∣ k := or.elim (eq_zero_or_pos k) (λh, by rw h; exact dvd_zero _) (λkpos, dvd_of_mul_dvd_mul_left (gcd_pos_of_pos_left n (pos_of_dvd_of_pos H1 kpos)) $ by rw [gcd_mul_lcm, ←gcd_mul_right, mul_comm n k]; exact dvd_gcd (mul_dvd_mul_left _ H2) (mul_dvd_mul_right H1 _)) theorem lcm_assoc (m n k : ℕ) : lcm (lcm m n) k = lcm m (lcm n k) := dvd_antisymm (lcm_dvd (lcm_dvd (dvd_lcm_left m (lcm n k)) (dvd.trans (dvd_lcm_left n k) (dvd_lcm_right m (lcm n k)))) (dvd.trans (dvd_lcm_right n k) (dvd_lcm_right m (lcm n k)))) (lcm_dvd (dvd.trans (dvd_lcm_left m n) (dvd_lcm_left (lcm m n) k)) (lcm_dvd (dvd.trans (dvd_lcm_right m n) (dvd_lcm_left (lcm m n) k)) (dvd_lcm_right (lcm m n) k))) /- coprime -/ instance (m n : ℕ) : decidable (coprime m n) := by unfold coprime; apply_instance theorem coprime.gcd_eq_one {m n : ℕ} : coprime m n → gcd m n = 1 := id theorem coprime.symm {m n : ℕ} : coprime n m → coprime m n := (gcd_comm m n).trans theorem coprime_of_dvd {m n : ℕ} (H : ∀ k > 1, k ∣ m → ¬ k ∣ n) : coprime m n := or.elim (eq_zero_or_pos (gcd m n)) (λg0, by rw [eq_zero_of_gcd_eq_zero_left g0, eq_zero_of_gcd_eq_zero_right g0] at H; exact false.elim (H 2 dec_trivial (dvd_zero _) (dvd_zero _))) (λ(g1 : 1 ≤ _), eq.symm $ (lt_or_eq_of_le g1).resolve_left $ λg2, H _ g2 (gcd_dvd_left _ _) (gcd_dvd_right _ _)) theorem coprime_of_dvd' {m n : ℕ} (H : ∀ k, k ∣ m → k ∣ n → k ∣ 1) : coprime m n := coprime_of_dvd $ λk kl km kn, not_le_of_gt kl $ le_of_dvd zero_lt_one (H k km kn) theorem coprime.dvd_of_dvd_mul_right {m n k : ℕ} (H1 : coprime k n) (H2 : k ∣ m * n) : k ∣ m := let t := dvd_gcd (dvd_mul_left k m) H2 in by rwa [gcd_mul_left, H1.gcd_eq_one, mul_one] at t theorem coprime.dvd_of_dvd_mul_left {m n k : ℕ} (H1 : coprime k m) (H2 : k ∣ m * n) : k ∣ n := by rw mul_comm at H2; exact H1.dvd_of_dvd_mul_right H2 theorem coprime.gcd_mul_left_cancel {k : ℕ} (m : ℕ) {n : ℕ} (H : coprime k n) : gcd (k * m) n = gcd m n := have H1 : coprime (gcd (k * m) n) k, by rw [coprime, gcd_assoc, H.symm.gcd_eq_one, gcd_one_right], dvd_antisymm (dvd_gcd (H1.dvd_of_dvd_mul_left (gcd_dvd_left _ _)) (gcd_dvd_right _ _)) (gcd_dvd_gcd_mul_left _ _ _) theorem coprime.gcd_mul_right_cancel (m : ℕ) {k n : ℕ} (H : coprime k n) : gcd (m * k) n = gcd m n := by rw [mul_comm m k, H.gcd_mul_left_cancel m] theorem coprime.gcd_mul_left_cancel_right {k m : ℕ} (n : ℕ) (H : coprime k m) : gcd m (k * n) = gcd m n := by rw [gcd_comm m n, gcd_comm m (k * n), H.gcd_mul_left_cancel n] theorem coprime.gcd_mul_right_cancel_right {k m : ℕ} (n : ℕ) (H : coprime k m) : gcd m (n * k) = gcd m n := by rw [mul_comm n k, H.gcd_mul_left_cancel_right n] theorem coprime_div_gcd_div_gcd {m n : ℕ} (H : gcd m n > 0) : coprime (m / gcd m n) (n / gcd m n) := by delta coprime; rw [gcd_div (gcd_dvd_left m n) (gcd_dvd_right m n), nat.div_self H] theorem not_coprime_of_dvd_of_dvd {m n d : ℕ} (dgt1 : d > 1) (Hm : d ∣ m) (Hn : d ∣ n) : ¬ coprime m n := λ (co : gcd m n = 1), not_lt_of_ge (le_of_dvd zero_lt_one $ by rw ←co; exact dvd_gcd Hm Hn) dgt1 theorem exists_coprime {m n : ℕ} (H : gcd m n > 0) : ∃ m' n', coprime m' n' ∧ m = m' * gcd m n ∧ n = n' * gcd m n := ⟨_, _, coprime_div_gcd_div_gcd H, (nat.div_mul_cancel (gcd_dvd_left m n)).symm, (nat.div_mul_cancel (gcd_dvd_right m n)).symm⟩ theorem exists_coprime' {m n : ℕ} (H : gcd m n > 0) : ∃ g m' n', 0 < g ∧ coprime m' n' ∧ m = m' * g ∧ n = n' * g := let ⟨m', n', h⟩ := exists_coprime H in ⟨_, m', n', H, h⟩ theorem coprime.mul {m n k : ℕ} (H1 : coprime m k) (H2 : coprime n k) : coprime (m * n) k := (H1.gcd_mul_left_cancel n).trans H2 theorem coprime.mul_right {k m n : ℕ} (H1 : coprime k m) (H2 : coprime k n) : coprime k (m * n) := (H1.symm.mul H2.symm).symm theorem coprime.coprime_dvd_left {m k n : ℕ} (H1 : m ∣ k) (H2 : coprime k n) : coprime m n := eq_one_of_dvd_one (by delta coprime at H2; rw ← H2; exact gcd_dvd_gcd_of_dvd_left _ H1) theorem coprime.coprime_dvd_right {m k n : ℕ} (H1 : n ∣ m) (H2 : coprime k m) : coprime k n := (H2.symm.coprime_dvd_left H1).symm theorem coprime.coprime_mul_left {k m n : ℕ} (H : coprime (k * m) n) : coprime m n := H.coprime_dvd_left (dvd_mul_left _ _) theorem coprime.coprime_mul_right {k m n : ℕ} (H : coprime (m * k) n) : coprime m n := H.coprime_dvd_left (dvd_mul_right _ _) theorem coprime.coprime_mul_left_right {k m n : ℕ} (H : coprime m (k * n)) : coprime m n := H.coprime_dvd_right (dvd_mul_left _ _) theorem coprime.coprime_mul_right_right {k m n : ℕ} (H : coprime m (n * k)) : coprime m n := H.coprime_dvd_right (dvd_mul_right _ _) lemma coprime_mul_iff_left {k m n : ℕ} : coprime (m * n) k ↔ coprime m k ∧ coprime n k := ⟨λ h, ⟨coprime.coprime_mul_right h, coprime.coprime_mul_left h⟩, λ ⟨h, _⟩, by rwa [coprime, coprime.gcd_mul_left_cancel n h]⟩ lemma coprime_mul_iff_right {k m n : ℕ} : coprime k (m * n) ↔ coprime m k ∧ coprime n k := by rw [coprime, nat.gcd_comm]; exact coprime_mul_iff_left lemma coprime.mul_dvd_of_dvd_of_dvd {a n m : ℕ} (hmn : coprime m n) (hm : m ∣ a) (hn : n ∣ a) : m * n ∣ a := let ⟨k, hk⟩ := hm in hk.symm ▸ mul_dvd_mul_left _ (hmn.symm.dvd_of_dvd_mul_left (hk ▸ hn)) theorem coprime_one_left : ∀ n, coprime 1 n := gcd_one_left theorem coprime_one_right : ∀ n, coprime n 1 := gcd_one_right theorem coprime.pow_left {m k : ℕ} (n : ℕ) (H1 : coprime m k) : coprime (m ^ n) k := nat.rec_on n (coprime_one_left _) (λn IH, IH.mul H1) theorem coprime.pow_right {m k : ℕ} (n : ℕ) (H1 : coprime k m) : coprime k (m ^ n) := (H1.symm.pow_left n).symm theorem coprime.pow {k l : ℕ} (m n : ℕ) (H1 : coprime k l) : coprime (k ^ m) (l ^ n) := (H1.pow_left _).pow_right _ theorem coprime.eq_one_of_dvd {k m : ℕ} (H : coprime k m) (d : k ∣ m) : k = 1 := by rw [← H.gcd_eq_one, gcd_eq_left d] theorem exists_eq_prod_and_dvd_and_dvd {m n k : ℕ} (H : k ∣ m * n) : ∃ m' n', k = m' * n' ∧ m' ∣ m ∧ n' ∣ n := or.elim (eq_zero_or_pos (gcd k m)) (λg0, ⟨0, n, by rw [zero_mul, eq_zero_of_gcd_eq_zero_left g0], by rw [eq_zero_of_gcd_eq_zero_right g0]; apply dvd_zero, dvd_refl _⟩) (λgpos, let hd := (nat.mul_div_cancel' (gcd_dvd_left k m)).symm in ⟨_, _, hd, gcd_dvd_right _ _, dvd_of_mul_dvd_mul_left gpos $ by rw [←hd, ←gcd_mul_right]; exact dvd_gcd (dvd_mul_right _ _) H⟩) theorem pow_dvd_pow_iff {a b n : ℕ} (n0 : 0 < n) : a ^ n ∣ b ^ n ↔ a ∣ b := begin refine ⟨λ h, _, λ h, pow_dvd_pow_of_dvd h _⟩, cases eq_zero_or_pos (gcd a b) with g0 g0, { simp [eq_zero_of_gcd_eq_zero_right g0] }, rcases exists_coprime' g0 with ⟨g, a', b', g0', co, rfl, rfl⟩, rw [mul_pow, mul_pow] at h, replace h := dvd_of_mul_dvd_mul_right (pos_pow_of_pos _ g0') h, have := pow_dvd_pow a' n0, rw [pow_one, (co.pow n n).eq_one_of_dvd h] at this, simp [eq_one_of_dvd_one this] end end nat
0c447f11c3db47d6a2e8bb3fcdd310304a4f5075
137c667471a40116a7afd7261f030b30180468c2
/src/analysis/specific_limits.lean
80e739b2c8ff3a1b3cd871c88130587f0024a684
[ "Apache-2.0" ]
permissive
bragadeesh153/mathlib
46bf814cfb1eecb34b5d1549b9117dc60f657792
b577bb2cd1f96eb47031878256856020b76f73cd
refs/heads/master
1,687,435,188,334
1,626,384,207,000
1,626,384,207,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
41,821
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 algebra.geom_sum import order.filter.archimedean import order.iterate import topology.instances.ennreal import tactic.ring_exp import analysis.asymptotics.asymptotics /-! # A collection of specific limit computations -/ noncomputable theory open classical set function filter finset metric asymptotics open_locale classical topological_space nat big_operators uniformity nnreal ennreal variables {α : Type*} {β : Type*} {ι : Type*} lemma tendsto_norm_at_top_at_top : tendsto (norm : ℝ → ℝ) at_top at_top := tendsto_abs_at_top_at_top lemma summable_of_absolute_convergence_real {f : ℕ → ℝ} : (∃r, tendsto (λn, (∑ i in range n, abs (f i))) at_top (𝓝 r)) → summable f | ⟨r, hr⟩ := begin refine summable_of_summable_norm ⟨r, (has_sum_iff_tendsto_nat_of_nonneg _ _).2 _⟩, exact assume i, norm_nonneg _, simpa only using hr end lemma tendsto_inverse_at_top_nhds_0_nat : tendsto (λ n : ℕ, (n : ℝ)⁻¹) at_top (𝓝 0) := tendsto_inv_at_top_zero.comp tendsto_coe_nat_at_top_at_top lemma tendsto_const_div_at_top_nhds_0_nat (C : ℝ) : tendsto (λ n : ℕ, C / n) at_top (𝓝 0) := by simpa only [mul_zero] using tendsto_const_nhds.mul tendsto_inverse_at_top_nhds_0_nat lemma nnreal.tendsto_inverse_at_top_nhds_0_nat : tendsto (λ n : ℕ, (n : ℝ≥0)⁻¹) at_top (𝓝 0) := by { rw ← nnreal.tendsto_coe, convert tendsto_inverse_at_top_nhds_0_nat, simp } lemma nnreal.tendsto_const_div_at_top_nhds_0_nat (C : ℝ≥0) : tendsto (λ n : ℕ, C / n) at_top (𝓝 0) := by simpa using tendsto_const_nhds.mul nnreal.tendsto_inverse_at_top_nhds_0_nat lemma tendsto_one_div_add_at_top_nhds_0_nat : tendsto (λ n : ℕ, 1 / ((n : ℝ) + 1)) at_top (𝓝 0) := suffices tendsto (λ n : ℕ, 1 / (↑(n + 1) : ℝ)) at_top (𝓝 0), by simpa, (tendsto_add_at_top_iff_nat 1).2 (tendsto_const_div_at_top_nhds_0_nat 1) /-! ### Powers -/ lemma tendsto_add_one_pow_at_top_at_top_of_pos [linear_ordered_semiring α] [archimedean α] {r : α} (h : 0 < r) : tendsto (λ n:ℕ, (r + 1)^n) at_top at_top := tendsto_at_top_at_top_of_monotone' (λ n m, pow_le_pow (le_add_of_nonneg_left (le_of_lt h))) $ not_bdd_above_iff.2 $ λ x, set.exists_range_iff.2 $ add_one_pow_unbounded_of_pos _ h lemma tendsto_pow_at_top_at_top_of_one_lt [linear_ordered_ring α] [archimedean α] {r : α} (h : 1 < r) : tendsto (λn:ℕ, r ^ n) at_top at_top := sub_add_cancel r 1 ▸ tendsto_add_one_pow_at_top_at_top_of_pos (sub_pos.2 h) lemma nat.tendsto_pow_at_top_at_top_of_one_lt {m : ℕ} (h : 1 < m) : tendsto (λn:ℕ, m ^ n) at_top at_top := nat.sub_add_cancel (le_of_lt h) ▸ tendsto_add_one_pow_at_top_at_top_of_pos (nat.sub_pos_of_lt h) lemma tendsto_norm_zero' {𝕜 : Type*} [normed_group 𝕜] : tendsto (norm : 𝕜 → ℝ) (𝓝[{x | x ≠ 0}] 0) (𝓝[set.Ioi 0] 0) := tendsto_norm_zero.inf $ tendsto_principal_principal.2 $ λ x hx, norm_pos_iff.2 hx lemma normed_field.tendsto_norm_inverse_nhds_within_0_at_top {𝕜 : Type*} [normed_field 𝕜] : tendsto (λ x:𝕜, ∥x⁻¹∥) (𝓝[{x | x ≠ 0}] 0) at_top := (tendsto_inv_zero_at_top.comp tendsto_norm_zero').congr $ λ x, (normed_field.norm_inv x).symm lemma tendsto_pow_at_top_nhds_0_of_lt_1 {𝕜 : Type*} [linear_ordered_field 𝕜] [archimedean 𝕜] [topological_space 𝕜] [order_topology 𝕜] {r : 𝕜} (h₁ : 0 ≤ r) (h₂ : r < 1) : tendsto (λn:ℕ, r^n) at_top (𝓝 0) := h₁.eq_or_lt.elim (assume : 0 = r, (tendsto_add_at_top_iff_nat 1).mp $ by simp [pow_succ, ← this, tendsto_const_nhds]) (assume : 0 < r, have tendsto (λn, (r⁻¹ ^ n)⁻¹) at_top (𝓝 0), from tendsto_inv_at_top_zero.comp (tendsto_pow_at_top_at_top_of_one_lt $ one_lt_inv this h₂), this.congr (λ n, by simp)) lemma tendsto_pow_at_top_nhds_within_0_of_lt_1 {𝕜 : Type*} [linear_ordered_field 𝕜] [archimedean 𝕜] [topological_space 𝕜] [order_topology 𝕜] {r : 𝕜} (h₁ : 0 < r) (h₂ : r < 1) : tendsto (λn:ℕ, r^n) at_top (𝓝[Ioi 0] 0) := tendsto_inf.2 ⟨tendsto_pow_at_top_nhds_0_of_lt_1 h₁.le h₂, tendsto_principal.2 $ eventually_of_forall $ λ n, pow_pos h₁ _⟩ lemma is_o_pow_pow_of_lt_left {r₁ r₂ : ℝ} (h₁ : 0 ≤ r₁) (h₂ : r₁ < r₂) : is_o (λ n : ℕ, r₁ ^ n) (λ n, r₂ ^ n) at_top := have H : 0 < r₂ := h₁.trans_lt h₂, is_o_of_tendsto (λ n hn, false.elim $ H.ne' $ pow_eq_zero hn) $ (tendsto_pow_at_top_nhds_0_of_lt_1 (div_nonneg h₁ (h₁.trans h₂.le)) ((div_lt_one H).2 h₂)).congr (λ n, div_pow _ _ _) lemma is_O_pow_pow_of_le_left {r₁ r₂ : ℝ} (h₁ : 0 ≤ r₁) (h₂ : r₁ ≤ r₂) : is_O (λ n : ℕ, r₁ ^ n) (λ n, r₂ ^ n) at_top := h₂.eq_or_lt.elim (λ h, h ▸ is_O_refl _ _) (λ h, (is_o_pow_pow_of_lt_left h₁ h).is_O) lemma is_o_pow_pow_of_abs_lt_left {r₁ r₂ : ℝ} (h : abs r₁ < abs r₂) : is_o (λ n : ℕ, r₁ ^ n) (λ n, r₂ ^ n) at_top := begin refine (is_o.of_norm_left _).of_norm_right, exact (is_o_pow_pow_of_lt_left (abs_nonneg r₁) h).congr (pow_abs r₁) (pow_abs r₂) end /-- Various statements equivalent to the fact that `f n` grows exponentially slower than `R ^ n`. * 0: $f n = o(a ^ n)$ for some $-R < a < R$; * 1: $f n = o(a ^ n)$ for some $0 < a < R$; * 2: $f n = O(a ^ n)$ for some $-R < a < R$; * 3: $f n = O(a ^ n)$ for some $0 < a < R$; * 4: there exist `a < R` and `C` such that one of `C` and `R` is positive and $|f n| ≤ Ca^n$ for all `n`; * 5: there exists `0 < a < R` and a positive `C` such that $|f n| ≤ Ca^n$ for all `n`; * 6: there exists `a < R` such that $|f n| ≤ a ^ n$ for sufficiently large `n`; * 7: there exists `0 < a < R` such that $|f n| ≤ a ^ n$ for sufficiently large `n`. NB: For backwards compatibility, if you add more items to the list, please append them at the end of the list. -/ lemma tfae_exists_lt_is_o_pow (f : ℕ → ℝ) (R : ℝ) : tfae [∃ a ∈ Ioo (-R) R, is_o f (pow a) at_top, ∃ a ∈ Ioo 0 R, is_o f (pow a) at_top, ∃ a ∈ Ioo (-R) R, is_O f (pow a) at_top, ∃ a ∈ Ioo 0 R, is_O f (pow a) at_top, ∃ (a < R) C (h₀ : 0 < C ∨ 0 < R), ∀ n, abs (f n) ≤ C * a ^ n, ∃ (a ∈ Ioo 0 R) (C > 0), ∀ n, abs (f n) ≤ C * a ^ n, ∃ a < R, ∀ᶠ n in at_top, abs (f n) ≤ a ^ n, ∃ a ∈ Ioo 0 R, ∀ᶠ n in at_top, abs (f n) ≤ a ^ n] := begin have A : Ico 0 R ⊆ Ioo (-R) R, from λ x hx, ⟨(neg_lt_zero.2 (hx.1.trans_lt hx.2)).trans_le hx.1, hx.2⟩, have B : Ioo 0 R ⊆ Ioo (-R) R := subset.trans Ioo_subset_Ico_self A, -- First we prove that 1-4 are equivalent using 2 → 3 → 4, 1 → 3, and 2 → 1 tfae_have : 1 → 3, from λ ⟨a, ha, H⟩, ⟨a, ha, H.is_O⟩, tfae_have : 2 → 1, from λ ⟨a, ha, H⟩, ⟨a, B ha, H⟩, tfae_have : 3 → 2, { rintro ⟨a, ha, H⟩, rcases exists_between (abs_lt.2 ha) with ⟨b, hab, hbR⟩, exact ⟨b, ⟨(abs_nonneg a).trans_lt hab, hbR⟩, H.trans_is_o (is_o_pow_pow_of_abs_lt_left (hab.trans_le (le_abs_self b)))⟩ }, tfae_have : 2 → 4, from λ ⟨a, ha, H⟩, ⟨a, ha, H.is_O⟩, tfae_have : 4 → 3, from λ ⟨a, ha, H⟩, ⟨a, B ha, H⟩, -- Add 5 and 6 using 4 → 6 → 5 → 3 tfae_have : 4 → 6, { rintro ⟨a, ha, H⟩, rcases bound_of_is_O_nat_at_top H with ⟨C, hC₀, hC⟩, refine ⟨a, ha, C, hC₀, λ n, _⟩, simpa only [real.norm_eq_abs, abs_pow, abs_of_nonneg ha.1.le] using hC (pow_ne_zero n ha.1.ne') }, tfae_have : 6 → 5, from λ ⟨a, ha, C, H₀, H⟩, ⟨a, ha.2, C, or.inl H₀, H⟩, tfae_have : 5 → 3, { rintro ⟨a, ha, C, h₀, H⟩, rcases sign_cases_of_C_mul_pow_nonneg (λ n, (abs_nonneg _).trans (H n)) with rfl | ⟨hC₀, ha₀⟩, { obtain rfl : f = 0, by { ext n, simpa using H n }, simp only [lt_irrefl, false_or] at h₀, exact ⟨0, ⟨neg_lt_zero.2 h₀, h₀⟩, is_O_zero _ _⟩ }, exact ⟨a, A ⟨ha₀, ha⟩, is_O_of_le' _ (λ n, (H n).trans $ mul_le_mul_of_nonneg_left (le_abs_self _) hC₀.le)⟩ }, -- Add 7 and 8 using 2 → 8 → 7 → 3 tfae_have : 2 → 8, { rintro ⟨a, ha, H⟩, refine ⟨a, ha, (H.def zero_lt_one).mono (λ n hn, _)⟩, rwa [real.norm_eq_abs, real.norm_eq_abs, one_mul, abs_pow, abs_of_pos ha.1] at hn }, tfae_have : 8 → 7, from λ ⟨a, ha, H⟩, ⟨a, ha.2, H⟩, tfae_have : 7 → 3, { rintro ⟨a, ha, H⟩, have : 0 ≤ a, from nonneg_of_eventually_pow_nonneg (H.mono $ λ n, (abs_nonneg _).trans), refine ⟨a, A ⟨this, ha⟩, is_O.of_bound 1 _⟩, simpa only [real.norm_eq_abs, one_mul, abs_pow, abs_of_nonneg this] }, tfae_finish end lemma uniformity_basis_dist_pow_of_lt_1 {α : Type*} [pseudo_metric_space α] {r : ℝ} (h₀ : 0 < r) (h₁ : r < 1) : (𝓤 α).has_basis (λ k : ℕ, true) (λ k, {p : α × α | dist p.1 p.2 < r ^ k}) := metric.mk_uniformity_basis (λ i _, pow_pos h₀ _) $ λ ε ε0, (exists_pow_lt_of_lt_one ε0 h₁).imp $ λ k hk, ⟨trivial, hk.le⟩ lemma geom_lt {u : ℕ → ℝ} {c : ℝ} (hc : 0 ≤ c) {n : ℕ} (hn : 0 < n) (h : ∀ k < n, c * u k < u (k + 1)) : c ^ n * u 0 < u n := begin refine (monotone_mul_left_of_nonneg hc).seq_pos_lt_seq_of_le_of_lt hn _ _ h, { simp }, { simp [pow_succ, mul_assoc, le_refl] } end lemma geom_le {u : ℕ → ℝ} {c : ℝ} (hc : 0 ≤ c) (n : ℕ) (h : ∀ k < n, c * u k ≤ u (k + 1)) : c ^ n * u 0 ≤ u n := by refine (monotone_mul_left_of_nonneg hc).seq_le_seq n _ _ h; simp [pow_succ, mul_assoc, le_refl] lemma lt_geom {u : ℕ → ℝ} {c : ℝ} (hc : 0 ≤ c) {n : ℕ} (hn : 0 < n) (h : ∀ k < n, u (k + 1) < c * u k) : u n < c ^ n * u 0 := begin refine (monotone_mul_left_of_nonneg hc).seq_pos_lt_seq_of_lt_of_le hn _ h _, { simp }, { simp [pow_succ, mul_assoc, le_refl] } end lemma le_geom {u : ℕ → ℝ} {c : ℝ} (hc : 0 ≤ c) (n : ℕ) (h : ∀ k < n, u (k + 1) ≤ c * u k) : u n ≤ (c ^ n) * u 0 := by refine (monotone_mul_left_of_nonneg hc).seq_le_seq n _ h _; simp [pow_succ, mul_assoc, le_refl] /-- For any natural `k` and a real `r > 1` we have `n ^ k = o(r ^ n)` as `n → ∞`. -/ lemma is_o_pow_const_const_pow_of_one_lt {R : Type*} [normed_ring R] (k : ℕ) {r : ℝ} (hr : 1 < r) : is_o (λ n, n ^ k : ℕ → R) (λ n, r ^ n) at_top := begin have : tendsto (λ x : ℝ, x ^ k) (𝓝[Ioi 1] 1) (𝓝 1), from ((continuous_id.pow k).tendsto' (1 : ℝ) 1 (one_pow _)).mono_left inf_le_left, obtain ⟨r' : ℝ, hr' : r' ^ k < r, h1 : 1 < r'⟩ := ((this.eventually (gt_mem_nhds hr)).and self_mem_nhds_within).exists, have h0 : 0 ≤ r' := zero_le_one.trans h1.le, suffices : is_O _ (λ n : ℕ, (r' ^ k) ^ n) at_top, from this.trans_is_o (is_o_pow_pow_of_lt_left (pow_nonneg h0 _) hr'), conv in ((r' ^ _) ^ _) { rw [← pow_mul, mul_comm, pow_mul] }, suffices : ∀ n : ℕ, ∥(n : R)∥ ≤ (r' - 1)⁻¹ * ∥(1 : R)∥ * ∥r' ^ n∥, from (is_O_of_le' _ this).pow _, intro n, rw mul_right_comm, refine n.norm_cast_le.trans (mul_le_mul_of_nonneg_right _ (norm_nonneg _)), simpa [div_eq_inv_mul, real.norm_eq_abs, abs_of_nonneg h0] using n.cast_le_pow_div_sub h1 end /-- For a real `r > 1` we have `n = o(r ^ n)` as `n → ∞`. -/ lemma is_o_coe_const_pow_of_one_lt {R : Type*} [normed_ring R] {r : ℝ} (hr : 1 < r) : is_o (coe : ℕ → R) (λ n, r ^ n) at_top := by simpa only [pow_one] using is_o_pow_const_const_pow_of_one_lt 1 hr /-- If `∥r₁∥ < r₂`, then for any naturak `k` we have `n ^ k r₁ ^ n = o (r₂ ^ n)` as `n → ∞`. -/ lemma is_o_pow_const_mul_const_pow_const_pow_of_norm_lt {R : Type*} [normed_ring R] (k : ℕ) {r₁ : R} {r₂ : ℝ} (h : ∥r₁∥ < r₂) : is_o (λ n, n ^ k * r₁ ^ n : ℕ → R) (λ n, r₂ ^ n) at_top := begin by_cases h0 : r₁ = 0, { refine (is_o_zero _ _).congr' (mem_at_top_sets.2 $ ⟨1, λ n hn, _⟩) eventually_eq.rfl, simp [zero_pow (zero_lt_one.trans_le hn), h0] }, rw [← ne.def, ← norm_pos_iff] at h0, have A : is_o (λ n, n ^ k : ℕ → R) (λ n, (r₂ / ∥r₁∥) ^ n) at_top, from is_o_pow_const_const_pow_of_one_lt k ((one_lt_div h0).2 h), suffices : is_O (λ n, r₁ ^ n) (λ n, ∥r₁∥ ^ n) at_top, by simpa [div_mul_cancel _ (pow_pos h0 _).ne'] using A.mul_is_O this, exact is_O.of_bound 1 (by simpa using eventually_norm_pow_le r₁) end lemma tendsto_pow_const_div_const_pow_of_one_lt (k : ℕ) {r : ℝ} (hr : 1 < r) : tendsto (λ n, n ^ k / r ^ n : ℕ → ℝ) at_top (𝓝 0) := (is_o_pow_const_const_pow_of_one_lt k hr).tendsto_0 /-- If `|r| < 1`, then `n ^ k r ^ n` tends to zero for any natural `k`. -/ lemma tendsto_pow_const_mul_const_pow_of_abs_lt_one (k : ℕ) {r : ℝ} (hr : abs r < 1) : tendsto (λ n, n ^ k * r ^ n : ℕ → ℝ) at_top (𝓝 0) := begin by_cases h0 : r = 0, { exact tendsto_const_nhds.congr' (mem_at_top_sets.2 ⟨1, λ n hn, by simp [zero_lt_one.trans_le hn, h0]⟩) }, have hr' : 1 < (abs r)⁻¹, from one_lt_inv (abs_pos.2 h0) hr, rw tendsto_zero_iff_norm_tendsto_zero, simpa [div_eq_mul_inv] using tendsto_pow_const_div_const_pow_of_one_lt k hr' end /-- If a sequence `v` of real numbers satisfies `k * v n ≤ v (n+1)` with `1 < k`, then it goes to +∞. -/ lemma tendsto_at_top_of_geom_le {v : ℕ → ℝ} {c : ℝ} (h₀ : 0 < v 0) (hc : 1 < c) (hu : ∀ n, c * v n ≤ v (n + 1)) : tendsto v at_top at_top := tendsto_at_top_mono (λ n, geom_le (zero_le_one.trans hc.le) n (λ k hk, hu k)) $ (tendsto_pow_at_top_at_top_of_one_lt hc).at_top_mul_const h₀ lemma nnreal.tendsto_pow_at_top_nhds_0_of_lt_1 {r : ℝ≥0} (hr : r < 1) : tendsto (λ n:ℕ, r^n) at_top (𝓝 0) := nnreal.tendsto_coe.1 $ by simp only [nnreal.coe_pow, nnreal.coe_zero, tendsto_pow_at_top_nhds_0_of_lt_1 r.coe_nonneg hr] lemma ennreal.tendsto_pow_at_top_nhds_0_of_lt_1 {r : ℝ≥0∞} (hr : r < 1) : tendsto (λ n:ℕ, r^n) at_top (𝓝 0) := begin rcases ennreal.lt_iff_exists_coe.1 hr with ⟨r, rfl, hr'⟩, rw [← ennreal.coe_zero], norm_cast at *, apply nnreal.tendsto_pow_at_top_nhds_0_of_lt_1 hr end /-- In a normed ring, the powers of an element x with `∥x∥ < 1` tend to zero. -/ lemma tendsto_pow_at_top_nhds_0_of_norm_lt_1 {R : Type*} [normed_ring R] {x : R} (h : ∥x∥ < 1) : tendsto (λ (n : ℕ), x ^ n) at_top (𝓝 0) := begin apply squeeze_zero_norm' (eventually_norm_pow_le x), exact tendsto_pow_at_top_nhds_0_of_lt_1 (norm_nonneg _) h, end lemma tendsto_pow_at_top_nhds_0_of_abs_lt_1 {r : ℝ} (h : abs r < 1) : tendsto (λn:ℕ, r^n) at_top (𝓝 0) := tendsto_pow_at_top_nhds_0_of_norm_lt_1 h /-! ### Geometric series-/ section geometric lemma has_sum_geometric_of_lt_1 {r : ℝ} (h₁ : 0 ≤ r) (h₂ : r < 1) : has_sum (λn:ℕ, r ^ n) (1 - r)⁻¹ := have r ≠ 1, from ne_of_lt h₂, have tendsto (λn, (r ^ n - 1) * (r - 1)⁻¹) at_top (𝓝 ((0 - 1) * (r - 1)⁻¹)), from ((tendsto_pow_at_top_nhds_0_of_lt_1 h₁ h₂).sub tendsto_const_nhds).mul tendsto_const_nhds, have (λ n, (∑ i in range n, r ^ i)) = (λ n, geom_sum r n) := rfl, (has_sum_iff_tendsto_nat_of_nonneg (pow_nonneg h₁) _).mpr $ by simp [neg_inv, geom_sum_eq, div_eq_mul_inv, *] at * lemma summable_geometric_of_lt_1 {r : ℝ} (h₁ : 0 ≤ r) (h₂ : r < 1) : summable (λn:ℕ, r ^ n) := ⟨_, has_sum_geometric_of_lt_1 h₁ h₂⟩ lemma tsum_geometric_of_lt_1 {r : ℝ} (h₁ : 0 ≤ r) (h₂ : r < 1) : ∑'n:ℕ, r ^ n = (1 - r)⁻¹ := (has_sum_geometric_of_lt_1 h₁ h₂).tsum_eq lemma has_sum_geometric_two : has_sum (λn:ℕ, ((1:ℝ)/2) ^ n) 2 := by convert has_sum_geometric_of_lt_1 _ _; norm_num lemma summable_geometric_two : summable (λn:ℕ, ((1:ℝ)/2) ^ n) := ⟨_, has_sum_geometric_two⟩ lemma tsum_geometric_two : ∑'n:ℕ, ((1:ℝ)/2) ^ n = 2 := has_sum_geometric_two.tsum_eq lemma sum_geometric_two_le (n : ℕ) : ∑ (i : ℕ) in range n, (1 / (2 : ℝ)) ^ i ≤ 2 := begin have : ∀ i, 0 ≤ (1 / (2 : ℝ)) ^ i, { intro i, apply pow_nonneg, norm_num }, convert sum_le_tsum (range n) (λ i _, this i) summable_geometric_two, exact tsum_geometric_two.symm end lemma has_sum_geometric_two' (a : ℝ) : has_sum (λn:ℕ, (a / 2) / 2 ^ n) a := begin convert has_sum.mul_left (a / 2) (has_sum_geometric_of_lt_1 (le_of_lt one_half_pos) one_half_lt_one), { funext n, simp, refl, }, { norm_num } end lemma summable_geometric_two' (a : ℝ) : summable (λ n:ℕ, (a / 2) / 2 ^ n) := ⟨a, has_sum_geometric_two' a⟩ lemma tsum_geometric_two' (a : ℝ) : ∑' n:ℕ, (a / 2) / 2^n = a := (has_sum_geometric_two' a).tsum_eq /-- **Sum of a Geometric Series** -/ lemma nnreal.has_sum_geometric {r : ℝ≥0} (hr : r < 1) : has_sum (λ n : ℕ, r ^ n) (1 - r)⁻¹ := begin apply nnreal.has_sum_coe.1, push_cast, rw [nnreal.coe_sub (le_of_lt hr)], exact has_sum_geometric_of_lt_1 r.coe_nonneg hr end lemma nnreal.summable_geometric {r : ℝ≥0} (hr : r < 1) : summable (λn:ℕ, r ^ n) := ⟨_, nnreal.has_sum_geometric hr⟩ lemma tsum_geometric_nnreal {r : ℝ≥0} (hr : r < 1) : ∑'n:ℕ, r ^ n = (1 - r)⁻¹ := (nnreal.has_sum_geometric hr).tsum_eq /-- The series `pow r` converges to `(1-r)⁻¹`. For `r < 1` the RHS is a finite number, and for `1 ≤ r` the RHS equals `∞`. -/ @[simp] lemma ennreal.tsum_geometric (r : ℝ≥0∞) : ∑'n:ℕ, r ^ n = (1 - r)⁻¹ := begin cases lt_or_le r 1 with hr hr, { rcases ennreal.lt_iff_exists_coe.1 hr with ⟨r, rfl, hr'⟩, norm_cast at *, convert ennreal.tsum_coe_eq (nnreal.has_sum_geometric hr), rw [ennreal.coe_inv $ ne_of_gt $ nnreal.sub_pos.2 hr] }, { rw [ennreal.sub_eq_zero_of_le hr, ennreal.inv_zero, ennreal.tsum_eq_supr_nat, supr_eq_top], refine λ a ha, (ennreal.exists_nat_gt (lt_top_iff_ne_top.1 ha)).imp (λ n hn, lt_of_lt_of_le hn _), have : ∀ k:ℕ, 1 ≤ r^k, by simpa using canonically_ordered_comm_semiring.pow_le_pow_of_le_left hr, calc (n:ℝ≥0∞) = (∑ i in range n, 1) : by rw [sum_const, nsmul_one, card_range] ... ≤ ∑ i in range n, r ^ i : sum_le_sum (λ k _, this k) } end variables {K : Type*} [normed_field K] {ξ : K} lemma has_sum_geometric_of_norm_lt_1 (h : ∥ξ∥ < 1) : has_sum (λn:ℕ, ξ ^ n) (1 - ξ)⁻¹ := begin have xi_ne_one : ξ ≠ 1, by { contrapose! h, simp [h] }, have A : tendsto (λn, (ξ ^ n - 1) * (ξ - 1)⁻¹) at_top (𝓝 ((0 - 1) * (ξ - 1)⁻¹)), from ((tendsto_pow_at_top_nhds_0_of_norm_lt_1 h).sub tendsto_const_nhds).mul tendsto_const_nhds, have B : (λ n, (∑ i in range n, ξ ^ i)) = (λ n, geom_sum ξ n) := rfl, rw [has_sum_iff_tendsto_nat_of_summable_norm, B], { simpa [geom_sum_eq, xi_ne_one, neg_inv, div_eq_mul_inv] using A }, { simp [normed_field.norm_pow, summable_geometric_of_lt_1 (norm_nonneg _) h] } end lemma summable_geometric_of_norm_lt_1 (h : ∥ξ∥ < 1) : summable (λn:ℕ, ξ ^ n) := ⟨_, has_sum_geometric_of_norm_lt_1 h⟩ lemma tsum_geometric_of_norm_lt_1 (h : ∥ξ∥ < 1) : ∑'n:ℕ, ξ ^ n = (1 - ξ)⁻¹ := (has_sum_geometric_of_norm_lt_1 h).tsum_eq lemma has_sum_geometric_of_abs_lt_1 {r : ℝ} (h : abs r < 1) : has_sum (λn:ℕ, r ^ n) (1 - r)⁻¹ := has_sum_geometric_of_norm_lt_1 h lemma summable_geometric_of_abs_lt_1 {r : ℝ} (h : abs r < 1) : summable (λn:ℕ, r ^ n) := summable_geometric_of_norm_lt_1 h lemma tsum_geometric_of_abs_lt_1 {r : ℝ} (h : abs r < 1) : ∑'n:ℕ, r ^ n = (1 - r)⁻¹ := tsum_geometric_of_norm_lt_1 h /-- A geometric series in a normed field is summable iff the norm of the common ratio is less than one. -/ @[simp] lemma summable_geometric_iff_norm_lt_1 : summable (λ n : ℕ, ξ ^ n) ↔ ∥ξ∥ < 1 := begin refine ⟨λ h, _, summable_geometric_of_norm_lt_1⟩, obtain ⟨k : ℕ, hk : dist (ξ ^ k) 0 < 1⟩ := (h.tendsto_cofinite_zero.eventually (ball_mem_nhds _ zero_lt_one)).exists, simp only [normed_field.norm_pow, dist_zero_right] at hk, rw [← one_pow k] at hk, exact lt_of_pow_lt_pow _ zero_le_one hk end end geometric section mul_geometric lemma summable_norm_pow_mul_geometric_of_norm_lt_1 {R : Type*} [normed_ring R] (k : ℕ) {r : R} (hr : ∥r∥ < 1) : summable (λ n : ℕ, ∥(n ^ k * r ^ n : R)∥) := begin rcases exists_between hr with ⟨r', hrr', h⟩, exact summable_of_is_O_nat _ (summable_geometric_of_lt_1 ((norm_nonneg _).trans hrr'.le) h) (is_o_pow_const_mul_const_pow_const_pow_of_norm_lt _ hrr').is_O.norm_left end lemma summable_pow_mul_geometric_of_norm_lt_1 {R : Type*} [normed_ring R] [complete_space R] (k : ℕ) {r : R} (hr : ∥r∥ < 1) : summable (λ n, n ^ k * r ^ n : ℕ → R) := summable_of_summable_norm $ summable_norm_pow_mul_geometric_of_norm_lt_1 _ hr /-- If `∥r∥ < 1`, then `∑' n : ℕ, n * r ^ n = r / (1 - r) ^ 2`, `has_sum` version. -/ lemma has_sum_coe_mul_geometric_of_norm_lt_1 {𝕜 : Type*} [normed_field 𝕜] [complete_space 𝕜] {r : 𝕜} (hr : ∥r∥ < 1) : has_sum (λ n, n * r ^ n : ℕ → 𝕜) (r / (1 - r) ^ 2) := begin have A : summable (λ n, n * r ^ n : ℕ → 𝕜), by simpa using summable_pow_mul_geometric_of_norm_lt_1 1 hr, have B : has_sum (pow r : ℕ → 𝕜) (1 - r)⁻¹, from has_sum_geometric_of_norm_lt_1 hr, refine A.has_sum_iff.2 _, have hr' : r ≠ 1, by { rintro rfl, simpa [lt_irrefl] using hr }, set s : 𝕜 := ∑' n : ℕ, n * r ^ n, calc s = (1 - r) * s / (1 - r) : (mul_div_cancel_left _ (sub_ne_zero.2 hr'.symm)).symm ... = (s - r * s) / (1 - r) : by rw [sub_mul, one_mul] ... = ((0 : ℕ) * r ^ 0 + (∑' n : ℕ, (n + 1) * r ^ (n + 1)) - r * s) / (1 - r) : by { congr, exact tsum_eq_zero_add A } ... = (r * (∑' n : ℕ, (n + 1) * r ^ n) - r * s) / (1 - r) : by simp [pow_succ, mul_left_comm _ r, tsum_mul_left] ... = r / (1 - r) ^ 2 : by simp [add_mul, tsum_add A B.summable, mul_add, B.tsum_eq, ← div_eq_mul_inv, sq, div_div_eq_div_mul] end /-- If `∥r∥ < 1`, then `∑' n : ℕ, n * r ^ n = r / (1 - r) ^ 2`. -/ lemma tsum_coe_mul_geometric_of_norm_lt_1 {𝕜 : Type*} [normed_field 𝕜] [complete_space 𝕜] {r : 𝕜} (hr : ∥r∥ < 1) : (∑' n : ℕ, n * r ^ n : 𝕜) = (r / (1 - r) ^ 2) := (has_sum_coe_mul_geometric_of_norm_lt_1 hr).tsum_eq end mul_geometric /-! ### Sequences with geometrically decaying distance in metric spaces In this paragraph, we discuss sequences in metric spaces or emetric spaces for which the distance between two consecutive terms decays geometrically. We show that such sequences are Cauchy sequences, and bound their distances to the limit. We also discuss series with geometrically decaying terms. -/ section edist_le_geometric variables [pseudo_emetric_space α] (r C : ℝ≥0∞) (hr : r < 1) (hC : C ≠ ⊤) {f : ℕ → α} (hu : ∀n, edist (f n) (f (n+1)) ≤ C * r^n) include hr hC hu /-- If `edist (f n) (f (n+1))` is bounded by `C * r^n`, `C ≠ ∞`, `r < 1`, then `f` is a Cauchy sequence.-/ lemma cauchy_seq_of_edist_le_geometric : cauchy_seq f := begin refine cauchy_seq_of_edist_le_of_tsum_ne_top _ hu _, rw [ennreal.tsum_mul_left, ennreal.tsum_geometric], refine ennreal.mul_ne_top hC (ennreal.inv_ne_top.2 _), exact ne_of_gt (ennreal.zero_lt_sub_iff_lt.2 hr) end omit hr hC /-- If `edist (f n) (f (n+1))` is bounded by `C * r^n`, then the distance from `f n` to the limit of `f` is bounded above by `C * r^n / (1 - r)`. -/ lemma edist_le_of_edist_le_geometric_of_tendsto {a : α} (ha : tendsto f at_top (𝓝 a)) (n : ℕ) : edist (f n) a ≤ (C * r^n) / (1 - r) := begin convert edist_le_tsum_of_edist_le_of_tendsto _ hu ha _, simp only [pow_add, ennreal.tsum_mul_left, ennreal.tsum_geometric, div_eq_mul_inv, mul_assoc] end /-- If `edist (f n) (f (n+1))` is bounded by `C * r^n`, then the distance from `f 0` to the limit of `f` is bounded above by `C / (1 - r)`. -/ lemma edist_le_of_edist_le_geometric_of_tendsto₀ {a : α} (ha : tendsto f at_top (𝓝 a)) : edist (f 0) a ≤ C / (1 - r) := by simpa only [pow_zero, mul_one] using edist_le_of_edist_le_geometric_of_tendsto r C hu ha 0 end edist_le_geometric section edist_le_geometric_two variables [pseudo_emetric_space α] (C : ℝ≥0∞) (hC : C ≠ ⊤) {f : ℕ → α} (hu : ∀n, edist (f n) (f (n+1)) ≤ C / 2^n) {a : α} (ha : tendsto f at_top (𝓝 a)) include hC hu /-- If `edist (f n) (f (n+1))` is bounded by `C * 2^-n`, then `f` is a Cauchy sequence.-/ lemma cauchy_seq_of_edist_le_geometric_two : cauchy_seq f := begin simp only [div_eq_mul_inv, ennreal.inv_pow] at hu, refine cauchy_seq_of_edist_le_geometric 2⁻¹ C _ hC hu, simp [ennreal.one_lt_two] end omit hC include ha /-- If `edist (f n) (f (n+1))` is bounded by `C * 2^-n`, then the distance from `f n` to the limit of `f` is bounded above by `2 * C * 2^-n`. -/ lemma edist_le_of_edist_le_geometric_two_of_tendsto (n : ℕ) : edist (f n) a ≤ 2 * C / 2^n := begin simp only [div_eq_mul_inv, ennreal.inv_pow] at *, rw [mul_assoc, mul_comm], convert edist_le_of_edist_le_geometric_of_tendsto 2⁻¹ C hu ha n, rw [ennreal.one_sub_inv_two, ennreal.inv_inv] end /-- If `edist (f n) (f (n+1))` is bounded by `C * 2^-n`, then the distance from `f 0` to the limit of `f` is bounded above by `2 * C`. -/ lemma edist_le_of_edist_le_geometric_two_of_tendsto₀: edist (f 0) a ≤ 2 * C := by simpa only [pow_zero, div_eq_mul_inv, ennreal.inv_one, mul_one] using edist_le_of_edist_le_geometric_two_of_tendsto C hu ha 0 end edist_le_geometric_two section le_geometric variables [pseudo_metric_space α] {r C : ℝ} (hr : r < 1) {f : ℕ → α} (hu : ∀n, dist (f n) (f (n+1)) ≤ C * r^n) include hr hu lemma aux_has_sum_of_le_geometric : has_sum (λ n : ℕ, C * r^n) (C / (1 - r)) := begin rcases sign_cases_of_C_mul_pow_nonneg (λ n, dist_nonneg.trans (hu n)) with rfl | ⟨C₀, r₀⟩, { simp [has_sum_zero] }, { refine has_sum.mul_left C _, simpa using has_sum_geometric_of_lt_1 r₀ hr } end variables (r C) /-- If `dist (f n) (f (n+1))` is bounded by `C * r^n`, `r < 1`, then `f` is a Cauchy sequence. Note that this lemma does not assume `0 ≤ C` or `0 ≤ r`. -/ lemma cauchy_seq_of_le_geometric : cauchy_seq f := cauchy_seq_of_dist_le_of_summable _ hu ⟨_, aux_has_sum_of_le_geometric hr hu⟩ /-- If `dist (f n) (f (n+1))` is bounded by `C * r^n`, `r < 1`, then the distance from `f n` to the limit of `f` is bounded above by `C * r^n / (1 - r)`. -/ lemma dist_le_of_le_geometric_of_tendsto₀ {a : α} (ha : tendsto f at_top (𝓝 a)) : dist (f 0) a ≤ C / (1 - r) := (aux_has_sum_of_le_geometric hr hu).tsum_eq ▸ dist_le_tsum_of_dist_le_of_tendsto₀ _ hu ⟨_, aux_has_sum_of_le_geometric hr hu⟩ ha /-- If `dist (f n) (f (n+1))` is bounded by `C * r^n`, `r < 1`, then the distance from `f 0` to the limit of `f` is bounded above by `C / (1 - r)`. -/ lemma dist_le_of_le_geometric_of_tendsto {a : α} (ha : tendsto f at_top (𝓝 a)) (n : ℕ) : dist (f n) a ≤ (C * r^n) / (1 - r) := begin have := aux_has_sum_of_le_geometric hr hu, convert dist_le_tsum_of_dist_le_of_tendsto _ hu ⟨_, this⟩ ha n, simp only [pow_add, mul_left_comm C, mul_div_right_comm], rw [mul_comm], exact (this.mul_left _).tsum_eq.symm end omit hr hu variable (hu₂ : ∀ n, dist (f n) (f (n+1)) ≤ (C / 2) / 2^n) /-- If `dist (f n) (f (n+1))` is bounded by `(C / 2) / 2^n`, then `f` is a Cauchy sequence. -/ lemma cauchy_seq_of_le_geometric_two : cauchy_seq f := cauchy_seq_of_dist_le_of_summable _ hu₂ $ ⟨_, has_sum_geometric_two' C⟩ /-- If `dist (f n) (f (n+1))` is bounded by `(C / 2) / 2^n`, then the distance from `f 0` to the limit of `f` is bounded above by `C`. -/ lemma dist_le_of_le_geometric_two_of_tendsto₀ {a : α} (ha : tendsto f at_top (𝓝 a)) : dist (f 0) a ≤ C := (tsum_geometric_two' C) ▸ dist_le_tsum_of_dist_le_of_tendsto₀ _ hu₂ (summable_geometric_two' C) ha include hu₂ /-- If `dist (f n) (f (n+1))` is bounded by `(C / 2) / 2^n`, then the distance from `f n` to the limit of `f` is bounded above by `C / 2^n`. -/ lemma dist_le_of_le_geometric_two_of_tendsto {a : α} (ha : tendsto f at_top (𝓝 a)) (n : ℕ) : dist (f n) a ≤ C / 2^n := begin convert dist_le_tsum_of_dist_le_of_tendsto _ hu₂ (summable_geometric_two' C) ha n, simp only [add_comm n, pow_add, ← div_div_eq_div_mul], symmetry, exact ((has_sum_geometric_two' C).div_const _).tsum_eq end end le_geometric section summable_le_geometric variables [semi_normed_group α] {r C : ℝ} {f : ℕ → α} lemma semi_normed_group.cauchy_seq_of_le_geometric {C : ℝ} {r : ℝ} (hr : r < 1) {u : ℕ → α} (h : ∀ n, ∥u n - u (n + 1)∥ ≤ C*r^n) : cauchy_seq u := cauchy_seq_of_le_geometric r C hr (by simpa [dist_eq_norm] using h) lemma dist_partial_sum_le_of_le_geometric (hf : ∀n, ∥f n∥ ≤ C * r^n) (n : ℕ) : dist (∑ i in range n, f i) (∑ i in range (n+1), f i) ≤ C * r ^ n := begin rw [sum_range_succ, dist_eq_norm, ← norm_neg, neg_sub, add_sub_cancel'], exact hf n, end /-- If `∥f n∥ ≤ C * r ^ n` for all `n : ℕ` and some `r < 1`, then the partial sums of `f` form a Cauchy sequence. This lemma does not assume `0 ≤ r` or `0 ≤ C`. -/ lemma cauchy_seq_finset_of_geometric_bound (hr : r < 1) (hf : ∀n, ∥f n∥ ≤ C * r^n) : cauchy_seq (λ s : finset (ℕ), ∑ x in s, f x) := cauchy_seq_finset_of_norm_bounded _ (aux_has_sum_of_le_geometric hr (dist_partial_sum_le_of_le_geometric hf)).summable hf /-- If `∥f n∥ ≤ C * r ^ n` for all `n : ℕ` and some `r < 1`, then the partial sums of `f` are within distance `C * r ^ n / (1 - r)` of the sum of the series. This lemma does not assume `0 ≤ r` or `0 ≤ C`. -/ lemma norm_sub_le_of_geometric_bound_of_has_sum (hr : r < 1) (hf : ∀n, ∥f n∥ ≤ C * r^n) {a : α} (ha : has_sum f a) (n : ℕ) : ∥(∑ x in finset.range n, f x) - a∥ ≤ (C * r ^ n) / (1 - r) := begin rw ← dist_eq_norm, apply dist_le_of_le_geometric_of_tendsto r C hr (dist_partial_sum_le_of_le_geometric hf), exact ha.tendsto_sum_nat end @[simp] lemma dist_partial_sum (u : ℕ → α) (n : ℕ) : dist (∑ k in range (n + 1), u k) (∑ k in range n, u k) = ∥u n∥ := by simp [dist_eq_norm, sum_range_succ] @[simp] lemma dist_partial_sum' (u : ℕ → α) (n : ℕ) : dist (∑ k in range n, u k) (∑ k in range (n+1), u k) = ∥u n∥ := by simp [dist_eq_norm', sum_range_succ] lemma cauchy_series_of_le_geometric {C : ℝ} {u : ℕ → α} {r : ℝ} (hr : r < 1) (h : ∀ n, ∥u n∥ ≤ C*r^n) : cauchy_seq (λ n, ∑ k in range n, u k) := cauchy_seq_of_le_geometric r C hr (by simp [h]) lemma normed_group.cauchy_series_of_le_geometric' {C : ℝ} {u : ℕ → α} {r : ℝ} (hr : r < 1) (h : ∀ n, ∥u n∥ ≤ C*r^n) : cauchy_seq (λ n, ∑ k in range (n + 1), u k) := begin by_cases hC : C = 0, { subst hC, simp at h, exact cauchy_seq_of_le_geometric 0 0 zero_lt_one (by simp [h]) }, have : 0 ≤ C, { simpa using (norm_nonneg _).trans (h 0) }, replace hC : 0 < C, from (ne.symm hC).le_iff_lt.mp this, have : 0 ≤ r, { have := (norm_nonneg _).trans (h 1), rw pow_one at this, exact (zero_le_mul_left hC).mp this }, simp_rw finset.sum_range_succ_comm, have : cauchy_seq u, { apply tendsto.cauchy_seq, apply squeeze_zero_norm h, rw show 0 = C*0, by simp, exact tendsto_const_nhds.mul (tendsto_pow_at_top_nhds_0_of_lt_1 this hr) }, exact this.add (cauchy_series_of_le_geometric hr h), end lemma normed_group.cauchy_series_of_le_geometric'' {C : ℝ} {u : ℕ → α} {N : ℕ} {r : ℝ} (hr₀ : 0 < r) (hr₁ : r < 1) (h : ∀ n ≥ N, ∥u n∥ ≤ C*r^n) : cauchy_seq (λ n, ∑ k in range (n + 1), u k) := begin set v : ℕ → α := λ n, if n < N then 0 else u n, have hC : 0 ≤ C, from (zero_le_mul_right $ pow_pos hr₀ N).mp ((norm_nonneg _).trans $ h N $ le_refl N), have : ∀ n ≥ N, u n = v n, { intros n hn, simp [v, hn, if_neg (not_lt.mpr hn)] }, refine cauchy_seq_sum_of_eventually_eq this (normed_group.cauchy_series_of_le_geometric' hr₁ _), { exact C }, intro n, dsimp [v], split_ifs with H H, { rw norm_zero, exact mul_nonneg hC (pow_nonneg hr₀.le _) }, { push_neg at H, exact h _ H } end end summable_le_geometric section normed_ring_geometric variables {R : Type*} [normed_ring R] [complete_space R] open normed_space /-- A geometric series in a complete normed ring is summable. Proved above (same name, different namespace) for not-necessarily-complete normed fields. -/ lemma normed_ring.summable_geometric_of_norm_lt_1 (x : R) (h : ∥x∥ < 1) : summable (λ (n:ℕ), x ^ n) := begin have h1 : summable (λ (n:ℕ), ∥x∥ ^ n) := summable_geometric_of_lt_1 (norm_nonneg _) h, refine summable_of_norm_bounded_eventually _ h1 _, rw nat.cofinite_eq_at_top, exact eventually_norm_pow_le x, end /-- Bound for the sum of a geometric series in a normed ring. This formula does not assume that the normed ring satisfies the axiom `∥1∥ = 1`. -/ lemma normed_ring.tsum_geometric_of_norm_lt_1 (x : R) (h : ∥x∥ < 1) : ∥∑' n:ℕ, x ^ n∥ ≤ ∥(1:R)∥ - 1 + (1 - ∥x∥)⁻¹ := begin rw tsum_eq_zero_add (normed_ring.summable_geometric_of_norm_lt_1 x h), simp only [pow_zero], refine le_trans (norm_add_le _ _) _, have : ∥∑' b : ℕ, (λ n, x ^ (n + 1)) b∥ ≤ (1 - ∥x∥)⁻¹ - 1, { refine tsum_of_norm_bounded _ (λ b, norm_pow_le' _ (nat.succ_pos b)), convert (has_sum_nat_add_iff' 1).mpr (has_sum_geometric_of_lt_1 (norm_nonneg x) h), simp }, linarith end lemma geom_series_mul_neg (x : R) (h : ∥x∥ < 1) : (∑' i:ℕ, x ^ i) * (1 - x) = 1 := begin have := ((normed_ring.summable_geometric_of_norm_lt_1 x h).has_sum.mul_right (1 - x)), refine tendsto_nhds_unique this.tendsto_sum_nat _, have : tendsto (λ (n : ℕ), 1 - x ^ n) at_top (𝓝 1), { simpa using tendsto_const_nhds.sub (tendsto_pow_at_top_nhds_0_of_norm_lt_1 h) }, convert ← this, ext n, rw [←geom_sum_mul_neg, geom_sum_def, finset.sum_mul], end lemma mul_neg_geom_series (x : R) (h : ∥x∥ < 1) : (1 - x) * ∑' i:ℕ, x ^ i = 1 := begin have := (normed_ring.summable_geometric_of_norm_lt_1 x h).has_sum.mul_left (1 - x), refine tendsto_nhds_unique this.tendsto_sum_nat _, have : tendsto (λ (n : ℕ), 1 - x ^ n) at_top (nhds 1), { simpa using tendsto_const_nhds.sub (tendsto_pow_at_top_nhds_0_of_norm_lt_1 h) }, convert ← this, ext n, rw [←mul_neg_geom_sum, geom_sum_def, finset.mul_sum] end end normed_ring_geometric /-! ### Summability tests based on comparison with geometric series -/ lemma summable_of_ratio_norm_eventually_le {α : Type*} [semi_normed_group α] [complete_space α] {f : ℕ → α} {r : ℝ} (hr₁ : r < 1) (h : ∀ᶠ n in at_top, ∥f (n+1)∥ ≤ r * ∥f n∥) : summable f := begin by_cases hr₀ : 0 ≤ r, { rw eventually_at_top at h, rcases h with ⟨N, hN⟩, rw ← @summable_nat_add_iff α _ _ _ _ N, refine summable_of_norm_bounded (λ n, ∥f N∥ * r^n) (summable.mul_left _ $ summable_geometric_of_lt_1 hr₀ hr₁) (λ n, _), conv_rhs {rw [mul_comm, ← zero_add N]}, refine le_geom hr₀ n (λ i _, _), convert hN (i + N) (N.le_add_left i) using 3, ac_refl }, { push_neg at hr₀, refine summable_of_norm_bounded_eventually 0 summable_zero _, rw nat.cofinite_eq_at_top, filter_upwards [h], intros n hn, by_contra h, push_neg at h, exact not_lt.mpr (norm_nonneg _) (lt_of_le_of_lt hn $ mul_neg_of_neg_of_pos hr₀ h) } end lemma summable_of_ratio_test_tendsto_lt_one {α : Type*} [normed_group α] [complete_space α] {f : ℕ → α} {l : ℝ} (hl₁ : l < 1) (hf : ∀ᶠ n in at_top, f n ≠ 0) (h : tendsto (λ n, ∥f (n+1)∥/∥f n∥) at_top (𝓝 l)) : summable f := begin rcases exists_between hl₁ with ⟨r, hr₀, hr₁⟩, refine summable_of_ratio_norm_eventually_le hr₁ _, filter_upwards [eventually_le_of_tendsto_lt hr₀ h, hf], intros n h₀ h₁, rwa ← div_le_iff (norm_pos_iff.mpr h₁) end lemma not_summable_of_ratio_norm_eventually_ge {α : Type*} [semi_normed_group α] {f : ℕ → α} {r : ℝ} (hr : 1 < r) (hf : ∃ᶠ n in at_top, ∥f n∥ ≠ 0) (h : ∀ᶠ n in at_top, r * ∥f n∥ ≤ ∥f (n+1)∥) : ¬ summable f := begin rw eventually_at_top at h, rcases h with ⟨N₀, hN₀⟩, rw frequently_at_top at hf, rcases hf N₀ with ⟨N, hNN₀ : N₀ ≤ N, hN⟩, rw ← @summable_nat_add_iff α _ _ _ _ N, refine mt summable.tendsto_at_top_zero (λ h', not_tendsto_at_top_of_tendsto_nhds (tendsto_norm_zero.comp h') _), convert tendsto_at_top_of_geom_le _ hr _, { refine lt_of_le_of_ne (norm_nonneg _) _, intro h'', specialize hN₀ N hNN₀, simp only [comp_app, zero_add] at h'', exact hN h''.symm }, { intro i, dsimp only [comp_app], convert (hN₀ (i + N) (hNN₀.trans (N.le_add_left i))) using 3, ac_refl } end lemma not_summable_of_ratio_test_tendsto_gt_one {α : Type*} [semi_normed_group α] {f : ℕ → α} {l : ℝ} (hl : 1 < l) (h : tendsto (λ n, ∥f (n+1)∥/∥f n∥) at_top (𝓝 l)) : ¬ summable f := begin have key : ∀ᶠ n in at_top, ∥f n∥ ≠ 0, { filter_upwards [eventually_ge_of_tendsto_gt hl h], intros n hn hc, rw [hc, div_zero] at hn, linarith }, rcases exists_between hl with ⟨r, hr₀, hr₁⟩, refine not_summable_of_ratio_norm_eventually_ge hr₀ key.frequently _, filter_upwards [eventually_ge_of_tendsto_gt hr₁ h, key], intros n h₀ h₁, rwa ← le_div_iff (lt_of_le_of_ne (norm_nonneg _) h₁.symm) end /-- A series whose terms are bounded by the terms of a converging geometric series converges. -/ lemma summable_one_div_pow_of_le {m : ℝ} {f : ℕ → ℕ} (hm : 1 < m) (fi : ∀ i, i ≤ f i) : summable (λ i, 1 / m ^ f i) := begin refine summable_of_nonneg_of_le (λ a, one_div_nonneg.mpr (pow_nonneg (zero_le_one.trans hm.le) _)) (λ a, _) (summable_geometric_of_lt_1 (one_div_nonneg.mpr (zero_le_one.trans hm.le)) ((one_div_lt (zero_lt_one.trans hm) zero_lt_one).mpr (one_div_one.le.trans_lt hm))), rw [div_pow, one_pow], refine (one_div_le_one_div _ _).mpr (pow_le_pow hm.le (fi a)); exact pow_pos (zero_lt_one.trans hm) _ end /-! ### Positive sequences with small sums on encodable types -/ /-- For any positive `ε`, define on an encodable type a positive sequence with sum less than `ε` -/ def pos_sum_of_encodable {ε : ℝ} (hε : 0 < ε) (ι) [encodable ι] : {ε' : ι → ℝ // (∀ i, 0 < ε' i) ∧ ∃ c, has_sum ε' c ∧ c ≤ ε} := begin let f := λ n, (ε / 2) / 2 ^ n, have hf : has_sum f ε := has_sum_geometric_two' _, have f0 : ∀ n, 0 < f n := λ n, div_pos (half_pos hε) (pow_pos zero_lt_two _), refine ⟨f ∘ encodable.encode, λ i, f0 _, _⟩, rcases hf.summable.comp_injective (@encodable.encode_injective ι _) with ⟨c, hg⟩, refine ⟨c, hg, has_sum_le_inj _ (@encodable.encode_injective ι _) _ _ hg hf⟩, { assume i _, exact le_of_lt (f0 _) }, { assume n, exact le_refl _ } end namespace nnreal theorem exists_pos_sum_of_encodable {ε : ℝ≥0} (hε : 0 < ε) (ι) [encodable ι] : ∃ ε' : ι → ℝ≥0, (∀ i, 0 < ε' i) ∧ ∃c, has_sum ε' c ∧ c < ε := let ⟨a, a0, aε⟩ := exists_between hε in let ⟨ε', hε', c, hc, hcε⟩ := pos_sum_of_encodable a0 ι in ⟨ λi, ⟨ε' i, le_of_lt $ hε' i⟩, assume i, nnreal.coe_lt_coe.2 $ hε' i, ⟨c, has_sum_le (assume i, le_of_lt $ hε' i) has_sum_zero hc ⟩, nnreal.has_sum_coe.1 hc, lt_of_le_of_lt (nnreal.coe_le_coe.1 hcε) aε ⟩ end nnreal namespace ennreal theorem exists_pos_sum_of_encodable {ε : ℝ≥0∞} (hε : 0 < ε) (ι) [encodable ι] : ∃ ε' : ι → ℝ≥0, (∀ i, 0 < ε' i) ∧ ∑' i, (ε' i : ℝ≥0∞) < ε := begin rcases exists_between hε with ⟨r, h0r, hrε⟩, rcases lt_iff_exists_coe.1 hrε with ⟨x, rfl, hx⟩, rcases nnreal.exists_pos_sum_of_encodable (coe_lt_coe.1 h0r) ι with ⟨ε', hp, c, hc, hcr⟩, exact ⟨ε', hp, (ennreal.tsum_coe_eq hc).symm ▸ lt_trans (coe_lt_coe.2 hcr) hrε⟩ end theorem exists_pos_sum_of_encodable' {ε : ℝ≥0∞} (hε : 0 < ε) (ι) [encodable ι] : ∃ ε' : ι → ℝ≥0∞, (∀ i, 0 < ε' i) ∧ (∑' i, ε' i) < ε := let ⟨δ, δpos, hδ⟩ := exists_pos_sum_of_encodable hε ι in ⟨λ i, δ i, λ i, ennreal.coe_pos.2 (δpos i), hδ⟩ end ennreal /-! ### Factorial -/ lemma factorial_tendsto_at_top : tendsto nat.factorial at_top at_top := tendsto_at_top_at_top_of_monotone nat.monotone_factorial (λ n, ⟨n, n.self_le_factorial⟩) lemma tendsto_factorial_div_pow_self_at_top : tendsto (λ n, n! / n^n : ℕ → ℝ) at_top (𝓝 0) := tendsto_of_tendsto_of_tendsto_of_le_of_le' tendsto_const_nhds (tendsto_const_div_at_top_nhds_0_nat 1) (eventually_of_forall $ λ n, div_nonneg (by exact_mod_cast n.factorial_pos.le) (pow_nonneg (by exact_mod_cast n.zero_le) _)) begin refine (eventually_gt_at_top 0).mono (λ n hn, _), rcases nat.exists_eq_succ_of_ne_zero hn.ne.symm with ⟨k, rfl⟩, rw [← prod_range_add_one_eq_factorial, pow_eq_prod_const, div_eq_mul_inv, ← inv_eq_one_div, prod_nat_cast, nat.cast_succ, ← prod_inv_distrib', ← prod_mul_distrib, finset.prod_range_succ'], simp only [prod_range_succ', one_mul, nat.cast_add, zero_add, nat.cast_one], refine mul_le_of_le_one_left (inv_nonneg.mpr $ by exact_mod_cast hn.le) (prod_le_one _ _); intros x hx; rw finset.mem_range at hx, { refine mul_nonneg _ (inv_nonneg.mpr _); norm_cast; linarith }, { refine (div_le_one $ by exact_mod_cast hn).mpr _, norm_cast, linarith } end
29e767232a99e50b96e1dd7bc23f83f1844ac33d
c777c32c8e484e195053731103c5e52af26a25d1
/src/measure_theory/constructions/borel_space.lean
e8067d5ceca54e1c37b81b189039721f5b8a09f2
[ "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
94,180
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Yury Kudryashov -/ import analysis.complex.basic import analysis.normed_space.finite_dimension import measure_theory.function.ae_measurable_sequence import measure_theory.group.arithmetic import measure_theory.lattice import measure_theory.measure.open_pos import topology.algebra.order.liminf_limsup import topology.continuous_function.basic import topology.instances.add_circle import topology.instances.ereal import topology.G_delta import topology.order.lattice import topology.semicontinuous import topology.metric_space.metrizable /-! # Borel (measurable) space ## Main definitions * `borel α` : the least `σ`-algebra that contains all open sets; * `class borel_space` : a space with `topological_space` and `measurable_space` structures such that `‹measurable_space α› = borel α`; * `class opens_measurable_space` : a space with `topological_space` and `measurable_space` structures such that all open sets are measurable; equivalently, `borel α ≤ ‹measurable_space α›`. * `borel_space` instances on `empty`, `unit`, `bool`, `nat`, `int`, `rat`; * `measurable` and `borel_space` instances on `ℝ`, `ℝ≥0`, `ℝ≥0∞`. ## Main statements * `is_open.measurable_set`, `is_closed.measurable_set`: open and closed sets are measurable; * `continuous.measurable` : a continuous function is measurable; * `continuous.measurable2` : if `f : α → β` and `g : α → γ` are measurable and `op : β × γ → δ` is continuous, then `λ x, op (f x, g y)` is measurable; * `measurable.add` etc : dot notation for arithmetic operations on `measurable` predicates, and similarly for `dist` and `edist`; * `ae_measurable.add` : similar dot notation for almost everywhere measurable functions; * `measurable.ennreal*` : special cases for arithmetic operations on `ℝ≥0∞`. -/ noncomputable theory open classical set filter measure_theory open_locale classical big_operators topology nnreal ennreal measure_theory universes u v w x y variables {α β γ γ₂ δ : Type*} {ι : Sort y} {s t u : set α} open measurable_space topological_space /-- `measurable_space` structure generated by `topological_space`. -/ def borel (α : Type u) [topological_space α] : measurable_space α := generate_from {s : set α | is_open s} lemma borel_eq_top_of_discrete [topological_space α] [discrete_topology α] : borel α = ⊤ := top_le_iff.1 $ λ s hs, generate_measurable.basic s (is_open_discrete s) lemma borel_eq_top_of_countable [topological_space α] [t1_space α] [countable α] : borel α = ⊤ := begin refine (top_le_iff.1 $ λ s hs, bUnion_of_singleton s ▸ _), apply measurable_set.bUnion s.to_countable, intros x hx, apply measurable_set.of_compl, apply generate_measurable.basic, exact is_closed_singleton.is_open_compl end lemma borel_eq_generate_from_of_subbasis {s : set (set α)} [t : topological_space α] [second_countable_topology α] (hs : t = generate_from s) : borel α = generate_from s := le_antisymm (generate_from_le $ assume u (hu : t.is_open u), begin rw [hs] at hu, induction hu, case generate_open.basic : u hu { exact generate_measurable.basic u hu }, case generate_open.univ { exact @measurable_set.univ α (generate_from s) }, case generate_open.inter : s₁ s₂ _ _ hs₁ hs₂ { exact @measurable_set.inter α (generate_from s) _ _ hs₁ hs₂ }, case generate_open.sUnion : f hf ih { rcases is_open_sUnion_countable f (by rwa hs) with ⟨v, hv, vf, vu⟩, rw ← vu, exact @measurable_set.sUnion α (generate_from s) _ hv (λ x xv, ih _ (vf xv)) } end) (generate_from_le $ assume u hu, generate_measurable.basic _ $ show t.is_open u, by rw [hs]; exact generate_open.basic _ hu) lemma topological_space.is_topological_basis.borel_eq_generate_from [topological_space α] [second_countable_topology α] {s : set (set α)} (hs : is_topological_basis s) : borel α = generate_from s := borel_eq_generate_from_of_subbasis hs.eq_generate_from lemma is_pi_system_is_open [topological_space α] : is_pi_system (is_open : set α → Prop) := λ s hs t ht hst, is_open.inter hs ht lemma borel_eq_generate_from_is_closed [topological_space α] : borel α = generate_from {s | is_closed s} := le_antisymm (generate_from_le $ λ t ht, @measurable_set.of_compl α _ (generate_from {s | is_closed s}) (generate_measurable.basic _ $ is_closed_compl_iff.2 ht)) (generate_from_le $ λ t ht, @measurable_set.of_compl α _ (borel α) (generate_measurable.basic _ $ is_open_compl_iff.2 ht)) section order_topology variable (α) variables [topological_space α] [second_countable_topology α] [linear_order α] [order_topology α] lemma borel_eq_generate_from_Iio : borel α = generate_from (range Iio) := begin refine le_antisymm _ (generate_from_le _), { rw borel_eq_generate_from_of_subbasis (@order_topology.topology_eq_generate_intervals α _ _ _), letI : measurable_space α := measurable_space.generate_from (range Iio), have H : ∀ a : α, measurable_set (Iio a) := λ a, generate_measurable.basic _ ⟨_, rfl⟩, refine generate_from_le _, rintro _ ⟨a, rfl | rfl⟩; [skip, apply H], by_cases h : ∃ a', ∀ b, a < b ↔ a' ≤ b, { rcases h with ⟨a', ha'⟩, rw (_ : Ioi a = (Iio a')ᶜ), { exact (H _).compl }, simp [set.ext_iff, ha'] }, { rcases is_open_Union_countable (λ a' : {a' : α // a < a'}, {b | a'.1 < b}) (λ a', is_open_lt' _) with ⟨v, ⟨hv⟩, vu⟩, simp [set.ext_iff] at vu, have : Ioi a = ⋃ x : v, (Iio x.1.1)ᶜ, { simp [set.ext_iff], refine λ x, ⟨λ ax, _, λ ⟨a', ⟨h, av⟩, ax⟩, lt_of_lt_of_le h ax⟩, rcases (vu x).2 _ with ⟨a', h₁, h₂⟩, { exact ⟨a', h₁, le_of_lt h₂⟩ }, refine not_imp_comm.1 (λ h, _) h, exact ⟨x, λ b, ⟨λ ab, le_of_not_lt (λ h', h ⟨b, ab, h'⟩), lt_of_lt_of_le ax⟩⟩ }, rw this, resetI, apply measurable_set.Union, exact λ _, (H _).compl } }, { rw forall_range_iff, intro a, exact generate_measurable.basic _ is_open_Iio } end lemma borel_eq_generate_from_Ioi : borel α = generate_from (range Ioi) := @borel_eq_generate_from_Iio αᵒᵈ _ (by apply_instance : second_countable_topology α) _ _ end order_topology lemma borel_comap {f : α → β} {t : topological_space β} : @borel α (t.induced f) = (@borel β t).comap f := comap_generate_from.symm lemma continuous.borel_measurable [topological_space α] [topological_space β] {f : α → β} (hf : continuous f) : @measurable α β (borel α) (borel β) f := measurable.of_le_map $ generate_from_le $ λ s hs, generate_measurable.basic (f ⁻¹' s) (hs.preimage hf) /-- A space with `measurable_space` and `topological_space` structures such that all open sets are measurable. -/ class opens_measurable_space (α : Type*) [topological_space α] [h : measurable_space α] : Prop := (borel_le : borel α ≤ h) /-- A space with `measurable_space` and `topological_space` structures such that the `σ`-algebra of measurable sets is exactly the `σ`-algebra generated by open sets. -/ class borel_space (α : Type*) [topological_space α] [measurable_space α] : Prop := (measurable_eq : ‹measurable_space α› = borel α) namespace tactic /-- Add instances `borel α : measurable_space α` and `⟨rfl⟩ : borel_space α`. -/ meta def add_borel_instance (α : expr) : tactic unit := do n1 ← get_unused_name "_inst", to_expr ``(borel %%α) >>= pose n1, reset_instance_cache, n2 ← get_unused_name "_inst", v ← to_expr ``(borel_space.mk rfl : borel_space %%α), note n2 none v, reset_instance_cache /-- Given a type `α`, an assumption `i : measurable_space α`, and an instance `[borel_space α]`, replace `i` with `borel α`. -/ meta def borel_to_refl (α i : expr) : tactic unit := do n ← get_unused_name "h", to_expr ``(%%i = borel %%α) >>= assert n, applyc `borel_space.measurable_eq, unfreezing (tactic.subst i), n1 ← get_unused_name "_inst", to_expr ``(borel %%α) >>= pose n1, reset_instance_cache /-- Given a type `α`, if there is an assumption `[i : measurable_space α]`, then try to prove `[borel_space α]` and replace `i` with `borel α`. Otherwise, add instances `borel α : measurable_space α` and `⟨rfl⟩ : borel_space α`. -/ meta def borelize (α : expr) : tactic unit := do i ← optional (to_expr ``(measurable_space %%α) >>= find_assumption), i.elim (add_borel_instance α) (borel_to_refl α) namespace interactive setup_tactic_parser /-- The behaviour of `borelize α` depends on the existing assumptions on `α`. - if `α` is a topological space with instances `[measurable_space α] [borel_space α]`, then `borelize α` replaces the former instance by `borel α`; - otherwise, `borelize α` adds instances `borel α : measurable_space α` and `⟨rfl⟩ : borel_space α`. Finally, `borelize [α, β, γ]` runs `borelize α, borelize β, borelize γ`. -/ meta def borelize (ts : parse pexpr_list_or_texpr) : tactic unit := mmap' (λ t, to_expr t >>= tactic.borelize) ts add_tactic_doc { name := "borelize", category := doc_category.tactic, decl_names := [`tactic.interactive.borelize], tags := ["type class"] } end interactive end tactic @[priority 100] instance order_dual.opens_measurable_space {α : Type*} [topological_space α] [measurable_space α] [h : opens_measurable_space α] : opens_measurable_space αᵒᵈ := { borel_le := h.borel_le } @[priority 100] instance order_dual.borel_space {α : Type*} [topological_space α] [measurable_space α] [h : borel_space α] : borel_space αᵒᵈ := { measurable_eq := h.measurable_eq } /-- In a `borel_space` all open sets are measurable. -/ @[priority 100] instance borel_space.opens_measurable {α : Type*} [topological_space α] [measurable_space α] [borel_space α] : opens_measurable_space α := ⟨ge_of_eq $ borel_space.measurable_eq⟩ instance subtype.borel_space {α : Type*} [topological_space α] [measurable_space α] [hα : borel_space α] (s : set α) : borel_space s := ⟨by { rw [hα.1, subtype.measurable_space, ← borel_comap], refl }⟩ instance subtype.opens_measurable_space {α : Type*} [topological_space α] [measurable_space α] [h : opens_measurable_space α] (s : set α) : opens_measurable_space s := ⟨by { rw [borel_comap], exact comap_mono h.1 }⟩ @[priority 100] instance borel_space.countably_generated {α : Type*} [topological_space α] [measurable_space α] [borel_space α] [second_countable_topology α] : countably_generated α := begin obtain ⟨b, bct, -, hb⟩ := exists_countable_basis α, refine ⟨⟨b, bct, _⟩⟩, borelize α, exact hb.borel_eq_generate_from, end theorem _root_.measurable_set.induction_on_open [topological_space α] [measurable_space α] [borel_space α] {C : set α → Prop} (h_open : ∀ U, is_open U → C U) (h_compl : ∀ t, measurable_set t → C t → C tᶜ) (h_union : ∀ f : ℕ → set α, pairwise (disjoint on f) → (∀ i, measurable_set (f i)) → (∀ i, C (f i)) → C (⋃ i, f i)) : ∀ ⦃t⦄, measurable_set t → C t := measurable_space.induction_on_inter borel_space.measurable_eq is_pi_system_is_open (h_open _ is_open_empty) h_open h_compl h_union section variables [topological_space α] [measurable_space α] [opens_measurable_space α] [topological_space β] [measurable_space β] [opens_measurable_space β] [topological_space γ] [measurable_space γ] [borel_space γ] [topological_space γ₂] [measurable_space γ₂] [borel_space γ₂] [measurable_space δ] lemma is_open.measurable_set (h : is_open s) : measurable_set s := opens_measurable_space.borel_le _ $ generate_measurable.basic _ h @[measurability] lemma measurable_set_interior : measurable_set (interior s) := is_open_interior.measurable_set lemma is_Gδ.measurable_set (h : is_Gδ s) : measurable_set s := begin rcases h with ⟨S, hSo, hSc, rfl⟩, exact measurable_set.sInter hSc (λ t ht, (hSo t ht).measurable_set) end lemma measurable_set_of_continuous_at {β} [emetric_space β] (f : α → β) : measurable_set {x | continuous_at f x} := (is_Gδ_set_of_continuous_at f).measurable_set lemma is_closed.measurable_set (h : is_closed s) : measurable_set s := h.is_open_compl.measurable_set.of_compl lemma is_compact.measurable_set [t2_space α] (h : is_compact s) : measurable_set s := h.is_closed.measurable_set @[measurability] lemma measurable_set_closure : measurable_set (closure s) := is_closed_closure.measurable_set lemma measurable_of_is_open {f : δ → γ} (hf : ∀ s, is_open s → measurable_set (f ⁻¹' s)) : measurable f := by { rw [‹borel_space γ›.measurable_eq], exact measurable_generate_from hf } lemma measurable_of_is_closed {f : δ → γ} (hf : ∀ s, is_closed s → measurable_set (f ⁻¹' s)) : measurable f := begin apply measurable_of_is_open, intros s hs, rw [← measurable_set.compl_iff, ← preimage_compl], apply hf, rw [is_closed_compl_iff], exact hs end lemma measurable_of_is_closed' {f : δ → γ} (hf : ∀ s, is_closed s → s.nonempty → s ≠ univ → measurable_set (f ⁻¹' s)) : measurable f := begin apply measurable_of_is_closed, intros s hs, cases eq_empty_or_nonempty s with h1 h1, { simp [h1] }, by_cases h2 : s = univ, { simp [h2] }, exact hf s hs h1 h2 end instance nhds_is_measurably_generated (a : α) : (𝓝 a).is_measurably_generated := begin rw [nhds, infi_subtype'], refine @filter.infi_is_measurably_generated _ _ _ _ (λ i, _), exact i.2.2.measurable_set.principal_is_measurably_generated end /-- If `s` is a measurable set, then `𝓝[s] a` is a measurably generated filter for each `a`. This cannot be an `instance` because it depends on a non-instance `hs : measurable_set s`. -/ lemma measurable_set.nhds_within_is_measurably_generated {s : set α} (hs : measurable_set s) (a : α) : (𝓝[s] a).is_measurably_generated := by haveI := hs.principal_is_measurably_generated; exact filter.inf_is_measurably_generated _ _ @[priority 100] -- see Note [lower instance priority] instance opens_measurable_space.to_measurable_singleton_class [t1_space α] : measurable_singleton_class α := ⟨λ x, is_closed_singleton.measurable_set⟩ instance pi.opens_measurable_space {ι : Type*} {π : ι → Type*} [countable ι] [t' : Π i, topological_space (π i)] [Π i, measurable_space (π i)] [∀ i, second_countable_topology (π i)] [∀ i, opens_measurable_space (π i)] : opens_measurable_space (Π i, π i) := begin constructor, have : Pi.topological_space = generate_from {t | ∃(s:Πa, set (π a)) (i : finset ι), (∀a∈i, s a ∈ countable_basis (π a)) ∧ t = pi ↑i s}, { rw [funext (λ a, @eq_generate_from_countable_basis (π a) _ _), pi_generate_from_eq] }, rw [borel_eq_generate_from_of_subbasis this], apply generate_from_le, rintros _ ⟨s, i, hi, rfl⟩, refine measurable_set.pi i.countable_to_set (λ a ha, is_open.measurable_set _), rw [eq_generate_from_countable_basis (π a)], exact generate_open.basic _ (hi a ha) end instance prod.opens_measurable_space [second_countable_topology α] [second_countable_topology β] : opens_measurable_space (α × β) := begin constructor, rw [((is_basis_countable_basis α).prod (is_basis_countable_basis β)).borel_eq_generate_from], apply generate_from_le, rintros _ ⟨u, v, hu, hv, rfl⟩, exact (is_open_of_mem_countable_basis hu).measurable_set.prod (is_open_of_mem_countable_basis hv).measurable_set end variables {α' : Type*} [topological_space α'] [measurable_space α'] lemma interior_ae_eq_of_null_frontier {μ : measure α'} {s : set α'} (h : μ (frontier s) = 0) : interior s =ᵐ[μ] s := interior_subset.eventually_le.antisymm $ subset_closure.eventually_le.trans (ae_le_set.2 h) lemma measure_interior_of_null_frontier {μ : measure α'} {s : set α'} (h : μ (frontier s) = 0) : μ (interior s) = μ s := measure_congr (interior_ae_eq_of_null_frontier h) lemma null_measurable_set_of_null_frontier {s : set α} {μ : measure α} (h : μ (frontier s) = 0) : null_measurable_set s μ := ⟨interior s, is_open_interior.measurable_set, (interior_ae_eq_of_null_frontier h).symm⟩ lemma closure_ae_eq_of_null_frontier {μ : measure α'} {s : set α'} (h : μ (frontier s) = 0) : closure s =ᵐ[μ] s := ((ae_le_set.2 h).trans interior_subset.eventually_le).antisymm $ subset_closure.eventually_le lemma measure_closure_of_null_frontier {μ : measure α'} {s : set α'} (h : μ (frontier s) = 0) : μ (closure s) = μ s := measure_congr (closure_ae_eq_of_null_frontier h) section preorder variables [preorder α] [order_closed_topology α] {a b x : α} @[simp, measurability] lemma measurable_set_Ici : measurable_set (Ici a) := is_closed_Ici.measurable_set @[simp, measurability] lemma measurable_set_Iic : measurable_set (Iic a) := is_closed_Iic.measurable_set @[simp, measurability] lemma measurable_set_Icc : measurable_set (Icc a b) := is_closed_Icc.measurable_set instance nhds_within_Ici_is_measurably_generated : (𝓝[Ici b] a).is_measurably_generated := measurable_set_Ici.nhds_within_is_measurably_generated _ instance nhds_within_Iic_is_measurably_generated : (𝓝[Iic b] a).is_measurably_generated := measurable_set_Iic.nhds_within_is_measurably_generated _ instance nhds_within_Icc_is_measurably_generated : is_measurably_generated (𝓝[Icc a b] x) := by { rw [← Ici_inter_Iic, nhds_within_inter], apply_instance } instance at_top_is_measurably_generated : (filter.at_top : filter α).is_measurably_generated := @filter.infi_is_measurably_generated _ _ _ _ $ λ a, (measurable_set_Ici : measurable_set (Ici a)).principal_is_measurably_generated instance at_bot_is_measurably_generated : (filter.at_bot : filter α).is_measurably_generated := @filter.infi_is_measurably_generated _ _ _ _ $ λ a, (measurable_set_Iic : measurable_set (Iic a)).principal_is_measurably_generated end preorder section partial_order variables [partial_order α] [order_closed_topology α] [second_countable_topology α] {a b : α} @[measurability] lemma measurable_set_le' : measurable_set {p : α × α | p.1 ≤ p.2} := order_closed_topology.is_closed_le'.measurable_set @[measurability] lemma measurable_set_le {f g : δ → α} (hf : measurable f) (hg : measurable g) : measurable_set {a | f a ≤ g a} := hf.prod_mk hg measurable_set_le' end partial_order section linear_order variables [linear_order α] [order_closed_topology α] {a b x : α} -- we open this locale only here to avoid issues with list being treated as intervals above open_locale interval @[simp, measurability] lemma measurable_set_Iio : measurable_set (Iio a) := is_open_Iio.measurable_set @[simp, measurability] lemma measurable_set_Ioi : measurable_set (Ioi a) := is_open_Ioi.measurable_set @[simp, measurability] lemma measurable_set_Ioo : measurable_set (Ioo a b) := is_open_Ioo.measurable_set @[simp, measurability] lemma measurable_set_Ioc : measurable_set (Ioc a b) := measurable_set_Ioi.inter measurable_set_Iic @[simp, measurability] lemma measurable_set_Ico : measurable_set (Ico a b) := measurable_set_Ici.inter measurable_set_Iio instance nhds_within_Ioi_is_measurably_generated : (𝓝[Ioi b] a).is_measurably_generated := measurable_set_Ioi.nhds_within_is_measurably_generated _ instance nhds_within_Iio_is_measurably_generated : (𝓝[Iio b] a).is_measurably_generated := measurable_set_Iio.nhds_within_is_measurably_generated _ instance nhds_within_uIcc_is_measurably_generated : is_measurably_generated (𝓝[[a, b]] x) := nhds_within_Icc_is_measurably_generated @[measurability] lemma measurable_set_lt' [second_countable_topology α] : measurable_set {p : α × α | p.1 < p.2} := (is_open_lt continuous_fst continuous_snd).measurable_set @[measurability] lemma measurable_set_lt [second_countable_topology α] {f g : δ → α} (hf : measurable f) (hg : measurable g) : measurable_set {a | f a < g a} := hf.prod_mk hg measurable_set_lt' lemma null_measurable_set_lt [second_countable_topology α] {μ : measure δ} {f g : δ → α} (hf : ae_measurable f μ) (hg : ae_measurable g μ) : null_measurable_set {a | f a < g a} μ := (hf.prod_mk hg).null_measurable measurable_set_lt' lemma set.ord_connected.measurable_set (h : ord_connected s) : measurable_set s := begin let u := ⋃ (x ∈ s) (y ∈ s), Ioo x y, have huopen : is_open u := is_open_bUnion (λ x hx, is_open_bUnion (λ y hy, is_open_Ioo)), have humeas : measurable_set u := huopen.measurable_set, have hfinite : (s \ u).finite := s.finite_diff_Union_Ioo, have : u ⊆ s := Union₂_subset (λ x hx, Union₂_subset (λ y hy, Ioo_subset_Icc_self.trans (h.out hx hy))), rw ← union_diff_cancel this, exact humeas.union hfinite.measurable_set end lemma is_preconnected.measurable_set (h : is_preconnected s) : measurable_set s := h.ord_connected.measurable_set lemma generate_from_Ico_mem_le_borel {α : Type*} [topological_space α] [linear_order α] [order_closed_topology α] (s t : set α) : measurable_space.generate_from {S | ∃ (l ∈ s) (u ∈ t) (h : l < u), Ico l u = S} ≤ borel α := begin apply generate_from_le, borelize α, rintro _ ⟨a, -, b, -, -, rfl⟩, exact measurable_set_Ico end lemma dense.borel_eq_generate_from_Ico_mem_aux {α : Type*} [topological_space α] [linear_order α] [order_topology α] [second_countable_topology α] {s : set α} (hd : dense s) (hbot : ∀ x, is_bot x → x ∈ s) (hIoo : ∀ x y : α, x < y → Ioo x y = ∅ → y ∈ s) : borel α = generate_from {S : set α | ∃ (l ∈ s) (u ∈ s) (h : l < u), Ico l u = S} := begin set S : set (set α) := {S | ∃ (l ∈ s) (u ∈ s) (h : l < u), Ico l u = S}, refine le_antisymm _ (generate_from_Ico_mem_le_borel _ _), letI : measurable_space α := generate_from S, rw borel_eq_generate_from_Iio, refine generate_from_le (forall_range_iff.2 $ λ a, _), rcases hd.exists_countable_dense_subset_bot_top with ⟨t, hts, hc, htd, htb, htt⟩, by_cases ha : ∀ b < a, (Ioo b a).nonempty, { convert_to measurable_set (⋃ (l ∈ t) (u ∈ t) (hlu : l < u) (hu : u ≤ a), Ico l u), { ext y, simp only [mem_Union, mem_Iio, mem_Ico], split, { intro hy, rcases htd.exists_le' (λ b hb, htb _ hb (hbot b hb)) y with ⟨l, hlt, hly⟩, rcases htd.exists_mem_open is_open_Ioo (ha y hy) with ⟨u, hut, hyu, hua⟩, exact ⟨l, hlt, u, hut, hly.trans_lt hyu, hua.le, hly, hyu⟩ }, { rintro ⟨l, -, u, -, -, hua, -, hyu⟩, exact hyu.trans_le hua } }, { refine measurable_set.bUnion hc (λ a ha, measurable_set.bUnion hc $ λ b hb, _), refine measurable_set.Union (λ hab, measurable_set.Union $ λ hb', _), exact generate_measurable.basic _ ⟨a, hts ha, b, hts hb, hab, mem_singleton _⟩ } }, { simp only [not_forall, not_nonempty_iff_eq_empty] at ha, replace ha : a ∈ s := hIoo ha.some a ha.some_spec.fst ha.some_spec.snd, convert_to measurable_set (⋃ (l ∈ t) (hl : l < a), Ico l a), { symmetry, simp only [← Ici_inter_Iio, ← Union_inter, inter_eq_right_iff_subset, subset_def, mem_Union, mem_Ici, mem_Iio], intros x hx, rcases htd.exists_le' (λ b hb, htb _ hb (hbot b hb)) x with ⟨z, hzt, hzx⟩, exact ⟨z, hzt, hzx.trans_lt hx, hzx⟩ }, { refine measurable_set.bUnion hc (λ x hx, measurable_set.Union $ λ hlt, _), exact generate_measurable.basic _ ⟨x, hts hx, a, ha, hlt, mem_singleton _⟩ } } end lemma dense.borel_eq_generate_from_Ico_mem {α : Type*} [topological_space α] [linear_order α] [order_topology α] [second_countable_topology α] [densely_ordered α] [no_min_order α] {s : set α} (hd : dense s) : borel α = generate_from {S : set α | ∃ (l ∈ s) (u ∈ s) (h : l < u), Ico l u = S} := hd.borel_eq_generate_from_Ico_mem_aux (by simp) $ λ x y hxy H, ((nonempty_Ioo.2 hxy).ne_empty H).elim lemma borel_eq_generate_from_Ico (α : Type*) [topological_space α] [second_countable_topology α] [linear_order α] [order_topology α] : borel α = generate_from {S : set α | ∃ l u (h : l < u), Ico l u = S} := by simpa only [exists_prop, mem_univ, true_and] using (@dense_univ α _).borel_eq_generate_from_Ico_mem_aux (λ _ _, mem_univ _) (λ _ _ _ _, mem_univ _) lemma dense.borel_eq_generate_from_Ioc_mem_aux {α : Type*} [topological_space α] [linear_order α] [order_topology α] [second_countable_topology α] {s : set α} (hd : dense s) (hbot : ∀ x, is_top x → x ∈ s) (hIoo : ∀ x y : α, x < y → Ioo x y = ∅ → x ∈ s) : borel α = generate_from {S : set α | ∃ (l ∈ s) (u ∈ s) (h : l < u), Ioc l u = S} := begin convert hd.order_dual.borel_eq_generate_from_Ico_mem_aux hbot (λ x y hlt he, hIoo y x hlt _), { ext s, split; rintro ⟨l, hl, u, hu, hlt, rfl⟩, exacts [⟨u, hu, l, hl, hlt, dual_Ico⟩, ⟨u, hu, l, hl, hlt, dual_Ioc⟩] }, { erw dual_Ioo, exact he } end lemma dense.borel_eq_generate_from_Ioc_mem {α : Type*} [topological_space α] [linear_order α] [order_topology α] [second_countable_topology α] [densely_ordered α] [no_max_order α] {s : set α} (hd : dense s) : borel α = generate_from {S : set α | ∃ (l ∈ s) (u ∈ s) (h : l < u), Ioc l u = S} := hd.borel_eq_generate_from_Ioc_mem_aux (by simp) $ λ x y hxy H, ((nonempty_Ioo.2 hxy).ne_empty H).elim lemma borel_eq_generate_from_Ioc (α : Type*) [topological_space α] [second_countable_topology α] [linear_order α] [order_topology α] : borel α = generate_from {S : set α | ∃ l u (h : l < u), Ioc l u = S} := by simpa only [exists_prop, mem_univ, true_and] using (@dense_univ α _).borel_eq_generate_from_Ioc_mem_aux (λ _ _, mem_univ _) (λ _ _ _ _, mem_univ _) namespace measure_theory.measure /-- Two finite measures on a Borel space are equal if they agree on all closed-open intervals. If `α` is a conditionally complete linear order with no top element, `measure_theory.measure..ext_of_Ico` is an extensionality lemma with weaker assumptions on `μ` and `ν`. -/ lemma ext_of_Ico_finite {α : Type*} [topological_space α] {m : measurable_space α} [second_countable_topology α] [linear_order α] [order_topology α] [borel_space α] (μ ν : measure α) [is_finite_measure μ] (hμν : μ univ = ν univ) (h : ∀ ⦃a b⦄, a < b → μ (Ico a b) = ν (Ico a b)) : μ = ν := begin refine ext_of_generate_finite _ (borel_space.measurable_eq.trans (borel_eq_generate_from_Ico α)) (is_pi_system_Ico (id : α → α) id) _ hμν, { rintro - ⟨a, b, hlt, rfl⟩, exact h hlt } end /-- Two finite measures on a Borel space are equal if they agree on all open-closed intervals. If `α` is a conditionally complete linear order with no top element, `measure_theory.measure..ext_of_Ioc` is an extensionality lemma with weaker assumptions on `μ` and `ν`. -/ lemma ext_of_Ioc_finite {α : Type*} [topological_space α] {m : measurable_space α} [second_countable_topology α] [linear_order α] [order_topology α] [borel_space α] (μ ν : measure α) [is_finite_measure μ] (hμν : μ univ = ν univ) (h : ∀ ⦃a b⦄, a < b → μ (Ioc a b) = ν (Ioc a b)) : μ = ν := begin refine @ext_of_Ico_finite αᵒᵈ _ _ _ _ _ ‹_› μ ν _ hμν (λ a b hab, _), erw dual_Ico, exact h hab end /-- Two measures which are finite on closed-open intervals are equal if the agree on all closed-open intervals. -/ lemma ext_of_Ico' {α : Type*} [topological_space α] {m : measurable_space α} [second_countable_topology α] [linear_order α] [order_topology α] [borel_space α] [no_max_order α] (μ ν : measure α) (hμ : ∀ ⦃a b⦄, a < b → μ (Ico a b) ≠ ∞) (h : ∀ ⦃a b⦄, a < b → μ (Ico a b) = ν (Ico a b)) : μ = ν := begin rcases exists_countable_dense_bot_top α with ⟨s, hsc, hsd, hsb, hst⟩, have : (⋃ (l ∈ s) (u ∈ s) (h : l < u), {Ico l u} : set (set α)).countable, from hsc.bUnion (λ l hl, hsc.bUnion (λ u hu, countable_Union $ λ _, countable_singleton _)), simp only [← set_of_eq_eq_singleton, ← set_of_exists] at this, refine measure.ext_of_generate_from_of_cover_subset (borel_space.measurable_eq.trans (borel_eq_generate_from_Ico α)) (is_pi_system_Ico id id) _ this _ _ _, { rintro _ ⟨l, -, u, -, h, rfl⟩, exact ⟨l, u, h, rfl⟩ }, { refine sUnion_eq_univ_iff.2 (λ x, _), rcases hsd.exists_le' hsb x with ⟨l, hls, hlx⟩, rcases hsd.exists_gt x with ⟨u, hus, hxu⟩, exact ⟨_, ⟨l, hls, u, hus, hlx.trans_lt hxu, rfl⟩, hlx, hxu⟩ }, { rintro _ ⟨l, -, u, -, hlt, rfl⟩, exact hμ hlt }, { rintro _ ⟨l, u, hlt, rfl⟩, exact h hlt } end /-- Two measures which are finite on closed-open intervals are equal if the agree on all open-closed intervals. -/ lemma ext_of_Ioc' {α : Type*} [topological_space α] {m : measurable_space α} [second_countable_topology α] [linear_order α] [order_topology α] [borel_space α] [no_min_order α] (μ ν : measure α) (hμ : ∀ ⦃a b⦄, a < b → μ (Ioc a b) ≠ ∞) (h : ∀ ⦃a b⦄, a < b → μ (Ioc a b) = ν (Ioc a b)) : μ = ν := begin refine @ext_of_Ico' αᵒᵈ _ _ _ _ _ ‹_› _ μ ν _ _; intros a b hab; erw dual_Ico, exacts [hμ hab, h hab] end /-- Two measures which are finite on closed-open intervals are equal if the agree on all closed-open intervals. -/ lemma ext_of_Ico {α : Type*} [topological_space α] {m : measurable_space α} [second_countable_topology α] [conditionally_complete_linear_order α] [order_topology α] [borel_space α] [no_max_order α] (μ ν : measure α) [is_locally_finite_measure μ] (h : ∀ ⦃a b⦄, a < b → μ (Ico a b) = ν (Ico a b)) : μ = ν := μ.ext_of_Ico' ν (λ a b hab, measure_Ico_lt_top.ne) h /-- Two measures which are finite on closed-open intervals are equal if the agree on all open-closed intervals. -/ lemma ext_of_Ioc {α : Type*} [topological_space α] {m : measurable_space α} [second_countable_topology α] [conditionally_complete_linear_order α] [order_topology α] [borel_space α] [no_min_order α] (μ ν : measure α) [is_locally_finite_measure μ] (h : ∀ ⦃a b⦄, a < b → μ (Ioc a b) = ν (Ioc a b)) : μ = ν := μ.ext_of_Ioc' ν (λ a b hab, measure_Ioc_lt_top.ne) h /-- Two finite measures on a Borel space are equal if they agree on all left-infinite right-closed intervals. -/ lemma ext_of_Iic {α : Type*} [topological_space α] {m : measurable_space α} [second_countable_topology α] [linear_order α] [order_topology α] [borel_space α] (μ ν : measure α) [is_finite_measure μ] (h : ∀ a, μ (Iic a) = ν (Iic a)) : μ = ν := begin refine ext_of_Ioc_finite μ ν _ (λ a b hlt, _), { rcases exists_countable_dense_bot_top α with ⟨s, hsc, hsd, -, hst⟩, have : directed_on (≤) s, from directed_on_iff_directed.2 (directed_of_sup $ λ _ _, id), simp only [← bsupr_measure_Iic hsc (hsd.exists_ge' hst) this, h] }, rw [← Iic_diff_Iic, measure_diff (Iic_subset_Iic.2 hlt.le) measurable_set_Iic, measure_diff (Iic_subset_Iic.2 hlt.le) measurable_set_Iic, h a, h b], { rw ← h a, exact (measure_lt_top μ _).ne }, { exact (measure_lt_top μ _).ne } end /-- Two finite measures on a Borel space are equal if they agree on all left-closed right-infinite intervals. -/ lemma ext_of_Ici {α : Type*} [topological_space α] {m : measurable_space α} [second_countable_topology α] [linear_order α] [order_topology α] [borel_space α] (μ ν : measure α) [is_finite_measure μ] (h : ∀ a, μ (Ici a) = ν (Ici a)) : μ = ν := @ext_of_Iic αᵒᵈ _ _ _ _ _ ‹_› _ _ _ h end measure_theory.measure end linear_order section linear_order variables [linear_order α] [order_closed_topology α] {a b : α} @[measurability] lemma measurable_set_uIcc : measurable_set (uIcc a b) := measurable_set_Icc @[measurability] lemma measurable_set_uIoc : measurable_set (uIoc a b) := measurable_set_Ioc variables [second_countable_topology α] @[measurability] lemma measurable.max {f g : δ → α} (hf : measurable f) (hg : measurable g) : measurable (λ a, max (f a) (g a)) := by simpa only [max_def'] using hf.piecewise (measurable_set_le hg hf) hg @[measurability] lemma ae_measurable.max {f g : δ → α} {μ : measure δ} (hf : ae_measurable f μ) (hg : ae_measurable g μ) : ae_measurable (λ a, max (f a) (g a)) μ := ⟨λ a, max (hf.mk f a) (hg.mk g a), hf.measurable_mk.max hg.measurable_mk, eventually_eq.comp₂ hf.ae_eq_mk _ hg.ae_eq_mk⟩ @[measurability] lemma measurable.min {f g : δ → α} (hf : measurable f) (hg : measurable g) : measurable (λ a, min (f a) (g a)) := by simpa only [min_def] using hf.piecewise (measurable_set_le hf hg) hg @[measurability] lemma ae_measurable.min {f g : δ → α} {μ : measure δ} (hf : ae_measurable f μ) (hg : ae_measurable g μ) : ae_measurable (λ a, min (f a) (g a)) μ := ⟨λ a, min (hf.mk f a) (hg.mk g a), hf.measurable_mk.min hg.measurable_mk, eventually_eq.comp₂ hf.ae_eq_mk _ hg.ae_eq_mk⟩ end linear_order /-- A continuous function from an `opens_measurable_space` to a `borel_space` is measurable. -/ lemma continuous.measurable {f : α → γ} (hf : continuous f) : measurable f := hf.borel_measurable.mono opens_measurable_space.borel_le (le_of_eq $ borel_space.measurable_eq) /-- A continuous function from an `opens_measurable_space` to a `borel_space` is ae-measurable. -/ lemma continuous.ae_measurable {f : α → γ} (h : continuous f) {μ : measure α} : ae_measurable f μ := h.measurable.ae_measurable lemma closed_embedding.measurable {f : α → γ} (hf : closed_embedding f) : measurable f := hf.continuous.measurable lemma continuous.is_open_pos_measure_map {f : β → γ} (hf : continuous f) (hf_surj : function.surjective f) {μ : measure β} [μ.is_open_pos_measure] : (measure.map f μ).is_open_pos_measure := begin refine ⟨λ U hUo hUne, _⟩, rw [measure.map_apply hf.measurable hUo.measurable_set], exact (hUo.preimage hf).measure_ne_zero μ (hf_surj.nonempty_preimage.mpr hUne) end /-- If a function is defined piecewise in terms of functions which are continuous on their respective pieces, then it is measurable. -/ lemma continuous_on.measurable_piecewise {f g : α → γ} {s : set α} [Π (j : α), decidable (j ∈ s)] (hf : continuous_on f s) (hg : continuous_on g sᶜ) (hs : measurable_set s) : measurable (s.piecewise f g) := begin refine measurable_of_is_open (λ t ht, _), rw [piecewise_preimage, set.ite], apply measurable_set.union, { rcases _root_.continuous_on_iff'.1 hf t ht with ⟨u, u_open, hu⟩, rw hu, exact u_open.measurable_set.inter hs }, { rcases _root_.continuous_on_iff'.1 hg t ht with ⟨u, u_open, hu⟩, rw [diff_eq_compl_inter, inter_comm, hu], exact u_open.measurable_set.inter hs.compl } end @[priority 100, to_additive] instance has_continuous_mul.has_measurable_mul [has_mul γ] [has_continuous_mul γ] : has_measurable_mul γ := { measurable_const_mul := λ c, (continuous_const.mul continuous_id).measurable, measurable_mul_const := λ c, (continuous_id.mul continuous_const).measurable } @[priority 100] instance has_continuous_sub.has_measurable_sub [has_sub γ] [has_continuous_sub γ] : has_measurable_sub γ := { measurable_const_sub := λ c, (continuous_const.sub continuous_id).measurable, measurable_sub_const := λ c, (continuous_id.sub continuous_const).measurable } @[priority 100, to_additive] instance topological_group.has_measurable_inv [group γ] [topological_group γ] : has_measurable_inv γ := ⟨continuous_inv.measurable⟩ @[priority 100] instance has_continuous_smul.has_measurable_smul {M α} [topological_space M] [topological_space α] [measurable_space M] [measurable_space α] [opens_measurable_space M] [borel_space α] [has_smul M α] [has_continuous_smul M α] : has_measurable_smul M α := ⟨λ c, (continuous_const_smul _).measurable, λ y, (continuous_id.smul continuous_const).measurable⟩ section lattice @[priority 100] instance has_continuous_sup.has_measurable_sup [has_sup γ] [has_continuous_sup γ] : has_measurable_sup γ := { measurable_const_sup := λ c, (continuous_const.sup continuous_id).measurable, measurable_sup_const := λ c, (continuous_id.sup continuous_const).measurable } @[priority 100] instance has_continuous_sup.has_measurable_sup₂ [second_countable_topology γ] [has_sup γ] [has_continuous_sup γ] : has_measurable_sup₂ γ := ⟨continuous_sup.measurable⟩ @[priority 100] instance has_continuous_inf.has_measurable_inf [has_inf γ] [has_continuous_inf γ] : has_measurable_inf γ := { measurable_const_inf := λ c, (continuous_const.inf continuous_id).measurable, measurable_inf_const := λ c, (continuous_id.inf continuous_const).measurable } @[priority 100] instance has_continuous_inf.has_measurable_inf₂ [second_countable_topology γ] [has_inf γ] [has_continuous_inf γ] : has_measurable_inf₂ γ := ⟨continuous_inf.measurable⟩ end lattice section homeomorph @[measurability] protected lemma homeomorph.measurable (h : α ≃ₜ γ) : measurable h := h.continuous.measurable /-- A homeomorphism between two Borel spaces is a measurable equivalence.-/ def homeomorph.to_measurable_equiv (h : γ ≃ₜ γ₂) : γ ≃ᵐ γ₂ := { measurable_to_fun := h.measurable, measurable_inv_fun := h.symm.measurable, to_equiv := h.to_equiv } @[simp] lemma homeomorph.to_measurable_equiv_coe (h : γ ≃ₜ γ₂) : (h.to_measurable_equiv : γ → γ₂) = h := rfl @[simp] lemma homeomorph.to_measurable_equiv_symm_coe (h : γ ≃ₜ γ₂) : (h.to_measurable_equiv.symm : γ₂ → γ) = h.symm := rfl end homeomorph @[measurability] lemma continuous_map.measurable (f : C(α, γ)) : measurable f := f.continuous.measurable lemma measurable_of_continuous_on_compl_singleton [t1_space α] {f : α → γ} (a : α) (hf : continuous_on f {a}ᶜ) : measurable f := measurable_of_measurable_on_compl_singleton a (continuous_on_iff_continuous_restrict.1 hf).measurable lemma continuous.measurable2 [second_countable_topology α] [second_countable_topology β] {f : δ → α} {g : δ → β} {c : α → β → γ} (h : continuous (λ p : α × β, c p.1 p.2)) (hf : measurable f) (hg : measurable g) : measurable (λ a, c (f a) (g a)) := h.measurable.comp (hf.prod_mk hg) lemma continuous.ae_measurable2 [second_countable_topology α] [second_countable_topology β] {f : δ → α} {g : δ → β} {c : α → β → γ} {μ : measure δ} (h : continuous (λ p : α × β, c p.1 p.2)) (hf : ae_measurable f μ) (hg : ae_measurable g μ) : ae_measurable (λ a, c (f a) (g a)) μ := h.measurable.comp_ae_measurable (hf.prod_mk hg) @[priority 100] instance has_continuous_inv₀.has_measurable_inv [group_with_zero γ] [t1_space γ] [has_continuous_inv₀ γ] : has_measurable_inv γ := ⟨measurable_of_continuous_on_compl_singleton 0 continuous_on_inv₀⟩ @[priority 100, to_additive] instance has_continuous_mul.has_measurable_mul₂ [second_countable_topology γ] [has_mul γ] [has_continuous_mul γ] : has_measurable_mul₂ γ := ⟨continuous_mul.measurable⟩ @[priority 100] instance has_continuous_sub.has_measurable_sub₂ [second_countable_topology γ] [has_sub γ] [has_continuous_sub γ] : has_measurable_sub₂ γ := ⟨continuous_sub.measurable⟩ @[priority 100] instance has_continuous_smul.has_measurable_smul₂ {M α} [topological_space M] [second_countable_topology M] [measurable_space M] [opens_measurable_space M] [topological_space α] [second_countable_topology α] [measurable_space α] [borel_space α] [has_smul M α] [has_continuous_smul M α] : has_measurable_smul₂ M α := ⟨continuous_smul.measurable⟩ end section borel_space variables [topological_space α] [measurable_space α] [borel_space α] [topological_space β] [measurable_space β] [borel_space β] [topological_space γ] [measurable_space γ] [borel_space γ] [measurable_space δ] lemma pi_le_borel_pi {ι : Type*} {π : ι → Type*} [Π i, topological_space (π i)] [Π i, measurable_space (π i)] [∀ i, borel_space (π i)] : measurable_space.pi ≤ borel (Π i, π i) := begin have : ‹Π i, measurable_space (π i)› = λ i, borel (π i) := funext (λ i, borel_space.measurable_eq), rw [this], exact supr_le (λ i, comap_le_iff_le_map.2 $ (continuous_apply i).borel_measurable) end lemma prod_le_borel_prod : prod.measurable_space ≤ borel (α × β) := begin rw [‹borel_space α›.measurable_eq, ‹borel_space β›.measurable_eq], refine sup_le _ _, { exact comap_le_iff_le_map.mpr continuous_fst.borel_measurable }, { exact comap_le_iff_le_map.mpr continuous_snd.borel_measurable } end instance pi.borel_space {ι : Type*} {π : ι → Type*} [countable ι] [Π i, topological_space (π i)] [Π i, measurable_space (π i)] [∀ i, second_countable_topology (π i)] [∀ i, borel_space (π i)] : borel_space (Π i, π i) := ⟨le_antisymm pi_le_borel_pi opens_measurable_space.borel_le⟩ instance prod.borel_space [second_countable_topology α] [second_countable_topology β] : borel_space (α × β) := ⟨le_antisymm prod_le_borel_prod opens_measurable_space.borel_le⟩ protected lemma embedding.measurable_embedding {f : α → β} (h₁ : embedding f) (h₂ : measurable_set (range f)) : measurable_embedding f := show measurable_embedding (coe ∘ (homeomorph.of_embedding f h₁).to_measurable_equiv), from (measurable_embedding.subtype_coe h₂).comp (measurable_equiv.measurable_embedding _) protected lemma closed_embedding.measurable_embedding {f : α → β} (h : closed_embedding f) : measurable_embedding f := h.to_embedding.measurable_embedding h.closed_range.measurable_set protected lemma open_embedding.measurable_embedding {f : α → β} (h : open_embedding f) : measurable_embedding f := h.to_embedding.measurable_embedding h.open_range.measurable_set section linear_order variables [linear_order α] [order_topology α] [second_countable_topology α] lemma measurable_of_Iio {f : δ → α} (hf : ∀ x, measurable_set (f ⁻¹' Iio x)) : measurable f := begin convert measurable_generate_from _, exact borel_space.measurable_eq.trans (borel_eq_generate_from_Iio _), rintro _ ⟨x, rfl⟩, exact hf x end lemma upper_semicontinuous.measurable [topological_space δ] [opens_measurable_space δ] {f : δ → α} (hf : upper_semicontinuous f) : measurable f := measurable_of_Iio (λ y, (hf.is_open_preimage y).measurable_set) lemma measurable_of_Ioi {f : δ → α} (hf : ∀ x, measurable_set (f ⁻¹' Ioi x)) : measurable f := begin convert measurable_generate_from _, exact borel_space.measurable_eq.trans (borel_eq_generate_from_Ioi _), rintro _ ⟨x, rfl⟩, exact hf x end lemma lower_semicontinuous.measurable [topological_space δ] [opens_measurable_space δ] {f : δ → α} (hf : lower_semicontinuous f) : measurable f := measurable_of_Ioi (λ y, (hf.is_open_preimage y).measurable_set) lemma measurable_of_Iic {f : δ → α} (hf : ∀ x, measurable_set (f ⁻¹' Iic x)) : measurable f := begin apply measurable_of_Ioi, simp_rw [← compl_Iic, preimage_compl, measurable_set.compl_iff], assumption end lemma measurable_of_Ici {f : δ → α} (hf : ∀ x, measurable_set (f ⁻¹' Ici x)) : measurable f := begin apply measurable_of_Iio, simp_rw [← compl_Ici, preimage_compl, measurable_set.compl_iff], assumption end lemma measurable.is_lub {ι} [countable ι] {f : ι → δ → α} {g : δ → α} (hf : ∀ i, measurable (f i)) (hg : ∀ b, is_lub {a | ∃ i, f i b = a} (g b)) : measurable g := begin change ∀ b, is_lub (range $ λ i, f i b) (g b) at hg, rw [‹borel_space α›.measurable_eq, borel_eq_generate_from_Ioi α], apply measurable_generate_from, rintro _ ⟨a, rfl⟩, simp_rw [set.preimage, mem_Ioi, lt_is_lub_iff (hg _), exists_range_iff, set_of_exists], exact measurable_set.Union (λ i, hf i (is_open_lt' _).measurable_set) end private lemma ae_measurable.is_lub_of_nonempty {ι} (hι : nonempty ι) {μ : measure δ} [countable ι] {f : ι → δ → α} {g : δ → α} (hf : ∀ i, ae_measurable (f i) μ) (hg : ∀ᵐ b ∂μ, is_lub {a | ∃ i, f i b = a} (g b)) : ae_measurable g μ := begin let p : δ → (ι → α) → Prop := λ x f', is_lub {a | ∃ i, f' i = a} (g x), let g_seq := λ x, ite (x ∈ ae_seq_set hf p) (g x) (⟨g x⟩ : nonempty α).some, have hg_seq : ∀ b, is_lub {a | ∃ i, ae_seq hf p i b = a} (g_seq b), { intro b, haveI hα : nonempty α := nonempty.map g ⟨b⟩, simp only [ae_seq, g_seq], split_ifs, { have h_set_eq : {a : α | ∃ (i : ι), (hf i).mk (f i) b = a} = {a : α | ∃ (i : ι), f i b = a}, { ext x, simp_rw [set.mem_set_of_eq, ae_seq.mk_eq_fun_of_mem_ae_seq_set hf h], }, rw h_set_eq, exact ae_seq.fun_prop_of_mem_ae_seq_set hf h, }, { have h_singleton : {a : α | ∃ (i : ι), hα.some = a} = {hα.some}, { ext1 x, exact ⟨λ hx, hx.some_spec.symm, λ hx, ⟨hι.some, hx.symm⟩⟩, }, rw h_singleton, exact is_lub_singleton, }, }, refine ⟨g_seq, measurable.is_lub (ae_seq.measurable hf p) hg_seq, _⟩, exact (ite_ae_eq_of_measure_compl_zero g (λ x, (⟨g x⟩ : nonempty α).some) (ae_seq_set hf p) (ae_seq.measure_compl_ae_seq_set_eq_zero hf hg)).symm, end lemma ae_measurable.is_lub {ι} {μ : measure δ} [countable ι] {f : ι → δ → α} {g : δ → α} (hf : ∀ i, ae_measurable (f i) μ) (hg : ∀ᵐ b ∂μ, is_lub {a | ∃ i, f i b = a} (g b)) : ae_measurable g μ := begin by_cases hμ : μ = 0, { rw hμ, exact ae_measurable_zero_measure }, haveI : μ.ae.ne_bot, { simpa [ne_bot_iff] }, by_cases hι : nonempty ι, { exact ae_measurable.is_lub_of_nonempty hι hf hg, }, suffices : ∃ x, g =ᵐ[μ] λ y, g x, by { exact ⟨(λ y, g this.some), measurable_const, this.some_spec⟩, }, have h_empty : ∀ x, {a : α | ∃ (i : ι), f i x = a} = ∅, { intro x, ext1 y, rw [set.mem_set_of_eq, set.mem_empty_iff_false, iff_false], exact λ hi, hι (nonempty_of_exists hi), }, simp_rw h_empty at hg, exact ⟨hg.exists.some, hg.mono (λ y hy, is_lub.unique hy hg.exists.some_spec)⟩, end lemma measurable.is_glb {ι} [countable ι] {f : ι → δ → α} {g : δ → α} (hf : ∀ i, measurable (f i)) (hg : ∀ b, is_glb {a | ∃ i, f i b = a} (g b)) : measurable g := begin change ∀ b, is_glb (range $ λ i, f i b) (g b) at hg, rw [‹borel_space α›.measurable_eq, borel_eq_generate_from_Iio α], apply measurable_generate_from, rintro _ ⟨a, rfl⟩, simp_rw [set.preimage, mem_Iio, is_glb_lt_iff (hg _), exists_range_iff, set_of_exists], exact measurable_set.Union (λ i, hf i (is_open_gt' _).measurable_set) end lemma ae_measurable.is_glb {ι} {μ : measure δ} [countable ι] {f : ι → δ → α} {g : δ → α} (hf : ∀ i, ae_measurable (f i) μ) (hg : ∀ᵐ b ∂μ, is_glb {a | ∃ i, f i b = a} (g b)) : ae_measurable g μ := begin nontriviality α, haveI hα : nonempty α := infer_instance, casesI is_empty_or_nonempty ι with hι hι, { simp only [is_empty.exists_iff, set_of_false, is_glb_empty_iff] at hg, exact ae_measurable_const' (hg.mono $ λ a ha, hg.mono $ λ b hb, (hb _).antisymm (ha _)) }, let p : δ → (ι → α) → Prop := λ x f', is_glb {a | ∃ i, f' i = a} (g x), let g_seq := (ae_seq_set hf p).piecewise g (λ _, hα.some), have hg_seq : ∀ b, is_glb {a | ∃ i, ae_seq hf p i b = a} (g_seq b), { intro b, simp only [ae_seq, g_seq, set.piecewise], split_ifs, { have h_set_eq : {a : α | ∃ (i : ι), (hf i).mk (f i) b = a} = {a : α | ∃ (i : ι), f i b = a}, { ext x, simp_rw [set.mem_set_of_eq, ae_seq.mk_eq_fun_of_mem_ae_seq_set hf h], }, rw h_set_eq, exact ae_seq.fun_prop_of_mem_ae_seq_set hf h, }, { exact is_least.is_glb ⟨(@exists_const (hα.some = hα.some) ι _).2 rfl, λ x ⟨i, hi⟩, hi.le⟩ } }, refine ⟨g_seq, measurable.is_glb (ae_seq.measurable hf p) hg_seq, _⟩, exact (ite_ae_eq_of_measure_compl_zero g (λ x, hα.some) (ae_seq_set hf p) (ae_seq.measure_compl_ae_seq_set_eq_zero hf hg)).symm, end protected lemma monotone.measurable [linear_order β] [order_closed_topology β] {f : β → α} (hf : monotone f) : measurable f := suffices h : ∀ x, ord_connected (f ⁻¹' Ioi x), from measurable_of_Ioi (λ x, (h x).measurable_set), λ x, ord_connected_def.mpr (λ a ha b hb c hc, lt_of_lt_of_le ha (hf hc.1)) lemma ae_measurable_restrict_of_monotone_on [linear_order β] [order_closed_topology β] {μ : measure β} {s : set β} (hs : measurable_set s) {f : β → α} (hf : monotone_on f s) : ae_measurable f (μ.restrict s) := have this : monotone (f ∘ coe : s → α), from λ ⟨x, hx⟩ ⟨y, hy⟩ (hxy : x ≤ y), hf hx hy hxy, ae_measurable_restrict_of_measurable_subtype hs this.measurable protected lemma antitone.measurable [linear_order β] [order_closed_topology β] {f : β → α} (hf : antitone f) : measurable f := @monotone.measurable αᵒᵈ β _ _ ‹_› _ _ _ _ _ ‹_› _ _ _ hf lemma ae_measurable_restrict_of_antitone_on [linear_order β] [order_closed_topology β] {μ : measure β} {s : set β} (hs : measurable_set s) {f : β → α} (hf : antitone_on f s) : ae_measurable f (μ.restrict s) := @ae_measurable_restrict_of_monotone_on αᵒᵈ β _ _ ‹_› _ _ _ _ _ ‹_› _ _ _ _ hs _ hf lemma measurable_set_of_mem_nhds_within_Ioi_aux {s : set α} (h : ∀ x ∈ s, s ∈ 𝓝[>] x) (h' : ∀ x ∈ s, ∃ y, x < y) : measurable_set s := begin choose! M hM using h', suffices H : (s \ interior s).countable, { have : s = interior s ∪ (s \ interior s), by rw union_diff_cancel interior_subset, rw this, exact is_open_interior.measurable_set.union H.measurable_set }, have A : ∀ x ∈ s, ∃ y ∈ Ioi x, Ioo x y ⊆ s := λ x hx, (mem_nhds_within_Ioi_iff_exists_Ioo_subset' (hM x hx)).1 (h x hx), choose! y hy h'y using A, have B : set.pairwise_disjoint (s \ interior s) (λ x, Ioo x (y x)), { assume x hx x' hx' hxx', rcases lt_or_gt_of_ne hxx' with h'|h', { apply disjoint_left.2 (λ z hz h'z, _), have : x' ∈ interior s := mem_interior.2 ⟨Ioo x (y x), h'y _ hx.1, is_open_Ioo, ⟨h', h'z.1.trans hz.2⟩⟩, exact false.elim (hx'.2 this) }, { apply disjoint_left.2 (λ z hz h'z, _), have : x ∈ interior s := mem_interior.2 ⟨Ioo x' (y x'), h'y _ hx'.1, is_open_Ioo, ⟨h', hz.1.trans h'z.2⟩⟩, exact false.elim (hx.2 this) } }, exact B.countable_of_Ioo (λ x hx, hy x hx.1), end /-- If a set is a right-neighborhood of all of its points, then it is measurable. -/ lemma measurable_set_of_mem_nhds_within_Ioi {s : set α} (h : ∀ x ∈ s, s ∈ 𝓝[>] x) : measurable_set s := begin by_cases H : ∃ x ∈ s, is_top x, { rcases H with ⟨x₀, x₀s, h₀⟩, have : s = {x₀} ∪ (s \ {x₀}), by rw union_diff_cancel (singleton_subset_iff.2 x₀s), rw this, refine (measurable_set_singleton _).union _, have A : ∀ x ∈ s \ {x₀}, x < x₀ := λ x hx, lt_of_le_of_ne (h₀ _) (by simpa using hx.2), refine measurable_set_of_mem_nhds_within_Ioi_aux (λ x hx, _) (λ x hx, ⟨x₀, A x hx⟩), obtain ⟨u, hu, us⟩ : ∃ (u : α) (H : u ∈ Ioi x), Ioo x u ⊆ s := (mem_nhds_within_Ioi_iff_exists_Ioo_subset' (A x hx)).1 (h x hx.1), refine (mem_nhds_within_Ioi_iff_exists_Ioo_subset' (A x hx)).2 ⟨u, hu, λ y hy, ⟨us hy, _⟩⟩, exact ne_of_lt (hy.2.trans_le (h₀ _)) }, { apply measurable_set_of_mem_nhds_within_Ioi_aux h, simp only [is_top] at H, push_neg at H, exact H } end end linear_order @[measurability] lemma measurable.supr_Prop {α} [measurable_space α] [complete_lattice α] (p : Prop) {f : δ → α} (hf : measurable f) : measurable (λ b, ⨆ h : p, f b) := classical.by_cases (assume h : p, begin convert hf, funext, exact supr_pos h end) (assume h : ¬p, begin convert measurable_const, funext, exact supr_neg h end) @[measurability] lemma measurable.infi_Prop {α} [measurable_space α] [complete_lattice α] (p : Prop) {f : δ → α} (hf : measurable f) : measurable (λ b, ⨅ h : p, f b) := classical.by_cases (assume h : p, begin convert hf, funext, exact infi_pos h end ) (assume h : ¬p, begin convert measurable_const, funext, exact infi_neg h end) section complete_linear_order variables [complete_linear_order α] [order_topology α] [second_countable_topology α] @[measurability] lemma measurable_supr {ι} [countable ι] {f : ι → δ → α} (hf : ∀ i, measurable (f i)) : measurable (λ b, ⨆ i, f i b) := measurable.is_lub hf $ λ b, is_lub_supr @[measurability] lemma ae_measurable_supr {ι} {μ : measure δ} [countable ι] {f : ι → δ → α} (hf : ∀ i, ae_measurable (f i) μ) : ae_measurable (λ b, ⨆ i, f i b) μ := ae_measurable.is_lub hf $ (ae_of_all μ (λ b, is_lub_supr)) @[measurability] lemma measurable_infi {ι} [countable ι] {f : ι → δ → α} (hf : ∀ i, measurable (f i)) : measurable (λ b, ⨅ i, f i b) := measurable.is_glb hf $ λ b, is_glb_infi @[measurability] lemma ae_measurable_infi {ι} {μ : measure δ} [countable ι] {f : ι → δ → α} (hf : ∀ i, ae_measurable (f i) μ) : ae_measurable (λ b, ⨅ i, f i b) μ := ae_measurable.is_glb hf $ (ae_of_all μ (λ b, is_glb_infi)) lemma measurable_bsupr {ι} (s : set ι) {f : ι → δ → α} (hs : s.countable) (hf : ∀ i, measurable (f i)) : measurable (λ b, ⨆ i ∈ s, f i b) := by { haveI : encodable s := hs.to_encodable, simp only [supr_subtype'], exact measurable_supr (λ i, hf i) } lemma ae_measurable_bsupr {ι} {μ : measure δ} (s : set ι) {f : ι → δ → α} (hs : s.countable) (hf : ∀ i, ae_measurable (f i) μ) : ae_measurable (λ b, ⨆ i ∈ s, f i b) μ := begin haveI : encodable s := hs.to_encodable, simp only [supr_subtype'], exact ae_measurable_supr (λ i, hf i), end lemma measurable_binfi {ι} (s : set ι) {f : ι → δ → α} (hs : s.countable) (hf : ∀ i, measurable (f i)) : measurable (λ b, ⨅ i ∈ s, f i b) := by { haveI : encodable s := hs.to_encodable, simp only [infi_subtype'], exact measurable_infi (λ i, hf i) } lemma ae_measurable_binfi {ι} {μ : measure δ} (s : set ι) {f : ι → δ → α} (hs : s.countable) (hf : ∀ i, ae_measurable (f i) μ) : ae_measurable (λ b, ⨅ i ∈ s, f i b) μ := begin haveI : encodable s := hs.to_encodable, simp only [infi_subtype'], exact ae_measurable_infi (λ i, hf i), end /-- `liminf` over a general filter is measurable. See `measurable_liminf` for the version over `ℕ`. -/ lemma measurable_liminf' {ι ι'} {f : ι → δ → α} {u : filter ι} (hf : ∀ i, measurable (f i)) {p : ι' → Prop} {s : ι' → set ι} (hu : u.has_countable_basis p s) (hs : ∀ i, (s i).countable) : measurable (λ x, liminf (λ i, f i x) u) := begin simp_rw [hu.to_has_basis.liminf_eq_supr_infi], refine measurable_bsupr _ hu.countable _, exact λ i, measurable_binfi _ (hs i) hf end /-- `limsup` over a general filter is measurable. See `measurable_limsup` for the version over `ℕ`. -/ lemma measurable_limsup' {ι ι'} {f : ι → δ → α} {u : filter ι} (hf : ∀ i, measurable (f i)) {p : ι' → Prop} {s : ι' → set ι} (hu : u.has_countable_basis p s) (hs : ∀ i, (s i).countable) : measurable (λ x, limsup (λ i, f i x) u) := begin simp_rw [hu.to_has_basis.limsup_eq_infi_supr], refine measurable_binfi _ hu.countable _, exact λ i, measurable_bsupr _ (hs i) hf end /-- `liminf` over `ℕ` is measurable. See `measurable_liminf'` for a version with a general filter. -/ @[measurability] lemma measurable_liminf {f : ℕ → δ → α} (hf : ∀ i, measurable (f i)) : measurable (λ x, liminf (λ i, f i x) at_top) := measurable_liminf' hf at_top_countable_basis (λ i, to_countable _) /-- `limsup` over `ℕ` is measurable. See `measurable_limsup'` for a version with a general filter. -/ @[measurability] lemma measurable_limsup {f : ℕ → δ → α} (hf : ∀ i, measurable (f i)) : measurable (λ x, limsup (λ i, f i x) at_top) := measurable_limsup' hf at_top_countable_basis (λ i, to_countable _) end complete_linear_order section conditionally_complete_linear_order variables [conditionally_complete_linear_order α] [order_topology α] [second_countable_topology α] lemma measurable_cSup {ι} {f : ι → δ → α} {s : set ι} (hs : s.countable) (hf : ∀ i, measurable (f i)) (bdd : ∀ x, bdd_above ((λ i, f i x) '' s)) : measurable (λ x, Sup ((λ i, f i x) '' s)) := begin cases eq_empty_or_nonempty s with h2s h2s, { simp [h2s, measurable_const] }, { apply measurable_of_Iic, intro y, simp_rw [preimage, mem_Iic, cSup_le_iff (bdd _) (h2s.image _), ball_image_iff, set_of_forall], exact measurable_set.bInter hs (λ i hi, measurable_set_le (hf i) measurable_const) } end lemma measurable_cInf {ι} {f : ι → δ → α} {s : set ι} (hs : s.countable) (hf : ∀ i, measurable (f i)) (bdd : ∀ x, bdd_below ((λ i, f i x) '' s)) : measurable (λ x, Inf ((λ i, f i x) '' s)) := @measurable_cSup αᵒᵈ _ _ _ _ _ _ _ _ _ _ _ hs hf bdd lemma measurable_csupr {ι : Type*} [countable ι] {f : ι → δ → α} (hf : ∀ i, measurable (f i)) (bdd : ∀ x, bdd_above (range (λ i, f i x))) : measurable (λ x, ⨆ i, f i x) := begin change measurable (λ x, Sup (range (λ i : ι, f i x))), simp_rw ← image_univ at bdd ⊢, refine measurable_cSup countable_univ hf bdd, end lemma measurable_cinfi {ι : Type*} [countable ι] {f : ι → δ → α} (hf : ∀ i, measurable (f i)) (bdd : ∀ x, bdd_below (range (λ i, f i x))) : measurable (λ x, ⨅ i, f i x) := @measurable_csupr αᵒᵈ _ _ _ _ _ _ _ _ _ _ _ hf bdd end conditionally_complete_linear_order /-- Convert a `homeomorph` to a `measurable_equiv`. -/ def homemorph.to_measurable_equiv (h : α ≃ₜ β) : α ≃ᵐ β := { to_equiv := h.to_equiv, measurable_to_fun := h.continuous_to_fun.measurable, measurable_inv_fun := h.continuous_inv_fun.measurable } protected lemma is_finite_measure_on_compacts.map {α : Type*} {m0 : measurable_space α} [topological_space α] [opens_measurable_space α] {β : Type*} [measurable_space β] [topological_space β] [borel_space β] [t2_space β] (μ : measure α) [is_finite_measure_on_compacts μ] (f : α ≃ₜ β) : is_finite_measure_on_compacts (measure.map f μ) := ⟨begin assume K hK, rw [measure.map_apply f.measurable hK.measurable_set], apply is_compact.measure_lt_top, rwa f.is_compact_preimage end⟩ end borel_space instance empty.borel_space : borel_space empty := ⟨borel_eq_top_of_discrete.symm⟩ instance unit.borel_space : borel_space unit := ⟨borel_eq_top_of_discrete.symm⟩ instance bool.borel_space : borel_space bool := ⟨borel_eq_top_of_discrete.symm⟩ instance nat.borel_space : borel_space ℕ := ⟨borel_eq_top_of_discrete.symm⟩ instance int.borel_space : borel_space ℤ := ⟨borel_eq_top_of_discrete.symm⟩ instance rat.borel_space : borel_space ℚ := ⟨borel_eq_top_of_countable.symm⟩ @[priority 900] instance is_R_or_C.measurable_space {𝕜 : Type*} [is_R_or_C 𝕜] : measurable_space 𝕜 := borel 𝕜 @[priority 900] instance is_R_or_C.borel_space {𝕜 : Type*} [is_R_or_C 𝕜] : borel_space 𝕜 := ⟨rfl⟩ /- Instances on `real` and `complex` are special cases of `is_R_or_C` but without these instances, Lean fails to prove `borel_space (ι → ℝ)`, so we leave them here. -/ instance real.measurable_space : measurable_space ℝ := borel ℝ instance real.borel_space : borel_space ℝ := ⟨rfl⟩ instance nnreal.measurable_space : measurable_space ℝ≥0 := subtype.measurable_space instance nnreal.borel_space : borel_space ℝ≥0 := subtype.borel_space _ instance ennreal.measurable_space : measurable_space ℝ≥0∞ := borel ℝ≥0∞ instance ennreal.borel_space : borel_space ℝ≥0∞ := ⟨rfl⟩ instance ereal.measurable_space : measurable_space ereal := borel ereal instance ereal.borel_space : borel_space ereal := ⟨rfl⟩ instance complex.measurable_space : measurable_space ℂ := borel ℂ instance complex.borel_space : borel_space ℂ := ⟨rfl⟩ instance add_circle.measurable_space {a : ℝ} : measurable_space (add_circle a) := borel (add_circle a) instance add_circle.borel_space {a : ℝ} : borel_space (add_circle a) := ⟨rfl⟩ @[measurability] protected lemma add_circle.measurable_mk' {a : ℝ} : measurable (coe : ℝ → add_circle a) := continuous.measurable $ add_circle.continuous_mk' a /-- One can cut out `ℝ≥0∞` into the sets `{0}`, `Ico (t^n) (t^(n+1))` for `n : ℤ` and `{∞}`. This gives a way to compute the measure of a set in terms of sets on which a given function `f` does not fluctuate by more than `t`. -/ lemma measure_eq_measure_preimage_add_measure_tsum_Ico_zpow [measurable_space α] (μ : measure α) {f : α → ℝ≥0∞} (hf : measurable f) {s : set α} (hs : measurable_set s) {t : ℝ≥0} (ht : 1 < t) : μ s = μ (s ∩ f⁻¹' {0}) + μ (s ∩ f⁻¹' {∞}) + ∑' (n : ℤ), μ (s ∩ f⁻¹' (Ico (t^n) (t^(n+1)))) := begin have A : μ s = μ (s ∩ f⁻¹' {0}) + μ (s ∩ f⁻¹' (Ioi 0)), { rw ← measure_union, { congr' 1, ext x, have : 0 = f x ∨ 0 < f x := eq_or_lt_of_le bot_le, rw eq_comm at this, simp only [←and_or_distrib_left, this, mem_singleton_iff, mem_inter_iff, and_true, mem_union, mem_Ioi, mem_preimage], }, { apply disjoint_left.2 (λ x hx h'x, _), have : 0 < f x := h'x.2, exact lt_irrefl 0 (this.trans_le hx.2.le) }, { exact hs.inter (hf measurable_set_Ioi) } }, have B : μ (s ∩ f⁻¹' (Ioi 0)) = μ (s ∩ f⁻¹' {∞}) + μ (s ∩ f⁻¹' (Ioo 0 ∞)), { rw ← measure_union, { rw ← inter_union_distrib_left, congr, ext x, simp only [mem_singleton_iff, mem_union, mem_Ioo, mem_Ioi, mem_preimage], have H : f x = ∞ ∨ f x < ∞ := eq_or_lt_of_le le_top, cases H, { simp only [H, eq_self_iff_true, or_false, with_top.zero_lt_top, not_top_lt, and_false] }, { simp only [H, H.ne, and_true, false_or] } }, { apply disjoint_left.2 (λ x hx h'x, _), have : f x < ∞ := h'x.2.2, exact lt_irrefl _ (this.trans_le (le_of_eq hx.2.symm)) }, { exact hs.inter (hf measurable_set_Ioo) } }, have C : μ (s ∩ f⁻¹' (Ioo 0 ∞)) = ∑' (n : ℤ), μ (s ∩ f⁻¹' (Ico (t^n) (t^(n+1)))), { rw [← measure_Union, ennreal.Ioo_zero_top_eq_Union_Ico_zpow (ennreal.one_lt_coe_iff.2 ht) ennreal.coe_ne_top, preimage_Union, inter_Union], { assume i j, simp only [function.on_fun], assume hij, wlog h : i < j generalizing i j, { exact (this hij.symm (hij.lt_or_lt.resolve_left h)).symm }, apply disjoint_left.2 (λ x hx h'x, lt_irrefl (f x) _), calc f x < t ^ (i + 1) : hx.2.2 ... ≤ t ^ j : ennreal.zpow_le_of_le (ennreal.one_le_coe_iff.2 ht.le) h ... ≤ f x : h'x.2.1 }, { assume n, exact hs.inter (hf measurable_set_Ico) } }, rw [A, B, C, add_assoc], end section pseudo_metric_space variables [pseudo_metric_space α] [measurable_space α] [opens_measurable_space α] variables [measurable_space β] {x : α} {ε : ℝ} open metric @[measurability] lemma measurable_set_ball : measurable_set (metric.ball x ε) := metric.is_open_ball.measurable_set @[measurability] lemma measurable_set_closed_ball : measurable_set (metric.closed_ball x ε) := metric.is_closed_ball.measurable_set @[measurability] lemma measurable_inf_dist {s : set α} : measurable (λ x, inf_dist x s) := (continuous_inf_dist_pt s).measurable @[measurability] lemma measurable.inf_dist {f : β → α} (hf : measurable f) {s : set α} : measurable (λ x, inf_dist (f x) s) := measurable_inf_dist.comp hf @[measurability] lemma measurable_inf_nndist {s : set α} : measurable (λ x, inf_nndist x s) := (continuous_inf_nndist_pt s).measurable @[measurability] lemma measurable.inf_nndist {f : β → α} (hf : measurable f) {s : set α} : measurable (λ x, inf_nndist (f x) s) := measurable_inf_nndist.comp hf section variables [second_countable_topology α] @[measurability] lemma measurable_dist : measurable (λ p : α × α, dist p.1 p.2) := continuous_dist.measurable @[measurability] lemma measurable.dist {f g : β → α} (hf : measurable f) (hg : measurable g) : measurable (λ b, dist (f b) (g b)) := (@continuous_dist α _).measurable2 hf hg @[measurability] lemma measurable_nndist : measurable (λ p : α × α, nndist p.1 p.2) := continuous_nndist.measurable @[measurability] lemma measurable.nndist {f g : β → α} (hf : measurable f) (hg : measurable g) : measurable (λ b, nndist (f b) (g b)) := (@continuous_nndist α _).measurable2 hf hg end /-- If a set has a closed thickening with finite measure, then the measure of its `r`-closed thickenings converges to the measure of its closure as `r` tends to `0`. -/ lemma tendsto_measure_cthickening {μ : measure α} {s : set α} (hs : ∃ R > 0, μ (cthickening R s) ≠ ∞) : tendsto (λ r, μ (cthickening r s)) (𝓝 0) (𝓝 (μ (closure s))) := begin have A : tendsto (λ r, μ (cthickening r s)) (𝓝[Ioi 0] 0) (𝓝 (μ (closure s))), { rw closure_eq_Inter_cthickening, exact tendsto_measure_bInter_gt (λ r hr, is_closed_cthickening.measurable_set) (λ i j ipos ij, cthickening_mono ij _) hs }, have B : tendsto (λ r, μ (cthickening r s)) (𝓝[Iic 0] 0) (𝓝 (μ (closure s))), { apply tendsto.congr' _ tendsto_const_nhds, filter_upwards [self_mem_nhds_within] with _ hr, rw cthickening_of_nonpos hr, }, convert B.sup A, exact (nhds_left_sup_nhds_right' 0).symm, end /-- If a closed set has a closed thickening with finite measure, then the measure of its `r`-closed thickenings converges to its measure as `r` tends to `0`. -/ lemma tendsto_measure_cthickening_of_is_closed {μ : measure α} {s : set α} (hs : ∃ R > 0, μ (cthickening R s) ≠ ∞) (h's : is_closed s) : tendsto (λ r, μ (cthickening r s)) (𝓝 0) (𝓝 (μ s)) := begin convert tendsto_measure_cthickening hs, exact h's.closure_eq.symm end end pseudo_metric_space /-- Given a compact set in a proper space, the measure of its `r`-closed thickenings converges to its measure as `r` tends to `0`. -/ lemma tendsto_measure_cthickening_of_is_compact [metric_space α] [measurable_space α] [opens_measurable_space α] [proper_space α] {μ : measure α} [is_finite_measure_on_compacts μ] {s : set α} (hs : is_compact s) : tendsto (λ r, μ (metric.cthickening r s)) (𝓝 0) (𝓝 (μ s)) := tendsto_measure_cthickening_of_is_closed ⟨1, zero_lt_one, hs.bounded.cthickening.measure_lt_top.ne⟩ hs.is_closed section pseudo_emetric_space variables [pseudo_emetric_space α] [measurable_space α] [opens_measurable_space α] variables [measurable_space β] {x : α} {ε : ℝ≥0∞} open emetric @[measurability] lemma measurable_set_eball : measurable_set (emetric.ball x ε) := emetric.is_open_ball.measurable_set @[measurability] lemma measurable_edist_right : measurable (edist x) := (continuous_const.edist continuous_id).measurable @[measurability] lemma measurable_edist_left : measurable (λ y, edist y x) := (continuous_id.edist continuous_const).measurable @[measurability] lemma measurable_inf_edist {s : set α} : measurable (λ x, inf_edist x s) := continuous_inf_edist.measurable @[measurability] lemma measurable.inf_edist {f : β → α} (hf : measurable f) {s : set α} : measurable (λ x, inf_edist (f x) s) := measurable_inf_edist.comp hf variables [second_countable_topology α] @[measurability] lemma measurable_edist : measurable (λ p : α × α, edist p.1 p.2) := continuous_edist.measurable @[measurability] lemma measurable.edist {f g : β → α} (hf : measurable f) (hg : measurable g) : measurable (λ b, edist (f b) (g b)) := (@continuous_edist α _).measurable2 hf hg @[measurability] lemma ae_measurable.edist {f g : β → α} {μ : measure β} (hf : ae_measurable f μ) (hg : ae_measurable g μ) : ae_measurable (λ a, edist (f a) (g a)) μ := (@continuous_edist α _).ae_measurable2 hf hg end pseudo_emetric_space namespace real open measurable_space measure_theory lemma borel_eq_generate_from_Ioo_rat : borel ℝ = generate_from (⋃(a b : ℚ) (h : a < b), {Ioo a b}) := is_topological_basis_Ioo_rat.borel_eq_generate_from lemma is_pi_system_Ioo_rat : @is_pi_system ℝ (⋃ (a b : ℚ) (h : a < b), {Ioo a b}) := begin convert is_pi_system_Ioo (coe : ℚ → ℝ) (coe : ℚ → ℝ), ext x, simp [eq_comm] end /-- The intervals `(-(n + 1), (n + 1))` form a finite spanning sets in the set of open intervals with rational endpoints for a locally finite measure `μ` on `ℝ`. -/ def finite_spanning_sets_in_Ioo_rat (μ : measure ℝ) [is_locally_finite_measure μ] : μ.finite_spanning_sets_in (⋃ (a b : ℚ) (h : a < b), {Ioo a b}) := { set := λ n, Ioo (-(n + 1)) (n + 1), set_mem := λ n, begin simp only [mem_Union, mem_singleton_iff], refine ⟨-(n + 1 : ℕ), n + 1, _, by simp⟩, -- TODO: norm_cast fails here? exact (neg_nonpos.2 (@nat.cast_nonneg ℚ _ (n + 1))).trans_lt n.cast_add_one_pos end, finite := λ n, measure_Ioo_lt_top, spanning := Union_eq_univ_iff.2 $ λ x, ⟨⌊|x|⌋₊, neg_lt.1 ((neg_le_abs_self x).trans_lt (nat.lt_floor_add_one _)), (le_abs_self x).trans_lt (nat.lt_floor_add_one _)⟩ } lemma measure_ext_Ioo_rat {μ ν : measure ℝ} [is_locally_finite_measure μ] (h : ∀ a b : ℚ, μ (Ioo a b) = ν (Ioo a b)) : μ = ν := (finite_spanning_sets_in_Ioo_rat μ).ext borel_eq_generate_from_Ioo_rat is_pi_system_Ioo_rat $ by { simp only [mem_Union, mem_singleton_iff], rintro _ ⟨a, b, -, rfl⟩, apply h } lemma borel_eq_generate_from_Iio_rat : borel ℝ = generate_from (⋃ a : ℚ, {Iio a}) := begin let g : measurable_space ℝ := generate_from (⋃ a : ℚ, {Iio a}), refine le_antisymm _ _, { rw borel_eq_generate_from_Ioo_rat, refine generate_from_le (λ t, _), simp only [mem_Union, mem_singleton_iff], rintro ⟨a, b, h, rfl⟩, rw (set.ext (λ x, _) : Ioo (a : ℝ) b = (⋃c>a, (Iio c)ᶜ) ∩ Iio b), { have hg : ∀ q : ℚ, measurable_set[g] (Iio q) := λ q, generate_measurable.basic (Iio q) (by simp), refine @measurable_set.inter _ g _ _ _ (hg _), refine @measurable_set.bUnion _ _ g _ _ (to_countable _) (λ c h, _), exact @measurable_set.compl _ _ g (hg _) }, { suffices : x < ↑b → (↑a < x ↔ ∃ (i : ℚ), a < i ∧ ↑i ≤ x), by simpa, refine λ _, ⟨λ h, _, λ ⟨i, hai, hix⟩, (rat.cast_lt.2 hai).trans_le hix⟩, rcases exists_rat_btwn h with ⟨c, ac, cx⟩, exact ⟨c, rat.cast_lt.1 ac, cx.le⟩ } }, { refine measurable_space.generate_from_le (λ _, _), simp only [mem_Union, mem_singleton_iff], rintro ⟨r, rfl⟩, exact measurable_set_Iio } end end real variable [measurable_space α] @[measurability] lemma measurable_real_to_nnreal : measurable (real.to_nnreal) := continuous_real_to_nnreal.measurable @[measurability] lemma measurable.real_to_nnreal {f : α → ℝ} (hf : measurable f) : measurable (λ x, real.to_nnreal (f x)) := measurable_real_to_nnreal.comp hf @[measurability] lemma ae_measurable.real_to_nnreal {f : α → ℝ} {μ : measure α} (hf : ae_measurable f μ) : ae_measurable (λ x, real.to_nnreal (f x)) μ := measurable_real_to_nnreal.comp_ae_measurable hf @[measurability] lemma measurable_coe_nnreal_real : measurable (coe : ℝ≥0 → ℝ) := nnreal.continuous_coe.measurable @[measurability] lemma measurable.coe_nnreal_real {f : α → ℝ≥0} (hf : measurable f) : measurable (λ x, (f x : ℝ)) := measurable_coe_nnreal_real.comp hf @[measurability] lemma ae_measurable.coe_nnreal_real {f : α → ℝ≥0} {μ : measure α} (hf : ae_measurable f μ) : ae_measurable (λ x, (f x : ℝ)) μ := measurable_coe_nnreal_real.comp_ae_measurable hf @[measurability] lemma measurable_coe_nnreal_ennreal : measurable (coe : ℝ≥0 → ℝ≥0∞) := ennreal.continuous_coe.measurable @[measurability] lemma measurable.coe_nnreal_ennreal {f : α → ℝ≥0} (hf : measurable f) : measurable (λ x, (f x : ℝ≥0∞)) := ennreal.continuous_coe.measurable.comp hf @[measurability] lemma ae_measurable.coe_nnreal_ennreal {f : α → ℝ≥0} {μ : measure α} (hf : ae_measurable f μ) : ae_measurable (λ x, (f x : ℝ≥0∞)) μ := ennreal.continuous_coe.measurable.comp_ae_measurable hf @[measurability] lemma measurable.ennreal_of_real {f : α → ℝ} (hf : measurable f) : measurable (λ x, ennreal.of_real (f x)) := ennreal.continuous_of_real.measurable.comp hf @[simp, norm_cast] lemma measurable_coe_nnreal_real_iff {f : α → ℝ≥0} : measurable (λ x, f x : α → ℝ) ↔ measurable f := ⟨λ h, by simpa only [real.to_nnreal_coe] using h.real_to_nnreal, measurable.coe_nnreal_real⟩ @[simp, norm_cast] lemma ae_measurable_coe_nnreal_real_iff {f : α → ℝ≥0} {μ : measure α} : ae_measurable (λ x, f x : α → ℝ) μ ↔ ae_measurable f μ := ⟨λ h, by simpa only [real.to_nnreal_coe] using h.real_to_nnreal, ae_measurable.coe_nnreal_real⟩ /-- The set of finite `ℝ≥0∞` numbers is `measurable_equiv` to `ℝ≥0`. -/ def measurable_equiv.ennreal_equiv_nnreal : {r : ℝ≥0∞ | r ≠ ∞} ≃ᵐ ℝ≥0 := ennreal.ne_top_homeomorph_nnreal.to_measurable_equiv namespace ennreal lemma measurable_of_measurable_nnreal {f : ℝ≥0∞ → α} (h : measurable (λ p : ℝ≥0, f p)) : measurable f := measurable_of_measurable_on_compl_singleton ∞ (measurable_equiv.ennreal_equiv_nnreal.symm.measurable_comp_iff.1 h) /-- `ℝ≥0∞` is `measurable_equiv` to `ℝ≥0 ⊕ unit`. -/ def ennreal_equiv_sum : ℝ≥0∞ ≃ᵐ ℝ≥0 ⊕ unit := { measurable_to_fun := measurable_of_measurable_nnreal measurable_inl, measurable_inv_fun := measurable_sum measurable_coe_nnreal_ennreal (@measurable_const ℝ≥0∞ unit _ _ ∞), .. equiv.option_equiv_sum_punit ℝ≥0 } open function (uncurry) lemma measurable_of_measurable_nnreal_prod [measurable_space β] [measurable_space γ] {f : ℝ≥0∞ × β → γ} (H₁ : measurable (λ p : ℝ≥0 × β, f (p.1, p.2))) (H₂ : measurable (λ x, f (∞, x))) : measurable f := let e : ℝ≥0∞ × β ≃ᵐ ℝ≥0 × β ⊕ unit × β := (ennreal_equiv_sum.prod_congr (measurable_equiv.refl β)).trans (measurable_equiv.sum_prod_distrib _ _ _) in e.symm.measurable_comp_iff.1 $ measurable_sum H₁ (H₂.comp measurable_id.snd) lemma measurable_of_measurable_nnreal_nnreal [measurable_space β] {f : ℝ≥0∞ × ℝ≥0∞ → β} (h₁ : measurable (λ p : ℝ≥0 × ℝ≥0, f (p.1, p.2))) (h₂ : measurable (λ r : ℝ≥0, f (∞, r))) (h₃ : measurable (λ r : ℝ≥0, f (r, ∞))) : measurable f := measurable_of_measurable_nnreal_prod (measurable_swap_iff.1 $ measurable_of_measurable_nnreal_prod (h₁.comp measurable_swap) h₃) (measurable_of_measurable_nnreal h₂) @[measurability] lemma measurable_of_real : measurable ennreal.of_real := ennreal.continuous_of_real.measurable @[measurability] lemma measurable_to_real : measurable ennreal.to_real := ennreal.measurable_of_measurable_nnreal measurable_coe_nnreal_real @[measurability] lemma measurable_to_nnreal : measurable ennreal.to_nnreal := ennreal.measurable_of_measurable_nnreal measurable_id instance : has_measurable_mul₂ ℝ≥0∞ := begin refine ⟨measurable_of_measurable_nnreal_nnreal _ _ _⟩, { simp only [← ennreal.coe_mul, measurable_mul.coe_nnreal_ennreal] }, { simp only [ennreal.top_mul, ennreal.coe_eq_zero], exact measurable_const.piecewise (measurable_set_singleton _) measurable_const }, { simp only [ennreal.mul_top, ennreal.coe_eq_zero], exact measurable_const.piecewise (measurable_set_singleton _) measurable_const } end instance : has_measurable_sub₂ ℝ≥0∞ := ⟨by apply measurable_of_measurable_nnreal_nnreal; simp [← with_top.coe_sub, continuous_sub.measurable.coe_nnreal_ennreal]⟩ instance : has_measurable_inv ℝ≥0∞ := ⟨continuous_inv.measurable⟩ end ennreal @[measurability] lemma measurable.ennreal_to_nnreal {f : α → ℝ≥0∞} (hf : measurable f) : measurable (λ x, (f x).to_nnreal) := ennreal.measurable_to_nnreal.comp hf @[measurability] lemma ae_measurable.ennreal_to_nnreal {f : α → ℝ≥0∞} {μ : measure α} (hf : ae_measurable f μ) : ae_measurable (λ x, (f x).to_nnreal) μ := ennreal.measurable_to_nnreal.comp_ae_measurable hf @[simp, norm_cast] lemma measurable_coe_nnreal_ennreal_iff {f : α → ℝ≥0} : measurable (λ x, (f x : ℝ≥0∞)) ↔ measurable f := ⟨λ h, h.ennreal_to_nnreal, λ h, h.coe_nnreal_ennreal⟩ @[simp, norm_cast] lemma ae_measurable_coe_nnreal_ennreal_iff {f : α → ℝ≥0} {μ : measure α} : ae_measurable (λ x, (f x : ℝ≥0∞)) μ ↔ ae_measurable f μ := ⟨λ h, h.ennreal_to_nnreal, λ h, h.coe_nnreal_ennreal⟩ @[measurability] lemma measurable.ennreal_to_real {f : α → ℝ≥0∞} (hf : measurable f) : measurable (λ x, ennreal.to_real (f x)) := ennreal.measurable_to_real.comp hf @[measurability] lemma ae_measurable.ennreal_to_real {f : α → ℝ≥0∞} {μ : measure α} (hf : ae_measurable f μ) : ae_measurable (λ x, ennreal.to_real (f x)) μ := ennreal.measurable_to_real.comp_ae_measurable hf /-- note: `ℝ≥0∞` can probably be generalized in a future version of this lemma. -/ @[measurability] lemma measurable.ennreal_tsum {ι} [countable ι] {f : ι → α → ℝ≥0∞} (h : ∀ i, measurable (f i)) : measurable (λ x, ∑' i, f i x) := by { simp_rw [ennreal.tsum_eq_supr_sum], apply measurable_supr, exact λ s, s.measurable_sum (λ i _, h i) } @[measurability] lemma measurable.ennreal_tsum' {ι} [countable ι] {f : ι → α → ℝ≥0∞} (h : ∀ i, measurable (f i)) : measurable (∑' i, f i) := begin convert measurable.ennreal_tsum h, ext1 x, exact tsum_apply (pi.summable.2 (λ _, ennreal.summable)), end @[measurability] lemma measurable.nnreal_tsum {ι} [countable ι] {f : ι → α → ℝ≥0} (h : ∀ i, measurable (f i)) : measurable (λ x, ∑' i, f i x) := begin simp_rw [nnreal.tsum_eq_to_nnreal_tsum], exact (measurable.ennreal_tsum (λ i, (h i).coe_nnreal_ennreal)).ennreal_to_nnreal, end @[measurability] lemma ae_measurable.ennreal_tsum {ι} [countable ι] {f : ι → α → ℝ≥0∞} {μ : measure α} (h : ∀ i, ae_measurable (f i) μ) : ae_measurable (λ x, ∑' i, f i x) μ := by { simp_rw [ennreal.tsum_eq_supr_sum], apply ae_measurable_supr, exact λ s, finset.ae_measurable_sum s (λ i _, h i) } @[measurability] lemma ae_measurable.nnreal_tsum {α : Type*} [measurable_space α] {ι : Type*} [countable ι] {f : ι → α → nnreal} {μ : measure_theory.measure α} (h : ∀ (i : ι), ae_measurable (f i) μ) : ae_measurable (λ (x : α), ∑' (i : ι), f i x) μ := begin simp_rw [nnreal.tsum_eq_to_nnreal_tsum], exact (ae_measurable.ennreal_tsum (λ i, (h i).coe_nnreal_ennreal)).ennreal_to_nnreal, end @[measurability] lemma measurable_coe_real_ereal : measurable (coe : ℝ → ereal) := continuous_coe_real_ereal.measurable @[measurability] lemma measurable.coe_real_ereal {f : α → ℝ} (hf : measurable f) : measurable (λ x, (f x : ereal)) := measurable_coe_real_ereal.comp hf @[measurability] lemma ae_measurable.coe_real_ereal {f : α → ℝ} {μ : measure α} (hf : ae_measurable f μ) : ae_measurable (λ x, (f x : ereal)) μ := measurable_coe_real_ereal.comp_ae_measurable hf /-- The set of finite `ereal` numbers is `measurable_equiv` to `ℝ`. -/ def measurable_equiv.ereal_equiv_real : ({⊥, ⊤}ᶜ : set ereal) ≃ᵐ ℝ := ereal.ne_bot_top_homeomorph_real.to_measurable_equiv lemma ereal.measurable_of_measurable_real {f : ereal → α} (h : measurable (λ p : ℝ, f p)) : measurable f := measurable_of_measurable_on_compl_finite {⊥, ⊤} (by simp) (measurable_equiv.ereal_equiv_real.symm.measurable_comp_iff.1 h) @[measurability] lemma measurable_ereal_to_real : measurable ereal.to_real := ereal.measurable_of_measurable_real (by simpa using measurable_id) @[measurability] lemma measurable.ereal_to_real {f : α → ereal} (hf : measurable f) : measurable (λ x, (f x).to_real) := measurable_ereal_to_real.comp hf @[measurability] lemma ae_measurable.ereal_to_real {f : α → ereal} {μ : measure α} (hf : ae_measurable f μ) : ae_measurable (λ x, (f x).to_real) μ := measurable_ereal_to_real.comp_ae_measurable hf @[measurability] lemma measurable_coe_ennreal_ereal : measurable (coe : ℝ≥0∞ → ereal) := continuous_coe_ennreal_ereal.measurable @[measurability] lemma measurable.coe_ereal_ennreal {f : α → ℝ≥0∞} (hf : measurable f) : measurable (λ x, (f x : ereal)) := measurable_coe_ennreal_ereal.comp hf @[measurability] lemma ae_measurable.coe_ereal_ennreal {f : α → ℝ≥0∞} {μ : measure α} (hf : ae_measurable f μ) : ae_measurable (λ x, (f x : ereal)) μ := measurable_coe_ennreal_ereal.comp_ae_measurable hf section normed_add_comm_group variables [normed_add_comm_group α] [opens_measurable_space α] [measurable_space β] @[measurability] lemma measurable_norm : measurable (norm : α → ℝ) := continuous_norm.measurable @[measurability] lemma measurable.norm {f : β → α} (hf : measurable f) : measurable (λ a, norm (f a)) := measurable_norm.comp hf @[measurability] lemma ae_measurable.norm {f : β → α} {μ : measure β} (hf : ae_measurable f μ) : ae_measurable (λ a, norm (f a)) μ := measurable_norm.comp_ae_measurable hf @[measurability] lemma measurable_nnnorm : measurable (nnnorm : α → ℝ≥0) := continuous_nnnorm.measurable @[measurability] lemma measurable.nnnorm {f : β → α} (hf : measurable f) : measurable (λ a, ‖f a‖₊) := measurable_nnnorm.comp hf @[measurability] lemma ae_measurable.nnnorm {f : β → α} {μ : measure β} (hf : ae_measurable f μ) : ae_measurable (λ a, ‖f a‖₊) μ := measurable_nnnorm.comp_ae_measurable hf @[measurability] lemma measurable_ennnorm : measurable (λ x : α, (‖x‖₊ : ℝ≥0∞)) := measurable_nnnorm.coe_nnreal_ennreal @[measurability] lemma measurable.ennnorm {f : β → α} (hf : measurable f) : measurable (λ a, (‖f a‖₊ : ℝ≥0∞)) := hf.nnnorm.coe_nnreal_ennreal @[measurability] lemma ae_measurable.ennnorm {f : β → α} {μ : measure β} (hf : ae_measurable f μ) : ae_measurable (λ a, (‖f a‖₊ : ℝ≥0∞)) μ := measurable_ennnorm.comp_ae_measurable hf end normed_add_comm_group section limits variables [topological_space β] [pseudo_metrizable_space β] [measurable_space β] [borel_space β] open metric /-- A limit (over a general filter) of measurable `ℝ≥0∞` valued functions is measurable. -/ lemma measurable_of_tendsto_ennreal' {ι} {f : ι → α → ℝ≥0∞} {g : α → ℝ≥0∞} (u : filter ι) [ne_bot u] [is_countably_generated u] (hf : ∀ i, measurable (f i)) (lim : tendsto f u (𝓝 g)) : measurable g := begin rcases u.exists_seq_tendsto with ⟨x, hx⟩, rw [tendsto_pi_nhds] at lim, have : (λ y, liminf (λ n, (f (x n) y : ℝ≥0∞)) at_top) = g := by { ext1 y, exact ((lim y).comp hx).liminf_eq, }, rw ← this, show measurable (λ y, liminf (λ n, (f (x n) y : ℝ≥0∞)) at_top), exact measurable_liminf (λ n, hf (x n)), end /-- A sequential limit of measurable `ℝ≥0∞` valued functions is measurable. -/ lemma measurable_of_tendsto_ennreal {f : ℕ → α → ℝ≥0∞} {g : α → ℝ≥0∞} (hf : ∀ i, measurable (f i)) (lim : tendsto f at_top (𝓝 g)) : measurable g := measurable_of_tendsto_ennreal' at_top hf lim /-- A limit (over a general filter) of measurable `ℝ≥0` valued functions is measurable. -/ lemma measurable_of_tendsto_nnreal' {ι} {f : ι → α → ℝ≥0} {g : α → ℝ≥0} (u : filter ι) [ne_bot u] [is_countably_generated u] (hf : ∀ i, measurable (f i)) (lim : tendsto f u (𝓝 g)) : measurable g := begin simp_rw [← measurable_coe_nnreal_ennreal_iff] at hf ⊢, refine measurable_of_tendsto_ennreal' u hf _, rw tendsto_pi_nhds at lim ⊢, exact λ x, (ennreal.continuous_coe.tendsto (g x)).comp (lim x), end /-- A sequential limit of measurable `ℝ≥0` valued functions is measurable. -/ lemma measurable_of_tendsto_nnreal {f : ℕ → α → ℝ≥0} {g : α → ℝ≥0} (hf : ∀ i, measurable (f i)) (lim : tendsto f at_top (𝓝 g)) : measurable g := measurable_of_tendsto_nnreal' at_top hf lim /-- A limit (over a general filter) of measurable functions valued in a (pseudo) metrizable space is measurable. -/ lemma measurable_of_tendsto_metrizable' {ι} {f : ι → α → β} {g : α → β} (u : filter ι) [ne_bot u] [is_countably_generated u] (hf : ∀ i, measurable (f i)) (lim : tendsto f u (𝓝 g)) : measurable g := begin letI : pseudo_metric_space β := pseudo_metrizable_space_pseudo_metric β, apply measurable_of_is_closed', intros s h1s h2s h3s, have : measurable (λ x, inf_nndist (g x) s), { suffices : tendsto (λ i x, inf_nndist (f i x) s) u (𝓝 (λ x, inf_nndist (g x) s)), from measurable_of_tendsto_nnreal' u (λ i, (hf i).inf_nndist) this, rw [tendsto_pi_nhds] at lim ⊢, intro x, exact ((continuous_inf_nndist_pt s).tendsto (g x)).comp (lim x) }, have h4s : g ⁻¹' s = (λ x, inf_nndist (g x) s) ⁻¹' {0}, { ext x, simp [h1s, ← h1s.mem_iff_inf_dist_zero h2s, ← nnreal.coe_eq_zero] }, rw [h4s], exact this (measurable_set_singleton 0), end /-- A sequential limit of measurable functions valued in a (pseudo) metrizable space is measurable. -/ lemma measurable_of_tendsto_metrizable {f : ℕ → α → β} {g : α → β} (hf : ∀ i, measurable (f i)) (lim : tendsto f at_top (𝓝 g)) : measurable g := measurable_of_tendsto_metrizable' at_top hf lim lemma ae_measurable_of_tendsto_metrizable_ae {ι} {μ : measure α} {f : ι → α → β} {g : α → β} (u : filter ι) [hu : ne_bot u] [is_countably_generated u] (hf : ∀ n, ae_measurable (f n) μ) (h_tendsto : ∀ᵐ x ∂μ, tendsto (λ n, f n x) u (𝓝 (g x))) : ae_measurable g μ := begin rcases u.exists_seq_tendsto with ⟨v, hv⟩, have h'f : ∀ n, ae_measurable (f (v n)) μ := λ n, hf (v n), set p : α → (ℕ → β) → Prop := λ x f', tendsto (λ n, f' n) at_top (𝓝 (g x)), have hp : ∀ᵐ x ∂μ, p x (λ n, f (v n) x), by filter_upwards [h_tendsto] with x hx using hx.comp hv, set ae_seq_lim := λ x, ite (x ∈ ae_seq_set h'f p) (g x) (⟨f (v 0) x⟩ : nonempty β).some with hs, refine ⟨ae_seq_lim, measurable_of_tendsto_metrizable' at_top (ae_seq.measurable h'f p) (tendsto_pi_nhds.mpr (λ x, _)), _⟩, { simp_rw [ae_seq, ae_seq_lim], split_ifs with hx, { simp_rw ae_seq.mk_eq_fun_of_mem_ae_seq_set h'f hx, exact @ae_seq.fun_prop_of_mem_ae_seq_set _ α β _ _ _ _ _ h'f x hx, }, { exact tendsto_const_nhds } }, { exact (ite_ae_eq_of_measure_compl_zero g (λ x, (⟨f (v 0) x⟩ : nonempty β).some) (ae_seq_set h'f p) (ae_seq.measure_compl_ae_seq_set_eq_zero h'f hp)).symm }, end lemma ae_measurable_of_tendsto_metrizable_ae' {μ : measure α} {f : ℕ → α → β} {g : α → β} (hf : ∀ n, ae_measurable (f n) μ) (h_ae_tendsto : ∀ᵐ x ∂μ, tendsto (λ n, f n x) at_top (𝓝 (g x))) : ae_measurable g μ := ae_measurable_of_tendsto_metrizable_ae at_top hf h_ae_tendsto lemma ae_measurable_of_unif_approx {β} [measurable_space β] [pseudo_metric_space β] [borel_space β] {μ : measure α} {g : α → β} (hf : ∀ ε > (0 : ℝ), ∃ (f : α → β), ae_measurable f μ ∧ ∀ᵐ x ∂μ, dist (f x) (g x) ≤ ε) : ae_measurable g μ := begin obtain ⟨u, u_anti, u_pos, u_lim⟩ : ∃ (u : ℕ → ℝ), strict_anti u ∧ (∀ (n : ℕ), 0 < u n) ∧ tendsto u at_top (𝓝 0) := exists_seq_strict_anti_tendsto (0 : ℝ), choose f Hf using λ (n : ℕ), hf (u n) (u_pos n), have : ∀ᵐ x ∂μ, tendsto (λ n, f n x) at_top (𝓝 (g x)), { have : ∀ᵐ x ∂ μ, ∀ n, dist (f n x) (g x) ≤ u n := ae_all_iff.2 (λ n, (Hf n).2), filter_upwards [this], assume x hx, rw tendsto_iff_dist_tendsto_zero, exact squeeze_zero (λ n, dist_nonneg) hx u_lim }, exact ae_measurable_of_tendsto_metrizable_ae' (λ n, (Hf n).1) this, end lemma measurable_of_tendsto_metrizable_ae {μ : measure α} [μ.is_complete] {f : ℕ → α → β} {g : α → β} (hf : ∀ n, measurable (f n)) (h_ae_tendsto : ∀ᵐ x ∂μ, tendsto (λ n, f n x) at_top (𝓝 (g x))) : measurable g := ae_measurable_iff_measurable.mp (ae_measurable_of_tendsto_metrizable_ae' (λ i, (hf i).ae_measurable) h_ae_tendsto) lemma measurable_limit_of_tendsto_metrizable_ae {ι} [countable ι] [nonempty ι] {μ : measure α} {f : ι → α → β} {L : filter ι} [L.is_countably_generated] (hf : ∀ n, ae_measurable (f n) μ) (h_ae_tendsto : ∀ᵐ x ∂μ, ∃ l : β, tendsto (λ n, f n x) L (𝓝 l)) : ∃ (f_lim : α → β) (hf_lim_meas : measurable f_lim), ∀ᵐ x ∂μ, tendsto (λ n, f n x) L (𝓝 (f_lim x)) := begin inhabit ι, unfreezingI { rcases eq_or_ne L ⊥ with rfl | hL }, { exact ⟨(hf default).mk _, (hf default).measurable_mk, eventually_of_forall $ λ x, tendsto_bot⟩ }, haveI : ne_bot L := ⟨hL⟩, let p : α → (ι → β) → Prop := λ x f', ∃ l : β, tendsto (λ n, f' n) L (𝓝 l), have hp_mem : ∀ x ∈ ae_seq_set hf p, p x (λ n, f n x), from λ x hx, ae_seq.fun_prop_of_mem_ae_seq_set hf hx, have h_ae_eq : ∀ᵐ x ∂μ, ∀ n, ae_seq hf p n x = f n x, from ae_seq.ae_seq_eq_fun_ae hf h_ae_tendsto, let f_lim : α → β := λ x, dite (x ∈ ae_seq_set hf p) (λ h, (hp_mem x h).some) (λ h, (⟨f default x⟩ : nonempty β).some), have hf_lim : ∀ x, tendsto (λ n, ae_seq hf p n x) L (𝓝 (f_lim x)), { intros x, simp only [f_lim, ae_seq], split_ifs, { refine (hp_mem x h).some_spec.congr (λ n, _), exact (ae_seq.mk_eq_fun_of_mem_ae_seq_set hf h n).symm }, { exact tendsto_const_nhds, }, }, have h_ae_tendsto_f_lim : ∀ᵐ x ∂μ, tendsto (λ n, f n x) L (𝓝 (f_lim x)), from h_ae_eq.mono (λ x hx, (hf_lim x).congr hx), have h_f_lim_meas : measurable f_lim, from measurable_of_tendsto_metrizable' L (ae_seq.measurable hf p) (tendsto_pi_nhds.mpr (λ x, hf_lim x)), exact ⟨f_lim, h_f_lim_meas, h_ae_tendsto_f_lim⟩, end end limits namespace continuous_linear_map variables {𝕜 : Type*} [normed_field 𝕜] variables {E : Type*} [normed_add_comm_group E] [normed_space 𝕜 E] [measurable_space E] [opens_measurable_space E] {F : Type*} [normed_add_comm_group F] [normed_space 𝕜 F] [measurable_space F] [borel_space F] @[measurability] protected lemma measurable (L : E →L[𝕜] F) : measurable L := L.continuous.measurable lemma measurable_comp (L : E →L[𝕜] F) {φ : α → E} (φ_meas : measurable φ) : measurable (λ (a : α), L (φ a)) := L.measurable.comp φ_meas end continuous_linear_map namespace continuous_linear_map variables {𝕜 : Type*} [nontrivially_normed_field 𝕜] variables {E : Type*} [normed_add_comm_group E] [normed_space 𝕜 E] {F : Type*} [normed_add_comm_group F] [normed_space 𝕜 F] instance : measurable_space (E →L[𝕜] F) := borel _ instance : borel_space (E →L[𝕜] F) := ⟨rfl⟩ @[measurability] lemma measurable_apply [measurable_space F] [borel_space F] (x : E) : measurable (λ f : E →L[𝕜] F, f x) := (apply 𝕜 F x).continuous.measurable @[measurability] lemma measurable_apply' [measurable_space E] [opens_measurable_space E] [measurable_space F] [borel_space F] : measurable (λ (x : E) (f : E →L[𝕜] F), f x) := measurable_pi_lambda _ $ λ f, f.measurable @[measurability] lemma measurable_coe [measurable_space F] [borel_space F] : measurable (λ (f : E →L[𝕜] F) (x : E), f x) := measurable_pi_lambda _ measurable_apply end continuous_linear_map section continuous_linear_map_nontrivially_normed_field variables {𝕜 : Type*} [nontrivially_normed_field 𝕜] variables {E : Type*} [normed_add_comm_group E] [normed_space 𝕜 E] [measurable_space E] [borel_space E] {F : Type*} [normed_add_comm_group F] [normed_space 𝕜 F] @[measurability] lemma measurable.apply_continuous_linear_map {φ : α → F →L[𝕜] E} (hφ : measurable φ) (v : F) : measurable (λ a, φ a v) := (continuous_linear_map.apply 𝕜 E v).measurable.comp hφ @[measurability] lemma ae_measurable.apply_continuous_linear_map {φ : α → F →L[𝕜] E} {μ : measure α} (hφ : ae_measurable φ μ) (v : F) : ae_measurable (λ a, φ a v) μ := (continuous_linear_map.apply 𝕜 E v).measurable.comp_ae_measurable hφ end continuous_linear_map_nontrivially_normed_field section normed_space variables {𝕜 : Type*} [nontrivially_normed_field 𝕜] [complete_space 𝕜] [measurable_space 𝕜] variables [borel_space 𝕜] {E : Type*} [normed_add_comm_group E] [normed_space 𝕜 E] [measurable_space E] [borel_space E] lemma measurable_smul_const {f : α → 𝕜} {c : E} (hc : c ≠ 0) : measurable (λ x, f x • c) ↔ measurable f := (closed_embedding_smul_left hc).measurable_embedding.measurable_comp_iff lemma ae_measurable_smul_const {f : α → 𝕜} {μ : measure α} {c : E} (hc : c ≠ 0) : ae_measurable (λ x, f x • c) μ ↔ ae_measurable f μ := (closed_embedding_smul_left hc).measurable_embedding.ae_measurable_comp_iff end normed_space
7995e26f5a3795b9ea8776a7bc9ce5408ea9bcf9
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/topology/algebra/uniform_field.lean
2125b4d4e90597d5f2f1a7aff032c0695972bb39
[ "Apache-2.0" ]
permissive
AntoineChambert-Loir/mathlib
64aabb896129885f12296a799818061bc90da1ff
07be904260ab6e36a5769680b6012f03a4727134
refs/heads/master
1,693,187,631,771
1,636,719,886,000
1,636,719,886,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
6,593
lean
/- Copyright (c) 2019 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot -/ import topology.algebra.uniform_ring import topology.algebra.field /-! # Completion of topological fields The goal of this file is to prove the main part of Proposition 7 of Bourbaki GT III 6.8 : The completion `hat K` of a Hausdorff topological field is a field if the image under the mapping `x ↦ x⁻¹` of every Cauchy filter (with respect to the additive uniform structure) which does not have a cluster point at `0` is a Cauchy filter (with respect to the additive uniform structure). Bourbaki does not give any detail here, he refers to the general discussion of extending functions defined on a dense subset with values in a complete Hausdorff space. In particular the subtlety about clustering at zero is totally left to readers. Note that the separated completion of a non-separated topological field is the zero ring, hence the separation assumption is needed. Indeed the kernel of the completion map is the closure of zero which is an ideal. Hence it's either zero (and the field is separated) or the full field, which implies one is sent to zero and the completion ring is trivial. The main definition is `completable_top_field` which packages the assumptions as a Prop-valued type class and the main results are the instances `field_completion` and `topological_division_ring_completion`. -/ noncomputable theory open_locale classical uniformity topological_space open set uniform_space uniform_space.completion filter variables (K : Type*) [field K] [uniform_space K] local notation `hat` := completion @[priority 100] instance [separated_space K] : nontrivial (hat K) := ⟨⟨0, 1, λ h, zero_ne_one $ (uniform_embedding_coe K).inj h⟩⟩ /-- A topological field is completable if it is separated and the image under the mapping x ↦ x⁻¹ of every Cauchy filter (with respect to the additive uniform structure) which does not have a cluster point at 0 is a Cauchy filter (with respect to the additive uniform structure). This ensures the completion is a field. -/ class completable_top_field extends separated_space K : Prop := (nice : ∀ F : filter K, cauchy F → 𝓝 0 ⊓ F = ⊥ → cauchy (map (λ x, x⁻¹) F)) variables {K} /-- extension of inversion to the completion of a field. -/ def hat_inv : hat K → hat K := dense_inducing_coe.extend (λ x : K, (coe x⁻¹ : hat K)) lemma continuous_hat_inv [completable_top_field K] {x : hat K} (h : x ≠ 0) : continuous_at hat_inv x := begin haveI : regular_space (hat K) := completion.regular_space K, refine dense_inducing_coe.continuous_at_extend _, apply mem_of_superset (compl_singleton_mem_nhds h), intros y y_ne, rw mem_compl_singleton_iff at y_ne, apply complete_space.complete, rw ← filter.map_map, apply cauchy.map _ (completion.uniform_continuous_coe K), apply completable_top_field.nice, { haveI := dense_inducing_coe.comap_nhds_ne_bot y, apply cauchy_nhds.comap, { rw completion.comap_coe_eq_uniformity, exact le_rfl } }, { have eq_bot : 𝓝 (0 : hat K) ⊓ 𝓝 y = ⊥, { by_contradiction h, exact y_ne (eq_of_nhds_ne_bot $ ne_bot_iff.mpr h).symm }, erw [dense_inducing_coe.nhds_eq_comap (0 : K), ← comap_inf, eq_bot], exact comap_bot }, end /- The value of `hat_inv` at zero is not really specified, although it's probably zero. Here we explicitly enforce the `inv_zero` axiom. -/ instance completion.has_inv : has_inv (hat K) := ⟨λ x, if x = 0 then 0 else hat_inv x⟩ variables [topological_division_ring K] lemma hat_inv_extends {x : K} (h : x ≠ 0) : hat_inv (x : hat K) = coe (x⁻¹ : K) := dense_inducing_coe.extend_eq_at ((continuous_coe K).continuous_at.comp (topological_division_ring.continuous_inv x h)) variables [completable_top_field K] @[norm_cast] lemma coe_inv (x : K) : (x : hat K)⁻¹ = ((x⁻¹ : K) : hat K) := begin by_cases h : x = 0, { rw [h, inv_zero], dsimp [has_inv.inv], norm_cast, simp [if_pos] }, { conv_lhs { dsimp [has_inv.inv] }, norm_cast, rw if_neg, { exact hat_inv_extends h }, { exact λ H, h (dense_embedding_coe.inj H) } } end variables [uniform_add_group K] [topological_ring K] lemma mul_hat_inv_cancel {x : hat K} (x_ne : x ≠ 0) : x*hat_inv x = 1 := begin haveI : t1_space (hat K) := t2_space.t1_space, let f := λ x : hat K, x*hat_inv x, let c := (coe : K → hat K), change f x = 1, have cont : continuous_at f x, { letI : topological_space (hat K × hat K) := prod.topological_space, have : continuous_at (λ y : hat K, ((y, hat_inv y) : hat K × hat K)) x, from continuous_id.continuous_at.prod (continuous_hat_inv x_ne), exact (_root_.continuous_mul.continuous_at.comp this : _) }, have clo : x ∈ closure (c '' {0}ᶜ), { have := dense_inducing_coe.dense x, rw [← image_univ, show (univ : set K) = {0} ∪ {0}ᶜ, from (union_compl_self _).symm, image_union] at this, apply mem_closure_of_mem_closure_union this, rw image_singleton, exact compl_singleton_mem_nhds x_ne }, have fxclo : f x ∈ closure (f '' (c '' {0}ᶜ)) := mem_closure_image cont clo, have : f '' (c '' {0}ᶜ) ⊆ {1}, { rw image_image, rintros _ ⟨z, z_ne, rfl⟩, rw mem_singleton_iff, rw mem_compl_singleton_iff at z_ne, dsimp [c, f], rw hat_inv_extends z_ne, norm_cast, rw mul_inv_cancel z_ne, norm_cast }, replace fxclo := closure_mono this fxclo, rwa [closure_singleton, mem_singleton_iff] at fxclo end instance field_completion : field (hat K) := { exists_pair_ne := ⟨0, 1, λ h, zero_ne_one ((uniform_embedding_coe K).inj h)⟩, mul_inv_cancel := λ x x_ne, by { dsimp [has_inv.inv], simp [if_neg x_ne, mul_hat_inv_cancel x_ne], }, inv_zero := show ((0 : K) : hat K)⁻¹ = ((0 : K) : hat K), by rw [coe_inv, inv_zero], ..completion.has_inv, ..(by apply_instance : comm_ring (hat K)) } instance topological_division_ring_completion : topological_division_ring (hat K) := { continuous_inv := begin intros x x_ne, have : {y | hat_inv y = y⁻¹ } ∈ 𝓝 x, { have : {(0 : hat K)}ᶜ ⊆ {y : hat K | hat_inv y = y⁻¹ }, { intros y y_ne, rw mem_compl_singleton_iff at y_ne, dsimp [has_inv.inv], rw if_neg y_ne }, exact mem_of_superset (compl_singleton_mem_nhds x_ne) this }, exact continuous_at.congr (continuous_hat_inv x_ne) this end, ..completion.top_ring_compl }
08045ac821b07ce841a175c86cdcdab96403e8b5
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/751.lean
bc01a67e3903f2a12928be25c5e89b006b03833b
[ "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
95
lean
#exit inductive foo (A : Type) := | intro : foo A → foo A with bar : Type := | intro : bar A
89ddbaae94f2c75ffb4ba36f09b9d634a06ffdf9
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/tests/lean/run/prod_notation.lean
9c3070961d18868571819867ea7b26f7f34427f5
[ "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
128
lean
open prod definition tst1 : num × Prop × num × Prop := (1, true, 2, false) definition tst2 : num × num × num := (1, 2, 3)
c0f543c3cc344811229db97f4bf360b9a4f45bc7
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/ring_theory/mv_polynomial/basic.lean
d029ddd1ebe907093c9b5e2db2de521588440295
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
4,228
lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import algebra.char_p.basic import linear_algebra.finsupp_vector_space /-! # Multivariate polynomials over commutative rings This file contains basic facts about multivariate polynomials over commutative rings, for example that the monomials form a basis. ## Main definitions * `restrict_total_degree σ R m`: the subspace of multivariate polynomials indexed by `σ` over the commutative ring `R` of total degree at most `m`. * `restrict_degree σ R m`: the subspace of multivariate polynomials indexed by `σ` over the commutative ring `R` such that the degree in each individual variable is at most `m`. ## Main statements * The multivariate polynomial ring over a commutative ring of positive characteristic has positive characteristic. * `basis_monomials`: shows that the monomials form a basis of the vector space of multivariate polynomials. ## TODO Generalise to noncommutative (semi)rings -/ noncomputable theory open_locale classical open set linear_map submodule open_locale big_operators universes u v variables (σ : Type u) (R : Type v) [comm_ring R] (p m : ℕ) namespace mv_polynomial section char_p instance [char_p R p] : char_p (mv_polynomial σ R) p := { cast_eq_zero_iff := λ n, by rw [← C_eq_coe_nat, ← C_0, C_inj, char_p.cast_eq_zero_iff R p] } end char_p section homomorphism lemma map_range_eq_map {R S : Type*} [comm_ring R] [comm_ring S] (p : mv_polynomial σ R) (f : R →+* S) : finsupp.map_range f f.map_zero p = map f p := begin -- `finsupp.map_range_finset_sum` expects `f : R →+ S` change finsupp.map_range (f : R →+ S) (f : R →+ S).map_zero p = map f p, rw [p.as_sum, finsupp.map_range_finset_sum, (map f).map_sum], refine finset.sum_congr rfl (assume n _, _), rw [map_monomial, ← single_eq_monomial, finsupp.map_range_single, single_eq_monomial, f.coe_add_monoid_hom], end end homomorphism section degree /-- The submodule of polynomials of total degree less than or equal to `m`.-/ def restrict_total_degree : submodule R (mv_polynomial σ R) := finsupp.supported _ _ {n | n.sum (λn e, e) ≤ m } /-- The submodule of polynomials such that the degree with respect to each individual variable is less than or equal to `m`.-/ def restrict_degree (m : ℕ) : submodule R (mv_polynomial σ R) := finsupp.supported _ _ {n | ∀i, n i ≤ m } variable {R} lemma mem_restrict_total_degree (p : mv_polynomial σ R) : p ∈ restrict_total_degree σ R m ↔ p.total_degree ≤ m := begin rw [total_degree, finset.sup_le_iff], refl end lemma mem_restrict_degree (p : mv_polynomial σ R) (n : ℕ) : p ∈ restrict_degree σ R n ↔ (∀s ∈ p.support, ∀i, (s : σ →₀ ℕ) i ≤ n) := begin rw [restrict_degree, finsupp.mem_supported], refl end lemma mem_restrict_degree_iff_sup (p : mv_polynomial σ R) (n : ℕ) : p ∈ restrict_degree σ R n ↔ ∀i, p.degrees.count i ≤ n := begin simp only [mem_restrict_degree, degrees, multiset.count_finset_sup, finsupp.count_to_multiset, finset.sup_le_iff], exact ⟨assume h n s hs, h s hs n, assume h s hs n, h n s hs⟩ end variables (σ R) /-- The monomials form a basis on `mv_polynomial σ R`. -/ def basis_monomials : basis (σ →₀ ℕ) R (mv_polynomial σ R) := finsupp.basis_single_one @[simp] lemma coe_basis_monomials : (basis_monomials σ R : (σ →₀ ℕ) → mv_polynomial σ R) = λ s, monomial s 1 := rfl lemma linear_independent_X : linear_independent R (X : σ → mv_polynomial σ R) := (basis_monomials σ R).linear_independent.comp (λ s : σ, finsupp.single s 1) (finsupp.single_left_injective one_ne_zero) end degree end mv_polynomial /- this is here to avoid import cycle issues -/ namespace polynomial /-- The monomials form a basis on `polynomial R`. -/ noncomputable def basis_monomials : basis ℕ R (polynomial R) := finsupp.basis_single_one.map (to_finsupp_iso_alg R).to_linear_equiv.symm @[simp] lemma coe_basis_monomials : (basis_monomials R : ℕ → polynomial R) = λ s, monomial s 1 := _root_.funext $ λ n, to_finsupp_iso_symm_single end polynomial
93ce453afc261bd2cae92418a57b0688a627e1c6
42c01158c2730cc6ac3e058c1339c18cb90366e2
/M1F/2017-18/Example_Sheet_01/Questions_02_to_4/M1F_sheet01_solutions02_to_04.lean
c56bf95dafa8e089d3adf67a950513c82adbc288
[]
no_license
ChrisHughes24/xena
c80d94355d0c2ae8deddda9d01e6d31bc21c30ae
337a0d7c9f0e255e08d6d0a383e303c080c6ec0c
refs/heads/master
1,631,059,898,392
1,511,200,551,000
1,511,200,551,000
111,468,589
1
0
null
null
null
null
UTF-8
Lean
false
false
3,734
lean
/- M1F 2017-18 Sheet 1 Question 2 to 4 solutions. Author : Kevin Buzzard This file should work with any version of lean -- whether you installed it yourself or are running the version on https://leanprover.github.io/live/latest/ -/ -- We probably need the "law of the excluded middle" for this question -- every -- proposition is either true or false! Don't even ask me to explain what the -- other options are, but Lean does not come with this axiom by default (blame -- the computer scientists) and mathematicians have to add it themselves. -- It's easy to add though. "em" for excluded middle. axiom em (X : Prop) : X ∨ ¬ X variables P Q R S : Prop -- A "Prop" is a proposition, that is, a true/false statement. -- Sheet 1 Q2 is true. theorem m1f_sheet01_q02_is_T (HQP : Q → P) (HnQnR : ¬ Q → ¬ R) : R → P := begin intro HR, -- hypothesis R cases em Q with HQ HnQ, -- Q is either true or false. -- Q is true in this branch. exact HQP HQ, -- HPQ HQ is a proof of P. -- Q is false in this branch -- HnQ is the hypothesis "not Q" -- HnQnR is "not Q implies not R" -- so HnQnR HnQ is a proof of "not R" -- i.e. a proof of "R implies false" -- but HR is a proof of R -- and that's enough for a contradiction. have HnR : ¬ R, exact HnQnR HnQ, contradiction, end -- Sheet 1 Q3. Prove one result and delete the other. -- theorem m1f_sheet01_q03_is_T (HP : P) (HnQ : ¬ Q) (HnR : ¬ R) (HS : S) : (R → S) → (P → Q) := theorem m1f_sheet01_q03_is_F (HP : P) (HnQ : ¬ Q) (HnR : ¬ R) (HS : S) : ¬ ((R → S) → (P → Q)) := begin intro H, have HRS : R → S, intro HR, contradiction, have HPQ : P → Q, exact H HRS, have HQ : Q, exact HPQ HP, -- now we have Q and not Q contradiction, end -- Sheet 1 Q4. -- Let me first make a tool which is capable of proving all three hypotheses -- when we have the right assumptions. meta def prove_hyps : tactic unit := `[ { -- This tactic will try to prove -- (P → Q ∨ R) ∧ (¬ Q → R ∨ ¬ P) ∧ (Q ∧ R → ¬ P) apply and.intro, -- next goal is P → Q ∨ R intro, -- now P is a hypothesis and Q ∨ R is the goal. -- next line works if any of ¬ P or Q or R are true. contradiction <|> {left,assumption} <|> {right,assumption}, apply and.intro, -- same story, intro,contradiction <|> {left,assumption} <|> {right,assumption}, -- next line attempts to prove Q and R -> not P. intro HQR, -- have Q, from HQR.left, have R, from HQR.right, -- now Q and R are assumptions and not P is the goal. assumption <|> contradiction } ] -- I used that tool to figure out what the answer is. -- The answer to Q4 is that all three hypotheses are true if and only if either -- (i) P is false, or -- (ii) P is true, and exactly one of Q and R are true. -- It's possible to write a very long proof of this. -- But in this case I just did a brute force case by case check, -- using basic tactics joined together with glue I learnt about -- in section 5.5 of Theorem Proving In Lean. theorem m1f_sheet01_q04 : (P → (Q ∨ R)) ∧ (¬ Q → (R ∨ ¬ P)) ∧ ((Q ∧ R) → ¬ P) ↔ (¬ P) ∨ (P ∧ Q ∧ ¬ R) ∨ (P ∧ ¬ Q ∧ R) := begin cases em P with HP HnP;cases em Q with HQ HnQ;cases em R with HR HnR;apply iff.intro, repeat {-- we'll do all eight cases automatically. intro hyps, cc, -- this does the case where hyps implies my solution -- now check my solution implies hyps (possibly by contradiction) intro hmypqr, { prove_hyps } <|> { cases hmypqr with h1 h2, contradiction, cases h2 with ha hb, cases ha with h3 h4, cases h4, contradiction, cases hb with h5 h6, cases h6, contradiction } }, end
eb036d278cad3a7e5306d696572be54d0b83afaa
4b4a91d762ac3b6ef8f164899a6a26fc125eddd6
/src/solutions/level_2_group_actions.lean
48f1022205582e5e7e8cdbf088eea92ee05a1de7
[ "Apache-2.0" ]
permissive
ImperialCollegeLondon/group-action-exercises
955ceba8edb7eba7b8916690083829d321909aee
197b1a0e53ec8d84bf3903c9ab5cddf615a44816
refs/heads/master
1,686,020,547,415
1,625,354,242,000
1,625,354,242,000
382,577,731
2
0
null
null
null
null
UTF-8
Lean
false
false
2,783
lean
import group_theory.group_action.basic import tactic import data.setoid.partition variables {G : Type*} [group G] {S : Type} {s t u : S} [mul_action G S] open mul_action theorem mem_orbit_refl (s : S) : s ∈ orbit G s := begin -- we could use `1 : G` but this is already in the library under another name exact mem_orbit_self s, end theorem mem_orbit_symm (h : s ∈ orbit G t) : t ∈ orbit G s := begin rw mem_orbit_iff at *, -- h says ∃ x, x • t = s so let's let `a` be that `x` and -- then replace `s` by `a • t` everywhere (that's the `rfl`) rcases h with ⟨a, rfl⟩, -- By the maths proof, we use a⁻¹ use a⁻¹, -- now the simplifier can solve this equality simp, end theorem mem_orbit_trans (hst : s ∈ orbit G t) (htu : t ∈ orbit G u) : s ∈ orbit G u := begin rw mem_orbit_iff at *, -- we know a • t = s and b • u = t rcases hst with ⟨a, rfl⟩, rcases htu with ⟨b, rfl⟩, -- so we have to solve `∃ x, x • u = a • b • u` use a * b, exact mul_smul a b u, -- I know the axiom name end open set variable (G) theorem orbit_nonempty (s : S) : set.nonempty (orbit G s) := begin rw nonempty_def, -- the orbit is nonempty because it contains s use s, -- and here's the proof that s is in its own orbit exact mem_orbit_refl s, end variable {G} theorem mem_orbit (s : S) : ∃ (t : S), s ∈ orbit G t := begin -- we can use t = s use s, -- and here's the proof that s is in its own orbit exact mem_orbit_refl s, end variable {a : S} theorem boring_lemma (has : a ∈ orbit G s) (hat : a ∈ orbit G t) : s ∈ orbit G t := begin -- this is a little logic puzzle. Note that my proof is backwards refine mem_orbit_trans _ hat, exact mem_orbit_symm has, end theorem orbit_subset_of_mem_orbit (hst : s ∈ orbit G t) : orbit G s ⊆ orbit G t := begin rintros u hu, exact mem_orbit_trans hu hst, end theorem orbit_eq_orbit_of_mem_inter (has : a ∈ orbit G s) (hat : a ∈ orbit G t) : orbit G s = orbit G t := begin -- ⊆ is antisymmetric apply subset.antisymm, { -- both cases follow from the boring lemma and `orbit_subset_of_mem_orbit` apply orbit_subset_of_mem_orbit, exact boring_lemma has hat, }, { apply orbit_subset_of_mem_orbit, exact boring_lemma hat has, } end variable {g : G} open setoid -- this is harder and can probably be golfed. example : is_partition {𝒪 : set S | ∃ s, orbit G s = 𝒪} := begin refine ⟨_, _⟩, { rintro ⟨s, hs⟩, exact not_nonempty_iff_eq_empty.mpr hs (orbit_nonempty G s), }, intro s, refine exists_unique_of_exists_of_unique _ _, { use orbit G s, simp }, { rintro A B ⟨⟨t, rfl⟩, hst, -⟩ ⟨⟨u, rfl⟩, hsu, -⟩, exact orbit_eq_orbit_of_mem_inter hst hsu, }, end
a468d251c40fb6997fc6c30ba1865d7f34d49df2
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/seq/seq.lean
11377190ea5e7ddfc06f5ae62ee39a6aa3b6afd7
[]
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
19,881
lean
/- Copyright (c) 2017 Mario Carneiro. 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.list.basic import Mathlib.Lean3Lib.data.stream import Mathlib.Lean3Lib.data.lazy_list import Mathlib.data.seq.computation import Mathlib.PostPort universes u u_1 v w namespace Mathlib /- coinductive seq (α : Type u) : Type u | nil : seq α | cons : α → seq α → seq α -/ /-- A stream `s : option α` is a sequence if `s.nth n = none` implies `s.nth (n + 1) = none`. -/ def stream.is_seq {α : Type u} (s : stream (Option α)) := ∀ {n : ℕ}, s n = none → s (n + 1) = none /-- `seq α` is the type of possibly infinite lists (referred here as sequences). It is encoded as an infinite stream of options such that if `f n = none`, then `f m = none` for all `m ≥ n`. -/ def seq (α : Type u) := Subtype fun (f : stream (Option α)) => stream.is_seq f /-- `seq1 α` is the type of nonempty sequences. -/ def seq1 (α : Type u_1) := α × seq α namespace seq /-- The empty sequence -/ def nil {α : Type u} : seq α := { val := stream.const none, property := sorry } protected instance inhabited {α : Type u} : Inhabited (seq α) := { default := nil } /-- Prepend an element to a sequence -/ def cons {α : Type u} (a : α) : seq α → seq α := sorry /-- Get the nth element of a sequence (if it exists) -/ def nth {α : Type u} : seq α → ℕ → Option α := subtype.val /-- A sequence has terminated at position `n` if the value at position `n` equals `none`. -/ def terminated_at {α : Type u} (s : seq α) (n : ℕ) := nth s n = none /-- It is decidable whether a sequence terminates at a given position. -/ protected instance terminated_at_decidable {α : Type u} (s : seq α) (n : ℕ) : Decidable (terminated_at s n) := decidable_of_iff' ↥(option.is_none (nth s n)) sorry /-- A sequence terminates if there is some position `n` at which it has terminated. -/ def terminates {α : Type u} (s : seq α) := ∃ (n : ℕ), terminated_at s n /-- Functorial action of the functor `option (α × _)` -/ @[simp] def omap {α : Type u} {β : Type v} {γ : Type w} (f : β → γ) : Option (α × β) → Option (α × γ) := sorry /-- Get the first element of a sequence -/ def head {α : Type u} (s : seq α) : Option α := nth s 0 /-- Get the tail of a sequence (or `nil` if the sequence is `nil`) -/ def tail {α : Type u} : seq α → seq α := sorry protected def mem {α : Type u} (a : α) (s : seq α) := some a ∈ subtype.val s protected instance has_mem {α : Type u} : has_mem α (seq α) := has_mem.mk seq.mem theorem le_stable {α : Type u} (s : seq α) {m : ℕ} {n : ℕ} (h : m ≤ n) : nth s m = none → nth s n = none := sorry /-- If a sequence terminated at position `n`, it also terminated at `m ≥ n `. -/ theorem terminated_stable {α : Type u} (s : seq α) {m : ℕ} {n : ℕ} (m_le_n : m ≤ n) (terminated_at_m : terminated_at s m) : terminated_at s n := le_stable s m_le_n terminated_at_m /-- If `s.nth n = some aₙ` for some value `aₙ`, then there is also some value `aₘ` such that `s.nth = some aₘ` for `m ≤ n`. -/ theorem ge_stable {α : Type u} (s : seq α) {aₙ : α} {n : ℕ} {m : ℕ} (m_le_n : m ≤ n) (s_nth_eq_some : nth s n = some aₙ) : ∃ (aₘ : α), nth s m = some aₘ := sorry theorem not_mem_nil {α : Type u} (a : α) : ¬a ∈ nil := sorry theorem mem_cons {α : Type u} (a : α) (s : seq α) : a ∈ cons a s := subtype.cases_on s fun (s_val : stream (Option α)) (s_property : stream.is_seq s_val) => idRhs (some a ∈ some a :: s_val) (stream.mem_cons (some a) s_val) theorem mem_cons_of_mem {α : Type u} (y : α) {a : α} {s : seq α} : a ∈ s → a ∈ cons y s := sorry theorem eq_or_mem_of_mem_cons {α : Type u} {a : α} {b : α} {s : seq α} : a ∈ cons b s → a = b ∨ a ∈ s := sorry @[simp] theorem mem_cons_iff {α : Type u} {a : α} {b : α} {s : seq α} : a ∈ cons b s ↔ a = b ∨ a ∈ s := sorry /-- Destructor for a sequence, resulting in either `none` (for `nil`) or `some (a, s)` (for `cons a s`). -/ def destruct {α : Type u} (s : seq α) : Option (seq1 α) := (fun (a' : α) => (a', tail s)) <$> nth s 0 theorem destruct_eq_nil {α : Type u} {s : seq α} : destruct s = none → s = nil := sorry theorem destruct_eq_cons {α : Type u} {s : seq α} {a : α} {s' : seq α} : destruct s = some (a, s') → s = cons a s' := sorry @[simp] theorem destruct_nil {α : Type u} : destruct nil = none := rfl @[simp] theorem destruct_cons {α : Type u} (a : α) (s : seq α) : destruct (cons a s) = some (a, s) := sorry theorem head_eq_destruct {α : Type u} (s : seq α) : head s = prod.fst <$> destruct s := sorry @[simp] theorem head_nil {α : Type u} : head nil = none := rfl @[simp] theorem head_cons {α : Type u} (a : α) (s : seq α) : head (cons a s) = some a := eq.mpr (id (Eq._oldrec (Eq.refl (head (cons a s) = some a)) (head_eq_destruct (cons a s)))) (eq.mpr (id (Eq._oldrec (Eq.refl (prod.fst <$> destruct (cons a s) = some a)) (destruct_cons a s))) (Eq.refl (prod.fst <$> some (a, s)))) @[simp] theorem tail_nil {α : Type u} : tail nil = nil := rfl @[simp] theorem tail_cons {α : Type u} (a : α) (s : seq α) : tail (cons a s) = s := sorry def cases_on {α : Type u} {C : seq α → Sort v} (s : seq α) (h1 : C nil) (h2 : (x : α) → (s : seq α) → C (cons x s)) : C s := (fun (_x : Option (seq1 α)) (H : destruct s = _x) => Option.rec (fun (H : destruct s = none) => eq.mpr sorry h1) (fun (v : seq1 α) (H : destruct s = some v) => prod.cases_on v (fun (a : α) (s' : seq α) (H : destruct s = some (a, s')) => eq.mpr sorry (h2 a s')) H) _x H) (destruct s) sorry theorem mem_rec_on {α : Type u} {C : seq α → Prop} {a : α} {s : seq α} (M : a ∈ s) (h1 : ∀ (b : α) (s' : seq α), a = b ∨ C s' → C (cons b s')) : C s := sorry def corec.F {α : Type u} {β : Type v} (f : β → Option (α × β)) : Option β → Option α × Option β := sorry /-- Corecursor for `seq α` as a coinductive type. Iterates `f` to produce new elements of the sequence until `none` is obtained. -/ def corec {α : Type u} {β : Type v} (f : β → Option (α × β)) (b : β) : seq α := { val := stream.corec' sorry (some b), property := sorry } @[simp] theorem corec_eq {α : Type u} {β : Type v} (f : β → Option (α × β)) (b : β) : destruct (corec f b) = omap (corec f) (f b) := sorry /-- Embed a list as a sequence -/ def of_list {α : Type u} (l : List α) : seq α := { val := list.nth l, property := sorry } protected instance coe_list {α : Type u} : has_coe (List α) (seq α) := has_coe.mk of_list @[simp] def bisim_o {α : Type u} (R : seq α → seq α → Prop) : Option (seq1 α) → Option (seq1 α) → Prop := sorry def is_bisimulation {α : Type u} (R : seq α → seq α → Prop) := ∀ {s₁ s₂ : seq α}, R s₁ s₂ → bisim_o R (destruct s₁) (destruct s₂) theorem eq_of_bisim {α : Type u} (R : seq α → seq α → Prop) (bisim : is_bisimulation R) {s₁ : seq α} {s₂ : seq α} (r : R s₁ s₂) : s₁ = s₂ := sorry theorem coinduction {α : Type u} {s₁ : seq α} {s₂ : seq α} : head s₁ = head s₂ → (∀ (β : Type u) (fr : seq α → β), fr s₁ = fr s₂ → fr (tail s₁) = fr (tail s₂)) → s₁ = s₂ := sorry theorem coinduction2 {α : Type u} {β : Type v} (s : seq α) (f : seq α → seq β) (g : seq α → seq β) (H : ∀ (s : seq α), bisim_o (fun (s1 s2 : seq β) => ∃ (s : seq α), s1 = f s ∧ s2 = g s) (destruct (f s)) (destruct (g s))) : f s = g s := sorry /-- Embed an infinite stream as a sequence -/ def of_stream {α : Type u} (s : stream α) : seq α := { val := stream.map some s, property := sorry } protected instance coe_stream {α : Type u} : has_coe (stream α) (seq α) := has_coe.mk of_stream /-- Embed a `lazy_list α` as a sequence. Note that even though this is non-meta, it will produce infinite sequences if used with cyclic `lazy_list`s created by meta constructions. -/ def of_lazy_list {α : Type u} : lazy_list α → seq α := corec fun (l : lazy_list α) => sorry protected instance coe_lazy_list {α : Type u} : has_coe (lazy_list α) (seq α) := has_coe.mk of_lazy_list /-- Translate a sequence into a `lazy_list`. Since `lazy_list` and `list` are isomorphic as non-meta types, this function is necessarily meta. -/ /-- Translate a sequence to a list. This function will run forever if run on an infinite sequence. -/ /-- The sequence of natural numbers some 0, some 1, ... -/ def nats : seq ℕ := ↑stream.nats @[simp] theorem nats_nth (n : ℕ) : nth nats n = some n := rfl /-- Append two sequences. If `s₁` is infinite, then `s₁ ++ s₂ = s₁`, otherwise it puts `s₂` at the location of the `nil` in `s₁`. -/ def append {α : Type u} (s₁ : seq α) (s₂ : seq α) : seq α := corec (fun (_x : seq α × seq α) => sorry) (s₁, s₂) /-- Map a function over a sequence. -/ def map {α : Type u} {β : Type v} (f : α → β) : seq α → seq β := sorry /-- Flatten a sequence of sequences. (It is required that the sequences be nonempty to ensure productivity; in the case of an infinite sequence of `nil`, the first element is never generated.) -/ def join {α : Type u} : seq (seq1 α) → seq α := corec fun (S : seq (seq1 α)) => sorry /-- Remove the first `n` elements from the sequence. -/ @[simp] def drop {α : Type u} (s : seq α) : ℕ → seq α := sorry /-- Take the first `n` elements of the sequence (producing a list) -/ def take {α : Type u} : ℕ → seq α → List α := sorry /-- Split a sequence at `n`, producing a finite initial segment and an infinite tail. -/ def split_at {α : Type u} : ℕ → seq α → List α × seq α := sorry /-- Combine two sequences with a function -/ def zip_with {α : Type u} {β : Type v} {γ : Type w} (f : α → β → γ) : seq α → seq β → seq γ := sorry theorem zip_with_nth_some {α : Type u} {β : Type v} {γ : Type w} {s : seq α} {s' : seq β} {n : ℕ} {a : α} {b : β} (s_nth_eq_some : nth s n = some a) (s_nth_eq_some' : nth s' n = some b) (f : α → β → γ) : nth (zip_with f s s') n = some (f a b) := sorry theorem zip_with_nth_none {α : Type u} {β : Type v} {γ : Type w} {s : seq α} {s' : seq β} {n : ℕ} (s_nth_eq_none : nth s n = none) (f : α → β → γ) : nth (zip_with f s s') n = none := sorry theorem zip_with_nth_none' {α : Type u} {β : Type v} {γ : Type w} {s : seq α} {s' : seq β} {n : ℕ} (s'_nth_eq_none : nth s' n = none) (f : α → β → γ) : nth (zip_with f s s') n = none := sorry /-- Pair two sequences into a sequence of pairs -/ def zip {α : Type u} {β : Type v} : seq α → seq β → seq (α × β) := zip_with Prod.mk /-- Separate a sequence of pairs into two sequences -/ def unzip {α : Type u} {β : Type v} (s : seq (α × β)) : seq α × seq β := (map prod.fst s, map prod.snd s) /-- Convert a sequence which is known to terminate into a list -/ def to_list {α : Type u} (s : seq α) (h : ∃ (n : ℕ), ¬↥(option.is_some (nth s n))) : List α := take (nat.find h) s /-- Convert a sequence which is known not to terminate into a stream -/ def to_stream {α : Type u} (s : seq α) (h : ∀ (n : ℕ), ↥(option.is_some (nth s n))) : stream α := fun (n : ℕ) => option.get (h n) /-- Convert a sequence into either a list or a stream depending on whether it is finite or infinite. (Without decidability of the infiniteness predicate, this is not constructively possible.) -/ def to_list_or_stream {α : Type u} (s : seq α) [Decidable (∃ (n : ℕ), ¬↥(option.is_some (nth s n)))] : List α ⊕ stream α := dite (∃ (n : ℕ), ¬↥(option.is_some (nth s n))) (fun (h : ∃ (n : ℕ), ¬↥(option.is_some (nth s n))) => sum.inl (to_list s h)) fun (h : ¬∃ (n : ℕ), ¬↥(option.is_some (nth s n))) => sum.inr (to_stream s sorry) @[simp] theorem nil_append {α : Type u} (s : seq α) : append nil s = s := sorry @[simp] theorem cons_append {α : Type u} (a : α) (s : seq α) (t : seq α) : append (cons a s) t = cons a (append s t) := sorry @[simp] theorem append_nil {α : Type u} (s : seq α) : append s nil = s := sorry @[simp] theorem append_assoc {α : Type u} (s : seq α) (t : seq α) (u : seq α) : append (append s t) u = append s (append t u) := sorry @[simp] theorem map_nil {α : Type u} {β : Type v} (f : α → β) : map f nil = nil := rfl @[simp] theorem map_cons {α : Type u} {β : Type v} (f : α → β) (a : α) (s : seq α) : map f (cons a s) = cons (f a) (map f s) := sorry @[simp] theorem map_id {α : Type u} (s : seq α) : map id s = s := sorry @[simp] theorem map_tail {α : Type u} {β : Type v} (f : α → β) (s : seq α) : map f (tail s) = tail (map f s) := sorry theorem map_comp {α : Type u} {β : Type v} {γ : Type w} (f : α → β) (g : β → γ) (s : seq α) : map (g ∘ f) s = map g (map f s) := sorry @[simp] theorem map_append {α : Type u} {β : Type v} (f : α → β) (s : seq α) (t : seq α) : map f (append s t) = append (map f s) (map f t) := sorry @[simp] theorem map_nth {α : Type u} {β : Type v} (f : α → β) (s : seq α) (n : ℕ) : nth (map f s) n = option.map f (nth s n) := sorry protected instance functor : Functor seq := { map := map, mapConst := fun (α β : Type u_1) => map ∘ function.const β } protected instance is_lawful_functor : is_lawful_functor seq := is_lawful_functor.mk map_id map_comp @[simp] theorem join_nil {α : Type u} : join nil = nil := destruct_eq_nil rfl @[simp] theorem join_cons_nil {α : Type u} (a : α) (S : seq (seq1 α)) : join (cons (a, nil) S) = cons a (join S) := sorry @[simp] theorem join_cons_cons {α : Type u} (a : α) (b : α) (s : seq α) (S : seq (seq1 α)) : join (cons (a, cons b s) S) = cons a (join (cons (b, s) S)) := sorry @[simp] theorem join_cons {α : Type u} (a : α) (s : seq α) (S : seq (seq1 α)) : join (cons (a, s) S) = cons a (append s (join S)) := sorry @[simp] theorem join_append {α : Type u} (S : seq (seq1 α)) (T : seq (seq1 α)) : join (append S T) = append (join S) (join T) := sorry @[simp] theorem of_list_nil {α : Type u} : of_list [] = nil := rfl @[simp] theorem of_list_cons {α : Type u} (a : α) (l : List α) : of_list (a :: l) = cons a (of_list l) := sorry @[simp] theorem of_stream_cons {α : Type u} (a : α) (s : stream α) : of_stream (a :: s) = cons a (of_stream s) := sorry @[simp] theorem of_list_append {α : Type u} (l : List α) (l' : List α) : of_list (l ++ l') = append (of_list l) (of_list l') := sorry @[simp] theorem of_stream_append {α : Type u} (l : List α) (s : stream α) : of_stream (l++ₛs) = append (of_list l) (of_stream s) := sorry /-- Convert a sequence into a list, embedded in a computation to allow for the possibility of infinite sequences (in which case the computation never returns anything). -/ def to_list' {α : Type u_1} (s : seq α) : computation (List α) := computation.corec (fun (_x : List α × seq α) => sorry) ([], s) theorem dropn_add {α : Type u} (s : seq α) (m : ℕ) (n : ℕ) : drop s (m + n) = drop (drop s m) n := sorry theorem dropn_tail {α : Type u} (s : seq α) (n : ℕ) : drop (tail s) n = drop s (n + 1) := eq.mpr (id (Eq._oldrec (Eq.refl (drop (tail s) n = drop s (n + 1))) (add_comm n 1))) (Eq.symm (dropn_add s 1 n)) theorem nth_tail {α : Type u} (s : seq α) (n : ℕ) : nth (tail s) n = nth s (n + 1) := sorry protected theorem ext {α : Type u} (s : seq α) (s' : seq α) (hyp : ∀ (n : ℕ), nth s n = nth s' n) : s = s' := sorry @[simp] theorem head_dropn {α : Type u} (s : seq α) (n : ℕ) : head (drop s n) = nth s n := sorry theorem mem_map {α : Type u} {β : Type v} (f : α → β) {a : α} {s : seq α} : a ∈ s → f a ∈ map f s := sorry theorem exists_of_mem_map {α : Type u} {β : Type v} {f : α → β} {b : β} {s : seq α} : b ∈ map f s → ∃ (a : α), a ∈ s ∧ f a = b := sorry theorem of_mem_append {α : Type u} {s₁ : seq α} {s₂ : seq α} {a : α} (h : a ∈ append s₁ s₂) : a ∈ s₁ ∨ a ∈ s₂ := sorry theorem mem_append_left {α : Type u} {s₁ : seq α} {s₂ : seq α} {a : α} (h : a ∈ s₁) : a ∈ append s₁ s₂ := sorry end seq namespace seq1 /-- Convert a `seq1` to a sequence. -/ def to_seq {α : Type u} : seq1 α → seq α := sorry protected instance coe_seq {α : Type u} : has_coe (seq1 α) (seq α) := has_coe.mk to_seq /-- Map a function on a `seq1` -/ def map {α : Type u} {β : Type v} (f : α → β) : seq1 α → seq1 β := sorry theorem map_id {α : Type u} (s : seq1 α) : map id s = s := sorry /-- Flatten a nonempty sequence of nonempty sequences -/ def join {α : Type u} : seq1 (seq1 α) → seq1 α := sorry @[simp] theorem join_nil {α : Type u} (a : α) (S : seq (seq1 α)) : join ((a, seq.nil), S) = (a, seq.join S) := rfl @[simp] theorem join_cons {α : Type u} (a : α) (b : α) (s : seq α) (S : seq (seq1 α)) : join ((a, seq.cons b s), S) = (a, seq.join (seq.cons (b, s) S)) := sorry /-- The `return` operator for the `seq1` monad, which produces a singleton sequence. -/ def ret {α : Type u} (a : α) : seq1 α := (a, seq.nil) protected instance inhabited {α : Type u} [Inhabited α] : Inhabited (seq1 α) := { default := ret Inhabited.default } /-- The `bind` operator for the `seq1` monad, which maps `f` on each element of `s` and appends the results together. (Not all of `s` may be evaluated, because the first few elements of `s` may already produce an infinite result.) -/ def bind {α : Type u} {β : Type v} (s : seq1 α) (f : α → seq1 β) : seq1 β := join (map f s) @[simp] theorem join_map_ret {α : Type u} (s : seq α) : seq.join (seq.map ret s) = s := sorry @[simp] theorem bind_ret {α : Type u} {β : Type v} (f : α → β) (s : seq1 α) : bind s (ret ∘ f) = map f s := sorry @[simp] theorem ret_bind {α : Type u} {β : Type v} (a : α) (f : α → seq1 β) : bind (ret a) f = f a := sorry @[simp] theorem map_join' {α : Type u} {β : Type v} (f : α → β) (S : seq (seq1 α)) : seq.map f (seq.join S) = seq.join (seq.map (map f) S) := sorry @[simp] theorem map_join {α : Type u} {β : Type v} (f : α → β) (S : seq1 (seq1 α)) : map f (join S) = join (map (map f) S) := sorry @[simp] theorem join_join {α : Type u} (SS : seq (seq1 (seq1 α))) : seq.join (seq.join SS) = seq.join (seq.map join SS) := sorry @[simp] theorem bind_assoc {α : Type u} {β : Type v} {γ : Type w} (s : seq1 α) (f : α → seq1 β) (g : β → seq1 γ) : bind (bind s f) g = bind s fun (x : α) => bind (f x) g := sorry protected instance monad : Monad seq1 := { toApplicative := { toFunctor := { map := map, mapConst := fun (α β : Type u_1) => map ∘ function.const β }, toPure := { pure := ret }, toSeq := { seq := fun (α β : Type u_1) (f : seq1 (α → β)) (x : seq1 α) => bind f fun (_x : α → β) => map _x x }, toSeqLeft := { seqLeft := fun (α β : Type u_1) (a : seq1 α) (b : seq1 β) => (fun (α β : Type u_1) (f : seq1 (α → β)) (x : seq1 α) => bind f fun (_x : α → β) => map _x x) β α (map (function.const β) a) b }, toSeqRight := { seqRight := fun (α β : Type u_1) (a : seq1 α) (b : seq1 β) => (fun (α β : Type u_1) (f : seq1 (α → β)) (x : seq1 α) => bind f fun (_x : α → β) => map _x x) β β (map (function.const α id) a) b } }, toBind := { bind := bind } } protected instance is_lawful_monad : is_lawful_monad seq1 := is_lawful_monad.mk ret_bind bind_assoc
f6dd763e5158b37ae52b927c028ba4ebf9818e5f
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/unhygienicCode.lean
e2a963fe1f1cb96a945ee9f00bb54d15daa56aa8
[ "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
299
lean
import Lean.Hygiene open Lean set_option trace.Compiler.result true set_option trace.compiler.ir.result true -- The following function should not allocate any closures, -- nor any heap object that doesn't appear in the result: def foo (n : Nat) : Syntax.Term := Unhygienic.run `(a + $(quote n))
2f800bde44c59ff34835d18c8c816ae7e11a6a17
abd85493667895c57a7507870867b28124b3998f
/src/category_theory/limits/limits.lean
de333ddfcdd6cdc4cdca88cbd5f0b82b3516f1c3
[ "Apache-2.0" ]
permissive
pechersky/mathlib
d56eef16bddb0bfc8bc552b05b7270aff5944393
f1df14c2214ee114c9738e733efd5de174deb95d
refs/heads/master
1,666,714,392,571
1,591,747,567,000
1,591,747,567,000
270,557,274
0
0
Apache-2.0
1,591,597,975,000
1,591,597,974,000
null
UTF-8
Lean
false
false
43,213
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Reid Barton, Mario Carneiro, Scott Morrison, Floris van Doorn -/ import category_theory.limits.cones import category_theory.adjunction.basic open category_theory category_theory.category category_theory.functor opposite namespace category_theory.limits universes v u u' u'' w -- declare the `v`'s first; see `category_theory.category` for an explanation -- See the notes at the top of cones.lean, explaining why we can't allow `J : Prop` here. variables {J K : Type v} [small_category J] [small_category K] variables {C : Type u} [category.{v} C] variables {F : J ⥤ C} /-- A cone `t` on `F` is a limit cone if each cone on `F` admits a unique cone morphism to `t`. -/ @[nolint has_inhabited_instance] structure is_limit (t : cone F) := (lift : Π (s : cone F), s.X ⟶ t.X) (fac' : ∀ (s : cone F) (j : J), lift s ≫ t.π.app j = s.π.app j . obviously) (uniq' : ∀ (s : cone F) (m : s.X ⟶ t.X) (w : ∀ j : J, m ≫ t.π.app j = s.π.app j), m = lift s . obviously) restate_axiom is_limit.fac' attribute [simp, reassoc] is_limit.fac restate_axiom is_limit.uniq' namespace is_limit instance subsingleton {t : cone F} : subsingleton (is_limit t) := ⟨by intros P Q; cases P; cases Q; congr; ext; solve_by_elim⟩ /- Repackaging the definition in terms of cone morphisms. -/ /-- The universal morphism from any other cone to a limit cone. -/ def lift_cone_morphism {t : cone F} (h : is_limit t) (s : cone F) : s ⟶ t := { hom := h.lift s } lemma uniq_cone_morphism {s t : cone F} (h : is_limit t) {f f' : s ⟶ t} : f = f' := have ∀ {g : s ⟶ t}, g = h.lift_cone_morphism s, by intro g; ext; exact h.uniq _ _ g.w, this.trans this.symm /-- Alternative constructor for `is_limit`, providing a morphism of cones rather than a morphism between the cone points and separately the factorisation condition. -/ def mk_cone_morphism {t : cone F} (lift : Π (s : cone F), s ⟶ t) (uniq' : ∀ (s : cone F) (m : s ⟶ t), m = lift s) : is_limit t := { lift := λ s, (lift s).hom, uniq' := λ s m w, have cone_morphism.mk m w = lift s, by apply uniq', congr_arg cone_morphism.hom this } /-- Limit cones on `F` are unique up to isomorphism. -/ def unique_up_to_iso {s t : cone F} (P : is_limit s) (Q : is_limit t) : s ≅ t := { hom := Q.lift_cone_morphism s, inv := P.lift_cone_morphism t, hom_inv_id' := P.uniq_cone_morphism, inv_hom_id' := Q.uniq_cone_morphism } /-- Limits of `F` are unique up to isomorphism. -/ -- We may later want to prove the coherence of these isomorphisms. def cone_point_unique_up_to_iso {s t : cone F} (P : is_limit s) (Q : is_limit t) : s.X ≅ t.X := (cones.forget F).map_iso (unique_up_to_iso P Q) /-- Transport evidence that a cone is a limit cone across an isomorphism of cones. -/ def of_iso_limit {r t : cone F} (P : is_limit r) (i : r ≅ t) : is_limit t := is_limit.mk_cone_morphism (λ s, P.lift_cone_morphism s ≫ i.hom) (λ s m, by rw ←i.comp_inv_eq; apply P.uniq_cone_morphism) variables {t : cone F} lemma hom_lift (h : is_limit t) {W : C} (m : W ⟶ t.X) : m = h.lift { X := W, π := { app := λ b, m ≫ t.π.app b } } := h.uniq { X := W, π := { app := λ b, m ≫ t.π.app b } } m (λ b, rfl) /-- Two morphisms into a limit are equal if their compositions with each cone morphism are equal. -/ lemma hom_ext (h : is_limit t) {W : C} {f f' : W ⟶ t.X} (w : ∀ j, f ≫ t.π.app j = f' ≫ t.π.app j) : f = f' := by rw [h.hom_lift f, h.hom_lift f']; congr; exact funext w /-- The universal property of a limit cone: a map `W ⟶ X` is the same as a cone on `F` with vertex `W`. -/ def hom_iso (h : is_limit t) (W : C) : (W ⟶ t.X) ≅ ((const J).obj W ⟶ F) := { hom := λ f, (t.extend f).π, inv := λ π, h.lift { X := W, π := π }, hom_inv_id' := by ext f; apply h.hom_ext; intro j; simp; dsimp; refl } @[simp] lemma hom_iso_hom (h : is_limit t) {W : C} (f : W ⟶ t.X) : (is_limit.hom_iso h W).hom f = (t.extend f).π := rfl /-- The limit of `F` represents the functor taking `W` to the set of cones on `F` with vertex `W`. -/ def nat_iso (h : is_limit t) : yoneda.obj t.X ≅ F.cones := nat_iso.of_components (λ W, is_limit.hom_iso h (unop W)) (by tidy). /-- Another, more explicit, formulation of the universal property of a limit cone. See also `hom_iso`. -/ def hom_iso' (h : is_limit t) (W : C) : ((W ⟶ t.X) : Type v) ≅ { p : Π j, W ⟶ F.obj j // ∀ {j j'} (f : j ⟶ j'), p j ≫ F.map f = p j' } := h.hom_iso W ≪≫ { hom := λ π, ⟨λ j, π.app j, λ j j' f, by convert ←(π.naturality f).symm; apply id_comp⟩, inv := λ p, { app := λ j, p.1 j, naturality' := λ j j' f, begin dsimp, rw [id_comp], exact (p.2 f).symm end } } /-- If G : C → D is a faithful functor which sends t to a limit cone, then it suffices to check that the induced maps for the image of t can be lifted to maps of C. -/ def of_faithful {t : cone F} {D : Type u'} [category.{v} D] (G : C ⥤ D) [faithful G] (ht : is_limit (G.map_cone t)) (lift : Π (s : cone F), s.X ⟶ t.X) (h : ∀ s, G.map (lift s) = ht.lift (G.map_cone s)) : is_limit t := { lift := lift, fac' := λ s j, by apply G.injectivity; rw [G.map_comp, h]; apply ht.fac, uniq' := λ s m w, begin apply G.injectivity, rw h, refine ht.uniq (G.map_cone s) _ (λ j, _), convert ←congr_arg (λ f, G.map f) (w j), apply G.map_comp end } /-- If `F` and `G` are naturally isomorphic, then `F.map_cone c` being a limit implies `G.map_cone c` is also a limit. -/ def map_cone_equiv {D : Type u'} [category.{v} D] {K : J ⥤ C} {F G : C ⥤ D} (h : F ≅ G) {c : cone K} (t : is_limit (F.map_cone c)) : is_limit (G.map_cone c) := { lift := λ s, t.lift ((cones.postcompose (iso_whisker_left K h).inv).obj s) ≫ h.hom.app c.X, fac' := λ s j, begin slice_lhs 2 3 {erw ← h.hom.naturality (c.π.app j)}, slice_lhs 1 2 {erw t.fac ((cones.postcompose (iso_whisker_left K h).inv).obj s) j}, dsimp, slice_lhs 2 3 {rw nat_iso.inv_hom_id_app}, rw category.comp_id, end, uniq' := λ s m J, begin rw ← cancel_mono (h.inv.app c.X), apply t.hom_ext, intro j, dsimp, slice_lhs 2 3 {erw ← h.inv.naturality (c.π.app j)}, slice_lhs 1 2 {erw J j}, conv_rhs {congr, rw [category.assoc, nat_iso.hom_inv_id_app, comp_id]}, apply (t.fac ((cones.postcompose (iso_whisker_left K h).inv).obj s) j).symm end } /-- A cone is a limit cone exactly if there is a unique cone morphism from any other cone. -/ def iso_unique_cone_morphism {t : cone F} : is_limit t ≅ Π s, unique (s ⟶ t) := { hom := λ h s, { default := h.lift_cone_morphism s, uniq := λ _, h.uniq_cone_morphism }, inv := λ h, { lift := λ s, (h s).default.hom, uniq' := λ s f w, congr_arg cone_morphism.hom ((h s).uniq ⟨f, w⟩) } } /-- Given two functors which have equivalent categories of cones, we can transport a limiting cone across the equivalence. -/ def of_cone_equiv {D : Type u'} [category.{v} D] {G : K ⥤ D} (h : cone G ⥤ cone F) [is_right_adjoint h] {c : cone G} (t : is_limit c) : is_limit (h.obj c) := mk_cone_morphism (λ s, (adjunction.of_right_adjoint h).hom_equiv s c (t.lift_cone_morphism _)) (λ s m, (adjunction.eq_hom_equiv_apply _ _ _).2 t.uniq_cone_morphism ) namespace of_nat_iso variables {X : C} (h : yoneda.obj X ≅ F.cones) /-- If `F.cones` is represented by `X`, each morphism `f : Y ⟶ X` gives a cone with cone point `Y`. -/ def cone_of_hom {Y : C} (f : Y ⟶ X) : cone F := { X := Y, π := h.hom.app (op Y) f } /-- If `F.cones` is represented by `X`, each cone `s` gives a morphism `s.X ⟶ X`. -/ def hom_of_cone (s : cone F) : s.X ⟶ X := h.inv.app (op s.X) s.π @[simp] lemma cone_of_hom_of_cone (s : cone F) : cone_of_hom h (hom_of_cone h s) = s := begin dsimp [cone_of_hom, hom_of_cone], cases s, congr, dsimp, exact congr_fun (congr_fun (congr_arg nat_trans.app h.inv_hom_id) (op s_X)) s_π, end @[simp] lemma hom_of_cone_of_hom {Y : C} (f : Y ⟶ X) : hom_of_cone h (cone_of_hom h f) = f := congr_fun (congr_fun (congr_arg nat_trans.app h.hom_inv_id) (op Y)) f /-- If `F.cones` is represented by `X`, the cone corresponding to the identity morphism on `X` will be a limit cone. -/ def limit_cone : cone F := cone_of_hom h (𝟙 X) /-- If `F.cones` is represented by `X`, the cone corresponding to a morphism `f : Y ⟶ X` is the limit cone extended by `f`. -/ lemma cone_of_hom_fac {Y : C} (f : Y ⟶ X) : cone_of_hom h f = (limit_cone h).extend f := begin dsimp [cone_of_hom, limit_cone, cone.extend], congr, ext j, have t := congr_fun (h.hom.naturality f.op) (𝟙 X), dsimp at t, simp only [comp_id] at t, rw congr_fun (congr_arg nat_trans.app t) j, refl, end /-- If `F.cones` is represented by `X`, any cone is the extension of the limit cone by the corresponding morphism. -/ lemma cone_fac (s : cone F) : (limit_cone h).extend (hom_of_cone h s) = s := begin rw ←cone_of_hom_of_cone h s, conv_lhs { simp only [hom_of_cone_of_hom] }, apply (cone_of_hom_fac _ _).symm, end end of_nat_iso section open of_nat_iso /-- If `F.cones` is representable, then the cone corresponding to the identity morphism on the representing object is a limit cone. -/ def of_nat_iso {X : C} (h : yoneda.obj X ≅ F.cones) : is_limit (limit_cone h) := { lift := λ s, hom_of_cone h s, fac' := λ s j, begin have h := cone_fac h s, cases s, injection h with h₁ h₂, simp only [heq_iff_eq] at h₂, conv_rhs { rw ← h₂ }, refl, end, uniq' := λ s m w, begin rw ←hom_of_cone_of_hom h m, congr, rw cone_of_hom_fac, dsimp, cases s, congr, ext j, exact w j, end } end end is_limit /-- A cocone `t` on `F` is a colimit cocone if each cocone on `F` admits a unique cocone morphism from `t`. -/ @[nolint has_inhabited_instance] structure is_colimit (t : cocone F) := (desc : Π (s : cocone F), t.X ⟶ s.X) (fac' : ∀ (s : cocone F) (j : J), t.ι.app j ≫ desc s = s.ι.app j . obviously) (uniq' : ∀ (s : cocone F) (m : t.X ⟶ s.X) (w : ∀ j : J, t.ι.app j ≫ m = s.ι.app j), m = desc s . obviously) restate_axiom is_colimit.fac' attribute [simp] is_colimit.fac restate_axiom is_colimit.uniq' namespace is_colimit instance subsingleton {t : cocone F} : subsingleton (is_colimit t) := ⟨by intros P Q; cases P; cases Q; congr; ext; solve_by_elim⟩ /- Repackaging the definition in terms of cone morphisms. -/ /-- The universal morphism from a colimit cocone to any other cone. -/ def desc_cocone_morphism {t : cocone F} (h : is_colimit t) (s : cocone F) : t ⟶ s := { hom := h.desc s } lemma uniq_cocone_morphism {s t : cocone F} (h : is_colimit t) {f f' : t ⟶ s} : f = f' := have ∀ {g : t ⟶ s}, g = h.desc_cocone_morphism s, by intro g; ext; exact h.uniq _ _ g.w, this.trans this.symm /-- Alternative constructor for `is_colimit`, providing a morphism of cocones rather than a morphism between the cocone points and separately the factorisation condition. -/ def mk_cocone_morphism {t : cocone F} (desc : Π (s : cocone F), t ⟶ s) (uniq' : ∀ (s : cocone F) (m : t ⟶ s), m = desc s) : is_colimit t := { desc := λ s, (desc s).hom, uniq' := λ s m w, have cocone_morphism.mk m w = desc s, by apply uniq', congr_arg cocone_morphism.hom this } /-- Limit cones on `F` are unique up to isomorphism. -/ def unique_up_to_iso {s t : cocone F} (P : is_colimit s) (Q : is_colimit t) : s ≅ t := { hom := P.desc_cocone_morphism t, inv := Q.desc_cocone_morphism s, hom_inv_id' := P.uniq_cocone_morphism, inv_hom_id' := Q.uniq_cocone_morphism } /-- Colimits of `F` are unique up to isomorphism. -/ -- We may later want to prove the coherence of these isomorphisms. def cocone_point_unique_up_to_iso {s t : cocone F} (P : is_colimit s) (Q : is_colimit t) : s.X ≅ t.X := (cocones.forget F).map_iso (unique_up_to_iso P Q) /-- Transport evidence that a cocone is a colimit cocone across an isomorphism of cocones. -/ def of_iso_colimit {r t : cocone F} (P : is_colimit r) (i : r ≅ t) : is_colimit t := is_colimit.mk_cocone_morphism (λ s, i.inv ≫ P.desc_cocone_morphism s) (λ s m, by rw i.eq_inv_comp; apply P.uniq_cocone_morphism) variables {t : cocone F} lemma hom_desc (h : is_colimit t) {W : C} (m : t.X ⟶ W) : m = h.desc { X := W, ι := { app := λ b, t.ι.app b ≫ m, naturality' := by intros; erw [←assoc, t.ι.naturality, comp_id, comp_id] } } := h.uniq { X := W, ι := { app := λ b, t.ι.app b ≫ m, naturality' := _ } } m (λ b, rfl) /-- Two morphisms out of a colimit are equal if their compositions with each cocone morphism are equal. -/ lemma hom_ext (h : is_colimit t) {W : C} {f f' : t.X ⟶ W} (w : ∀ j, t.ι.app j ≫ f = t.ι.app j ≫ f') : f = f' := by rw [h.hom_desc f, h.hom_desc f']; congr; exact funext w /-- The universal property of a colimit cocone: a map `X ⟶ W` is the same as a cocone on `F` with vertex `W`. -/ def hom_iso (h : is_colimit t) (W : C) : (t.X ⟶ W) ≅ (F ⟶ (const J).obj W) := { hom := λ f, (t.extend f).ι, inv := λ ι, h.desc { X := W, ι := ι }, hom_inv_id' := by ext f; apply h.hom_ext; intro j; simp; dsimp; refl } @[simp] lemma hom_iso_hom (h : is_colimit t) {W : C} (f : t.X ⟶ W) : (is_colimit.hom_iso h W).hom f = (t.extend f).ι := rfl /-- The colimit of `F` represents the functor taking `W` to the set of cocones on `F` with vertex `W`. -/ def nat_iso (h : is_colimit t) : coyoneda.obj (op t.X) ≅ F.cocones := nat_iso.of_components (is_colimit.hom_iso h) (by intros; ext; dsimp; rw ←assoc; refl) /-- Another, more explicit, formulation of the universal property of a colimit cocone. See also `hom_iso`. -/ def hom_iso' (h : is_colimit t) (W : C) : ((t.X ⟶ W) : Type v) ≅ { p : Π j, F.obj j ⟶ W // ∀ {j j' : J} (f : j ⟶ j'), F.map f ≫ p j' = p j } := h.hom_iso W ≪≫ { hom := λ ι, ⟨λ j, ι.app j, λ j j' f, by convert ←(ι.naturality f); apply comp_id⟩, inv := λ p, { app := λ j, p.1 j, naturality' := λ j j' f, begin dsimp, rw [comp_id], exact (p.2 f) end } } /-- If G : C → D is a faithful functor which sends t to a colimit cocone, then it suffices to check that the induced maps for the image of t can be lifted to maps of C. -/ def of_faithful {t : cocone F} {D : Type u'} [category.{v} D] (G : C ⥤ D) [faithful G] (ht : is_colimit (G.map_cocone t)) (desc : Π (s : cocone F), t.X ⟶ s.X) (h : ∀ s, G.map (desc s) = ht.desc (G.map_cocone s)) : is_colimit t := { desc := desc, fac' := λ s j, by apply G.injectivity; rw [G.map_comp, h]; apply ht.fac, uniq' := λ s m w, begin apply G.injectivity, rw h, refine ht.uniq (G.map_cocone s) _ (λ j, _), convert ←congr_arg (λ f, G.map f) (w j), apply G.map_comp end } /-- A cocone is a colimit cocone exactly if there is a unique cocone morphism from any other cocone. -/ def iso_unique_cocone_morphism {t : cocone F} : is_colimit t ≅ Π s, unique (t ⟶ s) := { hom := λ h s, { default := h.desc_cocone_morphism s, uniq := λ _, h.uniq_cocone_morphism }, inv := λ h, { desc := λ s, (h s).default.hom, uniq' := λ s f w, congr_arg cocone_morphism.hom ((h s).uniq ⟨f, w⟩) } } /-- Given two functors which have equivalent categories of cocones, we can transport a limiting cocone across the equivalence. -/ def of_cocone_equiv {D : Type u'} [category.{v} D] {G : K ⥤ D} (h : cocone G ⥤ cocone F) [is_left_adjoint h] {c : cocone G} (t : is_colimit c) : is_colimit (h.obj c) := mk_cocone_morphism (λ s, ((adjunction.of_left_adjoint h).hom_equiv c s).symm (t.desc_cocone_morphism _)) (λ s m, (adjunction.hom_equiv_apply_eq _ _ _).1 t.uniq_cocone_morphism) namespace of_nat_iso variables {X : C} (h : coyoneda.obj (op X) ≅ F.cocones) /-- If `F.cocones` is corepresented by `X`, each morphism `f : X ⟶ Y` gives a cocone with cone point `Y`. -/ def cocone_of_hom {Y : C} (f : X ⟶ Y) : cocone F := { X := Y, ι := h.hom.app Y f } /-- If `F.cocones` is corepresented by `X`, each cocone `s` gives a morphism `X ⟶ s.X`. -/ def hom_of_cocone (s : cocone F) : X ⟶ s.X := h.inv.app s.X s.ι @[simp] lemma cocone_of_hom_of_cocone (s : cocone F) : cocone_of_hom h (hom_of_cocone h s) = s := begin dsimp [cocone_of_hom, hom_of_cocone], cases s, congr, dsimp, exact congr_fun (congr_fun (congr_arg nat_trans.app h.inv_hom_id) s_X) s_ι, end @[simp] lemma hom_of_cocone_of_hom {Y : C} (f : X ⟶ Y) : hom_of_cocone h (cocone_of_hom h f) = f := congr_fun (congr_fun (congr_arg nat_trans.app h.hom_inv_id) Y) f /-- If `F.cocones` is corepresented by `X`, the cocone corresponding to the identity morphism on `X` will be a colimit cocone. -/ def colimit_cocone : cocone F := cocone_of_hom h (𝟙 X) /-- If `F.cocones` is corepresented by `X`, the cocone corresponding to a morphism `f : Y ⟶ X` is the colimit cocone extended by `f`. -/ lemma cocone_of_hom_fac {Y : C} (f : X ⟶ Y) : cocone_of_hom h f = (colimit_cocone h).extend f := begin dsimp [cocone_of_hom, colimit_cocone, cocone.extend], congr, ext j, have t := congr_fun (h.hom.naturality f) (𝟙 X), dsimp at t, simp only [id_comp] at t, rw congr_fun (congr_arg nat_trans.app t) j, refl, end /-- If `F.cocones` is corepresented by `X`, any cocone is the extension of the colimit cocone by the corresponding morphism. -/ lemma cocone_fac (s : cocone F) : (colimit_cocone h).extend (hom_of_cocone h s) = s := begin rw ←cocone_of_hom_of_cocone h s, conv_lhs { simp only [hom_of_cocone_of_hom] }, apply (cocone_of_hom_fac _ _).symm, end end of_nat_iso section open of_nat_iso /-- If `F.cocones` is corepresentable, then the cocone corresponding to the identity morphism on the representing object is a colimit cocone. -/ def of_nat_iso {X : C} (h : coyoneda.obj (op X) ≅ F.cocones) : is_colimit (colimit_cocone h) := { desc := λ s, hom_of_cocone h s, fac' := λ s j, begin have h := cocone_fac h s, cases s, injection h with h₁ h₂, simp only [heq_iff_eq] at h₂, conv_rhs { rw ← h₂ }, refl, end, uniq' := λ s m w, begin rw ←hom_of_cocone_of_hom h m, congr, rw cocone_of_hom_fac, dsimp, cases s, congr, ext j, exact w j, end } end end is_colimit section limit /-- `has_limit F` represents a particular chosen limit of the diagram `F`. -/ class has_limit (F : J ⥤ C) := (cone : cone F) (is_limit : is_limit cone) variables (J C) /-- `C` has limits of shape `J` if we have chosen a particular limit of every functor `F : J ⥤ C`. -/ class has_limits_of_shape := (has_limit : Π F : J ⥤ C, has_limit F) /-- `C` has all (small) limits if it has limits of every shape. -/ class has_limits := (has_limits_of_shape : Π (J : Type v) [𝒥 : small_category J], has_limits_of_shape J C) variables {J C} @[priority 100] -- see Note [lower instance priority] instance has_limit_of_has_limits_of_shape {J : Type v} [small_category J] [H : has_limits_of_shape J C] (F : J ⥤ C) : has_limit F := has_limits_of_shape.has_limit F @[priority 100] -- see Note [lower instance priority] instance has_limits_of_shape_of_has_limits {J : Type v} [small_category J] [H : has_limits.{v} C] : has_limits_of_shape J C := has_limits.has_limits_of_shape J /- Interface to the `has_limit` class. -/ /-- The chosen limit cone of a functor. -/ def limit.cone (F : J ⥤ C) [has_limit F] : cone F := has_limit.cone /-- The chosen limit object of a functor. -/ def limit (F : J ⥤ C) [has_limit F] := (limit.cone F).X /-- The projection from the chosen limit object to a value of the functor. -/ def limit.π (F : J ⥤ C) [has_limit F] (j : J) : limit F ⟶ F.obj j := (limit.cone F).π.app j @[simp] lemma limit.cone_π {F : J ⥤ C} [has_limit F] (j : J) : (limit.cone F).π.app j = limit.π _ j := rfl @[simp] lemma limit.w (F : J ⥤ C) [has_limit F] {j j' : J} (f : j ⟶ j') : limit.π F j ≫ F.map f = limit.π F j' := (limit.cone F).w f /-- Evidence that the chosen cone is a limit cone. -/ def limit.is_limit (F : J ⥤ C) [has_limit F] : is_limit (limit.cone F) := has_limit.is_limit.{v} /-- The morphism from the cone point of any other cone to the chosen limit object. -/ def limit.lift (F : J ⥤ C) [has_limit F] (c : cone F) : c.X ⟶ limit F := (limit.is_limit F).lift c @[simp] lemma limit.is_limit_lift {F : J ⥤ C} [has_limit F] (c : cone F) : (limit.is_limit F).lift c = limit.lift F c := rfl @[simp, reassoc] lemma limit.lift_π {F : J ⥤ C} [has_limit F] (c : cone F) (j : J) : limit.lift F c ≫ limit.π F j = c.π.app j := is_limit.fac _ c j /-- The cone morphism from any cone to the chosen limit cone. -/ def limit.cone_morphism {F : J ⥤ C} [has_limit F] (c : cone F) : c ⟶ (limit.cone F) := (limit.is_limit F).lift_cone_morphism c @[simp] lemma limit.cone_morphism_hom {F : J ⥤ C} [has_limit F] (c : cone F) : (limit.cone_morphism c).hom = limit.lift F c := rfl lemma limit.cone_morphism_π {F : J ⥤ C} [has_limit F] (c : cone F) (j : J) : (limit.cone_morphism c).hom ≫ limit.π F j = c.π.app j := by simp @[ext] lemma limit.hom_ext {F : J ⥤ C} [has_limit F] {X : C} {f f' : X ⟶ limit F} (w : ∀ j, f ≫ limit.π F j = f' ≫ limit.π F j) : f = f' := (limit.is_limit F).hom_ext w /-- The isomorphism (in `Type`) between morphisms from a specified object `W` to the limit object, and cones with cone point `W`. -/ def limit.hom_iso (F : J ⥤ C) [has_limit F] (W : C) : (W ⟶ limit F) ≅ (F.cones.obj (op W)) := (limit.is_limit F).hom_iso W @[simp] lemma limit.hom_iso_hom (F : J ⥤ C) [has_limit F] {W : C} (f : W ⟶ limit F) : (limit.hom_iso F W).hom f = (const J).map f ≫ (limit.cone F).π := (limit.is_limit F).hom_iso_hom f /-- The isomorphism (in `Type`) between morphisms from a specified object `W` to the limit object, and an explicit componentwise description of cones with cone point `W`. -/ def limit.hom_iso' (F : J ⥤ C) [has_limit F] (W : C) : ((W ⟶ limit F) : Type v) ≅ { p : Π j, W ⟶ F.obj j // ∀ {j j' : J} (f : j ⟶ j'), p j ≫ F.map f = p j' } := (limit.is_limit F).hom_iso' W lemma limit.lift_extend {F : J ⥤ C} [has_limit F] (c : cone F) {X : C} (f : X ⟶ c.X) : limit.lift F (c.extend f) = f ≫ limit.lift F c := by obviously /-- If we've chosen a limit for a functor `F`, we can transport that choice across a natural isomorphism. -/ def has_limit_of_iso {F G : J ⥤ C} [has_limit F] (α : F ≅ G) : has_limit G := { cone := (cones.postcompose α.hom).obj (limit.cone F), is_limit := { lift := λ s, limit.lift F ((cones.postcompose α.inv).obj s), fac' := λ s j, begin rw [cones.postcompose_obj_π, nat_trans.comp_app, limit.cone_π, ←category.assoc, limit.lift_π], simp end, uniq' := λ s m w, begin apply limit.hom_ext, intro j, rw [limit.lift_π, cones.postcompose_obj_π, nat_trans.comp_app, ←nat_iso.app_inv, iso.eq_comp_inv], simpa using w j end } } /-- If a functor `G` has the same collection of cones as a functor `F` which has a limit, then `G` also has a limit. -/ -- See the construction of limits from products and equalizers -- for an example usage. def has_limit.of_cones_iso {J K : Type v} [small_category J] [small_category K] (F : J ⥤ C) (G : K ⥤ C) (h : F.cones ≅ G.cones) [has_limit F] : has_limit G := ⟨_, is_limit.of_nat_iso ((is_limit.nat_iso (limit.is_limit F)) ≪≫ h)⟩ section pre variables (F) [has_limit F] (E : K ⥤ J) [has_limit (E ⋙ F)] /-- The canonical morphism from the chosen limit of `F` to the chosen limit of `E ⋙ F`. -/ def limit.pre : limit F ⟶ limit (E ⋙ F) := limit.lift (E ⋙ F) { X := limit F, π := { app := λ k, limit.π F (E.obj k) } } @[simp] lemma limit.pre_π (k : K) : limit.pre F E ≫ limit.π (E ⋙ F) k = limit.π F (E.obj k) := by erw is_limit.fac @[simp] lemma limit.lift_pre (c : cone F) : limit.lift F c ≫ limit.pre F E = limit.lift (E ⋙ F) (c.whisker E) := by ext; simp variables {L : Type v} [small_category L] variables (D : L ⥤ K) [has_limit (D ⋙ E ⋙ F)] @[simp] lemma limit.pre_pre : limit.pre F E ≫ limit.pre (E ⋙ F) D = limit.pre F (D ⋙ E) := by ext j; erw [assoc, limit.pre_π, limit.pre_π, limit.pre_π]; refl end pre section post variables {D : Type u'} [category.{v} D] variables (F) [has_limit F] (G : C ⥤ D) [has_limit (F ⋙ G)] /-- The canonical morphism from `G` applied to the chosen limit of `F` to the chosen limit of `F ⋙ G`. -/ def limit.post : G.obj (limit F) ⟶ limit (F ⋙ G) := limit.lift (F ⋙ G) { X := G.obj (limit F), π := { app := λ j, G.map (limit.π F j), naturality' := by intros j j' f; erw [←G.map_comp, limits.cone.w, id_comp]; refl } } @[simp] lemma limit.post_π (j : J) : limit.post F G ≫ limit.π (F ⋙ G) j = G.map (limit.π F j) := by erw is_limit.fac @[simp] lemma limit.lift_post (c : cone F) : G.map (limit.lift F c) ≫ limit.post F G = limit.lift (F ⋙ G) (G.map_cone c) := by ext; rw [assoc, limit.post_π, ←G.map_comp, limit.lift_π, limit.lift_π]; refl @[simp] lemma limit.post_post {E : Type u''} [category.{v} E] (H : D ⥤ E) [has_limit ((F ⋙ G) ⋙ H)] : /- H G (limit F) ⟶ H (limit (F ⋙ G)) ⟶ limit ((F ⋙ G) ⋙ H) equals -/ /- H G (limit F) ⟶ limit (F ⋙ (G ⋙ H)) -/ H.map (limit.post F G) ≫ limit.post (F ⋙ G) H = limit.post F (G ⋙ H) := by ext; erw [assoc, limit.post_π, ←H.map_comp, limit.post_π, limit.post_π]; refl end post lemma limit.pre_post {D : Type u'} [category.{v} D] (E : K ⥤ J) (F : J ⥤ C) (G : C ⥤ D) [has_limit F] [has_limit (E ⋙ F)] [has_limit (F ⋙ G)] [has_limit ((E ⋙ F) ⋙ G)] : /- G (limit F) ⟶ G (limit (E ⋙ F)) ⟶ limit ((E ⋙ F) ⋙ G) vs -/ /- G (limit F) ⟶ limit F ⋙ G ⟶ limit (E ⋙ (F ⋙ G)) or -/ G.map (limit.pre F E) ≫ limit.post (E ⋙ F) G = limit.post F G ≫ limit.pre (F ⋙ G) E := by ext; erw [assoc, limit.post_π, ←G.map_comp, limit.pre_π, assoc, limit.pre_π, limit.post_π]; refl open category_theory.equivalence instance has_limit_equivalence_comp (e : K ≌ J) [has_limit F] : has_limit (e.functor ⋙ F) := { cone := cone.whisker e.functor (limit.cone F), is_limit := let e' := cones.postcompose (e.inv_fun_id_assoc F).hom in { lift := λ s, limit.lift F (e'.obj (cone.whisker e.inverse s)), fac' := λ s j, begin dsimp, rw [limit.lift_π], dsimp [e'], erw [inv_fun_id_assoc_hom_app, counit_functor, ←s.π.naturality, id_comp] end, uniq' := λ s m w, begin apply limit.hom_ext, intro j, erw [limit.lift_π, ←limit.w F (e.counit_iso.hom.app j)], slice_lhs 1 2 { erw [w (e.inverse.obj j)] }, simp end } } local attribute [elab_simple] inv_fun_id_assoc -- not entirely sure why this is needed /-- If a `E ⋙ F` has a chosen limit, and `E` is an equivalence, we can construct a chosen limit of `F`. -/ def has_limit_of_equivalence_comp (e : K ≌ J) [has_limit (e.functor ⋙ F)] : has_limit F := begin haveI : has_limit (e.inverse ⋙ e.functor ⋙ F) := limits.has_limit_equivalence_comp e.symm, apply has_limit_of_iso (e.inv_fun_id_assoc F), end -- `has_limit_comp_equivalence` and `has_limit_of_comp_equivalence` -- are proved in `category_theory/adjunction/limits.lean`. section lim_functor variables [has_limits_of_shape J C] /-- `limit F` is functorial in `F`, when `C` has all limits of shape `J`. -/ def lim : (J ⥤ C) ⥤ C := { obj := λ F, limit F, map := λ F G α, limit.lift G { X := limit F, π := { app := λ j, limit.π F j ≫ α.app j, naturality' := λ j j' f, by erw [id_comp, assoc, ←α.naturality, ←assoc, limit.w] } }, map_comp' := λ F G H α β, by ext; erw [assoc, is_limit.fac, is_limit.fac, ←assoc, is_limit.fac, assoc]; refl } variables {F} {G : J ⥤ C} (α : F ⟶ G) @[simp, reassoc] lemma limit.map_π (j : J) : lim.map α ≫ limit.π G j = limit.π F j ≫ α.app j := by apply is_limit.fac @[simp] lemma limit.lift_map (c : cone F) : limit.lift F c ≫ lim.map α = limit.lift G ((cones.postcompose α).obj c) := by ext; rw [assoc, limit.map_π, ←assoc, limit.lift_π, limit.lift_π]; refl lemma limit.map_pre [has_limits_of_shape K C] (E : K ⥤ J) : lim.map α ≫ limit.pre G E = limit.pre F E ≫ lim.map (whisker_left E α) := by ext; rw [assoc, limit.pre_π, limit.map_π, assoc, limit.map_π, ←assoc, limit.pre_π]; refl lemma limit.map_pre' [has_limits_of_shape.{v} K C] (F : J ⥤ C) {E₁ E₂ : K ⥤ J} (α : E₁ ⟶ E₂) : limit.pre F E₂ = limit.pre F E₁ ≫ lim.map (whisker_right α F) := by ext1; simp [← category.assoc] lemma limit.id_pre (F : J ⥤ C) : limit.pre F (𝟭 _) = lim.map (functor.left_unitor F).inv := by tidy lemma limit.map_post {D : Type u'} [category.{v} D] [has_limits_of_shape J D] (H : C ⥤ D) : /- H (limit F) ⟶ H (limit G) ⟶ limit (G ⋙ H) vs H (limit F) ⟶ limit (F ⋙ H) ⟶ limit (G ⋙ H) -/ H.map (lim.map α) ≫ limit.post G H = limit.post F H ≫ lim.map (whisker_right α H) := begin ext, rw [assoc, limit.post_π, ←H.map_comp, limit.map_π, H.map_comp], rw [assoc, limit.map_π, ←assoc, limit.post_π], refl end /-- The isomorphism between morphisms from `W` to the cone point of the limit cone for `F` and cones over `F` with cone point `W` is natural in `F`. -/ def lim_yoneda : lim ⋙ yoneda ≅ category_theory.cones J C := nat_iso.of_components (λ F, nat_iso.of_components (λ W, limit.hom_iso F (unop W)) (by tidy)) (by tidy) end lim_functor /-- We can transport chosen limits of shape `J` along an equivalence `J ≌ J'`. -/ def has_limits_of_shape_of_equivalence {J' : Type v} [small_category J'] (e : J ≌ J') [has_limits_of_shape J C] : has_limits_of_shape J' C := by { constructor, intro F, apply has_limit_of_equivalence_comp e, apply_instance } end limit section colimit /-- `has_colimit F` represents a particular chosen colimit of the diagram `F`. -/ class has_colimit (F : J ⥤ C) := (cocone : cocone F) (is_colimit : is_colimit cocone) variables (J C) /-- `C` has colimits of shape `J` if we have chosen a particular colimit of every functor `F : J ⥤ C`. -/ class has_colimits_of_shape := (has_colimit : Π F : J ⥤ C, has_colimit F) /-- `C` has all (small) colimits if it has colimits of every shape. -/ class has_colimits := (has_colimits_of_shape : Π (J : Type v) [𝒥 : small_category J], has_colimits_of_shape J C) variables {J C} @[priority 100] -- see Note [lower instance priority] instance has_colimit_of_has_colimits_of_shape {J : Type v} [small_category J] [H : has_colimits_of_shape J C] (F : J ⥤ C) : has_colimit F := has_colimits_of_shape.has_colimit F @[priority 100] -- see Note [lower instance priority] instance has_colimits_of_shape_of_has_colimits {J : Type v} [small_category J] [H : has_colimits.{v} C] : has_colimits_of_shape J C := has_colimits.has_colimits_of_shape J /- Interface to the `has_colimit` class. -/ /-- The chosen colimit cocone of a functor. -/ def colimit.cocone (F : J ⥤ C) [has_colimit F] : cocone F := has_colimit.cocone /-- The chosen colimit object of a functor. -/ def colimit (F : J ⥤ C) [has_colimit F] := (colimit.cocone F).X /-- The coprojection from a value of the functor to the chosen colimit object. -/ def colimit.ι (F : J ⥤ C) [has_colimit F] (j : J) : F.obj j ⟶ colimit F := (colimit.cocone F).ι.app j @[simp] lemma colimit.cocone_ι {F : J ⥤ C} [has_colimit F] (j : J) : (colimit.cocone F).ι.app j = colimit.ι _ j := rfl @[simp] lemma colimit.w (F : J ⥤ C) [has_colimit F] {j j' : J} (f : j ⟶ j') : F.map f ≫ colimit.ι F j' = colimit.ι F j := (colimit.cocone F).w f /-- Evidence that the chosen cocone is a colimit cocone. -/ def colimit.is_colimit (F : J ⥤ C) [has_colimit F] : is_colimit (colimit.cocone F) := has_colimit.is_colimit.{v} /-- The morphism from the chosen colimit object to the cone point of any other cocone. -/ def colimit.desc (F : J ⥤ C) [has_colimit F] (c : cocone F) : colimit F ⟶ c.X := (colimit.is_colimit F).desc c @[simp] lemma colimit.is_colimit_desc {F : J ⥤ C} [has_colimit F] (c : cocone F) : (colimit.is_colimit F).desc c = colimit.desc F c := rfl /-- We have lots of lemmas describing how to simplify `colimit.ι F j ≫ _`, and combined with `colimit.ext` we rely on these lemmas for many calculations. However, since `category.assoc` is a `@[simp]` lemma, often expressions are right associated, and it's hard to apply these lemmas about `colimit.ι`. We thus use `reassoc` to define additional `@[simp]` lemmas, with an arbitrary extra morphism. (see `tactic/reassoc_axiom.lean`) -/ @[simp, reassoc] lemma colimit.ι_desc {F : J ⥤ C} [has_colimit F] (c : cocone F) (j : J) : colimit.ι F j ≫ colimit.desc F c = c.ι.app j := is_colimit.fac _ c j /-- The cocone morphism from the chosen colimit cocone to any cocone. -/ def colimit.cocone_morphism {F : J ⥤ C} [has_colimit F] (c : cocone F) : (colimit.cocone F) ⟶ c := (colimit.is_colimit F).desc_cocone_morphism c @[simp] lemma colimit.cocone_morphism_hom {F : J ⥤ C} [has_colimit F] (c : cocone F) : (colimit.cocone_morphism c).hom = colimit.desc F c := rfl lemma colimit.ι_cocone_morphism {F : J ⥤ C} [has_colimit F] (c : cocone F) (j : J) : colimit.ι F j ≫ (colimit.cocone_morphism c).hom = c.ι.app j := by simp @[ext] lemma colimit.hom_ext {F : J ⥤ C} [has_colimit F] {X : C} {f f' : colimit F ⟶ X} (w : ∀ j, colimit.ι F j ≫ f = colimit.ι F j ≫ f') : f = f' := (colimit.is_colimit F).hom_ext w /-- The isomorphism (in `Type`) between morphisms from the colimit object to a specified object `W`, and cocones with cone point `W`. -/ def colimit.hom_iso (F : J ⥤ C) [has_colimit F] (W : C) : (colimit F ⟶ W) ≅ (F.cocones.obj W) := (colimit.is_colimit F).hom_iso W @[simp] lemma colimit.hom_iso_hom (F : J ⥤ C) [has_colimit F] {W : C} (f : colimit F ⟶ W) : (colimit.hom_iso F W).hom f = (colimit.cocone F).ι ≫ (const J).map f := (colimit.is_colimit F).hom_iso_hom f /-- The isomorphism (in `Type`) between morphisms from the colimit object to a specified object `W`, and an explicit componentwise description of cocones with cone point `W`. -/ def colimit.hom_iso' (F : J ⥤ C) [has_colimit F] (W : C) : ((colimit F ⟶ W) : Type v) ≅ { p : Π j, F.obj j ⟶ W // ∀ {j j'} (f : j ⟶ j'), F.map f ≫ p j' = p j } := (colimit.is_colimit F).hom_iso' W lemma colimit.desc_extend (F : J ⥤ C) [has_colimit F] (c : cocone F) {X : C} (f : c.X ⟶ X) : colimit.desc F (c.extend f) = colimit.desc F c ≫ f := begin ext1, rw [←category.assoc], simp end /-- If we've chosen a colimit for a functor `F`, we can transport that choice across a natural isomorphism. -/ -- This has the isomorphism pointing in the opposite direction than in `has_limit_of_iso`. -- This is intentional; it seems to help with elaboration. def has_colimit_of_iso {F G : J ⥤ C} [has_colimit F] (α : G ≅ F) : has_colimit G := { cocone := (cocones.precompose α.hom).obj (colimit.cocone F), is_colimit := { desc := λ s, colimit.desc F ((cocones.precompose α.inv).obj s), fac' := λ s j, begin rw [cocones.precompose_obj_ι, nat_trans.comp_app, colimit.cocone_ι], rw [category.assoc, colimit.ι_desc, ←nat_iso.app_hom, ←iso.eq_inv_comp], refl end, uniq' := λ s m w, begin apply colimit.hom_ext, intro j, rw [colimit.ι_desc, cocones.precompose_obj_ι, nat_trans.comp_app, ←nat_iso.app_inv, iso.eq_inv_comp], simpa using w j end } } /-- If a functor `G` has the same collection of cocones as a functor `F` which has a colimit, then `G` also has a colimit. -/ def has_colimit.of_cocones_iso {J K : Type v} [small_category J] [small_category K] (F : J ⥤ C) (G : K ⥤ C) (h : F.cocones ≅ G.cocones) [has_colimit F] : has_colimit G := ⟨_, is_colimit.of_nat_iso ((is_colimit.nat_iso (colimit.is_colimit F)) ≪≫ h)⟩ section pre variables (F) [has_colimit F] (E : K ⥤ J) [has_colimit (E ⋙ F)] /-- The canonical morphism from the chosen colimit of `E ⋙ F` to the chosen colimit of `F`. -/ def colimit.pre : colimit (E ⋙ F) ⟶ colimit F := colimit.desc (E ⋙ F) { X := colimit F, ι := { app := λ k, colimit.ι F (E.obj k) } } @[simp, reassoc] lemma colimit.ι_pre (k : K) : colimit.ι (E ⋙ F) k ≫ colimit.pre F E = colimit.ι F (E.obj k) := by erw is_colimit.fac @[simp] lemma colimit.pre_desc (c : cocone F) : colimit.pre F E ≫ colimit.desc F c = colimit.desc (E ⋙ F) (c.whisker E) := by ext; rw [←assoc, colimit.ι_pre]; simp variables {L : Type v} [small_category L] variables (D : L ⥤ K) [has_colimit (D ⋙ E ⋙ F)] @[simp] lemma colimit.pre_pre : colimit.pre (E ⋙ F) D ≫ colimit.pre F E = colimit.pre F (D ⋙ E) := begin ext j, rw [←assoc, colimit.ι_pre, colimit.ι_pre], letI : has_colimit ((D ⋙ E) ⋙ F) := show has_colimit (D ⋙ E ⋙ F), by apply_instance, exact (colimit.ι_pre F (D ⋙ E) j).symm end end pre section post variables {D : Type u'} [category.{v} D] variables (F) [has_colimit F] (G : C ⥤ D) [has_colimit (F ⋙ G)] /-- The canonical morphism from `G` applied to the chosen colimit of `F ⋙ G` to `G` applied to the chosen colimit of `F`. -/ def colimit.post : colimit (F ⋙ G) ⟶ G.obj (colimit F) := colimit.desc (F ⋙ G) { X := G.obj (colimit F), ι := { app := λ j, G.map (colimit.ι F j), naturality' := by intros j j' f; erw [←G.map_comp, limits.cocone.w, comp_id]; refl } } @[simp, reassoc] lemma colimit.ι_post (j : J) : colimit.ι (F ⋙ G) j ≫ colimit.post F G = G.map (colimit.ι F j) := by erw is_colimit.fac @[simp] lemma colimit.post_desc (c : cocone F) : colimit.post F G ≫ G.map (colimit.desc F c) = colimit.desc (F ⋙ G) (G.map_cocone c) := by ext; rw [←assoc, colimit.ι_post, ←G.map_comp, colimit.ι_desc, colimit.ι_desc]; refl @[simp] lemma colimit.post_post {E : Type u''} [category.{v} E] (H : D ⥤ E) [has_colimit ((F ⋙ G) ⋙ H)] : /- H G (colimit F) ⟶ H (colimit (F ⋙ G)) ⟶ colimit ((F ⋙ G) ⋙ H) equals -/ /- H G (colimit F) ⟶ colimit (F ⋙ (G ⋙ H)) -/ colimit.post (F ⋙ G) H ≫ H.map (colimit.post F G) = colimit.post F (G ⋙ H) := begin ext, rw [←assoc, colimit.ι_post, ←H.map_comp, colimit.ι_post], exact (colimit.ι_post F (G ⋙ H) j).symm end end post lemma colimit.pre_post {D : Type u'} [category.{v} D] (E : K ⥤ J) (F : J ⥤ C) (G : C ⥤ D) [has_colimit F] [has_colimit (E ⋙ F)] [has_colimit (F ⋙ G)] [has_colimit ((E ⋙ F) ⋙ G)] : /- G (colimit F) ⟶ G (colimit (E ⋙ F)) ⟶ colimit ((E ⋙ F) ⋙ G) vs -/ /- G (colimit F) ⟶ colimit F ⋙ G ⟶ colimit (E ⋙ (F ⋙ G)) or -/ colimit.post (E ⋙ F) G ≫ G.map (colimit.pre F E) = colimit.pre (F ⋙ G) E ≫ colimit.post F G := begin ext, rw [←assoc, colimit.ι_post, ←G.map_comp, colimit.ι_pre, ←assoc], letI : has_colimit (E ⋙ F ⋙ G) := show has_colimit ((E ⋙ F) ⋙ G), by apply_instance, erw [colimit.ι_pre (F ⋙ G) E j, colimit.ι_post] end open category_theory.equivalence instance has_colimit_equivalence_comp (e : K ≌ J) [has_colimit F] : has_colimit (e.functor ⋙ F) := { cocone := cocone.whisker e.functor (colimit.cocone F), is_colimit := let e' := cocones.precompose (e.inv_fun_id_assoc F).inv in { desc := λ s, colimit.desc F (e'.obj (cocone.whisker e.inverse s)), fac' := λ s j, begin dsimp, rw [colimit.ι_desc], dsimp [e'], erw [inv_fun_id_assoc_inv_app, ←functor_unit, s.ι.naturality, comp_id], refl end, uniq' := λ s m w, begin apply colimit.hom_ext, intro j, erw [colimit.ι_desc], have := w (e.inverse.obj j), simp at this, erw [←colimit.w F (e.counit_iso.hom.app j)] at this, erw [assoc, ←iso.eq_inv_comp (F.map_iso $ e.counit_iso.app j)] at this, erw [this], simp end } } /-- If a `E ⋙ F` has a chosen colimit, and `E` is an equivalence, we can construct a chosen colimit of `F`. -/ def has_colimit_of_equivalence_comp (e : K ≌ J) [has_colimit (e.functor ⋙ F)] : has_colimit F := begin haveI : has_colimit (e.inverse ⋙ e.functor ⋙ F) := limits.has_colimit_equivalence_comp e.symm, apply has_colimit_of_iso (e.inv_fun_id_assoc F).symm, end section colim_functor variables [has_colimits_of_shape J C] /-- `colimit F` is functorial in `F`, when `C` has all colimits of shape `J`. -/ def colim : (J ⥤ C) ⥤ C := { obj := λ F, colimit F, map := λ F G α, colimit.desc F { X := colimit G, ι := { app := λ j, α.app j ≫ colimit.ι G j, naturality' := λ j j' f, by erw [comp_id, ←assoc, α.naturality, assoc, colimit.w] } }, map_comp' := λ F G H α β, by ext; erw [←assoc, is_colimit.fac, is_colimit.fac, assoc, is_colimit.fac, ←assoc]; refl } variables {F} {G : J ⥤ C} (α : F ⟶ G) @[simp, reassoc] lemma colimit.ι_map (j : J) : colimit.ι F j ≫ colim.map α = α.app j ≫ colimit.ι G j := by apply is_colimit.fac @[simp] lemma colimit.map_desc (c : cocone G) : colim.map α ≫ colimit.desc G c = colimit.desc F ((cocones.precompose α).obj c) := by ext; rw [←assoc, colimit.ι_map, assoc, colimit.ι_desc, colimit.ι_desc]; refl lemma colimit.pre_map [has_colimits_of_shape K C] (E : K ⥤ J) : colimit.pre F E ≫ colim.map α = colim.map (whisker_left E α) ≫ colimit.pre G E := by ext; rw [←assoc, colimit.ι_pre, colimit.ι_map, ←assoc, colimit.ι_map, assoc, colimit.ι_pre]; refl lemma colimit.pre_map' [has_colimits_of_shape.{v} K C] (F : J ⥤ C) {E₁ E₂ : K ⥤ J} (α : E₁ ⟶ E₂) : colimit.pre F E₁ = colim.map (whisker_right α F) ≫ colimit.pre F E₂ := by ext1; simp [← category.assoc] lemma colimit.pre_id (F : J ⥤ C) : colimit.pre F (𝟭 _) = colim.map (functor.left_unitor F).hom := by tidy lemma colimit.map_post {D : Type u'} [category.{v} D] [has_colimits_of_shape J D] (H : C ⥤ D) : /- H (colimit F) ⟶ H (colimit G) ⟶ colimit (G ⋙ H) vs H (colimit F) ⟶ colimit (F ⋙ H) ⟶ colimit (G ⋙ H) -/ colimit.post F H ≫ H.map (colim.map α) = colim.map (whisker_right α H) ≫ colimit.post G H:= begin ext, rw [←assoc, colimit.ι_post, ←H.map_comp, colimit.ι_map, H.map_comp], rw [←assoc, colimit.ι_map, assoc, colimit.ι_post], refl end /-- The isomorphism between morphisms from the cone point of the chosen colimit cocone for `F` to `W` and cocones over `F` with cone point `W` is natural in `F`. -/ def colim_coyoneda : colim.op ⋙ coyoneda ≅ category_theory.cocones J C := nat_iso.of_components (λ F, nat_iso.of_components (colimit.hom_iso (unop F)) (by tidy)) (by tidy) end colim_functor /-- We can transport chosen colimits of shape `J` along an equivalence `J ≌ J'`. -/ def has_colimits_of_shape_of_equivalence {J' : Type v} [small_category J'] (e : J ≌ J') [has_colimits_of_shape J C] : has_colimits_of_shape J' C := by { constructor, intro F, apply has_colimit_of_equivalence_comp e, apply_instance } end colimit end category_theory.limits
a98abc40df81db052536565682e0e9721581f675
d436468d80b739ba7e06843c4d0d2070e43448e5
/src/category_theory/monoidal/of_has_finite_products.lean
57c8c2295e803ea9c9217e6ab3e26c8aba4923c6
[ "Apache-2.0" ]
permissive
roro47/mathlib
761fdc002aef92f77818f3fef06bf6ec6fc1a28e
80aa7d52537571a2ca62a3fdf71c9533a09422cf
refs/heads/master
1,599,656,410,625
1,573,649,488,000
1,573,649,488,000
221,452,951
0
0
Apache-2.0
1,573,647,693,000
1,573,647,692,000
null
UTF-8
Lean
false
false
2,212
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Simon Hudon -/ import category_theory.monoidal.category import category_theory.limits.shapes.finite_products import category_theory.limits.shapes.binary_products import category_theory.limits.shapes.terminal import category_theory.limits.types /-! # The natural monoidal structure on any category with finite (co)products. A category with a monoidal structure provided in this way is sometimes called a (co)cartesian category, although this is also sometimes used to mean a finitely complete category. (See https://ncatlab.org/nlab/show/cartesian+category.) As this works with either products or coproducts, we don't set up either construct as an instance. -/ open category_theory.limits universes v u namespace category_theory section variables (C : Type u) [𝒞 : category.{v} C] include 𝒞 local attribute [tidy] tactic.case_bash /-- A category with finite products has a natural monoidal structure. -/ def monoidal_of_has_finite_products [has_finite_products.{v} C] : monoidal_category C := { tensor_unit := terminal C, tensor_obj := λ X Y, limits.prod X Y, tensor_hom := λ _ _ _ _ f g, limits.prod.map f g, associator := prod.associator, left_unitor := prod.left_unitor, right_unitor := prod.right_unitor, pentagon' := prod.pentagon, triangle' := prod.triangle, associator_naturality' := @prod.associator_naturality _ _ _, } /-- A category with finite coproducts has a natural monoidal structure. -/ def monoidal_of_has_finite_coproducts [has_finite_coproducts.{v} C] : monoidal_category C := { tensor_unit := initial C, tensor_obj := λ X Y, limits.coprod X Y, tensor_hom := λ _ _ _ _ f g, limits.coprod.map f g, associator := coprod.associator, left_unitor := coprod.left_unitor, right_unitor := coprod.right_unitor, pentagon' := coprod.pentagon, triangle' := coprod.triangle, associator_naturality' := @coprod.associator_naturality _ _ _, } end end category_theory -- TODO in fact, a category with finite products is braided, and symmetric, -- and we should say that here.
72bbc3fa2b4322d0045b6cd80e6e58d22d77cddc
6f1049e897f569e5c47237de40321e62f0181948
/src/exercises/09_limits_final.lean
bbad8fe10c5ae4749121e65c0ac9cd46d1fe3e3b
[ "Apache-2.0" ]
permissive
anrddh/tutorials
f654a0807b9523608544836d9a81939f8e1dceb8
3ba43804e7b632201c494cdaa8da5406f1a255f9
refs/heads/master
1,655,542,921,827
1,588,846,595,000
1,588,846,595,000
262,330,134
0
0
null
1,588,944,346,000
1,588,944,345,000
null
UTF-8
Lean
false
false
7,189
lean
import tuto_lib set_option pp.beta true set_option pp.coercions false /- This is the final file in this series. Here we use everything covered in previous files to prove a couple of famous theorems from elementary real analysis. Of course they all have more general versions in mathlib. As usual, keep in mind: abs_le (x y : ℝ) : |x| ≤ y ↔ -y ≤ x ∧ x ≤ y ge_max_iff (p q r) : r ≥ max p q ↔ r ≥ p ∧ r ≥ q le_max_left p q : p ≤ max p q le_max_right p q : q ≤ max p q as well as a lemma from the previous file: le_of_le_add_all : (∀ ε > 0, y ≤ x + ε) → y ≤ x Let's start with a variation on a known exercise. -/ -- 0071 lemma le_lim {x y : ℝ} {u : ℕ → ℝ} (hu : seq_limit u x) (ineg : ∃ N, ∀ n ≥ N, y ≤ u n) : y ≤ x := begin sorry end /- Let's now return to the result proved in the 0th file of this series, and reprove the sequential characterization of upper bounds (with a slighly different proof). For this, and other exercises below, we'll need many things proved in previous files, and a couple of extras. From the 5th file: limit_const (x : ℝ) : seq_limit (λ n, x) x squeeze (lim_u : seq_limit u l) (lim_w : seq_limit w l) (hu : ∀ n, u n ≤ v n) (hw : ∀ n, v n ≤ w n) : seq_limit v l From the 8th: def upper_bound (A : set ℝ) (x : ℝ) := ∀ a ∈ A, a ≤ x def is_sup (A : set ℝ) (x : ℝ) := upper_bound A x ∧ ∀ y, upper_bound A y → x ≤ y lt_sup (hx : is_sup A x) : ∀ y, y < x → ∃ a ∈ A, y < a := You can also use inv_succ_pos : ∀ n : ℕ, 1/(n + 1 : ℝ) > 0 inv_succ_le_all : ∀ ε > 0, ∃ N : ℕ, ∀ n ≥ N, 1/(n + 1 : ℝ) ≤ ε and their easy consequences: limit_of_sub_le_inv_succ (h : ∀ n, |u n - x| ≤ 1/(n+1)) : seq_limit u x limit_const_add_inv_succ (x : ℝ) : seq_limit (λ n, x + 1/(n+1)) x limit_const_sub_inv_succ (x : ℝ) : seq_limit (λ n, x - 1/(n+1)) x The structure of the proof is offered. It features a new tactic: `choose` which invokes the axiom of choice (observing the tactic state before and after using it should be enough to understand everything). -/ -- 0072 lemma is_sup_iff (A : set ℝ) (x : ℝ) : (is_sup A x) ↔ (upper_bound A x ∧ ∃ u : ℕ → ℝ, seq_limit u x ∧ ∀ n, u n ∈ A ) := begin split, { intro h, split, { sorry }, { have : ∀ n : ℕ, ∃ a ∈ A, x - 1/(n+1) < a, { intros n, have : 1/(n+1 : ℝ) > 0, exact nat.one_div_pos_of_nat, sorry }, choose u hu using this, sorry } }, { rintro ⟨maj, u, limu, u_in⟩, sorry }, end /-- Continuity of a function at a point -/ def continuous_at_pt (f : ℝ → ℝ) (x₀ : ℝ) : Prop := ∀ ε > 0, ∃ δ > 0, ∀ x, |x - x₀| ≤ δ → |f x - f x₀| ≤ ε variables {f : ℝ → ℝ} {x₀ : ℝ} {u : ℕ → ℝ} -- 0073 lemma seq_continuous_of_continuous (hf : continuous_at_pt f x₀) (hu : seq_limit u x₀) : seq_limit (f ∘ u) (f x₀) := begin sorry end -- 0074 example : (∀ u : ℕ → ℝ, seq_limit u x₀ → seq_limit (f ∘ u) (f x₀)) → continuous_at_pt f x₀ := begin sorry end /- Recall from the 6th file: def extraction (φ : ℕ → ℕ) := ∀ n m, n < m → φ n < φ m def cluster_point (u : ℕ → ℝ) (a : ℝ) := ∃ φ, extraction φ ∧ seq_limit (u ∘ φ) a id_le_extraction : extraction φ → ∀ n, n ≤ φ n and from the 8th file: def tendsto_infinity (u : ℕ → ℝ) := ∀ A, ∃ N, ∀ n ≥ N, u n ≥ A not_seq_limit_of_tendstoinfinity : tendsto_infinity u → ∀ l, ¬ seq_limit u l -/ variables {φ : ℕ → ℕ} -- 0075 lemma subseq_tenstoinfinity (h : tendsto_infinity u) (hφ : extraction φ) : tendsto_infinity (u ∘ φ) := begin sorry end -- 0076 lemma squeeze_infinity {u v : ℕ → ℝ} (hu : tendsto_infinity u) (huv : ∀ n, u n ≤ v n) : tendsto_infinity v := begin sorry end /- We will use segments Icc a b := { x | a ≤ x ∧ x ≤ b } The notation stands for Interval-closed-closed. Variations exist with o or i instead of c, where o stands for open and i for infinity. We will use the following version of Bolzano-Weirstrass bolzano_weierstrass (h : ∀ n, u n ∈ [a, b]) : ∃ c ∈ [a, b], cluster_point u c as well as the obvious seq_limit_id : tendsto_infinity (λ n, n) -/ open set -- 0077 lemma bdd_above_segment {f : ℝ → ℝ} {a b : ℝ} (hf : ∀ x ∈ Icc a b, continuous_at_pt f x) : ∃ M, ∀ x ∈ Icc a b, f x ≤ M := begin sorry end /- In the next exercice, we can use: abs_neg x : |-x| = |x| -/ -- 0078 lemma continuous_opposite {f : ℝ → ℝ} {x₀ : ℝ} (h : continuous_at_pt f x₀) : continuous_at_pt (λ x, -f x) x₀ := begin sorry end /- Now let's combine the two exercices above -/ -- 0079 lemma bdd_below_segment {f : ℝ → ℝ} {a b : ℝ} (hf : ∀ x ∈ Icc a b, continuous_at_pt f x) : ∃ m, ∀ x ∈ Icc a b, m ≤ f x := begin sorry end /- Remember from the 5th file: unique_limit : seq_limit u l → seq_limit u l' → l = l' and from the 6th one: subseq_tendsto_of_tendsto (h : seq_limit u l) (hφ : extraction φ) : seq_limit (u ∘ φ) l We now admit the following version of the least upper bound theorem (that cannot be proved without discussing the construction of real numbers or admitting another strong theorem). sup_segment {a b : ℝ} {A : set ℝ} (hnonvide : ∃ x, x ∈ A) (h : A ⊆ Icc a b) : ∃ x ∈ Icc a b, is_sup A x In the next exercise, it can be useful to prove inclusions of sets of real number. By definition, A ⊆ B means : ∀ x, x ∈ A → x ∈ B. Hence one can start a proof of A ⊆ B by `intros x x_in`, which brings `x : ℝ` and `x_in : x ∈ A` in the local context, and then prove `x ∈ B`. Note also the use of {x | P x} which denotes the set of x satisfying predicate P. Hence `x' ∈ { x | P x} ↔ P x'`, by definition. -/ -- 0080 example {a b : ℝ} (hab : a ≤ b) (hf : ∀ x ∈ Icc a b, continuous_at_pt f x) : ∃ x₀ ∈ Icc a b, ∀ x ∈ Icc a b, f x ≤ f x₀ := begin sorry end lemma stupid {a b x : ℝ} (h : x ∈ Icc a b) (h' : x ≠ b) : x < b := lt_of_le_of_ne h.right h' /- And now the final boss... -/ def I := (Icc 0 1 : set ℝ) -- the type ascription makes sure 0 and 1 are real numbers here -- 0081 example (f : ℝ → ℝ) (hf : ∀ x, continuous_at_pt f x) (h₀ : f 0 < 0) (h₁ : f 1 > 0) : ∃ x₀ ∈ I, f x₀ = 0 := begin let A := { x | x ∈ I ∧ f x < 0}, have ex_x₀ : ∃ x₀ ∈ I, is_sup A x₀, { sorry }, rcases ex_x₀ with ⟨x₀, x₀_in, x₀_sup⟩, use [x₀, x₀_in], have : f x₀ ≤ 0, { sorry }, have x₀_1: x₀ < 1, { sorry }, have : f x₀ ≥ 0, { have dans : ∃ N : ℕ, ∀ n ≥ N, x₀ + 1/(n+1) ∈ I, { have : ∃ N : ℕ, ∀ n≥ N, 1/(n+1 : ℝ) ≤ 1-x₀, { sorry }, sorry }, have not_in : ∀ n : ℕ, x₀ + 1/(n+1) ∉ A, -- By definition, x ∉ A means ¬ (x ∈ A). { sorry }, dsimp [A] at not_in, -- This is useful to unfold a let sorry }, linarith, end
ae7f69a9ed71faf5cff4e06c85c7211aab14d0a8
9dd3f3912f7321eb58ee9aa8f21778ad6221f87c
/library/init/native/cf.lean
5528ee77887ecf6ed6b95463053256eeae612a7a
[ "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
2,483
lean
/- Copyright (c) 2016 Jared Roesch. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jared Roesch -/ prelude import init.meta.format import init.meta.expr import init.data.string import init.category.state import init.native.ir import init.native.format import init.native.builtin import init.native.util import init.native.pass import init.native.procedure import init.native.internal import init.native.config open native namespace cf @[reducible] meta def cf_state := config × nat @[reducible] meta def cf_monad := state cf_state meta def when_debug (action : cf_monad unit) : cf_monad unit := do (config, _) ← state.read, if config.debug config then action else return () -- point at the code where you can't synthesize? -- the error behavior here seems bad if you replace the unit -- with `u` meta def trace_cf (s : string) : cf_monad unit := when_debug (trace s (return ())) meta def fresh_name : cf_monad name := do (config, count) ← state.read, -- need to replace this with unique prefix as per our earlier conversation n ← pure $ name.mk_numeral (unsigned.of_nat count) `_anf_, state.write (config, count + 1), return n private meta def cf_case (action : expr → cf_monad expr) (e : expr) : cf_monad expr := do under_lambda fresh_name (fun e', action e') e private meta def cf_cases_on (head : expr) (args : list expr) (cf : expr → cf_monad expr) : cf_monad expr := match args with | [] := return $ mk_call head [] | (scrut :: cases) := do trace_cf "inside cases on", cases' ← monad.mapm (cf_case cf) cases, return $ mk_call head (scrut :: cases') end meta def cf' : expr → cf_monad expr | (expr.elet n ty val body) := expr.elet n ty val <$> (cf' body) | (expr.app f arg) := do trace_cf "processing app", let fn := expr.get_app_fn (expr.app f arg), let args := expr.get_app_args (expr.app f arg), if is_cases_on fn then cf_cases_on fn args cf' else return (mk_call (expr.const `native_compiler.return []) [(expr.app f arg)]) | e := return $ expr.app (expr.const `native_compiler.return []) e meta def init_state : config → cf_state := fun c, (c, 0) end cf private meta def cf_transform (conf : config) (e : expr) : expr := prod.fst $ (under_lambda cf.fresh_name cf.cf' e) (cf.init_state conf) meta def cf : pass := { name := "control_flow", transform := fun conf proc, procedure.map_body (fun e, cf_transform conf e) proc }
9903a04abdf3b90b3418cdfc1f27aebeacce0233
6df8d5ae3acf20ad0d7f0247d2cee1957ef96df1
/HW/hw6_prop_logic_and_satifiability.lean
287993b891bdca7318a03e5ca4eab9ac5d48fec8
[]
no_license
derekjohnsonva/CS2102
8ed45daa6658e6121bac0f6691eac6147d08246d
b3f507d4be824a2511838a1054d04fc9aef3304c
refs/heads/master
1,648,529,162,527
1,578,851,859,000
1,578,851,859,000
233,433,207
0
0
null
null
null
null
UTF-8
Lean
false
false
9,588
lean
namespace prop_logic /- This assignment has five problems. The first is to extend our propositional logic syntax and semantics to support the three additional connectives, exclusive or (⊕), implies (which we will write as ⇒), and if and only iff (↔). We first give you the definitions developed in class. You are to extend/modify them to support expressions with the new connectives. The remaining problems use this definition of our language of expressions in propositional logic. -/ /- 1. Extend our syntax and semantics for propositional logic to support the xor, implies, and iff and only iff connectives/operators. A. Add support for the exclusive or connective/operator. Define the symbol, ⊕, as an infix notation. Here are specific steps to take for the exclusive or connective, as an example. 1. Add new binary connective, xorOp 2. Add pXor as shorthand for binOpExp xorOp 3. Add ⊕ as an infix notation for pXor 4. Specify the interpretation of ⊕ to be bxor 5. Extend interpBinOp to handle the new case Then add support for the implies connective, using the symbol, ⇒, as an infix operator. We can't use → because it's reserved by Lean and cannot be overloaded. Lean does not have a Boolean implies operator (analogous to bor), so you will have to define one. Call it bimpl. Finally add support for if and only iff. Use the symbol ↔ as an infix notation. You will have to define a Boolean function as Lean does not provide one for iff. Call it biff. Here is the code as developed in class. Now review the step-by-step instructions, and proceed to read and midify this logic as required. We've bracketed areas where new material will have to be added. -/ /- *** SYNTAX *** -/ inductive var : Type | mkVar : ℕ → var inductive unOp : Type | notOp inductive binOp : Type | andOp | orOp /-HW-/ -- add new binOps here | xorOp | impOp | iffOp /-HW-/ inductive pExp : Type | litExp : bool → pExp | varExp : var → pExp | unOpExp : unOp → pExp → pExp | binOpExp : binOp → pExp → pExp → pExp open var open pExp open unOp open binOp -- Shorthand notations def pTrue := litExp tt def pFalse := litExp ff def pNot := unOpExp notOp def pAnd := binOpExp andOp def pOr := binOpExp orOp /-HW-/ -- Add new operator application -- shorthands here. -- Add pXor as shorthand for binOpExp xorOp def pXor := binOpExp xorOp def pImple := binOpExp impOp def pIff := binOpExp iffOp /-HW-/ -- conventional notation notation e1 ∧ e2 := pAnd e1 e2 notation e1 ∨ e2 := pOr e1 e2 notation ¬ e := pNot e /-HW-/ -- Add new notations here -- Add ⊕ as an infix notation for pXor notation e1 ⊕ e2 := pXor e1 e2 notation e1 ⇒ e2 := pImple e1 e2 notation e1 ↔ e2 := pIff e1 e2 /-HW-/ /- ***************** *** SEMANTICS *** ***************** -/ def interpUnOp : unOp → (bool → bool) | notOp := bnot /-HW-/ -- Add Boolean function definitions here -- Specify the interpretation of ⊕ to be bxor def bimpl : bool → bool → bool | tt tt := tt | tt ff := ff | ff tt := tt | ff ff := tt def biff : bool → bool → bool | tt tt := tt | tt ff := ff | ff tt := ff | ff ff := tt /-HW-/ def interpBinOp : binOp → (bool → bool → bool) | andOp := band | orOp := bor | xorOp := bxor | impOp := bimpl | iffOp := biff /-HW-/ -- Add cases for new binOps here -- Extend interpBinOp to handle the new case /-HW-/ /- *** SEMANTICS *** -/ /- Given a pExp and an interpretation for the variables, compute and return the Boolean value of the expression. -/ def pEval : pExp → (var → bool) → bool | (litExp b) i := b | (varExp v) i := i v | (unOpExp op e) i := (interpUnOp op) (pEval e i) | (binOpExp op e1 e2) i := (interpBinOp op) (pEval e1 i) (pEval e2 i) /- Note: You are free to use pEval, if you wish to, to check answers to some of the questions below. It is not mandatory and you will not be marked down for not doing this. -/ /- #2. Define X, Y, and Z to be variable expressions bound to a different variable expression terms. Hint: Look at the prop_logic_test.lean file to remind yourself how we did this in class. -/ def varX := mkVar 0 def varY := mkVar 1 def varZ := mkVar 2 def X : pExp:= varExp varX def Y : pExp := varExp varY def Z : pExp := varExp varZ /- #3. Here are some English language sentences that you are to re-express in propositional logic. Here's one example. -/ /- EXAMPLE: Formalize the following proposition, as a formula in propositional logic: If it's raining then it's raining. -/ -- Use R to represent "it's raining" def R : pExp := varExp (mkVar 4) -- Solution here def ex1 := R ⇒ R /- Explanation: We first choose to represent the smaller proposition, "it's raining", by the variable expression, R. We then formalize the overall natural language expression, if R then R, as the formula, R ⇒ R. Note: R ⇒ R can be pronounced as any of: - if R is true then R is true - if R then R - the truth of R implies the truth of R - R implies R The second and fourth pronounciations are the two that we prefer to use. -/ /- For the remaining problems, use the variables expressions, X, Y, and Z, as already defined. Use parentheses if needed to group sub-expressions. -/ /- A. If it's raining and the streets are wet then it's raining. -/ def p2 : pExp := (X ∧ Y) ⇒ X /- B. If it's raining and the streets are wet, then the streets are wet and it's raining. -/ def p3 := (X ∧ Y) ⇒ (Y ∧ X) /- C. If it's raining then if the streets are wet then it's raining and the streets are wet. -/ def p4 := X ⇒ (Y ⇒ (X ∧ Y)) /- D. If it's raining then it's raining or the moon is made of green cheese. -/ def p5 := X ⇒ (X ∨ Z) /- E. If it's raining, then if it's raining implies that the streets are wet, then the streets are wet. -/ def p6 := X ⇒ (X ⇒ Y) ⇒ Y /- #4. For each of the propositional logic expressions below, write a truth table and based on your result, state whether the expression is unsatisfiable, satisfiable but not valid, or valid. Here's an example solution for the expression, (X ∧ Y) ⇒ Y. X Y X ∧ Y (X ∧ Y) ⇒ Y - - ----- ----------- T T T T T F F T F T F T F F F T The proposition is valid. -/ /- A. After each "#check" give your answer for the specified proposition. That is, write a truth table in a comment and then say whether given the proposition is valid, satisfiable but not valid, or unsatisifiable. Note: This expression reqires that you have properly specified ¬ and ⇒ as notations in our pExp language. The errors indicated in many of the following lines will go away once you have these notations properly defined. -/ #check (X ⇒ Y) ⇒ (¬ X ⇒ ¬ Y) /- -- Answer here X Y X ⇒ Y ¬ X ¬ Y (¬ X ⇒ ¬ Y) (X ⇒ Y) ⇒ (¬ X ⇒ ¬ Y) - - ----- - - ----------- ---------------------- T T T F F T T T F F F T T T F T T T F F F F F T T T T T Satifiable -/ /- B. -/ #check ((X ⇒ Y) ∧ (Y ⇒ X)) ⇒ (X ⇒ Z) /- -- Answer here X Y X ⇒ Y Y ⇒ X (X ⇒ Y) ∧ (Y ⇒ X) Z (X ⇒ Z) ((X ⇒ Y) ∧ (Y ⇒ X)) ⇒ (X ⇒ Z) - - ----- ----- ----------------- - ----- ---------------------------- T T T T T T T T T F F T F F F T F T T F F T T T F F T T T F T T Valid -/ /- C. -/ #check pFalse ⇒ (X ∧ ¬ X) /- -- Answer here pFalse X ¬ X (X ∧ ¬ X) pFalse ⇒(X ∧ ¬ X) ------ - --- ------- ----------------- F T F F T F F T F T Valid -/ /- D.≠ -/ #check pTrue ⇒(X ∧ ¬ X) -- Answer here /- pTrue X ¬ X (X ∧ ¬ X) pFalse ⇒(X ∧ ¬ X) ------ - --- ------- ----------------- T T F F F T F T F F Unsatisfiable -/ /- E. -/ #check (X ∨ Y) ∧ X ⇒ ¬ Y -- Answer here /- X Y X ∨ Y (X ∨ Y) ∧ X ¬ Y (X ∨ Y) ∧ X ⇒ ¬ Y - - ------ ---------- -- ---------------- T T T T F F T F T T T T F T T F F T F F F F T T Satisfiable but not valid -/ /- #5. A. Find and present an interpretation that causes the following proposition to be satisfied (to evaluate to true). (X ∨ Y) ∧ (¬ Y ∨ Z) Answer: X Y X ∨ Y ¬ Y Z ¬ Y ∨ Z (X ∨ Y) ∧ (¬ Y ∨ Z) - - ----- --- - ------- ------------------ T T T F T T T T F T T T T T F T T F F F F F F F T F T F The proposition will be true when X=T, Y=T, Z=T B. Count and state how many of the possible interpretations satisfy the formula. Answer; 2 -/ theorem prove_false_elim {pFalse : Prop}: false → pFalse := begin assume a, apply false.elim a, end end prop_logic
e95416883e7fe2915828cb261a894d07207c422d
08bd4ba4ca87dba1f09d2c96a26f5d65da81f4b4
/doc/examples/bintree.lean
ff62f88c42c59ec6ec45e807eb973b65bae8512f
[ "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", "Apache-2.0", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
gebner/lean4
d51c4922640a52a6f7426536ea669ef18a1d9af5
8cd9ce06843c9d42d6d6dc43d3e81e3b49dfc20f
refs/heads/master
1,685,732,780,391
1,672,962,627,000
1,673,459,398,000
373,307,283
0
0
Apache-2.0
1,691,316,730,000
1,622,669,271,000
Lean
UTF-8
Lean
false
false
10,920
lean
/-! # Binary Search Trees If the type of keys can be totally ordered -- that is, it supports a well-behaved `≤` comparison -- then maps can be implemented with binary search trees (BSTs). Insert and lookup operations on BSTs take time proportional to the height of the tree. If the tree is balanced, the operations therefore take logarithmic time. This example is based on a similar example found in the ["Sofware Foundations"](https://softwarefoundations.cis.upenn.edu/vfa-current/SearchTree.html) book (volume 3). -/ /-! We use `Nat` as the key type in our implementation of BSTs, since it has a convenient total order with lots of theorems and automation available. We leave as an exercise to the reader the generalization to arbitrary types. -/ inductive Tree (β : Type v) where | leaf | node (left : Tree β) (key : Nat) (value : β) (right : Tree β) deriving Repr /-! The function `contains` returns `true` iff the given tree contains the key `k`. -/ def Tree.contains (t : Tree β) (k : Nat) : Bool := match t with | leaf => false | node left key value right => if k < key then left.contains k else if key < k then right.contains k else true /-! `t.find? k` returns `some v` if `v` is the value bound to key `k` in the tree `t`. It returns `none` otherwise. -/ def Tree.find? (t : Tree β) (k : Nat) : Option β := match t with | leaf => none | node left key value right => if k < key then left.find? k else if key < k then right.find? k else some value /-! `t.insert k v` is the map containing all the bindings of `t` along with a binding of `k` to `v`. -/ def Tree.insert (t : Tree β) (k : Nat) (v : β) : Tree β := match t with | leaf => node leaf k v leaf | node left key value right => if k < key then node (left.insert k v) key value right else if key < k then node left key value (right.insert k v) else node left k v right /-! Let's add a new operation to our tree: converting it to an association list that contains the key--value bindings from the tree stored as pairs. If that list is sorted by the keys, then any two trees that represent the same map would be converted to the same list. Here's a function that does so with an in-order traversal of the tree. -/ def Tree.toList (t : Tree β) : List (Nat × β) := match t with | leaf => [] | node l k v r => l.toList ++ [(k, v)] ++ r.toList #eval Tree.leaf.insert 2 "two" |>.insert 3 "three" |>.insert 1 "one" #eval Tree.leaf.insert 2 "two" |>.insert 3 "three" |>.insert 1 "one" |>.toList /-! The implemention of `Tree.toList` is inefficient because of how it uses the `++` operator. On a balanced tree its running time is linearithmic, because it does a linear number of concatentations at each level of the tree. On an unbalanced tree it's quadratic time. Here's a tail-recursive implementation than runs in linear time, regardless of whether the tree is balanced: -/ def Tree.toListTR (t : Tree β) : List (Nat × β) := go t [] where go (t : Tree β) (acc : List (Nat × β)) : List (Nat × β) := match t with | leaf => acc | node l k v r => go l ((k, v) :: go r acc) /-! We now prove that `t.toList` and `t.toListTR` return the same list. The proof is on induction, and as we used the auxiliary function `go` to define `Tree.toListTR`, we use the auxiliary theorem `go` to prove the theorem. The proof of the auxiliary theorem is by induction on `t`. The `generalizing acc` modifier instructs Lean to revert `acc`, apply the induction theorem for `Tree`s, and then reintroduce `acc` in each case. By using `generalizing`, we obtain the more general induction hypotheses - `left_ih : ∀ acc, toListTR.go left acc = toList left ++ acc` - `right_ih : ∀ acc, toListTR.go right acc = toList right ++ acc` Recall that the combinator `tac <;> tac'` runs `tac` on the main goal and `tac'` on each produced goal, concatenating all goals produced by `tac'`. In this theorem, we use it to apply `simp` and close each subgoal produced by the `induction` tactic. The `simp` parameters `toListTR.go` and `toList` instruct the simplifier to try to reduce and/or apply auto generated equation theorems for these two functions. The parameter `*` intructs the simplifier to use any equation in a goal as rewriting rules. In this particular case, `simp` uses the induction hypotheses as rewriting rules. Finally, the parameter `List.append_assoc` intructs the simplifier to use the `List.append_assoc` theorem as a rewriting rule. -/ theorem Tree.toList_eq_toListTR (t : Tree β) : t.toList = t.toListTR := by simp [toListTR, go t []] where go (t : Tree β) (acc : List (Nat × β)) : toListTR.go t acc = t.toList ++ acc := by induction t generalizing acc <;> simp [toListTR.go, toList, *, List.append_assoc] /-! The `[csimp]` annotation instructs the Lean code generator to replace any `Tree.toList` with `Tree.toListTR` when generating code. -/ @[csimp] theorem Tree.toList_eq_toListTR_csimp : @Tree.toList = @Tree.toListTR := by funext β t apply toList_eq_toListTR /-! The implementations of `Tree.find?` and `Tree.insert` assume that values of type tree obey the BST invariant: for any non-empty node with key `k`, all the values of the `left` subtree are less than `k` and all the values of the right subtree are greater than `k`. But that invariant is not part of the definition of tree. So, let's formalize the BST invariant. Here's one way to do so. First, we define a helper `ForallTree` to express that idea that a predicate holds at every node of a tree: -/ inductive ForallTree (p : Nat → β → Prop) : Tree β → Prop | leaf : ForallTree p .leaf | node : ForallTree p left → p key value → ForallTree p right → ForallTree p (.node left key value right) /-! Second, we define the BST invariant: An empty tree is a BST. A non-empty tree is a BST if all its left nodes have a lesser key, its right nodes have a greater key, and the left and right subtrees are themselves BSTs. -/ inductive BST : Tree β → Prop | leaf : BST .leaf | node : ForallTree (fun k v => k < key) left → ForallTree (fun k v => key < k) right → BST left → BST right → BST (.node left key value right) /-! We can use the `macro` command to create helper tactics for organizing our proofs. The macro `have_eq x y` tries to prove `x = y` using linear arithmetic, and then immediately uses the new equality to substitute `x` with `y` everywhere in the goal. The modifier `local` specifies the scope of the macro. -/ /-- The `have_eq lhs rhs` tactic (tries to) prove that `lhs = rhs`, and then replaces `lhs` with `rhs`. -/ local macro "have_eq " lhs:term:max rhs:term:max : tactic => `(tactic| (have h : $lhs = $rhs := -- TODO: replace with linarith by simp_arith at *; apply Nat.le_antisymm <;> assumption try subst $lhs)) /-! The `by_cases' e` is just the regular `by_cases` followed by `simp` using all hypotheses in the current goal as rewriting rules. Recall that the `by_cases` tactic creates two goals. One where we have `h : e` and another one containing `h : ¬ e`. The simplier uses the `h` to rewrite `e` to `True` in the first subgoal, and `e` to `False` in the second. This is particularly useful if `e` is the condition of an `if`-statement. -/ /-- `by_cases' e` is a shorthand form `by_cases e <;> simp[*]` -/ local macro "by_cases' " e:term : tactic => `(tactic| by_cases $e <;> simp [*]) /-! We can use the attribute `[simp]` to instruct the simplifier to reduce given definitions or apply rewrite theorems. The `local` modifier limits the scope of this modification to this file. -/ attribute [local simp] Tree.insert /-! We now prove that `Tree.insert` preserves the BST invariant using induction and case analysis. Recall that the tactic `. tac` focuses on the main goal and tries to solve it using `tac`, or else fails. It is used to structure proofs in Lean. The notation `‹e›` is just syntax sugar for `(by assumption : e)`. That is, it tries to find a hypothesis `h : e`. It is useful to access hypothesis that have auto generated names (aka "inaccessible") names. -/ theorem Tree.forall_insert_of_forall (h₁ : ForallTree p t) (h₂ : p key value) : ForallTree p (t.insert key value) := by induction h₁ with | leaf => exact .node .leaf h₂ .leaf | node hl hp hr ihl ihr => rename Nat => k by_cases' key < k . exact .node ihl hp hr . by_cases' k < key . exact .node hl hp ihr . have_eq key k exact .node hl h₂ hr theorem Tree.bst_insert_of_bst {t : Tree β} (h : BST t) (key : Nat) (value : β) : BST (t.insert key value) := by induction h with | leaf => exact .node .leaf .leaf .leaf .leaf | node h₁ h₂ b₁ b₂ ih₁ ih₂ => rename Nat => k simp by_cases' key < k . exact .node (forall_insert_of_forall h₁ ‹key < k›) h₂ ih₁ b₂ . by_cases' k < key . exact .node h₁ (forall_insert_of_forall h₂ ‹k < key›) b₁ ih₂ . have_eq key k exact .node h₁ h₂ b₁ b₂ /-! Now, we define the type `BinTree` using a `Subtype` that states that only trees satisfying the BST invariant are `BinTree`s. -/ def BinTree (β : Type u) := { t : Tree β // BST t } def BinTree.mk : BinTree β := ⟨.leaf, .leaf⟩ def BinTree.contains (b : BinTree β) (k : Nat) : Bool := b.val.contains k def BinTree.find? (b : BinTree β) (k : Nat) : Option β := b.val.find? k def BinTree.insert (b : BinTree β) (k : Nat) (v : β) : BinTree β := ⟨b.val.insert k v, b.val.bst_insert_of_bst b.property k v⟩ /-! Finally, we prove that `BinTree.find?` and `BinTree.insert` satisfy the map properties. -/ attribute [local simp] BinTree.mk BinTree.contains BinTree.find? BinTree.insert Tree.find? Tree.contains Tree.insert theorem BinTree.find_mk (k : Nat) : BinTree.mk.find? k = (none : Option β) := by simp theorem BinTree.find_insert (b : BinTree β) (k : Nat) (v : β) : (b.insert k v).find? k = some v := by let ⟨t, h⟩ := b; simp induction t with simp | node left key value right ihl ihr => by_cases' k < key . cases h; apply ihl; assumption . by_cases' key < k cases h; apply ihr; assumption theorem BinTree.find_insert_of_ne (b : BinTree β) (h : k ≠ k') (v : β) : (b.insert k v).find? k' = b.find? k' := by let ⟨t, h⟩ := b; simp induction t with simp | leaf => split <;> simp <;> split <;> simp have_eq k k' contradiction | node left key value right ihl ihr => let .node hl hr bl br := h specialize ihl bl specialize ihr br by_cases' k < key; by_cases' key < k have_eq key k by_cases' k' < k; by_cases' k < k' have_eq k k' contradiction
bdc0a13e03949c6653b950ce65d43ee7f1947f69
d840a2fd78ca0ee1e172fe2cf3751030229b56f3
/lean_demo/src/inf_primes.lean
77cc380be1cfc3bf13bf29569fe57abb533a83e2
[]
no_license
stormymcstorm/VFRust_Presentation
6e1d3964ce58d97320b36314ae83021bfb55f12d
90142be25fa032464b3c4e68bc9f152213146254
refs/heads/main
1,673,178,849,384
1,605,289,504,000
1,605,289,504,000
312,644,751
0
0
null
null
null
null
UTF-8
Lean
false
false
249
lean
import data.nat.prime open nat -- A theorem stating that there are an infinite number of primes, or -- more precisely for any natural number N there exists a prime p ≥ N theorem infinite_primes: ∀ N, ∃ p ≥ N, prime p := begin sorry end
7611cc89e44db45477eb29da0fe1b8d12135bbb8
63abd62053d479eae5abf4951554e1064a4c45b4
/src/category_theory/limits/shapes/constructions/limits_of_products_and_equalizers.lean
fd9e64a3589a527b3873ea5112084d7fdee453f1
[ "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
4,886
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 category_theory.limits.shapes.equalizers import category_theory.limits.shapes.finite_products /-! # Constructing limits from products and equalizers. If a category has all products, and all equalizers, then it has all limits. Similarly, if it has all finite products, and all equalizers, then it has all finite limits. TODO: provide the dual result. -/ noncomputable theory open category_theory open opposite namespace category_theory.limits universes v u variables {C : Type u} [category.{v} C] variables {J : Type v} [small_category J] -- We hide the "implementation details" inside a namespace namespace has_limit_of_has_products_of_has_equalizers -- We assume here only that we have exactly the products we need, so that we can prove -- variations of the construction (all products gives all limits, finite products gives finite limits...) variables (F : J ⥤ C) [H₁ : has_limit (discrete.functor F.obj)] [H₂ : has_limit (discrete.functor (λ f : (Σ p : J × J, p.1 ⟶ p.2), F.obj f.1.2))] include H₁ H₂ /-- Corresponding to any functor `F : J ⥤ C`, we construct a new functor from the walking parallel pair of morphisms to `C`, given by the diagram ``` s ∏_j F j ===> Π_{f : j ⟶ j'} F j' t ``` where the two morphisms `s` and `t` are defined componentwise: * The `s_f` component is the projection `∏_j F j ⟶ F j` followed by `f`. * The `t_f` component is the projection `∏_j F j ⟶ F j'`. In a moment we prove that cones over `F` are isomorphic to cones over this new diagram. -/ @[simp] def diagram : walking_parallel_pair ⥤ C := let pi_obj := limits.pi_obj F.obj in let pi_hom := limits.pi_obj (λ f : (Σ p : J × J, p.1 ⟶ p.2), F.obj f.1.2) in let s : pi_obj ⟶ pi_hom := pi.lift (λ f : (Σ p : J × J, p.1 ⟶ p.2), pi.π F.obj f.1.1 ≫ F.map f.2) in let t : pi_obj ⟶ pi_hom := pi.lift (λ f : (Σ p : J × J, p.1 ⟶ p.2), pi.π F.obj f.1.2) in parallel_pair s t /-- The morphism from cones over the walking pair diagram `diagram F` to cones over the original diagram `F`. -/ @[simp] def cones_hom : (diagram F).cones ⟶ F.cones := { app := λ X c, { app := λ j, c.app walking_parallel_pair.zero ≫ pi.π _ j, naturality' := λ j j' f, begin have L := c.naturality walking_parallel_pair_hom.left, have R := c.naturality walking_parallel_pair_hom.right, have t := congr_arg (λ g, g ≫ pi.π _ (⟨(j, j'), f⟩ : Σ (p : J × J), p.fst ⟶ p.snd)) (R.symm.trans L), dsimp at t, dsimp, simpa only [limit.lift_π, fan.mk_π_app, category.assoc, category.id_comp] using t, end }, }. local attribute [semireducible] op unop opposite /-- The morphism from cones over the original diagram `F` to cones over the walking pair diagram `diagram F`. -/ @[simp] def cones_inv : F.cones ⟶ (diagram F).cones := { app := λ X c, begin refine (fork.of_ι _ _).π, { exact pi.lift c.app }, { ext ⟨⟨A,B⟩,f⟩, dsimp, simp only [limit.lift_π, limit.lift_π_assoc, fan.mk_π_app, category.assoc], rw ←(c.naturality f), dsimp, simp only [category.id_comp], } end, naturality' := λ X Y f, by { ext c j, cases j; tidy, } }. /-- The natural isomorphism between cones over the walking pair diagram `diagram F` and cones over the original diagram `F`. -/ def cones_iso : (diagram F).cones ≅ F.cones := { hom := cones_hom F, inv := cones_inv F, hom_inv_id' := begin ext X c j, cases j, { ext, simp }, { ext, have t := c.naturality walking_parallel_pair_hom.left, conv at t { dsimp, to_lhs, simp only [category.id_comp] }, simp [t], } end } end has_limit_of_has_products_of_has_equalizers open has_limit_of_has_products_of_has_equalizers /-- Any category with products and equalizers has all limits. See https://stacks.math.columbia.edu/tag/002N. -/ -- This is not an instance, as it is not always how one wants to construct limits! lemma limits_from_equalizers_and_products [has_products C] [has_equalizers C] : has_limits C := { has_limits_of_shape := λ J 𝒥, by exactI { has_limit := λ F, has_limit.of_cones_iso (diagram F) F (cones_iso F) } } /-- Any category with finite products and equalizers has all finite limits. See https://stacks.math.columbia.edu/tag/002O. (We do not prove equivalence with the third condition.) -/ -- This is not an instance, as it is not always how one wants to construct finite limits! lemma finite_limits_from_equalizers_and_finite_products [has_finite_products C] [has_equalizers C] : has_finite_limits C := λ J _ _, by exactI { has_limit := λ F, has_limit.of_cones_iso (diagram F) F (cones_iso F) } end category_theory.limits