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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a221473df7d88617c5b9c2c8d581d56d0789df9c | 4727251e0cd73359b15b664c3170e5d754078599 | /src/analysis/special_functions/polynomials.lean | a0292cb8fd7371d83ac9fea277686ade356b943b | [
"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 | 10,713 | lean | /-
Copyright (c) 2020 Anatole Dedecker. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Anatole Dedecker, Devon Tuma
-/
import analysis.asymptotics.asymptotic_equivalent
import analysis.asymptotics.specific_asymptotics
import data.polynomial.ring_division
/-!
# Limits related to polynomial and rational functions
This file proves basic facts about limits of polynomial and rationals functions.
The main result is `eval_is_equivalent_at_top_eval_lead`, which states that for
any polynomial `P` of degree `n` with leading coefficient `a`, the corresponding
polynomial function is equivalent to `a * x^n` as `x` goes to +∞.
We can then use this result to prove various limits for polynomial and rational
functions, depending on the degrees and leading coefficients of the considered
polynomials.
-/
open filter finset asymptotics
open_locale asymptotics polynomial topological_space
namespace polynomial
variables {𝕜 : Type*} [normed_linear_ordered_field 𝕜] (P Q : 𝕜[X])
lemma eventually_no_roots (hP : P ≠ 0) : ∀ᶠ x in filter.at_top, ¬ P.is_root x :=
begin
obtain ⟨x₀, hx₀⟩ := exists_max_root P hP,
refine filter.eventually_at_top.mpr (⟨x₀ + 1, λ x hx h, _⟩),
exact absurd (hx₀ x h) (not_le.mpr (lt_of_lt_of_le (lt_add_one x₀) hx)),
end
variables [order_topology 𝕜]
section polynomial_at_top
lemma is_equivalent_at_top_lead :
(λ x, eval x P) ~[at_top] (λ x, P.leading_coeff * x ^ P.nat_degree) :=
begin
by_cases h : P = 0,
{ simp [h] },
{ conv_rhs
{ funext,
rw [polynomial.eval_eq_sum_range, sum_range_succ] },
exact is_equivalent.refl.add_is_o (is_o.sum $ λ i hi, is_o.const_mul_left
(is_o.const_mul_right (λ hz, h $ leading_coeff_eq_zero.mp hz) $
is_o_pow_pow_at_top_of_lt (mem_range.mp hi)) _) }
end
lemma tendsto_at_top_of_leading_coeff_nonneg (hdeg : 1 ≤ P.degree) (hnng : 0 ≤ P.leading_coeff) :
tendsto (λ x, eval x P) at_top at_top :=
P.is_equivalent_at_top_lead.symm.tendsto_at_top
(tendsto_const_mul_pow_at_top (le_nat_degree_of_coe_le_degree hdeg)
(lt_of_le_of_ne hnng $ ne.symm $ mt leading_coeff_eq_zero.mp $ ne_zero_of_coe_le_degree hdeg))
lemma tendsto_at_top_iff_leading_coeff_nonneg :
tendsto (λ x, eval x P) at_top at_top ↔ 1 ≤ P.degree ∧ 0 ≤ P.leading_coeff :=
begin
refine ⟨λ h, _, λ h, tendsto_at_top_of_leading_coeff_nonneg P h.1 h.2⟩,
have : tendsto (λ x, P.leading_coeff * x ^ P.nat_degree) at_top at_top :=
is_equivalent.tendsto_at_top (is_equivalent_at_top_lead P) h,
rw tendsto_const_mul_pow_at_top_iff P.leading_coeff P.nat_degree at this,
rw [degree_eq_nat_degree (leading_coeff_ne_zero.mp (ne_of_lt this.2).symm), ← nat.cast_one],
refine ⟨with_bot.coe_le_coe.mpr this.1, le_of_lt this.2⟩,
end
lemma tendsto_at_bot_of_leading_coeff_nonpos (hdeg : 1 ≤ P.degree) (hnps : P.leading_coeff ≤ 0) :
tendsto (λ x, eval x P) at_top at_bot :=
P.is_equivalent_at_top_lead.symm.tendsto_at_bot
(tendsto_neg_const_mul_pow_at_top (le_nat_degree_of_coe_le_degree hdeg)
(lt_of_le_of_ne hnps $ mt leading_coeff_eq_zero.mp $ ne_zero_of_coe_le_degree hdeg))
lemma tendsto_at_bot_iff_leading_coeff_nonpos :
tendsto (λ x, eval x P) at_top at_bot ↔ 1 ≤ P.degree ∧ P.leading_coeff ≤ 0 :=
begin
refine ⟨λ h, _, λ h, tendsto_at_bot_of_leading_coeff_nonpos P h.1 h.2⟩,
have : tendsto (λ x, P.leading_coeff * x ^ P.nat_degree) at_top at_bot :=
(is_equivalent.tendsto_at_bot (is_equivalent_at_top_lead P) h),
rw tendsto_neg_const_mul_pow_at_top_iff P.leading_coeff P.nat_degree at this,
rw [degree_eq_nat_degree (leading_coeff_ne_zero.mp (ne_of_lt this.2)), ← nat.cast_one],
refine ⟨with_bot.coe_le_coe.mpr this.1, le_of_lt this.2⟩,
end
lemma abs_tendsto_at_top (hdeg : 1 ≤ P.degree) :
tendsto (λ x, abs $ eval x P) at_top at_top :=
begin
by_cases hP : 0 ≤ P.leading_coeff,
{ exact tendsto_abs_at_top_at_top.comp (P.tendsto_at_top_of_leading_coeff_nonneg hdeg hP)},
{ push_neg at hP,
exact tendsto_abs_at_bot_at_top.comp (P.tendsto_at_bot_of_leading_coeff_nonpos hdeg hP.le)}
end
lemma abs_is_bounded_under_iff :
is_bounded_under (≤) at_top (λ x, |eval x P|) ↔ P.degree ≤ 0 :=
begin
refine ⟨λ h, _, λ h, ⟨|P.coeff 0|, eventually_map.mpr (eventually_of_forall
(forall_imp (λ _, le_of_eq) (λ x, congr_arg abs $ trans (congr_arg (eval x)
(eq_C_of_degree_le_zero h)) (eval_C))))⟩⟩,
contrapose! h,
exact not_is_bounded_under_of_tendsto_at_top
(abs_tendsto_at_top P (nat.with_bot.one_le_iff_zero_lt.2 h))
end
lemma abs_tendsto_at_top_iff :
tendsto (λ x, abs $ eval x P) at_top at_top ↔ 1 ≤ P.degree :=
⟨λ h, nat.with_bot.one_le_iff_zero_lt.2 (not_le.mp ((mt (abs_is_bounded_under_iff P).mpr)
(not_is_bounded_under_of_tendsto_at_top h))), abs_tendsto_at_top P⟩
lemma tendsto_nhds_iff {c : 𝕜} :
tendsto (λ x, eval x P) at_top (𝓝 c) ↔ P.leading_coeff = c ∧ P.degree ≤ 0 :=
begin
refine ⟨λ h, _, λ h, _⟩,
{ have := P.is_equivalent_at_top_lead.tendsto_nhds h,
by_cases hP : P.leading_coeff = 0,
{ simp only [hP, zero_mul, tendsto_const_nhds_iff] at this,
refine ⟨trans hP this, by simp [leading_coeff_eq_zero.1 hP]⟩ },
{ rw [tendsto_const_mul_pow_nhds_iff hP, nat_degree_eq_zero_iff_degree_le_zero] at this,
exact this.symm } },
{ refine P.is_equivalent_at_top_lead.symm.tendsto_nhds _,
have : P.nat_degree = 0 := nat_degree_eq_zero_iff_degree_le_zero.2 h.2,
simp only [h.1, this, pow_zero, mul_one],
exact tendsto_const_nhds }
end
end polynomial_at_top
section polynomial_div_at_top
lemma is_equivalent_at_top_div :
(λ x, (eval x P)/(eval x Q)) ~[at_top]
λ x, P.leading_coeff/Q.leading_coeff * x^(P.nat_degree - Q.nat_degree : ℤ) :=
begin
by_cases hP : P = 0,
{ simp [hP] },
by_cases hQ : Q = 0,
{ simp [hQ] },
refine (P.is_equivalent_at_top_lead.symm.div
Q.is_equivalent_at_top_lead.symm).symm.trans
(eventually_eq.is_equivalent ((eventually_gt_at_top 0).mono $ λ x hx, _)),
simp [← div_mul_div_comm, hP, hQ, zpow_sub₀ hx.ne.symm]
end
lemma div_tendsto_zero_of_degree_lt (hdeg : P.degree < Q.degree) :
tendsto (λ x, (eval x P)/(eval x Q)) at_top (𝓝 0) :=
begin
by_cases hP : P = 0,
{ simp [hP, tendsto_const_nhds] },
rw ← nat_degree_lt_nat_degree_iff hP at hdeg,
refine (is_equivalent_at_top_div P Q).symm.tendsto_nhds _,
rw ← mul_zero,
refine (tendsto_zpow_at_top_zero _).const_mul _,
linarith
end
lemma div_tendsto_zero_iff_degree_lt (hQ : Q ≠ 0) :
tendsto (λ x, (eval x P)/(eval x Q)) at_top (𝓝 0) ↔ P.degree < Q.degree :=
begin
refine ⟨λ h, _, div_tendsto_zero_of_degree_lt P Q⟩,
by_cases hPQ : P.leading_coeff / Q.leading_coeff = 0,
{ simp only [div_eq_mul_inv, inv_eq_zero, mul_eq_zero] at hPQ,
cases hPQ with hP0 hQ0,
{ rw [leading_coeff_eq_zero.1 hP0, degree_zero],
exact bot_lt_iff_ne_bot.2 (λ hQ', hQ (degree_eq_bot.1 hQ')) },
{ exact absurd (leading_coeff_eq_zero.1 hQ0) hQ } },
{ have := (is_equivalent_at_top_div P Q).tendsto_nhds h,
rw tendsto_const_mul_zpow_at_top_zero_iff hPQ at this,
cases this with h h,
{ exact absurd h.2 hPQ },
{ rw [sub_lt_iff_lt_add, zero_add, int.coe_nat_lt] at h,
exact degree_lt_degree h.1 } }
end
lemma div_tendsto_leading_coeff_div_of_degree_eq (hdeg : P.degree = Q.degree) :
tendsto (λ x, (eval x P)/(eval x Q)) at_top (𝓝 $ P.leading_coeff / Q.leading_coeff) :=
begin
refine (is_equivalent_at_top_div P Q).symm.tendsto_nhds _,
rw show (P.nat_degree : ℤ) = Q.nat_degree, by simp [hdeg, nat_degree],
simp [tendsto_const_nhds]
end
lemma div_tendsto_at_top_of_degree_gt' (hdeg : Q.degree < P.degree)
(hpos : 0 < P.leading_coeff/Q.leading_coeff) :
tendsto (λ x, (eval x P)/(eval x Q)) at_top at_top :=
begin
have hQ : Q ≠ 0 := λ h, by {simp only [h, div_zero, leading_coeff_zero] at hpos, linarith},
rw ← nat_degree_lt_nat_degree_iff hQ at hdeg,
refine (is_equivalent_at_top_div P Q).symm.tendsto_at_top _,
apply tendsto.const_mul_at_top hpos,
apply tendsto_zpow_at_top_at_top,
linarith
end
lemma div_tendsto_at_top_of_degree_gt (hdeg : Q.degree < P.degree)
(hQ : Q ≠ 0) (hnng : 0 ≤ P.leading_coeff/Q.leading_coeff) :
tendsto (λ x, (eval x P)/(eval x Q)) at_top at_top :=
have ratio_pos : 0 < P.leading_coeff/Q.leading_coeff,
from lt_of_le_of_ne hnng
(div_ne_zero (λ h, ne_zero_of_degree_gt hdeg $ leading_coeff_eq_zero.mp h)
(λ h, hQ $ leading_coeff_eq_zero.mp h)).symm,
div_tendsto_at_top_of_degree_gt' P Q hdeg ratio_pos
lemma div_tendsto_at_bot_of_degree_gt' (hdeg : Q.degree < P.degree)
(hneg : P.leading_coeff/Q.leading_coeff < 0) :
tendsto (λ x, (eval x P)/(eval x Q)) at_top at_bot :=
begin
have hQ : Q ≠ 0 := λ h, by {simp only [h, div_zero, leading_coeff_zero] at hneg, linarith},
rw ← nat_degree_lt_nat_degree_iff hQ at hdeg,
refine (is_equivalent_at_top_div P Q).symm.tendsto_at_bot _,
apply tendsto.neg_const_mul_at_top hneg,
apply tendsto_zpow_at_top_at_top,
linarith
end
lemma div_tendsto_at_bot_of_degree_gt (hdeg : Q.degree < P.degree)
(hQ : Q ≠ 0) (hnps : P.leading_coeff/Q.leading_coeff ≤ 0) :
tendsto (λ x, (eval x P)/(eval x Q)) at_top at_bot :=
have ratio_neg : P.leading_coeff/Q.leading_coeff < 0,
from lt_of_le_of_ne hnps
(div_ne_zero (λ h, ne_zero_of_degree_gt hdeg $ leading_coeff_eq_zero.mp h)
(λ h, hQ $ leading_coeff_eq_zero.mp h)),
div_tendsto_at_bot_of_degree_gt' P Q hdeg ratio_neg
lemma abs_div_tendsto_at_top_of_degree_gt (hdeg : Q.degree < P.degree)
(hQ : Q ≠ 0) :
tendsto (λ x, |(eval x P)/(eval x Q)|) at_top at_top :=
begin
by_cases h : 0 ≤ P.leading_coeff/Q.leading_coeff,
{ exact tendsto_abs_at_top_at_top.comp (P.div_tendsto_at_top_of_degree_gt Q hdeg hQ h) },
{ push_neg at h,
exact tendsto_abs_at_bot_at_top.comp (P.div_tendsto_at_bot_of_degree_gt Q hdeg hQ h.le) }
end
end polynomial_div_at_top
theorem is_O_of_degree_le (h : P.degree ≤ Q.degree) :
is_O (λ x, eval x P) (λ x, eval x Q) filter.at_top :=
begin
by_cases hp : P = 0,
{ simpa [hp] using is_O_zero (λ x, eval x Q) filter.at_top },
{ have hq : Q ≠ 0 := ne_zero_of_degree_ge_degree h hp,
have hPQ : ∀ᶠ (x : 𝕜) in at_top, eval x Q = 0 → eval x P = 0 :=
filter.mem_of_superset (polynomial.eventually_no_roots Q hq) (λ x h h', absurd h' h),
cases le_iff_lt_or_eq.mp h with h h,
{ exact is_O_of_div_tendsto_nhds hPQ 0 (div_tendsto_zero_of_degree_lt P Q h) },
{ exact is_O_of_div_tendsto_nhds hPQ _ (div_tendsto_leading_coeff_div_of_degree_eq P Q h) } }
end
end polynomial
|
47f1fbbef3a860bbde88fd093608996b43863cbd | 35677d2df3f081738fa6b08138e03ee36bc33cad | /src/order/lexicographic.lean | 552cdff53f6aa1ddd7fc048198eba5efcc7002d3 | [
"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 | 8,620 | lean | /-
Copyright (c) 2019 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Scott Morrison, Minchao Wu
Lexicographic preorder / partial_order / linear_order / decidable_linear_order,
for pairs and dependent pairs.
-/
import tactic.basic
import algebra.order
universes u v
def lex (α : Type u) (β : Type v) := α × β
variables {α : Type u} {β : Type v}
instance [decidable_eq α] [decidable_eq β] : decidable_eq (lex α β) :=
prod.decidable_eq
instance [inhabited α] [inhabited β] : inhabited (lex α β) :=
prod.inhabited
/-- Dictionary / lexicographic ordering on pairs. -/
instance lex_has_le [preorder α] [preorder β] : has_le (lex α β) :=
{ le := prod.lex (<) (≤) }
instance lex_has_lt [preorder α] [preorder β] : has_lt (lex α β) :=
{ lt := prod.lex (<) (<) }
/-- Dictionary / lexicographic preorder for pairs. -/
instance lex_preorder [preorder α] [preorder β] : preorder (lex α β) :=
{ le_refl := λ ⟨l, r⟩, by { right, apply le_refl },
le_trans :=
begin
rintros ⟨a₁, b₁⟩ ⟨a₂, b₂⟩ ⟨a₃, b₃⟩ ⟨h₁l, h₁r⟩ ⟨h₂l, h₂r⟩,
{ left, apply lt_trans, repeat { assumption } },
{ left, assumption },
{ left, assumption },
{ right, apply le_trans, repeat { assumption } }
end,
lt_iff_le_not_le :=
begin
rintros ⟨a₁, b₁⟩ ⟨a₂, b₂⟩,
split,
{ rintros (⟨_, _, _, _, hlt⟩ | ⟨_, _, _, hlt⟩),
{ split,
{ left, assumption },
{ rintro ⟨l,r⟩,
{ apply lt_asymm hlt, assumption },
{ apply lt_irrefl _ hlt } } },
{ split,
{ right, rw lt_iff_le_not_le at hlt, exact hlt.1 },
{ rintro ⟨l,r⟩,
{ apply lt_irrefl a₁, assumption },
{ rw lt_iff_le_not_le at hlt, apply hlt.2, assumption } } } },
{ rintros ⟨⟨h₁ll, h₁lr⟩, h₂r⟩,
{ left, assumption },
{ right, rw lt_iff_le_not_le, split,
{ assumption },
{ intro h, apply h₂r, right, exact h } } }
end,
.. lex_has_le,
.. lex_has_lt }
/-- Dictionary / lexicographic partial_order for pairs. -/
instance lex_partial_order [partial_order α] [partial_order β] : partial_order (lex α β) :=
{ le_antisymm :=
begin
rintros ⟨a₁, b₁⟩ ⟨a₂, b₂⟩ (⟨_, _, _, _, hlt₁⟩ | ⟨_, _, _, hlt₁⟩) (⟨_, _, _, _, hlt₂⟩ | ⟨_, _, _, hlt₂⟩),
{ exfalso, exact lt_irrefl a₁ (lt_trans hlt₁ hlt₂) },
{ exfalso, exact lt_irrefl a₁ hlt₁ },
{ exfalso, exact lt_irrefl a₁ hlt₂ },
{ have := le_antisymm hlt₁ hlt₂, simp [this] }
end
.. lex_preorder }
/-- Dictionary / lexicographic linear_order for pairs. -/
instance lex_linear_order [linear_order α] [linear_order β] : linear_order (lex α β) :=
{ le_total :=
begin
rintros ⟨a₁, b₁⟩ ⟨a₂, b₂⟩,
rcases le_total a₁ a₂ with ha | ha;
cases lt_or_eq_of_le ha with a_lt a_eq,
-- Deal with the two goals with a₁ ≠ a₂
{ left, left, exact a_lt },
swap,
{ right, left, exact a_lt },
-- Now deal with the two goals with a₁ = a₂
all_goals { subst a_eq, rcases le_total b₁ b₂ with hb | hb },
{ left, right, exact hb },
{ right, right, exact hb },
{ left, right, exact hb },
{ right, right, exact hb },
end
.. lex_partial_order }.
/-- Dictionary / lexicographic decidable_linear_order for pairs. -/
instance lex_decidable_linear_order [decidable_linear_order α] [decidable_linear_order β] :
decidable_linear_order (lex α β) :=
{ decidable_le :=
begin
rintros ⟨a₁, b₁⟩ ⟨a₂, b₂⟩,
rcases decidable_linear_order.decidable_le a₁ a₂ with a_lt | a_le,
{ -- a₂ < a₁
left, rw not_le at a_lt, rintro ⟨l, r⟩,
{ apply lt_irrefl a₂, apply lt_trans, repeat { assumption } },
{ apply lt_irrefl a₁, assumption } },
{ -- a₁ ≤ a₂
by_cases h : a₁ = a₂,
{ rw h,
rcases decidable_linear_order.decidable_le b₁ b₂ with b_lt | b_le,
{ -- b₂ < b₁
left, rw not_le at b_lt, rintro ⟨l, r⟩,
{ apply lt_irrefl a₂, assumption },
{ apply lt_irrefl b₂, apply lt_of_lt_of_le, repeat { assumption } } },
-- b₁ ≤ b₂
{ right, right, assumption } },
-- a₁ < a₂
{ right, left, apply lt_of_le_of_ne, repeat { assumption } } }
end,
.. lex_linear_order }
variables {Z : α → Type v}
/--
Dictionary / lexicographic ordering on dependent pairs.
The 'pointwise' partial order `prod.has_le` doesn't make
sense for dependent pairs, so it's safe to mark these as
instances here.
-/
instance dlex_has_le [preorder α] [∀ a, preorder (Z a)] : has_le (Σ' a, Z a) :=
{ le := psigma.lex (<) (λ a, (≤)) }
instance dlex_has_lt [preorder α] [∀ a, preorder (Z a)] : has_lt (Σ' a, Z a) :=
{ lt := psigma.lex (<) (λ a, (<)) }
/-- Dictionary / lexicographic preorder on dependent pairs. -/
instance dlex_preorder [preorder α] [∀ a, preorder (Z a)] : preorder (Σ' a, Z a) :=
{ le_refl := λ ⟨l, r⟩, by { right, apply le_refl },
le_trans :=
begin
rintros ⟨a₁, b₁⟩ ⟨a₂, b₂⟩ ⟨a₃, b₃⟩ ⟨h₁l, h₁r⟩ ⟨h₂l, h₂r⟩,
{ left, apply lt_trans, repeat { assumption } },
{ left, assumption },
{ left, assumption },
{ right, apply le_trans, repeat { assumption } }
end,
lt_iff_le_not_le :=
begin
rintros ⟨a₁, b₁⟩ ⟨a₂, b₂⟩,
split,
{ rintros (⟨_, _, _, _, hlt⟩ | ⟨_, _, _, hlt⟩),
{ split,
{ left, assumption },
{ rintro ⟨l,r⟩,
{ apply lt_asymm hlt, assumption },
{ apply lt_irrefl _ hlt } } },
{ split,
{ right, rw lt_iff_le_not_le at hlt, exact hlt.1 },
{ rintro ⟨l,r⟩,
{ apply lt_irrefl a₁, assumption },
{ rw lt_iff_le_not_le at hlt, apply hlt.2, assumption } } } },
{ rintros ⟨⟨h₁ll, h₁lr⟩, h₂r⟩,
{ left, assumption },
{ right, rw lt_iff_le_not_le, split,
{ assumption },
{ intro h, apply h₂r, right, exact h } } }
end,
.. dlex_has_le,
.. dlex_has_lt }
/-- Dictionary / lexicographic partial_order for dependent pairs. -/
instance dlex_partial_order [partial_order α] [∀ a, partial_order (Z a)] : partial_order (Σ' a, Z a) :=
{ le_antisymm :=
begin
rintros ⟨a₁, b₁⟩ ⟨a₂, b₂⟩ (⟨_, _, _, _, hlt₁⟩ | ⟨_, _, _, hlt₁⟩) (⟨_, _, _, _, hlt₂⟩ | ⟨_, _, _, hlt₂⟩),
{ exfalso, exact lt_irrefl a₁ (lt_trans hlt₁ hlt₂) },
{ exfalso, exact lt_irrefl a₁ hlt₁ },
{ exfalso, exact lt_irrefl a₁ hlt₂ },
{ have := le_antisymm hlt₁ hlt₂, simp [this] }
end
.. dlex_preorder }
/-- Dictionary / lexicographic linear_order for pairs. -/
instance dlex_linear_order [linear_order α] [∀ a, linear_order (Z a)] : linear_order (Σ' a, Z a) :=
{ le_total :=
begin
rintros ⟨a₁, b₁⟩ ⟨a₂, b₂⟩,
rcases le_total a₁ a₂ with ha | ha;
cases lt_or_eq_of_le ha with a_lt a_eq,
-- Deal with the two goals with a₁ ≠ a₂
{ left, left, exact a_lt },
swap,
{ right, left, exact a_lt },
-- Now deal with the two goals with a₁ = a₂
all_goals { subst a_eq, rcases le_total b₁ b₂ with hb | hb },
{ left, right, exact hb },
{ right, right, exact hb },
{ left, right, exact hb },
{ right, right, exact hb },
end
.. dlex_partial_order }.
/-- Dictionary / lexicographic decidable_linear_order for dependent pairs. -/
instance dlex_decidable_linear_order [decidable_linear_order α] [∀ a, decidable_linear_order (Z a)] :
decidable_linear_order (Σ' a, Z a) :=
{ decidable_le :=
begin
rintros ⟨a₁, b₁⟩ ⟨a₂, b₂⟩,
rcases decidable_linear_order.decidable_le a₁ a₂ with a_lt | a_le,
{ -- a₂ < a₁
left, rw not_le at a_lt, rintro ⟨l, r⟩,
{ apply lt_irrefl a₂, apply lt_trans, repeat { assumption } },
{ apply lt_irrefl a₁, assumption } },
{ -- a₁ ≤ a₂
by_cases h : a₁ = a₂,
{ subst h,
rcases decidable_linear_order.decidable_le b₁ b₂ with b_lt | b_le,
{ -- b₂ < b₁
left, rw not_le at b_lt, rintro ⟨l, r⟩,
{ apply lt_irrefl a₁, assumption },
{ apply lt_irrefl b₂, apply lt_of_lt_of_le, repeat { assumption } } },
-- b₁ ≤ b₂
{ right, right, assumption } },
-- a₁ < a₂
{ right, left, apply lt_of_le_of_ne, repeat { assumption } } }
end,
.. dlex_linear_order }
|
65ea87e7d073758e627ae50b02613f919d4d109e | 9dd3f3912f7321eb58ee9aa8f21778ad6221f87c | /tests/lean/run/def_ite_value.lean | f551f1fcc0832ba75beb3297007ff364ff300fe3 | [
"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 | 552 | lean | inductive bv : nat → Type
| nil : bv 0
| cons : Π n, bool → bv n → bv (n+1)
open bv
definition f : ∀ n : nat, bv n → nat → nat
| (n+1) (cons .n b v) 1000000 := f n v 0
| (n+1) (cons .n b v) x := f n v (x + 1)
| _ _ _ := 1
set_option pp.binder_types true
check @f._main.equations._eqn_1
check @f._main.equations._eqn_2
check @f._main.equations._eqn_3
example (n : nat) (b : bool) (v : bv n) (x : nat) : x ≠ 1000000 → f (n+1) (cons n b v) x = f n v (x + 1) :=
assume H, f._main.equations._eqn_3 n b v x H
|
605136f87a28f3b46c4f7b9d17996c9cb97dbfb4 | 302c785c90d40ad3d6be43d33bc6a558354cc2cf | /src/analysis/normed_space/enorm.lean | f3d1dc6afcf8587991b86360ff07e76efd3f20d2 | [
"Apache-2.0"
] | permissive | ilitzroth/mathlib | ea647e67f1fdfd19a0f7bdc5504e8acec6180011 | 5254ef14e3465f6504306132fe3ba9cec9ffff16 | refs/heads/master | 1,680,086,661,182 | 1,617,715,647,000 | 1,617,715,647,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 7,707 | lean | /-
Copyright (c) 2020 Yury G. Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury G. Kudryashov
-/
import analysis.normed_space.basic
/-!
# Extended norm
In this file we define a structure `enorm 𝕜 V` representing an extended norm (i.e., a norm that can
take the value `∞`) on a vector space `V` over a normed field `𝕜`. We do not use `class` for
an `enorm` because the same space can have more than one extended norm. For example, the space of
measurable functions `f : α → ℝ` has a family of `L_p` extended norms.
We prove some basic inequalities, then define
* `emetric_space` structure on `V` corresponding to `e : enorm 𝕜 V`;
* the subspace of vectors with finite norm, called `e.finite_subspace`;
* a `normed_space` structure on this space.
The last definition is an instance because the type involves `e`.
## Implementation notes
We do not define extended normed groups. They can be added to the chain once someone will need them.
## Tags
normed space, extended norm
-/
local attribute [instance, priority 1001] classical.prop_decidable
open_locale ennreal
/-- Extended norm on a vector space. As in the case of normed spaces, we require only
`∥c • x∥ ≤ ∥c∥ * ∥x∥` in the definition, then prove an equality in `map_smul`. -/
structure enorm (𝕜 : Type*) (V : Type*) [normed_field 𝕜] [add_comm_group V] [vector_space 𝕜 V] :=
(to_fun : V → ℝ≥0∞)
(eq_zero' : ∀ x, to_fun x = 0 → x = 0)
(map_add_le' : ∀ x y : V, to_fun (x + y) ≤ to_fun x + to_fun y)
(map_smul_le' : ∀ (c : 𝕜) (x : V), to_fun (c • x) ≤ nnnorm c * to_fun x)
namespace enorm
variables {𝕜 : Type*} {V : Type*} [normed_field 𝕜] [add_comm_group V] [vector_space 𝕜 V]
(e : enorm 𝕜 V)
instance : has_coe_to_fun (enorm 𝕜 V) := ⟨_, enorm.to_fun⟩
lemma coe_fn_injective : function.injective (λ (e : enorm 𝕜 V) (x : V), e x) :=
λ e₁ e₂ h, by cases e₁; cases e₂; congr; exact h
@[ext] lemma ext {e₁ e₂ : enorm 𝕜 V} (h : ∀ x, e₁ x = e₂ x) : e₁ = e₂ :=
coe_fn_injective $ funext h
lemma ext_iff {e₁ e₂ : enorm 𝕜 V} : e₁ = e₂ ↔ ∀ x, e₁ x = e₂ x :=
⟨λ h x, h ▸ rfl, ext⟩
@[simp, norm_cast] lemma coe_inj {e₁ e₂ : enorm 𝕜 V} : ⇑e₁ = e₂ ↔ e₁ = e₂ :=
coe_fn_injective.eq_iff
@[simp] lemma map_smul (c : 𝕜) (x : V) : e (c • x) = nnnorm c * e x :=
le_antisymm (e.map_smul_le' c x) $
begin
by_cases hc : c = 0, { simp [hc] },
calc (nnnorm c : ℝ≥0∞) * e x = nnnorm c * e (c⁻¹ • c • x) : by rw [inv_smul_smul' hc]
... ≤ nnnorm c * (nnnorm (c⁻¹) * e (c • x)) : _
... = e (c • x) : _,
{ exact ennreal.mul_le_mul (le_refl _) (e.map_smul_le' _ _) },
{ rw [← mul_assoc, normed_field.nnnorm_inv, ennreal.coe_inv,
ennreal.mul_inv_cancel _ ennreal.coe_ne_top, one_mul]; simp [hc] }
end
@[simp] lemma map_zero : e 0 = 0 :=
by { rw [← zero_smul 𝕜 (0:V), e.map_smul], norm_num }
@[simp] lemma eq_zero_iff {x : V} : e x = 0 ↔ x = 0 :=
⟨e.eq_zero' x, λ h, h.symm ▸ e.map_zero⟩
@[simp] lemma map_neg (x : V) : e (-x) = e x :=
calc e (-x) = nnnorm (-1:𝕜) * e x : by rw [← map_smul, neg_one_smul]
... = e x : by simp
lemma map_sub_rev (x y : V) : e (x - y) = e (y - x) :=
by rw [← neg_sub, e.map_neg]
lemma map_add_le (x y : V) : e (x + y) ≤ e x + e y := e.map_add_le' x y
lemma map_sub_le (x y : V) : e (x - y) ≤ e x + e y :=
calc e (x - y) = e (x + -y) : by rw sub_eq_add_neg
... ≤ e x + e (-y) : e.map_add_le x (-y)
... = e x + e y : by rw [e.map_neg]
instance : partial_order (enorm 𝕜 V) :=
{ le := λ e₁ e₂, ∀ x, e₁ x ≤ e₂ x,
le_refl := λ e x, le_refl _,
le_trans := λ e₁ e₂ e₃ h₁₂ h₂₃ x, le_trans (h₁₂ x) (h₂₃ x),
le_antisymm := λ e₁ e₂ h₁₂ h₂₁, ext $ λ x, le_antisymm (h₁₂ x) (h₂₁ x) }
/-- The `enorm` sending each non-zero vector to infinity. -/
noncomputable instance : has_top (enorm 𝕜 V) :=
⟨{ to_fun := λ x, if x = 0 then 0 else ⊤,
eq_zero' := λ x, by { split_ifs; simp [*] },
map_add_le' := λ x y,
begin
split_ifs with hxy hx hy hy hx hy hy; try { simp [*] },
simpa [hx, hy] using hxy
end,
map_smul_le' := λ c x,
begin
split_ifs with hcx hx hx; simp only [smul_eq_zero, not_or_distrib] at hcx,
{ simp only [mul_zero, le_refl] },
{ have : c = 0, by tauto,
simp [this] },
{ tauto },
{ simp [hcx.1] }
end }⟩
noncomputable instance : inhabited (enorm 𝕜 V) := ⟨⊤⟩
lemma top_map {x : V} (hx : x ≠ 0) : (⊤ : enorm 𝕜 V) x = ⊤ := if_neg hx
noncomputable instance : semilattice_sup_top (enorm 𝕜 V) :=
{ le := (≤),
lt := (<),
top := ⊤,
le_top := λ e x, if h : x = 0 then by simp [h] else by simp [top_map h],
sup := λ e₁ e₂,
{ to_fun := λ x, max (e₁ x) (e₂ x),
eq_zero' := λ x h, e₁.eq_zero_iff.1 (ennreal.max_eq_zero_iff.1 h).1,
map_add_le' := λ x y, max_le
(le_trans (e₁.map_add_le _ _) $ add_le_add (le_max_left _ _) (le_max_left _ _))
(le_trans (e₂.map_add_le _ _) $ add_le_add (le_max_right _ _) (le_max_right _ _)),
map_smul_le' := λ c x, le_of_eq $ by simp only [map_smul, ennreal.mul_max] },
le_sup_left := λ e₁ e₂ x, le_max_left _ _,
le_sup_right := λ e₁ e₂ x, le_max_right _ _,
sup_le := λ e₁ e₂ e₃ h₁ h₂ x, max_le (h₁ x) (h₂ x),
.. enorm.partial_order }
@[simp, norm_cast] lemma coe_max (e₁ e₂ : enorm 𝕜 V) : ⇑(e₁ ⊔ e₂) = λ x, max (e₁ x) (e₂ x) := rfl
@[norm_cast]
lemma max_map (e₁ e₂ : enorm 𝕜 V) (x : V) : (e₁ ⊔ e₂) x = max (e₁ x) (e₂ x) := rfl
/-- Structure of an `emetric_space` defined by an extended norm. -/
def emetric_space : emetric_space V :=
{ edist := λ x y, e (x - y),
edist_self := λ x, by simp,
eq_of_edist_eq_zero := λ x y, by simp [sub_eq_zero],
edist_comm := e.map_sub_rev,
edist_triangle := λ x y z,
calc e (x - z) = e ((x - y) + (y - z)) : by rw [sub_add_sub_cancel]
... ≤ e (x - y) + e (y - z) : e.map_add_le (x - y) (y - z) }
/-- The subspace of vectors with finite enorm. -/
def finite_subspace : subspace 𝕜 V :=
{ carrier := {x | e x < ⊤},
zero_mem' := by simp,
add_mem' := λ x y hx hy, lt_of_le_of_lt (e.map_add_le x y) (ennreal.add_lt_top.2 ⟨hx, hy⟩),
smul_mem' := λ c x hx,
calc e (c • x) = nnnorm c * e x : e.map_smul c x
... < ⊤ : ennreal.mul_lt_top ennreal.coe_lt_top hx }
/-- Metric space structure on `e.finite_subspace`. We use `emetric_space.to_metric_space_of_dist`
to ensure that this definition agrees with `e.emetric_space`. -/
instance : metric_space e.finite_subspace :=
begin
letI := e.emetric_space,
refine emetric_space.to_metric_space_of_dist _ (λ x y, _) (λ x y, rfl),
change e (x - y) ≠ ⊤,
rw [← ennreal.lt_top_iff_ne_top],
exact lt_of_le_of_lt (e.map_sub_le x y) (ennreal.add_lt_top.2 ⟨x.2, y.2⟩)
end
lemma finite_dist_eq (x y : e.finite_subspace) : dist x y = (e (x - y)).to_real := rfl
lemma finite_edist_eq (x y : e.finite_subspace) : edist x y = e (x - y) := rfl
/-- Normed group instance on `e.finite_subspace`. -/
instance : normed_group e.finite_subspace :=
{ norm := λ x, (e x).to_real,
dist_eq := λ x y, rfl }
lemma finite_norm_eq (x : e.finite_subspace) : ∥x∥ = (e x).to_real := rfl
/-- Normed space instance on `e.finite_subspace`. -/
instance : normed_space 𝕜 e.finite_subspace :=
{ norm_smul_le := λ c x, le_of_eq $ by simp [finite_norm_eq, ennreal.to_real_mul] }
end enorm
|
d8cf6439c89645db217ae5aa6ba3f98159474cef | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /src/Lean/Data/Xml/Parser.lean | 8b8dd40f415bcf0cf68ee5b3ebaaa49cfbba0069 | [
"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 | 15,237 | lean | /-
Copyright (c) 2021 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Dany Fabian
-/
import Lean.Data.Parsec
import Lean.Data.Xml.Basic
open IO
open System
open Lean
namespace Lean
namespace Xml
namespace Parser
open Lean.Parsec
open Parsec.ParseResult
abbrev LeanChar := Char
/-- consume a newline character sequence pretending, that we read '\n'. As per spec:
https://www.w3.org/TR/xml/#sec-line-ends -/
def endl : Parsec LeanChar := (skipString "\r\n" <|> skipChar '\r' <|> skipChar '\n') *> pure '\n'
def quote (p : Parsec α) : Parsec α :=
skipChar '\'' *> p <* skipChar '\''
<|> skipChar '"' *> p <* skipChar '"'
/-- https://www.w3.org/TR/xml/#NT-Char -/
def Char : Parsec LeanChar :=
(attempt do
let c ← anyChar
let cNat := c.toNat
if (0x20 ≤ cNat ∧ cNat ≤ 0xD7FF)
∨ (0xE000 ≤ cNat ∧ cNat ≤ 0xFFFD)
∨ (0x10000 ≤ cNat ∧ cNat ≤ 0x10FFFF) then pure c else fail "expected xml char")
<|> pchar '\t' <|> endl
/-- https://www.w3.org/TR/xml/#NT-S -/
def S : Parsec String :=
many1Chars (pchar ' ' <|> endl <|> pchar '\t')
/-- https://www.w3.org/TR/xml/#NT-Eq -/
def Eq : Parsec Unit :=
optional S *> skipChar '=' <* optional S
private def nameStartCharRanges : Array (Nat × Nat) :=
#[(0xC0, 0xD6),
(0xD8, 0xF6),
(0xF8, 0x2FF),
(0x370, 0x37D),
(0x37F, 0x1FFF),
(0x200C, 0x200D),
(0x2070, 0x218F),
(0x2C00, 0x2FEF),
(0x3001, 0xD7FF),
(0xF900, 0xFDCF),
(0xFDF0, 0xFFFD),
(0x10000, 0xEFFFF)]
/-- https://www.w3.org/TR/xml/#NT-NameStartChar -/
def NameStartChar : Parsec LeanChar := attempt do
let c ← anyChar
if ('A' ≤ c ∧ c ≤ 'Z') ∨ ('a' ≤ c ∧ c ≤ 'z') then pure c
else if c = ':' ∨ c = '_' then pure c
else
let cNum := c.toNat
if nameStartCharRanges.any (fun (lo, hi) => lo ≤ cNum ∧ cNum ≤ hi) then pure c
else fail "expected a name character"
/-- https://www.w3.org/TR/xml/#NT-NameChar -/
def NameChar : Parsec LeanChar :=
NameStartChar <|> digit <|> pchar '-' <|> pchar '.' <|> pchar '\xB7'
<|> satisfy (λ c => ('\u0300' ≤ c ∧ c ≤ '\u036F') ∨ ('\u203F' ≤ c ∧ c ≤ '\u2040'))
/-- https://www.w3.org/TR/xml/#NT-Name -/
def Name : Parsec String := do
let x ← NameStartChar
manyCharsCore NameChar x.toString
/-- https://www.w3.org/TR/xml/#NT-VersionNum -/
def VersionNum : Parsec Unit :=
skipString "1." <* (many1 digit)
/-- https://www.w3.org/TR/xml/#NT-VersionInfo -/
def VersionInfo : Parsec Unit := do
S *>
skipString "version"
Eq
quote VersionNum
/-- https://www.w3.org/TR/xml/#NT-EncName -/
def EncName : Parsec String := do
let x ← asciiLetter
manyCharsCore (asciiLetter <|> digit <|> pchar '-' <|> pchar '_' <|> pchar '.') x.toString
/-- https://www.w3.org/TR/xml/#NT-EncodingDecl -/
def EncodingDecl : Parsec String := do
S *>
skipString "encoding"
Eq
quote EncName
/-- https://www.w3.org/TR/xml/#NT-SDDecl -/
def SDDecl : Parsec String := do
S *> skipString "standalone" *> Eq *> quote (pstring "yes" <|> pstring "no")
/-- https://www.w3.org/TR/xml/#NT-XMLDecl -/
def XMLdecl : Parsec Unit := do
skipString "<?xml"
VersionInfo
optional EncodingDecl *>
optional SDDecl *>
optional S *>
skipString "?>"
/-- https://www.w3.org/TR/xml/#NT-Comment -/
def Comment : Parsec String :=
let notDash := Char.toString <$> satisfy (λ c => c ≠ '-')
skipString "<!--" *>
Array.foldl String.append "" <$> many (notDash <|> (do
let d ← pchar '-'
let c ← notDash
pure $ d.toString ++ c))
<* skipString "-->"
/-- https://www.w3.org/TR/xml/#NT-PITarget -/
def PITarget : Parsec String :=
Name <* (skipChar 'X' <|> skipChar 'x') <* (skipChar 'M' <|> skipChar 'm') <* (skipChar 'L' <|> skipChar 'l')
/-- https://www.w3.org/TR/xml/#NT-PI -/
def PI : Parsec Unit := do
skipString "<?"
<* PITarget <*
optional (S *> manyChars (notFollowedBy (skipString "?>") *> Char))
skipString "?>"
/-- https://www.w3.org/TR/xml/#NT-Misc -/
def Misc : Parsec Unit :=
Comment *> pure () <|> PI <|> S *> pure ()
/-- https://www.w3.org/TR/xml/#NT-SystemLiteral -/
def SystemLiteral : Parsec String :=
pchar '"' *> manyChars (satisfy λ c => c ≠ '"') <* pchar '"'
<|> pchar '\'' *> manyChars (satisfy λ c => c ≠ '\'') <* pure '\''
/-- https://www.w3.org/TR/xml/#NT-PubidChar -/
def PubidChar : Parsec LeanChar :=
asciiLetter <|> digit <|> endl <|> attempt do
let c ← anyChar
if "-'()+,./:=?;!*#@$_%".contains c then pure c else fail "PublidChar expected"
/-- https://www.w3.org/TR/xml/#NT-PubidLiteral -/
def PubidLiteral : Parsec String :=
pchar '"' *> manyChars PubidChar <* pchar '"'
<|> pchar '\'' *> manyChars (attempt do
let c ← PubidChar
if c = '\'' then fail "'\\'' not expected" else pure c) <* pchar '\''
/-- https://www.w3.org/TR/xml/#NT-ExternalID -/
def ExternalID : Parsec Unit :=
skipString "SYSTEM" *> S *> SystemLiteral *> pure ()
<|> skipString "PUBLIC" *> S *> PubidLiteral *> S *> SystemLiteral *> pure ()
/-- https://www.w3.org/TR/xml/#NT-Mixed -/
def Mixed : Parsec Unit :=
(do
skipChar '('
optional S *>
skipString "#PCDATA" *>
many (optional S *> skipChar '|' *> optional S *> Name) *>
optional S *>
skipString ")*")
<|> skipChar '(' *> (optional S) *> skipString "#PCDATA" <* (optional S) <* skipChar ')'
mutual
/-- https://www.w3.org/TR/xml/#NT-cp -/
partial def cp : Parsec Unit :=
(Name *> pure () <|> choice <|> seq) <* optional (skipChar '?' <|> skipChar '*' <|> skipChar '+')
/-- https://www.w3.org/TR/xml/#NT-choice -/
partial def choice : Parsec Unit := do
skipChar '('
optional S *>
cp
many1 (optional S *> skipChar '|' *> optional S *> cp) *>
optional S *>
skipChar ')'
/-- https://www.w3.org/TR/xml/#NT-seq -/
partial def seq : Parsec Unit := do
skipChar '('
optional S *>
cp
many (optional S *> skipChar ',' *> optional S *> cp) *>
optional S *>
skipChar ')'
end
/-- https://www.w3.org/TR/xml/#NT-children -/
def children : Parsec Unit :=
(choice <|> seq) <* optional (skipChar '?' <|> skipChar '*' <|> skipChar '+')
/-- https://www.w3.org/TR/xml/#NT-contentspec -/
def contentspec : Parsec Unit := do
skipString "EMPTY" <|> skipString "ANY" <|> Mixed <|> children
/-- https://www.w3.org/TR/xml/#NT-elementdecl -/
def elementDecl : Parsec Unit := do
skipString "<!ELEMENT"
S *>
Name *>
contentspec *>
optional S *>
skipChar '>'
/-- https://www.w3.org/TR/xml/#NT-StringType -/
def StringType : Parsec Unit :=
skipString "CDATA"
/-- https://www.w3.org/TR/xml/#NT-TokenizedType -/
def TokenizedType : Parsec Unit :=
skipString "ID"
<|> skipString "IDREF"
<|> skipString "IDREFS"
<|> skipString "ENTITY"
<|> skipString "ENTITIES"
<|> skipString "NMTOKEN"
<|> skipString "NMTOKENS"
/-- https://www.w3.org/TR/xml/#NT-NotationType -/
def NotationType : Parsec Unit := do
skipString "NOTATION"
S *>
skipChar '(' <*
optional S
Name *> many (optional S *> skipChar '|' *> optional S *> Name) *>
optional S *>
skipChar ')'
/-- https://www.w3.org/TR/xml/#NT-Nmtoken -/
def Nmtoken : Parsec String := do
many1Chars NameChar
/-- https://www.w3.org/TR/xml/#NT-Enumeration -/
def Enumeration : Parsec Unit := do
skipChar '('
optional S *>
Nmtoken *> many (optional S *> skipChar '|' *> optional S *> Nmtoken) *>
optional S *>
skipChar ')'
/-- https://www.w3.org/TR/xml/#NT-EnumeratedType -/
def EnumeratedType : Parsec Unit :=
NotationType <|> Enumeration
/-- https://www.w3.org/TR/xml/#NT-AttType -/
def AttType : Parsec Unit :=
StringType <|> TokenizedType <|> EnumeratedType
def predefinedEntityToChar : String → Option LeanChar
| "lt" => some '<'
| "gt" => some '>'
| "amp" => some '&'
| "apos" => some '\''
| "quot" => some '"'
| _ => none
/-- https://www.w3.org/TR/xml/#NT-EntityRef -/
def EntityRef : Parsec $ Option LeanChar := attempt $
skipChar '&' *> predefinedEntityToChar <$> Name <* skipChar ';'
@[inline]
def hexDigitToNat (c : LeanChar) : Nat :=
if '0' ≤ c ∧ c ≤ '9' then c.toNat - '0'.toNat
else if 'a' ≤ c ∧ c ≤ 'f' then c.toNat - 'a'.toNat + 10
else c.toNat - 'A'.toNat + 10
def digitsToNat (base : Nat) (digits : Array Nat) : Nat :=
digits.foldl (λ r d => r * base + d) 0
/-- https://www.w3.org/TR/xml/#NT-CharRef -/
def CharRef : Parsec LeanChar := do
skipString "&#"
let charCode ←
digitsToNat 10 <$> many1 (hexDigitToNat <$> digit)
<|> skipChar 'x' *> digitsToNat 16 <$> many1 (hexDigitToNat <$> hexDigit)
skipChar ';'
return Char.ofNat charCode
/-- https://www.w3.org/TR/xml/#NT-Reference -/
def Reference : Parsec $ Option LeanChar :=
EntityRef <|> some <$> CharRef
/-- https://www.w3.org/TR/xml/#NT-AttValue -/
def AttValue : Parsec String := do
let chars ←
(do
skipChar '"'
many (some <$> satisfy (λ c => c ≠ '<' ∧ c ≠ '&' ∧ c ≠ '"') <|> Reference) <*
skipChar '"')
<|> (do
skipChar '\''
many (some <$> satisfy (λ c => c ≠ '<' ∧ c ≠ '&' ∧ c ≠ '\'') <|> Reference) <*
skipChar '\'')
return chars.foldl (λ s c => if let some c := c then s.push c else s) ""
/-- https://www.w3.org/TR/xml/#NT-DefaultDecl -/
def DefaultDecl : Parsec Unit :=
skipString "#REQUIRED"
<|> skipString "#IMPLIED"
<|> optional (skipString "#FIXED" <* S) *> AttValue *> pure ()
/-- https://www.w3.org/TR/xml/#NT-AttDef -/
def AttDef : Parsec Unit :=
S *> Name *> S *> AttType *> S *> DefaultDecl
/-- https://www.w3.org/TR/xml/#NT-AttlistDecl -/
def AttlistDecl : Parsec Unit :=
skipString "<!ATTLIST" *> S *> Name *> many AttDef *> optional S *> skipChar '>'
/-- https://www.w3.org/TR/xml/#NT-PEReference -/
def PEReference : Parsec Unit :=
skipChar '%' *> Name *> skipChar ';'
/-- https://www.w3.org/TR/xml/#NT-EntityValue -/
def EntityValue : Parsec String := do
let chars ←
(do
skipChar '"'
many (some <$> satisfy (λ c => c ≠ '%' ∧ c ≠ '&' ∧ c ≠ '"') <|> PEReference *> pure none <|> Reference) <*
skipChar '"')
<|> (do
skipChar '\''
many (some <$> satisfy (λ c => c ≠ '%' ∧ c ≠ '&' ∧ c ≠ '\'') <|> PEReference *> pure none <|> Reference) <*
skipChar '\'')
return chars.foldl (λ s c => if let some c := c then s.push c else s) ""
/-- https://www.w3.org/TR/xml/#NT-NDataDecl -/
def NDataDecl : Parsec Unit :=
S *> skipString "NDATA" <* S <* Name
/-- https://www.w3.org/TR/xml/#NT-EntityDef -/
def EntityDef : Parsec Unit :=
EntityValue *> pure () <|> (ExternalID <* optional NDataDecl)
/-- https://www.w3.org/TR/xml/#NT-GEDecl -/
def GEDecl : Parsec Unit :=
skipString "<!ENTITY" *> S *> Name *> S *> EntityDef *> optional S *> skipChar '>'
/-- https://www.w3.org/TR/xml/#NT-PEDef -/
def PEDef : Parsec Unit :=
EntityValue *> pure () <|> ExternalID
/-- https://www.w3.org/TR/xml/#NT-PEDecl -/
def PEDecl : Parsec Unit :=
skipString "<!ENTITY" *> S *> skipChar '%' *> S *> Name *> PEDef *> optional S *> skipChar '>'
/-- https://www.w3.org/TR/xml/#NT-EntityDecl -/
def EntityDecl : Parsec Unit :=
GEDecl <|> PEDecl
/-- https://www.w3.org/TR/xml/#NT-PublicID -/
def PublicID : Parsec Unit :=
skipString "PUBLIC" <* S <* PubidLiteral
/-- https://www.w3.org/TR/xml/#NT-NotationDecl -/
def NotationDecl : Parsec Unit :=
skipString "<!NOTATION" *> S *> Name *> (ExternalID <|> PublicID) *> optional S *> skipChar '>'
/-- https://www.w3.org/TR/xml/#NT-markupdecl -/
def markupDecl : Parsec Unit :=
elementDecl <|> AttlistDecl <|> EntityDecl <|> NotationDecl <|> PI <|> (Comment *> pure ())
/-- https://www.w3.org/TR/xml/#NT-DeclSep -/
def DeclSep : Parsec Unit :=
PEReference <|> S *> pure ()
/-- https://www.w3.org/TR/xml/#NT-intSubset -/
def intSubset : Parsec Unit :=
many (markupDecl <|> DeclSep) *> pure ()
/-- https://www.w3.org/TR/xml/#NT-doctypedecl -/
def doctypedecl : Parsec Unit := do
skipString "<!DOCTYPE"
S *>
Name *>
optional (S *> ExternalID) *> pure ()
<* optional S
optional (skipChar '[' *> intSubset <* skipChar ']' <* optional S) *>
skipChar '>'
/-- https://www.w3.org/TR/xml/#NT-prolog -/
def prolog : Parsec Unit :=
optional XMLdecl *>
many Misc *>
optional (doctypedecl <* many Misc) *> pure ()
/-- https://www.w3.org/TR/xml/#NT-Attribute -/
def Attribute : Parsec (String × String) := do
let name ← Name
Eq
let value ← AttValue
return (name, value)
protected def elementPrefix : Parsec (Array Content → Element) := do
skipChar '<'
let name ← Name
let attributes ← many (S *> Attribute)
optional S *> pure ()
return Element.Element name (RBMap.fromList attributes.toList compare)
/-- https://www.w3.org/TR/xml/#NT-EmptyElemTag -/
def EmptyElemTag (elem : Array Content → Element) : Parsec Element := do
skipString "/>" *> pure (elem #[])
/-- https://www.w3.org/TR/xml/#NT-STag -/
def STag (elem : Array Content → Element) : Parsec (Array Content → Element) := do
skipChar '>' *> pure elem
/-- https://www.w3.org/TR/xml/#NT-ETag -/
def ETag : Parsec Unit :=
skipString "</" *> Name *> optional S *> skipChar '>'
/-- https://www.w3.org/TR/xml/#NT-CDStart -/
def CDStart : Parsec Unit :=
skipString "<![CDATA["
/-- https://www.w3.org/TR/xml/#NT-CDEnd -/
def CDEnd : Parsec Unit :=
skipString "]]>"
/-- https://www.w3.org/TR/xml/#NT-CData -/
def CData : Parsec String :=
manyChars (notFollowedBy (skipString "]]>") *> anyChar)
/-- https://www.w3.org/TR/xml/#NT-CDSect -/
def CDSect : Parsec String :=
CDStart *> CData <* CDEnd
/-- https://www.w3.org/TR/xml/#NT-CharData -/
def CharData : Parsec String :=
notFollowedBy (skipString "]]>") *> manyChars (satisfy λ c => c ≠ '<' ∧ c ≠ '&')
mutual
/-- https://www.w3.org/TR/xml/#NT-content -/
partial def content : Parsec (Array Content) := do
let x ← optional (Content.Character <$> CharData)
let xs ← many do
let y ←
attempt (some <$> Content.Element <$> element)
<|> (do let c ← Reference; pure <| c.map (Content.Character ∘ Char.toString))
<|> some <$> Content.Character <$> CDSect
<|> PI *> pure none
<|> some <$> Content.Comment <$> Comment
let z ← optional (Content.Character <$> CharData)
pure #[y, z]
let xs := #[x] ++ xs.concatMap id |>.filterMap id
let mut res := #[]
for x in xs do
if res.size > 0 then
match res.back, x with
| Content.Character x, Content.Character y => res := res.set! (res.size - 1) (Content.Character $ x ++ y)
| _, x => res := res.push x
else res := res.push x
return res
/-- https://www.w3.org/TR/xml/#NT-element -/
partial def element : Parsec Element := do
let elem ← Parser.elementPrefix
EmptyElemTag elem <|> STag elem <*> content <* ETag
end
/-- https://www.w3.org/TR/xml/#NT-document -/
def document : Parsec Element := prolog *> element <* many Misc <* eof
end Parser
def parse (s : String) : Except String Element :=
match Xml.Parser.document s.mkIterator with
| Parsec.ParseResult.success _ res => Except.ok res
| Parsec.ParseResult.error it err => Except.error s!"offset {it.i.byteIdx.repr}: {err}\n{(it.prevn 10).extract it}"
end Xml
|
2189fcba94a50339e09f4fec28a85dae9c0ebdd0 | 57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d | /tests/lean/run/CoeNew.lean | 140b09d767c1137d1911d9b6f5b773978d5acc96 | [
"Apache-2.0"
] | permissive | collares/lean4 | 861a9269c4592bce49b71059e232ff0bfe4594cc | 52a4f535d853a2c7c7eea5fee8a4fa04c682c1ee | refs/heads/master | 1,691,419,031,324 | 1,618,678,138,000 | 1,618,678,138,000 | 358,989,750 | 0 | 0 | Apache-2.0 | 1,618,696,333,000 | 1,618,696,333,000 | null | UTF-8 | Lean | false | false | 738 | lean |
universes u v w
instance boolToNat : Coe Bool Nat :=
{ coe := fun b => cond b 1 0 }
instance natToBool : Coe Nat Bool :=
{ coe := fun n => match n with
| 0 => false
| _ => true }
structure ConstantFunction (α β : Type) :=
(f : α → β)
(h : ∀ a₁ a₂, f a₁ = f a₂)
instance constantFunctionCoe {α β : Type} : CoeFun (ConstantFunction α β) (fun _ => α → β) :=
{ coe := fun c => c.f }
set_option pp.explicit true
#synth CoeT { x : Nat // x > 0 } ⟨1, sorryAx _⟩ Nat
#synth CoeT { x : Nat // x > 0 } ⟨1, sorryAx _⟩ Bool
#synth CoeT Nat 0 (Option Nat)
#synth CoeT Bool true (Option Nat)
#synth CoeT Prop (0 = 1) Bool
#synth CoeT Bool true (Option Nat)
def f (c : ConstantFunction Nat Nat) : Nat :=
c 0
|
f036ba232bf1e1b503c464d716c717b5ee24a3cb | 137c667471a40116a7afd7261f030b30180468c2 | /src/group_theory/perm/support.lean | 05d5903d81e8c8a9226392e89969714b441b82e2 | [
"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 | 19,009 | lean | /-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes, Aaron Anderson, Yakov Pechersky
-/
import data.finset.sort
import data.fintype.basic
import group_theory.perm.basic
/-!
# Support of a permutation
## Main definitions
In the following, `f g : equiv.perm α`.
* `equiv.perm.disjoint`: two permutations `f` and `g` are `disjoint` if every element is fixed
either by `f`, or by `g`.
Equivalently, `f` and `g` are `disjoint` iff their `support` are disjoint.
* `equiv.perm.is_swap`: `f = swap x y` for `x ≠ y`.
* `equiv.perm.support`: the elements `x : α` that are not fixed by `f`.
-/
open equiv finset
namespace equiv.perm
variables {α : Type*}
section disjoint
/-- Two permutations `f` and `g` are `disjoint` if their supports are disjoint, i.e.,
every element is fixed either by `f`, or by `g`. -/
def disjoint (f g : perm α) := ∀ x, f x = x ∨ g x = x
variables {f g h : perm α}
@[symm] lemma disjoint.symm : disjoint f g → disjoint g f :=
by simp only [disjoint, or.comm, imp_self]
lemma disjoint.symmetric : symmetric (@disjoint α) :=
λ _ _, disjoint.symm
lemma disjoint_comm : disjoint f g ↔ disjoint g f :=
⟨disjoint.symm, disjoint.symm⟩
lemma disjoint.commute (h : disjoint f g) : commute f g :=
equiv.ext $ λ x, (h x).elim
(λ hf, (h (g x)).elim (λ hg, by simp [mul_apply, hf, hg])
(λ hg, by simp [mul_apply, hf, g.injective hg]))
(λ hg, (h (f x)).elim (λ hf, by simp [mul_apply, f.injective hf, hg])
(λ hf, by simp [mul_apply, hf, hg]))
@[simp] lemma disjoint_one_left (f : perm α) : disjoint 1 f := λ _, or.inl rfl
@[simp] lemma disjoint_one_right (f : perm α) : disjoint f 1 := λ _, or.inr rfl
lemma disjoint_iff_eq_or_eq : disjoint f g ↔ ∀ (x : α), f x = x ∨ g x = x := iff.rfl
@[simp] lemma disjoint_refl_iff : disjoint f f ↔ f = 1 :=
begin
refine ⟨λ h, _, λ h, h.symm ▸ disjoint_one_left 1⟩,
ext x,
cases h x with hx hx;
simp [hx]
end
lemma disjoint.inv_left (h : disjoint f g) : disjoint f⁻¹ g :=
begin
intro x,
rw [inv_eq_iff_eq, eq_comm],
exact h x
end
lemma disjoint.inv_right (h : disjoint f g) : disjoint f g⁻¹ :=
h.symm.inv_left.symm
@[simp] lemma disjoint_inv_left_iff : disjoint f⁻¹ g ↔ disjoint f g :=
begin
refine ⟨λ h, _, disjoint.inv_left⟩,
convert h.inv_left,
exact (inv_inv _).symm
end
@[simp] lemma disjoint_inv_right_iff : disjoint f g⁻¹ ↔ disjoint f g :=
by rw [disjoint_comm, disjoint_inv_left_iff, disjoint_comm]
lemma disjoint.mul_left (H1 : disjoint f h) (H2 : disjoint g h) :
disjoint (f * g) h :=
λ x, by cases H1 x; cases H2 x; simp *
lemma disjoint.mul_right (H1 : disjoint f g) (H2 : disjoint f h) :
disjoint f (g * h) :=
by { rw disjoint_comm, exact H1.symm.mul_left H2.symm }
lemma disjoint_prod_right (l : list (perm α))
(h : ∀ g ∈ l, disjoint f g) : disjoint f l.prod :=
begin
induction l with g l ih,
{ exact disjoint_one_right _ },
{ rw list.prod_cons,
exact (h _ (list.mem_cons_self _ _)).mul_right (ih (λ g hg, h g (list.mem_cons_of_mem _ hg))) }
end
lemma disjoint_prod_perm {l₁ l₂ : list (perm α)} (hl : l₁.pairwise disjoint)
(hp : l₁ ~ l₂) : l₁.prod = l₂.prod :=
hp.prod_eq' $ hl.imp $ λ f g, disjoint.commute
lemma nodup_of_pairwise_disjoint {l : list (perm α)} (h1 : (1 : perm α) ∉ l)
(h2 : l.pairwise disjoint) : l.nodup :=
begin
refine list.pairwise.imp_of_mem _ h2,
rintros σ - h_mem - h_disjoint rfl,
suffices : σ = 1,
{ rw this at h_mem,
exact h1 h_mem },
exact ext (λ a, (or_self _).mp (h_disjoint a)),
end
lemma pow_apply_eq_self_of_apply_eq_self {x : α} (hfx : f x = x) :
∀ n : ℕ, (f ^ n) x = x
| 0 := rfl
| (n+1) := by rw [pow_succ', mul_apply, hfx, pow_apply_eq_self_of_apply_eq_self]
lemma gpow_apply_eq_self_of_apply_eq_self {x : α} (hfx : f x = x) :
∀ n : ℤ, (f ^ n) x = x
| (n : ℕ) := pow_apply_eq_self_of_apply_eq_self hfx n
| -[1+ n] := by rw [gpow_neg_succ_of_nat, inv_eq_iff_eq, pow_apply_eq_self_of_apply_eq_self hfx]
lemma pow_apply_eq_of_apply_apply_eq_self {x : α} (hffx : f (f x) = x) :
∀ n : ℕ, (f ^ n) x = x ∨ (f ^ n) x = f x
| 0 := or.inl rfl
| (n+1) := (pow_apply_eq_of_apply_apply_eq_self n).elim
(λ h, or.inr (by rw [pow_succ, mul_apply, h]))
(λ h, or.inl (by rw [pow_succ, mul_apply, h, hffx]))
lemma gpow_apply_eq_of_apply_apply_eq_self {x : α} (hffx : f (f x) = x) :
∀ i : ℤ, (f ^ i) x = x ∨ (f ^ i) x = f x
| (n : ℕ) := pow_apply_eq_of_apply_apply_eq_self hffx n
| -[1+ n] := by { rw [gpow_neg_succ_of_nat, inv_eq_iff_eq, ← f.injective.eq_iff, ← mul_apply,
← pow_succ, eq_comm, inv_eq_iff_eq, ← mul_apply, ← pow_succ', @eq_comm _ x, or.comm],
exact pow_apply_eq_of_apply_apply_eq_self hffx _ }
lemma disjoint.mul_apply_eq_iff {σ τ : perm α} (hστ : disjoint σ τ) {a : α} :
(σ * τ) a = a ↔ σ a = a ∧ τ a = a :=
begin
refine ⟨λ h, _, λ h, by rw [mul_apply, h.2, h.1]⟩,
cases hστ a with hσ hτ,
{ exact ⟨hσ, σ.injective (h.trans hσ.symm)⟩ },
{ exact ⟨(congr_arg σ hτ).symm.trans h, hτ⟩ },
end
lemma disjoint.mul_eq_one_iff {σ τ : perm α} (hστ : disjoint σ τ) :
σ * τ = 1 ↔ σ = 1 ∧ τ = 1 :=
by simp_rw [ext_iff, one_apply, hστ.mul_apply_eq_iff, forall_and_distrib]
lemma disjoint.gpow_disjoint_gpow {σ τ : perm α} (hστ : disjoint σ τ) (m n : ℤ) :
disjoint (σ ^ m) (τ ^ n) :=
λ x, or.imp (λ h, gpow_apply_eq_self_of_apply_eq_self h m)
(λ h, gpow_apply_eq_self_of_apply_eq_self h n) (hστ x)
lemma disjoint.pow_disjoint_pow {σ τ : perm α} (hστ : disjoint σ τ) (m n : ℕ) :
disjoint (σ ^ m) (τ ^ n) :=
hστ.gpow_disjoint_gpow m n
end disjoint
section is_swap
variable [decidable_eq α]
/-- `f.is_swap` indicates that the permutation `f` is a transposition of two elements. -/
def is_swap (f : perm α) : Prop := ∃ x y, x ≠ y ∧ f = swap x y
lemma is_swap.of_subtype_is_swap {p : α → Prop} [decidable_pred p]
{f : perm (subtype p)} (h : f.is_swap) : (of_subtype f).is_swap :=
let ⟨⟨x, hx⟩, ⟨y, hy⟩, hxy⟩ := h in
⟨x, y, by { simp only [ne.def] at hxy, exact hxy.1 },
equiv.ext $ λ z, begin
rw [hxy.2, of_subtype],
simp only [swap_apply_def, coe_fn_mk, swap_inv, subtype.mk_eq_mk, monoid_hom.coe_mk],
split_ifs;
rw subtype.coe_mk <|> cc,
end⟩
lemma ne_and_ne_of_swap_mul_apply_ne_self {f : perm α} {x y : α}
(hy : (swap x (f x) * f) y ≠ y) : f y ≠ y ∧ y ≠ x :=
begin
simp only [swap_apply_def, mul_apply, f.injective.eq_iff] at *,
by_cases h : f y = x,
{ split; intro; simp only [*, if_true, eq_self_iff_true, not_true, ne.def] at * },
{ split_ifs at hy; cc }
end
end is_swap
section support
variables [decidable_eq α] [fintype α] {f g : perm α}
/-- The `finset` of nonfixed points of a permutation. -/
def support (f : perm α) : finset α := univ.filter (λ x, f x ≠ x)
@[simp] lemma mem_support {x : α} : x ∈ f.support ↔ f x ≠ x :=
by rw [support, mem_filter, and_iff_right (mem_univ x)]
lemma not_mem_support {x : α} : x ∉ f.support ↔ f x = x := by simp
@[simp] lemma support_eq_empty_iff {σ : perm α} : σ.support = ∅ ↔ σ = 1 :=
by simp_rw [finset.ext_iff, mem_support, finset.not_mem_empty, iff_false, not_not,
equiv.perm.ext_iff, one_apply]
@[simp] lemma support_one : (1 : perm α).support = ∅ :=
by rw support_eq_empty_iff
@[simp] lemma support_refl : support (equiv.refl α) = ∅ := support_one
lemma support_congr (h : f.support ⊆ g.support)
(h' : ∀ x ∈ g.support, f x = g x) : f = g :=
begin
ext x,
by_cases hx : x ∈ g.support,
{ exact h' x hx },
{ rw [not_mem_support.mp hx, ←not_mem_support],
exact λ H, hx (h H) }
end
lemma support_mul_le (f g : perm α) :
(f * g).support ≤ f.support ⊔ g.support :=
λ x, begin
rw [sup_eq_union, mem_union, mem_support, mem_support,
mem_support, mul_apply, ←not_and_distrib, not_imp_not],
rintro ⟨hf, hg⟩,
rw [hg, hf]
end
lemma exists_mem_support_of_mem_support_prod {l : list (perm α)} {x : α}
(hx : x ∈ l.prod.support) :
∃ f : perm α, f ∈ l ∧ x ∈ f.support :=
begin
contrapose! hx,
simp_rw [mem_support, not_not] at hx ⊢,
induction l with f l ih generalizing hx,
{ refl },
{ rw [list.prod_cons, mul_apply, ih (λ g hg, hx g (or.inr hg)), hx f (or.inl rfl)] },
end
lemma support_pow_le (σ : perm α) (n : ℕ) :
(σ ^ n).support ≤ σ.support :=
λ x h1, mem_support.mpr (λ h2, mem_support.mp h1 (pow_apply_eq_self_of_apply_eq_self h2 n))
@[simp] lemma support_inv (σ : perm α) : support (σ⁻¹) = σ.support :=
by simp_rw [finset.ext_iff, mem_support, not_iff_not,
(inv_eq_iff_eq).trans eq_comm, iff_self, imp_true_iff]
@[simp]
lemma apply_mem_support {x : α} :
f x ∈ f.support ↔ x ∈ f.support :=
by rw [mem_support, mem_support, ne.def, ne.def, not_iff_not, apply_eq_iff_eq]
@[simp]
lemma pow_apply_mem_support {n : ℕ} {x : α} :
(f ^ n) x ∈ f.support ↔ x ∈ f.support :=
begin
induction n with n ih,
{ refl },
rw [pow_succ, perm.mul_apply, apply_mem_support, ih]
end
@[simp]
lemma gpow_apply_mem_support {n : ℤ} {x : α} :
(f ^ n) x ∈ f.support ↔ x ∈ f.support :=
begin
cases n,
{ rw [int.of_nat_eq_coe, gpow_coe_nat, pow_apply_mem_support] },
{ rw [gpow_neg_succ_of_nat, ← support_inv, ← inv_pow, pow_apply_mem_support] }
end
lemma pow_eq_on_of_mem_support (h : ∀ (x ∈ f.support ∩ g.support), f x = g x)
(k : ℕ) : ∀ (x ∈ f.support ∩ g.support), (f ^ k) x = (g ^ k) x :=
begin
induction k with k hk,
{ simp },
{ intros x hx,
rw [pow_succ', mul_apply, pow_succ', mul_apply, h _ hx, hk],
rwa [mem_inter, apply_mem_support, ←h _ hx, apply_mem_support, ←mem_inter] }
end
lemma disjoint_iff_disjoint_support :
disjoint f g ↔ _root_.disjoint f.support g.support :=
by simp [disjoint_iff_eq_or_eq, disjoint_iff, finset.ext_iff, not_and_distrib]
lemma disjoint.disjoint_support (h : disjoint f g) :
_root_.disjoint f.support g.support :=
disjoint_iff_disjoint_support.1 h
lemma disjoint.support_mul (h : disjoint f g) :
(f * g).support = f.support ∪ g.support :=
begin
refine le_antisymm (support_mul_le _ _) (λ a, _),
rw [mem_union, mem_support, mem_support, mem_support, mul_apply, ←not_and_distrib, not_imp_not],
exact (h a).elim (λ hf h, ⟨hf, f.apply_eq_iff_eq.mp (h.trans hf.symm)⟩)
(λ hg h, ⟨(congr_arg f hg).symm.trans h, hg⟩),
end
lemma support_prod_of_pairwise_disjoint (l : list (perm α)) (h : l.pairwise disjoint) :
l.prod.support = (l.map support).foldr (⊔) ⊥ :=
begin
induction l with hd tl hl,
{ simp },
{ rw [list.pairwise_cons] at h,
have : disjoint hd tl.prod := disjoint_prod_right _ h.left,
simp [this.support_mul, hl h.right] }
end
lemma support_prod_le (l : list (perm α)) :
l.prod.support ≤ (l.map support).foldr (⊔) ⊥ :=
begin
induction l with hd tl hl,
{ simp },
{ rw [list.prod_cons, list.map_cons, list.foldr_cons],
refine (support_mul_le hd tl.prod).trans _,
exact sup_le_sup (le_refl _) hl }
end
lemma support_gpow_le (σ : perm α) (n : ℤ) :
(σ ^ n).support ≤ σ.support :=
λ x h1, mem_support.mpr (λ h2, mem_support.mp h1 (gpow_apply_eq_self_of_apply_eq_self h2 n))
@[simp] lemma support_swap {x y : α} (h : x ≠ y) : support (swap x y) = {x, y} :=
begin
ext z,
by_cases hx : z = x;
by_cases hy : z = y,
any_goals { simpa [hx, hy] using h.symm },
{ simp [swap_apply_of_ne_of_ne, hx, hy] }
end
lemma support_swap_iff (x y : α) :
support (swap x y) = {x, y} ↔ x ≠ y :=
begin
refine ⟨λ h H, _, support_swap⟩,
subst H,
simp only [swap_self, support_refl, insert_singleton_self_eq] at h,
have : x ∈ ∅,
{ rw h,
exact mem_singleton.mpr rfl },
simpa
end
lemma support_swap_mul_swap {x y z : α} (h : list.nodup [x, y, z]) :
support (swap x y * swap y z) = {x, y, z} :=
begin
simp only [list.not_mem_nil, and_true, list.mem_cons_iff, not_false_iff, list.nodup_cons,
list.mem_singleton, and_self, list.nodup_nil] at h,
push_neg at h,
apply le_antisymm,
{ convert support_mul_le _ _,
rw [support_swap h.left.left, support_swap h.right],
ext,
simp [or.comm, or.left_comm] },
{ intro,
simp only [mem_insert, mem_singleton],
rintro (rfl | rfl | rfl | _);
simp [swap_apply_of_ne_of_ne, h.left.left, h.left.left.symm, h.left.right, h.left.right.symm,
h.right.symm] }
end
lemma support_swap_mul_ge_support_diff (f : perm α) (x y : α) :
f.support \ {x, y} ≤ (swap x y * f).support :=
begin
intro,
simp only [and_imp, perm.coe_mul, function.comp_app, ne.def, mem_support, mem_insert, mem_sdiff,
mem_singleton],
push_neg,
rintro ha ⟨hx, hy⟩ H,
rw [swap_apply_eq_iff, swap_apply_of_ne_of_ne hx hy] at H,
exact ha H
end
lemma support_swap_mul_eq (f : perm α) (x : α) (h : f (f x) ≠ x) :
(swap x (f x) * f).support = f.support \ {x} :=
begin
by_cases hx : f x = x,
{ simp [hx, sdiff_singleton_eq_erase, not_mem_support.mpr hx, erase_eq_of_not_mem] },
ext z,
by_cases hzx : z = x,
{ simp [hzx] },
by_cases hzf : z = f x,
{ simp [hzf, hx, h, swap_apply_of_ne_of_ne], },
by_cases hzfx : f z = x,
{ simp [ne.symm hzx, hzx, ne.symm hzf, hzfx] },
{ simp [ne.symm hzx, hzx, ne.symm hzf, hzfx, f.injective.ne hzx, swap_apply_of_ne_of_ne] }
end
lemma mem_support_swap_mul_imp_mem_support_ne {x y : α}
(hy : y ∈ support (swap x (f x) * f)) : y ∈ support f ∧ y ≠ x :=
begin
simp only [mem_support, swap_apply_def, mul_apply, f.injective.eq_iff] at *,
by_cases h : f y = x,
{ split; intro; simp only [*, if_true, eq_self_iff_true, not_true, ne.def] at * },
{ split_ifs at hy; cc }
end
lemma disjoint.mem_imp (h : disjoint f g) {x : α} (hx : x ∈ f.support) :
x ∉ g.support :=
λ H, h.disjoint_support (mem_inter_of_mem hx H)
lemma eq_on_support_mem_disjoint {l : list (perm α)} (h : f ∈ l) (hl : l.pairwise disjoint) :
∀ (x ∈ f.support), f x = l.prod x :=
begin
induction l with hd tl IH,
{ simpa using h },
{ intros x hx,
rw list.pairwise_cons at hl,
rw list.mem_cons_iff at h,
rcases h with rfl|h,
{ rw [list.prod_cons, mul_apply, not_mem_support.mp
((disjoint_prod_right tl hl.left).mem_imp hx)] },
{ rw [list.prod_cons, mul_apply, ←IH h hl.right _ hx, eq_comm, ←not_mem_support],
refine (hl.left _ h).symm.mem_imp _,
simpa using hx } }
end
lemma support_le_prod_of_mem {l : list (perm α)} (h : f ∈ l) (hl : l.pairwise disjoint) :
f.support ≤ l.prod.support :=
begin
intros x hx,
rwa [mem_support, ←eq_on_support_mem_disjoint h hl _ hx, ←mem_support],
end
section extend_domain
variables {β : Type*} [decidable_eq β] [fintype β] {p : β → Prop} [decidable_pred p]
@[simp]
lemma support_extend_domain (f : α ≃ subtype p) {g : perm α} :
support (g.extend_domain f) = g.support.map f.as_embedding :=
begin
ext b,
simp only [exists_prop, function.embedding.coe_fn_mk, to_embedding_apply, mem_map, ne.def,
function.embedding.trans_apply, mem_support],
by_cases pb : p b,
{ rw [extend_domain_apply_subtype _ _ pb],
split,
{ rintro h,
refine ⟨f.symm ⟨b, pb⟩, _, by simp⟩,
contrapose! h,
simp [h] },
{ rintro ⟨a, ha, hb⟩,
contrapose! ha,
obtain rfl : a = f.symm ⟨b, pb⟩,
{ rw eq_symm_apply,
exact subtype.coe_injective hb },
rw eq_symm_apply,
exact subtype.coe_injective ha } },
{ rw [extend_domain_apply_not_subtype _ _ pb],
simp only [not_exists, false_iff, not_and, eq_self_iff_true, not_true],
rintros a ha rfl,
exact pb (subtype.prop _) }
end
lemma card_support_extend_domain (f : α ≃ subtype p) {g : perm α} :
(g.extend_domain f).support.card = g.support.card :=
by simp
end extend_domain
section card
@[simp]
lemma card_support_eq_zero {f : perm α} :
f.support.card = 0 ↔ f = 1 :=
by rw [finset.card_eq_zero, support_eq_empty_iff]
lemma one_lt_card_support_of_ne_one {f : perm α} (h : f ≠ 1) :
1 < f.support.card :=
begin
simp_rw [one_lt_card_iff, mem_support, ←not_or_distrib],
contrapose! h,
ext a,
specialize h (f a) a,
rwa [apply_eq_iff_eq, or_self, or_self] at h,
end
lemma card_support_ne_one (f : perm α) : f.support.card ≠ 1 :=
begin
by_cases h : f = 1,
{ exact ne_of_eq_of_ne (card_support_eq_zero.mpr h) zero_ne_one },
{ exact ne_of_gt (one_lt_card_support_of_ne_one h) },
end
@[simp] lemma card_support_le_one {f : perm α} : f.support.card ≤ 1 ↔ f = 1 :=
by rw [le_iff_lt_or_eq, nat.lt_succ_iff, nat.le_zero_iff, card_support_eq_zero,
or_iff_not_imp_right, imp_iff_right f.card_support_ne_one]
lemma two_le_card_support_of_ne_one {f : perm α} (h : f ≠ 1) :
2 ≤ f.support.card :=
one_lt_card_support_of_ne_one h
lemma card_support_swap_mul {f : perm α} {x : α}
(hx : f x ≠ x) : (swap x (f x) * f).support.card < f.support.card :=
finset.card_lt_card
⟨λ z hz, (mem_support_swap_mul_imp_mem_support_ne hz).left,
λ h, absurd (h (mem_support.2 hx)) (mt mem_support.1 (by simp))⟩
lemma card_support_swap {x y : α} (hxy : x ≠ y) : (swap x y).support.card = 2 :=
show (swap x y).support.card = finset.card ⟨x ::ₘ y ::ₘ 0, by simp [hxy]⟩,
from congr_arg card $ by simp [support_swap hxy, *, finset.ext_iff]
@[simp]
lemma card_support_eq_two {f : perm α} : f.support.card = 2 ↔ is_swap f :=
begin
split; intro h,
{ obtain ⟨x, t, hmem, hins, ht⟩ := card_eq_succ.1 h,
obtain ⟨y, rfl⟩ := card_eq_one.1 ht,
rw mem_singleton at hmem,
refine ⟨x, y, hmem, _⟩,
ext a,
have key : ∀ b, f b ≠ b ↔ _ := λ b, by rw [←mem_support, ←hins, mem_insert, mem_singleton],
by_cases ha : f a = a,
{ have ha' := not_or_distrib.mp (mt (key a).mpr (not_not.mpr ha)),
rw [ha, swap_apply_of_ne_of_ne ha'.1 ha'.2] },
{ have ha' := (key (f a)).mp (mt f.apply_eq_iff_eq.mp ha),
obtain rfl | rfl := ((key a).mp ha),
{ rw [or.resolve_left ha' ha, swap_apply_left] },
{ rw [or.resolve_right ha' ha, swap_apply_right] } } },
{ obtain ⟨x, y, hxy, rfl⟩ := h,
exact card_support_swap hxy }
end
lemma disjoint.card_support_mul (h : disjoint f g) :
(f * g).support.card = f.support.card + g.support.card :=
begin
rw ←finset.card_disjoint_union,
{ congr,
ext,
simp [h.support_mul] },
{ simpa using h.disjoint_support }
end
lemma card_support_prod_list_of_pairwise_disjoint {l : list (perm α)}
(h : l.pairwise disjoint) :
l.prod.support.card = (l.map (finset.card ∘ support)).sum :=
begin
induction l with a t ih,
{ exact card_support_eq_zero.mpr rfl, },
{ obtain ⟨ha, ht⟩ := list.pairwise_cons.1 h,
rw [list.prod_cons, list.map_cons, list.sum_cons, ←ih ht],
exact (disjoint_prod_right _ ha).card_support_mul }
end
end card
end support
end equiv.perm
|
29ff7e8e16ec735e0f39fb129533ebee83dce3ca | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /test/finish4.lean | 939d82d9ddbaede10d84106d543c96c31aa26486 | [
"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 | 1,540 | lean | /-
Copyright (c) 2019 Jesse Michael Han. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author(s): Jesse Michael Han
Tests for `finish using [...]`
-/
import tactic.finish
import algebra.ordered_ring
section list_rev
open list
variable {α : Type*}
def append1 (a : α) : list α → list α
| nil := [a]
| (b :: l) := b :: (append1 l)
def rev : list α → list α
| nil := nil
| (a :: l) := append1 a (rev l)
lemma hd_rev (a : α) (l : list α) :
a :: rev l = rev (append1 a l) :=
begin
induction l with l_hd l_tl ih, refl,
-- finish -- fails
-- finish[rev, append1] -- fails
-- finish[rev, append1, ih] -- fails
-- finish[rev, append1, ih.symm] -- times out
finish using [rev, append1]
end
end list_rev
section barber
variables (man : Type) (barber : man)
variable (shaves : man → man → Prop)
example (h : ∀ x : man, shaves barber x ↔ ¬ shaves x x) : false :=
by finish using [h barber]
end barber
constant real : Type
@[instance] constant orreal : ordered_ring real
-- TODO(Mario): suspicious fix
@[irreducible] noncomputable instance : has_lt real := by apply_instance
constants (log exp : real → real)
constant log_exp_eq : ∀ x, log (exp x) = x
constant exp_log_eq : ∀ {x}, x > 0 → exp (log x) = x
constant exp_pos : ∀ x, exp x > 0
constant exp_add : ∀ x y, exp (x + y) = exp x * exp y
theorem log_mul' {x y : real} (hx : x > 0) (hy : y > 0) :
log (x * y) = log x + log y :=
by finish using [log_exp_eq, exp_log_eq, exp_add]
|
2edc93ef1f6edc50565e6ea1cda32b6fc8e2c063 | 3ed5a65c1ab3ce5d1a094edce8fa3287980f197b | /src/herstein/ch2_3.lean | 4e2e24d44928f76c77bb5ee1cb0e23e8e7956630 | [] | no_license | group-study-group/herstein | 35d32e77158efa2cc303c84e1ee5e3bc80831137 | f5a1a72eb56fa19c19ece0cb3ab6cf7ffd161f66 | refs/heads/master | 1,586,202,191,519 | 1,548,969,759,000 | 1,548,969,759,000 | 157,746,953 | 0 | 0 | null | 1,542,412,901,000 | 1,542,302,366,000 | Lean | UTF-8 | Lean | false | false | 2,885 | lean | import algebra.group algebra.group_power
universe u
variables {A G: Type u}
-- Theorems & lemmas from the body text of chapter 2.3
-- Lemma 2.3.1: If G is a group, then
-- a. The identity element of G is unique.
-- b. Every a ∈ G has a unique inverse in G.
-- c. For every a ∈ G, (a⁻¹)⁻¹ = a.
-- d. For all a, b ∈ G, (a * b)⁻¹ = b⁻¹ * a ⁻¹
lemma L2_3_1a (e f: G) [group G]:
(∀ a: G, a = a * e) ∧
(∀ a: G, a = e * a) ∧
(∀ a: G, a = a * f) ∧
(∀ a: G, a = f * a) → e = f :=
λ ⟨h1, ⟨h2, ⟨h3, h4⟩⟩⟩, eq.trans (h3 e) (h2 f).symm
-- now justified: use of group.one G to extract unique identity of G,
-- and the notation 1 for group.one G.
lemma L2_3_1b (a g h: G) [group G]:
a * g = 1 ∧ g * a = 1 ∧
a * h = 1 ∧ h * a = 1 → g = h :=
λ ⟨h1, ⟨h2, ⟨h3, h4⟩⟩⟩, calc
g = g * 1 : (mul_one g).symm
... = g * (a * h) : h3 ▸ ⟨g * (a * h)⟩
... = (g * a) * h : (mul_assoc g a h).symm
... = 1 * h : h2 ▸ ⟨(g * a) * h⟩
... = h : (one_mul h)
-- now justified: use of group.inv and notation a⁻¹ for the inverse of a.
lemma L2_3_1b₁ (a b c: G) [group G]:
a * b = a * c → b = c := λ h, calc
b = 1 * b : (one_mul b).symm
... = a⁻¹ * a * b : by rw inv_mul_self
... = a⁻¹ * a * c : by rw [mul_assoc, h, ←mul_assoc]
... = 1 * c : by rw inv_mul_self
... = c : one_mul c
lemma L2_3_1c (a: G) [group G]: (a⁻¹)⁻¹ = a :=
eq.symm $ calc a
= 1 * a : (one_mul _).symm
... = (a⁻¹)⁻¹ * a⁻¹ * a : by rw ←inv_mul_self
... = (a⁻¹)⁻¹ * (a⁻¹ * a) : by rw mul_assoc
... = (a⁻¹)⁻¹ * 1 : by rw inv_mul_self
... = (a⁻¹)⁻¹ : mul_one _
-- now justified: use of group.mul_inv_rev
lemma L2_3_1d (a b : G) [group G] : (a * b)⁻¹ = b⁻¹ * a⁻¹ :=
inv_eq_of_mul_eq_one $ calc a * b * (b⁻¹ * a⁻¹)
= a * (b * (b⁻¹ * a⁻¹)) : mul_assoc _ _ _
... = a * (b * b⁻¹ * a ⁻¹) : by rw ←mul_assoc b b⁻¹ a⁻¹
... = a * (1 * a⁻¹) : by rw mul_right_inv
... = a * a⁻¹ : by rw one_mul
... = 1 : by rw mul_right_inv
-- left cancellation
lemma L2_3_2₁ (a u w: G) [group G]:
a * u = a * w → u = w :=
λ h, calc u
= 1 * u : (one_mul _).symm
... = a⁻¹ * a * u : by rw ←inv_mul_self
... = a⁻¹ * (a * u) : mul_assoc _ _ _
... = a⁻¹ * (a * w) : by rw h
... = a⁻¹ * a * w : (mul_assoc _ _ _).symm
... = 1 * w : by rw inv_mul_self
... = w : by rw one_mul
-- right cancellation: similarly
lemma L2_3_2₂ (a u w: G) [group G]:
u * a = w * a → u = w :=
λ h, calc u
= u * (a * a⁻¹) : (mul_right_inv a).symm ▸ (mul_one u).symm
... = w * (a * a⁻¹) : by rw [ ←mul_assoc, h, mul_assoc ]
... = w : by rw [ mul_right_inv, mul_one ]
|
9422e678a96e40125b53579298ffd5f2d8187ebe | 957a80ea22c5abb4f4670b250d55534d9db99108 | /library/init/meta/declaration.lean | fc75f7bbaeaa867cd6fa7498e8e7dff003303178 | [
"Apache-2.0"
] | permissive | GaloisInc/lean | aa1e64d604051e602fcf4610061314b9a37ab8cd | f1ec117a24459b59c6ff9e56a1d09d9e9e60a6c0 | refs/heads/master | 1,592,202,909,807 | 1,504,624,387,000 | 1,504,624,387,000 | 75,319,626 | 2 | 1 | Apache-2.0 | 1,539,290,164,000 | 1,480,616,104,000 | C++ | UTF-8 | Lean | false | false | 5,372 | lean | /-
Copyright (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
prelude
import init.meta.expr init.meta.name init.meta.task
/--
Reducibility hints are used in the convertibility checker.
When trying to solve a constraint such a
(f ...) =?= (g ...)
where f and g are definitions, the checker has to decide which one will be unfolded.
If f (g) is opaque, then g (f) is unfolded if it is also not marked as opaque,
Else if f (g) is abbrev, then f (g) is unfolded if g (f) is also not marked as abbrev,
Else if f and g are regular, then we unfold the one with the biggest definitional height.
Otherwise both are unfolded.
The arguments of the `regular` constructor are: the definitional height and the flag `self_opt`.
The definitional height is by default computed by the kernel. It only takes into account
other regular definitions used in a definition. When creating declarations using meta-programming,
we can specify the definitional depth manually.
For definitions marked as regular, we also have a hint for constraints such as
(f a) =?= (f b)
if self_opt == true, then checker will first try to solve (a =?= b), only if it fails,
it unfolds f.
Remark: the hint only affects performance. None of the hints prevent the kernel from unfolding a
declaration during type checking.
Remark: the reducibility_hints are not related to the attributes: reducible/irrelevance/semireducible.
These attributes are used by the elaborator. The reducibility_hints are used by the kernel (and elaborator).
Moreover, the reducibility_hints cannot be changed after a declaration is added to the kernel.
-/
inductive reducibility_hints
| opaque : reducibility_hints
| abbrev : reducibility_hints
| regular : nat → bool → reducibility_hints
/-- Reflect a C++ declaration object. The VM replaces it with the C++ implementation. -/
meta inductive declaration
/- definition: name, list universe parameters, type, value, is_trusted -/
| defn : name → list name → expr → expr → reducibility_hints → bool → declaration
/- theorem: name, list universe parameters, type, value (remark: theorems are always trusted) -/
| thm : name → list name → expr → task expr → declaration
/- constant assumption: name, list universe parameters, type, is_trusted -/
| cnst : name → list name → expr → bool → declaration
/- axiom : name → list universe parameters, type (remark: axioms are always trusted) -/
| ax : name → list name → expr → declaration
open declaration
meta def mk_definition (n : name) (ls : list name) (v : expr) (e : expr) : declaration :=
defn n ls v e (reducibility_hints.regular 1 tt) tt
namespace declaration
meta def to_name : declaration → name
| (defn n _ _ _ _ _) := n
| (thm n _ _ _) := n
| (cnst n _ _ _) := n
| (ax n _ _) := n
meta def univ_params : declaration → list name
| (defn _ ls _ _ _ _) := ls
| (thm _ ls _ _) := ls
| (cnst _ ls _ _) := ls
| (ax _ ls _) := ls
meta def type : declaration → expr
| (defn _ _ t _ _ _) := t
| (thm _ _ t _) := t
| (cnst _ _ t _) := t
| (ax _ _ t) := t
meta def value : declaration → expr
| (defn _ _ _ v _ _) := v
| (thm _ _ _ v) := v.get
| _ := default expr
meta def value_task : declaration → task expr
| (defn _ _ _ v _ _) := task.pure v
| (thm _ _ _ v) := v
| _ := task.pure (default expr)
meta def update_type : declaration → expr → declaration
| (defn n ls t v h tr) new_t := defn n ls new_t v h tr
| (thm n ls t v) new_t := thm n ls new_t v
| (cnst n ls t tr) new_t := cnst n ls new_t tr
| (ax n ls t) new_t := ax n ls new_t
meta def update_name : declaration → name → declaration
| (defn n ls t v h tr) new_n := defn new_n ls t v h tr
| (thm n ls t v) new_n := thm new_n ls t v
| (cnst n ls t tr) new_n := cnst new_n ls t tr
| (ax n ls t) new_n := ax new_n ls t
meta def update_value : declaration → expr → declaration
| (defn n ls t v h tr) new_v := defn n ls t new_v h tr
| (thm n ls t v) new_v := thm n ls t (task.pure new_v)
| d new_v := d
meta def update_value_task : declaration → task expr → declaration
| (defn n ls t v h tr) new_v := defn n ls t new_v.get h tr
| (thm n ls t v) new_v := thm n ls t new_v
| d new_v := d
meta def map_value : declaration → (expr → expr) → declaration
| (defn n ls t v h tr) f := defn n ls t (f v) h tr
| (thm n ls t v) f := thm n ls t (task.map f v)
| d f := d
meta def to_definition : declaration → declaration
| (cnst n ls t tr) := defn n ls t (default expr) reducibility_hints.abbrev tr
| (ax n ls t) := thm n ls t (task.pure (default expr))
| d := d
meta def is_definition : declaration → bool
| (defn _ _ _ _ _ _) := tt
| _ := ff
/-- Instantiate a universe polymorphic declaration type with the given universes. -/
meta constant instantiate_type_univ_params : declaration → list level → option expr
/-- Instantiate a universe polymorphic declaration value with the given universes. -/
meta constant instantiate_value_univ_params : declaration → list level → option expr
end declaration
|
183614d46d36fad263dcae4eb63e723c26b27d9d | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/analysis/normed_space/enorm.lean | c5aeb25999affefed69bd028d17df63bf8d06b92 | [
"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,957 | lean | /-
Copyright (c) 2020 Yury G. Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury G. Kudryashov
-/
import analysis.normed_space.basic
/-!
# Extended norm
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
In this file we define a structure `enorm 𝕜 V` representing an extended norm (i.e., a norm that can
take the value `∞`) on a vector space `V` over a normed field `𝕜`. We do not use `class` for
an `enorm` because the same space can have more than one extended norm. For example, the space of
measurable functions `f : α → ℝ` has a family of `L_p` extended norms.
We prove some basic inequalities, then define
* `emetric_space` structure on `V` corresponding to `e : enorm 𝕜 V`;
* the subspace of vectors with finite norm, called `e.finite_subspace`;
* a `normed_space` structure on this space.
The last definition is an instance because the type involves `e`.
## Implementation notes
We do not define extended normed groups. They can be added to the chain once someone will need them.
## Tags
normed space, extended norm
-/
noncomputable theory
local attribute [instance, priority 1001] classical.prop_decidable
open_locale ennreal
/-- Extended norm on a vector space. As in the case of normed spaces, we require only
`‖c • x‖ ≤ ‖c‖ * ‖x‖` in the definition, then prove an equality in `map_smul`. -/
structure enorm (𝕜 : Type*) (V : Type*) [normed_field 𝕜] [add_comm_group V] [module 𝕜 V] :=
(to_fun : V → ℝ≥0∞)
(eq_zero' : ∀ x, to_fun x = 0 → x = 0)
(map_add_le' : ∀ x y : V, to_fun (x + y) ≤ to_fun x + to_fun y)
(map_smul_le' : ∀ (c : 𝕜) (x : V), to_fun (c • x) ≤ ‖c‖₊ * to_fun x)
namespace enorm
variables {𝕜 : Type*} {V : Type*} [normed_field 𝕜] [add_comm_group V] [module 𝕜 V]
(e : enorm 𝕜 V)
instance : has_coe_to_fun (enorm 𝕜 V) (λ _, V → ℝ≥0∞) := ⟨enorm.to_fun⟩
lemma coe_fn_injective : function.injective (coe_fn : enorm 𝕜 V → (V → ℝ≥0∞)) :=
λ e₁ e₂ h, by cases e₁; cases e₂; congr; exact h
@[ext] lemma ext {e₁ e₂ : enorm 𝕜 V} (h : ∀ x, e₁ x = e₂ x) : e₁ = e₂ :=
coe_fn_injective $ funext h
lemma ext_iff {e₁ e₂ : enorm 𝕜 V} : e₁ = e₂ ↔ ∀ x, e₁ x = e₂ x :=
⟨λ h x, h ▸ rfl, ext⟩
@[simp, norm_cast] lemma coe_inj {e₁ e₂ : enorm 𝕜 V} : (e₁ : V → ℝ≥0∞) = e₂ ↔ e₁ = e₂ :=
coe_fn_injective.eq_iff
@[simp] lemma map_smul (c : 𝕜) (x : V) : e (c • x) = ‖c‖₊ * e x :=
le_antisymm (e.map_smul_le' c x) $
begin
by_cases hc : c = 0, { simp [hc] },
calc (‖c‖₊ : ℝ≥0∞) * e x = ‖c‖₊ * e (c⁻¹ • c • x) : by rw [inv_smul_smul₀ hc]
... ≤ ‖c‖₊ * (‖c⁻¹‖₊ * e (c • x)) : _
... = e (c • x) : _,
{ exact mul_le_mul_left' (e.map_smul_le' _ _) _ },
{ rw [← mul_assoc, nnnorm_inv, ennreal.coe_inv,
ennreal.mul_inv_cancel _ ennreal.coe_ne_top, one_mul]; simp [hc] }
end
@[simp] lemma map_zero : e 0 = 0 :=
by { rw [← zero_smul 𝕜 (0:V), e.map_smul], norm_num }
@[simp] lemma eq_zero_iff {x : V} : e x = 0 ↔ x = 0 :=
⟨e.eq_zero' x, λ h, h.symm ▸ e.map_zero⟩
@[simp] lemma map_neg (x : V) : e (-x) = e x :=
calc e (-x) = ‖(-1 : 𝕜)‖₊ * e x : by rw [← map_smul, neg_one_smul]
... = e x : by simp
lemma map_sub_rev (x y : V) : e (x - y) = e (y - x) :=
by rw [← neg_sub, e.map_neg]
lemma map_add_le (x y : V) : e (x + y) ≤ e x + e y := e.map_add_le' x y
lemma map_sub_le (x y : V) : e (x - y) ≤ e x + e y :=
calc e (x - y) = e (x + -y) : by rw sub_eq_add_neg
... ≤ e x + e (-y) : e.map_add_le x (-y)
... = e x + e y : by rw [e.map_neg]
instance : partial_order (enorm 𝕜 V) :=
{ le := λ e₁ e₂, ∀ x, e₁ x ≤ e₂ x,
le_refl := λ e x, le_rfl,
le_trans := λ e₁ e₂ e₃ h₁₂ h₂₃ x, le_trans (h₁₂ x) (h₂₃ x),
le_antisymm := λ e₁ e₂ h₁₂ h₂₁, ext $ λ x, le_antisymm (h₁₂ x) (h₂₁ x) }
/-- The `enorm` sending each non-zero vector to infinity. -/
noncomputable instance : has_top (enorm 𝕜 V) :=
⟨{ to_fun := λ x, if x = 0 then 0 else ⊤,
eq_zero' := λ x, by { split_ifs; simp [*] },
map_add_le' := λ x y,
begin
split_ifs with hxy hx hy hy hx hy hy; try { simp [*] },
simpa [hx, hy] using hxy
end,
map_smul_le' := λ c x,
begin
split_ifs with hcx hx hx; simp only [smul_eq_zero, not_or_distrib] at hcx,
{ simp only [mul_zero, le_refl] },
{ have : c = 0, by tauto,
simp [this] },
{ tauto },
{ simp [hcx.1] }
end }⟩
noncomputable instance : inhabited (enorm 𝕜 V) := ⟨⊤⟩
lemma top_map {x : V} (hx : x ≠ 0) : (⊤ : enorm 𝕜 V) x = ⊤ := if_neg hx
noncomputable instance : order_top (enorm 𝕜 V) :=
{ top := ⊤,
le_top := λ e x, if h : x = 0 then by simp [h] else by simp [top_map h] }
noncomputable instance : semilattice_sup (enorm 𝕜 V) :=
{ le := (≤),
lt := (<),
sup := λ e₁ e₂,
{ to_fun := λ x, max (e₁ x) (e₂ x),
eq_zero' := λ x h, e₁.eq_zero_iff.1 (ennreal.max_eq_zero_iff.1 h).1,
map_add_le' := λ x y, max_le
(le_trans (e₁.map_add_le _ _) $ add_le_add (le_max_left _ _) (le_max_left _ _))
(le_trans (e₂.map_add_le _ _) $ add_le_add (le_max_right _ _) (le_max_right _ _)),
map_smul_le' := λ c x, le_of_eq $ by simp only [map_smul, ennreal.mul_max] },
le_sup_left := λ e₁ e₂ x, le_max_left _ _,
le_sup_right := λ e₁ e₂ x, le_max_right _ _,
sup_le := λ e₁ e₂ e₃ h₁ h₂ x, max_le (h₁ x) (h₂ x),
.. enorm.partial_order }
@[simp, norm_cast] lemma coe_max (e₁ e₂ : enorm 𝕜 V) : ⇑(e₁ ⊔ e₂) = λ x, max (e₁ x) (e₂ x) := rfl
@[norm_cast]
lemma max_map (e₁ e₂ : enorm 𝕜 V) (x : V) : (e₁ ⊔ e₂) x = max (e₁ x) (e₂ x) := rfl
/-- Structure of an `emetric_space` defined by an extended norm. -/
@[reducible] def emetric_space : emetric_space V :=
{ edist := λ x y, e (x - y),
edist_self := λ x, by simp,
eq_of_edist_eq_zero := λ x y, by simp [sub_eq_zero],
edist_comm := e.map_sub_rev,
edist_triangle := λ x y z,
calc e (x - z) = e ((x - y) + (y - z)) : by rw [sub_add_sub_cancel]
... ≤ e (x - y) + e (y - z) : e.map_add_le (x - y) (y - z) }
/-- The subspace of vectors with finite enorm. -/
def finite_subspace : subspace 𝕜 V :=
{ carrier := {x | e x < ⊤},
zero_mem' := by simp,
add_mem' := λ x y hx hy, lt_of_le_of_lt (e.map_add_le x y) (ennreal.add_lt_top.2 ⟨hx, hy⟩),
smul_mem' := λ c x (hx : _ < _),
calc e (c • x) = ‖c‖₊ * e x : e.map_smul c x
... < ⊤ : ennreal.mul_lt_top ennreal.coe_ne_top hx.ne }
/-- Metric space structure on `e.finite_subspace`. We use `emetric_space.to_metric_space`
to ensure that this definition agrees with `e.emetric_space`. -/
instance : metric_space e.finite_subspace :=
begin
letI := e.emetric_space,
refine emetric_space.to_metric_space (λ x y, _),
change e (x - y) ≠ ⊤,
exact ne_top_of_le_ne_top (ennreal.add_lt_top.2 ⟨x.2, y.2⟩).ne (e.map_sub_le x y)
end
lemma finite_dist_eq (x y : e.finite_subspace) : dist x y = (e (x - y)).to_real := rfl
lemma finite_edist_eq (x y : e.finite_subspace) : edist x y = e (x - y) := rfl
/-- Normed group instance on `e.finite_subspace`. -/
instance : normed_add_comm_group e.finite_subspace :=
{ norm := λ x, (e x).to_real,
dist_eq := λ x y, rfl,
.. finite_subspace.metric_space e, .. submodule.add_comm_group _ }
lemma finite_norm_eq (x : e.finite_subspace) : ‖x‖ = (e x).to_real := rfl
/-- Normed space instance on `e.finite_subspace`. -/
instance : normed_space 𝕜 e.finite_subspace :=
{ norm_smul_le := λ c x, le_of_eq $ by simp [finite_norm_eq, ennreal.to_real_mul] }
end enorm
|
57b0920e6767e38b46b3c60a121d178d0c83dff6 | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/run/have2.lean | 8f9ed54daca04485dd294c738212b19aee5738ff | [
"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 | 175 | lean | prelude
definition Prop : Type.{1} := Type.{0}
constants a b c : Prop
axiom Ha : a
axiom Hb : b
axiom Hc : c
#check have H1 : a, from Ha,
have H2 : a, from H1,
H2
|
9e8b99fecbe32472649824c34bf9fe9918da5c2d | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/topology/covering.lean | 79f0fbf19cf3f7f92540cfc0e78e798b1e022ed9 | [
"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 | 7,064 | lean | /-
Copyright (c) 2022 Thomas Browning. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Thomas Browning
-/
import topology.is_locally_homeomorph
import topology.fiber_bundle.basic
/-!
# Covering Maps
This file defines covering maps.
## Main definitions
* `is_evenly_covered f x I`: A point `x` is evenly coverd by `f : E → X` with fiber `I` if `I` is
discrete and there is a `trivialization` of `f` at `x` with fiber `I`.
* `is_covering_map f`: A function `f : E → X` is a covering map if every point `x` is evenly
covered by `f` with fiber `f ⁻¹' {x}`. The fibers `f ⁻¹' {x}` must be discrete, but if `X` is
not connected, then the fibers `f ⁻¹' {x}` are not necessarily isomorphic. Also, `f` is not
assumed to be surjective, so the fibers are even allowed to be empty.
-/
open_locale bundle
variables {E X : Type*} [topological_space E] [topological_space X] (f : E → X) (s : set X)
/-- A point `x : X` is evenly covered by `f : E → X` if `x` has an evenly covered neighborhood. -/
def is_evenly_covered (x : X) (I : Type*) [topological_space I] :=
discrete_topology I ∧ ∃ t : trivialization I f, x ∈ t.base_set
namespace is_evenly_covered
variables {f}
/-- If `x` is evenly covered by `f`, then we can construct a trivialization of `f` at `x`. -/
noncomputable def to_trivialization {x : X} {I : Type*} [topological_space I]
(h : is_evenly_covered f x I) : trivialization (f ⁻¹' {x}) f :=
(classical.some h.2).trans_fiber_homeomorph ((classical.some h.2).preimage_singleton_homeomorph
(classical.some_spec h.2)).symm
lemma mem_to_trivialization_base_set {x : X} {I : Type*} [topological_space I]
(h : is_evenly_covered f x I) : x ∈ h.to_trivialization.base_set :=
classical.some_spec h.2
lemma to_trivialization_apply {x : E} {I : Type*} [topological_space I]
(h : is_evenly_covered f (f x) I) : (h.to_trivialization x).2 = ⟨x, rfl⟩ :=
let e := classical.some h.2, h := classical.some_spec h.2, he := e.mk_proj_snd' h in
subtype.ext ((e.to_local_equiv.eq_symm_apply (e.mem_source.mpr h)
(by rwa [he, e.mem_target, e.coe_fst (e.mem_source.mpr h)])).mpr he.symm).symm
protected lemma continuous_at {x : E} {I : Type*} [topological_space I]
(h : is_evenly_covered f (f x) I) : continuous_at f x :=
let e := h.to_trivialization in
e.continuous_at_proj (e.mem_source.mpr (mem_to_trivialization_base_set h))
lemma to_is_evenly_covered_preimage {x : X} {I : Type*} [topological_space I]
(h : is_evenly_covered f x I) : is_evenly_covered f x (f ⁻¹' {x}) :=
let ⟨h1, h2⟩ := h in by exactI ⟨((classical.some h2).preimage_singleton_homeomorph
(classical.some_spec h2)).embedding.discrete_topology, _, h.mem_to_trivialization_base_set⟩
end is_evenly_covered
/-- A covering map is a continuous function `f : E → X` with discrete fibers such that each point
of `X` has an evenly covered neighborhood. -/
def is_covering_map_on :=
∀ x ∈ s, is_evenly_covered f x (f ⁻¹' {x})
namespace is_covering_map_on
lemma mk (F : X → Type*) [Π x, topological_space (F x)] [hF : Π x, discrete_topology (F x)]
(e : Π x ∈ s, trivialization (F x) f) (h : ∀ (x : X) (hx : x ∈ s), x ∈ (e x hx).base_set) :
is_covering_map_on f s :=
λ x hx, is_evenly_covered.to_is_evenly_covered_preimage ⟨hF x, e x hx, h x hx⟩
variables {f} {s}
protected lemma continuous_at (hf : is_covering_map_on f s) {x : E} (hx : f x ∈ s) :
continuous_at f x :=
(hf (f x) hx).continuous_at
protected lemma continuous_on (hf : is_covering_map_on f s) : continuous_on f (f ⁻¹' s) :=
continuous_at.continuous_on (λ x, hf.continuous_at)
protected lemma is_locally_homeomorph_on (hf : is_covering_map_on f s) :
is_locally_homeomorph_on f (f ⁻¹' s) :=
begin
refine is_locally_homeomorph_on.mk f (f ⁻¹' s) (λ x hx, _),
let e := (hf (f x) hx).to_trivialization,
have h := (hf (f x) hx).mem_to_trivialization_base_set,
let he := e.mem_source.2 h,
refine ⟨e.to_local_homeomorph.trans
{ to_fun := λ p, p.1,
inv_fun := λ p, ⟨p, x, rfl⟩,
source := e.base_set ×ˢ ({⟨x, rfl⟩} : set (f ⁻¹' {f x})),
target := e.base_set,
open_source := e.open_base_set.prod (singletons_open_iff_discrete.2 (hf (f x) hx).1 ⟨x, rfl⟩),
open_target := e.open_base_set,
map_source' := λ p, and.left,
map_target' := λ p hp, ⟨hp, rfl⟩,
left_inv' := λ p hp, prod.ext rfl hp.2.symm,
right_inv' := λ p hp, rfl,
continuous_to_fun := continuous_fst.continuous_on,
continuous_inv_fun := (continuous_id'.prod_mk continuous_const).continuous_on },
⟨he, by rwa [e.to_local_homeomorph.symm_symm, e.proj_to_fun x he],
(hf (f x) hx).to_trivialization_apply⟩, λ p h, (e.proj_to_fun p h.1).symm⟩,
end
end is_covering_map_on
/-- A covering map is a continuous function `f : E → X` with discrete fibers such that each point
of `X` has an evenly covered neighborhood. -/
def is_covering_map :=
∀ x, is_evenly_covered f x (f ⁻¹' {x})
variables {f}
lemma is_covering_map_iff_is_covering_map_on_univ :
is_covering_map f ↔ is_covering_map_on f set.univ :=
by simp only [is_covering_map, is_covering_map_on, set.mem_univ, forall_true_left]
protected lemma is_covering_map.is_covering_map_on (hf : is_covering_map f) :
is_covering_map_on f set.univ :=
is_covering_map_iff_is_covering_map_on_univ.mp hf
variables (f)
namespace is_covering_map
lemma mk (F : X → Type*) [Π x, topological_space (F x)] [hF : Π x, discrete_topology (F x)]
(e : Π x, trivialization (F x) f) (h : ∀ x, x ∈ (e x).base_set) : is_covering_map f :=
is_covering_map_iff_is_covering_map_on_univ.mpr
(is_covering_map_on.mk f set.univ F (λ x hx, e x) (λ x hx, h x))
variables {f}
protected lemma continuous (hf : is_covering_map f) : continuous f :=
continuous_iff_continuous_on_univ.mpr hf.is_covering_map_on.continuous_on
protected lemma is_locally_homeomorph (hf : is_covering_map f) : is_locally_homeomorph f :=
is_locally_homeomorph_iff_is_locally_homeomorph_on_univ.mpr
hf.is_covering_map_on.is_locally_homeomorph_on
protected lemma is_open_map (hf : is_covering_map f) : is_open_map f :=
hf.is_locally_homeomorph.is_open_map
protected lemma quotient_map (hf : is_covering_map f) (hf' : function.surjective f) :
quotient_map f :=
hf.is_open_map.to_quotient_map hf.continuous hf'
end is_covering_map
variables {f}
protected lemma is_fiber_bundle.is_covering_map {F : Type*} [topological_space F]
[discrete_topology F] (hf : ∀ x : X, ∃ e : trivialization F f, x ∈ e.base_set) :
is_covering_map f :=
is_covering_map.mk f (λ x, F) (λ x, classical.some (hf x)) (λ x, classical.some_spec (hf x))
protected lemma fiber_bundle.is_covering_map {F : Type*} {E : X → Type*} [topological_space F]
[discrete_topology F] [topological_space (bundle.total_space E)] [Π x, topological_space (E x)]
[hf : fiber_bundle F E] : is_covering_map (π E) :=
is_fiber_bundle.is_covering_map
(λ x, ⟨trivialization_at F E x, mem_base_set_trivialization_at F E x ⟩)
|
9654a0cdc10858304303a262cc4fe23c4e447204 | 491068d2ad28831e7dade8d6dff871c3e49d9431 | /tests/lean/run/801.lean | a9c70b5250bd94b2d7c30d6211269e0a7315f3be | [
"Apache-2.0"
] | permissive | davidmueller13/lean | 65a3ed141b4088cd0a268e4de80eb6778b21a0e9 | c626e2e3c6f3771e07c32e82ee5b9e030de5b050 | refs/heads/master | 1,611,278,313,401 | 1,444,021,177,000 | 1,444,021,177,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 359 | lean | open nat
definition seq_diagram (A : ℕ → Type) : Type := (Πn, A n → A (succ n))
variables (A : ℕ → Type) (f : seq_diagram A)
include f
definition shift_diag [unfold-full] (k : ℕ) : seq_diagram (λn, A (k + n)) :=
λn a, f (k + n) a
example (n k : ℕ) (b : A (k + n)) : shift_diag A f k n b = sorry :=
begin
esimp,
state,
apply sorry
end
|
0976bd6a10a3a8d7541f3191a60c03d5f39749dd | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/run/dofun_prec.lean | e5e37eecb509311b744306771975a8eb46e8f7b7 | [
"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 | 167 | lean |
def tst1 (x : Nat) : IO Unit := do
if x > 0 then
IO.println "hello"
IO.println "world"
def tst2 (xs : List Nat) : IO Unit :=
xs.forM fun x => do
IO.println x
|
c528abb9e915239b914496622926259579e0013a | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/run/K_new_elab.lean | a923b35daf6bfc9ce257bc7f7094fc97b394d64b | [
"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 | 66 | lean |
theorem ex2 {A : Type} (H : A = A) (a : A) : cast H a = a :=
rfl
|
086ce357e27efdbee810c17a2167d307e80251bc | 367134ba5a65885e863bdc4507601606690974c1 | /src/algebra/category/Module/kernels.lean | 51bc2bd7c796ab264594bfc3eac518f7059dec40 | [
"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 | 2,468 | lean | /-
Copyright (c) 2020 Markus Himmel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Markus Himmel
-/
import algebra.category.Module.basic
/-!
# The concrete (co)kernels in the category of modules are (co)kernels in the categorical sense.
-/
open category_theory
open category_theory.limits
open category_theory.limits.walking_parallel_pair
universes u v
namespace Module
variables {R : Type u} [ring R]
section
variables {M N : Module.{v} R} (f : M ⟶ N)
/-- The kernel cone induced by the concrete kernel. -/
def kernel_cone : kernel_fork f :=
kernel_fork.of_ι (as_hom f.ker.subtype) $ by tidy
/-- The kernel of a linear map is a kernel in the categorical sense. -/
def kernel_is_limit : is_limit (kernel_cone f) :=
fork.is_limit.mk _
(λ s, linear_map.cod_restrict f.ker (fork.ι s) (λ c, linear_map.mem_ker.2 $
by { rw [←@function.comp_apply _ _ _ f (fork.ι s) c, ←coe_comp, fork.condition,
has_zero_morphisms.comp_zero (fork.ι s) N], refl }))
(λ s, linear_map.subtype_comp_cod_restrict _ _ _)
(λ s m h, linear_map.ext $ λ x, subtype.ext_iff_val.2 $
have h₁ : (m ≫ (kernel_cone f).π.app zero).to_fun = (s.π.app zero).to_fun,
by { congr, exact h zero },
by convert @congr_fun _ _ _ _ h₁ x )
/-- The cokernel cocone induced by the projection onto the quotient. -/
def cokernel_cocone : cokernel_cofork f :=
cokernel_cofork.of_π (as_hom f.range.mkq) $ linear_map.range_mkq_comp _
/-- The projection onto the quotient is a cokernel in the categorical sense. -/
def cokernel_is_colimit : is_colimit (cokernel_cocone f) :=
cofork.is_colimit.mk _
(λ s, f.range.liftq (cofork.π s) $ linear_map.range_le_ker_iff.2 $ cokernel_cofork.condition s)
(λ s, f.range.liftq_mkq (cofork.π s) _)
(λ s m h,
begin
haveI : epi (as_hom f.range.mkq) := epi_of_range_eq_top _ (submodule.range_mkq _),
apply (cancel_epi (as_hom f.range.mkq)).1,
convert h walking_parallel_pair.one,
exact submodule.liftq_mkq _ _ _
end)
end
/-- The category of R-modules has kernels, given by the inclusion of the kernel submodule. -/
lemma has_kernels_Module : has_kernels (Module R) :=
⟨λ X Y f, has_limit.mk ⟨_, kernel_is_limit f⟩⟩
/-- The category or R-modules has cokernels, given by the projection onto the quotient. -/
lemma has_cokernels_Module : has_cokernels (Module R) :=
⟨λ X Y f, has_colimit.mk ⟨_, cokernel_is_colimit f⟩⟩
end Module
|
b29b40fa524dc1b252b0e81801ab0513c7adaf4b | 367134ba5a65885e863bdc4507601606690974c1 | /src/order/lattice.lean | 5426e935bae69259a35678ed869d208eddffd255 | [
"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 | 26,423 | 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 order.rel_classes
/-!
# (Semi-)lattices
Semilattices are partially ordered sets with join (greatest lower bound, or `sup`) or
meet (least upper bound, or `inf`) operations. Lattices are posets that are both
join-semilattices and meet-semilattices.
Distributive lattices are lattices which satisfy any of four equivalent distributivity properties,
of `sup` over `inf`, on the left or on the right.
## Main declarations
* `has_sup`: type class for the `⊔` notation
* `has_inf`: type class for the `⊓` notation
* `semilattice_sup`: a type class for join semilattices
* `semilattice_sup.mk'`: an alternative constructor for `semilattice_sup` via proofs that `⊔` is
commutative, associative and idempotent.
* `semilattice_inf`: a type class for meet semilattices
* `semilattice_sup.mk'`: an alternative constructor for `semilattice_inf` via proofs that `⊓` is
commutative, associative and idempotent.
* `lattice`: a type class for lattices
* `lattice.mk'`: an alternative constructor for `lattice` via profs that `⊔` and `⊓` are
commutative, associative and satisfy a pair of "absorption laws".
* `distrib_lattice`: a type class for distributive lattices.
## Notations
* `a ⊔ b`: the supremum or join of `a` and `b`
* `a ⊓ b`: the infimum or meet of `a` and `b`
## TODO
* (Semi-)lattice homomorphisms
* Alternative constructors for distributive lattices from the other distributive properties
## Tags
semilattice, lattice
-/
set_option old_structure_cmd true
universes u v w
variables {α : Type u} {β : Type v}
-- TODO: move this eventually, if we decide to use them
attribute [ematch] le_trans lt_of_le_of_lt lt_of_lt_of_le lt_trans
section
-- TODO: this seems crazy, but it also seems to work reasonably well
@[ematch] theorem le_antisymm' [partial_order α] : ∀ {a b : α}, (: a ≤ b :) → b ≤ a → a = b :=
@le_antisymm _ _
end
/- TODO: automatic construction of dual definitions / theorems -/
/-- Typeclass for the `⊔` (`\lub`) notation -/
class has_sup (α : Type u) := (sup : α → α → α)
/-- Typeclass for the `⊓` (`\glb`) notation -/
class has_inf (α : Type u) := (inf : α → α → α)
infix ⊔ := has_sup.sup
infix ⊓ := has_inf.inf
/-!
### Join-semilattices
-/
/-- A `semilattice_sup` is a join-semilattice, that is, a partial order
with a join (a.k.a. lub / least upper bound, sup / supremum) operation
`⊔` which is the least element larger than both factors. -/
class semilattice_sup (α : Type u) extends has_sup α, partial_order α :=
(le_sup_left : ∀ a b : α, a ≤ a ⊔ b)
(le_sup_right : ∀ a b : α, b ≤ a ⊔ b)
(sup_le : ∀ a b c : α, a ≤ c → b ≤ c → a ⊔ b ≤ c)
/--
A type with a commutative, associative and idempotent binary `sup` operation has the structure of a
join-semilattice.
The partial order is defined so that `a ≤ b` unfolds to `a ⊔ b = b`; cf. `sup_eq_right`.
-/
def semilattice_sup.mk' {α : Type*} [has_sup α]
(sup_comm : ∀ (a b : α), a ⊔ b = b ⊔ a)
(sup_assoc : ∀ (a b c : α), a ⊔ b ⊔ c = a ⊔ (b ⊔ c))
(sup_idem : ∀ (a : α), a ⊔ a = a) : semilattice_sup α :=
{ sup := (⊔),
le := λ a b, a ⊔ b = b,
le_refl := sup_idem,
le_trans := λ a b c hab hbc,
begin
dsimp only [(≤)] at *,
rwa [←hbc, ←sup_assoc, hab],
end,
le_antisymm := λ a b hab hba,
begin
dsimp only [(≤)] at *,
rwa [←hba, sup_comm],
end,
le_sup_left := λ a b, show a ⊔ (a ⊔ b) = (a ⊔ b), by rw [←sup_assoc, sup_idem],
le_sup_right := λ a b, show b ⊔ (a ⊔ b) = (a ⊔ b), by rw [sup_comm, sup_assoc, sup_idem],
sup_le := λ a b c hac hbc,
begin
dsimp only [(≤), preorder.le] at *,
rwa [sup_assoc, hbc],
end }
instance (α : Type*) [has_inf α] : has_sup (order_dual α) := ⟨((⊓) : α → α → α)⟩
instance (α : Type*) [has_sup α] : has_inf (order_dual α) := ⟨((⊔) : α → α → α)⟩
section semilattice_sup
variables [semilattice_sup α] {a b c d : α}
@[simp] theorem le_sup_left : a ≤ a ⊔ b :=
semilattice_sup.le_sup_left a b
@[ematch] theorem le_sup_left' : a ≤ (: a ⊔ b :) :=
le_sup_left
@[simp] theorem le_sup_right : b ≤ a ⊔ b :=
semilattice_sup.le_sup_right a b
@[ematch] theorem le_sup_right' : b ≤ (: a ⊔ b :) :=
le_sup_right
theorem le_sup_left_of_le (h : c ≤ a) : c ≤ a ⊔ b :=
le_trans h le_sup_left
theorem le_sup_right_of_le (h : c ≤ b) : c ≤ a ⊔ b :=
le_trans h le_sup_right
theorem sup_le : a ≤ c → b ≤ c → a ⊔ b ≤ c :=
semilattice_sup.sup_le a b c
@[simp] theorem sup_le_iff : a ⊔ b ≤ c ↔ a ≤ c ∧ b ≤ c :=
⟨assume h : a ⊔ b ≤ c, ⟨le_trans le_sup_left h, le_trans le_sup_right h⟩,
assume ⟨h₁, h₂⟩, sup_le h₁ h₂⟩
@[simp] theorem sup_eq_left : a ⊔ b = a ↔ b ≤ a :=
le_antisymm_iff.trans $ by simp [le_refl]
theorem sup_of_le_left (h : b ≤ a) : a ⊔ b = a :=
sup_eq_left.2 h
@[simp] theorem left_eq_sup : a = a ⊔ b ↔ b ≤ a :=
eq_comm.trans sup_eq_left
@[simp] theorem sup_eq_right : a ⊔ b = b ↔ a ≤ b :=
le_antisymm_iff.trans $ by simp [le_refl]
theorem sup_of_le_right (h : a ≤ b) : a ⊔ b = b :=
sup_eq_right.2 h
@[simp] theorem right_eq_sup : b = a ⊔ b ↔ a ≤ b :=
eq_comm.trans sup_eq_right
theorem sup_le_sup (h₁ : a ≤ b) (h₂ : c ≤ d) : a ⊔ c ≤ b ⊔ d :=
sup_le (le_sup_left_of_le h₁) (le_sup_right_of_le h₂)
theorem sup_le_sup_left (h₁ : a ≤ b) (c) : c ⊔ a ≤ c ⊔ b :=
sup_le_sup (le_refl _) h₁
theorem sup_le_sup_right (h₁ : a ≤ b) (c) : a ⊔ c ≤ b ⊔ c :=
sup_le_sup h₁ (le_refl _)
theorem le_of_sup_eq (h : a ⊔ b = b) : a ≤ b :=
by { rw ← h, simp }
lemma sup_ind [is_total α (≤)] (a b : α) {p : α → Prop} (ha : p a) (hb : p b) : p (a ⊔ b) :=
(is_total.total a b).elim (λ h : a ≤ b, by rwa sup_eq_right.2 h) (λ h, by rwa sup_eq_left.2 h)
@[simp] lemma sup_lt_iff [is_total α (≤)] {a b c : α} : b ⊔ c < a ↔ b < a ∧ c < a :=
⟨λ h, ⟨le_sup_left.trans_lt h, le_sup_right.trans_lt h⟩, λ h, sup_ind b c h.1 h.2⟩
@[simp] lemma le_sup_iff [is_total α (≤)] {a b c : α} : a ≤ b ⊔ c ↔ a ≤ b ∨ a ≤ c :=
by rw [← not_iff_not]; simp only [not_or_distrib, @sup_lt_iff α, @not_le (as_linear_order α)]
@[simp] lemma lt_sup_iff [is_total α (≤)] {a b c : α} : a < b ⊔ c ↔ a < b ∨ a < c :=
by { rw ← not_iff_not, simp only [not_or_distrib, @not_lt (as_linear_order α), sup_le_iff] }
@[simp] theorem sup_idem : a ⊔ a = a :=
by apply le_antisymm; simp
instance sup_is_idempotent : is_idempotent α (⊔) := ⟨@sup_idem _ _⟩
theorem sup_comm : a ⊔ b = b ⊔ a :=
by apply le_antisymm; simp
instance sup_is_commutative : is_commutative α (⊔) := ⟨@sup_comm _ _⟩
theorem sup_assoc : a ⊔ b ⊔ c = a ⊔ (b ⊔ c) :=
le_antisymm
(sup_le
(sup_le le_sup_left (le_sup_right_of_le le_sup_left))
(le_sup_right_of_le le_sup_right))
(sup_le
(le_sup_left_of_le le_sup_left)
(sup_le (le_sup_left_of_le le_sup_right) le_sup_right))
instance sup_is_associative : is_associative α (⊔) := ⟨@sup_assoc _ _⟩
@[simp] lemma sup_left_idem : a ⊔ (a ⊔ b) = a ⊔ b :=
by rw [← sup_assoc, sup_idem]
@[simp] lemma sup_right_idem : (a ⊔ b) ⊔ b = a ⊔ b :=
by rw [sup_assoc, sup_idem]
lemma sup_left_comm (a b c : α) : a ⊔ (b ⊔ c) = b ⊔ (a ⊔ c) :=
by rw [← sup_assoc, ← sup_assoc, @sup_comm α _ a]
lemma sup_right_comm (a b c : α) : a ⊔ b ⊔ c = a ⊔ c ⊔ b :=
by rw [sup_assoc, sup_assoc, @sup_comm _ _ b]
lemma forall_le_or_exists_lt_sup (a : α) : (∀b, b ≤ a) ∨ (∃b, a < b) :=
suffices (∃b, ¬b ≤ a) → (∃b, a < b),
by rwa [or_iff_not_imp_left, not_forall],
assume ⟨b, hb⟩,
⟨a ⊔ b, lt_of_le_of_ne le_sup_left $ mt left_eq_sup.1 hb⟩
/-- If `f` is a monotonically increasing sequence, `g` is a monotonically decreasing
sequence, and `f n ≤ g n` for all `n`, then for all `m`, `n` we have `f m ≤ g n`. -/
theorem forall_le_of_monotone_of_mono_decr {β : Type*} [preorder β]
{f g : α → β} (hf : monotone f) (hg : ∀ ⦃m n⦄, m ≤ n → g n ≤ g m)
(h : ∀ n, f n ≤ g n) (m n : α) : f m ≤ g n :=
calc f m ≤ f (m ⊔ n) : hf le_sup_left
... ≤ g (m ⊔ n) : h _
... ≤ g n : hg le_sup_right
theorem semilattice_sup.ext_sup {α} {A B : semilattice_sup α}
(H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y)
(x y : α) : (by haveI := A; exact (x ⊔ y)) = x ⊔ y :=
eq_of_forall_ge_iff $ λ c,
by simp only [sup_le_iff]; rw [← H, @sup_le_iff α A, H, H]
theorem semilattice_sup.ext {α} {A B : semilattice_sup α}
(H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B :=
begin
have := partial_order.ext H,
have ss := funext (λ x, funext $ semilattice_sup.ext_sup H x),
casesI A, casesI B,
injection this; congr'
end
end semilattice_sup
/-!
### Meet-semilattices
-/
/-- A `semilattice_inf` is a meet-semilattice, that is, a partial order
with a meet (a.k.a. glb / greatest lower bound, inf / infimum) operation
`⊓` which is the greatest element smaller than both factors. -/
class semilattice_inf (α : Type u) extends has_inf α, partial_order α :=
(inf_le_left : ∀ a b : α, a ⊓ b ≤ a)
(inf_le_right : ∀ a b : α, a ⊓ b ≤ b)
(le_inf : ∀ a b c : α, a ≤ b → a ≤ c → a ≤ b ⊓ c)
instance (α) [semilattice_inf α] : semilattice_sup (order_dual α) :=
{ le_sup_left := semilattice_inf.inf_le_left,
le_sup_right := semilattice_inf.inf_le_right,
sup_le := assume a b c hca hcb, @semilattice_inf.le_inf α _ _ _ _ hca hcb,
.. order_dual.partial_order α, .. order_dual.has_sup α }
instance (α) [semilattice_sup α] : semilattice_inf (order_dual α) :=
{ inf_le_left := @le_sup_left α _,
inf_le_right := @le_sup_right α _,
le_inf := assume a b c hca hcb, @sup_le α _ _ _ _ hca hcb,
.. order_dual.partial_order α, .. order_dual.has_inf α }
theorem semilattice_sup.dual_dual (α : Type*) [H : semilattice_sup α] :
order_dual.semilattice_sup (order_dual α) = H :=
semilattice_sup.ext $ λ _ _, iff.rfl
section semilattice_inf
variables [semilattice_inf α] {a b c d : α}
@[simp] theorem inf_le_left : a ⊓ b ≤ a :=
semilattice_inf.inf_le_left a b
@[ematch] theorem inf_le_left' : (: a ⊓ b :) ≤ a :=
semilattice_inf.inf_le_left a b
@[simp] theorem inf_le_right : a ⊓ b ≤ b :=
semilattice_inf.inf_le_right a b
@[ematch] theorem inf_le_right' : (: a ⊓ b :) ≤ b :=
semilattice_inf.inf_le_right a b
theorem le_inf : a ≤ b → a ≤ c → a ≤ b ⊓ c :=
semilattice_inf.le_inf a b c
theorem inf_le_left_of_le (h : a ≤ c) : a ⊓ b ≤ c :=
le_trans inf_le_left h
theorem inf_le_right_of_le (h : b ≤ c) : a ⊓ b ≤ c :=
le_trans inf_le_right h
@[simp] theorem le_inf_iff : a ≤ b ⊓ c ↔ a ≤ b ∧ a ≤ c :=
@sup_le_iff (order_dual α) _ _ _ _
@[simp] theorem inf_eq_left : a ⊓ b = a ↔ a ≤ b :=
le_antisymm_iff.trans $ by simp [le_refl]
theorem inf_of_le_left (h : a ≤ b) : a ⊓ b = a :=
inf_eq_left.2 h
@[simp] theorem left_eq_inf : a = a ⊓ b ↔ a ≤ b :=
eq_comm.trans inf_eq_left
@[simp] theorem inf_eq_right : a ⊓ b = b ↔ b ≤ a :=
le_antisymm_iff.trans $ by simp [le_refl]
theorem inf_of_le_right (h : b ≤ a) : a ⊓ b = b :=
inf_eq_right.2 h
@[simp] theorem right_eq_inf : b = a ⊓ b ↔ b ≤ a :=
eq_comm.trans inf_eq_right
theorem inf_le_inf (h₁ : a ≤ b) (h₂ : c ≤ d) : a ⊓ c ≤ b ⊓ d :=
le_inf (inf_le_left_of_le h₁) (inf_le_right_of_le h₂)
lemma inf_le_inf_right (a : α) {b c : α} (h : b ≤ c) : b ⊓ a ≤ c ⊓ a :=
inf_le_inf h (le_refl _)
lemma inf_le_inf_left (a : α) {b c : α} (h : b ≤ c) : a ⊓ b ≤ a ⊓ c :=
inf_le_inf (le_refl _) h
theorem le_of_inf_eq (h : a ⊓ b = a) : a ≤ b :=
by { rw ← h, simp }
lemma inf_ind [is_total α (≤)] (a b : α) {p : α → Prop} (ha : p a) (hb : p b) : p (a ⊓ b) :=
@sup_ind (order_dual α) _ _ _ _ _ ha hb
@[simp] lemma lt_inf_iff [is_total α (≤)] {a b c : α} : a < b ⊓ c ↔ a < b ∧ a < c :=
@sup_lt_iff (order_dual α) _ _ _ _ _
@[simp] lemma inf_le_iff [is_total α (≤)] {a b c : α} : b ⊓ c ≤ a ↔ b ≤ a ∨ c ≤ a :=
@le_sup_iff (order_dual α) _ _ _ _ _
@[simp] theorem inf_idem : a ⊓ a = a :=
@sup_idem (order_dual α) _ _
instance inf_is_idempotent : is_idempotent α (⊓) := ⟨@inf_idem _ _⟩
theorem inf_comm : a ⊓ b = b ⊓ a :=
@sup_comm (order_dual α) _ _ _
instance inf_is_commutative : is_commutative α (⊓) := ⟨@inf_comm _ _⟩
theorem inf_assoc : a ⊓ b ⊓ c = a ⊓ (b ⊓ c) :=
@sup_assoc (order_dual α) _ a b c
instance inf_is_associative : is_associative α (⊓) := ⟨@inf_assoc _ _⟩
@[simp] lemma inf_left_idem : a ⊓ (a ⊓ b) = a ⊓ b :=
@sup_left_idem (order_dual α) _ a b
@[simp] lemma inf_right_idem : (a ⊓ b) ⊓ b = a ⊓ b :=
@sup_right_idem (order_dual α) _ a b
lemma inf_left_comm (a b c : α) : a ⊓ (b ⊓ c) = b ⊓ (a ⊓ c) :=
@sup_left_comm (order_dual α) _ a b c
lemma inf_right_comm (a b c : α) : a ⊓ b ⊓ c = a ⊓ c ⊓ b :=
@sup_right_comm (order_dual α) _ a b c
lemma forall_le_or_exists_lt_inf (a : α) : (∀b, a ≤ b) ∨ (∃b, b < a) :=
@forall_le_or_exists_lt_sup (order_dual α) _ a
theorem semilattice_inf.ext_inf {α} {A B : semilattice_inf α}
(H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y)
(x y : α) : (by haveI := A; exact (x ⊓ y)) = x ⊓ y :=
eq_of_forall_le_iff $ λ c,
by simp only [le_inf_iff]; rw [← H, @le_inf_iff α A, H, H]
theorem semilattice_inf.ext {α} {A B : semilattice_inf α}
(H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B :=
begin
have := partial_order.ext H,
have ss := funext (λ x, funext $ semilattice_inf.ext_inf H x),
casesI A, casesI B,
injection this; congr'
end
theorem semilattice_inf.dual_dual (α : Type*) [H : semilattice_inf α] :
order_dual.semilattice_inf (order_dual α) = H :=
semilattice_inf.ext $ λ _ _, iff.rfl
end semilattice_inf
/--
A type with a commutative, associative and idempotent binary `inf` operation has the structure of a
meet-semilattice.
The partial order is defined so that `a ≤ b` unfolds to `b ⊓ a = a`; cf. `inf_eq_right`.
-/
def semilattice_inf.mk' {α : Type*} [has_inf α]
(inf_comm : ∀ (a b : α), a ⊓ b = b ⊓ a)
(inf_assoc : ∀ (a b c : α), a ⊓ b ⊓ c = a ⊓ (b ⊓ c))
(inf_idem : ∀ (a : α), a ⊓ a = a) : semilattice_inf α :=
begin
haveI : semilattice_sup (order_dual α) := semilattice_sup.mk' inf_comm inf_assoc inf_idem,
haveI i := order_dual.semilattice_inf (order_dual α),
exact i,
end
/-!
### Lattices
-/
/-- A lattice is a join-semilattice which is also a meet-semilattice. -/
class lattice (α : Type u) extends semilattice_sup α, semilattice_inf α
instance (α) [lattice α] : lattice (order_dual α) :=
{ .. order_dual.semilattice_sup α, .. order_dual.semilattice_inf α }
/-- The partial orders from `semilattice_sup_mk'` and `semilattice_inf_mk'` agree
if `sup` and `inf` satisfy the lattice absorption laws `sup_inf_self` (`a ⊔ a ⊓ b = a`)
and `inf_sup_self` (`a ⊓ (a ⊔ b) = a`). -/
lemma semilattice_sup_mk'_partial_order_eq_semilattice_inf_mk'_partial_order {α : Type*}
[has_sup α] [has_inf α]
(sup_comm : ∀ (a b : α), a ⊔ b = b ⊔ a)
(sup_assoc : ∀ (a b c : α), a ⊔ b ⊔ c = a ⊔ (b ⊔ c))
(sup_idem : ∀ (a : α), a ⊔ a = a)
(inf_comm : ∀ (a b : α), a ⊓ b = b ⊓ a)
(inf_assoc : ∀ (a b c : α), a ⊓ b ⊓ c = a ⊓ (b ⊓ c))
(inf_idem : ∀ (a : α), a ⊓ a = a)
(sup_inf_self : ∀ (a b : α), a ⊔ a ⊓ b = a)
(inf_sup_self : ∀ (a b : α), a ⊓ (a ⊔ b) = a) :
@semilattice_sup.to_partial_order _ (semilattice_sup.mk' sup_comm sup_assoc sup_idem) =
@semilattice_inf.to_partial_order _ (semilattice_inf.mk' inf_comm inf_assoc inf_idem) :=
partial_order.ext $ λ a b, show a ⊔ b = b ↔ b ⊓ a = a, from
⟨λ h, by rw [←h, inf_comm, inf_sup_self],
λ h, by rw [←h, sup_comm, sup_inf_self]⟩
/--
A type with a pair of commutative and associative binary operations which satisfy two absorption
laws relating the two operations has the structure of a lattice.
The partial order is defined so that `a ≤ b` unfolds to `a ⊔ b = b`; cf. `sup_eq_right`.
-/
def lattice.mk' {α : Type*} [has_sup α] [has_inf α]
(sup_comm : ∀ (a b : α), a ⊔ b = b ⊔ a)
(sup_assoc : ∀ (a b c : α), a ⊔ b ⊔ c = a ⊔ (b ⊔ c))
(inf_comm : ∀ (a b : α), a ⊓ b = b ⊓ a)
(inf_assoc : ∀ (a b c : α), a ⊓ b ⊓ c = a ⊓ (b ⊓ c))
(sup_inf_self : ∀ (a b : α), a ⊔ a ⊓ b = a)
(inf_sup_self : ∀ (a b : α), a ⊓ (a ⊔ b) = a) : lattice α :=
have sup_idem : ∀ (b : α), b ⊔ b = b := λ b,
calc b ⊔ b = b ⊔ b ⊓ (b ⊔ b) : by rw inf_sup_self
... = b : by rw sup_inf_self,
have inf_idem : ∀ (b : α), b ⊓ b = b := λ b,
calc b ⊓ b = b ⊓ (b ⊔ b ⊓ b) : by rw sup_inf_self
... = b : by rw inf_sup_self,
let semilatt_inf_inst := semilattice_inf.mk' inf_comm inf_assoc inf_idem,
semilatt_sup_inst := semilattice_sup.mk' sup_comm sup_assoc sup_idem,
-- here we help Lean to see that the two partial orders are equal
partial_order_inst := @semilattice_sup.to_partial_order _ semilatt_sup_inst in
have partial_order_eq :
partial_order_inst = @semilattice_inf.to_partial_order _ semilatt_inf_inst :=
semilattice_sup_mk'_partial_order_eq_semilattice_inf_mk'_partial_order _ _ _ _ _ _
sup_inf_self inf_sup_self,
{ inf_le_left := λ a b, by { rw partial_order_eq, apply inf_le_left },
inf_le_right := λ a b, by { rw partial_order_eq, apply inf_le_right },
le_inf := λ a b c, by { rw partial_order_eq, apply le_inf },
..partial_order_inst,
..semilatt_sup_inst,
..semilatt_inf_inst, }
section lattice
variables [lattice α] {a b c d : α}
/-!
#### Distributivity laws
-/
/- TODO: better names? -/
theorem sup_inf_le : a ⊔ (b ⊓ c) ≤ (a ⊔ b) ⊓ (a ⊔ c) :=
le_inf (sup_le_sup_left inf_le_left _) (sup_le_sup_left inf_le_right _)
theorem le_inf_sup : (a ⊓ b) ⊔ (a ⊓ c) ≤ a ⊓ (b ⊔ c) :=
sup_le (inf_le_inf_left _ le_sup_left) (inf_le_inf_left _ le_sup_right)
theorem inf_sup_self : a ⊓ (a ⊔ b) = a :=
by simp
theorem sup_inf_self : a ⊔ (a ⊓ b) = a :=
by simp
theorem sup_eq_iff_inf_eq : a ⊔ b = b ↔ a ⊓ b = a :=
by rw [sup_eq_right, ←inf_eq_left]
theorem lattice.ext {α} {A B : lattice α}
(H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B :=
begin
have SS : @lattice.to_semilattice_sup α A =
@lattice.to_semilattice_sup α B := semilattice_sup.ext H,
have II := semilattice_inf.ext H,
casesI A, casesI B,
injection SS; injection II; congr'
end
end lattice
/-!
### Distributive lattices
-/
/-- A distributive lattice is a lattice that satisfies any of four
equivalent distributive properties (of `sup` over `inf` or `inf` over `sup`,
on the left or right).
The definition here chooses `le_sup_inf`: `(x ⊔ y) ⊓ (x ⊔ z) ≤ x ⊔ (y ⊓ z)`.
A classic example of a distributive lattice
is the lattice of subsets of a set, and in fact this example is
generic in the sense that every distributive lattice is realizable
as a sublattice of a powerset lattice. -/
class distrib_lattice α extends lattice α :=
(le_sup_inf : ∀x y z : α, (x ⊔ y) ⊓ (x ⊔ z) ≤ x ⊔ (y ⊓ z))
/- TODO: alternative constructors from the other distributive properties,
and perhaps a `tfae` statement -/
section distrib_lattice
variables [distrib_lattice α] {x y z : α}
theorem le_sup_inf : ∀{x y z : α}, (x ⊔ y) ⊓ (x ⊔ z) ≤ x ⊔ (y ⊓ z) :=
distrib_lattice.le_sup_inf
theorem sup_inf_left : x ⊔ (y ⊓ z) = (x ⊔ y) ⊓ (x ⊔ z) :=
le_antisymm sup_inf_le le_sup_inf
theorem sup_inf_right : (y ⊓ z) ⊔ x = (y ⊔ x) ⊓ (z ⊔ x) :=
by simp only [sup_inf_left, λy:α, @sup_comm α _ y x, eq_self_iff_true]
theorem inf_sup_left : x ⊓ (y ⊔ z) = (x ⊓ y) ⊔ (x ⊓ z) :=
calc x ⊓ (y ⊔ z) = (x ⊓ (x ⊔ z)) ⊓ (y ⊔ z) : by rw [inf_sup_self]
... = x ⊓ ((x ⊓ y) ⊔ z) : by simp only [inf_assoc, sup_inf_right,
eq_self_iff_true]
... = (x ⊔ (x ⊓ y)) ⊓ ((x ⊓ y) ⊔ z) : by rw [sup_inf_self]
... = ((x ⊓ y) ⊔ x) ⊓ ((x ⊓ y) ⊔ z) : by rw [sup_comm]
... = (x ⊓ y) ⊔ (x ⊓ z) : by rw [sup_inf_left]
instance (α : Type*) [distrib_lattice α] : distrib_lattice (order_dual α) :=
{ le_sup_inf := assume x y z, le_of_eq inf_sup_left.symm,
.. order_dual.lattice α }
theorem inf_sup_right : (y ⊔ z) ⊓ x = (y ⊓ x) ⊔ (z ⊓ x) :=
by simp only [inf_sup_left, λy:α, @inf_comm α _ y x, eq_self_iff_true]
lemma le_of_inf_le_sup_le (h₁ : x ⊓ z ≤ y ⊓ z) (h₂ : x ⊔ z ≤ y ⊔ z) : x ≤ y :=
calc x ≤ (y ⊓ z) ⊔ x : le_sup_right
... = (y ⊔ x) ⊓ (x ⊔ z) : by rw [sup_inf_right, @sup_comm _ _ x]
... ≤ (y ⊔ x) ⊓ (y ⊔ z) : inf_le_inf_left _ h₂
... = y ⊔ (x ⊓ z) : sup_inf_left.symm
... ≤ y ⊔ (y ⊓ z) : sup_le_sup_left h₁ _
... ≤ _ : sup_le (le_refl y) inf_le_left
lemma eq_of_inf_eq_sup_eq {α : Type u} [distrib_lattice α] {a b c : α}
(h₁ : b ⊓ a = c ⊓ a) (h₂ : b ⊔ a = c ⊔ a) : b = c :=
le_antisymm
(le_of_inf_le_sup_le (le_of_eq h₁) (le_of_eq h₂))
(le_of_inf_le_sup_le (le_of_eq h₁.symm) (le_of_eq h₂.symm))
end distrib_lattice
/-!
### Lattices derived from linear orders
-/
@[priority 100] -- see Note [lower instance priority]
instance lattice_of_linear_order {α : Type u} [o : linear_order α] :
lattice α :=
{ sup := max,
le_sup_left := le_max_left,
le_sup_right := le_max_right,
sup_le := assume a b c, max_le,
inf := min,
inf_le_left := min_le_left,
inf_le_right := min_le_right,
le_inf := assume a b c, le_min,
..o }
theorem sup_eq_max [linear_order α] {x y : α} : x ⊔ y = max x y := rfl
theorem inf_eq_min [linear_order α] {x y : α} : x ⊓ y = min x y := rfl
@[priority 100] -- see Note [lower instance priority]
instance distrib_lattice_of_linear_order {α : Type u} [o : linear_order α] :
distrib_lattice α :=
{ le_sup_inf := assume a b c,
match le_total b c with
| or.inl h := inf_le_left_of_le $ sup_le_sup_left (le_inf (le_refl b) h) _
| or.inr h := inf_le_right_of_le $ sup_le_sup_left (le_inf h (le_refl c)) _
end,
..lattice_of_linear_order }
instance nat.distrib_lattice : distrib_lattice ℕ :=
by apply_instance
/-!
### Monotone functions and lattices
-/
namespace monotone
lemma le_map_sup [semilattice_sup α] [semilattice_sup β]
{f : α → β} (h : monotone f) (x y : α) :
f x ⊔ f y ≤ f (x ⊔ y) :=
sup_le (h le_sup_left) (h le_sup_right)
lemma map_sup [semilattice_sup α] [is_total α (≤)] [semilattice_sup β] {f : α → β}
(hf : monotone f) (x y : α) :
f (x ⊔ y) = f x ⊔ f y :=
(is_total.total x y).elim
(λ h : x ≤ y, by simp only [h, hf h, sup_of_le_right])
(λ h, by simp only [h, hf h, sup_of_le_left])
lemma map_inf_le [semilattice_inf α] [semilattice_inf β]
{f : α → β} (h : monotone f) (x y : α) :
f (x ⊓ y) ≤ f x ⊓ f y :=
le_inf (h inf_le_left) (h inf_le_right)
lemma map_inf [semilattice_inf α] [is_total α (≤)] [semilattice_inf β] {f : α → β}
(hf : monotone f) (x y : α) :
f (x ⊓ y) = f x ⊓ f y :=
@monotone.map_sup (order_dual α) _ _ _ _ _ hf.order_dual x y
end monotone
/-!
### Products of (semi-)lattices
-/
namespace prod
variables (α β)
instance [has_sup α] [has_sup β] : has_sup (α × β) := ⟨λp q, ⟨p.1 ⊔ q.1, p.2 ⊔ q.2⟩⟩
instance [has_inf α] [has_inf β] : has_inf (α × β) := ⟨λp q, ⟨p.1 ⊓ q.1, p.2 ⊓ q.2⟩⟩
instance [semilattice_sup α] [semilattice_sup β] : semilattice_sup (α × β) :=
{ sup_le := assume a b c h₁ h₂, ⟨sup_le h₁.1 h₂.1, sup_le h₁.2 h₂.2⟩,
le_sup_left := assume a b, ⟨le_sup_left, le_sup_left⟩,
le_sup_right := assume a b, ⟨le_sup_right, le_sup_right⟩,
.. prod.partial_order α β, .. prod.has_sup α β }
instance [semilattice_inf α] [semilattice_inf β] : semilattice_inf (α × β) :=
{ le_inf := assume a b c h₁ h₂, ⟨le_inf h₁.1 h₂.1, le_inf h₁.2 h₂.2⟩,
inf_le_left := assume a b, ⟨inf_le_left, inf_le_left⟩,
inf_le_right := assume a b, ⟨inf_le_right, inf_le_right⟩,
.. prod.partial_order α β, .. prod.has_inf α β }
instance [lattice α] [lattice β] : lattice (α × β) :=
{ .. prod.semilattice_inf α β, .. prod.semilattice_sup α β }
instance [distrib_lattice α] [distrib_lattice β] : distrib_lattice (α × β) :=
{ le_sup_inf := assume a b c, ⟨le_sup_inf, le_sup_inf⟩,
.. prod.lattice α β }
end prod
/-!
### Subtypes of (semi-)lattices
-/
namespace subtype
/-- A subtype forms a `⊔`-semilattice if `⊔` preserves the property. -/
protected def semilattice_sup [semilattice_sup α] {P : α → Prop}
(Psup : ∀⦃x y⦄, P x → P y → P (x ⊔ y)) : semilattice_sup {x : α // P x} :=
{ sup := λ x y, ⟨x.1 ⊔ y.1, Psup x.2 y.2⟩,
le_sup_left := λ x y, @le_sup_left _ _ (x : α) y,
le_sup_right := λ x y, @le_sup_right _ _ (x : α) y,
sup_le := λ x y z h1 h2, @sup_le α _ _ _ _ h1 h2,
..subtype.partial_order P }
/-- A subtype forms a `⊓`-semilattice if `⊓` preserves the property. -/
protected def semilattice_inf [semilattice_inf α] {P : α → Prop}
(Pinf : ∀⦃x y⦄, P x → P y → P (x ⊓ y)) : semilattice_inf {x : α // P x} :=
{ inf := λ x y, ⟨x.1 ⊓ y.1, Pinf x.2 y.2⟩,
inf_le_left := λ x y, @inf_le_left _ _ (x : α) y,
inf_le_right := λ x y, @inf_le_right _ _ (x : α) y,
le_inf := λ x y z h1 h2, @le_inf α _ _ _ _ h1 h2,
..subtype.partial_order P }
/-- A subtype forms a lattice if `⊔` and `⊓` preserve the property. -/
protected def lattice [lattice α] {P : α → Prop}
(Psup : ∀⦃x y⦄, P x → P y → P (x ⊔ y)) (Pinf : ∀⦃x y⦄, P x → P y → P (x ⊓ y)) :
lattice {x : α // P x} :=
{ ..subtype.semilattice_inf Pinf, ..subtype.semilattice_sup Psup }
end subtype
|
5ba32338758556be675520c0fe83f8681971d96a | 35b83be3126daae10419b573c55e1fed009d3ae8 | /_target/deps/mathlib/data/rat.lean | 91b0a1a100ff55cb3170b36a19b40b19b5cb1363 | [] | no_license | AHassan1024/Lean_Playground | ccb25b72029d199c0d23d002db2d32a9f2689ebc | a00b004c3a2eb9e3e863c361aa2b115260472414 | refs/heads/master | 1,586,221,905,125 | 1,544,951,310,000 | 1,544,951,310,000 | 157,934,290 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 42,041 | 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
Introduces the rational numbers as discrete, linear ordered field.
-/
import
data.nat.gcd data.pnat data.int.basic data.equiv.encodable order.basic
algebra.ordered_field data.real.cau_seq
/- rational numbers -/
/-- `rat`, or `ℚ`, is the type of rational numbers. It is defined
as the set of pairs ⟨n, d⟩ of integers such that `d` is positive and `n` and
`d` are coprime. This representation is preferred to the quotient
because without periodic reduction, the numerator and denominator can grow
exponentially (for example, adding 1/2 to itself repeatedly). -/
structure rat := mk' ::
(num : ℤ)
(denom : ℕ)
(pos : denom > 0)
(cop : num.nat_abs.coprime denom)
notation `ℚ` := rat
namespace rat
protected def repr : ℚ → string
| ⟨n, d, _, _⟩ := if d = 1 then _root_.repr n else
_root_.repr n ++ "/" ++ _root_.repr d
instance : has_repr ℚ := ⟨rat.repr⟩
instance : has_to_string ℚ := ⟨rat.repr⟩
meta instance : has_to_format ℚ := ⟨coe ∘ rat.repr⟩
instance : encodable ℚ := encodable.of_equiv (Σ n : ℤ, {d : ℕ // d > 0 ∧ n.nat_abs.coprime d})
⟨λ ⟨a, b, c, d⟩, ⟨a, b, c, d⟩, λ⟨a, b, c, d⟩, ⟨a, b, c, d⟩,
λ ⟨a, b, c, d⟩, rfl, λ⟨a, b, c, d⟩, rfl⟩
/-- Embed an integer as a rational number -/
def of_int (n : ℤ) : ℚ :=
⟨n, 1, nat.one_pos, nat.coprime_one_right _⟩
instance : has_zero ℚ := ⟨of_int 0⟩
instance : has_one ℚ := ⟨of_int 1⟩
instance : inhabited ℚ := ⟨0⟩
/-- Form the quotient `n / d` where `n:ℤ` and `d:ℕ+` (not necessarily coprime) -/
def mk_pnat (n : ℤ) : ℕ+ → ℚ | ⟨d, dpos⟩ :=
let n' := n.nat_abs, g := n'.gcd d in
⟨n / g, d / g, begin
apply (nat.le_div_iff_mul_le _ _ (nat.gcd_pos_of_pos_right _ dpos)).2,
simp, exact nat.le_of_dvd dpos (nat.gcd_dvd_right _ _)
end, begin
have : int.nat_abs (n / ↑g) = n' / g,
{ cases int.nat_abs_eq n with e e; rw e, { refl },
rw [int.neg_div_of_dvd, int.nat_abs_neg], { refl },
exact int.coe_nat_dvd.2 (nat.gcd_dvd_left _ _) },
rw this,
exact nat.coprime_div_gcd_div_gcd (nat.gcd_pos_of_pos_right _ dpos)
end⟩
/-- Form the quotient `n / d` where `n:ℤ` and `d:ℕ`. In the case `d = 0`, we
define `n / 0 = 0` by convention. -/
def mk_nat (n : ℤ) (d : ℕ) : ℚ :=
if d0 : d = 0 then 0 else mk_pnat n ⟨d, nat.pos_of_ne_zero d0⟩
/-- Form the quotient `n / d` where `n d : ℤ`. -/
def mk : ℤ → ℤ → ℚ
| n (int.of_nat d) := mk_nat n d
| n -[1+ d] := mk_pnat (-n) d.succ_pnat
local infix ` /. `:70 := mk
theorem mk_pnat_eq (n d h) : mk_pnat n ⟨d, h⟩ = n /. d :=
by change n /. d with dite _ _ _; simp [ne_of_gt h]
theorem mk_nat_eq (n d) : mk_nat n d = n /. d := rfl
@[simp] theorem mk_zero (n) : n /. 0 = 0 := rfl
@[simp] theorem zero_mk_pnat (n) : mk_pnat 0 n = 0 :=
by cases n; simp [mk_pnat]; change int.nat_abs 0 with 0; simp *; refl
@[simp] theorem zero_mk_nat (n) : mk_nat 0 n = 0 :=
by by_cases n = 0; simp [*, mk_nat]
@[simp] theorem zero_mk (n) : 0 /. n = 0 :=
by cases n; simp [mk]
private lemma gcd_abs_dvd_left {a b} : (nat.gcd (int.nat_abs a) b : ℤ) ∣ a :=
int.dvd_nat_abs.1 $ int.coe_nat_dvd.2 $ nat.gcd_dvd_left (int.nat_abs a) b
@[simp] theorem mk_eq_zero {a b : ℤ} (b0 : b ≠ 0) : a /. b = 0 ↔ a = 0 :=
begin
constructor; intro h; [skip, {subst a, simp}],
have : ∀ {a b}, mk_pnat a b = 0 → a = 0,
{ intros a b e, cases b with b h,
injection e with e,
apply int.eq_mul_of_div_eq_right gcd_abs_dvd_left e },
cases b with b; simp [mk, mk_nat] at h,
{ simp [mt (congr_arg int.of_nat) b0] at h,
exact this h },
{ apply neg_inj, simp [this h] }
end
theorem mk_eq : ∀ {a b c d : ℤ} (hb : b ≠ 0) (hd : d ≠ 0),
a /. b = c /. d ↔ a * d = c * b :=
suffices ∀ a b c d hb hd, mk_pnat a ⟨b, hb⟩ = mk_pnat c ⟨d, hd⟩ ↔ a * d = c * b,
begin
intros, cases b with b b; simp [mk, mk_nat, nat.succ_pnat],
simp [mt (congr_arg int.of_nat) hb],
all_goals {
cases d with d d; simp [mk, mk_nat, nat.succ_pnat],
simp [mt (congr_arg int.of_nat) hd],
all_goals { rw this, try {refl} } },
{ change a * ↑(d.succ) = -c * ↑b ↔ a * -(d.succ) = c * b,
constructor; intro h; apply neg_inj; simpa [left_distrib, neg_add_eq_iff_eq_add,
eq_neg_iff_add_eq_zero, neg_eq_iff_add_eq_zero] using h },
{ change -a * ↑d = c * b.succ ↔ a * d = c * -b.succ,
constructor; intro h; apply neg_inj; simpa [left_distrib, eq_comm] using h },
{ change -a * d.succ = -c * b.succ ↔ a * -d.succ = c * -b.succ,
simp [left_distrib] }
end,
begin
intros, simp [mk_pnat], constructor; intro h,
{ cases h with ha hb,
have ha, {
have dv := @gcd_abs_dvd_left,
have := int.eq_mul_of_div_eq_right dv ha,
rw ← int.mul_div_assoc _ dv at this,
exact int.eq_mul_of_div_eq_left (dvd_mul_of_dvd_right dv _) this.symm },
have hb, {
have dv := λ {a b}, nat.gcd_dvd_right (int.nat_abs a) b,
have := nat.eq_mul_of_div_eq_right dv hb,
rw ← nat.mul_div_assoc _ dv at this,
exact nat.eq_mul_of_div_eq_left (dvd_mul_of_dvd_right dv _) this.symm },
have m0 : (a.nat_abs.gcd b * c.nat_abs.gcd d : ℤ) ≠ 0, {
refine int.coe_nat_ne_zero.2 (ne_of_gt _),
apply mul_pos; apply nat.gcd_pos_of_pos_right; assumption },
apply eq_of_mul_eq_mul_right m0,
simpa [mul_comm, mul_left_comm] using
congr (congr_arg (*) ha.symm) (congr_arg coe hb) },
{ suffices : ∀ a c, a * d = c * b →
a / a.gcd b = c / c.gcd d ∧ b / a.gcd b = d / c.gcd d,
{ cases this a.nat_abs c.nat_abs
(by simpa [int.nat_abs_mul] using congr_arg int.nat_abs h) with h₁ h₂,
have hs := congr_arg int.sign h,
simp [int.sign_eq_one_of_pos (int.coe_nat_lt.2 hb),
int.sign_eq_one_of_pos (int.coe_nat_lt.2 hd)] at hs,
conv in a { rw ← int.sign_mul_nat_abs a },
conv in c { rw ← int.sign_mul_nat_abs c },
rw [int.mul_div_assoc, int.mul_div_assoc],
exact ⟨congr (congr_arg (*) hs) (congr_arg coe h₁), h₂⟩,
all_goals { exact int.coe_nat_dvd.2 (nat.gcd_dvd_left _ _) } },
intros a c h,
suffices bd : b / a.gcd b = d / c.gcd d,
{ refine ⟨_, bd⟩,
apply nat.eq_of_mul_eq_mul_left hb,
rw [← nat.mul_div_assoc _ (nat.gcd_dvd_left _ _), mul_comm,
nat.mul_div_assoc _ (nat.gcd_dvd_right _ _), bd,
← nat.mul_div_assoc _ (nat.gcd_dvd_right _ _), h, mul_comm,
nat.mul_div_assoc _ (nat.gcd_dvd_left _ _)] },
suffices : ∀ {a c : ℕ} (b>0) (d>0),
a * d = c * b → b / a.gcd b ≤ d / c.gcd d,
{ exact le_antisymm (this _ hb _ hd h) (this _ hd _ hb h.symm) },
intros a c b hb d hd h,
have gb0 := nat.gcd_pos_of_pos_right a hb,
have gd0 := nat.gcd_pos_of_pos_right c hd,
apply nat.le_of_dvd,
apply (nat.le_div_iff_mul_le _ _ gd0).2,
simp, apply nat.le_of_dvd hd (nat.gcd_dvd_right _ _),
apply (nat.coprime_div_gcd_div_gcd gb0).symm.dvd_of_dvd_mul_left,
refine ⟨c / c.gcd d, _⟩,
rw [← nat.mul_div_assoc _ (nat.gcd_dvd_left _ _),
← nat.mul_div_assoc _ (nat.gcd_dvd_right _ _)],
apply congr_arg (/ c.gcd d),
rw [mul_comm, ← nat.mul_div_assoc _ (nat.gcd_dvd_left _ _),
mul_comm, h, nat.mul_div_assoc _ (nat.gcd_dvd_right _ _), mul_comm] }
end
@[simp] theorem div_mk_div_cancel_left {a b c : ℤ} (c0 : c ≠ 0) :
(a * c) /. (b * c) = a /. b :=
begin
by_cases b0 : b = 0, { subst b0, simp },
apply (mk_eq (mul_ne_zero b0 c0) b0).2, simp [mul_comm, mul_assoc]
end
theorem num_denom : ∀ a : ℚ, a = a.num /. a.denom
| ⟨n, d, h, (c:_=1)⟩ := show _ = mk_nat n d,
by simp [mk_nat, ne_of_gt h, mk_pnat, c]
theorem num_denom' (n d h c) : (⟨n, d, h, c⟩ : ℚ) = n /. d := num_denom _
@[elab_as_eliminator] theorem {u} num_denom_cases_on {C : ℚ → Sort u}
: ∀ (a : ℚ) (H : ∀ n d, d > 0 → (int.nat_abs n).coprime d → C (n /. d)), C a
| ⟨n, d, h, c⟩ H := by rw num_denom'; exact H n d h c
@[elab_as_eliminator] theorem {u} num_denom_cases_on' {C : ℚ → Sort u}
(a : ℚ) (H : ∀ (n:ℤ) (d:ℕ), d ≠ 0 → C (n /. d)) : C a :=
num_denom_cases_on a $ λ n d h c,
H n d $ ne_of_gt h
theorem num_dvd (a) {b : ℤ} (b0 : b ≠ 0) : (a /. b).num ∣ a :=
begin
cases e : a /. b with n d h c,
rw [rat.num_denom', rat.mk_eq b0
(ne_of_gt (int.coe_nat_pos.2 h))] at e,
refine (int.nat_abs_dvd.1 $ int.dvd_nat_abs.1 $ int.coe_nat_dvd.2 $
c.dvd_of_dvd_mul_right _),
have := congr_arg int.nat_abs e,
simp [int.nat_abs_mul, int.nat_abs_of_nat] at this, simp [this]
end
theorem denom_dvd (a b : ℤ) : ((a /. b).denom : ℤ) ∣ b :=
begin
by_cases b0 : b = 0, {simp [b0]},
cases e : a /. b with n d h c,
rw [num_denom', mk_eq b0 (ne_of_gt (int.coe_nat_pos.2 h))] at e,
refine (int.dvd_nat_abs.1 $ int.coe_nat_dvd.2 $ c.symm.dvd_of_dvd_mul_left _),
rw [← int.nat_abs_mul, ← int.coe_nat_dvd, int.dvd_nat_abs, ← e], simp
end
protected def add : ℚ → ℚ → ℚ
| ⟨n₁, d₁, h₁, c₁⟩ ⟨n₂, d₂, h₂, c₂⟩ := mk_pnat (n₁ * d₂ + n₂ * d₁) ⟨d₁ * d₂, mul_pos h₁ h₂⟩
instance : has_add ℚ := ⟨rat.add⟩
theorem lift_binop_eq (f : ℚ → ℚ → ℚ) (f₁ : ℤ → ℤ → ℤ → ℤ → ℤ) (f₂ : ℤ → ℤ → ℤ → ℤ → ℤ)
(fv : ∀ {n₁ d₁ h₁ c₁ n₂ d₂ h₂ c₂},
f ⟨n₁, d₁, h₁, c₁⟩ ⟨n₂, d₂, h₂, c₂⟩ = f₁ n₁ d₁ n₂ d₂ /. f₂ n₁ d₁ n₂ d₂)
(f0 : ∀ {n₁ d₁ n₂ d₂} (d₁0 : d₁ ≠ 0) (d₂0 : d₂ ≠ 0), f₂ n₁ d₁ n₂ d₂ ≠ 0)
(a b c d : ℤ) (b0 : b ≠ 0) (d0 : d ≠ 0)
(H : ∀ {n₁ d₁ n₂ d₂} (h₁ : a * d₁ = n₁ * b) (h₂ : c * d₂ = n₂ * d),
f₁ n₁ d₁ n₂ d₂ * f₂ a b c d = f₁ a b c d * f₂ n₁ d₁ n₂ d₂) :
f (a /. b) (c /. d) = f₁ a b c d /. f₂ a b c d :=
begin
generalize ha : a /. b = x, cases x with n₁ d₁ h₁ c₁, rw num_denom' at ha,
generalize hc : c /. d = x, cases x with n₂ d₂ h₂ c₂, rw num_denom' at hc,
rw fv,
have d₁0 := ne_of_gt (int.coe_nat_lt.2 h₁),
have d₂0 := ne_of_gt (int.coe_nat_lt.2 h₂),
exact (mk_eq (f0 d₁0 d₂0) (f0 b0 d0)).2 (H ((mk_eq b0 d₁0).1 ha) ((mk_eq d0 d₂0).1 hc))
end
@[simp] theorem add_def {a b c d : ℤ} (b0 : b ≠ 0) (d0 : d ≠ 0) :
a /. b + c /. d = (a * d + c * b) /. (b * d) :=
begin
apply lift_binop_eq rat.add; intros; try {assumption},
{ apply mk_pnat_eq },
{ apply mul_ne_zero d₁0 d₂0 },
calc (n₁ * d₂ + n₂ * d₁) * (b * d) =
(n₁ * b) * d₂ * d + (n₂ * d) * (d₁ * b) : by simp [mul_add, mul_comm, mul_left_comm]
... = (a * d₁) * d₂ * d + (c * d₂) * (d₁ * b) : by rw [h₁, h₂]
... = (a * d + c * b) * (d₁ * d₂) : by simp [mul_add, mul_comm, mul_left_comm]
end
protected def neg : ℚ → ℚ
| ⟨n, d, h, c⟩ := ⟨-n, d, h, by simp [c]⟩
instance : has_neg ℚ := ⟨rat.neg⟩
@[simp] theorem neg_def {a b : ℤ} : -(a /. b) = -a /. b :=
begin
by_cases b0 : b = 0, { subst b0, simp, refl },
generalize ha : a /. b = x, cases x with n₁ d₁ h₁ c₁, rw num_denom' at ha,
show rat.mk' _ _ _ _ = _, rw num_denom',
have d0 := ne_of_gt (int.coe_nat_lt.2 h₁),
apply (mk_eq d0 b0).2, have h₁ := (mk_eq b0 d0).1 ha,
simp only [neg_mul_eq_neg_mul_symm, congr_arg has_neg.neg h₁]
end
protected def mul : ℚ → ℚ → ℚ
| ⟨n₁, d₁, h₁, c₁⟩ ⟨n₂, d₂, h₂, c₂⟩ := mk_pnat (n₁ * n₂) ⟨d₁ * d₂, mul_pos h₁ h₂⟩
instance : has_mul ℚ := ⟨rat.mul⟩
@[simp] theorem mul_def {a b c d : ℤ} (b0 : b ≠ 0) (d0 : d ≠ 0) :
(a /. b) * (c /. d) = (a * c) /. (b * d) :=
begin
apply lift_binop_eq rat.mul; intros; try {assumption},
{ apply mk_pnat_eq },
{ apply mul_ne_zero d₁0 d₂0 },
cc
end
protected def inv : ℚ → ℚ
| ⟨(n+1:ℕ), d, h, c⟩ := ⟨d, n+1, n.succ_pos, c.symm⟩
| ⟨0, d, h, c⟩ := 0
| ⟨-[1+ n], d, h, c⟩ := ⟨-d, n+1, n.succ_pos, nat.coprime.symm $ by simp; exact c⟩
instance : has_inv ℚ := ⟨rat.inv⟩
@[simp] theorem inv_def {a b : ℤ} : (a /. b)⁻¹ = b /. a :=
begin
by_cases a0 : a = 0, { subst a0, simp, refl },
by_cases b0 : b = 0, { subst b0, simp, refl },
generalize ha : a /. b = x, cases x with n d h c, rw num_denom' at ha,
refine eq.trans (_ : rat.inv ⟨n, d, h, c⟩ = d /. n) _,
{ cases n with n; [cases n with n, skip],
{ refl },
{ change int.of_nat n.succ with (n+1:ℕ),
unfold rat.inv, rw num_denom' },
{ unfold rat.inv, rw num_denom', refl } },
have n0 : n ≠ 0,
{ refine mt (λ (n0 : n = 0), _) a0,
subst n0, simp at ha,
exact (mk_eq_zero b0).1 ha },
have d0 := ne_of_gt (int.coe_nat_lt.2 h),
have ha := (mk_eq b0 d0).1 ha,
apply (mk_eq n0 a0).2,
cc
end
variables (a b c : ℚ)
protected theorem add_zero : a + 0 = a :=
num_denom_cases_on' a $ λ n d h,
by rw [← zero_mk d]; simp [h, -zero_mk]
protected theorem zero_add : 0 + a = a :=
num_denom_cases_on' a $ λ n d h,
by rw [← zero_mk d]; simp [h, -zero_mk]
protected theorem add_comm : a + b = b + a :=
num_denom_cases_on' a $ λ n₁ d₁ h₁,
num_denom_cases_on' b $ λ n₂ d₂ h₂,
by simp [h₁, h₂, mul_comm]
protected theorem add_assoc : a + b + c = a + (b + c) :=
num_denom_cases_on' a $ λ n₁ d₁ h₁,
num_denom_cases_on' b $ λ n₂ d₂ h₂,
num_denom_cases_on' c $ λ n₃ d₃ h₃,
by simp [h₁, h₂, h₃, mul_ne_zero, mul_add, mul_comm, mul_left_comm, add_left_comm]
protected theorem add_left_neg : -a + a = 0 :=
num_denom_cases_on' a $ λ n d h,
by simp [h]
protected theorem mul_one : a * 1 = a :=
num_denom_cases_on' a $ λ n d h,
by change (1:ℚ) with 1 /. 1; simp [h]
protected theorem one_mul : 1 * a = a :=
num_denom_cases_on' a $ λ n d h,
by change (1:ℚ) with 1 /. 1; simp [h]
protected theorem mul_comm : a * b = b * a :=
num_denom_cases_on' a $ λ n₁ d₁ h₁,
num_denom_cases_on' b $ λ n₂ d₂ h₂,
by simp [h₁, h₂, mul_comm]
protected theorem mul_assoc : a * b * c = a * (b * c) :=
num_denom_cases_on' a $ λ n₁ d₁ h₁,
num_denom_cases_on' b $ λ n₂ d₂ h₂,
num_denom_cases_on' c $ λ n₃ d₃ h₃,
by simp [h₁, h₂, h₃, mul_ne_zero, mul_comm, mul_left_comm]
protected theorem add_mul : (a + b) * c = a * c + b * c :=
num_denom_cases_on' a $ λ n₁ d₁ h₁,
num_denom_cases_on' b $ λ n₂ d₂ h₂,
num_denom_cases_on' c $ λ n₃ d₃ h₃,
by simp [h₁, h₂, h₃, mul_ne_zero];
refine (div_mk_div_cancel_left (int.coe_nat_ne_zero.2 h₃)).symm.trans _;
simp [mul_add, mul_comm, mul_assoc, mul_left_comm]
protected theorem mul_add : a * (b + c) = a * b + a * c :=
by rw [rat.mul_comm, rat.add_mul, rat.mul_comm, rat.mul_comm c a]
protected theorem zero_ne_one : 0 ≠ (1:ℚ) :=
mt (λ (h : 0 = 1 /. 1), (mk_eq_zero one_ne_zero).1 h.symm) one_ne_zero
protected theorem mul_inv_cancel : a ≠ 0 → a * a⁻¹ = 1 :=
num_denom_cases_on' a $ λ n d h a0,
have n0 : n ≠ 0, from mt (by intro e; subst e; simp) a0,
by simp [h, n0, mul_comm]; exact
eq.trans (by simp) (@div_mk_div_cancel_left 1 1 _ n0)
protected theorem inv_mul_cancel (h : a ≠ 0) : a⁻¹ * a = 1 :=
eq.trans (rat.mul_comm _ _) (rat.mul_inv_cancel _ h)
instance : decidable_eq ℚ := by tactic.mk_dec_eq_instance
instance : discrete_field ℚ :=
{ zero := 0,
add := rat.add,
neg := rat.neg,
one := 1,
mul := rat.mul,
inv := rat.inv,
zero_add := rat.zero_add,
add_zero := rat.add_zero,
add_comm := rat.add_comm,
add_assoc := rat.add_assoc,
add_left_neg := rat.add_left_neg,
mul_one := rat.mul_one,
one_mul := rat.one_mul,
mul_comm := rat.mul_comm,
mul_assoc := rat.mul_assoc,
left_distrib := rat.mul_add,
right_distrib := rat.add_mul,
zero_ne_one := rat.zero_ne_one,
mul_inv_cancel := rat.mul_inv_cancel,
inv_mul_cancel := rat.inv_mul_cancel,
has_decidable_eq := rat.decidable_eq,
inv_zero := rfl }
/- Extra instances to short-circuit type class resolution -/
instance : field ℚ := by apply_instance
instance : division_ring ℚ := by apply_instance
instance : integral_domain ℚ := by apply_instance
-- TODO(Mario): this instance slows down data.real.basic
--instance : domain ℚ := by apply_instance
instance : nonzero_comm_ring ℚ := by apply_instance
instance : comm_ring ℚ := by apply_instance
--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
theorem sub_def {a b c d : ℤ} (b0 : b ≠ 0) (d0 : d ≠ 0) :
a /. b - c /. d = (a * d - c * b) /. (b * d) :=
by simp [b0, d0]
protected def nonneg : ℚ → Prop
| ⟨n, d, h, c⟩ := n ≥ 0
@[simp] theorem mk_nonneg (a : ℤ) {b : ℤ} (h : b > 0) : (a /. b).nonneg ↔ a ≥ 0 :=
begin
generalize ha : a /. b = x, cases x with n₁ d₁ h₁ c₁, rw num_denom' at ha,
simp [rat.nonneg],
have d0 := int.coe_nat_lt.2 h₁,
have := (mk_eq (ne_of_gt h) (ne_of_gt d0)).1 ha,
constructor; intro h₂,
{ apply nonneg_of_mul_nonneg_right _ d0,
rw this, exact mul_nonneg h₂ (le_of_lt h) },
{ apply nonneg_of_mul_nonneg_right _ h,
rw ← this, exact mul_nonneg h₂ (int.coe_zero_le _) },
end
protected def nonneg_add {a b} : rat.nonneg a → rat.nonneg b → rat.nonneg (a + b) :=
num_denom_cases_on' a $ λ n₁ d₁ h₁,
num_denom_cases_on' b $ λ n₂ d₂ h₂,
begin
have d₁0 : (d₁:ℤ) > 0 := int.coe_nat_pos.2 (nat.pos_of_ne_zero h₁),
have d₂0 : (d₂:ℤ) > 0 := int.coe_nat_pos.2 (nat.pos_of_ne_zero h₂),
simp [d₁0, d₂0, h₁, h₂, mul_pos d₁0 d₂0],
intros n₁0 n₂0,
apply add_nonneg; apply mul_nonneg; {assumption <|> apply int.coe_zero_le}
end
protected def nonneg_mul {a b} : rat.nonneg a → rat.nonneg b → rat.nonneg (a * b) :=
num_denom_cases_on' a $ λ n₁ d₁ h₁,
num_denom_cases_on' b $ λ n₂ d₂ h₂,
begin
have d₁0 : (d₁:ℤ) > 0 := int.coe_nat_pos.2 (nat.pos_of_ne_zero h₁),
have d₂0 : (d₂:ℤ) > 0 := int.coe_nat_pos.2 (nat.pos_of_ne_zero h₂),
simp [d₁0, d₂0, h₁, h₂, mul_pos d₁0 d₂0],
exact mul_nonneg
end
protected def nonneg_antisymm {a} : rat.nonneg a → rat.nonneg (-a) → a = 0 :=
num_denom_cases_on' a $ λ n d h,
begin
have d0 : (d:ℤ) > 0 := int.coe_nat_pos.2 (nat.pos_of_ne_zero h),
simp [d0, h],
exact λ h₁ h₂, le_antisymm (nonpos_of_neg_nonneg h₂) h₁
end
protected def nonneg_total : rat.nonneg a ∨ rat.nonneg (-a) :=
by cases a with n; exact
or.imp_right neg_nonneg_of_nonpos (le_total 0 n)
instance decidable_nonneg : decidable (rat.nonneg a) :=
by cases a; unfold rat.nonneg; apply_instance
protected def le (a b : ℚ) := rat.nonneg (b - a)
instance : has_le ℚ := ⟨rat.le⟩
instance decidable_le : decidable_rel ((≤) : ℚ → ℚ → Prop)
| a b := show decidable (rat.nonneg (b - a)), by apply_instance
protected theorem le_def {a b c d : ℤ} (b0 : b > 0) (d0 : d > 0) :
a /. b ≤ c /. d ↔ a * d ≤ c * b :=
show rat.nonneg _ ↔ _,
by simpa [ne_of_gt b0, ne_of_gt d0, mul_pos b0 d0, mul_comm]
using @sub_nonneg _ _ (b * c) (a * d)
protected theorem le_refl : a ≤ a :=
show rat.nonneg (a - a), by rw sub_self; exact le_refl (0 : ℤ)
protected theorem le_total : a ≤ b ∨ b ≤ a :=
by have := rat.nonneg_total (b - a); rwa neg_sub at this
protected theorem le_antisymm {a b : ℚ} (hab : a ≤ b) (hba : b ≤ a) : a = b :=
by have := eq_neg_of_add_eq_zero (rat.nonneg_antisymm hba $ by simpa);
rwa neg_neg at this
protected theorem le_trans {a b c : ℚ} (hab : a ≤ b) (hbc : b ≤ c) : a ≤ c :=
have rat.nonneg (b - a + (c - b)), from rat.nonneg_add hab hbc,
have rat.nonneg (c - a + (b - b)), by simpa [-add_right_neg, add_left_comm],
by simpa
instance : decidable_linear_order ℚ :=
{ le := rat.le,
le_refl := rat.le_refl,
le_trans := @rat.le_trans,
le_antisymm := @rat.le_antisymm,
le_total := rat.le_total,
decidable_eq := by apply_instance,
decidable_le := assume a b, rat.decidable_nonneg (b - a) }
/- Extra instances to short-circuit type class resolution -/
instance : has_lt ℚ := by apply_instance
instance : lattice.distrib_lattice ℚ := by apply_instance
instance : lattice.lattice ℚ := by apply_instance
instance : lattice.semilattice_inf ℚ := by apply_instance
instance : lattice.semilattice_sup ℚ := by apply_instance
instance : lattice.has_inf ℚ := by apply_instance
instance : lattice.has_sup ℚ := by apply_instance
instance : linear_order ℚ := by apply_instance
instance : partial_order ℚ := by apply_instance
instance : preorder ℚ := by apply_instance
theorem nonneg_iff_zero_le {a} : rat.nonneg a ↔ 0 ≤ a :=
show rat.nonneg a ↔ rat.nonneg (a - 0), by simp
theorem num_nonneg_iff_zero_le : ∀ {a : ℚ}, 0 ≤ a.num ↔ 0 ≤ a
| ⟨n, d, h, c⟩ := @nonneg_iff_zero_le ⟨n, d, h, c⟩
theorem mk_le {a b c d : ℤ} (h₁ : b > 0) (h₂ : d > 0) :
a /. b ≤ c /. d ↔ a * d ≤ c * b :=
by conv in (_ ≤ _) {
simp only [(≤), rat.le],
rw [sub_def (ne_of_gt h₂) (ne_of_gt h₁),
mk_nonneg _ (mul_pos h₂ h₁), ge, sub_nonneg] }
protected theorem add_le_add_left {a b c : ℚ} : c + a ≤ c + b ↔ a ≤ b :=
by unfold has_le.le rat.le; rw add_sub_add_left_eq_sub
protected theorem mul_nonneg {a b : ℚ} (ha : 0 ≤ a) (hb : 0 ≤ b) : 0 ≤ a * b :=
by rw ← nonneg_iff_zero_le at ha hb ⊢; exact rat.nonneg_mul ha hb
instance : discrete_linear_ordered_field ℚ :=
{ zero_lt_one := dec_trivial,
add_le_add_left := assume a b ab c, rat.add_le_add_left.2 ab,
add_lt_add_left := assume a b ab c, lt_of_not_ge $ λ ba,
not_le_of_lt ab $ rat.add_le_add_left.1 ba,
mul_nonneg := @rat.mul_nonneg,
mul_pos := assume a b ha hb, lt_of_le_of_ne
(rat.mul_nonneg (le_of_lt ha) (le_of_lt hb))
(mul_ne_zero (ne_of_lt ha).symm (ne_of_lt hb).symm).symm,
..rat.discrete_field, ..rat.decidable_linear_order }
/- Extra instances to short-circuit type class resolution -/
instance : linear_ordered_field ℚ := by apply_instance
instance : decidable_linear_ordered_comm_ring ℚ := by apply_instance
instance : linear_ordered_comm_ring ℚ := by apply_instance
instance : linear_ordered_ring ℚ := by apply_instance
instance : ordered_ring ℚ := by apply_instance
instance : decidable_linear_ordered_semiring ℚ := by apply_instance
instance : linear_ordered_semiring ℚ := by apply_instance
instance : ordered_semiring ℚ := by apply_instance
instance : decidable_linear_ordered_comm_group ℚ := by apply_instance
instance : ordered_comm_group ℚ := by apply_instance
instance : ordered_cancel_comm_monoid ℚ := by apply_instance
instance : ordered_comm_monoid ℚ := by apply_instance
theorem num_pos_iff_pos {a : ℚ} : 0 < a.num ↔ 0 < a :=
lt_iff_lt_of_le_iff_le $
by simpa [(by cases a; refl : (-a).num = -a.num)]
using @num_nonneg_iff_zero_le (-a)
theorem of_int_eq_mk (z : ℤ) : of_int z = z /. 1 := num_denom' _ _ _ _
theorem coe_int_eq_mk : ∀ z : ℤ, ↑z = z /. 1
| (n : ℕ) := show (n:ℚ) = n /. 1,
by induction n with n IH n; simp [*, show (1:ℚ) = 1 /. 1, from rfl]
| -[1+ n] := show (-(n + 1) : ℚ) = -[1+ n] /. 1, begin
induction n with n IH, {refl},
show -(n + 1 + 1 : ℚ) = -[1+ n.succ] /. 1,
rw [neg_add, IH],
simpa [show -1 = (-1) /. 1, from rfl]
end
theorem coe_int_eq_of_int (z : ℤ) : ↑z = of_int z :=
(coe_int_eq_mk z).trans (of_int_eq_mk z).symm
theorem mk_eq_div (n d : ℤ) : n /. d = (n / d : ℚ) :=
begin
by_cases d0 : d = 0, {simp [d0, div_zero]},
rw [division_def, coe_int_eq_mk, coe_int_eq_mk, inv_def,
mul_def one_ne_zero d0, one_mul, mul_one]
end
/-- `floor q` is the largest integer `z` such that `z ≤ q` -/
def floor : ℚ → ℤ
| ⟨n, d, h, c⟩ := n / d
theorem le_floor {z : ℤ} : ∀ {r : ℚ}, z ≤ floor r ↔ (z : ℚ) ≤ r
| ⟨n, d, h, c⟩ := begin
simp [floor],
rw [num_denom'],
have h' := int.coe_nat_lt.2 h,
conv { to_rhs,
rw [coe_int_eq_mk, mk_le zero_lt_one h', mul_one] },
exact int.le_div_iff_mul_le h'
end
theorem floor_lt {r : ℚ} {z : ℤ} : floor r < z ↔ r < z :=
lt_iff_lt_of_le_iff_le le_floor
theorem floor_le (r : ℚ) : (floor r : ℚ) ≤ r :=
le_floor.1 (le_refl _)
theorem lt_succ_floor (r : ℚ) : r < (floor r).succ :=
floor_lt.1 $ int.lt_succ_self _
@[simp] theorem floor_coe (z : ℤ) : floor z = z :=
eq_of_forall_le_iff $ λ a, by rw [le_floor, int.cast_le]
theorem floor_mono {a b : ℚ} (h : a ≤ b) : floor a ≤ floor b :=
le_floor.2 (le_trans (floor_le _) h)
@[simp] theorem floor_add_int (r : ℚ) (z : ℤ) : floor (r + z) = floor r + z :=
eq_of_forall_le_iff $ λ a, by rw [le_floor,
← sub_le_iff_le_add, ← sub_le_iff_le_add, le_floor, int.cast_sub]
theorem floor_sub_int (r : ℚ) (z : ℤ) : floor (r - z) = floor r - z :=
eq.trans (by rw [int.cast_neg]; refl) (floor_add_int _ _)
/-- `ceil q` is the smallest integer `z` such that `q ≤ z` -/
def ceil (r : ℚ) : ℤ :=
-(floor (-r))
theorem ceil_le {z : ℤ} {r : ℚ} : ceil r ≤ z ↔ r ≤ z :=
by rw [ceil, neg_le, le_floor, int.cast_neg, neg_le_neg_iff]
theorem le_ceil (r : ℚ) : r ≤ ceil r :=
ceil_le.1 (le_refl _)
@[simp] theorem ceil_coe (z : ℤ) : ceil z = z :=
by rw [ceil, ← int.cast_neg, floor_coe, neg_neg]
theorem ceil_mono {a b : ℚ} (h : a ≤ b) : ceil a ≤ ceil b :=
ceil_le.2 (le_trans h (le_ceil _))
@[simp] theorem ceil_add_int (r : ℚ) (z : ℤ) : ceil (r + z) = ceil r + z :=
by rw [ceil, neg_add', floor_sub_int, neg_sub, sub_eq_neg_add]; refl
theorem ceil_sub_int (r : ℚ) (z : ℤ) : ceil (r - z) = ceil r - z :=
eq.trans (by rw [int.cast_neg]; refl) (ceil_add_int _ _)
/- cast (injection into fields) -/
section cast
variables {α : Type*}
section
variables [division_ring α]
/-- Construct the canonical injection from `ℚ` into an arbitrary
division ring. If the field has positive characteristic `p`,
we define `1 / p = 1 / 0 = 0` for consistency with our
division by zero convention. -/
protected def cast : ℚ → α
| ⟨n, d, h, c⟩ := n / d
@[priority 0] instance cast_coe : has_coe ℚ α := ⟨rat.cast⟩
@[simp] theorem cast_of_int (n : ℤ) : (of_int n : α) = n :=
show (n / (1:ℕ) : α) = n, by rw [nat.cast_one, div_one]
@[simp] theorem cast_coe_int (n : ℤ) : ((n : ℚ) : α) = n :=
by rw [coe_int_eq_of_int, cast_of_int]
@[simp] theorem coe_int_num (n : ℤ) : (n : ℚ).num = n :=
by rw coe_int_eq_of_int; refl
@[simp] theorem coe_int_denom (n : ℤ) : (n : ℚ).denom = 1 :=
by rw coe_int_eq_of_int; refl
@[simp] theorem coe_nat_num (n : ℕ) : (n : ℚ).num = n :=
by rw [← int.cast_coe_nat, coe_int_num]
@[simp] theorem coe_nat_denom (n : ℕ) : (n : ℚ).denom = 1 :=
by rw [← int.cast_coe_nat, coe_int_denom]
@[simp] theorem cast_coe_nat (n : ℕ) : ((n : ℚ) : α) = n := cast_coe_int n
@[simp] theorem cast_zero : ((0 : ℚ) : α) = 0 :=
(cast_of_int _).trans int.cast_zero
@[simp] theorem cast_one : ((1 : ℚ) : α) = 1 :=
(cast_of_int _).trans int.cast_one
theorem mul_cast_comm (a : α) :
∀ (n : ℚ), (n.denom : α) ≠ 0 → a * n = n * a
| ⟨n, d, h, c⟩ h₂ := show a * (n * d⁻¹) = n * d⁻¹ * a,
by rw [← mul_assoc, int.mul_cast_comm, mul_assoc, mul_assoc,
← show (d:α)⁻¹ * a = a * d⁻¹, from
division_ring.inv_comm_of_comm h₂ (int.mul_cast_comm a d).symm]
theorem cast_mk_of_ne_zero (a b : ℤ)
(b0 : (b:α) ≠ 0) : (a /. b : α) = a / b :=
begin
have b0' : b ≠ 0, { refine mt _ b0, simp {contextual := tt} },
cases e : a /. b with n d h c,
have d0 : (d:α) ≠ 0,
{ intro d0,
have dd := denom_dvd a b,
cases (show (d:ℤ) ∣ b, by rwa e at dd) with k ke,
have : (b:α) = (d:α) * (k:α), {rw [ke, int.cast_mul], refl},
rw [d0, zero_mul] at this, contradiction },
rw [num_denom'] at e,
have := congr_arg (coe : ℤ → α) ((mk_eq b0' $ ne_of_gt $ int.coe_nat_pos.2 h).1 e),
rw [int.cast_mul, int.cast_mul, int.cast_coe_nat] at this,
symmetry, change (a * b⁻¹ : α) = n / d,
rw [eq_div_iff_mul_eq _ _ d0, mul_assoc, nat.mul_cast_comm,
← mul_assoc, this, mul_assoc, mul_inv_cancel b0, mul_one]
end
theorem cast_add_of_ne_zero : ∀ {m n : ℚ},
(m.denom : α) ≠ 0 → (n.denom : α) ≠ 0 → ((m + n : ℚ) : α) = m + n
| ⟨n₁, d₁, h₁, c₁⟩ ⟨n₂, d₂, h₂, c₂⟩ := λ (d₁0 : (d₁:α) ≠ 0) (d₂0 : (d₂:α) ≠ 0), begin
have d₁0' : (d₁:ℤ) ≠ 0 := int.coe_nat_ne_zero.2 (λ e, by rw e at d₁0; exact d₁0 rfl),
have d₂0' : (d₂:ℤ) ≠ 0 := int.coe_nat_ne_zero.2 (λ e, by rw e at d₂0; exact d₂0 rfl),
rw [num_denom', num_denom', add_def d₁0' d₂0'],
suffices : (n₁ * (d₂ * (d₂⁻¹ * d₁⁻¹)) +
n₂ * (d₁ * d₂⁻¹) * d₁⁻¹ : α) = n₁ * d₁⁻¹ + n₂ * d₂⁻¹,
{ rw [cast_mk_of_ne_zero, cast_mk_of_ne_zero, cast_mk_of_ne_zero],
{ simpa [division_def, left_distrib, right_distrib, mul_inv_eq,
d₁0, d₂0, division_ring.mul_ne_zero d₁0 d₂0, mul_assoc] },
all_goals {simp [d₁0, d₂0, division_ring.mul_ne_zero d₁0 d₂0]} },
rw [← mul_assoc (d₂:α), mul_inv_cancel d₂0, one_mul,
← nat.mul_cast_comm], simp [d₁0, mul_assoc]
end
@[simp] theorem cast_neg : ∀ n, ((-n : ℚ) : α) = -n
| ⟨n, d, h, c⟩ := show (↑-n * d⁻¹ : α) = -(n * d⁻¹),
by rw [int.cast_neg, neg_mul_eq_neg_mul]
theorem cast_sub_of_ne_zero {m n : ℚ}
(m0 : (m.denom : α) ≠ 0) (n0 : (n.denom : α) ≠ 0) : ((m - n : ℚ) : α) = m - n :=
have ((-n).denom : α) ≠ 0, by cases n; exact n0,
by simp [m0, this, cast_add_of_ne_zero]
theorem cast_mul_of_ne_zero : ∀ {m n : ℚ},
(m.denom : α) ≠ 0 → (n.denom : α) ≠ 0 → ((m * n : ℚ) : α) = m * n
| ⟨n₁, d₁, h₁, c₁⟩ ⟨n₂, d₂, h₂, c₂⟩ := λ (d₁0 : (d₁:α) ≠ 0) (d₂0 : (d₂:α) ≠ 0), begin
have d₁0' : (d₁:ℤ) ≠ 0 := int.coe_nat_ne_zero.2 (λ e, by rw e at d₁0; exact d₁0 rfl),
have d₂0' : (d₂:ℤ) ≠ 0 := int.coe_nat_ne_zero.2 (λ e, by rw e at d₂0; exact d₂0 rfl),
rw [num_denom', num_denom', mul_def d₁0' d₂0'],
suffices : (n₁ * ((n₂ * d₂⁻¹) * d₁⁻¹) : α) = n₁ * (d₁⁻¹ * (n₂ * d₂⁻¹)),
{ rw [cast_mk_of_ne_zero, cast_mk_of_ne_zero, cast_mk_of_ne_zero],
{ simpa [division_def, mul_inv_eq, d₁0, d₂0, division_ring.mul_ne_zero d₁0 d₂0, mul_assoc] },
all_goals {simp [d₁0, d₂0, division_ring.mul_ne_zero d₁0 d₂0]} },
rw [division_ring.inv_comm_of_comm d₁0 (nat.mul_cast_comm _ _).symm]
end
theorem cast_inv_of_ne_zero : ∀ {n : ℚ},
(n.num : α) ≠ 0 → (n.denom : α) ≠ 0 → ((n⁻¹ : ℚ) : α) = n⁻¹
| ⟨n, d, h, c⟩ := λ (n0 : (n:α) ≠ 0) (d0 : (d:α) ≠ 0), begin
have n0' : (n:ℤ) ≠ 0 := λ e, by rw e at n0; exact n0 rfl,
have d0' : (d:ℤ) ≠ 0 := int.coe_nat_ne_zero.2 (λ e, by rw e at d0; exact d0 rfl),
rw [num_denom', inv_def],
rw [cast_mk_of_ne_zero, cast_mk_of_ne_zero, inv_div];
simp [n0, d0]
end
theorem cast_div_of_ne_zero {m n : ℚ} (md : (m.denom : α) ≠ 0)
(nn : (n.num : α) ≠ 0) (nd : (n.denom : α) ≠ 0) : ((m / n : ℚ) : α) = m / n :=
have (n⁻¹.denom : ℤ) ∣ n.num,
by conv in n⁻¹.denom { rw [num_denom n, inv_def] };
apply denom_dvd,
have (n⁻¹.denom : α) = 0 → (n.num : α) = 0, from
λ h, let ⟨k, e⟩ := this in
by have := congr_arg (coe : ℤ → α) e;
rwa [int.cast_mul, int.cast_coe_nat, h, zero_mul] at this,
by rw [division_def, cast_mul_of_ne_zero md (mt this nn), cast_inv_of_ne_zero nn nd, division_def]
@[simp] theorem cast_inj [char_zero α] : ∀ {m n : ℚ}, (m : α) = n ↔ m = n
| ⟨n₁, d₁, h₁, c₁⟩ ⟨n₂, d₂, h₂, c₂⟩ := begin
refine ⟨λ h, _, congr_arg _⟩,
have d₁0 : d₁ ≠ 0 := ne_of_gt h₁,
have d₂0 : d₂ ≠ 0 := ne_of_gt h₂,
have d₁a : (d₁:α) ≠ 0 := nat.cast_ne_zero.2 d₁0,
have d₂a : (d₂:α) ≠ 0 := nat.cast_ne_zero.2 d₂0,
rw [num_denom', num_denom'] at h ⊢,
rw [cast_mk_of_ne_zero, cast_mk_of_ne_zero] at h; simp [d₁0, d₂0] at h ⊢,
rwa [eq_div_iff_mul_eq _ _ d₂a, division_def, mul_assoc,
division_ring.inv_comm_of_comm d₁a (nat.mul_cast_comm _ _),
← mul_assoc, ← division_def, eq_comm, eq_div_iff_mul_eq _ _ d₁a, eq_comm,
← int.cast_coe_nat, ← int.cast_mul, ← int.cast_coe_nat, ← int.cast_mul,
int.cast_inj, ← mk_eq (int.coe_nat_ne_zero.2 d₁0) (int.coe_nat_ne_zero.2 d₂0)] at h
end
theorem cast_injective [char_zero α] : function.injective (coe : ℚ → α)
| m n := cast_inj.1
@[simp] theorem cast_eq_zero [char_zero α] {n : ℚ} : (n : α) = 0 ↔ n = 0 :=
by rw [← cast_zero, cast_inj]
@[simp] theorem cast_ne_zero [char_zero α] {n : ℚ} : (n : α) ≠ 0 ↔ n ≠ 0 :=
not_congr cast_eq_zero
theorem eq_cast_of_ne_zero (f : ℚ → α) (H1 : f 1 = 1)
(Hadd : ∀ x y, f (x + y) = f x + f y)
(Hmul : ∀ x y, f (x * y) = f x * f y) :
∀ n : ℚ, (n.denom : α) ≠ 0 → f n = n
| ⟨n, d, h, c⟩ := λ (h₂ : ((d:ℤ):α) ≠ 0), show _ = (n / (d:ℤ) : α), begin
rw [num_denom', mk_eq_div, eq_div_iff_mul_eq _ _ h₂],
have : ∀ n : ℤ, f n = n, { apply int.eq_cast; simp [H1, Hadd] },
rw [← this, ← this, ← Hmul, div_mul_cancel],
exact int.cast_ne_zero.2 (int.coe_nat_ne_zero.2 $ ne_of_gt h),
end
theorem eq_cast [char_zero α] (f : ℚ → α) (H1 : f 1 = 1)
(Hadd : ∀ x y, f (x + y) = f x + f y)
(Hmul : ∀ x y, f (x * y) = f x * f y) (n : ℚ) : f n = n :=
eq_cast_of_ne_zero _ H1 Hadd Hmul _ $
nat.cast_ne_zero.2 $ ne_of_gt n.pos
end
theorem cast_mk [discrete_field α] [char_zero α] (a b : ℤ) : ((a /. b) : α) = a / b :=
if b0 : b = 0 then by simp [b0, div_zero]
else cast_mk_of_ne_zero a b (int.cast_ne_zero.2 b0)
@[simp] theorem cast_add [division_ring α] [char_zero α] (m n) : ((m + n : ℚ) : α) = m + n :=
cast_add_of_ne_zero (nat.cast_ne_zero.2 $ ne_of_gt m.pos) (nat.cast_ne_zero.2 $ ne_of_gt n.pos)
@[simp] theorem cast_sub [division_ring α] [char_zero α] (m n) : ((m - n : ℚ) : α) = m - n :=
cast_sub_of_ne_zero (nat.cast_ne_zero.2 $ ne_of_gt m.pos) (nat.cast_ne_zero.2 $ ne_of_gt n.pos)
@[simp] theorem cast_mul [division_ring α] [char_zero α] (m n) : ((m * n : ℚ) : α) = m * n :=
cast_mul_of_ne_zero (nat.cast_ne_zero.2 $ ne_of_gt m.pos) (nat.cast_ne_zero.2 $ ne_of_gt n.pos)
@[simp] theorem cast_inv [discrete_field α] [char_zero α] (n) : ((n⁻¹ : ℚ) : α) = n⁻¹ :=
if n0 : n.num = 0 then
by simp [show n = 0, by rw [num_denom n, n0]; simp, inv_zero] else
cast_inv_of_ne_zero (int.cast_ne_zero.2 n0) (nat.cast_ne_zero.2 $ ne_of_gt n.pos)
@[simp] theorem cast_div [discrete_field α] [char_zero α] (m n) : ((m / n : ℚ) : α) = m / n :=
by rw [division_def, cast_mul, cast_inv, division_def]
@[simp] theorem cast_bit0 [division_ring α] [char_zero α] (n : ℚ) : ((bit0 n : ℚ) : α) = bit0 n := cast_add _ _
@[simp] theorem cast_bit1 [division_ring α] [char_zero α] (n : ℚ) : ((bit1 n : ℚ) : α) = bit1 n :=
by rw [bit1, cast_add, cast_one, cast_bit0]; refl
@[simp] theorem cast_nonneg [linear_ordered_field α] : ∀ {n : ℚ}, 0 ≤ (n : α) ↔ 0 ≤ n
| ⟨n, d, h, c⟩ := show 0 ≤ (n * d⁻¹ : α) ↔ 0 ≤ (⟨n, d, h, c⟩ : ℚ),
by rw [num_denom', ← nonneg_iff_zero_le, mk_nonneg _ (int.coe_nat_pos.2 h),
mul_nonneg_iff_right_nonneg_of_pos (@inv_pos α _ _ (nat.cast_pos.2 h)),
int.cast_nonneg]
@[simp] theorem cast_le [linear_ordered_field α] {m n : ℚ} : (m : α) ≤ n ↔ m ≤ n :=
by rw [← sub_nonneg, ← cast_sub, cast_nonneg, sub_nonneg]
@[simp] theorem cast_lt [linear_ordered_field α] {m n : ℚ} : (m : α) < n ↔ m < n :=
by simpa [-cast_le] using not_congr (@cast_le α _ n m)
@[simp] theorem cast_nonpos [linear_ordered_field α] {n : ℚ} : (n : α) ≤ 0 ↔ n ≤ 0 :=
by rw [← cast_zero, cast_le]
@[simp] theorem cast_pos [linear_ordered_field α] {n : ℚ} : (0 : α) < n ↔ 0 < n :=
by rw [← cast_zero, cast_lt]
@[simp] theorem cast_lt_zero [linear_ordered_field α] {n : ℚ} : (n : α) < 0 ↔ n < 0 :=
by rw [← cast_zero, cast_lt]
@[simp] theorem cast_id : ∀ n : ℚ, ↑n = n
| ⟨n, d, h, c⟩ := show (n / (d : ℤ) : ℚ) = _, by rw [num_denom', mk_eq_div]
@[simp] theorem cast_min [discrete_linear_ordered_field α] {a b : ℚ} : (↑(min a b) : α) = min a b :=
by by_cases a ≤ b; simp [h, min]
@[simp] theorem cast_max [discrete_linear_ordered_field α] {a b : ℚ} : (↑(max a b) : α) = max a b :=
by by_cases a ≤ b; simp [h, max]
@[simp] theorem cast_abs [discrete_linear_ordered_field α] {q : ℚ} : ((abs q : ℚ) : α) = abs q :=
by simp [abs]
end cast
/- nat ceiling -/
/-- `nat_ceil q` is the smallest nonnegative integer `n` with `q ≤ n`.
It is the same as `ceil q` when `q ≥ 0`, otherwise it is `0`. -/
def nat_ceil (q : ℚ) : ℕ := int.to_nat (ceil q)
theorem nat_ceil_le {q : ℚ} {n : ℕ} : nat_ceil q ≤ n ↔ q ≤ n :=
by rw [nat_ceil, int.to_nat_le, ceil_le]; refl
theorem lt_nat_ceil {q : ℚ} {n : ℕ} : n < nat_ceil q ↔ (n : ℚ) < q :=
not_iff_not.1 $ by rw [not_lt, not_lt, nat_ceil_le]
theorem le_nat_ceil (q : ℚ) : q ≤ nat_ceil q :=
nat_ceil_le.1 (le_refl _)
theorem nat_ceil_mono {q₁ q₂ : ℚ} (h : q₁ ≤ q₂) : nat_ceil q₁ ≤ nat_ceil q₂ :=
nat_ceil_le.2 (le_trans h (le_nat_ceil _))
@[simp] theorem nat_ceil_coe (n : ℕ) : nat_ceil n = n :=
show (ceil (n:ℤ)).to_nat = n, by rw [ceil_coe]; refl
@[simp] theorem nat_ceil_zero : nat_ceil 0 = 0 := nat_ceil_coe 0
theorem nat_ceil_add_nat {q : ℚ} (hq : 0 ≤ q) (n : ℕ) : nat_ceil (q + n) = nat_ceil q + n :=
show int.to_nat (ceil (q + (n:ℤ))) = int.to_nat (ceil q) + n,
by rw [ceil_add_int]; exact
match ceil q, int.eq_coe_of_zero_le (ceil_mono hq) with
| _, ⟨m, rfl⟩ := rfl
end
theorem nat_ceil_lt_add_one {q : ℚ} (hq : q ≥ 0) : ↑(nat_ceil q) < q + 1 :=
lt_nat_ceil.1 $ by rw [
show nat_ceil (q+1) = nat_ceil q+1, from nat_ceil_add_nat hq 1]; apply nat.lt_succ_self
@[simp] lemma denom_neg_eq_denom : ∀ q : ℚ, (-q).denom = q.denom
| ⟨_, d, _, _⟩ := rfl
@[simp] lemma num_neg_eq_neg_num : ∀ q : ℚ, (-q).num = -(q.num)
| ⟨n, _, _, _⟩ := rfl
@[simp] lemma num_zero : rat.num 0 = 0 := rfl
lemma zero_of_num_zero {q : ℚ} (hq : q.num = 0) : q = 0 :=
have q = q.num /. q.denom, from num_denom _,
by simpa [hq]
lemma zero_iff_num_zero {q : ℚ} : q = 0 ↔ q.num = 0 :=
⟨λ _, by simp *, zero_of_num_zero⟩
lemma num_ne_zero_of_ne_zero {q : ℚ} (h : q ≠ 0) : q.num ≠ 0 :=
assume : q.num = 0,
h $ zero_of_num_zero this
lemma denom_ne_zero (q : ℚ) : q.denom ≠ 0 :=
ne_of_gt q.pos
lemma mk_num_ne_zero_of_ne_zero {q : ℚ} {n d : ℤ} (hq : q ≠ 0) (hqnd : q = n /. d) : n ≠ 0 :=
assume : n = 0,
hq $ by simpa [this] using hqnd
lemma mk_denom_ne_zero_of_ne_zero {q : ℚ} {n d : ℤ} (hq : q ≠ 0) (hqnd : q = n /. d) : d ≠ 0 :=
assume : d = 0,
hq $ by simpa [this] using hqnd
lemma mk_ne_zero_of_ne_zero {n d : ℤ} (h : n ≠ 0) (hd : d ≠ 0) : n /. d ≠ 0 :=
assume : n /. d = 0,
h $ (mk_eq_zero hd).1 this
lemma mul_num_denom (q r : ℚ) : q * r = (q.num * r.num) /. ↑(q.denom * r.denom) :=
have hq' : (↑q.denom : ℤ) ≠ 0, by have := denom_ne_zero q; simpa,
have hr' : (↑r.denom : ℤ) ≠ 0, by have := denom_ne_zero r; simpa,
suffices (q.num /. ↑q.denom) * (r.num /. ↑r.denom) = (q.num * r.num) /. ↑(q.denom * r.denom),
by rwa [←num_denom q, ←num_denom r] at this,
by simp [mul_def hq' hr']
lemma div_num_denom (q r : ℚ) : q / r = (q.num * r.denom) /. (q.denom * r.num) :=
if hr : r.num = 0 then
have hr' : r = 0, from zero_of_num_zero hr,
by simp *
else calc q / r = q * r⁻¹ : div_eq_mul_inv
... = (q.num /. q.denom) * (r.num /. r.denom)⁻¹ : by rw [←num_denom q, ←num_denom r]
... = (q.num /. q.denom) * (r.denom /. r.num) : by rw inv_def
... = (q.num * r.denom) /. (q.denom * r.num) : mul_def (by simpa using denom_ne_zero q) hr
lemma num_denom_mk {q : ℚ} {n d : ℤ} (hn : n ≠ 0) (hd : d ≠ 0) (qdf : q = n /. d) :
∃ c : ℤ, n = c * q.num ∧ d = c * q.denom :=
have hq : q ≠ 0, from
assume : q = 0,
hn $ (rat.mk_eq_zero hd).1 (by cc),
have q.num /. q.denom = n /. d, by rwa [←rat.num_denom q],
have q.num * d = n * ↑(q.denom), from (rat.mk_eq (by simp [rat.denom_ne_zero]) hd).1 this,
begin
existsi n / q.num,
have hqdn : q.num ∣ n, begin rw qdf, apply rat.num_dvd, assumption end,
split,
{ rw int.div_mul_cancel hqdn },
{ apply int.eq_mul_div_of_mul_eq_mul_of_dvd_left,
{apply rat.num_ne_zero_of_ne_zero hq},
{simp [rat.denom_ne_zero]},
repeat {assumption} }
end
end rat
|
892ad761bcdafc36eb95e868957a4d32c3ffd936 | b7f22e51856f4989b970961f794f1c435f9b8f78 | /tests/lean/run/pattern1.lean | 581b444c7dc5f2ad59939be7451b2d91f2cc30c2 | [
"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 | 344 | lean | constant f : nat → nat → nat
definition lemma1 [forward] {a b : nat} : f a b = a :=
sorry
print lemma1
definition lemma2 [forward] {a b : nat} : f a b = f b a :=
sorry
definition lemma3 {a b : nat} : (:f a b:) = f b a :=
sorry
print lemma2
print lemma3
definition lemma4 [forward] {a b c : nat} : f a b = f a c :=
sorry
print lemma4
|
de01d7ebce772d101797fe4ed659c6f5d2817ccd | a7eef317ddec01b9fc6cfbb876fe7ac00f205ac7 | /src/data/seq/computation.lean | 1acc09dc58001967cbf79a1ac0164280265dac9e | [
"Apache-2.0"
] | permissive | kmill/mathlib | ea5a007b67ae4e9e18dd50d31d8aa60f650425ee | 1a419a9fea7b959317eddd556e1bb9639f4dcc05 | refs/heads/master | 1,668,578,197,719 | 1,593,629,163,000 | 1,593,629,163,000 | 276,482,939 | 0 | 0 | null | 1,593,637,960,000 | 1,593,637,959,000 | null | UTF-8 | Lean | false | false | 37,542 | lean | /-
Copyright (c) 2017 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Mario Carneiro
Coinductive formalization of unbounded computations.
-/
import data.stream
import tactic.basic
universes u v w
/-
coinductive computation (α : Type u) : Type u
| return : α → computation α
| think : computation α → computation α
-/
/-- `computation α` is the type of unbounded computations returning `α`.
An element of `computation α` is an infinite sequence of `option α` such
that if `f n = some a` for some `n` then it is constantly `some a` after that. -/
def computation (α : Type u) : Type u :=
{ f : stream (option α) // ∀ {n a}, f n = some a → f (n+1) = some a }
namespace computation
variables {α : Type u} {β : Type v} {γ : Type w}
-- constructors
/-- `return a` is the computation that immediately terminates with result `a`. -/
def return (a : α) : computation α := ⟨stream.const (some a), λn a', id⟩
instance : has_coe_t α (computation α) := ⟨return⟩ -- note [use has_coe_t]
/-- `think c` is the computation that delays for one "tick" and then performs
computation `c`. -/
def think (c : computation α) : computation α :=
⟨none :: c.1, λn a h, by {cases n with n, contradiction, exact c.2 h}⟩
/-- `thinkN c n` is the computation that delays for `n` ticks and then performs
computation `c`. -/
def thinkN (c : computation α) : ℕ → computation α
| 0 := c
| (n+1) := think (thinkN n)
-- check for immediate result
/-- `head c` is the first step of computation, either `some a` if `c = return a`
or `none` if `c = think c'`. -/
def head (c : computation α) : option α := c.1.head
-- one step of computation
/-- `tail c` is the remainder of computation, either `c` if `c = return a`
or `c'` if `c = think c'`. -/
def tail (c : computation α) : computation α :=
⟨c.1.tail, λ n a, let t := c.2 in t⟩
/-- `empty α` is the computation that never returns, an infinite sequence of
`think`s. -/
def empty (α) : computation α := ⟨stream.const none, λn a', id⟩
instance : inhabited (computation α) := ⟨empty _⟩
/-- `run_for c n` evaluates `c` for `n` steps and returns the result, or `none`
if it did not terminate after `n` steps. -/
def run_for : computation α → ℕ → option α := subtype.val
/-- `destruct c` is the destructor for `computation α` as a coinductive type.
It returns `inl a` if `c = return a` and `inr c'` if `c = think c'`. -/
def destruct (c : computation α) : α ⊕ computation α :=
match c.1 0 with
| none := sum.inr (tail c)
| some a := sum.inl a
end
/-- `run c` is an unsound meta function that runs `c` to completion, possibly
resulting in an infinite loop in the VM. -/
meta def run : computation α → α | c :=
match destruct c with
| sum.inl a := a
| sum.inr ca := run ca
end
theorem destruct_eq_ret {s : computation α} {a : α} :
destruct s = sum.inl a → s = return a :=
begin
dsimp [destruct],
induction f0 : s.1 0; intro h,
{ contradiction },
{ apply subtype.eq, funext n,
induction n with n IH,
{ injection h with h', rwa h' at f0 },
{ exact s.2 IH } }
end
theorem destruct_eq_think {s : computation α} {s'} :
destruct s = sum.inr s' → s = think s' :=
begin
dsimp [destruct],
induction f0 : s.1 0 with a'; intro h,
{ injection h with h', rw ←h',
cases s with f al,
apply subtype.eq, dsimp [think, tail],
rw ←f0, exact (stream.eta f).symm },
{ contradiction }
end
@[simp] theorem destruct_ret (a : α) : destruct (return a) = sum.inl a := rfl
@[simp] theorem destruct_think : ∀ s : computation α, destruct (think s) = sum.inr s
| ⟨f, al⟩ := rfl
@[simp] theorem destruct_empty : destruct (empty α) = sum.inr (empty α) := rfl
@[simp] theorem head_ret (a : α) : head (return a) = some a := rfl
@[simp] theorem head_think (s : computation α) : head (think s) = none := rfl
@[simp] theorem head_empty : head (empty α) = none := rfl
@[simp] theorem tail_ret (a : α) : tail (return a) = return a := rfl
@[simp] theorem tail_think (s : computation α) : tail (think s) = s :=
by cases s with f al; apply subtype.eq; dsimp [tail, think]; rw [stream.tail_cons]
@[simp] theorem tail_empty : tail (empty α) = empty α := rfl
theorem think_empty : empty α = think (empty α) :=
destruct_eq_think destruct_empty
def cases_on {C : computation α → Sort v} (s : computation α)
(h1 : ∀ a, C (return a)) (h2 : ∀ s, C (think s)) : C s := begin
induction H : destruct s with v v,
{ rw destruct_eq_ret H, apply h1 },
{ cases v with a s', rw destruct_eq_think H, apply h2 }
end
def corec.F (f : β → α ⊕ β) : α ⊕ β → option α × (α ⊕ β)
| (sum.inl a) := (some a, sum.inl a)
| (sum.inr b) := (match f b with
| sum.inl a := some a
| sum.inr b' := none
end, f b)
/-- `corec f b` is the corecursor for `computation α` as a coinductive type.
If `f b = inl a` then `corec f b = return a`, and if `f b = inl b'` then
`corec f b = think (corec f b')`. -/
def corec (f : β → α ⊕ β) (b : β) : computation α :=
begin
refine ⟨stream.corec' (corec.F f) (sum.inr b), λn a' h, _⟩,
rw stream.corec'_eq,
change stream.corec' (corec.F f) (corec.F f (sum.inr b)).2 n = some a',
revert h, generalize : sum.inr b = o, revert o,
induction n with n IH; intro o,
{ change (corec.F f o).1 = some a' → (corec.F f (corec.F f o).2).1 = some a',
cases o with a b; intro h, { exact h },
dsimp [corec.F] at h, dsimp [corec.F],
cases f b with a b', { exact h },
{ contradiction } },
{ rw [stream.corec'_eq (corec.F f) (corec.F f o).2,
stream.corec'_eq (corec.F f) o],
exact IH (corec.F f o).2 }
end
/-- left map of `⊕` -/
def lmap (f : α → β) : α ⊕ γ → β ⊕ γ
| (sum.inl a) := sum.inl (f a)
| (sum.inr b) := sum.inr b
/-- right map of `⊕` -/
def rmap (f : β → γ) : α ⊕ β → α ⊕ γ
| (sum.inl a) := sum.inl a
| (sum.inr b) := sum.inr (f b)
attribute [simp] lmap rmap
@[simp] lemma corec_eq (f : β → α ⊕ β) (b : β) :
destruct (corec f b) = rmap (corec f) (f b) :=
begin
dsimp [corec, destruct],
change stream.corec' (corec.F f) (sum.inr b) 0 with corec.F._match_1 (f b),
induction h : f b with a b', { refl },
dsimp [corec.F, destruct],
apply congr_arg, apply subtype.eq,
dsimp [corec, tail],
rw [stream.corec'_eq, stream.tail_cons],
dsimp [corec.F], rw h
end
section bisim
variable (R : computation α → computation α → Prop)
local infix ~ := R
def bisim_o : α ⊕ computation α → α ⊕ computation α → Prop
| (sum.inl a) (sum.inl a') := a = a'
| (sum.inr s) (sum.inr s') := R s s'
| _ _ := false
attribute [simp] bisim_o
def is_bisimulation := ∀ ⦃s₁ s₂⦄, s₁ ~ s₂ → bisim_o R (destruct s₁) (destruct s₂)
-- If two computations are bisimilar, then they are equal
theorem eq_of_bisim (bisim : is_bisimulation R) {s₁ s₂} (r : s₁ ~ s₂) : s₁ = s₂ :=
begin
apply subtype.eq,
apply stream.eq_of_bisim (λx y, ∃ s s' : computation α, s.1 = x ∧ s'.1 = y ∧ R s s'),
dsimp [stream.is_bisimulation],
intros t₁ t₂ e,
exact match t₁, t₂, e with ._, ._, ⟨s, s', rfl, rfl, r⟩ :=
suffices head s = head s' ∧ R (tail s) (tail s'), from
and.imp id (λr, ⟨tail s, tail s',
by cases s; refl, by cases s'; refl, r⟩) this,
begin
have := bisim r, revert r this,
apply cases_on s _ _; intros; apply cases_on s' _ _; intros; intros r this,
{ constructor, dsimp at this, rw this, assumption },
{ rw [destruct_ret, destruct_think] at this,
exact false.elim this },
{ rw [destruct_ret, destruct_think] at this,
exact false.elim this },
{ simp at this, simp [*] }
end
end,
exact ⟨s₁, s₂, rfl, rfl, r⟩
end
end bisim
-- It's more of a stretch to use ∈ for this relation, but it
-- asserts that the computation limits to the given value.
protected def mem (a : α) (s : computation α) := some a ∈ s.1
instance : has_mem α (computation α) := ⟨computation.mem⟩
theorem le_stable (s : computation α) {a m n} (h : m ≤ n) :
s.1 m = some a → s.1 n = some a :=
by {cases s with f al, induction h with n h IH, exacts [id, λ h2, al (IH h2)]}
theorem mem_unique :
relator.left_unique ((∈) : α → computation α → Prop) :=
λa s b ⟨m, ha⟩ ⟨n, hb⟩, by injection
(le_stable s (le_max_left m n) ha.symm).symm.trans
(le_stable s (le_max_right m n) hb.symm)
/-- `terminates s` asserts that the computation `s` eventually terminates with some value. -/
@[class] def terminates (s : computation α) : Prop := ∃ a, a ∈ s
theorem terminates_of_mem {s : computation α} {a : α} : a ∈ s → terminates s :=
exists.intro a
theorem terminates_def (s : computation α) : terminates s ↔ ∃ n, (s.1 n).is_some :=
⟨λ⟨a, n, h⟩, ⟨n, by {dsimp [stream.nth] at h, rw ←h, exact rfl}⟩,
λ⟨n, h⟩, ⟨option.get h, n, (option.eq_some_of_is_some h).symm⟩⟩
theorem ret_mem (a : α) : a ∈ return a :=
exists.intro 0 rfl
theorem eq_of_ret_mem {a a' : α} (h : a' ∈ return a) : a' = a :=
mem_unique h (ret_mem _)
instance ret_terminates (a : α) : terminates (return a) :=
terminates_of_mem (ret_mem _)
theorem think_mem {s : computation α} {a} : a ∈ s → a ∈ think s
| ⟨n, h⟩ := ⟨n+1, h⟩
instance think_terminates (s : computation α) :
∀ [terminates s], terminates (think s)
| ⟨a, n, h⟩ := ⟨a, n+1, h⟩
theorem of_think_mem {s : computation α} {a} : a ∈ think s → a ∈ s
| ⟨n, h⟩ := by {cases n with n', contradiction, exact ⟨n', h⟩}
theorem of_think_terminates {s : computation α} :
terminates (think s) → terminates s
| ⟨a, h⟩ := ⟨a, of_think_mem h⟩
theorem not_mem_empty (a : α) : a ∉ empty α :=
λ ⟨n, h⟩, by clear _fun_match; contradiction
theorem not_terminates_empty : ¬ terminates (empty α) :=
λ ⟨a, h⟩, not_mem_empty a h
theorem eq_empty_of_not_terminates {s} (H : ¬ terminates s) : s = empty α :=
begin
apply subtype.eq, funext n,
induction h : s.val n, {refl},
refine absurd _ H, exact ⟨_, _, h.symm⟩
end
theorem thinkN_mem {s : computation α} {a} : ∀ n, a ∈ thinkN s n ↔ a ∈ s
| 0 := iff.rfl
| (n+1) := iff.trans ⟨of_think_mem, think_mem⟩ (thinkN_mem n)
instance thinkN_terminates (s : computation α) :
∀ [terminates s] n, terminates (thinkN s n)
| ⟨a, h⟩ n := ⟨a, (thinkN_mem n).2 h⟩
theorem of_thinkN_terminates (s : computation α) (n) :
terminates (thinkN s n) → terminates s
| ⟨a, h⟩ := ⟨a, (thinkN_mem _).1 h⟩
/-- `promises s a`, or `s ~> a`, asserts that although the computation `s`
may not terminate, if it does, then the result is `a`. -/
def promises (s : computation α) (a : α) : Prop := ∀ ⦃a'⦄, a' ∈ s → a = a'
infix ` ~> `:50 := promises
theorem mem_promises {s : computation α} {a : α} : a ∈ s → s ~> a :=
λ h a', mem_unique h
theorem empty_promises (a : α) : empty α ~> a :=
λ a' h, absurd h (not_mem_empty _)
section get
variables (s : computation α) [h : terminates s]
include s h
/-- `length s` gets the number of steps of a terminating computation -/
def length : ℕ := nat.find ((terminates_def _).1 h)
/-- `get s` returns the result of a terminating computation -/
def get : α := option.get (nat.find_spec $ (terminates_def _).1 h)
theorem get_mem : get s ∈ s :=
exists.intro (length s) (option.eq_some_of_is_some _).symm
theorem get_eq_of_mem {a} : a ∈ s → get s = a :=
mem_unique (get_mem _)
theorem mem_of_get_eq {a} : get s = a → a ∈ s :=
by intro h; rw ←h; apply get_mem
@[simp] theorem get_think : get (think s) = get s :=
get_eq_of_mem _ $ let ⟨n, h⟩ := get_mem s in ⟨n+1, h⟩
@[simp] theorem get_thinkN (n) : get (thinkN s n) = get s :=
get_eq_of_mem _ $ (thinkN_mem _).2 (get_mem _)
theorem get_promises : s ~> get s := λ a, get_eq_of_mem _
theorem mem_of_promises {a} (p : s ~> a) : a ∈ s :=
by { casesI h with a' h, rw p h, exact h }
theorem get_eq_of_promises {a} : s ~> a → get s = a :=
get_eq_of_mem _ ∘ mem_of_promises _
end get
/-- `results s a n` completely characterizes a terminating computation:
it asserts that `s` terminates after exactly `n` steps, with result `a`. -/
def results (s : computation α) (a : α) (n : ℕ) :=
∃ (h : a ∈ s), @length _ s (terminates_of_mem h) = n
theorem results_of_terminates (s : computation α) [T : terminates s] :
results s (get s) (length s) :=
⟨get_mem _, rfl⟩
theorem results_of_terminates' (s : computation α) [T : terminates s] {a} (h : a ∈ s) :
results s a (length s) :=
by rw ←get_eq_of_mem _ h; apply results_of_terminates
theorem results.mem {s : computation α} {a n} : results s a n → a ∈ s
| ⟨m, _⟩ := m
theorem results.terminates {s : computation α} {a n} (h : results s a n) : terminates s :=
terminates_of_mem h.mem
theorem results.length {s : computation α} {a n} [T : terminates s] :
results s a n → length s = n
| ⟨_, h⟩ := h
theorem results.val_unique {s : computation α} {a b m n}
(h1 : results s a m) (h2 : results s b n) : a = b :=
mem_unique h1.mem h2.mem
theorem results.len_unique {s : computation α} {a b m n}
(h1 : results s a m) (h2 : results s b n) : m = n :=
by haveI := h1.terminates; haveI := h2.terminates; rw [←h1.length, h2.length]
theorem exists_results_of_mem {s : computation α} {a} (h : a ∈ s) : ∃ n, results s a n :=
by haveI := terminates_of_mem h; exact ⟨_, results_of_terminates' s h⟩
@[simp] theorem get_ret (a : α) : get (return a) = a :=
get_eq_of_mem _ ⟨0, rfl⟩
@[simp] theorem length_ret (a : α) : length (return a) = 0 :=
let h := computation.ret_terminates a in
nat.eq_zero_of_le_zero $ nat.find_min' ((terminates_def (return a)).1 h) rfl
theorem results_ret (a : α) : results (return a) a 0 :=
⟨_, length_ret _⟩
@[simp] theorem length_think (s : computation α) [h : terminates s] :
length (think s) = length s + 1 :=
begin
apply le_antisymm,
{ exact nat.find_min' _ (nat.find_spec ((terminates_def _).1 h)) },
{ have : (option.is_some ((think s).val (length (think s))) : Prop) :=
nat.find_spec ((terminates_def _).1 s.think_terminates),
cases length (think s) with n,
{ contradiction },
{ apply nat.succ_le_succ, apply nat.find_min', apply this } }
end
theorem results_think {s : computation α} {a n}
(h : results s a n) : results (think s) a (n + 1) :=
by haveI := h.terminates; exact ⟨think_mem h.mem, by rw [length_think, h.length]⟩
theorem of_results_think {s : computation α} {a n}
(h : results (think s) a n) : ∃ m, results s a m ∧ n = m + 1 :=
begin
haveI := of_think_terminates h.terminates,
have := results_of_terminates' _ (of_think_mem h.mem),
exact ⟨_, this, results.len_unique h (results_think this)⟩,
end
@[simp] theorem results_think_iff {s : computation α} {a n} :
results (think s) a (n + 1) ↔ results s a n :=
⟨λ h, let ⟨n', r, e⟩ := of_results_think h in by injection e with h'; rwa h',
results_think⟩
theorem results_thinkN {s : computation α} {a m} :
∀ n, results s a m → results (thinkN s n) a (m + n)
| 0 h := h
| (n+1) h := results_think (results_thinkN n h)
theorem results_thinkN_ret (a : α) (n) : results (thinkN (return a) n) a n :=
by have := results_thinkN n (results_ret a); rwa nat.zero_add at this
@[simp] theorem length_thinkN (s : computation α) [h : terminates s] (n) :
length (thinkN s n) = length s + n :=
(results_thinkN n (results_of_terminates _)).length
theorem eq_thinkN {s : computation α} {a n} (h : results s a n) :
s = thinkN (return a) n :=
begin
revert s,
induction n with n IH; intro s;
apply cases_on s (λ a', _) (λ s, _); intro h,
{ rw ←eq_of_ret_mem h.mem, refl },
{ cases of_results_think h with n h, cases h, contradiction },
{ have := h.len_unique (results_ret _), contradiction },
{ rw IH (results_think_iff.1 h), refl }
end
theorem eq_thinkN' (s : computation α) [h : terminates s] :
s = thinkN (return (get s)) (length s) :=
eq_thinkN (results_of_terminates _)
def mem_rec_on {C : computation α → Sort v} {a s} (M : a ∈ s)
(h1 : C (return a)) (h2 : ∀ s, C s → C (think s)) : C s :=
begin
haveI T := terminates_of_mem M,
rw [eq_thinkN' s, get_eq_of_mem s M],
generalize : length s = n,
induction n with n IH, exacts [h1, h2 _ IH]
end
def terminates_rec_on {C : computation α → Sort v} (s) [terminates s]
(h1 : ∀ a, C (return a)) (h2 : ∀ s, C s → C (think s)) : C s :=
mem_rec_on (get_mem s) (h1 _) h2
/-- Map a function on the result of a computation. -/
def map (f : α → β) : computation α → computation β
| ⟨s, al⟩ := ⟨s.map (λo, option.cases_on o none (some ∘ f)),
λn b, begin
dsimp [stream.map, stream.nth],
induction e : s n with a; intro h,
{ contradiction }, { rw [al e, ←h] }
end⟩
def bind.G : β ⊕ computation β → β ⊕ computation α ⊕ computation β
| (sum.inl b) := sum.inl b
| (sum.inr cb') := sum.inr $ sum.inr cb'
def bind.F (f : α → computation β) :
computation α ⊕ computation β → β ⊕ computation α ⊕ computation β
| (sum.inl ca) :=
match destruct ca with
| sum.inl a := bind.G $ destruct (f a)
| sum.inr ca' := sum.inr $ sum.inl ca'
end
| (sum.inr cb) := bind.G $ destruct cb
/-- Compose two computations into a monadic `bind` operation. -/
def bind (c : computation α) (f : α → computation β) : computation β :=
corec (bind.F f) (sum.inl c)
instance : has_bind computation := ⟨@bind⟩
theorem has_bind_eq_bind {β} (c : computation α) (f : α → computation β) :
c >>= f = bind c f := rfl
/-- Flatten a computation of computations into a single computation. -/
def join (c : computation (computation α)) : computation α := c >>= id
@[simp] theorem map_ret (f : α → β) (a) : map f (return a) = return (f a) := rfl
@[simp] theorem map_think (f : α → β) : ∀ s, map f (think s) = think (map f s)
| ⟨s, al⟩ := by apply subtype.eq; dsimp [think, map]; rw stream.map_cons
@[simp]
theorem destruct_map (f : α → β) (s) : destruct (map f s) = lmap f (rmap (map f) (destruct s)) :=
by apply s.cases_on; intro; simp
@[simp] theorem map_id : ∀ (s : computation α), map id s = s
| ⟨f, al⟩ := begin
apply subtype.eq; simp [map, function.comp],
have e : (@option.rec α (λ_, option α) none some) = id,
{ ext ⟨⟩; refl },
simp [e, stream.map_id]
end
theorem map_comp (f : α → β) (g : β → γ) :
∀ (s : computation α), map (g ∘ f) s = map g (map f s)
| ⟨s, al⟩ := begin
apply subtype.eq; dsimp [map],
rw stream.map_map,
apply congr_arg (λ f : _ → option γ, stream.map f s),
ext ⟨⟩; refl
end
@[simp] theorem ret_bind (a) (f : α → computation β) :
bind (return a) f = f a :=
begin
apply eq_of_bisim (λc₁ c₂,
c₁ = bind (return a) f ∧ c₂ = f a ∨
c₁ = corec (bind.F f) (sum.inr c₂)),
{ intros c₁ c₂ h,
exact match c₁, c₂, h with
| ._, ._, or.inl ⟨rfl, rfl⟩ := begin
simp [bind, bind.F],
cases destruct (f a) with b cb; simp [bind.G]
end
| ._, c, or.inr rfl := begin
simp [bind.F],
cases destruct c with b cb; simp [bind.G]
end end },
{ simp }
end
@[simp] theorem think_bind (c) (f : α → computation β) :
bind (think c) f = think (bind c f) :=
destruct_eq_think $ by simp [bind, bind.F]
@[simp] theorem bind_ret (f : α → β) (s) : bind s (return ∘ f) = map f s :=
begin
apply eq_of_bisim (λc₁ c₂, c₁ = c₂ ∨
∃ s, c₁ = bind s (return ∘ f) ∧ c₂ = map f s),
{ intros c₁ c₂ h,
exact match c₁, c₂, h with
| _, _, or.inl (eq.refl c) := begin cases destruct c with b cb; simp end
| _, _, or.inr ⟨s, rfl, rfl⟩ := begin
apply cases_on s; intros s; simp,
exact or.inr ⟨s, rfl, rfl⟩
end end },
{ exact or.inr ⟨s, rfl, rfl⟩ }
end
@[simp] theorem bind_ret' (s : computation α) : bind s return = s :=
by rw bind_ret; change (λ x : α, x) with @id α; rw map_id
@[simp] theorem bind_assoc (s : computation α) (f : α → computation β) (g : β → computation γ) :
bind (bind s f) g = bind s (λ (x : α), bind (f x) g) :=
begin
apply eq_of_bisim (λc₁ c₂, c₁ = c₂ ∨
∃ s, c₁ = bind (bind s f) g ∧ c₂ = bind s (λ (x : α), bind (f x) g)),
{ intros c₁ c₂ h,
exact match c₁, c₂, h with
| _, _, or.inl (eq.refl c) := by cases destruct c with b cb; simp
| ._, ._, or.inr ⟨s, rfl, rfl⟩ := begin
apply cases_on s; intros s; simp,
{ generalize : f s = fs,
apply cases_on fs; intros t; simp,
{ cases destruct (g t) with b cb; simp } },
{ exact or.inr ⟨s, rfl, rfl⟩ }
end end },
{ exact or.inr ⟨s, rfl, rfl⟩ }
end
theorem results_bind {s : computation α} {f : α → computation β} {a b m n}
(h1 : results s a m) (h2 : results (f a) b n) : results (bind s f) b (n + m) :=
begin
have := h1.mem, revert m,
apply mem_rec_on this _ (λ s IH, _); intros m h1,
{ rw [ret_bind], rw h1.len_unique (results_ret _), exact h2 },
{ rw [think_bind], cases of_results_think h1 with m' h, cases h with h1 e,
rw e, exact results_think (IH h1) }
end
theorem mem_bind {s : computation α} {f : α → computation β} {a b}
(h1 : a ∈ s) (h2 : b ∈ f a) : b ∈ bind s f :=
let ⟨m, h1⟩ := exists_results_of_mem h1,
⟨n, h2⟩ := exists_results_of_mem h2 in (results_bind h1 h2).mem
instance terminates_bind (s : computation α) (f : α → computation β)
[terminates s] [terminates (f (get s))] :
terminates (bind s f) :=
terminates_of_mem (mem_bind (get_mem s) (get_mem (f (get s))))
@[simp] theorem get_bind (s : computation α) (f : α → computation β)
[terminates s] [terminates (f (get s))] :
get (bind s f) = get (f (get s)) :=
get_eq_of_mem _ (mem_bind (get_mem s) (get_mem (f (get s))))
@[simp] theorem length_bind (s : computation α) (f : α → computation β)
[T1 : terminates s] [T2 : terminates (f (get s))] :
length (bind s f) = length (f (get s)) + length s :=
(results_of_terminates _).len_unique $
results_bind (results_of_terminates _) (results_of_terminates _)
theorem of_results_bind {s : computation α} {f : α → computation β} {b k} :
results (bind s f) b k →
∃ a m n, results s a m ∧ results (f a) b n ∧ k = n + m :=
begin
induction k with n IH generalizing s;
apply cases_on s (λ a, _) (λ s', _); intro e,
{ simp [thinkN] at e, refine ⟨a, _, _, results_ret _, e, rfl⟩ },
{ have := congr_arg head (eq_thinkN e), contradiction },
{ simp at e, refine ⟨a, _, n+1, results_ret _, e, rfl⟩ },
{ simp at e, exact let ⟨a, m, n', h1, h2, e'⟩ := IH e in
by rw e'; exact ⟨a, m.succ, n', results_think h1, h2, rfl⟩ }
end
theorem exists_of_mem_bind {s : computation α} {f : α → computation β} {b}
(h : b ∈ bind s f) : ∃ a ∈ s, b ∈ f a :=
let ⟨k, h⟩ := exists_results_of_mem h,
⟨a, m, n, h1, h2, e⟩ := of_results_bind h in ⟨a, h1.mem, h2.mem⟩
theorem bind_promises {s : computation α} {f : α → computation β} {a b}
(h1 : s ~> a) (h2 : f a ~> b) : bind s f ~> b :=
λ b' bB, begin
rcases exists_of_mem_bind bB with ⟨a', a's, ba'⟩,
rw ←h1 a's at ba', exact h2 ba'
end
instance : monad computation :=
{ map := @map,
pure := @return,
bind := @bind }
instance : is_lawful_monad computation :=
{ id_map := @map_id,
bind_pure_comp_eq_map := @bind_ret,
pure_bind := @ret_bind,
bind_assoc := @bind_assoc }
theorem has_map_eq_map {β} (f : α → β) (c : computation α) : f <$> c = map f c := rfl
@[simp] theorem return_def (a) : (_root_.return a : computation α) = return a := rfl
@[simp] theorem map_ret' {α β} : ∀ (f : α → β) (a), f <$> return a = return (f a) := map_ret
@[simp] theorem map_think' {α β} : ∀ (f : α → β) s, f <$> think s = think (f <$> s) := map_think
theorem mem_map (f : α → β) {a} {s : computation α} (m : a ∈ s) : f a ∈ map f s :=
by rw ←bind_ret; apply mem_bind m; apply ret_mem
theorem exists_of_mem_map {f : α → β} {b : β} {s : computation α} (h : b ∈ map f s) :
∃ a, a ∈ s ∧ f a = b :=
by rw ←bind_ret at h; exact
let ⟨a, as, fb⟩ := exists_of_mem_bind h in ⟨a, as, mem_unique (ret_mem _) fb⟩
instance terminates_map (f : α → β) (s : computation α) [terminates s] : terminates (map f s) :=
by rw ←bind_ret; apply_instance
theorem terminates_map_iff (f : α → β) (s : computation α) :
terminates (map f s) ↔ terminates s :=
⟨λ⟨a, h⟩, let ⟨b, h1, _⟩ := exists_of_mem_map h in ⟨_, h1⟩, @computation.terminates_map _ _ _ _⟩
-- Parallel computation
/-- `c₁ <|> c₂` calculates `c₁` and `c₂` simultaneously, returning
the first one that gives a result. -/
def orelse (c₁ c₂ : computation α) : computation α :=
@computation.corec α (computation α × computation α)
(λ⟨c₁, c₂⟩, match destruct c₁ with
| sum.inl a := sum.inl a
| sum.inr c₁' := match destruct c₂ with
| sum.inl a := sum.inl a
| sum.inr c₂' := sum.inr (c₁', c₂')
end
end) (c₁, c₂)
instance : alternative computation :=
{ orelse := @orelse, failure := @empty, ..computation.monad }
@[simp] theorem ret_orelse (a : α) (c₂ : computation α) :
(return a <|> c₂) = return a :=
destruct_eq_ret $ by unfold has_orelse.orelse; simp [orelse]
@[simp] theorem orelse_ret (c₁ : computation α) (a : α) :
(think c₁ <|> return a) = return a :=
destruct_eq_ret $ by unfold has_orelse.orelse; simp [orelse]
@[simp] theorem orelse_think (c₁ c₂ : computation α) :
(think c₁ <|> think c₂) = think (c₁ <|> c₂) :=
destruct_eq_think $ by unfold has_orelse.orelse; simp [orelse]
@[simp] theorem empty_orelse (c) : (empty α <|> c) = c :=
begin
apply eq_of_bisim (λc₁ c₂, (empty α <|> c₂) = c₁) _ rfl,
intros s' s h, rw ←h,
apply cases_on s; intros s; rw think_empty; simp,
rw ←think_empty,
end
@[simp] theorem orelse_empty (c : computation α) : (c <|> empty α) = c :=
begin
apply eq_of_bisim (λc₁ c₂, (c₂ <|> empty α) = c₁) _ rfl,
intros s' s h, rw ←h,
apply cases_on s; intros s; rw think_empty; simp,
rw←think_empty,
end
/-- `c₁ ~ c₂` asserts that `c₁` and `c₂` either both terminate with the same result,
or both loop forever. -/
def equiv (c₁ c₂ : computation α) : Prop := ∀ a, a ∈ c₁ ↔ a ∈ c₂
infix ~ := equiv
@[refl] theorem equiv.refl (s : computation α) : s ~ s := λ_, iff.rfl
@[symm] theorem equiv.symm {s t : computation α} : s ~ t → t ~ s :=
λh a, (h a).symm
@[trans] theorem equiv.trans {s t u : computation α} : s ~ t → t ~ u → s ~ u :=
λh1 h2 a, (h1 a).trans (h2 a)
theorem equiv.equivalence : equivalence (@equiv α) :=
⟨@equiv.refl _, @equiv.symm _, @equiv.trans _⟩
theorem equiv_of_mem {s t : computation α} {a} (h1 : a ∈ s) (h2 : a ∈ t) : s ~ t :=
λa', ⟨λma, by rw mem_unique ma h1; exact h2,
λma, by rw mem_unique ma h2; exact h1⟩
theorem terminates_congr {c₁ c₂ : computation α}
(h : c₁ ~ c₂) : terminates c₁ ↔ terminates c₂ :=
exists_congr h
theorem promises_congr {c₁ c₂ : computation α}
(h : c₁ ~ c₂) (a) : c₁ ~> a ↔ c₂ ~> a :=
forall_congr (λa', imp_congr (h a') iff.rfl)
theorem get_equiv {c₁ c₂ : computation α} (h : c₁ ~ c₂)
[terminates c₁] [terminates c₂] : get c₁ = get c₂ :=
get_eq_of_mem _ $ (h _).2 $ get_mem _
theorem think_equiv (s : computation α) : think s ~ s :=
λ a, ⟨of_think_mem, think_mem⟩
theorem thinkN_equiv (s : computation α) (n) : thinkN s n ~ s :=
λ a, thinkN_mem n
theorem bind_congr {s1 s2 : computation α} {f1 f2 : α → computation β}
(h1 : s1 ~ s2) (h2 : ∀ a, f1 a ~ f2 a) : bind s1 f1 ~ bind s2 f2 :=
λ b, ⟨λh, let ⟨a, ha, hb⟩ := exists_of_mem_bind h in
mem_bind ((h1 a).1 ha) ((h2 a b).1 hb),
λh, let ⟨a, ha, hb⟩ := exists_of_mem_bind h in
mem_bind ((h1 a).2 ha) ((h2 a b).2 hb)⟩
theorem equiv_ret_of_mem {s : computation α} {a} (h : a ∈ s) : s ~ return a :=
equiv_of_mem h (ret_mem _)
/-- `lift_rel R ca cb` is a generalization of `equiv` to relations other than
equality. It asserts that if `ca` terminates with `a`, then `cb` terminates with
some `b` such that `R a b`, and if `cb` terminates with `b` then `ca` terminates
with some `a` such that `R a b`. -/
def lift_rel (R : α → β → Prop) (ca : computation α) (cb : computation β) : Prop :=
(∀ {a}, a ∈ ca → ∃ {b}, b ∈ cb ∧ R a b) ∧
∀ {b}, b ∈ cb → ∃ {a}, a ∈ ca ∧ R a b
theorem lift_rel.swap (R : α → β → Prop) (ca : computation α) (cb : computation β) :
lift_rel (function.swap R) cb ca ↔ lift_rel R ca cb :=
and_comm _ _
theorem lift_eq_iff_equiv (c₁ c₂ : computation α) : lift_rel (=) c₁ c₂ ↔ c₁ ~ c₂ :=
⟨λ⟨h1, h2⟩ a,
⟨λ a1, let ⟨b, b2, ab⟩ := h1 a1 in by rwa ab,
λ a2, let ⟨b, b1, ab⟩ := h2 a2 in by rwa ←ab⟩,
λe, ⟨λ a a1, ⟨a, (e _).1 a1, rfl⟩, λ a a2, ⟨a, (e _).2 a2, rfl⟩⟩⟩
theorem lift_rel.refl (R : α → α → Prop) (H : reflexive R) : reflexive (lift_rel R) :=
λ s, ⟨λ a as, ⟨a, as, H a⟩, λ b bs, ⟨b, bs, H b⟩⟩
theorem lift_rel.symm (R : α → α → Prop) (H : symmetric R) : symmetric (lift_rel R) :=
λ s1 s2 ⟨l, r⟩,
⟨λ a a2, let ⟨b, b1, ab⟩ := r a2 in ⟨b, b1, H ab⟩,
λ a a1, let ⟨b, b2, ab⟩ := l a1 in ⟨b, b2, H ab⟩⟩
theorem lift_rel.trans (R : α → α → Prop) (H : transitive R) : transitive (lift_rel R) :=
λ s1 s2 s3 ⟨l1, r1⟩ ⟨l2, r2⟩,
⟨λ a a1, let ⟨b, b2, ab⟩ := l1 a1, ⟨c, c3, bc⟩ := l2 b2 in ⟨c, c3, H ab bc⟩,
λ c c3, let ⟨b, b2, bc⟩ := r2 c3, ⟨a, a1, ab⟩ := r1 b2 in ⟨a, a1, H ab bc⟩⟩
theorem lift_rel.equiv (R : α → α → Prop) : equivalence R → equivalence (lift_rel R)
| ⟨refl, symm, trans⟩ :=
⟨lift_rel.refl R refl, lift_rel.symm R symm, lift_rel.trans R trans⟩
theorem lift_rel.imp {R S : α → β → Prop} (H : ∀ {a b}, R a b → S a b) (s t) :
lift_rel R s t → lift_rel S s t | ⟨l, r⟩ :=
⟨λ a as, let ⟨b, bt, ab⟩ := l as in ⟨b, bt, H ab⟩,
λ b bt, let ⟨a, as, ab⟩ := r bt in ⟨a, as, H ab⟩⟩
theorem terminates_of_lift_rel {R : α → β → Prop} {s t} :
lift_rel R s t → (terminates s ↔ terminates t) | ⟨l, r⟩ :=
⟨λ ⟨a, as⟩, let ⟨b, bt, ab⟩ := l as in ⟨b, bt⟩,
λ ⟨b, bt⟩, let ⟨a, as, ab⟩ := r bt in ⟨a, as⟩⟩
theorem rel_of_lift_rel {R : α → β → Prop} {ca cb} :
lift_rel R ca cb → ∀ {a b}, a ∈ ca → b ∈ cb → R a b
| ⟨l, r⟩ a b ma mb :=
let ⟨b', mb', ab'⟩ := l ma in by rw mem_unique mb mb'; exact ab'
theorem lift_rel_of_mem {R : α → β → Prop} {a b ca cb}
(ma : a ∈ ca) (mb : b ∈ cb) (ab : R a b) : lift_rel R ca cb :=
⟨λ a' ma', by rw mem_unique ma' ma; exact ⟨b, mb, ab⟩,
λ b' mb', by rw mem_unique mb' mb; exact ⟨a, ma, ab⟩⟩
theorem exists_of_lift_rel_left {R : α → β → Prop} {ca cb}
(H : lift_rel R ca cb) {a} (h : a ∈ ca) : ∃ {b}, b ∈ cb ∧ R a b :=
H.left h
theorem exists_of_lift_rel_right {R : α → β → Prop} {ca cb}
(H : lift_rel R ca cb) {b} (h : b ∈ cb) : ∃ {a}, a ∈ ca ∧ R a b :=
H.right h
theorem lift_rel_def {R : α → β → Prop} {ca cb} : lift_rel R ca cb ↔
(terminates ca ↔ terminates cb) ∧ ∀ {a b}, a ∈ ca → b ∈ cb → R a b :=
⟨λh, ⟨terminates_of_lift_rel h, λ a b ma mb,
let ⟨b', mb', ab⟩ := h.left ma in by rwa mem_unique mb mb'⟩,
λ⟨l, r⟩,
⟨λ a ma, let ⟨b, mb⟩ := l.1 ⟨_, ma⟩ in ⟨b, mb, r ma mb⟩,
λ b mb, let ⟨a, ma⟩ := l.2 ⟨_, mb⟩ in ⟨a, ma, r ma mb⟩⟩⟩
theorem lift_rel_bind {δ} (R : α → β → Prop) (S : γ → δ → Prop)
{s1 : computation α} {s2 : computation β}
{f1 : α → computation γ} {f2 : β → computation δ}
(h1 : lift_rel R s1 s2) (h2 : ∀ {a b}, R a b → lift_rel S (f1 a) (f2 b))
: lift_rel S (bind s1 f1) (bind s2 f2) :=
let ⟨l1, r1⟩ := h1 in
⟨λ c cB,
let ⟨a, a1, c₁⟩ := exists_of_mem_bind cB,
⟨b, b2, ab⟩ := l1 a1,
⟨l2, r2⟩ := h2 ab,
⟨d, d2, cd⟩ := l2 c₁ in
⟨_, mem_bind b2 d2, cd⟩,
λ d dB,
let ⟨b, b1, d1⟩ := exists_of_mem_bind dB,
⟨a, a2, ab⟩ := r1 b1,
⟨l2, r2⟩ := h2 ab,
⟨c, c₂, cd⟩ := r2 d1 in
⟨_, mem_bind a2 c₂, cd⟩⟩
@[simp] theorem lift_rel_return_left (R : α → β → Prop) (a : α) (cb : computation β) :
lift_rel R (return a) cb ↔ ∃ {b}, b ∈ cb ∧ R a b :=
⟨λ⟨l, r⟩, l (ret_mem _),
λ⟨b, mb, ab⟩,
⟨λ a' ma', by rw eq_of_ret_mem ma'; exact ⟨b, mb, ab⟩,
λ b' mb', ⟨_, ret_mem _, by rw mem_unique mb' mb; exact ab⟩⟩⟩
@[simp] theorem lift_rel_return_right (R : α → β → Prop) (ca : computation α) (b : β) :
lift_rel R ca (return b) ↔ ∃ {a}, a ∈ ca ∧ R a b :=
by rw [lift_rel.swap, lift_rel_return_left]
@[simp] theorem lift_rel_return (R : α → β → Prop) (a : α) (b : β) :
lift_rel R (return a) (return b) ↔ R a b :=
by rw [lift_rel_return_left]; exact
⟨λ⟨b', mb', ab'⟩, by rwa eq_of_ret_mem mb' at ab',
λab, ⟨_, ret_mem _, ab⟩⟩
@[simp] theorem lift_rel_think_left (R : α → β → Prop) (ca : computation α) (cb : computation β) :
lift_rel R (think ca) cb ↔ lift_rel R ca cb :=
and_congr (forall_congr $ λb, imp_congr ⟨of_think_mem, think_mem⟩ iff.rfl)
(forall_congr $ λb, imp_congr iff.rfl $
exists_congr $ λ b, and_congr ⟨of_think_mem, think_mem⟩ iff.rfl)
@[simp] theorem lift_rel_think_right (R : α → β → Prop) (ca : computation α) (cb : computation β) :
lift_rel R ca (think cb) ↔ lift_rel R ca cb :=
by rw [←lift_rel.swap R, ←lift_rel.swap R]; apply lift_rel_think_left
theorem lift_rel_mem_cases {R : α → β → Prop} {ca cb}
(Ha : ∀ a ∈ ca, lift_rel R ca cb)
(Hb : ∀ b ∈ cb, lift_rel R ca cb) : lift_rel R ca cb :=
⟨λ a ma, (Ha _ ma).left ma, λ b mb, (Hb _ mb).right mb⟩
theorem lift_rel_congr {R : α → β → Prop} {ca ca' : computation α} {cb cb' : computation β}
(ha : ca ~ ca') (hb : cb ~ cb') : lift_rel R ca cb ↔ lift_rel R ca' cb' :=
and_congr
(forall_congr $ λ a, imp_congr (ha _) $ exists_congr $ λ b, and_congr (hb _) iff.rfl)
(forall_congr $ λ b, imp_congr (hb _) $ exists_congr $ λ a, and_congr (ha _) iff.rfl)
theorem lift_rel_map {δ} (R : α → β → Prop) (S : γ → δ → Prop)
{s1 : computation α} {s2 : computation β}
{f1 : α → γ} {f2 : β → δ}
(h1 : lift_rel R s1 s2) (h2 : ∀ {a b}, R a b → S (f1 a) (f2 b))
: lift_rel S (map f1 s1) (map f2 s2) :=
by rw [←bind_ret, ←bind_ret]; apply lift_rel_bind _ _ h1; simp; exact @h2
theorem map_congr (R : α → α → Prop) (S : β → β → Prop)
{s1 s2 : computation α} {f : α → β}
(h1 : s1 ~ s2) : map f s1 ~ map f s2 :=
by rw [←lift_eq_iff_equiv];
exact lift_rel_map eq _ ((lift_eq_iff_equiv _ _).2 h1) (λ a b, congr_arg _)
def lift_rel_aux (R : α → β → Prop)
(C : computation α → computation β → Prop) :
α ⊕ computation α → β ⊕ computation β → Prop
| (sum.inl a) (sum.inl b) := R a b
| (sum.inl a) (sum.inr cb) := ∃ {b}, b ∈ cb ∧ R a b
| (sum.inr ca) (sum.inl b) := ∃ {a}, a ∈ ca ∧ R a b
| (sum.inr ca) (sum.inr cb) := C ca cb
attribute [simp] lift_rel_aux
@[simp] lemma lift_rel_aux.ret_left (R : α → β → Prop)
(C : computation α → computation β → Prop) (a cb) :
lift_rel_aux R C (sum.inl a) (destruct cb) ↔ ∃ {b}, b ∈ cb ∧ R a b :=
begin
apply cb.cases_on (λ b, _) (λ cb, _),
{ exact ⟨λ h, ⟨_, ret_mem _, h⟩, λ ⟨b', mb, h⟩,
by rw [mem_unique (ret_mem _) mb]; exact h⟩ },
{ rw [destruct_think],
exact ⟨λ ⟨b, h, r⟩, ⟨b, think_mem h, r⟩,
λ ⟨b, h, r⟩, ⟨b, of_think_mem h, r⟩⟩ }
end
theorem lift_rel_aux.swap (R : α → β → Prop) (C) (a b) :
lift_rel_aux (function.swap R) (function.swap C) b a = lift_rel_aux R C a b :=
by cases a with a ca; cases b with b cb; simp only [lift_rel_aux]
@[simp] lemma lift_rel_aux.ret_right (R : α → β → Prop)
(C : computation α → computation β → Prop) (b ca) :
lift_rel_aux R C (destruct ca) (sum.inl b) ↔ ∃ {a}, a ∈ ca ∧ R a b :=
by rw [←lift_rel_aux.swap, lift_rel_aux.ret_left]
theorem lift_rel_rec.lem {R : α → β → Prop} (C : computation α → computation β → Prop)
(H : ∀ {ca cb}, C ca cb → lift_rel_aux R C (destruct ca) (destruct cb))
(ca cb) (Hc : C ca cb) (a) (ha : a ∈ ca) : lift_rel R ca cb :=
begin
revert cb, refine mem_rec_on ha _ (λ ca' IH, _);
intros cb Hc; have h := H Hc,
{ simp at h, simp [h] },
{ have h := H Hc, simp, revert h, apply cb.cases_on (λ b, _) (λ cb', _);
intro h; simp at h; simp [h], exact IH _ h }
end
theorem lift_rel_rec {R : α → β → Prop} (C : computation α → computation β → Prop)
(H : ∀ {ca cb}, C ca cb → lift_rel_aux R C (destruct ca) (destruct cb))
(ca cb) (Hc : C ca cb) : lift_rel R ca cb :=
lift_rel_mem_cases (lift_rel_rec.lem C @H ca cb Hc) (λ b hb,
(lift_rel.swap _ _ _).2 $
lift_rel_rec.lem (function.swap C)
(λ cb ca h, cast (lift_rel_aux.swap _ _ _ _).symm $ H h)
cb ca Hc b hb)
end computation
|
d51b208b6b2a4b2c3269f80968e1445e00fa7ad9 | 947fa6c38e48771ae886239b4edce6db6e18d0fb | /src/linear_algebra/finsupp.lean | 632fb1487a7fd5ed50e2bb692fd5ec3c925d9a32 | [
"Apache-2.0"
] | permissive | ramonfmir/mathlib | c5dc8b33155473fab97c38bd3aa6723dc289beaa | 14c52e990c17f5a00c0cc9e09847af16fabbed25 | refs/heads/master | 1,661,979,343,526 | 1,660,830,384,000 | 1,660,830,384,000 | 182,072,989 | 0 | 0 | null | 1,555,585,876,000 | 1,555,585,876,000 | null | UTF-8 | Lean | false | false | 38,755 | lean | /-
Copyright (c) 2019 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl
-/
import data.finsupp.basic
import linear_algebra.pi
import linear_algebra.span
/-!
# Properties of the module `α →₀ M`
Given an `R`-module `M`, the `R`-module structure on `α →₀ M` is defined in
`data.finsupp.basic`.
In this file we define `finsupp.supported s` to be the set `{f : α →₀ M | f.support ⊆ s}`
interpreted as a submodule of `α →₀ M`. We also define `linear_map` versions of various maps:
* `finsupp.lsingle a : M →ₗ[R] ι →₀ M`: `finsupp.single a` as a linear map;
* `finsupp.lapply a : (ι →₀ M) →ₗ[R] M`: the map `λ f, f a` as a linear map;
* `finsupp.lsubtype_domain (s : set α) : (α →₀ M) →ₗ[R] (s →₀ M)`: restriction to a subtype as a
linear map;
* `finsupp.restrict_dom`: `finsupp.filter` as a linear map to `finsupp.supported s`;
* `finsupp.lsum`: `finsupp.sum` or `finsupp.lift_add_hom` as a `linear_map`;
* `finsupp.total α M R (v : ι → M)`: sends `l : ι → R` to the linear combination of `v i` with
coefficients `l i`;
* `finsupp.total_on`: a restricted version of `finsupp.total` with domain `finsupp.supported R R s`
and codomain `submodule.span R (v '' s)`;
* `finsupp.supported_equiv_finsupp`: a linear equivalence between the functions `α →₀ M` supported
on `s` and the functions `s →₀ M`;
* `finsupp.lmap_domain`: a linear map version of `finsupp.map_domain`;
* `finsupp.dom_lcongr`: a `linear_equiv` version of `finsupp.dom_congr`;
* `finsupp.congr`: if the sets `s` and `t` are equivalent, then `supported M R s` is equivalent to
`supported M R t`;
* `finsupp.lcongr`: a `linear_equiv`alence between `α →₀ M` and `β →₀ N` constructed using `e : α ≃
β` and `e' : M ≃ₗ[R] N`.
## Tags
function with finite support, module, linear algebra
-/
noncomputable theory
open set linear_map submodule
open_locale classical big_operators
namespace finsupp
variables {α : Type*} {M : Type*} {N : Type*} {P : Type*} {R : Type*} {S : Type*}
variables [semiring R] [semiring S] [add_comm_monoid M] [module R M]
variables [add_comm_monoid N] [module R N]
variables [add_comm_monoid P] [module R P]
/-- Interpret `finsupp.single a` as a linear map. -/
def lsingle (a : α) : M →ₗ[R] (α →₀ M) :=
{ map_smul' := assume a b, (smul_single _ _ _).symm, ..finsupp.single_add_hom a }
/-- Two `R`-linear maps from `finsupp X M` which agree on each `single x y` agree everywhere. -/
lemma lhom_ext ⦃φ ψ : (α →₀ M) →ₗ[R] N⦄ (h : ∀ a b, φ (single a b) = ψ (single a b)) :
φ = ψ :=
linear_map.to_add_monoid_hom_injective $ add_hom_ext h
/-- Two `R`-linear maps from `finsupp X M` which agree on each `single x y` agree everywhere.
We formulate this fact using equality of linear maps `φ.comp (lsingle a)` and `ψ.comp (lsingle a)`
so that the `ext` tactic can apply a type-specific extensionality lemma to prove equality of these
maps. E.g., if `M = R`, then it suffices to verify `φ (single a 1) = ψ (single a 1)`. -/
@[ext] lemma lhom_ext' ⦃φ ψ : (α →₀ M) →ₗ[R] N⦄ (h : ∀ a, φ.comp (lsingle a) = ψ.comp (lsingle a)) :
φ = ψ :=
lhom_ext $ λ a, linear_map.congr_fun (h a)
/-- Interpret `λ (f : α →₀ M), f a` as a linear map. -/
def lapply (a : α) : (α →₀ M) →ₗ[R] M :=
{ map_smul' := assume a b, rfl, ..finsupp.apply_add_hom a }
section lsubtype_domain
variables (s : set α)
/-- Interpret `finsupp.subtype_domain s` as a linear map. -/
def lsubtype_domain : (α →₀ M) →ₗ[R] (s →₀ M) :=
{ to_fun := subtype_domain (λx, x ∈ s),
map_add' := λ a b, subtype_domain_add,
map_smul' := λ c a, ext $ λ a, rfl }
lemma lsubtype_domain_apply (f : α →₀ M) :
(lsubtype_domain s : (α →₀ M) →ₗ[R] (s →₀ M)) f = subtype_domain (λx, x ∈ s) f := rfl
end lsubtype_domain
@[simp] lemma lsingle_apply (a : α) (b : M) : (lsingle a : M →ₗ[R] (α →₀ M)) b = single a b :=
rfl
@[simp] lemma lapply_apply (a : α) (f : α →₀ M) : (lapply a : (α →₀ M) →ₗ[R] M) f = f a :=
rfl
@[simp] lemma ker_lsingle (a : α) : (lsingle a : M →ₗ[R] (α →₀ M)).ker = ⊥ :=
ker_eq_bot_of_injective (single_injective a)
lemma lsingle_range_le_ker_lapply (s t : set α) (h : disjoint s t) :
(⨆a∈s, (lsingle a : M →ₗ[R] (α →₀ M)).range) ≤ (⨅a∈t, ker (lapply a)) :=
begin
refine supr_le (assume a₁, supr_le $ assume h₁, range_le_iff_comap.2 _),
simp only [(ker_comp _ _).symm, eq_top_iff, set_like.le_def, mem_ker, comap_infi, mem_infi],
assume b hb a₂ h₂,
have : a₁ ≠ a₂ := assume eq, h ⟨h₁, eq.symm ▸ h₂⟩,
exact single_eq_of_ne this
end
lemma infi_ker_lapply_le_bot : (⨅a, ker (lapply a : (α →₀ M) →ₗ[R] M)) ≤ ⊥ :=
begin
simp only [set_like.le_def, mem_infi, mem_ker, mem_bot, lapply_apply],
exact assume a h, finsupp.ext h
end
lemma supr_lsingle_range : (⨆a, (lsingle a : M →ₗ[R] (α →₀ M)).range) = ⊤ :=
begin
refine (eq_top_iff.2 $ set_like.le_def.2 $ assume f _, _),
rw [← sum_single f],
exact sum_mem (assume a ha, submodule.mem_supr_of_mem a ⟨_, rfl⟩),
end
lemma disjoint_lsingle_lsingle (s t : set α) (hs : disjoint s t) :
disjoint (⨆a∈s, (lsingle a : M →ₗ[R] (α →₀ M)).range) (⨆a∈t, (lsingle a).range) :=
begin
refine disjoint.mono
(lsingle_range_le_ker_lapply _ _ $ disjoint_compl_right)
(lsingle_range_le_ker_lapply _ _ $ disjoint_compl_right)
(le_trans (le_infi $ assume i, _) infi_ker_lapply_le_bot),
classical,
by_cases his : i ∈ s,
{ by_cases hit : i ∈ t,
{ exact (hs ⟨his, hit⟩).elim },
exact inf_le_of_right_le (infi_le_of_le i $ infi_le _ hit) },
exact inf_le_of_left_le (infi_le_of_le i $ infi_le _ his)
end
lemma span_single_image (s : set M) (a : α) :
submodule.span R (single a '' s) = (submodule.span R s).map (lsingle a) :=
by rw ← span_image; refl
variables (M R)
/-- `finsupp.supported M R s` is the `R`-submodule of all `p : α →₀ M` such that `p.support ⊆ s`. -/
def supported (s : set α) : submodule R (α →₀ M) :=
begin
refine ⟨ {p | ↑p.support ⊆ s }, _, _, _ ⟩,
{ assume p q hp hq,
refine subset.trans
(subset.trans (finset.coe_subset.2 support_add) _) (union_subset hp hq),
rw [finset.coe_union] },
{ simp only [subset_def, finset.mem_coe, set.mem_set_of_eq, mem_support_iff, zero_apply],
assume h ha, exact (ha rfl).elim },
{ assume a p hp,
refine subset.trans (finset.coe_subset.2 support_smul) hp }
end
variables {M}
lemma mem_supported {s : set α} (p : α →₀ M) : p ∈ (supported M R s) ↔ ↑p.support ⊆ s :=
iff.rfl
lemma mem_supported' {s : set α} (p : α →₀ M) :
p ∈ supported M R s ↔ ∀ x ∉ s, p x = 0 :=
by haveI := classical.dec_pred (λ (x : α), x ∈ s);
simp [mem_supported, set.subset_def, not_imp_comm]
lemma mem_supported_support (p : α →₀ M) :
p ∈ finsupp.supported M R (p.support : set α) :=
by rw finsupp.mem_supported
lemma single_mem_supported {s : set α} {a : α} (b : M) (h : a ∈ s) :
single a b ∈ supported M R s :=
set.subset.trans support_single_subset (finset.singleton_subset_set_iff.2 h)
lemma supported_eq_span_single (s : set α) :
supported R R s = span R ((λ i, single i 1) '' s) :=
begin
refine (span_eq_of_le _ _ (set_like.le_def.2 $ λ l hl, _)).symm,
{ rintro _ ⟨_, hp, rfl ⟩ , exact single_mem_supported R 1 hp },
{ rw ← l.sum_single,
refine sum_mem (λ i il, _),
convert @smul_mem R (α →₀ R) _ _ _ _ (single i 1) (l i) _,
{ simp },
apply subset_span,
apply set.mem_image_of_mem _ (hl il) }
end
variables (M R)
/-- Interpret `finsupp.filter s` as a linear map from `α →₀ M` to `supported M R s`. -/
def restrict_dom (s : set α) : (α →₀ M) →ₗ[R] supported M R s :=
linear_map.cod_restrict _
{ to_fun := filter (∈ s),
map_add' := λ l₁ l₂, filter_add,
map_smul' := λ a l, filter_smul }
(λ l, (mem_supported' _ _).2 $ λ x, filter_apply_neg (∈ s) l)
variables {M R}
section
@[simp] theorem restrict_dom_apply (s : set α) (l : α →₀ M) :
((restrict_dom M R s : (α →₀ M) →ₗ[R] supported M R s) l : α →₀ M) = finsupp.filter (∈ s) l := rfl
end
theorem restrict_dom_comp_subtype (s : set α) :
(restrict_dom M R s).comp (submodule.subtype _) = linear_map.id :=
begin
ext l a,
by_cases a ∈ s; simp [h],
exact ((mem_supported' R l.1).1 l.2 a h).symm
end
theorem range_restrict_dom (s : set α) :
(restrict_dom M R s).range = ⊤ :=
range_eq_top.2 $ function.right_inverse.surjective $
linear_map.congr_fun (restrict_dom_comp_subtype s)
theorem supported_mono {s t : set α} (st : s ⊆ t) :
supported M R s ≤ supported M R t :=
λ l h, set.subset.trans h st
@[simp] theorem supported_empty : supported M R (∅ : set α) = ⊥ :=
eq_bot_iff.2 $ λ l h, (submodule.mem_bot R).2 $
by ext; simp [*, mem_supported'] at *
@[simp] theorem supported_univ : supported M R (set.univ : set α) = ⊤ :=
eq_top_iff.2 $ λ l _, set.subset_univ _
theorem supported_Union {δ : Type*} (s : δ → set α) :
supported M R (⋃ i, s i) = ⨆ i, supported M R (s i) :=
begin
refine le_antisymm _ (supr_le $ λ i, supported_mono $ set.subset_Union _ _),
haveI := classical.dec_pred (λ x, x ∈ (⋃ i, s i)),
suffices : ((submodule.subtype _).comp (restrict_dom M R (⋃ i, s i))).range ≤
⨆ i, supported M R (s i),
{ rwa [linear_map.range_comp, range_restrict_dom, map_top, range_subtype] at this },
rw [range_le_iff_comap, eq_top_iff],
rintro l ⟨⟩,
apply finsupp.induction l, { exact zero_mem _ },
refine λ x a l hl a0, add_mem _,
by_cases (∃ i, x ∈ s i); simp [h],
{ cases h with i hi,
exact le_supr (λ i, supported M R (s i)) i (single_mem_supported R _ hi) }
end
theorem supported_union (s t : set α) :
supported M R (s ∪ t) = supported M R s ⊔ supported M R t :=
by erw [set.union_eq_Union, supported_Union, supr_bool_eq]; refl
theorem supported_Inter {ι : Type*} (s : ι → set α) :
supported M R (⋂ i, s i) = ⨅ i, supported M R (s i) :=
submodule.ext $ λ x, by simp [mem_supported, subset_Inter_iff]
theorem supported_inter (s t : set α) :
supported M R (s ∩ t) = supported M R s ⊓ supported M R t :=
by rw [set.inter_eq_Inter, supported_Inter, infi_bool_eq]; refl
theorem disjoint_supported_supported {s t : set α} (h : disjoint s t) :
disjoint (supported M R s) (supported M R t) :=
disjoint_iff.2 $ by rw [← supported_inter, disjoint_iff_inter_eq_empty.1 h, supported_empty]
theorem disjoint_supported_supported_iff [nontrivial M] {s t : set α} :
disjoint (supported M R s) (supported M R t) ↔ disjoint s t :=
begin
refine ⟨λ h x hx, _, disjoint_supported_supported⟩,
rcases exists_ne (0 : M) with ⟨y, hy⟩,
have := h ⟨single_mem_supported R y hx.1, single_mem_supported R y hx.2⟩,
rw [mem_bot, single_eq_zero] at this,
exact hy this
end
/-- Interpret `finsupp.restrict_support_equiv` as a linear equivalence between
`supported M R s` and `s →₀ M`. -/
def supported_equiv_finsupp (s : set α) : (supported M R s) ≃ₗ[R] (s →₀ M) :=
begin
let F : (supported M R s) ≃ (s →₀ M) := restrict_support_equiv s M,
refine F.to_linear_equiv _,
have : (F : (supported M R s) → (↥s →₀ M)) = ((lsubtype_domain s : (α →₀ M) →ₗ[R] (s →₀ M)).comp
(submodule.subtype (supported M R s))) := rfl,
rw this,
exact linear_map.is_linear _
end
section lsum
variables (S) [module S N] [smul_comm_class R S N]
/-- Lift a family of linear maps `M →ₗ[R] N` indexed by `x : α` to a linear map from `α →₀ M` to
`N` using `finsupp.sum`. This is an upgraded version of `finsupp.lift_add_hom`.
See note [bundled maps over different rings] for why separate `R` and `S` semirings are used.
-/
def lsum : (α → M →ₗ[R] N) ≃ₗ[S] ((α →₀ M) →ₗ[R] N) :=
{ to_fun := λ F,
{ to_fun := λ d, d.sum (λ i, F i),
map_add' := (lift_add_hom (λ x, (F x).to_add_monoid_hom)).map_add,
map_smul' := λ c f, by simp [sum_smul_index', smul_sum] },
inv_fun := λ F x, F.comp (lsingle x),
left_inv := λ F, by { ext x y, simp },
right_inv := λ F, by { ext x y, simp },
map_add' := λ F G, by { ext x y, simp },
map_smul' := λ F G, by { ext x y, simp } }
@[simp] lemma coe_lsum (f : α → M →ₗ[R] N) : (lsum S f : (α →₀ M) → N) = λ d, d.sum (λ i, f i) :=
rfl
theorem lsum_apply (f : α → M →ₗ[R] N) (l : α →₀ M) :
finsupp.lsum S f l = l.sum (λ b, f b) := rfl
theorem lsum_single (f : α → M →ₗ[R] N) (i : α) (m : M) :
finsupp.lsum S f (finsupp.single i m) = f i m :=
finsupp.sum_single_index (f i).map_zero
theorem lsum_symm_apply (f : (α →₀ M) →ₗ[R] N) (x : α) :
(lsum S).symm f x = f.comp (lsingle x) := rfl
end lsum
section
variables (M) (R) (X : Type*)
/--
A slight rearrangement from `lsum` gives us
the bijection underlying the free-forgetful adjunction for R-modules.
-/
noncomputable def lift : (X → M) ≃+ ((X →₀ R) →ₗ[R] M) :=
(add_equiv.arrow_congr (equiv.refl X) (ring_lmap_equiv_self R ℕ M).to_add_equiv.symm).trans
(lsum _ : _ ≃ₗ[ℕ] _).to_add_equiv
@[simp]
lemma lift_symm_apply (f) (x) : ((lift M R X).symm f) x = f (single x 1) :=
rfl
@[simp]
lemma lift_apply (f) (g) :
((lift M R X) f) g = g.sum (λ x r, r • f x) :=
rfl
end
section lmap_domain
variables {α' : Type*} {α'' : Type*} (M R)
/-- Interpret `finsupp.map_domain` as a linear map. -/
def lmap_domain (f : α → α') : (α →₀ M) →ₗ[R] (α' →₀ M) :=
{ to_fun := map_domain f, map_add' := λ a b, map_domain_add, map_smul' := map_domain_smul }
@[simp] theorem lmap_domain_apply (f : α → α') (l : α →₀ M) :
(lmap_domain M R f : (α →₀ M) →ₗ[R] (α' →₀ M)) l = map_domain f l := rfl
@[simp] theorem lmap_domain_id : (lmap_domain M R id : (α →₀ M) →ₗ[R] α →₀ M) = linear_map.id :=
linear_map.ext $ λ l, map_domain_id
theorem lmap_domain_comp (f : α → α') (g : α' → α'') :
lmap_domain M R (g ∘ f) = (lmap_domain M R g).comp (lmap_domain M R f) :=
linear_map.ext $ λ l, map_domain_comp
theorem supported_comap_lmap_domain (f : α → α') (s : set α') :
supported M R (f ⁻¹' s) ≤ (supported M R s).comap (lmap_domain M R f) :=
λ l (hl : ↑l.support ⊆ f ⁻¹' s),
show ↑(map_domain f l).support ⊆ s, begin
rw [← set.image_subset_iff, ← finset.coe_image] at hl,
exact set.subset.trans map_domain_support hl
end
theorem lmap_domain_supported [nonempty α] (f : α → α') (s : set α) :
(supported M R s).map (lmap_domain M R f) = supported M R (f '' s) :=
begin
inhabit α,
refine le_antisymm (map_le_iff_le_comap.2 $
le_trans (supported_mono $ set.subset_preimage_image _ _)
(supported_comap_lmap_domain _ _ _ _)) _,
intros l hl,
refine ⟨(lmap_domain M R (function.inv_fun_on f s) : (α' →₀ M) →ₗ[R] α →₀ M) l, λ x hx, _, _⟩,
{ rcases finset.mem_image.1 (map_domain_support hx) with ⟨c, hc, rfl⟩,
exact function.inv_fun_on_mem (by simpa using hl hc) },
{ rw [← linear_map.comp_apply, ← lmap_domain_comp],
refine (map_domain_congr $ λ c hc, _).trans map_domain_id,
exact function.inv_fun_on_eq (by simpa using hl hc) }
end
theorem lmap_domain_disjoint_ker (f : α → α') {s : set α}
(H : ∀ a b ∈ s, f a = f b → a = b) :
disjoint (supported M R s) (lmap_domain M R f).ker :=
begin
rintro l ⟨h₁, h₂⟩,
rw [set_like.mem_coe, mem_ker, lmap_domain_apply, map_domain] at h₂,
simp, ext x,
haveI := classical.dec_pred (λ x, x ∈ s),
by_cases xs : x ∈ s,
{ have : finsupp.sum l (λ a, finsupp.single (f a)) (f x) = 0, {rw h₂, refl},
rw [finsupp.sum_apply, finsupp.sum, finset.sum_eq_single x] at this,
{ simpa [finsupp.single_apply] },
{ intros y hy xy, simp [mt (H _ (h₁ hy) _ xs) xy] },
{ simp {contextual := tt} } },
{ by_contra h, exact xs (h₁ $ finsupp.mem_support_iff.2 h) }
end
end lmap_domain
section total
variables (α) {α' : Type*} (M) {M' : Type*} (R)
[add_comm_monoid M'] [module R M']
(v : α → M) {v' : α' → M'}
/-- Interprets (l : α →₀ R) as linear combination of the elements in the family (v : α → M) and
evaluates this linear combination. -/
protected def total : (α →₀ R) →ₗ[R] M := finsupp.lsum ℕ (λ i, linear_map.id.smul_right (v i))
variables {α M v}
theorem total_apply (l : α →₀ R) :
finsupp.total α M R v l = l.sum (λ i a, a • v i) := rfl
theorem total_apply_of_mem_supported {l : α →₀ R} {s : finset α}
(hs : l ∈ supported R R (↑s : set α)) :
finsupp.total α M R v l = s.sum (λ i, l i • v i) :=
finset.sum_subset hs $ λ x _ hxg, show l x • v x = 0, by rw [not_mem_support_iff.1 hxg, zero_smul]
@[simp] theorem total_single (c : R) (a : α) :
finsupp.total α M R v (single a c) = c • (v a) :=
by simp [total_apply, sum_single_index]
theorem apply_total (f : M →ₗ[R] M') (v) (l : α →₀ R) :
f (finsupp.total α M R v l) = finsupp.total α M' R (f ∘ v) l :=
by apply finsupp.induction_linear l; simp { contextual := tt, }
theorem total_unique [unique α] (l : α →₀ R) (v) :
finsupp.total α M R v l = l default • v default :=
by rw [← total_single, ← unique_single l]
lemma total_surjective (h : function.surjective v) : function.surjective (finsupp.total α M R v) :=
begin
intro x,
obtain ⟨y, hy⟩ := h x,
exact ⟨finsupp.single y 1, by simp [hy]⟩
end
theorem total_range (h : function.surjective v) : (finsupp.total α M R v).range = ⊤ :=
range_eq_top.2 $ total_surjective R h
/-- Any module is a quotient of a free module. This is stated as surjectivity of
`finsupp.total M M R id : (M →₀ R) →ₗ[R] M`. -/
lemma total_id_surjective (M) [add_comm_monoid M] [module R M] :
function.surjective (finsupp.total M M R id) :=
total_surjective R function.surjective_id
lemma range_total : (finsupp.total α M R v).range = span R (range v) :=
begin
ext x,
split,
{ intros hx,
rw [linear_map.mem_range] at hx,
rcases hx with ⟨l, hl⟩,
rw ← hl,
rw finsupp.total_apply,
exact sum_mem (λ i hi, submodule.smul_mem _ _ (subset_span (mem_range_self i))) },
{ apply span_le.2,
intros x hx,
rcases hx with ⟨i, hi⟩,
rw [set_like.mem_coe, linear_map.mem_range],
use finsupp.single i 1,
simp [hi] }
end
theorem lmap_domain_total (f : α → α') (g : M →ₗ[R] M') (h : ∀ i, g (v i) = v' (f i)) :
(finsupp.total α' M' R v').comp (lmap_domain R R f) = g.comp (finsupp.total α M R v) :=
by ext l; simp [total_apply, finsupp.sum_map_domain_index, add_smul, h]
@[simp] theorem total_emb_domain (f : α ↪ α') (l : α →₀ R) :
(finsupp.total α' M' R v') (emb_domain f l) = (finsupp.total α M' R (v' ∘ f)) l :=
by simp [total_apply, finsupp.sum, support_emb_domain, emb_domain_apply]
theorem total_map_domain (f : α → α') (hf : function.injective f) (l : α →₀ R) :
(finsupp.total α' M' R v') (map_domain f l) = (finsupp.total α M' R (v' ∘ f)) l :=
begin
have : map_domain f l = emb_domain ⟨f, hf⟩ l,
{ rw emb_domain_eq_map_domain ⟨f, hf⟩,
refl },
rw this,
apply total_emb_domain R ⟨f, hf⟩ l
end
@[simp] theorem total_equiv_map_domain (f : α ≃ α') (l : α →₀ R) :
(finsupp.total α' M' R v') (equiv_map_domain f l) = (finsupp.total α M' R (v' ∘ f)) l :=
by rw [equiv_map_domain_eq_map_domain, total_map_domain _ _ f.injective]
/-- A version of `finsupp.range_total` which is useful for going in the other direction -/
theorem span_eq_range_total (s : set M) :
span R s = (finsupp.total s M R coe).range :=
by rw [range_total, subtype.range_coe_subtype, set.set_of_mem_eq]
theorem mem_span_iff_total (s : set M) (x : M) :
x ∈ span R s ↔ ∃ l : s →₀ R, finsupp.total s M R coe l = x :=
(set_like.ext_iff.1 $ span_eq_range_total _ _) x
theorem span_image_eq_map_total (s : set α):
span R (v '' s) = submodule.map (finsupp.total α M R v) (supported R R s) :=
begin
apply span_eq_of_le,
{ intros x hx,
rw set.mem_image at hx,
apply exists.elim hx,
intros i hi,
exact ⟨_, finsupp.single_mem_supported R 1 hi.1, by simp [hi.2]⟩ },
{ refine map_le_iff_le_comap.2 (λ z hz, _),
have : ∀i, z i • v i ∈ span R (v '' s),
{ intro c,
haveI := classical.dec_pred (λ x, x ∈ s),
by_cases c ∈ s,
{ exact smul_mem _ _ (subset_span (set.mem_image_of_mem _ h)) },
{ simp [(finsupp.mem_supported' R _).1 hz _ h] } },
refine sum_mem _, simp [this] }
end
theorem mem_span_image_iff_total {s : set α} {x : M} :
x ∈ span R (v '' s) ↔ ∃ l ∈ supported R R s, finsupp.total α M R v l = x :=
by { rw span_image_eq_map_total, simp, }
lemma total_option (v : option α → M) (f : option α →₀ R) :
finsupp.total (option α) M R v f =
f none • v none + finsupp.total α M R (v ∘ option.some) f.some :=
by rw [total_apply, sum_option_index_smul, total_apply]
lemma total_total {α β : Type*} (A : α → M) (B : β → (α →₀ R)) (f : β →₀ R) :
finsupp.total α M R A (finsupp.total β (α →₀ R) R B f) =
finsupp.total β M R (λ b, finsupp.total α M R A (B b)) f :=
begin
simp only [total_apply],
apply induction_linear f,
{ simp only [sum_zero_index], },
{ intros f₁ f₂ h₁ h₂,
simp [sum_add_index, h₁, h₂, add_smul], },
{ simp [sum_single_index, sum_smul_index, smul_sum, mul_smul], }
end
@[simp] lemma total_fin_zero (f : fin 0 → M) :
finsupp.total (fin 0) M R f = 0 :=
by { ext i, apply fin_zero_elim i }
variables (α) (M) (v)
/-- `finsupp.total_on M v s` interprets `p : α →₀ R` as a linear combination of a
subset of the vectors in `v`, mapping it to the span of those vectors.
The subset is indicated by a set `s : set α` of indices.
-/
protected def total_on (s : set α) : supported R R s →ₗ[R] span R (v '' s) :=
linear_map.cod_restrict _ ((finsupp.total _ _ _ v).comp (submodule.subtype (supported R R s))) $
λ ⟨l, hl⟩, (mem_span_image_iff_total _).2 ⟨l, hl, rfl⟩
variables {α} {M} {v}
theorem total_on_range (s : set α) : (finsupp.total_on α M R v s).range = ⊤ :=
begin
rw [finsupp.total_on, linear_map.range_eq_map, linear_map.map_cod_restrict,
← linear_map.range_le_iff_comap, range_subtype, map_top, linear_map.range_comp, range_subtype],
exact (span_image_eq_map_total _ _).le
end
theorem total_comp (f : α' → α) :
(finsupp.total α' M R (v ∘ f)) = (finsupp.total α M R v).comp (lmap_domain R R f) :=
by { ext, simp [total_apply] }
lemma total_comap_domain
(f : α → α') (l : α' →₀ R) (hf : set.inj_on f (f ⁻¹' ↑l.support)) :
finsupp.total α M R v (finsupp.comap_domain f l hf) =
(l.support.preimage f hf).sum (λ i, (l (f i)) • (v i)) :=
by rw finsupp.total_apply; refl
lemma total_on_finset
{s : finset α} {f : α → R} (g : α → M) (hf : ∀ a, f a ≠ 0 → a ∈ s):
finsupp.total α M R g (finsupp.on_finset s f hf) =
finset.sum s (λ (x : α), f x • g x) :=
begin
simp only [finsupp.total_apply, finsupp.sum, finsupp.on_finset_apply, finsupp.support_on_finset],
rw finset.sum_filter_of_ne,
intros x hx h,
contrapose! h,
simp [h],
end
end total
/-- An equivalence of domains induces a linear equivalence of finitely supported functions.
This is `finsupp.dom_congr` as a `linear_equiv`.
See also `linear_map.fun_congr_left` for the case of arbitrary functions. -/
protected def dom_lcongr {α₁ α₂ : Type*} (e : α₁ ≃ α₂) :
(α₁ →₀ M) ≃ₗ[R] (α₂ →₀ M) :=
(finsupp.dom_congr e : (α₁ →₀ M) ≃+ (α₂ →₀ M)).to_linear_equiv $
by simpa only [equiv_map_domain_eq_map_domain, dom_congr_apply]
using (lmap_domain M R e).map_smul
@[simp]
lemma dom_lcongr_apply {α₁ : Type*} {α₂ : Type*} (e : α₁ ≃ α₂) (v : α₁ →₀ M) :
(finsupp.dom_lcongr e : _ ≃ₗ[R] _) v = finsupp.dom_congr e v :=
rfl
@[simp]
lemma dom_lcongr_refl : finsupp.dom_lcongr (equiv.refl α) = linear_equiv.refl R (α →₀ M) :=
linear_equiv.ext $ λ _, equiv_map_domain_refl _
lemma dom_lcongr_trans {α₁ α₂ α₃ : Type*} (f : α₁ ≃ α₂) (f₂ : α₂ ≃ α₃) :
(finsupp.dom_lcongr f).trans (finsupp.dom_lcongr f₂) =
(finsupp.dom_lcongr (f.trans f₂) : (_ →₀ M) ≃ₗ[R] _) :=
linear_equiv.ext $ λ _, (equiv_map_domain_trans _ _ _).symm
@[simp]
lemma dom_lcongr_symm {α₁ α₂ : Type*} (f : α₁ ≃ α₂) :
((finsupp.dom_lcongr f).symm : (_ →₀ M) ≃ₗ[R] _) = finsupp.dom_lcongr f.symm :=
linear_equiv.ext $ λ x, rfl
@[simp] theorem dom_lcongr_single {α₁ : Type*} {α₂ : Type*} (e : α₁ ≃ α₂) (i : α₁) (m : M) :
(finsupp.dom_lcongr e : _ ≃ₗ[R] _) (finsupp.single i m) = finsupp.single (e i) m :=
by simp [finsupp.dom_lcongr, finsupp.dom_congr, equiv_map_domain_single]
/-- An equivalence of sets induces a linear equivalence of `finsupp`s supported on those sets. -/
noncomputable def congr {α' : Type*} (s : set α) (t : set α') (e : s ≃ t) :
supported M R s ≃ₗ[R] supported M R t :=
begin
haveI := classical.dec_pred (λ x, x ∈ s),
haveI := classical.dec_pred (λ x, x ∈ t),
refine (finsupp.supported_equiv_finsupp s) ≪≫ₗ
(_ ≪≫ₗ (finsupp.supported_equiv_finsupp t).symm),
exact finsupp.dom_lcongr e
end
/-- `finsupp.map_range` as a `linear_map`. -/
@[simps]
def map_range.linear_map (f : M →ₗ[R] N) : (α →₀ M) →ₗ[R] (α →₀ N) :=
{ to_fun := (map_range f f.map_zero : (α →₀ M) → (α →₀ N)),
map_smul' := λ c v, map_range_smul c v (f.map_smul c),
..map_range.add_monoid_hom f.to_add_monoid_hom }
@[simp]
lemma map_range.linear_map_id :
map_range.linear_map linear_map.id = (linear_map.id : (α →₀ M) →ₗ[R] _):=
linear_map.ext map_range_id
lemma map_range.linear_map_comp (f : N →ₗ[R] P) (f₂ : M →ₗ[R] N) :
(map_range.linear_map (f.comp f₂) : (α →₀ _) →ₗ[R] _) =
(map_range.linear_map f).comp (map_range.linear_map f₂) :=
linear_map.ext $ map_range_comp _ _ _ _ _
@[simp]
lemma map_range.linear_map_to_add_monoid_hom (f : M →ₗ[R] N) :
(map_range.linear_map f).to_add_monoid_hom =
(map_range.add_monoid_hom f.to_add_monoid_hom : (α →₀ M) →+ _):=
add_monoid_hom.ext $ λ _, rfl
/-- `finsupp.map_range` as a `linear_equiv`. -/
@[simps apply]
def map_range.linear_equiv (e : M ≃ₗ[R] N) : (α →₀ M) ≃ₗ[R] (α →₀ N) :=
{ to_fun := map_range e e.map_zero,
inv_fun := map_range e.symm e.symm.map_zero,
..map_range.linear_map e.to_linear_map,
..map_range.add_equiv e.to_add_equiv}
@[simp]
lemma map_range.linear_equiv_refl :
map_range.linear_equiv (linear_equiv.refl R M) = linear_equiv.refl R (α →₀ M) :=
linear_equiv.ext map_range_id
lemma map_range.linear_equiv_trans (f : M ≃ₗ[R] N) (f₂ : N ≃ₗ[R] P) :
(map_range.linear_equiv (f.trans f₂) : (α →₀ _) ≃ₗ[R] _) =
(map_range.linear_equiv f).trans (map_range.linear_equiv f₂) :=
linear_equiv.ext $ map_range_comp _ _ _ _ _
@[simp]
lemma map_range.linear_equiv_symm (f : M ≃ₗ[R] N) :
((map_range.linear_equiv f).symm : (α →₀ _) ≃ₗ[R] _) = map_range.linear_equiv f.symm :=
linear_equiv.ext $ λ x, rfl
@[simp]
lemma map_range.linear_equiv_to_add_equiv (f : M ≃ₗ[R] N) :
(map_range.linear_equiv f).to_add_equiv =
(map_range.add_equiv f.to_add_equiv : (α →₀ M) ≃+ _):=
add_equiv.ext $ λ _, rfl
@[simp]
lemma map_range.linear_equiv_to_linear_map (f : M ≃ₗ[R] N) :
(map_range.linear_equiv f).to_linear_map =
(map_range.linear_map f.to_linear_map : (α →₀ M) →ₗ[R] _):=
linear_map.ext $ λ _, rfl
/-- An equivalence of domain and a linear equivalence of codomain induce a linear equivalence of the
corresponding finitely supported functions. -/
def lcongr {ι κ : Sort*} (e₁ : ι ≃ κ) (e₂ : M ≃ₗ[R] N) : (ι →₀ M) ≃ₗ[R] (κ →₀ N) :=
(finsupp.dom_lcongr e₁).trans (map_range.linear_equiv e₂)
@[simp] theorem lcongr_single {ι κ : Sort*} (e₁ : ι ≃ κ) (e₂ : M ≃ₗ[R] N) (i : ι) (m : M) :
lcongr e₁ e₂ (finsupp.single i m) = finsupp.single (e₁ i) (e₂ m) :=
by simp [lcongr]
@[simp] lemma lcongr_apply_apply {ι κ : Sort*} (e₁ : ι ≃ κ) (e₂ : M ≃ₗ[R] N) (f : ι →₀ M) (k : κ) :
lcongr e₁ e₂ f k = e₂ (f (e₁.symm k)) :=
rfl
theorem lcongr_symm_single {ι κ : Sort*} (e₁ : ι ≃ κ) (e₂ : M ≃ₗ[R] N) (k : κ) (n : N) :
(lcongr e₁ e₂).symm (finsupp.single k n) = finsupp.single (e₁.symm k) (e₂.symm n) :=
begin
apply_fun lcongr e₁ e₂ using (lcongr e₁ e₂).injective,
simp,
end
@[simp] lemma lcongr_symm {ι κ : Sort*} (e₁ : ι ≃ κ) (e₂ : M ≃ₗ[R] N) :
(lcongr e₁ e₂).symm = lcongr e₁.symm e₂.symm :=
begin
ext f i,
simp only [equiv.symm_symm, finsupp.lcongr_apply_apply],
apply finsupp.induction_linear f,
{ simp, },
{ intros f g hf hg, simp [map_add, hf, hg], },
{ intros k m,
simp only [finsupp.lcongr_symm_single],
simp only [finsupp.single, equiv.symm_apply_eq, finsupp.coe_mk],
split_ifs; simp, },
end
section sum
variables (R)
/-- The linear equivalence between `(α ⊕ β) →₀ M` and `(α →₀ M) × (β →₀ M)`.
This is the `linear_equiv` version of `finsupp.sum_finsupp_equiv_prod_finsupp`. -/
@[simps apply symm_apply] def sum_finsupp_lequiv_prod_finsupp {α β : Type*} :
((α ⊕ β) →₀ M) ≃ₗ[R] (α →₀ M) × (β →₀ M) :=
{ map_smul' :=
by { intros, ext;
simp only [add_equiv.to_fun_eq_coe, prod.smul_fst, prod.smul_snd, smul_apply,
snd_sum_finsupp_add_equiv_prod_finsupp, fst_sum_finsupp_add_equiv_prod_finsupp,
ring_hom.id_apply] },
.. sum_finsupp_add_equiv_prod_finsupp }
lemma fst_sum_finsupp_lequiv_prod_finsupp {α β : Type*}
(f : (α ⊕ β) →₀ M) (x : α) :
(sum_finsupp_lequiv_prod_finsupp R f).1 x = f (sum.inl x) :=
rfl
lemma snd_sum_finsupp_lequiv_prod_finsupp {α β : Type*}
(f : (α ⊕ β) →₀ M) (y : β) :
(sum_finsupp_lequiv_prod_finsupp R f).2 y = f (sum.inr y) :=
rfl
lemma sum_finsupp_lequiv_prod_finsupp_symm_inl {α β : Type*}
(fg : (α →₀ M) × (β →₀ M)) (x : α) :
((sum_finsupp_lequiv_prod_finsupp R).symm fg) (sum.inl x) = fg.1 x :=
rfl
lemma sum_finsupp_lequiv_prod_finsupp_symm_inr {α β : Type*}
(fg : (α →₀ M) × (β →₀ M)) (y : β) :
((sum_finsupp_lequiv_prod_finsupp R).symm fg) (sum.inr y) = fg.2 y :=
rfl
end sum
section sigma
variables {η : Type*} [fintype η] {ιs : η → Type*} [has_zero α]
variables (R)
/-- On a `fintype η`, `finsupp.split` is a linear equivalence between
`(Σ (j : η), ιs j) →₀ M` and `Π j, (ιs j →₀ M)`.
This is the `linear_equiv` version of `finsupp.sigma_finsupp_add_equiv_pi_finsupp`. -/
noncomputable def sigma_finsupp_lequiv_pi_finsupp
{M : Type*} {ιs : η → Type*} [add_comm_monoid M] [module R M] :
((Σ j, ιs j) →₀ M) ≃ₗ[R] Π j, (ιs j →₀ M) :=
{ map_smul' := λ c f, by { ext, simp },
.. sigma_finsupp_add_equiv_pi_finsupp }
@[simp] lemma sigma_finsupp_lequiv_pi_finsupp_apply
{M : Type*} {ιs : η → Type*} [add_comm_monoid M] [module R M]
(f : (Σ j, ιs j) →₀ M) (j i) :
sigma_finsupp_lequiv_pi_finsupp R f j i = f ⟨j, i⟩ := rfl
@[simp] lemma sigma_finsupp_lequiv_pi_finsupp_symm_apply
{M : Type*} {ιs : η → Type*} [add_comm_monoid M] [module R M]
(f : Π j, (ιs j →₀ M)) (ji) :
(finsupp.sigma_finsupp_lequiv_pi_finsupp R).symm f ji = f ji.1 ji.2 := rfl
end sigma
section prod
/-- The linear equivalence between `α × β →₀ M` and `α →₀ β →₀ M`.
This is the `linear_equiv` version of `finsupp.finsupp_prod_equiv`. -/
noncomputable def finsupp_prod_lequiv {α β : Type*} (R : Type*) {M : Type*}
[semiring R] [add_comm_monoid M] [module R M] :
(α × β →₀ M) ≃ₗ[R] (α →₀ β →₀ M) :=
{ map_add' := λ f g, by { ext, simp [finsupp_prod_equiv, curry_apply] },
map_smul' := λ c f, by { ext, simp [finsupp_prod_equiv, curry_apply] },
.. finsupp_prod_equiv }
@[simp] lemma finsupp_prod_lequiv_apply {α β R M : Type*}
[semiring R] [add_comm_monoid M] [module R M] (f : α × β →₀ M) (x y) :
finsupp_prod_lequiv R f x y = f (x, y) :=
by rw [finsupp_prod_lequiv, linear_equiv.coe_mk, finsupp_prod_equiv, finsupp.curry_apply]
@[simp] lemma finsupp_prod_lequiv_symm_apply {α β R M : Type*}
[semiring R] [add_comm_monoid M] [module R M] (f : α →₀ β →₀ M) (xy) :
(finsupp_prod_lequiv R).symm f xy = f xy.1 xy.2 :=
by conv_rhs
{ rw [← (finsupp_prod_lequiv R).apply_symm_apply f, finsupp_prod_lequiv_apply, prod.mk.eta] }
end prod
end finsupp
variables {R : Type*} {M : Type*} {N : Type*}
variables [semiring R] [add_comm_monoid M] [module R M] [add_comm_monoid N] [module R N]
section
variables (R)
/--
Pick some representation of `x : span R w` as a linear combination in `w`,
using the axiom of choice.
-/
def span.repr (w : set M) (x : span R w) : w →₀ R :=
((finsupp.mem_span_iff_total _ _ _).mp x.2).some
@[simp] lemma span.finsupp_total_repr {w : set M} (x : span R w) :
finsupp.total w M R coe (span.repr R w x) = x :=
((finsupp.mem_span_iff_total _ _ _).mp x.2).some_spec
attribute [irreducible] span.repr
end
protected lemma submodule.finsupp_sum_mem {ι β : Type*} [has_zero β] (S : submodule R M)
(f : ι →₀ β) (g : ι → β → M) (h : ∀ c, f c ≠ 0 → g c (f c) ∈ S) : f.sum g ∈ S :=
add_submonoid_class.finsupp_sum_mem S f g h
lemma linear_map.map_finsupp_total
(f : M →ₗ[R] N) {ι : Type*} {g : ι → M} (l : ι →₀ R) :
f (finsupp.total ι M R g l) = finsupp.total ι N R (f ∘ g) l :=
by simp only [finsupp.total_apply, finsupp.total_apply, finsupp.sum, f.map_sum, f.map_smul]
lemma submodule.exists_finset_of_mem_supr
{ι : Sort*} (p : ι → submodule R M) {m : M} (hm : m ∈ ⨆ i, p i) :
∃ s : finset ι, m ∈ ⨆ i ∈ s, p i :=
begin
have := complete_lattice.is_compact_element.exists_finset_of_le_supr (submodule R M)
(submodule.singleton_span_is_compact_element m) p,
simp only [submodule.span_singleton_le_iff_mem] at this,
exact this hm,
end
/-- `submodule.exists_finset_of_mem_supr` as an `iff` -/
lemma submodule.mem_supr_iff_exists_finset
{ι : Sort*} {p : ι → submodule R M} {m : M} :
(m ∈ ⨆ i, p i) ↔ ∃ s : finset ι, m ∈ ⨆ i ∈ s, p i :=
⟨submodule.exists_finset_of_mem_supr p,
λ ⟨_, hs⟩, supr_mono (λ i, (supr_const_le : _ ≤ p i)) hs⟩
lemma mem_span_finset {s : finset M} {x : M} :
x ∈ span R (↑s : set M) ↔ ∃ f : M → R, ∑ i in s, f i • i = x :=
⟨λ hx, let ⟨v, hvs, hvx⟩ := (finsupp.mem_span_image_iff_total _).1
(show x ∈ span R (id '' (↑s : set M)), by rwa set.image_id) in
⟨v, hvx ▸ (finsupp.total_apply_of_mem_supported _ hvs).symm⟩,
λ ⟨f, hf⟩, hf ▸ sum_mem (λ i hi, smul_mem _ _ $ subset_span hi)⟩
/-- An element `m ∈ M` is contained in the `R`-submodule spanned by a set `s ⊆ M`, if and only if
`m` can be written as a finite `R`-linear combination of elements of `s`.
The implementation uses `finsupp.sum`. -/
lemma mem_span_set {m : M} {s : set M} :
m ∈ submodule.span R s ↔ ∃ c : M →₀ R, (c.support : set M) ⊆ s ∧ c.sum (λ mi r, r • mi) = m :=
begin
conv_lhs { rw ←set.image_id s },
simp_rw ←exists_prop,
exact finsupp.mem_span_image_iff_total R,
end
/-- If `subsingleton R`, then `M ≃ₗ[R] ι →₀ R` for any type `ι`. -/
@[simps]
def module.subsingleton_equiv (R M ι: Type*) [semiring R] [subsingleton R] [add_comm_monoid M]
[module R M] : M ≃ₗ[R] ι →₀ R :=
{ to_fun := λ m, 0,
inv_fun := λ f, 0,
left_inv := λ m, by { letI := module.subsingleton R M, simp only [eq_iff_true_of_subsingleton] },
right_inv := λ f, by simp only [eq_iff_true_of_subsingleton],
map_add' := λ m n, (add_zero 0).symm,
map_smul' := λ r m, (smul_zero r).symm }
namespace linear_map
variables {R M} {α : Type*}
open finsupp function
/-- A surjective linear map to finitely supported functions has a splitting. -/
-- See also `linear_map.splitting_of_fun_on_fintype_surjective`
def splitting_of_finsupp_surjective (f : M →ₗ[R] (α →₀ R)) (s : surjective f) : (α →₀ R) →ₗ[R] M :=
finsupp.lift _ _ _ (λ x : α, (s (finsupp.single x 1)).some)
lemma splitting_of_finsupp_surjective_splits (f : M →ₗ[R] (α →₀ R)) (s : surjective f) :
f.comp (splitting_of_finsupp_surjective f s) = linear_map.id :=
begin
ext x y,
dsimp [splitting_of_finsupp_surjective],
congr,
rw [sum_single_index, one_smul],
{ exact (s (finsupp.single x 1)).some_spec, },
{ rw zero_smul, },
end
lemma left_inverse_splitting_of_finsupp_surjective (f : M →ₗ[R] (α →₀ R)) (s : surjective f) :
left_inverse f (splitting_of_finsupp_surjective f s) :=
λ g, linear_map.congr_fun (splitting_of_finsupp_surjective_splits f s) g
lemma splitting_of_finsupp_surjective_injective (f : M →ₗ[R] (α →₀ R)) (s : surjective f) :
injective (splitting_of_finsupp_surjective f s) :=
(left_inverse_splitting_of_finsupp_surjective f s).injective
/-- A surjective linear map to functions on a finite type has a splitting. -/
-- See also `linear_map.splitting_of_finsupp_surjective`
def splitting_of_fun_on_fintype_surjective [fintype α] (f : M →ₗ[R] (α → R)) (s : surjective f) :
(α → R) →ₗ[R] M :=
(finsupp.lift _ _ _ (λ x : α, (s (finsupp.single x 1)).some)).comp
(linear_equiv_fun_on_fintype R R α).symm.to_linear_map
lemma splitting_of_fun_on_fintype_surjective_splits
[fintype α] (f : M →ₗ[R] (α → R)) (s : surjective f) :
f.comp (splitting_of_fun_on_fintype_surjective f s) = linear_map.id :=
begin
ext x y,
dsimp [splitting_of_fun_on_fintype_surjective],
rw [linear_equiv_fun_on_fintype_symm_single, finsupp.sum_single_index, one_smul,
(s (finsupp.single x 1)).some_spec, finsupp.single_eq_pi_single],
rw [zero_smul],
end
lemma left_inverse_splitting_of_fun_on_fintype_surjective
[fintype α] (f : M →ₗ[R] (α → R)) (s : surjective f) :
left_inverse f (splitting_of_fun_on_fintype_surjective f s) :=
λ g, linear_map.congr_fun (splitting_of_fun_on_fintype_surjective_splits f s) g
lemma splitting_of_fun_on_fintype_surjective_injective
[fintype α] (f : M →ₗ[R] (α → R)) (s : surjective f) :
injective (splitting_of_fun_on_fintype_surjective f s) :=
(left_inverse_splitting_of_fun_on_fintype_surjective f s).injective
end linear_map
|
493ad887d8370dd1ad945f2d65de9ff8fb5e60cd | 95dcf8dea2baf2b4b0a60d438f27c35ae3dd3990 | /src/category/fold.lean | f101336c154a09021b26c62a6faee27bf7fc076b | [
"Apache-2.0"
] | permissive | uniformity1/mathlib | 829341bad9dfa6d6be9adaacb8086a8a492e85a4 | dd0e9bd8f2e5ec267f68e72336f6973311909105 | refs/heads/master | 1,588,592,015,670 | 1,554,219,842,000 | 1,554,219,842,000 | 179,110,702 | 0 | 0 | Apache-2.0 | 1,554,220,076,000 | 1,554,220,076,000 | null | UTF-8 | Lean | false | false | 14,609 | lean | /-
Copyright (c) 2018 Simon Hudon. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Simon Hudon, Sean Leather
List folds generalized to `traversable`. Informally, we can think of
`foldl` as a special case of `traverse` where we do not care about the
reconstructed data structure and, in a state monad, we care about the
final state.
The obvious way to define `foldl` would be to use the state monad but it
is nicer to reason about a more abstract interface with `fold_map` as a
primitive and `fold_map_hom` as a defining property.
def fold_map {α ω} [has_one ω] [has_mul ω] (f : α → ω) : t α → ω := ...
lemma fold_map_hom (α β)
[monoid α] [monoid β] (f : α → β) [is_monoid_hom f]
(g : γ → α) (x : t γ) :
f (fold_map g x) = fold_map (f ∘ g) x :=
...
`fold_map` uses a monoid ω to accumulate a value for every element of
a data structure and `fold_map_hom` uses a monoid homomorphism to
substitute the monoid used by `fold_map`. The two are sufficient to
define `foldl`, `foldr` and `to_list`. `to_list` permits the
formulation of specifications in terms of operations on lists.
Each fold function can be defined using a specialized
monoid. `to_list` uses a free monoid represented as a list with
concatenation while `foldl` uses endofunctions together with function
composition.
The definition through monoids uses `traverse` together with the
applicative functor `const m` (where `m` is the monoid). As an
implementation, `const` guarantees that no resource is spent on
reconstructing the structure during traversal.
A special class could be defined for `foldable`, similarly to Haskell,
but the author cannot think of instances of `foldable` that are not also
`traversable`.
-/
import tactic.squeeze
import algebra.group
import data.list.basic
import category.traversable.instances category.traversable.lemmas
import category_theory.category category_theory.types category_theory.opposites category_theory.instances.kleisli
import category.applicative
universes u v
open ulift category_theory
namespace monoid
variables {m : Type u → Type u} [monad m]
variables {α β : Type u}
/--
For a list, foldl f x [y₀,y₁] reduces as follows
calc foldl f x [y₀,y₁]
= foldl f (f x y₀) [y₁] : rfl
... = foldl f (f (f x y₀) y₁) [] : rfl
... = f (f x y₀) y₁ : rfl
with f : α → β → α
x : α
[y₀,y₁] : list β
We can view the above as a composition of functions:
... = f (f x y₀) y₁ : rfl
... = flip f y₁ (flip f y₀ x) : rfl
... = (flip f y₁ ∘ flip f y₀) x : rfl
We can use traverse and const to construct this composition:
calc const.run (traverse (λ y, const.mk' (flip f y)) [y₀,y₁]) x
= const.run ((::) <$> const.mk' (flip f y₀) <*> traverse (λ y, const.mk' (flip f y)) [y₁]) x
... = const.run ((::) <$> const.mk' (flip f y₀) <*> ( (::) <$> const.mk' (flip f y₁) <*> traverse (λ y, const.mk' (flip f y)) [] )) x
... = const.run ((::) <$> const.mk' (flip f y₀) <*> ( (::) <$> const.mk' (flip f y₁) <*> pure [] )) x
... = const.run ( ((::) <$> const.mk' (flip f y₁) <*> pure []) ∘ ((::) <$> const.mk' (flip f y₀)) ) x
... = const.run ( const.mk' (flip f y₁) ∘ const.mk' (flip f y₀) ) x
... = const.run ( flip f y₁ ∘ flip f y₀ ) x
... = f (f x y₀) y₁
And this is how `const` turns a monoid into an applicative functor and
how the monoid of endofunctions define `foldl`.
-/
@[reducible] def foldl (α : Type u) : Type u := End α
def foldl.mk (f : α → α) : foldl α := f
def foldl.of_free_monoid (f : β → α → β) (xs : free_monoid α) : monoid.foldl β :=
flip (list.foldl f) xs
@[reducible] def foldr (α : Type u) : Type u := (End α)ᵒᵖ
def foldr.mk (f : α → α) : foldr α := op f
def foldr.get (x : foldr α) : α → α := unop x
def foldr.of_free_monoid (f : α → β → β) (xs : free_monoid α) : monoid.foldr β :=
op $ flip (list.foldr f) xs
@[reducible] def mfoldl (m : Type u → Type u) [monad m] (α : Type u) : Type u := End $ Kleisli.mk m α
def mfoldl.mk (f : α → m α) : mfoldl m α := f
def mfoldl.of_free_monoid (f : β → α → m β) (xs : free_monoid α) : monoid.mfoldl m β :=
flip (list.mfoldl f) xs
@[reducible] def mfoldr (m : Type u → Type u) [monad m] (α : Type u) : Type u := (End $ Kleisli.mk m α)ᵒᵖ
def mfoldr.mk (f : α → m α) : mfoldr m α := op f
def mfoldr.get (x : mfoldr m α) : α → m α := unop x
def mfoldr.of_free_monoid (f : α → β → m β) (xs : free_monoid α) : monoid.mfoldr m β :=
op $ flip (list.mfoldr f) xs
end monoid
namespace traversable
open monoid functor
section defs
variables {α β : Type u} {t : Type u → Type u} [traversable t]
def fold_map {α ω} [has_one ω] [has_mul ω] (f : α → ω) : t α → ω :=
traverse (const.mk' ∘ f)
def foldl (f : α → β → α) (x : α) (xs : t β) : α :=
fold_map (foldl.mk ∘ flip f) xs x
def foldr (f : α → β → β) (x : β) (xs : t α) : β :=
unop (fold_map (foldr.mk ∘ f) xs) x
/--
Conceptually, `to_list` collects all the elements of a collection
in a list. This idea is formalized by
`lemma to_list_spec (x : t α) : to_list x = fold_map free_monoid.mk x`.
The definition of `to_list` is based on `foldl` and `list.cons` for
speed. It is faster than using `fold_map free_monoid.mk` because, by
using `foldl` and `list.cons`, each insertion is done in constant
time. As a consequence, `to_list` performs in linear.
On the other hand, `fold_map free_monoid.mk` creates a singleton list
around each element and concatenates all the resulting lists. In
`xs ++ ys`, concatenation takes a time proportional to `length xs`. Since
the order in which concatenation is evaluated is unspecified, nothing
prevents each element of the traversable to be appended at the end
`xs ++ [x]` which would yield a `O(n²)` run time. -/
def to_list : t α → list α :=
list.reverse ∘ foldl (flip list.cons) []
def length (xs : t α) : ℕ :=
down $ foldl (λ l _, up $ l.down + 1) (up 0) xs
variables {m : Type u → Type u} [monad m]
def mfoldl (f : α → β → m α) (x : α) (xs : t β) : m α :=
fold_map (mfoldl.mk ∘ flip f) xs x
def mfoldr (f : α → β → m β) (x : β) (xs : t α) : m β :=
unop (fold_map (mfoldr.mk ∘ f) xs) x
end defs
section applicative_transformation
variables {α β γ : Type u}
open function (hiding const) is_monoid_hom
def map_fold [monoid α] [monoid β] (f : α → β) [is_monoid_hom f] :
applicative_transformation (const α) (const β) :=
{ app := λ x, f,
preserves_seq' := by { intros, simp only [map_mul f], },
preserves_pure' := by { intros, simp only [map_one f] } }
def free.mk : α → free_monoid α := list.ret
def free.map (f : α → β) : free_monoid α → free_monoid β := list.map f
lemma free.map_eq_map (f : α → β) (xs : list α) :
f <$> xs = free.map f xs := rfl
instance (f : α → β) : is_monoid_hom (free.map f) :=
by constructor; simp only [free.map, list.map_append, forall_2_true_iff, free_add_monoid.add_def, list.map, free_add_monoid.zero_def, list.map, eq_self_iff_true]
instance fold_foldl (f : β → α → β) :
is_monoid_hom (foldl.of_free_monoid f) :=
{ map_one := rfl,
map_mul := by { intros, unfold_projs, simp only [foldl.of_free_monoid, flip, list.foldl_append], } }
lemma foldr.unop_of_free_monoid (f : α → β → β) (xs : free_monoid α) (a : β) :
unop (foldr.of_free_monoid f xs) a = list.foldr f a xs := rfl
instance fold_foldr (f : α → β → β) :
is_monoid_hom (foldr.of_free_monoid f) :=
{ map_one := rfl,
map_mul := by { intros, apply unop_inj, ext, simp only [foldr.of_free_monoid,flip,free_add_monoid.add_def, list.foldr_append], refl } }
variables (m : Type u → Type u) [monad m] [is_lawful_monad m]
instance fold_mfoldl (f : β → α → m β) :
is_monoid_hom (mfoldl.of_free_monoid f) :=
{ map_one := rfl,
map_mul := by { intros, unfold_projs, simp only [mfoldl.of_free_monoid,flip, list.mfoldl_append] } }
@[simp]
lemma mfoldr.unop_of_free_monoid (f : α → β → m β) (xs : free_monoid α) (a : β) :
unop (mfoldr.of_free_monoid f xs) a = list.mfoldr f a xs := rfl
instance fold_mfoldr (f : α → β → m β) :
is_monoid_hom (mfoldr.of_free_monoid f) :=
{ map_one := rfl,
map_mul := by { intros, apply unop_inj, ext, simp only [list.mfoldr_append, mfoldr.unop_of_free_monoid, free_add_monoid.add_def],
apply bind_ext_congr, simp only [mfoldr.unop_of_free_monoid, eq_self_iff_true, forall_true_iff], } }
variables {t : Type u → Type u} [traversable t] [is_lawful_traversable t]
open is_lawful_traversable
lemma fold_map_hom
[monoid α] [monoid β] (f : α → β) [is_monoid_hom f]
(g : γ → α) (x : t γ) :
f (fold_map g x) = fold_map (f ∘ g) x :=
calc f (fold_map g x)
= f (traverse (const.mk' ∘ g) x) : rfl
... = (map_fold f).app _ (traverse (const.mk' ∘ g) x) : rfl
... = traverse ((map_fold f).app _ ∘ (const.mk' ∘ g)) x : naturality (map_fold f) _ _
... = fold_map (f ∘ g) x : rfl
lemma fold_map_hom_free
[monoid β] (f : free_monoid α → β) [is_monoid_hom f] (x : t α) :
f (fold_map free.mk x) = fold_map (f ∘ free.mk) x :=
fold_map_hom _ _ x
variable {m}
lemma fold_mfoldl_cons (f : α → β → m α) (x : β) (y : α) :
list.mfoldl f y (free.mk x) = f y x :=
by simp only [free.mk, list.ret, list.mfoldl, bind_pure]
lemma fold_mfoldr_cons (f : β → α → m α) (x : β) (y : α) :
list.mfoldr f y (free.mk x) = f x y :=
by simp only [free.mk, list.ret, list.mfoldr, pure_bind]
end applicative_transformation
section equalities
open is_lawful_traversable list (cons)
variables {α β γ : Type u}
variables {t : Type u → Type u} [traversable t] [is_lawful_traversable t]
@[simp]
lemma foldl.of_free_monoid_comp_free_mk (f : α → β → α) : foldl.of_free_monoid f ∘ free.mk = foldl.mk ∘ flip f := rfl
@[simp]
lemma foldr.of_free_monoid_comp_free_mk (f : β → α → α) : foldr.of_free_monoid f ∘ free.mk = foldr.mk ∘ f := rfl
@[simp]
lemma mfoldl.of_free_monoid_comp_free_mk {m} [monad m] [is_lawful_monad m] (f : α → β → m α) : mfoldl.of_free_monoid f ∘ free.mk = mfoldl.mk ∘ flip f :=
by { ext, simp only [(∘), mfoldl.of_free_monoid, mfoldl.mk, flip, fold_mfoldl_cons] }
@[simp]
lemma mfoldr.of_free_monoid_comp_free_mk {m} [monad m] [is_lawful_monad m] (f : β → α → m α) : mfoldr.of_free_monoid f ∘ free.mk = mfoldr.mk ∘ f :=
by { ext, apply unop_inj, ext, simp only [(∘),mfoldr.of_free_monoid,mfoldr.mk,flip,fold_mfoldr_cons] }
lemma to_list_spec (xs : t α) :
to_list xs = (fold_map free.mk xs : free_monoid _) :=
eq.symm $
calc fold_map free.mk xs
= (fold_map free.mk xs).reverse.reverse : by simp only [list.reverse_reverse]
... = (list.foldr cons [] (fold_map free.mk xs).reverse).reverse
: by simp only [list.foldr_eta]
... = (foldl.of_free_monoid (flip cons) (fold_map free.mk xs) []).reverse
: by simp only [flip,list.foldr_reverse,foldl.of_free_monoid]
... = to_list xs : by { rw fold_map_hom_free (foldl.of_free_monoid (flip cons)),
simp only [to_list, foldl, list.reverse_inj, foldl.of_free_monoid_comp_free_mk],
all_goals { apply_instance } }
lemma fold_map_map [monoid γ] (f : α → β) (g : β → γ) (xs : t α) :
fold_map g (f <$> xs) = fold_map (g ∘ f) xs :=
by simp only [fold_map,traverse_map]
lemma foldl_to_list (f : α → β → α) (xs : t β) (x : α) :
foldl f x xs = list.foldl f x (to_list xs) :=
by { change _ = foldl.of_free_monoid _ _ _,
simp only [foldl, to_list_spec, fold_map_hom_free (foldl.of_free_monoid f), foldl.of_free_monoid_comp_free_mk] }
lemma foldr_to_list (f : α → β → β) (xs : t α) (x : β) :
foldr f x xs = list.foldr f x (to_list xs) :=
by { rw ← foldr.unop_of_free_monoid,
simp only [foldr, to_list_spec, fold_map_hom_free (foldr.of_free_monoid f), foldr.of_free_monoid_comp_free_mk] }
lemma to_list_map (f : α → β) (xs : t α) :
to_list (f <$> xs) = f <$> to_list xs :=
by simp only [to_list_spec,free.map_eq_map,fold_map_hom (free.map f), fold_map_map]; refl
@[simp] theorem foldl_map (g : β → γ) (f : α → γ → α) (a : α) (l : t β) :
foldl f a (g <$> l) = foldl (λ x y, f x (g y)) a l :=
by simp only [foldl, fold_map_map, (∘), flip]
@[simp] theorem foldr_map (g : β → γ) (f : γ → α → α) (a : α) (l : t β) :
foldr f a (g <$> l) = foldr (f ∘ g) a l :=
by simp only [foldr, fold_map_map, (∘), flip]
@[simp] theorem to_list_eq_self {xs : list α} : to_list xs = xs :=
begin
simp only [to_list_spec, fold_map, traverse],
induction xs,
case list.nil { refl },
case list.cons : _ _ ih { unfold list.traverse list.ret, rw ih, refl }
end
theorem length_to_list {xs : t α} : length xs = list.length (to_list xs) :=
begin
unfold length,
rw foldl_to_list,
generalize : to_list xs = ys,
let f := λ (n : ℕ) (a : α), n + 1,
transitivity list.foldl f 0 ys,
{ generalize : 0 = n,
induction ys with _ _ ih generalizing n,
{ simp only [list.foldl_nil] },
{ simp only [list.foldl, ih (n+1)] } },
{ induction ys with _ tl ih,
{ simp only [list.length, list.foldl_nil] },
{ simp only [list.foldl, list.length],
transitivity list.foldl f 0 tl + 1,
{ exact eq.symm (list.foldl_hom (+1) f f 0 (λ _ _, rfl) _) },
{ rw ih } } }
end
variables {m : Type u → Type u} [monad m] [is_lawful_monad m]
lemma mfoldl_to_list {f : α → β → m α} {x : α} {xs : t β} :
mfoldl f x xs = list.mfoldl f x (to_list xs) :=
by { change _ = mfoldl.of_free_monoid f (to_list xs) x,
simp only [mfoldl, to_list_spec, fold_map_hom_free (mfoldl.of_free_monoid f),mfoldl.of_free_monoid_comp_free_mk] }
lemma mfoldr_to_list (f : α → β → m β) (x : β) (xs : t α) :
mfoldr f x xs = list.mfoldr f x (to_list xs) :=
by { change _ = unop (mfoldr.of_free_monoid f (to_list xs)) x,
simp only [mfoldr, to_list_spec, fold_map_hom_free (mfoldr.of_free_monoid f),mfoldr.of_free_monoid_comp_free_mk] }
@[simp] theorem mfoldl_map (g : β → γ) (f : α → γ → m α) (a : α) (l : t β) :
mfoldl f a (g <$> l) = mfoldl (λ x y, f x (g y)) a l :=
by simp only [mfoldl, fold_map_map, (∘), flip]
@[simp] theorem mfoldr_map (g : β → γ) (f : γ → α → m α) (a : α) (l : t β) :
mfoldr f a (g <$> l) = mfoldr (f ∘ g) a l :=
by simp only [mfoldr, fold_map_map, (∘), flip]
end equalities
end traversable
|
6f804adff6606b5e66f94941dbdb05d76a66cb63 | 9be442d9ec2fcf442516ed6e9e1660aa9071b7bd | /tests/lean/run/Reparen.lean | 8e62ffb0dd593956f84731bd92a770238f43880b | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | EdAyers/lean4 | 57ac632d6b0789cb91fab2170e8c9e40441221bd | 37ba0df5841bde51dbc2329da81ac23d4f6a4de4 | refs/heads/master | 1,676,463,245,298 | 1,660,619,433,000 | 1,660,619,433,000 | 183,433,437 | 1 | 0 | Apache-2.0 | 1,657,612,672,000 | 1,556,196,574,000 | Lean | UTF-8 | Lean | false | false | 2,200 | lean | import Lean.Parser
/-! Reprint file after removing all parentheses and then passing it through the parenthesizer -/
open Lean
open Std.Format open Std
def unparenAux (parens body : Syntax) : Syntax :=
match parens.getHeadInfo, body.getHeadInfo, body.getTailInfo, parens.getTailInfo with
| SourceInfo.original lead _ _ _, SourceInfo.original _ pos trail pos',
SourceInfo.original endLead endPos _ endPos', SourceInfo.original _ _ endTrail _ =>
body.setHeadInfo (SourceInfo.original lead pos trail pos') |>.setTailInfo (SourceInfo.original endLead endPos endTrail endPos')
| _, _, _, _ => body
partial def unparen : Syntax → Syntax
-- don't remove parentheses in syntax quotations, they might be semantically significant
| stx => if stx.isOfKind `Lean.Parser.Term.stxQuot then stx
else match stx with
| `(($stx')) => unparenAux stx $ unparen stx'
| `(level|($stx')) => unparenAux stx $ unparen stx'
| _ => stx.modifyArgs $ Array.map unparen
unsafe def main (args : List String) : IO Unit := do
let (debug, f) : Bool × String := match args with
| [f, "-d"] => (true, f)
| [f] => (false, f)
| _ => panic! "usage: file [-d]";
let env ← mkEmptyEnvironment;
let stx ← Lean.Parser.testParseFile env args.head!;
let header := stx.raw.getArg 0;
let some s ← pure header.reprint | throw $ IO.userError "header reprint failed";
IO.print s;
let cmds := (stx.raw.getArg 1).getArgs;
cmds.forM $ fun cmd => do
let cmd := unparen cmd;
let (cmd, _) ← (tryFinally (PrettyPrinter.parenthesizeCommand cmd) printTraces).toIO { options := Options.empty.setBool `trace.PrettyPrinter.parenthesize debug, fileName := "", fileMap := default } { env := env };
let some s ← pure cmd.reprint | throw $ IO.userError "cmd reprint failed";
IO.print s
#eval main ["../../../src/Init/Prelude.lean"]
def check (stx : Syntax) : CoreM Unit := do
let stx' := unparen stx;
let stx' ← PrettyPrinter.parenthesizeTerm stx';
let f ← PrettyPrinter.formatTerm stx';
IO.println f;
if (stx != stx') then
throwError "reparenthesization failed"
open Lean
syntax:80 term " ^~ " term:80 : term
syntax:70 term " *~ " term:71 : term
#eval check $ Unhygienic.run `(((1 + 2) *~ 3) ^~ 4)
|
6518749cf5179b18ad9e4753fa465458678a03ec | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/match_convoy_infer_type_failure.lean | ffc6cb848ae3ced0fb8414b242b500e7474b3a01 | [
"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 | 120 | lean | constant p : nat → Type
constant q : p 1 → Prop
lemma ex : ∀ a : p 1, q a :=
match q, p with
| q, p := sorry
end
|
4159027e72d2e27f788dd2e6314fdae0b40c2409 | 367134ba5a65885e863bdc4507601606690974c1 | /src/algebra/ring/ulift.lean | a5bc2bc7a8cc2186d8fc681ac965335953c1d275 | [
"Apache-2.0"
] | permissive | kodyvajjha/mathlib | 9bead00e90f68269a313f45f5561766cfd8d5cad | b98af5dd79e13a38d84438b850a2e8858ec21284 | refs/heads/master | 1,624,350,366,310 | 1,615,563,062,000 | 1,615,563,062,000 | 162,666,963 | 0 | 0 | Apache-2.0 | 1,545,367,651,000 | 1,545,367,651,000 | null | UTF-8 | Lean | false | false | 1,900 | lean | /-
Copyright (c) 2020 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import algebra.group.ulift
import data.equiv.ring
/-!
# `ulift` instances for ring
This file defines instances for ring, semiring and related structures on `ulift` types.
(Recall `ulift α` is just a "copy" of a type `α` in a higher universe.)
We also provide `ulift.ring_equiv : ulift R ≃+* R`.
-/
universes u v
variables {α : Type u} {x y : ulift.{v} α}
namespace ulift
instance mul_zero_class [mul_zero_class α] : mul_zero_class (ulift α) :=
by refine_struct { zero := (0 : ulift α), mul := (*), .. }; tactic.pi_instance_derive_field
instance distrib [distrib α] : distrib (ulift α) :=
by refine_struct { add := (+), mul := (*), .. }; tactic.pi_instance_derive_field
instance semiring [semiring α] : semiring (ulift α) :=
by refine_struct { zero := (0 : ulift α), one := 1, add := (+), mul := (*), .. };
tactic.pi_instance_derive_field
/--
The ring equivalence between `ulift α` and `α`.
-/
def ring_equiv [semiring α] : ulift α ≃+* α :=
{ to_fun := ulift.down,
inv_fun := ulift.up,
map_mul' := λ x y, rfl,
map_add' := λ x y, rfl,
left_inv := by tidy,
right_inv := by tidy, }
instance comm_semiring [comm_semiring α] : comm_semiring (ulift α) :=
by refine_struct { zero := (0 : ulift α), one := 1, add := (+), mul := (*), .. };
tactic.pi_instance_derive_field
instance ring [ring α] : ring (ulift α) :=
by refine_struct { zero := (0 : ulift α), one := 1, add := (+), mul := (*), sub := has_sub.sub,
neg := has_neg.neg, .. }; tactic.pi_instance_derive_field
instance comm_ring [comm_ring α] : comm_ring (ulift α) :=
by refine_struct { zero := (0 : ulift α), one := 1, add := (+), mul := (*), sub := has_sub.sub,
neg := has_neg.neg, .. }; tactic.pi_instance_derive_field
end ulift
|
e2c4ea0e07d091fadf43b1ccf4abf35d02bdf0b2 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /src/Lean/Meta/PPGoal.lean | d19e4673b0febd204e62cc6172cd3d233485f0ec | [
"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 | 4,283 | lean | /-
Copyright (c) 2020 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
-/
import Lean.Meta.InferType
namespace Lean.Meta
register_builtin_option pp.auxDecls : Bool := {
defValue := false
group := "pp"
descr := "display auxiliary declarations used to compile recursive functions"
}
register_builtin_option pp.implementationDetailHyps : Bool := {
defValue := false
group := "pp"
descr := "display implementation detail hypotheses in the local context"
}
register_builtin_option pp.inaccessibleNames : Bool := {
defValue := true
group := "pp"
descr := "display inaccessible declarations in the local context"
}
register_builtin_option pp.showLetValues : Bool := {
defValue := true
group := "pp"
descr := "display let-declaration values in the info view"
}
private def addLine (fmt : Format) : Format :=
if fmt.isNil then fmt else fmt ++ Format.line
def getGoalPrefix (mvarDecl : MetavarDecl) : String :=
if isLHSGoal? mvarDecl.type |>.isSome then
-- use special prefix for `conv` goals
"| "
else
"⊢ "
def ppGoal (mvarId : MVarId) : MetaM Format := do
match (← getMCtx).findDecl? mvarId with
| none => return "unknown goal"
| some mvarDecl =>
let indent := 2 -- Use option
let showLetValues := pp.showLetValues.get (← getOptions)
let ppAuxDecls := pp.auxDecls.get (← getOptions)
let ppImplDetailHyps := pp.implementationDetailHyps.get (← getOptions)
let lctx := mvarDecl.lctx
let lctx := lctx.sanitizeNames.run' { options := (← getOptions) }
withLCtx lctx mvarDecl.localInstances do
-- The followint two `let rec`s are being used to control the generated code size.
-- Then should be remove after we rewrite the compiler in Lean
let rec pushPending (ids : List Name) (type? : Option Expr) (fmt : Format) : MetaM Format := do
if ids.isEmpty then
return fmt
else
let fmt := addLine fmt
match type? with
| none => return fmt
| some type =>
let typeFmt ← ppExpr type
return fmt ++ (Format.joinSep ids.reverse (format " ") ++ " :" ++ Format.nest indent (Format.line ++ typeFmt)).group
let rec ppVars (varNames : List Name) (prevType? : Option Expr) (fmt : Format) (localDecl : LocalDecl) : MetaM (List Name × Option Expr × Format) := do
match localDecl with
| .cdecl _ _ varName type _ _ =>
let varName := varName.simpMacroScopes
let type ← instantiateMVars type
if prevType? == none || prevType? == some type then
return (varName :: varNames, some type, fmt)
else do
let fmt ← pushPending varNames prevType? fmt
return ([varName], some type, fmt)
| .ldecl _ _ varName type val _ _ => do
let varName := varName.simpMacroScopes
let fmt ← pushPending varNames prevType? fmt
let fmt := addLine fmt
let type ← instantiateMVars type
let typeFmt ← ppExpr type
let mut fmtElem := format varName ++ " : " ++ typeFmt
if showLetValues then
let val ← instantiateMVars val
let valFmt ← ppExpr val
fmtElem := fmtElem ++ " :=" ++ Format.nest indent (Format.line ++ valFmt)
let fmt := fmt ++ fmtElem.group
return ([], none, fmt)
let (varNames, type?, fmt) ← lctx.foldlM (init := ([], none, Format.nil)) fun (varNames, prevType?, fmt) (localDecl : LocalDecl) =>
if !ppAuxDecls && localDecl.isAuxDecl || !ppImplDetailHyps && localDecl.isImplementationDetail then
return (varNames, prevType?, fmt)
else
ppVars varNames prevType? fmt localDecl
let fmt ← pushPending varNames type? fmt
let fmt := addLine fmt
let typeFmt ← ppExpr (← instantiateMVars mvarDecl.type)
let fmt := fmt ++ getGoalPrefix mvarDecl ++ Format.nest indent typeFmt
match mvarDecl.userName with
| Name.anonymous => return fmt
| name => return "case " ++ format name.eraseMacroScopes ++ Format.line ++ fmt
end Lean.Meta
|
42cf681328fdf2c684f421c26f3355e891bfc1e7 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/run/forInRangeWF.lean | 5070e8a8e63e556b51fae5207183103a88d650a4 | [
"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 | 508 | lean | inductive Expr where
| app (f : String) (args : Array Expr)
def Expr.size (e : Expr) : Nat := Id.run do
match e with
| app f args =>
let mut sz := 1
for h : i in [: args.size] do
sz := sz + size (args.get ⟨i, h.upper⟩)
return sz
namespace Ex2
inductive Expr where
| app (f : String) (args : List Expr)
def Expr.size (e : Expr) : Nat := Id.run do
match e with
| app f args =>
let mut sz := 1
for h : arg in args do
sz := sz + size arg
return sz
end Ex2
|
c95a581c8250d5b6bf7a399703d4f787160fe742 | 5749d8999a76f3a8fddceca1f6941981e33aaa96 | /src/data/equiv/encodable.lean | a07c640d7230cfa6cbd91ff8ec3b6cc2548b5155 | [
"Apache-2.0"
] | permissive | jdsalchow/mathlib | 13ab43ef0d0515a17e550b16d09bd14b76125276 | 497e692b946d93906900bb33a51fd243e7649406 | refs/heads/master | 1,585,819,143,348 | 1,580,072,892,000 | 1,580,072,892,000 | 154,287,128 | 0 | 0 | Apache-2.0 | 1,540,281,610,000 | 1,540,281,609,000 | null | UTF-8 | Lean | false | false | 12,709 | lean | /-
Copyright (c) 2015 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura, Mario Carneiro
Type class for encodable Types.
Note that every encodable Type is countable.
-/
import data.equiv.nat
open option list nat function
/-- An encodable type is a "constructively countable" type. This is where
we have an explicit injection `encode : α → nat` and a partial inverse
`decode : nat → option α`. This makes the range of `encode` decidable,
although it is not decidable if `α` is finite or not. -/
class encodable (α : Type*) :=
(encode : α → nat) (decode : nat → option α) (encodek : ∀ a, decode (encode a) = some a)
namespace encodable
variables {α : Type*} {β : Type*}
universe u
open encodable
theorem encode_injective [encodable α] : function.injective (@encode α _)
| x y e := option.some.inj $ by rw [← encodek, e, encodek]
/- This is not set as an instance because this is usually not the best way
to infer decidability. -/
def decidable_eq_of_encodable (α) [encodable α] : decidable_eq α
| a b := decidable_of_iff _ encode_injective.eq_iff
def of_left_injection [encodable α]
(f : β → α) (finv : α → option β) (linv : ∀ b, finv (f b) = some b) : encodable β :=
⟨λ b, encode (f b),
λ n, (decode α n).bind finv,
λ b, by simp [encodable.encodek, linv]⟩
def of_left_inverse [encodable α]
(f : β → α) (finv : α → β) (linv : ∀ b, finv (f b) = b) : encodable β :=
of_left_injection f (some ∘ finv) (λ b, congr_arg some (linv b))
/-- If `α` is encodable and `β ≃ α`, then so is `β` -/
def of_equiv (α) [encodable α] (e : β ≃ α) : encodable β :=
of_left_inverse e e.symm e.left_inv
@[simp] theorem encode_of_equiv {α β} [encodable α] (e : β ≃ α) (b : β) :
@encode _ (of_equiv _ e) b = encode (e b) := rfl
@[simp] theorem decode_of_equiv {α β} [encodable α] (e : β ≃ α) (n : ℕ) :
@decode _ (of_equiv _ e) n = (decode α n).map e.symm := rfl
instance nat : encodable nat :=
⟨id, some, λ a, rfl⟩
@[simp] theorem encode_nat (n : ℕ) : encode n = n := rfl
@[simp] theorem decode_nat (n : ℕ) : decode ℕ n = some n := rfl
instance empty : encodable empty :=
⟨λ a, a.rec _, λ n, none, λ a, a.rec _⟩
instance unit : encodable punit :=
⟨λ_, zero, λn, nat.cases_on n (some punit.star) (λ _, none), λ⟨⟩, by simp⟩
@[simp] theorem encode_star : encode punit.star = 0 := rfl
@[simp] theorem decode_unit_zero : decode punit 0 = some punit.star := rfl
@[simp] theorem decode_unit_succ (n) : decode punit (succ n) = none := rfl
instance option {α : Type*} [h : encodable α] : encodable (option α) :=
⟨λ o, option.cases_on o nat.zero (λ a, succ (encode a)),
λ n, nat.cases_on n (some none) (λ m, (decode α m).map some),
λ o, by cases o; dsimp; simp [encodek, nat.succ_ne_zero]⟩
@[simp] theorem encode_none [encodable α] : encode (@none α) = 0 := rfl
@[simp] theorem encode_some [encodable α] (a : α) :
encode (some a) = succ (encode a) := rfl
@[simp] theorem decode_option_zero [encodable α] : decode (option α) 0 = some none := rfl
@[simp] theorem decode_option_succ [encodable α] (n) :
decode (option α) (succ n) = (decode α n).map some := rfl
def decode2 (α) [encodable α] (n : ℕ) : option α :=
(decode α n).bind (option.guard (λ a, encode a = n))
theorem mem_decode2' [encodable α] {n : ℕ} {a : α} :
a ∈ decode2 α n ↔ a ∈ decode α n ∧ encode a = n :=
by simp [decode2]; exact
⟨λ ⟨_, h₁, rfl, h₂⟩, ⟨h₁, h₂⟩, λ ⟨h₁, h₂⟩, ⟨_, h₁, rfl, h₂⟩⟩
theorem mem_decode2 [encodable α] {n : ℕ} {a : α} :
a ∈ decode2 α n ↔ encode a = n :=
mem_decode2'.trans (and_iff_right_of_imp $ λ e, e ▸ encodek _)
theorem decode2_is_partial_inv [encodable α] : is_partial_inv encode (decode2 α) :=
λ a n, mem_decode2
theorem decode2_inj [encodable α] {n : ℕ} {a₁ a₂ : α}
(h₁ : a₁ ∈ decode2 α n) (h₂ : a₂ ∈ decode2 α n) : a₁ = a₂ :=
encode_injective $ (mem_decode2.1 h₁).trans (mem_decode2.1 h₂).symm
theorem encodek2 [encodable α] (a : α) : decode2 α (encode a) = some a :=
mem_decode2.2 rfl
def decidable_range_encode (α : Type*) [encodable α] : decidable_pred (set.range (@encode α _)) :=
λ x, decidable_of_iff (option.is_some (decode2 α x))
⟨λ h, ⟨option.get h, by rw [← decode2_is_partial_inv (option.get h), option.some_get]⟩,
λ ⟨n, hn⟩, by rw [← hn, encodek2]; exact rfl⟩
def equiv_range_encode (α : Type*) [encodable α] : α ≃ set.range (@encode α _) :=
{ to_fun := λ a : α, ⟨encode a, set.mem_range_self _⟩,
inv_fun := λ n, option.get (show is_some (decode2 α n.1),
by cases n.2 with x hx; rw [← hx, encodek2]; exact rfl),
left_inv := λ a, by dsimp;
rw [← option.some_inj, option.some_get, encodek2],
right_inv := λ ⟨n, x, hx⟩, begin
apply subtype.eq,
dsimp,
conv {to_rhs, rw ← hx},
rw [encode_injective.eq_iff, ← option.some_inj, option.some_get, ← hx, encodek2],
end }
section sum
variables [encodable α] [encodable β]
def encode_sum : α ⊕ β → nat
| (sum.inl a) := bit0 $ encode a
| (sum.inr b) := bit1 $ encode b
def decode_sum (n : nat) : option (α ⊕ β) :=
match bodd_div2 n with
| (ff, m) := (decode α m).map sum.inl
| (tt, m) := (decode β m).map sum.inr
end
instance sum : encodable (α ⊕ β) :=
⟨encode_sum, decode_sum, λ s,
by cases s; simp [encode_sum, decode_sum, encodek]; refl⟩
@[simp] theorem encode_inl (a : α) :
@encode (α ⊕ β) _ (sum.inl a) = bit0 (encode a) := rfl
@[simp] theorem encode_inr (b : β) :
@encode (α ⊕ β) _ (sum.inr b) = bit1 (encode b) := rfl
@[simp] theorem decode_sum_val (n : ℕ) :
decode (α ⊕ β) n = decode_sum n := rfl
end sum
instance bool : encodable bool :=
of_equiv (unit ⊕ unit) equiv.bool_equiv_punit_sum_punit
@[simp] theorem encode_tt : encode tt = 1 := rfl
@[simp] theorem encode_ff : encode ff = 0 := rfl
@[simp] theorem decode_zero : decode bool 0 = some ff := rfl
@[simp] theorem decode_one : decode bool 1 = some tt := rfl
theorem decode_ge_two (n) (h : 2 ≤ n) : decode bool n = none :=
begin
suffices : decode_sum n = none,
{ change (decode_sum n).map _ = none, rw this, refl },
have : 1 ≤ div2 n,
{ rw [div2_val, nat.le_div_iff_mul_le],
exacts [h, dec_trivial] },
cases exists_eq_succ_of_ne_zero (ne_of_gt this) with m e,
simp [decode_sum]; cases bodd n; simp [decode_sum]; rw e; refl
end
section sigma
variables {γ : α → Type*} [encodable α] [∀ a, encodable (γ a)]
def encode_sigma : sigma γ → ℕ
| ⟨a, b⟩ := mkpair (encode a) (encode b)
def decode_sigma (n : ℕ) : option (sigma γ) :=
let (n₁, n₂) := unpair n in
(decode α n₁).bind $ λ a, (decode (γ a) n₂).map $ sigma.mk a
instance sigma : encodable (sigma γ) :=
⟨encode_sigma, decode_sigma, λ ⟨a, b⟩,
by simp [encode_sigma, decode_sigma, unpair_mkpair, encodek]⟩
@[simp] theorem decode_sigma_val (n : ℕ) : decode (sigma γ) n =
(decode α n.unpair.1).bind (λ a, (decode (γ a) n.unpair.2).map $ sigma.mk a) :=
show decode_sigma._match_1 _ = _, by cases n.unpair; refl
@[simp] theorem encode_sigma_val (a b) : @encode (sigma γ) _ ⟨a, b⟩ =
mkpair (encode a) (encode b) := rfl
end sigma
section prod
variables [encodable α] [encodable β]
instance prod : encodable (α × β) :=
of_equiv _ (equiv.sigma_equiv_prod α β).symm
@[simp] theorem decode_prod_val (n : ℕ) : decode (α × β) n =
(decode α n.unpair.1).bind (λ a, (decode β n.unpair.2).map $ prod.mk a) :=
show (decode (sigma (λ _, β)) n).map (equiv.sigma_equiv_prod α β) = _,
by simp; cases decode α n.unpair.1; simp;
cases decode β n.unpair.2; refl
@[simp] theorem encode_prod_val (a b) : @encode (α × β) _ (a, b) =
mkpair (encode a) (encode b) := rfl
end prod
section subtype
open subtype decidable
variable {P : α → Prop}
variable [encA : encodable α]
variable [decP : decidable_pred P]
include encA
def encode_subtype : {a : α // P a} → nat
| ⟨v, h⟩ := encode v
include decP
def decode_subtype (v : nat) : option {a : α // P a} :=
(decode α v).bind $ λ a,
if h : P a then some ⟨a, h⟩ else none
instance subtype : encodable {a : α // P a} :=
⟨encode_subtype, decode_subtype,
λ ⟨v, h⟩, by simp [encode_subtype, decode_subtype, encodek, h]⟩
end subtype
instance fin (n) : encodable (fin n) :=
of_equiv _ (equiv.fin_equiv_subtype _)
instance int : encodable ℤ :=
of_equiv _ equiv.int_equiv_nat
instance ulift [encodable α] : encodable (ulift α) :=
of_equiv _ equiv.ulift
instance plift [encodable α] : encodable (plift α) :=
of_equiv _ equiv.plift
noncomputable def of_inj [encodable β] (f : α → β) (hf : injective f) : encodable α :=
of_left_injection f (partial_inv f) (λ x, (partial_inv_of_injective hf _ _).2 rfl)
end encodable
/-
Choice function for encodable types and decidable predicates.
We provide the following API
choose {α : Type*} {p : α → Prop} [c : encodable α] [d : decidable_pred p] : (∃ x, p x) → α :=
choose_spec {α : Type*} {p : α → Prop} [c : encodable α] [d : decidable_pred p] (ex : ∃ x, p x) : p (choose ex) :=
-/
namespace encodable
section find_a
variables {α : Type*} (p : α → Prop) [encodable α] [decidable_pred p]
private def good : option α → Prop
| (some a) := p a
| none := false
private def decidable_good : decidable_pred (good p)
| n := by cases n; unfold good; apply_instance
local attribute [instance] decidable_good
open encodable
variable {p}
def choose_x (h : ∃ x, p x) : {a:α // p a} :=
have ∃ n, good p (decode α n), from
let ⟨w, pw⟩ := h in ⟨encode w, by simp [good, encodek, pw]⟩,
match _, nat.find_spec this : ∀ o, good p o → {a // p a} with
| some a, h := ⟨a, h⟩
end
def choose (h : ∃ x, p x) : α := (choose_x h).1
lemma choose_spec (h : ∃ x, p x) : p (choose h) := (choose_x h).2
end find_a
theorem axiom_of_choice {α : Type*} {β : α → Type*} {R : Π x, β x → Prop}
[Π a, encodable (β a)] [∀ x y, decidable (R x y)]
(H : ∀x, ∃y, R x y) : ∃f:Πa, β a, ∀x, R x (f x) :=
⟨λ x, choose (H x), λ x, choose_spec (H x)⟩
theorem skolem {α : Type*} {β : α → Type*} {P : Π x, β x → Prop}
[c : Π a, encodable (β a)] [d : ∀ x y, decidable (P x y)] :
(∀x, ∃y, P x y) ↔ ∃f : Π a, β a, (∀x, P x (f x)) :=
⟨axiom_of_choice, λ ⟨f, H⟩ x, ⟨_, H x⟩⟩
end encodable
namespace directed
open encodable
variables {α : Type*} {β : Type*} [encodable α] [inhabited α]
/-- Given a `directed r` function `f : α → β` defined on an encodable inhabited type,
construct a noncomputable sequence such that `r (f (x n)) (f (x (n + 1)))`
and `r (f a) (f (x (encode a + 1))`. -/
protected noncomputable def sequence {r : β → β → Prop} (f : α → β) (hf : directed r f) : ℕ → α
| 0 := default α
| (n + 1) :=
let p := sequence n in
match decode α n with
| none := classical.some (hf p p)
| (some a) := classical.some (hf p a)
end
lemma sequence_mono_nat {r : β → β → Prop} {f : α → β} (hf : directed r f) (n : ℕ) :
r (f (hf.sequence f n)) (f (hf.sequence f (n+1))) :=
begin
dsimp [directed.sequence],
generalize eq : hf.sequence f n = p,
cases h : decode α n with a,
{ exact (classical.some_spec (hf p p)).1 },
{ exact (classical.some_spec (hf p a)).1 }
end
lemma rel_sequence {r : β → β → Prop} {f : α → β} (hf : directed r f) (a : α) :
r (f a) (f (hf.sequence f (encode a + 1))) :=
begin
simp only [directed.sequence, encodek],
exact (classical.some_spec (hf _ a)).2
end
variables [preorder β] {f : α → β} (hf : directed (≤) f)
lemma sequence_mono : monotone (f ∘ (hf.sequence f)) :=
monotone_of_monotone_nat $ hf.sequence_mono_nat
lemma le_sequence (a : α) : f a ≤ f (hf.sequence f (encode a + 1)) :=
hf.rel_sequence a
end directed
section quotient
open encodable quotient
variables {α : Type*} {s : setoid α} [@decidable_rel α (≈)] [encodable α]
/-- Representative of an equivalence class. This is a computable version of `quot.out` for a setoid
on an encodable type. -/
def quotient.rep (q : quotient s) : α :=
choose (exists_rep q)
theorem quotient.rep_spec (q : quotient s) : ⟦q.rep⟧ = q :=
choose_spec (exists_rep q)
/-- The quotient of an encodable space by a decidable equivalence relation is encodable. -/
def encodable_quotient : encodable (quotient s) :=
⟨λ q, encode q.rep,
λ n, quotient.mk <$> decode α n,
by rintros ⟨l⟩; rw encodek; exact congr_arg some ⟦l⟧.rep_spec⟩
end quotient
|
36ef0d65bb094f58eda8965589679db6bd0c24e8 | 35677d2df3f081738fa6b08138e03ee36bc33cad | /src/data/complex/basic.lean | 7ee8ec8449cd1a5eb7c0dce0e511a0a46b32dd28 | [
"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 | 19,404 | lean | /-
Copyright (c) 2017 Kevin Buzzard. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kevin Buzzard, Mario Carneiro
The complex numbers, modelled as R^2 in the obvious way.
-/
import data.real.basic tactic.ring algebra.field_power
import tactic.norm_cast
structure complex : Type :=
(re : ℝ) (im : ℝ)
notation `ℂ` := complex
namespace complex
@[simp] theorem eta : ∀ z : ℂ, complex.mk z.re z.im = z
| ⟨a, b⟩ := rfl
@[ext]
theorem ext : ∀ {z w : ℂ}, z.re = w.re → z.im = w.im → z = w
| ⟨zr, zi⟩ ⟨_, _⟩ rfl rfl := rfl
theorem ext_iff {z w : ℂ} : z = w ↔ z.re = w.re ∧ z.im = w.im :=
⟨λ H, by simp [H], and.rec ext⟩
def of_real (r : ℝ) : ℂ := ⟨r, 0⟩
instance : has_coe ℝ ℂ := ⟨of_real⟩
@[simp] lemma of_real_eq_coe (r : ℝ) : of_real r = r := rfl
@[simp, elim_cast] lemma of_real_re (r : ℝ) : (r : ℂ).re = r := rfl
@[simp, elim_cast] lemma of_real_im (r : ℝ) : (r : ℂ).im = 0 := rfl
@[simp, elim_cast] theorem of_real_inj {z w : ℝ} : (z : ℂ) = w ↔ z = w :=
⟨congr_arg re, congr_arg _⟩
instance : has_zero ℂ := ⟨(0 : ℝ)⟩
instance : inhabited ℂ := ⟨0⟩
@[simp] lemma zero_re : (0 : ℂ).re = 0 := rfl
@[simp] lemma zero_im : (0 : ℂ).im = 0 := rfl
@[simp, squash_cast] lemma of_real_zero : ((0 : ℝ) : ℂ) = 0 := rfl
@[simp] theorem of_real_eq_zero {z : ℝ} : (z : ℂ) = 0 ↔ z = 0 := of_real_inj
theorem of_real_ne_zero {z : ℝ} : (z : ℂ) ≠ 0 ↔ z ≠ 0 := not_congr of_real_eq_zero
instance : has_one ℂ := ⟨(1 : ℝ)⟩
@[simp] lemma one_re : (1 : ℂ).re = 1 := rfl
@[simp] lemma one_im : (1 : ℂ).im = 0 := rfl
@[simp, squash_cast] lemma of_real_one : ((1 : ℝ) : ℂ) = 1 := rfl
def I : ℂ := ⟨0, 1⟩
@[simp] lemma I_re : I.re = 0 := rfl
@[simp] lemma I_im : I.im = 1 := rfl
instance : has_add ℂ := ⟨λ z w, ⟨z.re + w.re, z.im + w.im⟩⟩
@[simp] lemma add_re (z w : ℂ) : (z + w).re = z.re + w.re := rfl
@[simp] lemma add_im (z w : ℂ) : (z + w).im = z.im + w.im := rfl
@[simp, move_cast] lemma of_real_add (r s : ℝ) : ((r + s : ℝ) : ℂ) = r + s := ext_iff.2 $ by simp
@[simp, squash_cast, move_cast] lemma of_real_bit0 (r : ℝ) : ((bit0 r : ℝ) : ℂ) = bit0 r := ext_iff.2 $ by simp [bit0]
@[simp, squash_cast, move_cast] lemma of_real_bit1 (r : ℝ) : ((bit1 r : ℝ) : ℂ) = bit1 r := ext_iff.2 $ by simp [bit1]
instance : has_neg ℂ := ⟨λ z, ⟨-z.re, -z.im⟩⟩
@[simp] lemma neg_re (z : ℂ) : (-z).re = -z.re := rfl
@[simp] lemma neg_im (z : ℂ) : (-z).im = -z.im := rfl
@[simp, move_cast] lemma of_real_neg (r : ℝ) : ((-r : ℝ) : ℂ) = -r := ext_iff.2 $ by simp
instance : has_mul ℂ := ⟨λ z w, ⟨z.re * w.re - z.im * w.im, z.re * w.im + z.im * w.re⟩⟩
@[simp] lemma mul_re (z w : ℂ) : (z * w).re = z.re * w.re - z.im * w.im := rfl
@[simp] lemma mul_im (z w : ℂ) : (z * w).im = z.re * w.im + z.im * w.re := rfl
@[simp, move_cast] lemma of_real_mul (r s : ℝ) : ((r * s : ℝ) : ℂ) = r * s := ext_iff.2 $ by simp
lemma smul_re (r : ℝ) (z : ℂ) : (↑r * z).re = r * z.re := by simp
lemma smul_im (r : ℝ) (z : ℂ) : (↑r * z).im = r * z.im := by simp
@[simp] lemma I_mul_I : I * I = -1 := ext_iff.2 $ by simp
lemma I_ne_zero : (I : ℂ) ≠ 0 := mt (congr_arg im) zero_ne_one.symm
lemma mk_eq_add_mul_I (a b : ℝ) : complex.mk a b = a + b * I :=
ext_iff.2 $ by simp
@[simp] lemma re_add_im (z : ℂ) : (z.re : ℂ) + z.im * I = z :=
ext_iff.2 $ by simp
def real_prod_equiv : ℂ ≃ (ℝ × ℝ) :=
{ to_fun := λ z, ⟨z.re, z.im⟩,
inv_fun := λ p, ⟨p.1, p.2⟩,
left_inv := λ ⟨x, y⟩, rfl,
right_inv := λ ⟨x, y⟩, rfl }
@[simp] theorem real_prod_equiv_apply (z : ℂ) : real_prod_equiv z = (z.re, z.im) := rfl
theorem real_prod_equiv_symm_re (x y : ℝ) : (real_prod_equiv.symm (x, y)).re = x := rfl
theorem real_prod_equiv_symm_im (x y : ℝ) : (real_prod_equiv.symm (x, y)).im = y := rfl
def conj (z : ℂ) : ℂ := ⟨z.re, -z.im⟩
@[simp] lemma conj_re (z : ℂ) : (conj z).re = z.re := rfl
@[simp] lemma conj_im (z : ℂ) : (conj z).im = -z.im := rfl
@[simp] lemma conj_of_real (r : ℝ) : conj r = r := ext_iff.2 $ by simp [conj]
@[simp] lemma conj_zero : conj 0 = 0 := ext_iff.2 $ by simp [conj]
@[simp] lemma conj_one : conj 1 = 1 := ext_iff.2 $ by simp
@[simp] lemma conj_I : conj I = -I := ext_iff.2 $ by simp
@[simp] lemma conj_add (z w : ℂ) : conj (z + w) = conj z + conj w :=
ext_iff.2 $ by simp [add_comm]
@[simp] lemma conj_neg (z : ℂ) : conj (-z) = -conj z := rfl
@[simp] lemma conj_neg_I : conj (-I) = I := ext_iff.2 $ by simp
@[simp] lemma conj_mul (z w : ℂ) : conj (z * w) = conj z * conj w :=
ext_iff.2 $ by simp [add_comm]
@[simp] lemma conj_conj (z : ℂ) : conj (conj z) = z :=
ext_iff.2 $ by simp
lemma conj_involutive : function.involutive conj := conj_conj
lemma conj_bijective : function.bijective conj := conj_involutive.bijective
lemma conj_inj {z w : ℂ} : conj z = conj w ↔ z = w :=
conj_bijective.1.eq_iff
@[simp] lemma conj_eq_zero {z : ℂ} : conj z = 0 ↔ z = 0 :=
by simpa using @conj_inj z 0
lemma eq_conj_iff_real {z : ℂ} : conj z = z ↔ ∃ r : ℝ, z = r :=
⟨λ h, ⟨z.re, ext rfl $ eq_zero_of_neg_eq (congr_arg im h)⟩,
λ ⟨h, e⟩, e.symm ▸ rfl⟩
lemma eq_conj_iff_re {z : ℂ} : conj z = z ↔ (z.re : ℂ) = z :=
eq_conj_iff_real.trans ⟨by rintro ⟨r, rfl⟩; simp, λ h, ⟨_, h.symm⟩⟩
def norm_sq (z : ℂ) : ℝ := z.re * z.re + z.im * z.im
@[simp] lemma norm_sq_of_real (r : ℝ) : norm_sq r = r * r :=
by simp [norm_sq]
@[simp] lemma norm_sq_zero : norm_sq 0 = 0 := by simp [norm_sq]
@[simp] lemma norm_sq_one : norm_sq 1 = 1 := by simp [norm_sq]
@[simp] lemma norm_sq_I : norm_sq I = 1 := by simp [norm_sq]
lemma norm_sq_nonneg (z : ℂ) : 0 ≤ norm_sq z :=
add_nonneg (mul_self_nonneg _) (mul_self_nonneg _)
@[simp] lemma norm_sq_eq_zero {z : ℂ} : norm_sq z = 0 ↔ z = 0 :=
⟨λ h, ext
(eq_zero_of_mul_self_add_mul_self_eq_zero h)
(eq_zero_of_mul_self_add_mul_self_eq_zero $ (add_comm _ _).trans h),
λ h, h.symm ▸ norm_sq_zero⟩
@[simp] lemma norm_sq_pos {z : ℂ} : 0 < norm_sq z ↔ z ≠ 0 :=
by rw [lt_iff_le_and_ne, ne, eq_comm]; simp [norm_sq_nonneg]
@[simp] lemma norm_sq_neg (z : ℂ) : norm_sq (-z) = norm_sq z :=
by simp [norm_sq]
@[simp] lemma norm_sq_conj (z : ℂ) : norm_sq (conj z) = norm_sq z :=
by simp [norm_sq]
@[simp] lemma norm_sq_mul (z w : ℂ) : norm_sq (z * w) = norm_sq z * norm_sq w :=
by dsimp [norm_sq]; ring
lemma norm_sq_add (z w : ℂ) : norm_sq (z + w) =
norm_sq z + norm_sq w + 2 * (z * conj w).re :=
by dsimp [norm_sq]; ring
lemma re_sq_le_norm_sq (z : ℂ) : z.re * z.re ≤ norm_sq z :=
le_add_of_nonneg_right (mul_self_nonneg _)
lemma im_sq_le_norm_sq (z : ℂ) : z.im * z.im ≤ norm_sq z :=
le_add_of_nonneg_left (mul_self_nonneg _)
theorem mul_conj (z : ℂ) : z * conj z = norm_sq z :=
ext_iff.2 $ by simp [norm_sq, mul_comm, sub_eq_neg_add, add_comm]
theorem add_conj (z : ℂ) : z + conj z = (2 * z.re : ℝ) :=
ext_iff.2 $ by simp [two_mul]
instance : comm_ring ℂ :=
by refine { zero := 0, add := (+), neg := has_neg.neg, one := 1, mul := (*), ..};
{ intros, apply ext_iff.2; split; simp; ring }
@[simp] lemma I_sq : I ^ 2 = -1 := by rw [pow_two, I_mul_I]
@[simp] lemma bit0_re (z : ℂ) : (bit0 z).re = bit0 z.re := rfl
@[simp] lemma bit1_re (z : ℂ) : (bit1 z).re = bit1 z.re := rfl
@[simp] lemma bit0_im (z : ℂ) : (bit0 z).im = bit0 z.im := eq.refl _
@[simp] lemma bit1_im (z : ℂ) : (bit1 z).im = bit0 z.im := add_zero _
@[simp] lemma sub_re (z w : ℂ) : (z - w).re = z.re - w.re := rfl
@[simp] lemma sub_im (z w : ℂ) : (z - w).im = z.im - w.im := rfl
@[simp, move_cast] lemma of_real_sub (r s : ℝ) : ((r - s : ℝ) : ℂ) = r - s := ext_iff.2 $ by simp
@[simp, move_cast] lemma of_real_pow (r : ℝ) (n : ℕ) : ((r ^ n : ℝ) : ℂ) = r ^ n :=
by induction n; simp [*, of_real_mul, pow_succ]
theorem sub_conj (z : ℂ) : z - conj z = (2 * z.im : ℝ) * I :=
ext_iff.2 $ by simp [two_mul, sub_eq_add_neg]
lemma conj_pow (z : ℂ) (n : ℕ) : conj (z ^ n) = conj z ^ n :=
by induction n; simp [*, conj_mul, pow_succ]
@[simp] lemma conj_two : conj (2 : ℂ) = 2 := by apply complex.ext; simp
lemma norm_sq_sub (z w : ℂ) : norm_sq (z - w) =
norm_sq z + norm_sq w - 2 * (z * conj w).re :=
by rw [sub_eq_add_neg, norm_sq_add]; simp [-mul_re, add_comm, add_left_comm, sub_eq_add_neg]
noncomputable instance : has_inv ℂ := ⟨λ z, conj z * ((norm_sq z)⁻¹:ℝ)⟩
theorem inv_def (z : ℂ) : z⁻¹ = conj z * ((norm_sq z)⁻¹:ℝ) := rfl
@[simp] lemma inv_re (z : ℂ) : (z⁻¹).re = z.re / norm_sq z := by simp [inv_def, division_def]
@[simp] lemma inv_im (z : ℂ) : (z⁻¹).im = -z.im / norm_sq z := by simp [inv_def, division_def]
@[simp, move_cast] lemma of_real_inv (r : ℝ) : ((r⁻¹ : ℝ) : ℂ) = r⁻¹ :=
ext_iff.2 $ begin
simp,
by_cases r = 0, {simp [h]},
rw [← div_div_eq_div_mul, div_self h, one_div_eq_inv]
end
protected lemma inv_zero : (0⁻¹ : ℂ) = 0 :=
by rw [← of_real_zero, ← of_real_inv, inv_zero]
protected theorem mul_inv_cancel {z : ℂ} (h : z ≠ 0) : z * z⁻¹ = 1 :=
by rw [inv_def, ← mul_assoc, mul_conj, ← of_real_mul,
mul_inv_cancel (mt norm_sq_eq_zero.1 h), of_real_one]
noncomputable instance : field ℂ :=
{ inv := has_inv.inv,
zero_ne_one := mt (congr_arg re) zero_ne_one,
mul_inv_cancel := @complex.mul_inv_cancel,
inv_zero := complex.inv_zero,
..complex.comm_ring }
instance re.is_add_group_hom : is_add_group_hom complex.re :=
{ map_add := complex.add_re }
instance im.is_add_group_hom : is_add_group_hom complex.im :=
{ map_add := complex.add_im }
instance : is_ring_hom conj :=
by refine_struct {..}; simp
instance of_real.is_ring_hom : is_ring_hom (coe : ℝ → ℂ) :=
by refine_struct {..}; simp
lemma div_re (z w : ℂ) : (z / w).re = z.re * w.re / norm_sq w + z.im * w.im / norm_sq w :=
by simp [div_eq_mul_inv, mul_assoc, sub_eq_add_neg, add_comm, add_left_comm]
lemma div_im (z w : ℂ) : (z / w).im = z.im * w.re / norm_sq w - z.re * w.im / norm_sq w :=
by simp [div_eq_mul_inv, mul_assoc, sub_eq_add_neg, add_comm, add_left_comm]
@[simp, move_cast] lemma of_real_div (r s : ℝ) : ((r / s : ℝ) : ℂ) = r / s :=
is_ring_hom.map_div coe
@[simp, move_cast] lemma of_real_fpow (r : ℝ) (n : ℤ) : ((r ^ n : ℝ) : ℂ) = (r : ℂ) ^ n :=
is_ring_hom.map_fpow of_real r n
@[simp, squash_cast] theorem of_real_int_cast : ∀ n : ℤ, ((n : ℝ) : ℂ) = n :=
int.eq_cast (λ n, ((n : ℝ) : ℂ))
(by rw [int.cast_one, of_real_one])
(λ _ _, by rw [int.cast_add, of_real_add])
@[simp, squash_cast] theorem of_real_nat_cast (n : ℕ) : ((n : ℝ) : ℂ) = n :=
by rw [← int.cast_coe_nat, of_real_int_cast]; refl
@[simp] lemma conj_sub (z w : ℂ) : conj (z - w) = conj z - conj w :=
by simp [sub_eq_add_neg]
@[simp] lemma conj_inv (z : ℂ) : conj z⁻¹ = (conj z)⁻¹ :=
by ext; simp [neg_div]
@[simp] lemma conj_div (z w : ℂ) : conj (z / w) = conj z / conj w :=
by rw [division_def, conj_mul, conj_inv]; refl
@[simp] lemma norm_sq_inv (z : ℂ) : norm_sq z⁻¹ = (norm_sq z)⁻¹ :=
by classical; exact
if h : z = 0 then by simp [h] else
(domain.mul_left_inj (mt norm_sq_eq_zero.1 h)).1 $
by rw [← norm_sq_mul]; simp [h, -norm_sq_mul]
@[simp] lemma norm_sq_div (z w : ℂ) : norm_sq (z / w) = norm_sq z / norm_sq w :=
by rw [division_def, norm_sq_mul, norm_sq_inv]; refl
instance char_zero_complex : char_zero ℂ :=
add_group.char_zero_of_inj_zero $ λ n h,
by rwa [← of_real_nat_cast, of_real_eq_zero, nat.cast_eq_zero] at h
@[simp, squash_cast] theorem of_real_rat_cast : ∀ n : ℚ, ((n : ℝ) : ℂ) = n :=
by apply rat.eq_cast (λ n, ((n : ℝ) : ℂ)); simp
theorem re_eq_add_conj (z : ℂ) : (z.re : ℂ) = (z + conj z) / 2 :=
by rw [add_conj]; simp; rw [mul_div_cancel_left (z.re:ℂ) two_ne_zero']
@[simp, elim_cast] lemma nat_cast_re (n : ℕ) : (n : ℂ).re = n :=
by rw [← of_real_nat_cast, of_real_re]
@[simp, elim_cast] lemma nat_cast_im (n : ℕ) : (n : ℂ).im = 0 :=
by rw [← of_real_nat_cast, of_real_im]
@[simp, elim_cast] lemma int_cast_re (n : ℤ) : (n : ℂ).re = n :=
by rw [← of_real_int_cast, of_real_re]
@[simp, elim_cast] lemma int_cast_im (n : ℤ) : (n : ℂ).im = 0 :=
by rw [← of_real_int_cast, of_real_im]
@[simp, elim_cast] lemma rat_cast_re (q : ℚ) : (q : ℂ).re = q :=
by rw [← of_real_rat_cast, of_real_re]
@[simp, elim_cast] lemma rat_cast_im (q : ℚ) : (q : ℂ).im = 0 :=
by rw [← of_real_rat_cast, of_real_im]
noncomputable def abs (z : ℂ) : ℝ := (norm_sq z).sqrt
local notation `abs'` := _root_.abs
@[simp] lemma abs_of_real (r : ℝ) : abs r = abs' r :=
by simp [abs, norm_sq_of_real, real.sqrt_mul_self_eq_abs]
lemma abs_of_nonneg {r : ℝ} (h : 0 ≤ r) : abs r = r :=
(abs_of_real _).trans (abs_of_nonneg h)
lemma abs_of_nat (n : ℕ) : complex.abs n = n :=
calc complex.abs n = complex.abs (n:ℝ) : by rw [of_real_nat_cast]
... = _ : abs_of_nonneg (nat.cast_nonneg n)
lemma mul_self_abs (z : ℂ) : abs z * abs z = norm_sq z :=
real.mul_self_sqrt (norm_sq_nonneg _)
@[simp] lemma abs_zero : abs 0 = 0 := by simp [abs]
@[simp] lemma abs_one : abs 1 = 1 := by simp [abs]
@[simp] lemma abs_I : abs I = 1 := by simp [abs]
@[simp] lemma abs_two : abs 2 = 2 :=
calc abs 2 = abs (2 : ℝ) : by rw [of_real_bit0, of_real_one]
... = (2 : ℝ) : abs_of_nonneg (by norm_num)
lemma abs_nonneg (z : ℂ) : 0 ≤ abs z :=
real.sqrt_nonneg _
@[simp] lemma abs_eq_zero {z : ℂ} : abs z = 0 ↔ z = 0 :=
(real.sqrt_eq_zero $ norm_sq_nonneg _).trans norm_sq_eq_zero
@[simp] lemma abs_conj (z : ℂ) : abs (conj z) = abs z :=
by simp [abs]
@[simp] lemma abs_mul (z w : ℂ) : abs (z * w) = abs z * abs w :=
by rw [abs, norm_sq_mul, real.sqrt_mul (norm_sq_nonneg _)]; refl
lemma abs_re_le_abs (z : ℂ) : abs' z.re ≤ abs z :=
by rw [mul_self_le_mul_self_iff (_root_.abs_nonneg z.re) (abs_nonneg _),
abs_mul_abs_self, mul_self_abs];
apply re_sq_le_norm_sq
lemma abs_im_le_abs (z : ℂ) : abs' z.im ≤ abs z :=
by rw [mul_self_le_mul_self_iff (_root_.abs_nonneg z.im) (abs_nonneg _),
abs_mul_abs_self, mul_self_abs];
apply im_sq_le_norm_sq
lemma re_le_abs (z : ℂ) : z.re ≤ abs z :=
(abs_le.1 (abs_re_le_abs _)).2
lemma im_le_abs (z : ℂ) : z.im ≤ abs z :=
(abs_le.1 (abs_im_le_abs _)).2
lemma abs_add (z w : ℂ) : abs (z + w) ≤ abs z + abs w :=
(mul_self_le_mul_self_iff (abs_nonneg _)
(add_nonneg (abs_nonneg _) (abs_nonneg _))).2 $
begin
rw [mul_self_abs, add_mul_self_eq, mul_self_abs, mul_self_abs,
add_right_comm, norm_sq_add, add_le_add_iff_left,
mul_assoc, mul_le_mul_left (@two_pos ℝ _)],
simpa [-mul_re] using re_le_abs (z * conj w)
end
instance : is_absolute_value abs :=
{ abv_nonneg := abs_nonneg,
abv_eq_zero := λ _, abs_eq_zero,
abv_add := abs_add,
abv_mul := abs_mul }
open is_absolute_value
@[simp] lemma abs_abs (z : ℂ) : abs' (abs z) = abs z :=
_root_.abs_of_nonneg (abs_nonneg _)
@[simp] lemma abs_pos {z : ℂ} : 0 < abs z ↔ z ≠ 0 := abv_pos abs
@[simp] lemma abs_neg : ∀ z, abs (-z) = abs z := abv_neg abs
lemma abs_sub : ∀ z w, abs (z - w) = abs (w - z) := abv_sub abs
lemma abs_sub_le : ∀ a b c, abs (a - c) ≤ abs (a - b) + abs (b - c) := abv_sub_le abs
@[simp] theorem abs_inv : ∀ z, abs z⁻¹ = (abs z)⁻¹ := abv_inv abs
@[simp] theorem abs_div : ∀ z w, abs (z / w) = abs z / abs w := abv_div abs
lemma abs_abs_sub_le_abs_sub : ∀ z w, abs' (abs z - abs w) ≤ abs (z - w) := abs_abv_sub_le_abv_sub abs
lemma abs_le_abs_re_add_abs_im (z : ℂ) : abs z ≤ abs' z.re + abs' z.im :=
by simpa [re_add_im] using abs_add z.re (z.im * I)
lemma abs_re_div_abs_le_one (z : ℂ) : abs' (z.re / z.abs) ≤ 1 :=
by classical; exact
if hz : z = 0 then by simp [hz, zero_le_one]
else by rw [_root_.abs_div, abs_abs]; exact
div_le_of_le_mul (abs_pos.2 hz) (by rw mul_one; exact abs_re_le_abs _)
lemma abs_im_div_abs_le_one (z : ℂ) : abs' (z.im / z.abs) ≤ 1 :=
by classical; exact
if hz : z = 0 then by simp [hz, zero_le_one]
else by rw [_root_.abs_div, abs_abs]; exact
div_le_of_le_mul (abs_pos.2 hz) (by rw mul_one; exact abs_im_le_abs _)
@[simp, elim_cast] lemma abs_cast_nat (n : ℕ) : abs (n : ℂ) = n :=
by rw [← of_real_nat_cast, abs_of_nonneg (nat.cast_nonneg n)]
lemma norm_sq_eq_abs (x : ℂ) : norm_sq x = abs x ^ 2 :=
by rw [abs, pow_two, real.mul_self_sqrt (norm_sq_nonneg _)]
theorem is_cau_seq_re (f : cau_seq ℂ abs) : is_cau_seq abs' (λ n, (f n).re) :=
λ ε ε0, (f.cauchy ε0).imp $ λ i H j ij,
lt_of_le_of_lt (by simpa using abs_re_le_abs (f j - f i)) (H _ ij)
theorem is_cau_seq_im (f : cau_seq ℂ abs) : is_cau_seq abs' (λ n, (f n).im) :=
λ ε ε0, (f.cauchy ε0).imp $ λ i H j ij,
lt_of_le_of_lt (by simpa using abs_im_le_abs (f j - f i)) (H _ ij)
noncomputable def cau_seq_re (f : cau_seq ℂ abs) : cau_seq ℝ abs' :=
⟨_, is_cau_seq_re f⟩
noncomputable def cau_seq_im (f : cau_seq ℂ abs) : cau_seq ℝ abs' :=
⟨_, is_cau_seq_im f⟩
lemma is_cau_seq_abs {f : ℕ → ℂ} (hf : is_cau_seq abs f) :
is_cau_seq abs' (abs ∘ f) :=
λ ε ε0, let ⟨i, hi⟩ := hf ε ε0 in
⟨i, λ j hj, lt_of_le_of_lt (abs_abs_sub_le_abs_sub _ _) (hi j hj)⟩
noncomputable def lim_aux (f : cau_seq ℂ abs) : ℂ :=
⟨cau_seq.lim (cau_seq_re f), cau_seq.lim (cau_seq_im f)⟩
theorem equiv_lim_aux (f : cau_seq ℂ abs) : f ≈ cau_seq.const abs (lim_aux f) :=
λ ε ε0, (exists_forall_ge_and
(cau_seq.equiv_lim ⟨_, is_cau_seq_re f⟩ _ (half_pos ε0))
(cau_seq.equiv_lim ⟨_, is_cau_seq_im f⟩ _ (half_pos ε0))).imp $
λ i H j ij, begin
cases H _ ij with H₁ H₂,
apply lt_of_le_of_lt (abs_le_abs_re_add_abs_im _),
dsimp [lim_aux] at *,
have := add_lt_add H₁ H₂,
rwa add_halves at this,
end
noncomputable instance : cau_seq.is_complete ℂ abs :=
⟨λ f, ⟨lim_aux f, equiv_lim_aux f⟩⟩
open cau_seq
lemma lim_eq_lim_im_add_lim_re (f : cau_seq ℂ abs) : lim f =
↑(lim (cau_seq_re f)) + ↑(lim (cau_seq_im f)) * I :=
lim_eq_of_equiv_const $
calc f ≈ _ : equiv_lim_aux f
... = cau_seq.const abs (↑(lim (cau_seq_re f)) + ↑(lim (cau_seq_im f)) * I) :
cau_seq.ext (λ _, complex.ext (by simp [lim_aux, cau_seq_re]) (by simp [lim_aux, cau_seq_im]))
lemma lim_re (f : cau_seq ℂ abs) : lim (cau_seq_re f) = (lim f).re :=
by rw [lim_eq_lim_im_add_lim_re]; simp
lemma lim_im (f : cau_seq ℂ abs) : lim (cau_seq_im f) = (lim f).im :=
by rw [lim_eq_lim_im_add_lim_re]; simp
lemma is_cau_seq_conj (f : cau_seq ℂ abs) : is_cau_seq abs (λ n, conj (f n)) :=
λ ε ε0, let ⟨i, hi⟩ := f.2 ε ε0 in
⟨i, λ j hj, by rw [← conj_sub, abs_conj]; exact hi j hj⟩
noncomputable def cau_seq_conj (f : cau_seq ℂ abs) : cau_seq ℂ abs := ⟨_, is_cau_seq_conj f⟩
lemma lim_conj (f : cau_seq ℂ abs) : lim (cau_seq_conj f) = conj (lim f) :=
complex.ext (by simp [cau_seq_conj, (lim_re _).symm, cau_seq_re])
(by simp [cau_seq_conj, (lim_im _).symm, cau_seq_im, (lim_neg _).symm]; refl)
noncomputable def cau_seq_abs (f : cau_seq ℂ abs) : cau_seq ℝ abs' :=
⟨_, is_cau_seq_abs f.2⟩
lemma lim_abs (f : cau_seq ℂ abs) : lim (cau_seq_abs f) = abs (lim f) :=
lim_eq_of_equiv_const (λ ε ε0,
let ⟨i, hi⟩ := equiv_lim f ε ε0 in
⟨i, λ j hj, lt_of_le_of_lt (abs_abs_sub_le_abs_sub _ _) (hi j hj)⟩)
end complex
|
071ce17f118549bb3bff29b44e3a830a20b5c086 | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/measure_theory/function/continuous_map_dense.lean | f89292c96e26663a29fb02b33346aecebade0250 | [
"Apache-2.0"
] | permissive | jcommelin/mathlib | d8456447c36c176e14d96d9e76f39841f69d2d9b | ee8279351a2e434c2852345c51b728d22af5a156 | refs/heads/master | 1,664,782,136,488 | 1,663,638,983,000 | 1,663,638,983,000 | 132,563,656 | 0 | 0 | Apache-2.0 | 1,663,599,929,000 | 1,525,760,539,000 | Lean | UTF-8 | Lean | false | false | 10,091 | lean | /-
Copyright (c) 2021 Heather Macbeth. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Heather Macbeth
-/
import measure_theory.measure.regular
import measure_theory.function.simple_func_dense_lp
import topology.urysohns_lemma
import measure_theory.function.l1_space
/-!
# Approximation in Lᵖ by continuous functions
This file proves that bounded continuous functions are dense in `Lp E p μ`, for `1 ≤ p < ∞`, if the
domain `α` of the functions is a normal topological space and the measure `μ` is weakly regular.
The result is presented in several versions:
* `measure_theory.Lp.bounded_continuous_function_dense`: The subgroup
`measure_theory.Lp.bounded_continuous_function` of `Lp E p μ`, the additive subgroup of
`Lp E p μ` consisting of equivalence classes containing a continuous representative, is dense in
`Lp E p μ`.
* `bounded_continuous_function.to_Lp_dense_range`: For finite-measure `μ`, the continuous linear
map `bounded_continuous_function.to_Lp p μ 𝕜` from `α →ᵇ E` to `Lp E p μ` has dense range.
* `continuous_map.to_Lp_dense_range`: For compact `α` and finite-measure `μ`, the continuous linear
map `continuous_map.to_Lp p μ 𝕜` from `C(α, E)` to `Lp E p μ` has dense range.
Note that for `p = ∞` this result is not true: the characteristic function of the set `[0, ∞)` in
`ℝ` cannot be continuously approximated in `L∞`.
The proof is in three steps. First, since simple functions are dense in `Lp`, it suffices to prove
the result for a scalar multiple of a characteristic function of a measurable set `s`. Secondly,
since the measure `μ` is weakly regular, the set `s` can be approximated above by an open set and
below by a closed set. Finally, since the domain `α` is normal, we use Urysohn's lemma to find a
continuous function interpolating between these two sets.
## Related results
Are you looking for a result on "directional" approximation (above or below with respect to an
order) of functions whose codomain is `ℝ≥0∞` or `ℝ`, by semicontinuous functions? See the
Vitali-Carathéodory theorem, in the file `measure_theory.vitali_caratheodory`.
-/
open_locale ennreal nnreal topological_space bounded_continuous_function
open measure_theory topological_space continuous_map
variables {α : Type*} [measurable_space α] [topological_space α] [normal_space α] [borel_space α]
variables (E : Type*) [normed_add_comm_group E]
[second_countable_topology_either α E]
variables {p : ℝ≥0∞} [_i : fact (1 ≤ p)] (hp : p ≠ ∞) (μ : measure α)
include _i hp
namespace measure_theory.Lp
variables [normed_space ℝ E]
/-- A function in `Lp` can be approximated in `Lp` by continuous functions. -/
lemma bounded_continuous_function_dense [μ.weakly_regular] :
(bounded_continuous_function E p μ).topological_closure = ⊤ :=
begin
have hp₀ : 0 < p := lt_of_lt_of_le ennreal.zero_lt_one _i.elim,
have hp₀' : 0 ≤ 1 / p.to_real := div_nonneg zero_le_one ennreal.to_real_nonneg,
have hp₀'' : 0 < p.to_real,
{ simpa [← ennreal.to_real_lt_to_real ennreal.zero_ne_top hp] using hp₀ },
-- It suffices to prove that scalar multiples of the indicator function of a finite-measure
-- measurable set can be approximated by continuous functions
suffices : ∀ (c : E) {s : set α} (hs : measurable_set s) (hμs : μ s < ⊤),
(Lp.simple_func.indicator_const p hs hμs.ne c : Lp E p μ)
∈ (bounded_continuous_function E p μ).topological_closure,
{ rw add_subgroup.eq_top_iff',
refine Lp.induction hp _ _ _ _,
{ exact this },
{ exact λ f g hf hg hfg', add_subgroup.add_mem _ },
{ exact add_subgroup.is_closed_topological_closure _ } },
-- Let `s` be a finite-measure measurable set, let's approximate `c` times its indicator function
intros c s hs hsμ,
refine mem_closure_iff_frequently.mpr _,
rw metric.nhds_basis_closed_ball.frequently_iff,
intros ε hε,
-- A little bit of pre-emptive work, to find `η : ℝ≥0` which will be a margin small enough for
-- our purposes
obtain ⟨η, hη_pos, hη_le⟩ : ∃ η, 0 < η ∧ (↑(∥bit0 (∥c∥)∥₊ * (2 * η) ^ (1 / p.to_real)) : ℝ) ≤ ε,
{ have : filter.tendsto (λ x : ℝ≥0, ∥bit0 (∥c∥)∥₊ * (2 * x) ^ (1 / p.to_real)) (𝓝 0) (𝓝 0),
{ have : filter.tendsto (λ x : ℝ≥0, 2 * x) (𝓝 0) (𝓝 (2 * 0)) := filter.tendsto_id.const_mul 2,
convert ((nnreal.continuous_at_rpow_const (or.inr hp₀')).tendsto.comp this).const_mul _,
simp [hp₀''.ne'] },
let ε' : ℝ≥0 := ⟨ε, hε.le⟩,
have hε' : 0 < ε' := by exact_mod_cast hε,
obtain ⟨δ, hδ, hδε'⟩ :=
nnreal.nhds_zero_basis.eventually_iff.mp (eventually_le_of_tendsto_lt hε' this),
obtain ⟨η, hη, hηδ⟩ := exists_between hδ,
refine ⟨η, hη, _⟩,
exact_mod_cast hδε' hηδ },
have hη_pos' : (0 : ℝ≥0∞) < η := ennreal.coe_pos.2 hη_pos,
-- Use the regularity of the measure to `η`-approximate `s` by an open superset and a closed
-- subset
obtain ⟨u, su, u_open, μu⟩ : ∃ u ⊇ s, is_open u ∧ μ u < μ s + ↑η,
{ refine s.exists_is_open_lt_of_lt _ _,
simpa using ennreal.add_lt_add_left hsμ.ne hη_pos' },
obtain ⟨F, Fs, F_closed, μF⟩ : ∃ F ⊆ s, is_closed F ∧ μ s < μ F + ↑η :=
hs.exists_is_closed_lt_add hsμ.ne hη_pos'.ne',
have : disjoint uᶜ F := (Fs.trans su).disjoint_compl_left,
have h_μ_sdiff : μ (u \ F) ≤ 2 * η,
{ have hFμ : μ F < ⊤ := (measure_mono Fs).trans_lt hsμ,
refine ennreal.le_of_add_le_add_left hFμ.ne _,
have : μ u < μ F + ↑η + ↑η,
from μu.trans (ennreal.add_lt_add_right ennreal.coe_ne_top μF),
convert this.le using 1,
{ rw [add_comm, ← measure_union, set.diff_union_of_subset (Fs.trans su)],
exacts [disjoint_sdiff_self_left, F_closed.measurable_set] },
have : (2:ℝ≥0∞) * η = η + η := by simpa using add_mul (1:ℝ≥0∞) 1 η,
rw this,
abel },
-- Apply Urysohn's lemma to get a continuous approximation to the characteristic function of
-- the set `s`
obtain ⟨g, hgu, hgF, hg_range⟩ :=
exists_continuous_zero_one_of_closed u_open.is_closed_compl F_closed this,
-- Multiply this by `c` to get a continuous approximation to the function `f`; the key point is
-- that this is pointwise bounded by the indicator of the set `u \ F`
have g_norm : ∀ x, ∥g x∥ = g x := λ x, by rw [real.norm_eq_abs, abs_of_nonneg (hg_range x).1],
have gc_bd : ∀ x, ∥g x • c - s.indicator (λ x, c) x∥ ≤ ∥(u \ F).indicator (λ x, bit0 ∥c∥) x∥,
{ intros x,
by_cases hu : x ∈ u,
{ rw ← set.diff_union_of_subset (Fs.trans su) at hu,
cases hu with hFu hF,
{ refine (norm_sub_le _ _).trans _,
refine (add_le_add_left (norm_indicator_le_norm_self (λ x, c) x) _).trans _,
have h₀ : g x * ∥c∥ + ∥c∥ ≤ 2 * ∥c∥,
{ nlinarith [(hg_range x).1, (hg_range x).2, norm_nonneg c] },
have h₁ : (2:ℝ) * ∥c∥ = bit0 (∥c∥) := by simpa using add_mul (1:ℝ) 1 (∥c∥),
simp [hFu, norm_smul, h₀, ← h₁, g_norm x] },
{ simp [hgF hF, Fs hF] } },
{ have : x ∉ s := λ h, hu (su h),
simp [hgu hu, this] } },
-- The rest is basically just `ennreal`-arithmetic
have gc_snorm : snorm ((λ x, g x • c) - s.indicator (λ x, c)) p μ
≤ (↑(∥bit0 (∥c∥)∥₊ * (2 * η) ^ (1 / p.to_real)) : ℝ≥0∞),
{ refine (snorm_mono_ae (filter.eventually_of_forall gc_bd)).trans _,
rw snorm_indicator_const (u_open.sdiff F_closed).measurable_set hp₀.ne' hp,
push_cast [← ennreal.coe_rpow_of_nonneg _ hp₀'],
exact ennreal.mul_left_mono (ennreal.monotone_rpow_of_nonneg hp₀' h_μ_sdiff) },
have gc_cont : continuous (λ x, g x • c) := g.continuous.smul continuous_const,
have gc_mem_ℒp : mem_ℒp (λ x, g x • c) p μ,
{ have : mem_ℒp ((λ x, g x • c) - s.indicator (λ x, c)) p μ :=
⟨gc_cont.ae_strongly_measurable.sub (strongly_measurable_const.indicator hs)
.ae_strongly_measurable,
gc_snorm.trans_lt ennreal.coe_lt_top⟩,
simpa using this.add (mem_ℒp_indicator_const p hs c (or.inr hsμ.ne)) },
refine ⟨gc_mem_ℒp.to_Lp _, _, _⟩,
{ rw mem_closed_ball_iff_norm,
refine le_trans _ hη_le,
rw [simple_func.coe_indicator_const, indicator_const_Lp, ← mem_ℒp.to_Lp_sub, Lp.norm_to_Lp],
exact ennreal.to_real_le_coe_of_le_coe gc_snorm },
{ rw [set_like.mem_coe, mem_bounded_continuous_function_iff],
refine ⟨bounded_continuous_function.of_normed_add_comm_group _ gc_cont (∥c∥) _, rfl⟩,
intros x,
have h₀ : g x * ∥c∥ ≤ ∥c∥,
{ nlinarith [(hg_range x).1, (hg_range x).2, norm_nonneg c] },
simp [norm_smul, g_norm x, h₀] },
end
end measure_theory.Lp
variables (𝕜 : Type*) [normed_field 𝕜] [normed_algebra ℝ 𝕜] [normed_space 𝕜 E]
namespace bounded_continuous_function
lemma to_Lp_dense_range [μ.weakly_regular] [is_finite_measure μ] :
dense_range ⇑(to_Lp p μ 𝕜 : (α →ᵇ E) →L[𝕜] Lp E p μ) :=
begin
haveI : normed_space ℝ E := restrict_scalars.normed_space ℝ 𝕜 E,
rw dense_range_iff_closure_range,
suffices : (to_Lp p μ 𝕜 : _ →L[𝕜] Lp E p μ).range.to_add_subgroup.topological_closure = ⊤,
{ exact congr_arg coe this },
simp [range_to_Lp p μ, measure_theory.Lp.bounded_continuous_function_dense E hp],
end
end bounded_continuous_function
namespace continuous_map
lemma to_Lp_dense_range [compact_space α] [μ.weakly_regular] [is_finite_measure μ] :
dense_range ⇑(to_Lp p μ 𝕜 : C(α, E) →L[𝕜] Lp E p μ) :=
begin
haveI : normed_space ℝ E := restrict_scalars.normed_space ℝ 𝕜 E,
rw dense_range_iff_closure_range,
suffices : (to_Lp p μ 𝕜 : _ →L[𝕜] Lp E p μ).range.to_add_subgroup.topological_closure = ⊤,
{ exact congr_arg coe this },
simp [range_to_Lp p μ, measure_theory.Lp.bounded_continuous_function_dense E hp]
end
end continuous_map
|
86ec2a1da6246b79b1987cb8444b47ea2c06e507 | 271e26e338b0c14544a889c31c30b39c989f2e0f | /src/Init/Lean/Meta/Offset.lean | 750a0731e85221aaa46c85c3a0c086ae1ab14e94 | [
"Apache-2.0"
] | permissive | dgorokho/lean4 | 805f99b0b60c545b64ac34ab8237a8504f89d7d4 | e949a052bad59b1c7b54a82d24d516a656487d8a | refs/heads/master | 1,607,061,363,851 | 1,578,006,086,000 | 1,578,006,086,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 3,770 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
prelude
import Init.Lean.Data.LBool
import Init.Lean.Meta.InferType
namespace Lean
namespace Meta
partial def evalNat : Expr → Option Nat
| Expr.lit (Literal.natVal n) _ => pure n
| Expr.mdata _ e _ => evalNat e
| Expr.const `Nat.zero _ _ => pure 0
| e@(Expr.app _ a _) =>
let fn := e.getAppFn;
match fn with
| Expr.const c _ _ =>
let nargs := e.getAppNumArgs;
if c == `Nat.succ && nargs == 1 then do
v ← evalNat a; pure $ v+1
else if c == `Nat.add && nargs == 2 then do
v₁ ← evalNat (e.getArg! 0);
v₂ ← evalNat (e.getArg! 1);
pure $ v₁ + v₂
else if c == `Nat.sub && nargs == 2 then do
v₁ ← evalNat (e.getArg! 0);
v₂ ← evalNat (e.getArg! 1);
pure $ v₁ - v₂
else if c == `Nat.mul && nargs == 2 then do
v₁ ← evalNat (e.getArg! 0);
v₂ ← evalNat (e.getArg! 1);
pure $ v₁ * v₂
else if c == `HasAdd.add && nargs == 4 then do
v₁ ← evalNat (e.getArg! 2);
v₂ ← evalNat (e.getArg! 3);
pure $ v₁ + v₂
else if c == `HasAdd.sub && nargs == 4 then do
v₁ ← evalNat (e.getArg! 2);
v₂ ← evalNat (e.getArg! 3);
pure $ v₁ - v₂
else if c == `HasAdd.mul && nargs == 4 then do
v₁ ← evalNat (e.getArg! 2);
v₂ ← evalNat (e.getArg! 3);
pure $ v₁ * v₂
else
none
| _ => none
| _ => none
/- Quick function for converting `e` into `s + k` s.t. `e` is definitionally equal to `Nat.add s k`. -/
private partial def getOffset : Expr → Expr × Nat
| e@(Expr.app _ a _) =>
let fn := e.getAppFn;
match fn with
| Expr.const c _ _ =>
let nargs := e.getAppNumArgs;
if c == `Nat.succ && nargs == 1 then
let (s, k) := getOffset a;
(s, k+1)
else if c == `Nat.add && nargs == 2 then
match evalNat (e.getArg! 1) with
| none => (e, 0)
| some v =>
let (s, k) := getOffset (e.getArg! 0);
(s, k+v)
else if c == `HasAdd.add && nargs == 4 then
match evalNat (e.getArg! 3) with
| none => (e, 0)
| some v =>
let (s, k) := getOffset (e.getArg! 0);
(s, k+v)
else
(e, 0)
| _ => (e, 0)
| e => (e, 0)
private partial def isOffset : Expr → Option (Expr × Nat)
| e@(Expr.app _ a _) =>
let fn := e.getAppFn;
match fn with
| Expr.const c _ _ =>
let nargs := e.getAppNumArgs;
if (c == `Nat.succ && nargs == 1) || (c == `Nat.add && nargs == 2) || (c == `HasAdd.add && nargs == 4) then
some (getOffset e)
else none
| _ => none
| _ => none
def isDefEqOffset (s t : Expr) : MetaM LBool :=
let isDefEq (s t) : MetaM LBool := toLBoolM $ isExprDefEqAux s t;
match isOffset s with
| some (s, k₁) => match isOffset t with
| some (t, k₂) => -- s+k₁ =?= t+k₂
if k₁ == k₂ then isDefEq s t
else if k₁ < k₂ then isDefEq s (mkAppB (mkConst `Nat.add) t (mkNatLit $ k₂ - k₁))
else isDefEq (mkAppB (mkConst `Nat.add) s (mkNatLit $ k₁ - k₂)) t
| none => match evalNat t with
| some v₂ => -- s+k₁ =?= v₂
if v₂ ≥ k₁ then isDefEq s (mkNatLit $ v₂ - k₁) else pure LBool.false
| none => pure LBool.undef
| none => match evalNat s with
| some v₁ => match isOffset t with
| some (t, k₂) => -- v₁ =?= t+k₂
if v₁ ≥ k₂ then isDefEq s (mkNatLit $ v₁ - k₂) else pure LBool.false
| none => match evalNat t with
| some v₂ => pure (v₁ == v₂).toLBool -- v₁ =?= v₂
| none => pure LBool.undef
| none => pure LBool.undef
end Meta
end Lean
|
e8f43c413a0195087b556b1a239cc8d6ca6060c3 | 3bdd27ffdff3ffa22d4bb010eba695afcc96bc4a | /src/combinatorics/simplicial_complex/to_move/multiset.lean | 027a83d2eb08bffb79bebe94fa21f841b17c6d2e | [] | no_license | mmasdeu/brouwerfixedpoint | 684d712c982c6a8b258b4e2c6b2eab923f2f1289 | 548270f79ecf12d7e20a256806ccb9fcf57b87e2 | refs/heads/main | 1,690,539,793,996 | 1,631,801,831,000 | 1,631,801,831,000 | 368,139,809 | 4 | 3 | null | 1,624,453,250,000 | 1,621,246,034,000 | Lean | UTF-8 | Lean | false | false | 652 | lean | /-
Copyright (c) 2021 Yaël Dillies, Bhavik Mehta. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yaël Dillies, Bhavik Mehta
-/
import data.multiset.basic
import combinatorics.simplicial_complex.to_move.list
lemma multiset.exists_min_of_inf_closed {α : Type*} [semilattice_inf α] {s : multiset α}
(hs₁ : s ≠ 0) (hs₂ : ∀ x y ∈ s, x ⊓ y ∈ s) :
∃ z ∈ s, ∀ y ∈ s, z ≤ y :=
begin
revert hs₁ hs₂,
apply quotient.induction_on s,
intros s hs₁ hs₂,
apply list.exists_min_of_inf_closed _ hs₂,
intro t,
rw ←multiset.coe_eq_zero at t,
apply hs₁ t,
end
|
b7b4d633a3087d4f4d2857ff7ca5c76b28b8edbe | e0f9ba56b7fedc16ef8697f6caeef5898b435143 | /src/order/bounds.lean | 2ba98011011870b5558bfd665e8d6b184c5f089d | [
"Apache-2.0"
] | permissive | anrddh/mathlib | 6a374da53c7e3a35cb0298b0cd67824efef362b4 | a4266a01d2dcb10de19369307c986d038c7bb6a6 | refs/heads/master | 1,656,710,827,909 | 1,589,560,456,000 | 1,589,560,456,000 | 264,271,800 | 0 | 0 | Apache-2.0 | 1,589,568,062,000 | 1,589,568,061,000 | null | UTF-8 | Lean | false | false | 25,086 | 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.set.intervals.basic
/-!
# Upper / lower bounds
In this file we define:
* `upper_bounds`, `lower_bounds` : the set of upper bounds (resp., lower bounds) of a set;
* `bdd_above s`, `bdd_below s` : the set `s` is bounded above (resp., below), i.e., the set of upper
(resp., lower) bounds of `s` is nonempty;
* `is_least s a`, `is_greatest s a` : `a` is a least (resp., greatest) element of `s`;
for a partial order, it is unique if exists;
* `is_lub s a`, `is_glb s a` : `a` is a least upper bound (resp., a greatest lower bound)
of `s`; for a partial order, it is unique if exists.
We also prove various lemmas about monotonicity, behaviour under `∪`, `∩`, `insert`, and provide
formulas for `∅`, `univ`, and intervals.
-/
open set
universes u v w x
variables {α : Type u} {β : Type v} {γ : Type w} {ι : Sort x}
section
variables [preorder α] [preorder β] {s t : set α} {a b : α}
/-!
### Definitions
-/
/-- The set of upper bounds of a set. -/
def upper_bounds (s : set α) : set α := { x | ∀ ⦃a⦄, a ∈ s → a ≤ x }
/-- The set of lower bounds of a set. -/
def lower_bounds (s : set α) : set α := { x | ∀ ⦃a⦄, a ∈ s → x ≤ a }
/-- A set is bounded above if there exists an upper bound. -/
def bdd_above (s : set α) := (upper_bounds s).nonempty
/-- A set is bounded below if there exists a lower bound. -/
def bdd_below (s : set α) := (lower_bounds s).nonempty
/-- `a` is a least element of a set `s`; for a partial order, it is unique if exists. -/
def is_least (s : set α) (a : α) : Prop := a ∈ s ∧ a ∈ lower_bounds s
/-- `a` is a greatest element of a set `s`; for a partial order, it is unique if exists -/
def is_greatest (s : set α) (a : α) : Prop := a ∈ s ∧ a ∈ upper_bounds s
/-- `a` is a least upper bound of a set `s`; for a partial order, it is unique if exists. -/
def is_lub (s : set α) : α → Prop := is_least (upper_bounds s)
/-- `a` is a greatest lower bound of a set `s`; for a partial order, it is unique if exists. -/
def is_glb (s : set α) : α → Prop := is_greatest (lower_bounds s)
/-!
### Monotonicity
-/
lemma upper_bounds_mono_set ⦃s t : set α⦄ (hst : s ⊆ t) :
upper_bounds t ⊆ upper_bounds s :=
λ b hb x h, hb $ hst h
lemma lower_bounds_mono_set ⦃s t : set α⦄ (hst : s ⊆ t) :
lower_bounds t ⊆ lower_bounds s :=
λ b hb x h, hb $ hst h
lemma upper_bounds_mono_mem ⦃a b⦄ (hab : a ≤ b) : a ∈ upper_bounds s → b ∈ upper_bounds s :=
λ ha x h, le_trans (ha h) hab
lemma lower_bounds_mono_mem ⦃a b⦄ (hab : a ≤ b) : b ∈ lower_bounds s → a ∈ lower_bounds s :=
λ hb x h, le_trans hab (hb h)
lemma upper_bounds_mono ⦃s t : set α⦄ (hst : s ⊆ t) ⦃a b⦄ (hab : a ≤ b) :
a ∈ upper_bounds t → b ∈ upper_bounds s :=
λ ha, upper_bounds_mono_set hst $ upper_bounds_mono_mem hab ha
lemma lower_bounds_mono ⦃s t : set α⦄ (hst : s ⊆ t) ⦃a b⦄ (hab : a ≤ b) :
b ∈ lower_bounds t → a ∈ lower_bounds s :=
λ hb, lower_bounds_mono_set hst $ lower_bounds_mono_mem hab hb
/-- If `s ⊆ t` and `t` is bounded above, then so is `s`. -/
lemma bdd_above.mono ⦃s t : set α⦄ (h : s ⊆ t) : bdd_above t → bdd_above s :=
nonempty.mono $ upper_bounds_mono_set h
/-- If `s ⊆ t` and `t` is bounded below, then so is `s`. -/
lemma bdd_below.mono ⦃s t : set α⦄ (h : s ⊆ t) : bdd_below t → bdd_below s :=
nonempty.mono $ lower_bounds_mono_set h
/-- If `a` is a least upper bound for sets `s` and `p`, then it is a least upper bound for any
set `t`, `s ⊆ t ⊆ p`. -/
lemma is_lub.of_subset_of_superset {s t p : set α} (hs : is_lub s a) (hp : is_lub p a)
(hst : s ⊆ t) (htp : t ⊆ p) : is_lub t a :=
⟨upper_bounds_mono_set htp hp.1, lower_bounds_mono_set (upper_bounds_mono_set hst) hs.2⟩
/-- If `a` is a greatest lower bound for sets `s` and `p`, then it is a greater lower bound for any
set `t`, `s ⊆ t ⊆ p`. -/
lemma is_glb.of_subset_of_superset {s t p : set α} (hs : is_glb s a) (hp : is_glb p a)
(hst : s ⊆ t) (htp : t ⊆ p) : is_glb t a :=
@is_lub.of_subset_of_superset (order_dual α) _ a s t p hs hp hst htp
/-!
### Conversions
-/
lemma is_least.is_glb (h : is_least s a) : is_glb s a := ⟨h.2, λ b hb, hb h.1⟩
lemma is_greatest.is_lub (h : is_greatest s a) : is_lub s a := ⟨h.2, λ b hb, hb h.1⟩
lemma is_lub.upper_bounds_eq (h : is_lub s a) : upper_bounds s = Ici a :=
set.ext $ λ b, ⟨λ hb, h.2 hb, λ hb, upper_bounds_mono_mem hb h.1⟩
lemma is_glb.lower_bounds_eq (h : is_glb s a) : lower_bounds s = Iic a :=
@is_lub.upper_bounds_eq (order_dual α) _ _ _ h
lemma is_least.lower_bounds_eq (h : is_least s a) : lower_bounds s = Iic a :=
h.is_glb.lower_bounds_eq
lemma is_greatest.upper_bounds_eq (h : is_greatest s a) : upper_bounds s = Ici a :=
h.is_lub.upper_bounds_eq
/-- If `s` has a least upper bound, then it is bounded above. -/
lemma is_lub.bdd_above (h : is_lub s a) : bdd_above s := ⟨a, h.1⟩
/-- If `s` has a greatest lower bound, then it is bounded below. -/
lemma is_glb.bdd_below (h : is_glb s a) : bdd_below s := ⟨a, h.1⟩
/-- If `s` has a greatest element, then it is bounded above. -/
lemma is_greatest.bdd_above (h : is_greatest s a) : bdd_above s := ⟨a, h.2⟩
/-- If `s` has a least element, then it is bounded below. -/
lemma is_least.bdd_below (h : is_least s a) : bdd_below s := ⟨a, h.2⟩
lemma is_least.nonempty (h : is_least s a) : s.nonempty := ⟨a, h.1⟩
lemma is_greatest.nonempty (h : is_greatest s a) : s.nonempty := ⟨a, h.1⟩
/-!
### Union and intersection
-/
@[simp] lemma upper_bounds_union : upper_bounds (s ∪ t) = upper_bounds s ∩ upper_bounds t :=
subset.antisymm
(λ b hb, ⟨λ x hx, hb (or.inl hx), λ x hx, hb (or.inr hx)⟩)
(λ b hb x hx, hx.elim (λ hs, hb.1 hs) (λ ht, hb.2 ht))
@[simp] lemma lower_bounds_union : lower_bounds (s ∪ t) = lower_bounds s ∩ lower_bounds t :=
@upper_bounds_union (order_dual α) _ s t
lemma union_upper_bounds_subset_upper_bounds_inter :
upper_bounds s ∪ upper_bounds t ⊆ upper_bounds (s ∩ t) :=
union_subset
(upper_bounds_mono_set $ inter_subset_left _ _)
(upper_bounds_mono_set $ inter_subset_right _ _)
lemma union_lower_bounds_subset_lower_bounds_inter :
lower_bounds s ∪ lower_bounds t ⊆ lower_bounds (s ∩ t) :=
@union_upper_bounds_subset_upper_bounds_inter (order_dual α) _ s t
lemma is_least_union_iff {a : α} {s t : set α} :
is_least (s ∪ t) a ↔ (is_least s a ∧ a ∈ lower_bounds t ∨ a ∈ lower_bounds s ∧ is_least t a) :=
by simp [is_least, lower_bounds_union, or_and_distrib_right, and_comm (a ∈ t), and_assoc]
lemma is_greatest_union_iff :
is_greatest (s ∪ t) a ↔ (is_greatest s a ∧ a ∈ upper_bounds t ∨
a ∈ upper_bounds s ∧ is_greatest t a) :=
@is_least_union_iff (order_dual α) _ a s t
/-- If `s` is bounded, then so is `s ∩ t` -/
lemma bdd_above.inter_of_left (h : bdd_above s) : bdd_above (s ∩ t) :=
h.mono $ inter_subset_left s t
/-- If `t` is bounded, then so is `s ∩ t` -/
lemma bdd_above.inter_of_right (h : bdd_above t) : bdd_above (s ∩ t) :=
h.mono $ inter_subset_right s t
/-- If `s` is bounded, then so is `s ∩ t` -/
lemma bdd_below.inter_of_left (h : bdd_below s) : bdd_below (s ∩ t) :=
h.mono $ inter_subset_left s t
/-- If `t` is bounded, then so is `s ∩ t` -/
lemma bdd_below.inter_of_right (h : bdd_below t) : bdd_below (s ∩ t) :=
h.mono $ inter_subset_right s t
/-- If `s` and `t` are bounded above sets in a `semilattice_sup`, then so is `s ∪ t`. -/
lemma bdd_above.union [semilattice_sup γ] {s t : set γ} :
bdd_above s → bdd_above t → bdd_above (s ∪ t) :=
begin
rintros ⟨bs, hs⟩ ⟨bt, ht⟩,
use bs ⊔ bt,
rw upper_bounds_union,
exact ⟨upper_bounds_mono_mem le_sup_left hs,
upper_bounds_mono_mem le_sup_right ht⟩
end
/-- The union of two sets is bounded above if and only if each of the sets is. -/
lemma bdd_above_union [semilattice_sup γ] {s t : set γ} :
bdd_above (s ∪ t) ↔ bdd_above s ∧ bdd_above t :=
⟨λ h, ⟨h.mono $ subset_union_left s t, h.mono $ subset_union_right s t⟩,
λ h, h.1.union h.2⟩
lemma bdd_below.union [semilattice_inf γ] {s t : set γ} :
bdd_below s → bdd_below t → bdd_below (s ∪ t) :=
@bdd_above.union (order_dual γ) _ s t
/--The union of two sets is bounded above if and only if each of the sets is.-/
lemma bdd_below_union [semilattice_inf γ] {s t : set γ} :
bdd_below (s ∪ t) ↔ bdd_below s ∧ bdd_below t :=
@bdd_above_union (order_dual γ) _ s t
/-- If `a` is the least upper bound of `s` and `b` is the least upper bound of `t`,
then `a ⊔ b` is the least upper bound of `s ∪ t`. -/
lemma is_lub.union [semilattice_sup γ] {a b : γ} {s t : set γ}
(hs : is_lub s a) (ht : is_lub t b) :
is_lub (s ∪ t) (a ⊔ b) :=
⟨assume c h, h.cases_on (λ h, le_sup_left_of_le $ hs.left h) (λ h, le_sup_right_of_le $ ht.left h),
assume c hc, sup_le
(hs.right $ assume d hd, hc $ or.inl hd) (ht.right $ assume d hd, hc $ or.inr hd)⟩
/-- If `a` is the greatest lower bound of `s` and `b` is the greatest lower bound of `t`,
then `a ⊓ b` is the greatest lower bound of `s ∪ t`. -/
lemma is_glb.union [semilattice_inf γ] {a₁ a₂ : γ} {s t : set γ}
(hs : is_glb s a₁) (ht : is_glb t a₂) :
is_glb (s ∪ t) (a₁ ⊓ a₂) :=
@is_lub.union (order_dual γ) _ _ _ _ _ hs ht
/-- If `a` is the least element of `s` and `b` is the least element of `t`,
then `min a b` is the least element of `s ∪ t`. -/
lemma is_least.union [decidable_linear_order γ] {a b : γ} {s t : set γ}
(ha : is_least s a) (hb : is_least t b) : is_least (s ∪ t) (min a b) :=
⟨by cases (le_total a b) with h h; simp [h, ha.1, hb.1],
(ha.is_glb.union hb.is_glb).1⟩
/-- If `a` is the greatest element of `s` and `b` is the greatest element of `t`,
then `max a b` is the greatest element of `s ∪ t`. -/
lemma is_greatest.union [decidable_linear_order γ] {a b : γ} {s t : set γ}
(ha : is_greatest s a) (hb : is_greatest t b) : is_greatest (s ∪ t) (max a b) :=
⟨by cases (le_total a b) with h h; simp [h, ha.1, hb.1],
(ha.is_lub.union hb.is_lub).1⟩
/-!
### Specific sets
#### Unbounded intervals
-/
lemma is_least_Ici : is_least (Ici a) a := ⟨left_mem_Ici, λ x, id⟩
lemma is_greatest_Iic : is_greatest (Iic a) a := ⟨right_mem_Iic, λ x, id⟩
lemma is_lub_Iic : is_lub (Iic a) a := is_greatest_Iic.is_lub
lemma is_glb_Ici : is_glb (Ici a) a := is_least_Ici.is_glb
lemma upper_bounds_Iic : upper_bounds (Iic a) = Ici a := is_lub_Iic.upper_bounds_eq
lemma lower_bounds_Ici : lower_bounds (Ici a) = Iic a := is_glb_Ici.lower_bounds_eq
lemma bdd_above_Iic : bdd_above (Iic a) := is_lub_Iic.bdd_above
lemma bdd_below_Ici : bdd_below (Ici a) := is_glb_Ici.bdd_below
lemma bdd_above_Iio : bdd_above (Iio a) := ⟨a, λ x hx, le_of_lt hx⟩
lemma bdd_below_Ioi : bdd_below (Ioi a) := ⟨a, λ x hx, le_of_lt hx⟩
section
variables [linear_order γ] [densely_ordered γ]
lemma is_lub_Iio {a : γ} : is_lub (Iio a) a :=
⟨λ x hx, le_of_lt hx, λ y hy, le_of_forall_ge_of_dense hy⟩
lemma is_glb_Ioi {a : γ} : is_glb (Ioi a) a := @is_lub_Iio (order_dual γ) _ _ a
lemma upper_bounds_Iio {a : γ} : upper_bounds (Iio a) = Ici a := is_lub_Iio.upper_bounds_eq
lemma lower_bounds_Ioi {a : γ} : lower_bounds (Ioi a) = Iic a := is_glb_Ioi.lower_bounds_eq
end
/-!
#### Singleton
-/
lemma is_greatest_singleton : is_greatest {a} a :=
⟨mem_singleton a, λ x hx, le_of_eq $ eq_of_mem_singleton hx⟩
lemma is_least_singleton : is_least {a} a :=
@is_greatest_singleton (order_dual α) _ a
lemma is_lub_singleton : is_lub {a} a := is_greatest_singleton.is_lub
lemma is_glb_singleton : is_glb {a} a := is_least_singleton.is_glb
lemma bdd_above_singleton : bdd_above ({a} : set α) := is_lub_singleton.bdd_above
lemma bdd_below_singleton : bdd_below ({a} : set α) := is_glb_singleton.bdd_below
@[simp] lemma upper_bounds_singleton : upper_bounds {a} = Ici a := is_lub_singleton.upper_bounds_eq
@[simp] lemma lower_bounds_singleton : lower_bounds {a} = Iic a := is_glb_singleton.lower_bounds_eq
/-!
#### Bounded intervals
-/
lemma bdd_above_Icc : bdd_above (Icc a b) := ⟨b, λ _, and.right⟩
lemma bdd_above_Ico : bdd_above (Ico a b) := bdd_above_Icc.mono Ico_subset_Icc_self
lemma bdd_above_Ioc : bdd_above (Ioc a b) := bdd_above_Icc.mono Ioc_subset_Icc_self
lemma bdd_above_Ioo : bdd_above (Ioo a b) := bdd_above_Icc.mono Ioo_subset_Icc_self
lemma is_greatest_Icc (h : a ≤ b) : is_greatest (Icc a b) b :=
⟨right_mem_Icc.2 h, λ x, and.right⟩
lemma is_lub_Icc (h : a ≤ b) : is_lub (Icc a b) b := (is_greatest_Icc h).is_lub
lemma upper_bounds_Icc (h : a ≤ b) : upper_bounds (Icc a b) = Ici b :=
(is_lub_Icc h).upper_bounds_eq
lemma is_least_Icc (h : a ≤ b) : is_least (Icc a b) a :=
⟨left_mem_Icc.2 h, λ x, and.left⟩
lemma is_glb_Icc (h : a ≤ b) : is_glb (Icc a b) a := (is_least_Icc h).is_glb
lemma lower_bounds_Icc (h : a ≤ b) : lower_bounds (Icc a b) = Iic a :=
(is_glb_Icc h).lower_bounds_eq
lemma is_greatest_Ioc (h : a < b) : is_greatest (Ioc a b) b :=
⟨right_mem_Ioc.2 h, λ x, and.right⟩
lemma is_lub_Ioc (h : a < b) : is_lub (Ioc a b) b :=
(is_greatest_Ioc h).is_lub
lemma upper_bounds_Ioc (h : a < b) : upper_bounds (Ioc a b) = Ici b :=
(is_lub_Ioc h).upper_bounds_eq
lemma is_least_Ico (h : a < b) : is_least (Ico a b) a :=
⟨left_mem_Ico.2 h, λ x, and.left⟩
lemma is_glb_Ico (h : a < b) : is_glb (Ico a b) a :=
(is_least_Ico h).is_glb
lemma lower_bounds_Ico (h : a < b) : lower_bounds (Ico a b) = Iic a :=
(is_glb_Ico h).lower_bounds_eq
section
variables [linear_order γ] [densely_ordered γ]
lemma is_glb_Ioo {a b : γ} (hab : a < b) : is_glb (Ioo a b) a :=
begin
refine ⟨λx hx, le_of_lt hx.1, λy hy, le_of_not_lt $ λ h, _⟩,
letI := classical.DLO γ,
have : a < min b y, by { rw lt_min_iff, exact ⟨hab, h⟩ },
rcases dense this with ⟨z, az, zy⟩,
rw lt_min_iff at zy,
exact lt_irrefl _ (lt_of_le_of_lt (hy ⟨az, zy.1⟩) zy.2)
end
lemma lower_bounds_Ioo {a b : γ} (hab : a < b) : lower_bounds (Ioo a b) = Iic a :=
(is_glb_Ioo hab).lower_bounds_eq
lemma is_glb_Ioc {a b : γ} (hab : a < b) : is_glb (Ioc a b) a :=
(is_glb_Ioo hab).of_subset_of_superset (is_glb_Icc $ le_of_lt hab)
Ioo_subset_Ioc_self Ioc_subset_Icc_self
lemma lower_bound_Ioc {a b : γ} (hab : a < b) : lower_bounds (Ioc a b) = Iic a :=
(is_glb_Ioc hab).lower_bounds_eq
lemma is_lub_Ioo {a b : γ} (hab : a < b) : is_lub (Ioo a b) b :=
by simpa only [dual_Ioo] using @is_glb_Ioo (order_dual γ) _ _ b a hab
lemma upper_bounds_Ioo {a b : γ} (hab : a < b) : upper_bounds (Ioo a b) = Ici b :=
(is_lub_Ioo hab).upper_bounds_eq
lemma is_lub_Ico {a b : γ} (hab : a < b) : is_lub (Ico a b) b :=
by simpa only [dual_Ioc] using @is_glb_Ioc (order_dual γ) _ _ b a hab
lemma upper_bounds_Ico {a b : γ} (hab : a < b) : upper_bounds (Ico a b) = Ici b :=
(is_lub_Ico hab).upper_bounds_eq
end
lemma bdd_below_iff_subset_Ici : bdd_below s ↔ ∃ a, s ⊆ Ici a := iff.rfl
lemma bdd_above_iff_subset_Iic : bdd_above s ↔ ∃ a, s ⊆ Iic a := iff.rfl
lemma bdd_below_bdd_above_iff_subset_Icc : bdd_below s ∧ bdd_above s ↔ ∃ a b, s ⊆ Icc a b :=
by simp only [Ici_inter_Iic.symm, subset_inter_iff, bdd_below_iff_subset_Ici,
bdd_above_iff_subset_Iic, exists_and_distrib_left, exists_and_distrib_right]
/-!
### Univ
-/
lemma order_top.upper_bounds_univ [order_top γ] : upper_bounds (univ : set γ) = {⊤} :=
set.ext $ λ b, iff.trans ⟨λ hb, top_unique $ hb trivial, λ hb x hx, hb.symm ▸ le_top⟩
mem_singleton_iff.symm
lemma is_greatest_univ [order_top γ] : is_greatest (univ : set γ) ⊤ :=
by simp only [is_greatest, order_top.upper_bounds_univ, mem_univ, mem_singleton, true_and]
lemma is_lub_univ [order_top γ] : is_lub (univ : set γ) ⊤ :=
is_greatest_univ.is_lub
lemma order_bot.lower_bounds_univ [order_bot γ] : lower_bounds (univ : set γ) = {⊥} :=
@order_top.upper_bounds_univ (order_dual γ) _
lemma is_least_univ [order_bot γ] : is_least (univ : set γ) ⊥ :=
@is_greatest_univ (order_dual γ) _
lemma is_glb_univ [order_bot γ] : is_glb (univ : set γ) ⊥ :=
is_least_univ.is_glb
lemma no_top_order.upper_bounds_univ [no_top_order α] : upper_bounds (univ : set α) = ∅ :=
eq_empty_of_subset_empty $ λ b hb, let ⟨x, hx⟩ := no_top b in
not_le_of_lt hx (hb trivial)
lemma no_bot_order.lower_bounds_univ [no_bot_order α] : lower_bounds (univ : set α) = ∅ :=
@no_top_order.upper_bounds_univ (order_dual α) _ _
/-!
### Empty set
-/
@[simp] lemma upper_bounds_empty : upper_bounds (∅ : set α) = univ :=
by simp only [upper_bounds, eq_univ_iff_forall, mem_set_of_eq, ball_empty_iff, forall_true_iff]
@[simp] lemma lower_bounds_empty : lower_bounds (∅ : set α) = univ :=
@upper_bounds_empty (order_dual α) _
@[simp] lemma bdd_above_empty [nonempty α] : bdd_above (∅ : set α) :=
by simp only [bdd_above, upper_bounds_empty, univ_nonempty]
@[simp] lemma bdd_below_empty [nonempty α] : bdd_below (∅ : set α) :=
by simp only [bdd_below, lower_bounds_empty, univ_nonempty]
lemma is_glb_empty [order_top γ] : is_glb ∅ (⊤:γ) :=
by simp only [is_glb, lower_bounds_empty, is_greatest_univ]
lemma is_lub_empty [order_bot γ] : is_lub ∅ (⊥:γ) :=
@is_glb_empty (order_dual γ) _
lemma is_lub.nonempty [no_bot_order α] (hs : is_lub s a) : s.nonempty :=
let ⟨a', ha'⟩ := no_bot a in
ne_empty_iff_nonempty.1 $ assume h,
have a ≤ a', from hs.right $ by simp only [h, upper_bounds_empty],
not_le_of_lt ha' this
lemma is_glb.nonempty [no_top_order α] (hs : is_glb s a) : s.nonempty :=
@is_lub.nonempty (order_dual α) _ _ _ _ hs
/-!
### insert
-/
/-- Adding a point to a set preserves its boundedness above. -/
@[simp] lemma bdd_above_insert [semilattice_sup γ] (a : γ) {s : set γ} :
bdd_above (insert a s) ↔ bdd_above s :=
by simp only [insert_eq, bdd_above_union, bdd_above_singleton, true_and]
lemma bdd_above.insert [semilattice_sup γ] (a : γ) {s : set γ} (hs : bdd_above s) :
bdd_above (insert a s) :=
(bdd_above_insert a).2 hs
/--Adding a point to a set preserves its boundedness below.-/
@[simp] lemma bdd_below_insert [semilattice_inf γ] (a : γ) {s : set γ} :
bdd_below (insert a s) ↔ bdd_below s :=
by simp only [insert_eq, bdd_below_union, bdd_below_singleton, true_and]
lemma bdd_below.insert [semilattice_inf γ] (a : γ) {s : set γ} (hs : bdd_below s) :
bdd_below (insert a s) :=
(bdd_below_insert a).2 hs
lemma is_lub.insert [semilattice_sup γ] (a) {b} {s : set γ} (hs : is_lub s b) :
is_lub (insert a s) (a ⊔ b) :=
by { rw insert_eq, exact is_lub_singleton.union hs }
lemma is_glb.insert [semilattice_inf γ] (a) {b} {s : set γ} (hs : is_glb s b) :
is_glb (insert a s) (a ⊓ b) :=
by { rw insert_eq, exact is_glb_singleton.union hs }
lemma is_greatest.insert [decidable_linear_order γ] (a) {b} {s : set γ} (hs : is_greatest s b) :
is_greatest (insert a s) (max a b) :=
by { rw insert_eq, exact is_greatest_singleton.union hs }
lemma is_least.insert [decidable_linear_order γ] (a) {b} {s : set γ} (hs : is_least s b) :
is_least (insert a s) (min a b) :=
by { rw insert_eq, exact is_least_singleton.union hs }
@[simp] lemma upper_bounds_insert (a : α) (s : set α) :
upper_bounds (insert a s) = Ici a ∩ upper_bounds s :=
by rw [insert_eq, upper_bounds_union, upper_bounds_singleton]
@[simp] lemma lower_bounds_insert (a : α) (s : set α) :
lower_bounds (insert a s) = Iic a ∩ lower_bounds s :=
by rw [insert_eq, lower_bounds_union, lower_bounds_singleton]
/-- When there is a global maximum, every set is bounded above. -/
@[simp] protected lemma order_top.bdd_above [order_top γ] (s : set γ) : bdd_above s :=
⟨⊤, assume a ha, order_top.le_top a⟩
/-- When there is a global minimum, every set is bounded below. -/
@[simp] protected lemma order_bot.bdd_below [order_bot γ] (s : set γ) : bdd_below s :=
⟨⊥, assume a ha, order_bot.bot_le a⟩
/-!
### Pair
-/
lemma is_lub_pair [semilattice_sup γ] {a b : γ} : is_lub {a, b} (a ⊔ b) :=
by { rw sup_comm, exact is_lub_singleton.insert _}
lemma is_glb_pair [semilattice_inf γ] {a b : γ} : is_glb {a, b} (a ⊓ b) :=
by { rw inf_comm, exact is_glb_singleton.insert _ }
lemma is_least_pair [decidable_linear_order γ] {a b : γ} : is_least {a, b} (min a b) :=
by { rw min_comm, exact is_least_singleton.insert _ }
lemma is_greatest_pair [decidable_linear_order γ] {a b : γ} : is_greatest {a, b} (max a b) :=
by { rw max_comm, exact is_greatest_singleton.insert _ }
end
/-!
### (In)equalities with the least upper bound and the greatest lower bound
-/
section preorder
variables [preorder α] {s : set α} {a b : α}
lemma lower_bounds_le_upper_bounds (ha : a ∈ lower_bounds s) (hb : b ∈ upper_bounds s) :
s.nonempty → a ≤ b
| ⟨c, hc⟩ := le_trans (ha hc) (hb hc)
lemma is_glb_le_is_lub (ha : is_glb s a) (hb : is_lub s b) (hs : s.nonempty) : a ≤ b :=
lower_bounds_le_upper_bounds ha.1 hb.1 hs
lemma is_lub_lt_iff (ha : is_lub s a) : a < b ↔ ∃ c ∈ upper_bounds s, c < b :=
⟨λ hb, ⟨a, ha.1, hb⟩, λ ⟨c, hcs, hcb⟩, lt_of_le_of_lt (ha.2 hcs) hcb⟩
lemma lt_is_glb_iff (ha : is_glb s a) : b < a ↔ ∃ c ∈ lower_bounds s, b < c :=
@is_lub_lt_iff (order_dual α) _ s _ _ ha
end preorder
section partial_order
variables [partial_order α] {s : set α} {a b : α}
lemma is_least.unique (Ha : is_least s a) (Hb : is_least s b) : a = b :=
le_antisymm (Ha.right Hb.left) (Hb.right Ha.left)
lemma is_least.is_least_iff_eq (Ha : is_least s a) : is_least s b ↔ a = b :=
iff.intro Ha.unique (assume h, h ▸ Ha)
lemma is_greatest.unique (Ha : is_greatest s a) (Hb : is_greatest s b) : a = b :=
le_antisymm (Hb.right Ha.left) (Ha.right Hb.left)
lemma is_greatest.is_greatest_iff_eq (Ha : is_greatest s a) : is_greatest s b ↔ a = b :=
iff.intro Ha.unique (assume h, h ▸ Ha)
lemma is_lub.unique (Ha : is_lub s a) (Hb : is_lub s b) : a = b :=
Ha.unique Hb
lemma is_glb.unique (Ha : is_glb s a) (Hb : is_glb s b) : a = b :=
Ha.unique Hb
lemma is_lub_le_iff (h : is_lub s a) : a ≤ b ↔ b ∈ upper_bounds s :=
by { rw h.upper_bounds_eq, refl }
lemma le_is_glb_iff (h : is_glb s a) : b ≤ a ↔ b ∈ lower_bounds s :=
by { rw h.lower_bounds_eq, refl }
end partial_order
section linear_order
variables [linear_order α] {s : set α} {a b : α}
lemma lt_is_lub_iff (h : is_lub s a) : b < a ↔ ∃ c ∈ s, b < c :=
by haveI := classical.dec;
simpa [upper_bounds, not_ball] using
not_congr (@is_lub_le_iff _ _ _ _ b h)
lemma is_glb_lt_iff (h : is_glb s a) : a < b ↔ ∃ c ∈ s, c < b :=
@lt_is_lub_iff (order_dual α) _ _ _ _ h
end linear_order
/-!
### Images of upper/lower bounds under monotone functions
-/
namespace monotone
variables [preorder α] [preorder β] {f : α → β} (Hf : monotone f) {a : α} {s : set α}
lemma mem_upper_bounds_image (Ha : a ∈ upper_bounds s) :
f a ∈ upper_bounds (f '' s) :=
ball_image_of_ball (assume x H, Hf (Ha ‹x ∈ s›))
lemma mem_lower_bounds_image (Ha : a ∈ lower_bounds s) :
f a ∈ lower_bounds (f '' s) :=
ball_image_of_ball (assume x H, Hf (Ha ‹x ∈ s›))
/-- The image under a monotone function of a set which is bounded above is bounded above. -/
lemma map_bdd_above (hf : monotone f) : bdd_above s → bdd_above (f '' s)
| ⟨C, hC⟩ := ⟨f C, hf.mem_upper_bounds_image hC⟩
/-- The image under a monotone function of a set which is bounded below is bounded below. -/
lemma map_bdd_below (hf : monotone f) : bdd_below s → bdd_below (f '' s)
| ⟨C, hC⟩ := ⟨f C, hf.mem_lower_bounds_image hC⟩
/-- A monotone map sends a least element of a set to a least element of its image. -/
lemma map_is_least (Ha : is_least s a) : is_least (f '' s) (f a) :=
⟨mem_image_of_mem _ Ha.1, Hf.mem_lower_bounds_image Ha.2⟩
/-- A monotone map sends a greatest element of a set to a greatest element of its image. -/
lemma map_is_greatest (Ha : is_greatest s a) : is_greatest (f '' s) (f a) :=
⟨mem_image_of_mem _ Ha.1, Hf.mem_upper_bounds_image Ha.2⟩
lemma is_lub_image_le (Ha : is_lub s a) {b : β} (Hb : is_lub (f '' s) b) :
b ≤ f a :=
Hb.2 (Hf.mem_upper_bounds_image Ha.1)
lemma le_is_glb_image_le (Ha : is_glb s a) {b : β} (Hb : is_glb (f '' s) b) :
f a ≤ b :=
Hb.2 (Hf.mem_lower_bounds_image Ha.1)
end monotone
lemma is_glb.of_image [preorder α] [preorder β] {f : α → β} (hf : ∀ {x y}, f x ≤ f y ↔ x ≤ y)
{s : set α} {x : α} (hx : is_glb (f '' s) (f x)) :
is_glb s x :=
⟨λ y hy, hf.1 $ hx.1 $ mem_image_of_mem _ hy,
λ y hy, hf.1 $ hx.2 $ monotone.mem_lower_bounds_image (λ x y, hf.2) hy⟩
lemma is_lub.of_image [preorder α] [preorder β] {f : α → β} (hf : ∀ {x y}, f x ≤ f y ↔ x ≤ y)
{s : set α} {x : α} (hx : is_lub (f '' s) (f x)) :
is_lub s x :=
@is_glb.of_image (order_dual α) (order_dual β) _ _ f (λ x y, hf) _ _ hx
|
7e08c19853683d217f3bd04b5472a68270b70b5b | a726f88081e44db9edfd14d32cfe9c4393ee56a4 | /src/game/world1/level1.lean | cf261cf721241be49553b5349c6aad52acfbf02e | [] | no_license | b-mehta/natural_number_game | 80451bf10277adc89a55dbe8581692c36d822462 | 9faf799d0ab48ecbc89b3d70babb65ba64beee3b | refs/heads/master | 1,598,525,389,186 | 1,573,516,674,000 | 1,573,516,674,000 | 217,339,684 | 0 | 0 | null | 1,571,933,100,000 | 1,571,933,099,000 | null | UTF-8 | Lean | false | false | 3,326 | lean | import mynat.definition -- imports the natural numbers {0,1,2,3,4,...}.
import mynat.add -- imports definition of addition on the natural numbers.
import mynat.mul -- imports definition of multiplication on the natural numbers.
namespace mynat -- hide
-- World name : Tutorial world
/-
# Tutorial World
## Level 1: the `refl` tactic.
Let's learn some tactics! Let's start with the `refl` tactic. `refl` stands for "reflexivity", which is a fancy
way of saying that it will prove any goal of the form `A = A`. It doesn't matter how
complicated `A` is, all that matters is that the left hand side is *exactly equal* to the
right hand side (a computer scientist would say "definitionally equal"). I really mean
"press the same buttons on your computer in the same order" equal.
For example, `x * y + z = x * y + z` can be proved by `refl`, but `x + y = y + x` cannot.
Let's see `refl` in action! At the bottom of the text in this box, there's a lemma,
which says that if $x$, $y$ and $z$ are natural numbers then $xy + z = xy + z$.
Locate this lemma (if you can't see the lemma and these instructions at the same time, make this box wider
by dragging the sides). Let's supply the proof. Click on the word `sorry` and then delete it.
When the system finishes being busy, you'll be able to see your goal -- the objective
of this level -- in the box on the top right. Remember that the goal is
the thing with the weird `⊢` thing just before it. The goal in this case is `x * y + z = x * y + z`,
where `x`, `y` and `z` are some of your very own natural numbers.
That's a pretty easy goal to prove -- you can just prove it with the `refl` tactic.
Where it used to say `sorry`, write
`refl,`
**and don't forget the comma**. Then hit enter to go onto the next line.
If all is well, Lean should tell you "Proof complete!" in the top right box, and there
should be no errors in the bottom right box. You just did the first
level of the tutorial! And you also learnt how to avoid by *far* the most
common mistake that beginner users make -- **every line must end with a comma**.
If things go weird and you don't understand why the top right box is empty,
check for missing commas. Also check you've spelt `refl` correctly: it's REFL
for "reflexivity".
For each level, the idea is to get Lean into this state: with the top right
box saying "Proof complete!" and the bottom right box empty (i.e. with no errors in).
If you want to be reminded about the `refl` tactic, you can click on the "Tactics" drop
down menu on the left. Resize the window if it's too small.
Now click on "next level" in the top right of your browser to go onto the second level of
tutorial world, where we'll learn about the `rw` tactic.
-/
/- Lemma : no-side-bar
For all natural numbers $x$, $y$ and $z$, we have $xy + z = xy + z$.
-/
lemma example1 (x y z : mynat) : x * y + z = x * y + z :=
begin [less_leaky]
refl
end
/- Tactic : refl
## Summary
`refl` proves goals of the form `X = X`.
## Details
The `refl` tactic will close any goal of the form `A = B`
where `A` and `B` are *exactly the same thing*.
### Example:
If it looks like this in the top right hand box:
```
a b c d : mynat
⊢ (a + b) * (c + d) = (a + b) * (c + d)
```
then
`refl,`
will close the goal and solve the level. Don't forget the comma.
-/
end mynat -- hide
|
78827c27dae312f1f29f4d0f201acf0e4d747f43 | 624f6f2ae8b3b1adc5f8f67a365c51d5126be45a | /tmp/eqns/matchArrayLit.lean | 349ccbf588541a0675399dc5c220500726b927c3 | [
"Apache-2.0"
] | permissive | mhuisi/lean4 | 28d35a4febc2e251c7f05492e13f3b05d6f9b7af | dda44bc47f3e5d024508060dac2bcb59fd12e4c0 | refs/heads/master | 1,621,225,489,283 | 1,585,142,689,000 | 1,585,142,689,000 | 250,590,438 | 0 | 2 | Apache-2.0 | 1,602,443,220,000 | 1,585,327,814,000 | C | UTF-8 | Lean | false | false | 7,538 | lean | universes u v
namespace Experiment1
inductive ArrayLitMatch (α : Type u)
| sz0 {} : ArrayLitMatch
| sz1 (a₁ : α) : ArrayLitMatch
| sz2 (a₁ a₂ : α) : ArrayLitMatch
| sz3 (a₁ a₂ a₃ : α) : ArrayLitMatch
| other {} : ArrayLitMatch
def matchArrayLit {α : Type u} (a : Array α) : ArrayLitMatch α :=
if a.size = 0 then
ArrayLitMatch.sz0
else if h : a.size = 1 then
ArrayLitMatch.sz1 (a.getLit 0 h (ofDecideEqTrue rfl))
else if h : a.size = 2 then
ArrayLitMatch.sz2 (a.getLit 0 h (ofDecideEqTrue rfl)) (a.getLit 1 h (ofDecideEqTrue rfl))
else if h : a.size = 3 then
ArrayLitMatch.sz3 (a.getLit 0 h (ofDecideEqTrue rfl)) (a.getLit 1 h (ofDecideEqTrue rfl)) (a.getLit 2 h (ofDecideEqTrue rfl))
else
ArrayLitMatch.other
def matchArrayLit.eq0 {α : Type u} : matchArrayLit (#[] : Array α) = ArrayLitMatch.sz0 :=
rfl
def matchArrayLit.eq1 {α : Type u} (a₁ : α) : matchArrayLit #[a₁] = ArrayLitMatch.sz1 a₁ :=
rfl
def matchArrayLit.eq2 {α : Type u} (a₁ a₂ : α) : matchArrayLit #[a₁, a₂] = ArrayLitMatch.sz2 a₁ a₂ :=
rfl
def matchArrayLit.eq3 {α : Type u} (a₁ a₂ a₃ : α) : matchArrayLit #[a₁, a₂, a₃] = ArrayLitMatch.sz3 a₁ a₂ a₃ :=
rfl
def matchArrayLit.eq4 {α : Type u} (a₁ a₂ a₃ a₄ : α) : matchArrayLit #[a₁, a₂, a₃, a₄] = ArrayLitMatch.other :=
rfl
end Experiment1
def toListLitAux {α : Type u} (a : Array α) (n : Nat) (hsz : a.size = n) : ∀ (i : Nat), i ≤ a.size → List α → List α
| 0, hi, acc => acc
| (i+1), hi, acc => toListLitAux i (Nat.leOfSuccLe hi) (a.getLit i hsz (Nat.ltOfLtOfEq (Nat.ltOfLtOfLe (Nat.ltSuccSelf i) hi) hsz) :: acc)
def toArrayLit {α : Type u} (a : Array α) (n : Nat) (hsz : a.size = n) : Array α :=
List.toArray $ toListLitAux a n hsz n (hsz ▸ Nat.leRefl _) []
theorem toArrayLitEq {α : Type u} (a : Array α) (n : Nat) (hsz : a.size = n) : a = toArrayLit a n hsz :=
-- TODO: this is painful to prove without proper automation
sorry
/-
First, we need to prove
∀ i j acc, i ≤ a.size → (toListLitAux a n hsz (i+1) hi acc).index j = if j < i then a.getLit j hsz _ else acc.index (j - i)
by induction
Base case is trivial
(j : Nat) (acc : List α) (hi : 0 ≤ a.size)
|- (toListLitAux a n hsz 0 hi acc).index j = if j < 0 then a.getLit j hsz _ else acc.index (j - 0)
... |- acc.index j = acc.index j
Induction
(j : Nat) (acc : List α) (hi : i+1 ≤ a.size)
|- (toListLitAux a n hsz (i+1) hi acc).index j = if j < i + 1 then a.getLit j hsz _ else acc.index (j - (i + 1))
... |- (toListLitAux a n hsz i hi' (a.getLit i hsz _ :: acc)).index j = if j < i + 1 then a.getLit j hsz _ else acc.index (j - (i + 1)) * by def
... |- if j < i then a.getLit j hsz _ else (a.getLit i hsz _ :: acc).index (j-i) * by induction hypothesis
=
if j < i + 1 then a.getLit j hsz _ else acc.index (j - (i + 1))
If j < i, then both are a.getLit j hsz _
If j = i, then lhs reduces else-branch to (a.getLit i hsz _) and rhs is then-brachn (a.getLit i hsz _)
If j >= i + 1, we use
- j - i >= 1 > 0
- (a::as).index k = as.index (k-1) If k > 0
- j - (i + 1) = (j - i) - 1
Then lhs = (a.getLit i hsz _ :: acc).index (j-i) = acc.index (j-i-1) = acc.index (j-(i+1)) = rhs
With this proof, we have
∀ j, j < n → (toListLitAux a n hsz n _ []).index j = a.getLit j hsz _
We also need
- (toListLitAux a n hsz n _ []).length = n
- j < n -> (List.toArray as).getLit j _ _ = as.index j
Then using Array.extLit, we have that a = List.toArray $ toListLitAux a n hsz n _ []
-/
theorem Array.eqLitOfSize0 {α : Type u} (a : Array α) (hsz : a.size = 0) : a = #[] :=
toArrayLitEq a 0 hsz
/-
Array.ext a #[] h (fun i h₁ h₂ => absurd h₂ (Nat.notLtZero _))
-/
theorem Array.eqLitOfSize1 {α : Type u} (a : Array α) (hsz : a.size = 1) : a = #[a.getLit 0 hsz (ofDecideEqTrue rfl)] :=
toArrayLitEq a 1 hsz
/-
Array.extLit a #[a.getLit 0 hsz (ofDecideEqTrue rfl)] hsz rfl $ fun i =>
match i with
| 0 => fun hi => rfl
| (n+1) => fun hi =>
have n < 0 from hi;
absurd this (Nat.notLtZero _)
-/
theorem Array.eqLitOfSize2 {α : Type u} (a : Array α) (hsz : a.size = 2) : a = #[a.getLit 0 hsz (ofDecideEqTrue rfl), a.getLit 1 hsz (ofDecideEqTrue rfl)] :=
toArrayLitEq a 2 hsz
/-
Array.extLit a #[a.getLit 0 hsz (ofDecideEqTrue rfl), a.getLit 1 hsz (ofDecideEqTrue rfl)] hsz rfl $ fun i =>
match i with
| 0 => fun hi => rfl
| 1 => fun hi => rfl
| (n+2) => fun hi =>
have n < 0 from hi;
absurd this (Nat.notLtZero _)
-/
theorem Array.eqLitOfSize3 {α : Type u} (a : Array α) (hsz : a.size = 3) :
a = #[a.getLit 0 hsz (ofDecideEqTrue rfl), a.getLit 1 hsz (ofDecideEqTrue rfl), a.getLit 2 hsz (ofDecideEqTrue rfl)] :=
toArrayLitEq a 3 hsz
/-
Array.extLit a #[a.getLit 0 hsz (ofDecideEqTrue rfl), a.getLit 1 hsz (ofDecideEqTrue rfl), a.getLit 2 hsz (ofDecideEqTrue rfl)] hsz rfl $ fun i =>
match i with
| 0 => fun hi => rfl
| 1 => fun hi => rfl
| 2 => fun hi => rfl
| (n+3) => fun hi =>
have n < 0 from hi;
absurd this (Nat.notLtZero _)
-/
/-
Matcher for the following patterns
```
| #[] => _
| #[a₁] => _
| #[a₁, a₂, a₃] => _
| a => _
``` -/
def matchArrayLit {α : Type u} (C : Array α → Sort v) (a : Array α)
(h₁ : Unit → C #[])
(h₂ : ∀ a₁, C #[a₁])
(h₃ : ∀ a₁ a₂ a₃, C #[a₁, a₂, a₃])
(h₄ : ∀ a, C a)
: C a :=
if h : a.size = 0 then
@Eq.rec _ _ (fun x _ => C x) (h₁ ()) _ (toArrayLitEq a 0 h).symm
else if h : a.size = 1 then
@Eq.rec _ _ (fun x _ => C x) (h₂ (a.getLit 0 h (ofDecideEqTrue rfl))) _ (toArrayLitEq a 1 h).symm
else if h : a.size = 3 then
@Eq.rec _ _ (fun x _ => C x) (h₃ (a.getLit 0 h (ofDecideEqTrue rfl)) (a.getLit 1 h (ofDecideEqTrue rfl)) (a.getLit 2 h (ofDecideEqTrue rfl))) _ (toArrayLitEq a 3 h).symm
else
h₄ a
/- Equational lemmas that should be generated automatically. -/
theorem matchArrayLit.eq1 {α : Type u} (C : Array α → Sort v)
(h₁ : Unit → C #[])
(h₂ : ∀ a₁, C #[a₁])
(h₃ : ∀ a₁ a₂ a₃, C #[a₁, a₂, a₃])
(h₄ : ∀ a, C a)
: matchArrayLit C #[] h₁ h₂ h₃ h₄ = h₁ () :=
rfl
theorem matchArrayLit.eq2 {α : Type u} (C : Array α → Sort v)
(h₁ : Unit → C #[])
(h₂ : ∀ a₁, C #[a₁])
(h₃ : ∀ a₁ a₂ a₃, C #[a₁, a₂, a₃])
(h₄ : ∀ a, C a)
(a₁ : α)
: matchArrayLit C #[a₁] h₁ h₂ h₃ h₄ = h₂ a₁ :=
rfl
theorem matchArrayLit.eq3 {α : Type u} (C : Array α → Sort v)
(h₁ : Unit → C #[])
(h₂ : ∀ a₁, C #[a₁])
(h₃ : ∀ a₁ a₂ a₃, C #[a₁, a₂, a₃])
(h₄ : ∀ a, C a)
(a₁ a₂ a₃ : α)
: matchArrayLit C #[a₁, a₂, a₃] h₁ h₂ h₃ h₄ = h₃ a₁ a₂ a₃ :=
rfl
theorem matchArrayLit.eq4 {α : Type u} (C : Array α → Sort v)
(h₁ : Unit → C #[])
(h₂ : ∀ a₁, C #[a₁])
(h₃ : ∀ a₁ a₂ a₃, C #[a₁, a₂, a₃])
(h₄ : ∀ a, C a)
(a : Array α)
(n₁ : a.size ≠ 0) (n₂ : a.size ≠ 1) (n₃ : a.size ≠ 3)
: matchArrayLit C a h₁ h₂ h₃ h₄ = h₄ a :=
match a, n₁, n₂, n₃ with
| ⟨0, _⟩, n₁, _, _ => absurd rfl n₁
| ⟨1, _⟩, _, n₂, _ => absurd rfl n₂
| ⟨2, _⟩, _, _, _ => rfl
| ⟨3, _⟩, _, _, n₃ => absurd rfl n₃
| ⟨n+4, _⟩, _, _, _ => rfl
|
9c1b485a26b1a9ff13b632475701fef72d5aa423 | 05d69962fb9deab19838de9bbcf33ebdbf8faa57 | /aux.lean | bf25ed0c356ed017df5dc492fbb00912baff4c6e | [] | no_license | pj0y1/polynom | 6eb7c96dbf34960be5721a232a67f7a592aedf7a | 9e198cc9104017fae7774574f141197bb295ee66 | refs/heads/master | 1,611,193,417,139 | 1,501,472,138,000 | 1,501,472,138,000 | 64,856,946 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 13,760 | lean | /-
finset product and set product
some theorems with ' denoting prod version, for convenience
some disjoint properties of set, orginally in m15.lean
-/
import data.set data.finset.comb
import algebra.group_bigops
open set classical prod.ops
variables {A B:Type}{a:A}{b:B}{x:A×B}
namespace set
definition product (s: set A)(t: set B) : set (A × B) :=
λ x, x.1 ∈ s ∧ x.2 ∈ t
notation a * b := product a b
end set
namespace finset
open [notation]set
variables {s s1:finset A}{t t1: finset B}
theorem mem_product_iff: ((a,b)∈s*t) ↔ (a∈s∧b∈t) :=
iff.intro
(λl,and.intro(mem_of_mem_product_left l)(mem_of_mem_product_right l))
(λr,mem_product (and.left r)(and.right r))
theorem mem_product_iff': x∈s*t ↔ x.1∈s∧x.2∈t :=
match x with (m, n) := !mem_product_iff end
theorem mem_product_eq: ((a,b)∈s*t) = (a∈s∧b∈t) :=
propext (!mem_product_iff)
theorem mem_product_eq': x∈s*t = (x.1∈s∧x.2∈t):=
match x with (a,b) := propext (!mem_product_iff) end
theorem mem_to_set_product: ((a,b)∈s*t) = (a∈to_set s∧b∈to_set t):=
!mem_product_eq
theorem mem_to_set_product': x∈ s*t = (x.1∈to_set s∧x.2∈to_set t):=
match x with (a,b) := !mem_product_eq end
theorem to_set_product': to_set (s*t) = (to_set s)*(to_set t) :=
funext (λ x, match x with (a,b) := !mem_to_set_product end)
/-finset product singleton, originally in m14.lean-/
theorem singleton_of_singleton_product:'{a}*'{b} = '{(a,b)} :=
ext (take x, match x with (u,v) := iff.intro
(assume l,
have hu:u ∈ '{a}, from mem_of_mem_product_left l,
have hv:v ∈ '{b}, from mem_of_mem_product_right l,
mem_product hu hv)
(assume r,
have H:(u,v) = (a,b), from eq_of_mem_singleton r,
have (u,v).1 = (a,b).1, by rewrite H,
have u = a, from this,
have hu: u ∈ '{a}, from mem_singleton_of_eq this,
have (u,v).2 = (a,b).2, by rewrite H,
have v = b, from this,
have hv: v ∈ '{b}, from mem_singleton_of_eq this,
mem_product hu hv)
end)
namespace product --originally defined in m13.lean
variables [deceqA : decidable_eq A][deceqB: decidable_eq B]
local attribute prod.has_decidable_eq [instance]
/- Union distribution-/
include deceqA deceqB
theorem union_right_distrib : s*( t1 ∪ t) = s*t1 ∪ s*t :=
ext (take x, match x with (u,v) := iff.intro
(assume l, have u∈s∧v∈(t1∪t), by rewrite -mem_product_eq;exact l,
have hu: u ∈ s, from and.left this,
have hv: v ∈ t1 ∨ v ∈ t,
by rewrite -mem_union_eq;apply and.right this,
or.elim hv (assume h, mem_union_l (mem_product hu h))
(assume h, mem_union_r (mem_product hu h)))
(assume r, have (u,v)∈ s*t1∨(u,v)∈s*t,
by rewrite -mem_union_eq;exact r,
or.elim this
(assume h, have hu:u ∈s, from mem_of_mem_product_left h,
have v ∈ t1, from mem_of_mem_product_right h,
have hv: v∈ t1∪t, from mem_union_l this,
mem_product hu hv)
(assume h, have hu:u ∈s, from mem_of_mem_product_left h,
have v ∈ t, from mem_of_mem_product_right h,
have hv:v ∈t1∪t, from mem_union_r this,
mem_product hu hv))
end)
-- corollary c1:'{a}*(insert b t) = '{a}*'{b} ∪ '{a}*t :=
-- by rewrite {insert b t}insert_eq; apply union_right_distrib
theorem union_left_distrib: (s∪s1)*t = s*t ∪ s1*t :=
ext ( take x, match x with (u,v) := iff.intro
(assume l,
have hu: u∈s∨u∈s1, by rewrite -mem_union_eq;
apply mem_of_mem_product_left l,
have hv: v∈t, from mem_of_mem_product_right l,
or.elim hu
(assume h, mem_union_l (mem_product h hv))
(assume h, mem_union_r (mem_product h hv)))
(assume r,
have (u,v)∈s*t∨(u,v)∈s1*t,
by rewrite -mem_union_eq;exact r,
or.elim this
(assume h, have u∈s, from mem_of_mem_product_left h,
have hu:u∈s∪s1, from mem_union_l this,
have hv: v∈t, from mem_of_mem_product_right h,
mem_product hu hv)
(assume h, have u∈s1, from mem_of_mem_product_left h,
have hu: u∈s∪s1, from mem_union_r this,
have hv: v∈t, from mem_of_mem_product_right h,
mem_product hu hv))
end)
--corollary c2:(insert a s)*'{b} = '{a}*'{b} ∪ s*'{b} :=
--by rewrite {insert a s}insert_eq; apply union_left_distrib
-- lemma l1:(insert a s)*(insert b t) = '{a}*(insert b t)∪ s*(insert b t):=
-- by rewrite {insert a s}insert_eq; apply union_left_distrib
--lemma l2:'{a}*(insert b t)∪ s*(insert b t)='{a}*'{b}∪'{a}*t∪s*(insert b t):=
--by rewrite [{insert b t}insert_eq, *union_right_distrib]
--theorem t3: (insert a s)*(insert b t)= '{a}*'{b}∪'{a}*t∪ s*'{b}∪s*t :=
--by rewrite [l1,l2,{insert b t}insert_eq, *union_right_distrib,*union_assoc]
/-Jul 11: finished finset product union distribution-/
/-NEXT: disjointness!-/
theorem disjoint_of_disjoint_left (H: s∩s1=∅):(s*t) ∩ (s1*t) = ∅ :=
by_contradiction
( assume h: ¬ ((s*t) ∩ (s1*t) = ∅),
have (s*t) ∩ (s1*t) ≠ ∅, from h,
show false, from
(exists.elim (exists_mem_of_ne_empty this)
(λ (x:A×B) (hx: x∈ (s*t) ∩ (s1*t)),
have h1: x∈s*t, from mem_of_mem_inter_left hx,
have h2: x∈s1*t,from mem_of_mem_inter_right hx,
have h3: x.1∈s, from and.left ((iff.mp mem_product_iff') h1),
have h4: x.1∈s1, from and.left ((iff.mp mem_product_iff') h2),
have x.1∈s∩s1,from mem_inter h3 h4,
have x.1∈∅, by rewrite [H at this];exact this,
show false, by rewrite [mem_empty_eq at this];exact this)))
--corollary c3(H:a∉s):('{a}*t) ∩ (s*t) = ∅ :=
--by apply l3; apply singleton_inter_of_not_mem H
theorem disjoint_of_disjoint_right (H: t∩t1 = ∅):(s*t)∩(s*t1) = ∅:=
by_contradiction
( assume h: ¬ ((s*t) ∩ (s*t1) = ∅),
have (s*t) ∩ (s*t1) ≠ ∅, from h,
show false, from
(exists.elim (exists_mem_of_ne_empty this)
(λ (x:A×B) (hx: x∈ (s*t) ∩ (s*t1)),
have h1: x∈s*t, from mem_of_mem_inter_left hx,
have h2: x∈s*t1,from mem_of_mem_inter_right hx,
have h3: x.2∈t, from and.right ((iff.mp mem_product_iff') h1),
have h4: x.2∈t1, from and.right ((iff.mp mem_product_iff') h2),
have x.2∈t∩t1,from mem_inter h3 h4,
have x.1∈∅, by rewrite [H at this];exact this,
show false, by rewrite [mem_empty_eq at this];exact this)))
--corollary c4(H:b∉t):(s*'{b})∩(s*t) =∅ :=
--by apply l4;apply singleton_inter_of_not_mem H
end product
end finset
namespace set
variables {s s₁:set A}{t: set B}
theorem finite_product[instance][finite s][finite t]:finite (s*t):=
exists.intro (#finset to_finset s * to_finset t)
(by rewrite [finset.to_set_product',*to_set_to_finset])
theorem mem_product: a ∈ s → b ∈ t → (a, b) ∈ s*t :=
λ p q, and.intro p q
theorem mem_of_mem_product_left: (a,b) ∈ s*t → a ∈ s :=
λ p, and.left p
theorem mem_of_mem_product_left': x∈ s*t -> x.1∈s :=
λ p, and.left p
theorem mem_of_mem_product_right: (a,b) ∈ s*t → b ∈t :=
λ p, and.right p
theorem mem_of_mem_product_right': x∈ s*t -> x.2∈t :=
λ p, and.right p
theorem empty_product : @empty A * t = ∅ :=
by_contradiction (assume h: ¬ @empty A * t = ∅,
have @empty A * t ≠ ∅, from h, show false, from
obtain (x:A×B)(hx: x∈@empty A * t), from exists_mem_of_ne_empty this,
have x.1 ∈ @empty A, from mem_of_mem_product_left' hx,
by rewrite [(mem_empty_eq x.1) at this];exact this)
theorem product_empty : s * @empty B = ∅ :=
by_contradiction (assume h: ¬ s * @empty B = ∅,
have s * @empty B ≠ ∅, from h, show false, from
obtain (x:A×B)(hx: x∈s * @empty B), from exists_mem_of_ne_empty this,
have x.2 ∈ @empty B, from mem_of_mem_product_right' hx,
by rewrite [(mem_empty_eq x.2) at this];exact this)
theorem mem_product_iff: ((a,b) ∈ s*t) ↔ (a ∈ s ∧ b ∈ t) :=
iff.intro
(λ H,and.intro (mem_of_mem_product_left H) (mem_of_mem_product_right H))
(λ H', mem_product (and.left H') (and.right H'))
theorem mem_product_iff': x ∈ s*t ↔ x.1 ∈ s ∧ x.2 ∈ t :=
match x with (m, n) := !mem_product_iff end
theorem mem_product_eq: ((a,b) ∈ s * t) = (a ∈ s ∧ b ∈ t) :=
propext (!mem_product_iff)
theorem mem_product_eq': x∈ s*t = (x.1 ∈s ∧ x.2 ∈ t):=
propext (!mem_product_iff')
open [notation] finset
theorem mem_to_finset_product_left [finite s](h:(a,b)∈ s*t):
a∈to_finset s :=
by rewrite [(mem_to_finset_eq a s)];apply (mem_of_mem_product_left h)
theorem mem_to_finset_product_right [finite t](h:(a,b)∈ s*t):
b∈ to_finset t :=
by rewrite [(mem_to_finset_eq b t)];apply (mem_of_mem_product_right h)
theorem mem_product_of_mem_to_finset [finite s][finite t]
(h1: a∈ to_finset s)(h2: b ∈ to_finset t):(a,b)∈s*t :=
by rewrite [(mem_to_finset_eq b t) at h2, (mem_to_finset_eq a s) at h1];
apply mem_product h1 h2
theorem mem_to_finset_product [finite s][finite t]:
((a,b) ∈ s * t) = (a ∈ to_finset s ∧ b ∈ to_finset t) :=
propext (iff.intro (assume l, and.intro (mem_to_finset_product_left l)
(mem_to_finset_product_right l))
(assume r, mem_product_of_mem_to_finset (and.left r) (and.right r)))
theorem mem_to_finset_product' [finite s] [finite t]:
x∈ s*t = (x.1 ∈ to_finset s ∧ x.2 ∈ to_finset t) :=
match x with (a,b) := !mem_to_finset_product end
theorem to_finset_product [finite s][finite t]:
to_finset (s * t) = finset.product (to_finset s) (to_finset t) :=
have h:finite (s*t), from finite_product,
finset.ext (λ x, iff.intro
(assume l, have x∈s*t,
by rewrite [(mem_to_finset_eq x (s*t)) at l];exact l,
have x.1 ∈ to_finset s ∧ x.2 ∈ to_finset t,
by rewrite [mem_to_finset_product' at this];exact this,
show x∈(to_finset s)*(to_finset t),
by rewrite [-finset.mem_product_eq' at this];exact this)
(assume r,
have x∈ s*t,
by rewrite [finset.mem_product_eq' at r,-mem_to_finset_product' at r];
exact r,
show x∈ to_finset (s*t),
by rewrite (mem_to_finset_eq x (s*t));exact this))
/-disjoint and inter-/
theorem inter_union_diff_cancel: s₁ = (s₁∩s) ∪ (s₁\s) :=
ext (take x, iff.intro
(assume l, or.elim (em (x∈s))
(assume h, mem_unionl (mem_inter l h))
(assume h, mem_unionr (mem_diff l h)))
(assume r, or.elim r
(assume h, mem_of_mem_inter_left h)
(assume h, mem_of_mem_diff h)))
theorem inter_inter_diff_empty: (s₁∩s) ∩ (s₁\s) = ∅ :=
by_contradiction (assume h: (s₁∩s)∩(s₁\s) ≠ ∅,
obtain (x:A)(hx: x∈(s₁∩s)∩(s₁\s)), from exists_mem_of_ne_empty h,
have x∈(s₁∩s)∧x∈(s₁\s), by rewrite [mem_inter_eq at hx];exact hx,
have x∈s, from mem_of_mem_inter_right (and.left this),
have hn: x∉s, from not_mem_of_mem_diff (and.right hx),
show false, from absurd this hn)
theorem diff_inter_self_empty: (s₁\s)∩s = ∅ :=
by rewrite [(diff_eq s₁ s),inter_assoc,compl_inter_self,inter_empty]
theorem subset_inter_eq_self (h:s⊆s₁): s₁∩s = s :=
have s⊆s, from λx h, h,
have h1:s⊆s₁∩s, from subset_inter h this,
have h2:s₁∩s⊆s, from inter_subset_right s₁ s,
subset.antisymm h2 h1
/- image and preimage -/
theorem empty_preimage_of_empty_image {f:A -> B}(h:t=∅):
f '- t = ∅ :=
by_contradiction assume hne,
have f '- t ≠ ∅, from hne,
obtain (a:A)(ha: a∈ f '- t), from exists_mem_of_ne_empty this,
have f a ∈ t, from mem_of_mem_preimage ha,
have t≠∅, from ne_empty_of_mem this,
absurd h this
theorem empty_of_empty_image {f:A -> B}(h: f ' s = ∅):
s = ∅ :=
by_contradiction assume hne,
have s≠∅, from hne,
obtain (a:A)(ha: a∈s), from exists_mem_of_ne_empty this,
have f a ∈ f ' s, from mem_image_of_mem f ha,
have f ' s ≠ ∅, from ne_empty_of_mem this,
absurd h this
theorem exists_mem_of_mem_image {f:A->B}(h:b∈ f ' s):
∃a,a∈s∧f a = b := h
/- singleton -/
theorem eq_singleton_iff_all_eq (h: ∀x:A, x∈s ↔ x = a): s = '{a} :=
ext (take x, iff.intro
(assume l, mem_singleton_of_eq (iff.mp (h x) l))
(assume r, have heq:x=a, from eq_of_mem_singleton r,
iff.mpr (h x) heq))
theorem singleton_of_all_eq_of_ne_empty(h: ∀x:A, x∈s -> x = a)(g: s≠∅):
s = '{a}:=
ext (take x, iff.intro
(assume l, mem_singleton_of_eq (h x l))
(assume r, have heq:x=a, from eq_of_mem_singleton r,
obtain (u:A)(hu:u∈s), from exists_mem_of_ne_empty g,
have u=a, from h u hu, show x∈s, by rewrite [heq,-this];exact hu))
theorem empty_or_singleton_of_inter_singleton: s∩'{a} = ∅ ∨ s∩'{a} = '{a} :=
or.elim (em (s∩'{a} = ∅))
(λh, or.inl h)
(λh,have h1: s∩'{a}⊆'{a}, from inter_subset_right s '{a},
have h2:s∩'{a}≠∅, from h,
or.inr (singleton_of_all_eq_of_ne_empty
(λx hx, have x∈'{a}, from mem_of_subset_of_mem h1 hx,
show x=a, from eq_of_mem_singleton this) h2))
/- singleton image -/
theorem singleton_image {f:A-> B}(h: f ' s = '{b}):
∀x, x∈s -> f x = b :=
λ x hs, have f x ∈ f ' s, from mem_image_of_mem f hs,
have f x ∈ '{b}, by rewrite h at this;exact this,
show f x = b, from eq_of_mem_singleton this
theorem singleton_image' {f:A->B}(h: f ' s = '{b}):
∀x, x∈s -> b = f x :=
λ x hs, eq.symm (singleton_image h x hs)
end set
|
c4d36e6f4b2154a0f05391ef0a41845dd991d8a1 | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/algebra/ring/basic.lean | cc544997fe7e139b755e07ebf6544e467d33ae3f | [
"Apache-2.0"
] | permissive | jcommelin/mathlib | d8456447c36c176e14d96d9e76f39841f69d2d9b | ee8279351a2e434c2852345c51b728d22af5a156 | refs/heads/master | 1,664,782,136,488 | 1,663,638,983,000 | 1,663,638,983,000 | 132,563,656 | 0 | 0 | Apache-2.0 | 1,663,599,929,000 | 1,525,760,539,000 | Lean | UTF-8 | Lean | false | false | 56,995 | lean | /-
Copyright (c) 2014 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Leonardo de Moura, Floris van Doorn, Yury Kudryashov, Neil Strickland
-/
import algebra.divisibility
import algebra.regular.basic
import data.int.cast.defs
import data.pi.algebra
/-!
# Semirings and rings
This file defines semirings, rings and domains. This is analogous to `algebra.group.defs` and
`algebra.group.basic`, the difference being that the former is about `+` and `*` separately, while
the present file is about their interaction.
## Main definitions
* `distrib`: Typeclass for distributivity of multiplication over addition.
* `has_distrib_neg`: Typeclass for commutativity of negation and multiplication. This is useful when
dealing with multiplicative submonoids which are closed under negation without being closed under
addition, for example `units`.
* `(non_unital_)(non_assoc_)(semi)ring`: Typeclasses for possibly non-unital or non-associative
rings and semirings. Some combinations are not defined yet because they haven't found use.
## Tags
`semiring`, `comm_semiring`, `ring`, `comm_ring`, `domain`, `is_domain`, `nonzero`, `units`
-/
universes u v w x
variables {α : Type u} {β : Type v} {γ : Type w} {R : Type x}
set_option old_structure_cmd true
open function
/-!
### `distrib` class
-/
/-- A typeclass stating that multiplication is left and right distributive
over addition. -/
@[protect_proj, ancestor has_mul has_add]
class distrib (R : Type*) extends has_mul R, has_add R :=
(left_distrib : ∀ a b c : R, a * (b + c) = a * b + a * c)
(right_distrib : ∀ a b c : R, (a + b) * c = a * c + b * c)
/-- A typeclass stating that multiplication is left distributive over addition. -/
@[protect_proj]
class left_distrib_class (R : Type*) [has_mul R] [has_add R] :=
(left_distrib : ∀ a b c : R, a * (b + c) = a * b + a * c)
/-- A typeclass stating that multiplication is right distributive over addition. -/
@[protect_proj]
class right_distrib_class (R : Type*) [has_mul R] [has_add R] :=
(right_distrib : ∀ a b c : R, (a + b) * c = a * c + b * c)
@[priority 100] -- see Note [lower instance priority]
instance distrib.left_distrib_class (R : Type*) [distrib R] : left_distrib_class R :=
⟨distrib.left_distrib⟩
@[priority 100] -- see Note [lower instance priority]
instance distrib.right_distrib_class (R : Type*) [distrib R] : right_distrib_class R :=
⟨distrib.right_distrib⟩
lemma left_distrib [has_mul R] [has_add R] [left_distrib_class R] (a b c : R) :
a * (b + c) = a * b + a * c :=
left_distrib_class.left_distrib a b c
alias left_distrib ← mul_add
lemma right_distrib [has_mul R] [has_add R] [right_distrib_class R] (a b c : R) :
(a + b) * c = a * c + b * c :=
right_distrib_class.right_distrib a b c
alias right_distrib ← add_mul
lemma distrib_three_right [has_mul R] [has_add R] [right_distrib_class R] (a b c d : R) :
(a + b + c) * d = a * d + b * d + c * d :=
by simp [right_distrib]
/-- Pullback a `distrib` instance along an injective function.
See note [reducible non-instances]. -/
@[reducible]
protected def function.injective.distrib {S} [has_mul R] [has_add R] [distrib S]
(f : R → S) (hf : injective f) (add : ∀ x y, f (x + y) = f x + f y)
(mul : ∀ x y, f (x * y) = f x * f y) :
distrib R :=
{ mul := (*),
add := (+),
left_distrib := λ x y z, hf $ by simp only [*, left_distrib],
right_distrib := λ x y z, hf $ by simp only [*, right_distrib] }
/-- Pushforward a `distrib` instance along a surjective function.
See note [reducible non-instances]. -/
@[reducible]
protected def function.surjective.distrib {S} [distrib R] [has_add S] [has_mul S]
(f : R → S) (hf : surjective f) (add : ∀ x y, f (x + y) = f x + f y)
(mul : ∀ x y, f (x * y) = f x * f y) :
distrib S :=
{ mul := (*),
add := (+),
left_distrib := hf.forall₃.2 $ λ x y z, by simp only [← add, ← mul, left_distrib],
right_distrib := hf.forall₃.2 $ λ x y z, by simp only [← add, ← mul, right_distrib] }
/-!
### Semirings
-/
/-- A not-necessarily-unital, not-necessarily-associative semiring. -/
@[protect_proj, ancestor add_comm_monoid distrib mul_zero_class]
class non_unital_non_assoc_semiring (α : Type u) extends
add_comm_monoid α, distrib α, mul_zero_class α
/-- An associative but not-necessarily unital semiring. -/
@[protect_proj, ancestor non_unital_non_assoc_semiring semigroup_with_zero]
class non_unital_semiring (α : Type u) extends
non_unital_non_assoc_semiring α, semigroup_with_zero α
/-- A unital but not-necessarily-associative semiring. -/
@[protect_proj, ancestor non_unital_non_assoc_semiring mul_zero_one_class]
class non_assoc_semiring (α : Type u) extends
non_unital_non_assoc_semiring α, mul_zero_one_class α, add_comm_monoid_with_one α
/-- A semiring is a type with the following structures: additive commutative monoid
(`add_comm_monoid`), multiplicative monoid (`monoid`), distributive laws (`distrib`), and
multiplication by zero law (`mul_zero_class`). The actual definition extends `monoid_with_zero`
instead of `monoid` and `mul_zero_class`. -/
@[protect_proj, ancestor non_unital_semiring non_assoc_semiring monoid_with_zero]
class semiring (α : Type u) extends non_unital_semiring α, non_assoc_semiring α, monoid_with_zero α
section injective_surjective_maps
variables [has_zero β] [has_add β] [has_mul β] [has_smul ℕ β]
/-- Pullback a `non_unital_non_assoc_semiring` instance along an injective function.
See note [reducible non-instances]. -/
@[reducible]
protected def function.injective.non_unital_non_assoc_semiring
{α : Type u} [non_unital_non_assoc_semiring α]
(f : β → α) (hf : injective f) (zero : f 0 = 0)
(add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y)
(nsmul : ∀ x (n : ℕ), f (n • x) = n • f x) :
non_unital_non_assoc_semiring β :=
{ .. hf.mul_zero_class f zero mul, .. hf.add_comm_monoid f zero add nsmul, .. hf.distrib f add mul }
/-- Pullback a `non_unital_semiring` instance along an injective function.
See note [reducible non-instances]. -/
@[reducible]
protected def function.injective.non_unital_semiring
{α : Type u} [non_unital_semiring α]
(f : β → α) (hf : injective f) (zero : f 0 = 0)
(add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y)
(nsmul : ∀ x (n : ℕ), f (n • x) = n • f x) :
non_unital_semiring β :=
{ .. hf.non_unital_non_assoc_semiring f zero add mul nsmul, .. hf.semigroup_with_zero f zero mul }
/-- Pullback a `non_assoc_semiring` instance along an injective function.
See note [reducible non-instances]. -/
@[reducible]
protected def function.injective.non_assoc_semiring
{α : Type u} [non_assoc_semiring α]
{β : Type v} [has_zero β] [has_one β] [has_mul β] [has_add β]
[has_smul ℕ β] [has_nat_cast β]
(f : β → α) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1)
(add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y)
(nsmul : ∀ x (n : ℕ), f (n • x) = n • f x)
(nat_cast : ∀ n : ℕ, f n = n) :
non_assoc_semiring β :=
{ .. hf.add_monoid_with_one f zero one add nsmul nat_cast,
.. hf.non_unital_non_assoc_semiring f zero add mul nsmul,
.. hf.mul_one_class f one mul }
/-- Pullback a `semiring` instance along an injective function.
See note [reducible non-instances]. -/
@[reducible]
protected def function.injective.semiring
{α : Type u} [semiring α]
{β : Type v} [has_zero β] [has_one β] [has_add β] [has_mul β] [has_pow β ℕ]
[has_smul ℕ β] [has_nat_cast β]
(f : β → α) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1)
(add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y)
(nsmul : ∀ x (n : ℕ), f (n • x) = n • f x) (npow : ∀ x (n : ℕ), f (x ^ n) = f x ^ n)
(nat_cast : ∀ n : ℕ, f n = n) :
semiring β :=
{ .. hf.non_assoc_semiring f zero one add mul nsmul nat_cast,
.. hf.monoid_with_zero f zero one mul npow,
.. hf.distrib f add mul }
/-- Pushforward a `non_unital_non_assoc_semiring` instance along a surjective function.
See note [reducible non-instances]. -/
@[reducible]
protected def function.surjective.non_unital_non_assoc_semiring
{α : Type u} [non_unital_non_assoc_semiring α]
(f : α → β) (hf : surjective f) (zero : f 0 = 0)
(add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y)
(nsmul : ∀ x (n : ℕ), f (n • x) = n • f x) :
non_unital_non_assoc_semiring β :=
{ .. hf.mul_zero_class f zero mul, .. hf.add_comm_monoid f zero add nsmul, .. hf.distrib f add mul }
/-- Pushforward a `non_unital_semiring` instance along a surjective function.
See note [reducible non-instances]. -/
@[reducible]
protected def function.surjective.non_unital_semiring
{α : Type u} [non_unital_semiring α]
(f : α → β) (hf : surjective f) (zero : f 0 = 0)
(add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y)
(nsmul : ∀ x (n : ℕ), f (n • x) = n • f x) :
non_unital_semiring β :=
{ .. hf.non_unital_non_assoc_semiring f zero add mul nsmul, .. hf.semigroup_with_zero f zero mul }
/-- Pushforward a `non_assoc_semiring` instance along a surjective function.
See note [reducible non-instances]. -/
@[reducible]
protected def function.surjective.non_assoc_semiring
{α : Type u} [non_assoc_semiring α]
{β : Type v} [has_zero β] [has_one β] [has_add β] [has_mul β]
[has_smul ℕ β] [has_nat_cast β]
(f : α → β) (hf : surjective f) (zero : f 0 = 0) (one : f 1 = 1)
(add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y)
(nsmul : ∀ x (n : ℕ), f (n • x) = n • f x)
(nat_cast : ∀ n : ℕ, f n = n) :
non_assoc_semiring β :=
{ .. hf.add_monoid_with_one f zero one add nsmul nat_cast,
.. hf.non_unital_non_assoc_semiring f zero add mul nsmul, .. hf.mul_one_class f one mul }
/-- Pushforward a `semiring` instance along a surjective function.
See note [reducible non-instances]. -/
@[reducible]
protected def function.surjective.semiring
{α : Type u} [semiring α]
{β : Type v} [has_zero β] [has_one β] [has_add β] [has_mul β] [has_pow β ℕ]
[has_smul ℕ β] [has_nat_cast β]
(f : α → β) (hf : surjective f) (zero : f 0 = 0) (one : f 1 = 1)
(add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y)
(nsmul : ∀ x (n : ℕ), f (n • x) = n • f x) (npow : ∀ x (n : ℕ), f (x ^ n) = f x ^ n)
(nat_cast : ∀ n : ℕ, f n = n) :
semiring β :=
{ .. hf.non_assoc_semiring f zero one add mul nsmul nat_cast,
.. hf.monoid_with_zero f zero one mul npow, .. hf.add_comm_monoid f zero add nsmul,
.. hf.distrib f add mul }
end injective_surjective_maps
section has_one_has_add
variables [has_one α] [has_add α]
lemma one_add_one_eq_two : 1 + 1 = (2 : α) := rfl
end has_one_has_add
section distrib_semigroup
variables [has_add α] [semigroup α]
theorem dvd_add [left_distrib_class α] {a b c : α} (h₁ : a ∣ b) (h₂ : a ∣ c) : a ∣ b + c :=
dvd.elim h₁ (λ d hd, dvd.elim h₂ (λ e he, dvd.intro (d + e) (by simp [left_distrib, hd, he])))
end distrib_semigroup
section distrib_mul_one_class
variables [has_add α] [mul_one_class α]
lemma add_one_mul [right_distrib_class α] (a b : α) : (a + 1) * b = a * b + b :=
by rw [add_mul, one_mul]
lemma mul_add_one [left_distrib_class α] (a b : α) : a * (b + 1) = a * b + a :=
by rw [mul_add, mul_one]
lemma one_add_mul [right_distrib_class α] (a b : α) : (1 + a) * b = b + a * b :=
by rw [add_mul, one_mul]
lemma mul_one_add [left_distrib_class α] (a b : α) : a * (1 + b) = a + a * b :=
by rw [mul_add, mul_one]
theorem two_mul [right_distrib_class α] (n : α) : 2 * n = n + n :=
eq.trans (right_distrib 1 1 n) (by simp)
theorem bit0_eq_two_mul [right_distrib_class α] (n : α) : bit0 n = 2 * n :=
(two_mul _).symm
theorem mul_two [left_distrib_class α] (n : α) : n * 2 = n + n :=
(left_distrib n 1 1).trans (by simp)
end distrib_mul_one_class
section semiring
variables [semiring α]
@[to_additive] lemma mul_ite {α} [has_mul α] (P : Prop) [decidable P] (a b c : α) :
a * (if P then b else c) = if P then a * b else a * c :=
by split_ifs; refl
@[to_additive] lemma ite_mul {α} [has_mul α] (P : Prop) [decidable P] (a b c : α) :
(if P then a else b) * c = if P then a * c else b * c :=
by split_ifs; refl
-- We make `mul_ite` and `ite_mul` simp lemmas,
-- but not `add_ite` or `ite_add`.
-- The problem we're trying to avoid is dealing with
-- summations of the form `∑ x in s, (f x + ite P 1 0)`,
-- in which `add_ite` followed by `sum_ite` would needlessly slice up
-- the `f x` terms according to whether `P` holds at `x`.
-- There doesn't appear to be a corresponding difficulty so far with
-- `mul_ite` and `ite_mul`.
attribute [simp] mul_ite ite_mul
@[simp] lemma mul_boole {α} [mul_zero_one_class α] (P : Prop) [decidable P] (a : α) :
a * (if P then 1 else 0) = if P then a else 0 :=
by simp
@[simp] lemma boole_mul {α} [mul_zero_one_class α] (P : Prop) [decidable P] (a : α) :
(if P then 1 else 0) * a = if P then a else 0 :=
by simp
lemma ite_mul_zero_left {α : Type*} [mul_zero_class α] (P : Prop) [decidable P] (a b : α) :
ite P (a * b) 0 = ite P a 0 * b :=
by { by_cases h : P; simp [h], }
lemma ite_mul_zero_right {α : Type*} [mul_zero_class α] (P : Prop) [decidable P] (a b : α) :
ite P (a * b) 0 = a * ite P b 0 :=
by { by_cases h : P; simp [h], }
lemma ite_and_mul_zero {α : Type*} [mul_zero_class α]
(P Q : Prop) [decidable P] [decidable Q] (a b : α) :
ite (P ∧ Q) (a * b) 0 = ite P a 0 * ite Q b 0 :=
by simp only [←ite_and, ite_mul, mul_ite, mul_zero, zero_mul, and_comm]
end semiring
namespace add_hom
/-- Left multiplication by an element of a type with distributive multiplication is an `add_hom`. -/
@[simps { fully_applied := ff}] def mul_left {R : Type*} [distrib R] (r : R) : add_hom R R :=
⟨(*) r, mul_add r⟩
/-- Left multiplication by an element of a type with distributive multiplication is an `add_hom`. -/
@[simps { fully_applied := ff}] def mul_right {R : Type*} [distrib R] (r : R) : add_hom R R :=
⟨λ a, a * r, λ _ _, add_mul _ _ r⟩
end add_hom
section add_hom_class
variables {F : Type*} [non_assoc_semiring α] [non_assoc_semiring β] [add_hom_class F α β]
/-- Additive homomorphisms preserve `bit0`. -/
@[simp] lemma map_bit0 (f : F) (a : α) : (f (bit0 a) : β) = bit0 (f a) :=
map_add _ _ _
end add_hom_class
namespace add_monoid_hom
/-- Left multiplication by an element of a (semi)ring is an `add_monoid_hom` -/
def mul_left {R : Type*} [non_unital_non_assoc_semiring R] (r : R) : R →+ R :=
{ to_fun := (*) r,
map_zero' := mul_zero r,
map_add' := mul_add r }
@[simp] lemma coe_mul_left {R : Type*} [non_unital_non_assoc_semiring R] (r : R) :
⇑(mul_left r) = (*) r := rfl
/-- Right multiplication by an element of a (semi)ring is an `add_monoid_hom` -/
def mul_right {R : Type*} [non_unital_non_assoc_semiring R] (r : R) : R →+ R :=
{ to_fun := λ a, a * r,
map_zero' := zero_mul r,
map_add' := λ _ _, add_mul _ _ r }
@[simp] lemma coe_mul_right {R : Type*} [non_unital_non_assoc_semiring R] (r : R) :
⇑(mul_right r) = (* r) := rfl
lemma mul_right_apply {R : Type*} [non_unital_non_assoc_semiring R] (a r : R) :
mul_right r a = a * r := rfl
end add_monoid_hom
@[simp] theorem two_dvd_bit0 [semiring α] {a : α} : 2 ∣ bit0 a := ⟨a, bit0_eq_two_mul _⟩
/-- A non-unital commutative semiring is a `non_unital_semiring` with commutative multiplication.
In other words, it is a type with the following structures: additive commutative monoid
(`add_comm_monoid`), commutative semigroup (`comm_semigroup`), distributive laws (`distrib`), and
multiplication by zero law (`mul_zero_class`). -/
@[protect_proj, ancestor non_unital_semiring comm_semigroup]
class non_unital_comm_semiring (α : Type u) extends non_unital_semiring α, comm_semigroup α
section non_unital_comm_semiring
variables [non_unital_comm_semiring α] [non_unital_comm_semiring β] {a b c : α}
/-- Pullback a `non_unital_semiring` instance along an injective function.
See note [reducible non-instances]. -/
@[reducible]
protected def function.injective.non_unital_comm_semiring [has_zero γ] [has_add γ] [has_mul γ]
[has_smul ℕ γ] (f : γ → α) (hf : injective f) (zero : f 0 = 0)
(add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y)
(nsmul : ∀ x (n : ℕ), f (n • x) = n • f x) :
non_unital_comm_semiring γ :=
{ .. hf.non_unital_semiring f zero add mul nsmul, .. hf.comm_semigroup f mul }
/-- Pushforward a `non_unital_semiring` instance along a surjective function.
See note [reducible non-instances]. -/
@[reducible]
protected def function.surjective.non_unital_comm_semiring [has_zero γ] [has_add γ] [has_mul γ]
[has_smul ℕ γ] (f : α → γ) (hf : surjective f) (zero : f 0 = 0)
(add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y)
(nsmul : ∀ x (n : ℕ), f (n • x) = n • f x) :
non_unital_comm_semiring γ :=
{ .. hf.non_unital_semiring f zero add mul nsmul, .. hf.comm_semigroup f mul }
lemma has_dvd.dvd.linear_comb {d x y : α} (hdx : d ∣ x) (hdy : d ∣ y) (a b : α) :
d ∣ (a * x + b * y) :=
dvd_add (hdx.mul_left a) (hdy.mul_left b)
end non_unital_comm_semiring
/-- A commutative semiring is a `semiring` with commutative multiplication. In other words, it is a
type with the following structures: additive commutative monoid (`add_comm_monoid`), multiplicative
commutative monoid (`comm_monoid`), distributive laws (`distrib`), and multiplication by zero law
(`mul_zero_class`). -/
@[protect_proj, ancestor semiring comm_monoid]
class comm_semiring (α : Type u) extends semiring α, comm_monoid α
@[priority 100] -- see Note [lower instance priority]
instance comm_semiring.to_non_unital_comm_semiring [comm_semiring α] : non_unital_comm_semiring α :=
{ .. comm_semiring.to_comm_monoid α, .. comm_semiring.to_semiring α }
@[priority 100] -- see Note [lower instance priority]
instance comm_semiring.to_comm_monoid_with_zero [comm_semiring α] : comm_monoid_with_zero α :=
{ .. comm_semiring.to_comm_monoid α, .. comm_semiring.to_semiring α }
section comm_semiring
variables [comm_semiring α] [comm_semiring β] {a b c : α}
/-- Pullback a `semiring` instance along an injective function.
See note [reducible non-instances]. -/
@[reducible]
protected def function.injective.comm_semiring
[has_zero γ] [has_one γ] [has_add γ] [has_mul γ] [has_smul ℕ γ] [has_nat_cast γ]
[has_pow γ ℕ] (f : γ → α) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1)
(add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y)
(nsmul : ∀ x (n : ℕ), f (n • x) = n • f x) (npow : ∀ x (n : ℕ), f (x ^ n) = f x ^ n)
(nat_cast : ∀ n : ℕ, f n = n) :
comm_semiring γ :=
{ .. hf.semiring f zero one add mul nsmul npow nat_cast, .. hf.comm_semigroup f mul }
/-- Pushforward a `semiring` instance along a surjective function.
See note [reducible non-instances]. -/
@[reducible]
protected def function.surjective.comm_semiring
[has_zero γ] [has_one γ] [has_add γ] [has_mul γ] [has_smul ℕ γ] [has_nat_cast γ]
[has_pow γ ℕ] (f : α → γ) (hf : surjective f) (zero : f 0 = 0) (one : f 1 = 1)
(add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y)
(nsmul : ∀ x (n : ℕ), f (n • x) = n • f x) (npow : ∀ x (n : ℕ), f (x ^ n) = f x ^ n)
(nat_cast : ∀ n : ℕ, f n = n) :
comm_semiring γ :=
{ .. hf.semiring f zero one add mul nsmul npow nat_cast, .. hf.comm_semigroup f mul }
lemma add_mul_self_eq (a b : α) : (a + b) * (a + b) = a*a + 2*a*b + b*b :=
by simp only [two_mul, add_mul, mul_add, add_assoc, mul_comm b]
end comm_semiring
section has_distrib_neg
/-- Typeclass for a negation operator that distributes across multiplication.
This is useful for dealing with submonoids of a ring that contain `-1` without having to duplicate
lemmas. -/
class has_distrib_neg (α : Type*) [has_mul α] extends has_involutive_neg α :=
(neg_mul : ∀ x y : α, -x * y = -(x * y))
(mul_neg : ∀ x y : α, x * -y = -(x * y))
section has_mul
variables [has_mul α] [has_distrib_neg α]
@[simp] lemma neg_mul (a b : α) : - a * b = - (a * b) :=
has_distrib_neg.neg_mul _ _
@[simp] lemma mul_neg (a b : α) : a * - b = - (a * b) :=
has_distrib_neg.mul_neg _ _
lemma neg_mul_neg (a b : α) : -a * -b = a * b :=
by simp
lemma neg_mul_eq_neg_mul (a b : α) : -(a * b) = -a * b :=
(neg_mul _ _).symm
lemma neg_mul_eq_mul_neg (a b : α) : -(a * b) = a * -b :=
(mul_neg _ _).symm
lemma neg_mul_comm (a b : α) : -a * b = a * -b :=
by simp
/-- A type endowed with `-` and `*` has distributive negation, if it admits an injective map that
preserves `-` and `*` to a type which has distributive negation. -/
@[reducible] -- See note [reducible non-instances]
protected def function.injective.has_distrib_neg [has_neg β] [has_mul β] (f : β → α)
(hf : injective f) (neg : ∀ a, f (-a) = -f a) (mul : ∀ a b, f (a * b) = f a * f b) :
has_distrib_neg β :=
{ neg_mul := λ x y, hf $ by erw [neg, mul, neg, neg_mul, mul],
mul_neg := λ x y, hf $ by erw [neg, mul, neg, mul_neg, mul],
..hf.has_involutive_neg _ neg, ..‹has_mul β› }
/-- A type endowed with `-` and `*` has distributive negation, if it admits a surjective map that
preserves `-` and `*` from a type which has distributive negation. -/
@[reducible] -- See note [reducible non-instances]
protected def function.surjective.has_distrib_neg [has_neg β] [has_mul β] (f : α → β)
(hf : surjective f) (neg : ∀ a, f (-a) = -f a) (mul : ∀ a b, f (a * b) = f a * f b) :
has_distrib_neg β :=
{ neg_mul := hf.forall₂.2 $ λ x y, by { erw [←neg, ← mul, neg_mul, neg, mul], refl },
mul_neg := hf.forall₂.2 $ λ x y, by { erw [←neg, ← mul, mul_neg, neg, mul], refl },
..hf.has_involutive_neg _ neg, ..‹has_mul β› }
namespace add_opposite
instance : has_distrib_neg αᵃᵒᵖ := unop_injective.has_distrib_neg _ unop_neg unop_mul
end add_opposite
open mul_opposite
instance : has_distrib_neg αᵐᵒᵖ :=
{ neg_mul := λ _ _, unop_injective $ mul_neg _ _,
mul_neg := λ _ _, unop_injective $ neg_mul _ _,
..mul_opposite.has_involutive_neg _ }
end has_mul
section mul_one_class
variables [mul_one_class α] [has_distrib_neg α]
theorem neg_eq_neg_one_mul (a : α) : -a = -1 * a :=
by simp
/-- An element of a ring multiplied by the additive inverse of one is the element's additive
inverse. -/
lemma mul_neg_one (a : α) : a * -1 = -a := by simp
/-- The additive inverse of one multiplied by an element of a ring is the element's additive
inverse. -/
lemma neg_one_mul (a : α) : -1 * a = -a := by simp
end mul_one_class
section mul_zero_class
variables [mul_zero_class α] [has_distrib_neg α]
/-- Prefer `neg_zero` if `subtraction_monoid` is available. -/
@[simp] lemma neg_zero' : (-0 : α) = 0 :=
by rw [←zero_mul (0 : α), ←neg_mul, mul_zero, mul_zero]
end mul_zero_class
section semigroup
variables [semigroup α] [has_distrib_neg α] {a b c : α}
theorem dvd_neg_of_dvd (h : a ∣ b) : (a ∣ -b) :=
let ⟨c, hc⟩ := h in ⟨-c, by simp [hc]⟩
theorem dvd_of_dvd_neg (h : a ∣ -b) : (a ∣ b) :=
let t := dvd_neg_of_dvd h in by rwa neg_neg at t
/-- An element a of a semigroup with a distributive negation divides the negation of an element b
iff a divides b. -/
@[simp] lemma dvd_neg (a b : α) : (a ∣ -b) ↔ (a ∣ b) :=
⟨dvd_of_dvd_neg, dvd_neg_of_dvd⟩
theorem neg_dvd_of_dvd (h : a ∣ b) : -a ∣ b :=
let ⟨c, hc⟩ := h in ⟨-c, by simp [hc]⟩
theorem dvd_of_neg_dvd (h : -a ∣ b) : a ∣ b :=
let t := neg_dvd_of_dvd h in by rwa neg_neg at t
/-- The negation of an element a of a semigroup with a distributive negation divides
another element b iff a divides b. -/
@[simp] lemma neg_dvd (a b : α) : (-a ∣ b) ↔ (a ∣ b) :=
⟨dvd_of_neg_dvd, neg_dvd_of_dvd⟩
end semigroup
section group
variables [group α] [has_distrib_neg α]
@[simp] lemma inv_neg' (a : α) : (- a)⁻¹ = - a⁻¹ :=
by rw [eq_comm, eq_inv_iff_mul_eq_one, neg_mul, mul_neg,neg_neg, mul_left_inv]
end group
end has_distrib_neg
/-!
### Rings
-/
/-- A not-necessarily-unital, not-necessarily-associative ring. -/
@[protect_proj, ancestor add_comm_group non_unital_non_assoc_semiring]
class non_unital_non_assoc_ring (α : Type u) extends
add_comm_group α, non_unital_non_assoc_semiring α
section non_unital_non_assoc_ring
variables [non_unital_non_assoc_ring α]
/-- Pullback a `non_unital_non_assoc_ring` instance along an injective function.
See note [reducible non-instances]. -/
@[reducible]
protected def function.injective.non_unital_non_assoc_ring
[has_zero β] [has_add β] [has_mul β] [has_neg β] [has_sub β] [has_smul ℕ β] [has_smul ℤ β]
(f : β → α) (hf : injective f) (zero : f 0 = 0)
(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)
(nsmul : ∀ x (n : ℕ), f (n • x) = n • f x) (zsmul : ∀ x (n : ℤ), f (n • x) = n • f x) :
non_unital_non_assoc_ring β :=
{ .. hf.add_comm_group f zero add neg sub nsmul zsmul, ..hf.mul_zero_class f zero mul,
.. hf.distrib f add mul }
/-- Pushforward a `non_unital_non_assoc_ring` instance along a surjective function.
See note [reducible non-instances]. -/
@[reducible]
protected def function.surjective.non_unital_non_assoc_ring
[has_zero β] [has_add β] [has_mul β] [has_neg β] [has_sub β] [has_smul ℕ β] [has_smul ℤ β]
(f : α → β) (hf : surjective f) (zero : f 0 = 0)
(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)
(nsmul : ∀ x (n : ℕ), f (n • x) = n • f x) (zsmul : ∀ x (n : ℤ), f (n • x) = n • f x) :
non_unital_non_assoc_ring β :=
{ .. hf.add_comm_group f zero add neg sub nsmul zsmul, .. hf.mul_zero_class f zero mul,
.. hf.distrib f add mul }
@[priority 100]
instance non_unital_non_assoc_ring.to_has_distrib_neg : has_distrib_neg α :=
{ neg := has_neg.neg,
neg_neg := neg_neg,
neg_mul := λ a b, eq_neg_of_add_eq_zero_left $ by rw [←right_distrib, add_left_neg, zero_mul],
mul_neg := λ a b, eq_neg_of_add_eq_zero_left $ by rw [←left_distrib, add_left_neg, mul_zero] }
lemma mul_sub_left_distrib (a b c : α) : a * (b - c) = a * b - a * c :=
by simpa only [sub_eq_add_neg, neg_mul_eq_mul_neg] using mul_add a b (-c)
alias mul_sub_left_distrib ← mul_sub
lemma mul_sub_right_distrib (a b c : α) : (a - b) * c = a * c - b * c :=
by simpa only [sub_eq_add_neg, neg_mul_eq_neg_mul] using add_mul a (-b) c
alias mul_sub_right_distrib ← sub_mul
variables {a b c d e : α}
/-- An iff statement following from right distributivity in rings and the definition
of subtraction. -/
theorem mul_add_eq_mul_add_iff_sub_mul_add_eq : a * e + c = b * e + d ↔ (a - b) * e + c = d :=
calc
a * e + c = b * e + d ↔ a * e + c = d + b * e : by simp [add_comm]
... ↔ a * e + c - b * e = d : iff.intro (λ h, begin rw h, simp end) (λ h,
begin rw ← h, simp end)
... ↔ (a - b) * e + c = d : begin simp [sub_mul, sub_add_eq_add_sub] end
/-- A simplification of one side of an equation exploiting right distributivity in rings
and the definition of subtraction. -/
theorem sub_mul_add_eq_of_mul_add_eq_mul_add : a * e + c = b * e + d → (a - b) * e + c = d :=
assume h,
calc
(a - b) * e + c = (a * e + c) - b * e : begin simp [sub_mul, sub_add_eq_add_sub] end
... = d : begin rw h, simp [@add_sub_cancel α] end
end non_unital_non_assoc_ring
/-- An associative but not-necessarily unital ring. -/
@[protect_proj, ancestor non_unital_non_assoc_ring non_unital_semiring]
class non_unital_ring (α : Type*) extends
non_unital_non_assoc_ring α, non_unital_semiring α
section non_unital_ring
variables [non_unital_ring α]
/-- Pullback a `non_unital_ring` instance along an injective function.
See note [reducible non-instances]. -/
@[reducible]
protected def function.injective.non_unital_ring
[has_zero β] [has_add β] [has_mul β] [has_neg β] [has_sub β] [has_smul ℕ β] [has_smul ℤ β]
(f : β → α) (hf : injective f) (zero : f 0 = 0)
(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)
(nsmul : ∀ x (n : ℕ), f (n • x) = n • f x) (gsmul : ∀ x (n : ℤ), f (n • x) = n • f x) :
non_unital_ring β :=
{ .. hf.add_comm_group f zero add neg sub nsmul gsmul, ..hf.mul_zero_class f zero mul,
.. hf.distrib f add mul, .. hf.semigroup f mul }
/-- Pushforward a `non_unital_ring` instance along a surjective function.
See note [reducible non-instances]. -/
@[reducible]
protected def function.surjective.non_unital_ring
[has_zero β] [has_add β] [has_mul β] [has_neg β] [has_sub β] [has_smul ℕ β] [has_smul ℤ β]
(f : α → β) (hf : surjective f) (zero : f 0 = 0)
(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)
(nsmul : ∀ x (n : ℕ), f (n • x) = n • f x) (gsmul : ∀ x (n : ℤ), f (n • x) = n • f x) :
non_unital_ring β :=
{ .. hf.add_comm_group f zero add neg sub nsmul gsmul, .. hf.mul_zero_class f zero mul,
.. hf.distrib f add mul, .. hf.semigroup f mul }
end non_unital_ring
/-- A unital but not-necessarily-associative ring. -/
@[protect_proj, ancestor non_unital_non_assoc_ring non_assoc_semiring]
class non_assoc_ring (α : Type*) extends
non_unital_non_assoc_ring α, non_assoc_semiring α, add_group_with_one α
section non_assoc_ring
variables [non_assoc_ring α]
/-- Pullback a `non_assoc_ring` instance along an injective function.
See note [reducible non-instances]. -/
@[reducible]
protected def function.injective.non_assoc_ring
[has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β] [has_sub β]
[has_smul ℕ β] [has_smul ℤ β] [has_nat_cast β] [has_int_cast β]
(f : β → α) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1)
(add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y)
(neg : ∀ x, f (-x) = -f x) (sub : ∀ x y, f (x - y) = f x - f y)
(nsmul : ∀ x (n : ℕ), f (n • x) = n • f x) (gsmul : ∀ x (n : ℤ), f (n • x) = n • f x)
(nat_cast : ∀ n : ℕ, f n = n) (int_cast : ∀ n : ℤ, f n = n) :
non_assoc_ring β :=
{ .. hf.add_comm_group f zero add neg sub nsmul gsmul,
.. hf.add_group_with_one f zero one add neg sub nsmul gsmul nat_cast int_cast,
.. hf.mul_zero_class f zero mul, .. hf.distrib f add mul,
.. hf.mul_one_class f one mul }
/-- Pushforward a `non_unital_ring` instance along a surjective function.
See note [reducible non-instances]. -/
@[reducible]
protected def function.surjective.non_assoc_ring
[has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β] [has_sub β]
[has_smul ℕ β] [has_smul ℤ β] [has_nat_cast β] [has_int_cast β]
(f : α → β) (hf : surjective f) (zero : f 0 = 0) (one : f 1 = 1)
(add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y)
(neg : ∀ x, f (-x) = -f x) (sub : ∀ x y, f (x - y) = f x - f y)
(nsmul : ∀ x (n : ℕ), f (n • x) = n • f x) (gsmul : ∀ x (n : ℤ), f (n • x) = n • f x)
(nat_cast : ∀ n : ℕ, f n = n) (int_cast : ∀ n : ℤ, f n = n) :
non_assoc_ring β :=
{ .. hf.add_comm_group f zero add neg sub nsmul gsmul, .. hf.mul_zero_class f zero mul,
.. hf.add_group_with_one f zero one add neg sub nsmul gsmul nat_cast int_cast,
.. hf.distrib f add mul, .. hf.mul_one_class f one mul }
lemma sub_one_mul (a b : α) : (a - 1) * b = a * b - b :=
by rw [sub_mul, one_mul]
lemma mul_sub_one (a b : α) : a * (b - 1) = a * b - a :=
by rw [mul_sub, mul_one]
lemma one_sub_mul (a b : α) : (1 - a) * b = b - a * b :=
by rw [sub_mul, one_mul]
lemma mul_one_sub (a b : α) : a * (1 - b) = a - a * b :=
by rw [mul_sub, mul_one]
end non_assoc_ring
/-- A ring is a type with the following structures: additive commutative group (`add_comm_group`),
multiplicative monoid (`monoid`), and distributive laws (`distrib`). Equivalently, a ring is a
`semiring` with a negation operation making it an additive group. -/
@[protect_proj, ancestor add_comm_group monoid distrib]
class ring (α : Type u) extends add_comm_group_with_one α, monoid α, distrib α
section ring
variables [ring α] {a b c d e : α}
/- A (unital, associative) ring is a not-necessarily-unital ring -/
@[priority 100] -- see Note [lower instance priority]
instance ring.to_non_unital_ring :
non_unital_ring α :=
{ zero_mul := λ a, add_left_cancel $ show 0 * a + 0 * a = 0 * a + 0,
by rw [← add_mul, zero_add, add_zero],
mul_zero := λ a, add_left_cancel $ show a * 0 + a * 0 = a * 0 + 0,
by rw [← mul_add, add_zero, add_zero],
..‹ring α› }
/- A (unital, associative) ring is a not-necessarily-associative ring -/
@[priority 100] -- see Note [lower instance priority]
instance ring.to_non_assoc_ring :
non_assoc_ring α :=
{ zero_mul := λ a, add_left_cancel $ show 0 * a + 0 * a = 0 * a + 0,
by rw [← add_mul, zero_add, add_zero],
mul_zero := λ a, add_left_cancel $ show a * 0 + a * 0 = a * 0 + 0,
by rw [← mul_add, add_zero, add_zero],
..‹ring α› }
/- The instance from `ring` to `semiring` happens often in linear algebra, for which all the basic
definitions are given in terms of semirings, but many applications use rings or fields. We increase
a little bit its priority above 100 to try it quickly, but remaining below the default 1000 so that
more specific instances are tried first. -/
@[priority 200]
instance ring.to_semiring : semiring α :=
{ ..‹ring α›, .. ring.to_non_unital_ring }
/-- Pullback a `ring` instance along an injective function.
See note [reducible non-instances]. -/
@[reducible]
protected def function.injective.ring
[has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β] [has_sub β]
[has_smul ℕ β] [has_smul ℤ β] [has_pow β ℕ] [has_nat_cast β] [has_int_cast β]
(f : β → α) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1)
(add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y)
(neg : ∀ x, f (-x) = -f x) (sub : ∀ x y, f (x - y) = f x - f y)
(nsmul : ∀ x (n : ℕ), f (n • x) = n • f x) (zsmul : ∀ x (n : ℤ), f (n • x) = n • f x)
(npow : ∀ x (n : ℕ), f (x ^ n) = f x ^ n)
(nat_cast : ∀ n : ℕ, f n = n) (int_cast : ∀ n : ℤ, f n = n) :
ring β :=
{ .. hf.add_group_with_one f zero one add neg sub nsmul zsmul nat_cast int_cast,
.. hf.add_comm_group f zero add neg sub nsmul zsmul,
.. hf.monoid f one mul npow, .. hf.distrib f add mul }
/-- Pushforward a `ring` instance along a surjective function.
See note [reducible non-instances]. -/
@[reducible]
protected def function.surjective.ring
[has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β] [has_sub β]
[has_smul ℕ β] [has_smul ℤ β] [has_pow β ℕ] [has_nat_cast β] [has_int_cast β]
(f : α → β) (hf : surjective f) (zero : f 0 = 0) (one : f 1 = 1)
(add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y)
(neg : ∀ x, f (-x) = -f x) (sub : ∀ x y, f (x - y) = f x - f y)
(nsmul : ∀ x (n : ℕ), f (n • x) = n • f x) (zsmul : ∀ x (n : ℤ), f (n • x) = n • f x)
(npow : ∀ x (n : ℕ), f (x ^ n) = f x ^ n)
(nat_cast : ∀ n : ℕ, f n = n) (int_cast : ∀ n : ℤ, f n = n) :
ring β :=
{ .. hf.add_group_with_one f zero one add neg sub nsmul zsmul nat_cast int_cast,
.. hf.add_comm_group f zero add neg sub nsmul zsmul,
.. hf.monoid f one mul npow, .. hf.distrib f add mul }
end ring
namespace units
variables [ring α] {a b : α}
/-- Each element of the group of units of a ring has an additive inverse. -/
instance : has_neg αˣ := ⟨λu, ⟨-↑u, -↑u⁻¹, by simp, by simp⟩ ⟩
/-- Representing an element of a ring's unit group as an element of the ring commutes with
mapping this element to its additive inverse. -/
@[simp, norm_cast] protected theorem coe_neg (u : αˣ) : (↑-u : α) = -u := rfl
@[simp, norm_cast] protected theorem coe_neg_one : ((-1 : αˣ) : α) = -1 := rfl
instance : has_distrib_neg αˣ := units.ext.has_distrib_neg _ units.coe_neg units.coe_mul
@[field_simps] lemma neg_divp (a : α) (u : αˣ) : -(a /ₚ u) = (-a) /ₚ u :=
by simp only [divp, neg_mul]
@[field_simps] lemma divp_add_divp_same (a b : α) (u : αˣ) :
a /ₚ u + b /ₚ u = (a + b) /ₚ u :=
by simp only [divp, add_mul]
@[field_simps] lemma divp_sub_divp_same (a b : α) (u : αˣ) :
a /ₚ u - b /ₚ u = (a - b) /ₚ u :=
by rw [sub_eq_add_neg, sub_eq_add_neg, neg_divp, divp_add_divp_same]
@[field_simps] lemma add_divp (a b : α) (u : αˣ) : a + b /ₚ u = (a * u + b) /ₚ u :=
by simp only [divp, add_mul, units.mul_inv_cancel_right]
@[field_simps] lemma sub_divp (a b : α) (u : αˣ) : a - b /ₚ u = (a * u - b) /ₚ u :=
by simp only [divp, sub_mul, units.mul_inv_cancel_right]
@[field_simps] lemma divp_add (a b : α) (u : αˣ) : a /ₚ u + b = (a + b * u) /ₚ u :=
by simp only [divp, add_mul, units.mul_inv_cancel_right]
@[field_simps] lemma divp_sub (a b : α) (u : αˣ) : a /ₚ u - b = (a - b * u) /ₚ u :=
begin
simp only [divp, sub_mul, sub_right_inj],
assoc_rw [units.mul_inv, mul_one],
end
end units
lemma is_unit.neg [ring α] {a : α} : is_unit a → is_unit (-a)
| ⟨x, hx⟩ := hx ▸ (-x).is_unit
lemma is_unit.neg_iff [ring α] (a : α) : is_unit (-a) ↔ is_unit a :=
⟨λ h, neg_neg a ▸ h.neg, is_unit.neg⟩
lemma is_unit.sub_iff [ring α] {x y : α} :
is_unit (x - y) ↔ is_unit (y - x) :=
(is_unit.neg_iff _).symm.trans $ neg_sub x y ▸ iff.rfl
namespace ring_hom
end ring_hom
/-- A non-unital commutative ring is a `non_unital_ring` with commutative multiplication. -/
@[protect_proj, ancestor non_unital_ring comm_semigroup]
class non_unital_comm_ring (α : Type u) extends non_unital_ring α, comm_semigroup α
@[priority 100] -- see Note [lower instance priority]
instance non_unital_comm_ring.to_non_unital_comm_semiring [s : non_unital_comm_ring α] :
non_unital_comm_semiring α :=
{ ..s }
/-- A commutative ring is a `ring` with commutative multiplication. -/
@[protect_proj, ancestor ring comm_semigroup]
class comm_ring (α : Type u) extends ring α, comm_monoid α
@[priority 100] -- see Note [lower instance priority]
instance comm_ring.to_comm_semiring [s : comm_ring α] : comm_semiring α :=
{ mul_zero := mul_zero, zero_mul := zero_mul, ..s }
@[priority 100] -- see Note [lower instance priority]
instance comm_ring.to_non_unital_comm_ring [s : comm_ring α] : non_unital_comm_ring α :=
{ mul_zero := mul_zero, zero_mul := zero_mul, ..s }
section non_unital_ring
variables [non_unital_ring α] {a b c : α}
theorem dvd_sub (h₁ : a ∣ b) (h₂ : a ∣ c) : a ∣ b - c :=
by { rw sub_eq_add_neg, exact dvd_add h₁ (dvd_neg_of_dvd h₂) }
theorem dvd_add_iff_left (h : a ∣ c) : a ∣ b ↔ a ∣ b + c :=
⟨λh₂, dvd_add h₂ h, λH, by have t := dvd_sub H h; rwa add_sub_cancel at t⟩
theorem dvd_add_iff_right (h : a ∣ b) : a ∣ c ↔ a ∣ b + c :=
by rw add_comm; exact dvd_add_iff_left h
/-- If an element a divides another element c in a commutative ring, a divides the sum of another
element b with c iff a divides b. -/
theorem dvd_add_left (h : a ∣ c) : a ∣ b + c ↔ a ∣ b :=
(dvd_add_iff_left h).symm
/-- If an element a divides another element b in a commutative ring, a divides the sum of b and
another element c iff a divides c. -/
theorem dvd_add_right (h : a ∣ b) : a ∣ b + c ↔ a ∣ c :=
(dvd_add_iff_right h).symm
lemma dvd_iff_dvd_of_dvd_sub {a b c : α} (h : a ∣ (b - c)) : (a ∣ b ↔ a ∣ c) :=
begin
split,
{ intro h',
convert dvd_sub h' h,
exact eq.symm (sub_sub_self b c) },
{ intro h',
convert dvd_add h h',
exact eq_add_of_sub_eq rfl }
end
end non_unital_ring
section ring
variables [ring α] {a b c : α}
theorem two_dvd_bit1 : 2 ∣ bit1 a ↔ (2 : α) ∣ 1 := (dvd_add_iff_right (@two_dvd_bit0 _ _ a)).symm
/-- An element a divides the sum a + b if and only if a divides b.-/
@[simp] lemma dvd_add_self_left {a b : α} : a ∣ a + b ↔ a ∣ b :=
dvd_add_right (dvd_refl a)
/-- An element a divides the sum b + a if and only if a divides b.-/
@[simp] lemma dvd_add_self_right {a b : α} : a ∣ b + a ↔ a ∣ b :=
dvd_add_left (dvd_refl a)
end ring
section non_unital_comm_ring
variables [non_unital_comm_ring α] {a b c : α}
/-- Pullback a `comm_ring` instance along an injective function.
See note [reducible non-instances]. -/
@[reducible]
protected def function.injective.non_unital_comm_ring
[has_zero β] [has_add β] [has_mul β] [has_neg β] [has_sub β]
[has_smul ℕ β] [has_smul ℤ β]
(f : β → α) (hf : injective f) (zero : f 0 = 0)
(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)
(nsmul : ∀ x (n : ℕ), f (n • x) = n • f x) (zsmul : ∀ x (n : ℤ), f (n • x) = n • f x) :
non_unital_comm_ring β :=
{ .. hf.non_unital_ring f zero add mul neg sub nsmul zsmul, .. hf.comm_semigroup f mul }
/-- Pushforward a `non_unital_comm_ring` instance along a surjective function.
See note [reducible non-instances]. -/
@[reducible]
protected def function.surjective.non_unital_comm_ring
[has_zero β] [has_add β] [has_mul β] [has_neg β] [has_sub β]
[has_smul ℕ β] [has_smul ℤ β]
(f : α → β) (hf : surjective f) (zero : f 0 = 0)
(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)
(nsmul : ∀ x (n : ℕ), f (n • x) = n • f x) (zsmul : ∀ x (n : ℤ), f (n • x) = n • f x) :
non_unital_comm_ring β :=
{ .. hf.non_unital_ring f zero add mul neg sub nsmul zsmul, .. hf.comm_semigroup f mul }
local attribute [simp] add_assoc add_comm add_left_comm mul_comm
/-- Vieta's formula for a quadratic equation, relating the coefficients of the polynomial with
its roots. This particular version states that if we have a root `x` of a monic quadratic
polynomial, then there is another root `y` such that `x + y` is negative the `a_1` coefficient
and `x * y` is the `a_0` coefficient. -/
lemma Vieta_formula_quadratic {b c x : α} (h : x * x - b * x + c = 0) :
∃ y : α, y * y - b * y + c = 0 ∧ x + y = b ∧ x * y = c :=
begin
have : c = x * (b - x) := (eq_neg_of_add_eq_zero_right h).trans (by simp [mul_sub, mul_comm]),
refine ⟨b - x, _, by simp, by rw this⟩,
rw [this, sub_add, ← sub_mul, sub_self]
end
lemma dvd_mul_sub_mul {k a b x y : α} (hab : k ∣ a - b) (hxy : k ∣ x - y) :
k ∣ a * x - b * y :=
begin
convert dvd_add (hxy.mul_left a) (hab.mul_right y),
rw [mul_sub_left_distrib, mul_sub_right_distrib],
simp only [sub_eq_add_neg, add_assoc, neg_add_cancel_left],
end
end non_unital_comm_ring
section comm_ring
variables [comm_ring α] {a b c : α}
/-- Pullback a `comm_ring` instance along an injective function.
See note [reducible non-instances]. -/
@[reducible]
protected def function.injective.comm_ring
[has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β] [has_sub β]
[has_smul ℕ β] [has_smul ℤ β] [has_pow β ℕ] [has_nat_cast β] [has_int_cast β]
(f : β → α) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1)
(add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y)
(neg : ∀ x, f (-x) = -f x) (sub : ∀ x y, f (x - y) = f x - f y)
(nsmul : ∀ x (n : ℕ), f (n • x) = n • f x) (zsmul : ∀ x (n : ℤ), f (n • x) = n • f x)
(npow : ∀ x (n : ℕ), f (x ^ n) = f x ^ n)
(nat_cast : ∀ n : ℕ, f n = n) (int_cast : ∀ n : ℤ, f n = n) :
comm_ring β :=
{ .. hf.ring f zero one add mul neg sub nsmul zsmul npow nat_cast int_cast,
.. hf.comm_semigroup f mul }
/-- Pushforward a `comm_ring` instance along a surjective function.
See note [reducible non-instances]. -/
@[reducible]
protected def function.surjective.comm_ring
[has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β] [has_sub β]
[has_smul ℕ β] [has_smul ℤ β] [has_pow β ℕ] [has_nat_cast β] [has_int_cast β]
(f : α → β) (hf : surjective f) (zero : f 0 = 0) (one : f 1 = 1)
(add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y)
(neg : ∀ x, f (-x) = -f x) (sub : ∀ x y, f (x - y) = f x - f y)
(nsmul : ∀ x (n : ℕ), f (n • x) = n • f x) (zsmul : ∀ x (n : ℤ), f (n • x) = n • f x)
(npow : ∀ x (n : ℕ), f (x ^ n) = f x ^ n)
(nat_cast : ∀ n : ℕ, f n = n) (int_cast : ∀ n : ℤ, f n = n) :
comm_ring β :=
{ .. hf.ring f zero one add mul neg sub nsmul zsmul npow nat_cast int_cast,
.. hf.comm_semigroup f mul }
end comm_ring
lemma succ_ne_self [non_assoc_ring α] [nontrivial α] (a : α) : a + 1 ≠ a :=
λ h, one_ne_zero ((add_right_inj a).mp (by simp [h]))
lemma pred_ne_self [non_assoc_ring α] [nontrivial α] (a : α) : a - 1 ≠ a :=
λ h, one_ne_zero (neg_injective ((add_right_inj a).mp (by simpa [sub_eq_add_neg] using h)))
/-- Left `mul` by a `k : α` over `[ring α]` is injective, if `k` is not a zero divisor.
The typeclass that restricts all terms of `α` to have this property is `no_zero_divisors`. -/
lemma is_left_regular_of_non_zero_divisor [non_unital_non_assoc_ring α] (k : α)
(h : ∀ (x : α), k * x = 0 → x = 0) : is_left_regular k :=
begin
refine λ x y (h' : k * x = k * y), sub_eq_zero.mp (h _ _),
rw [mul_sub, sub_eq_zero, h']
end
/-- Right `mul` by a `k : α` over `[ring α]` is injective, if `k` is not a zero divisor.
The typeclass that restricts all terms of `α` to have this property is `no_zero_divisors`. -/
lemma is_right_regular_of_non_zero_divisor [non_unital_non_assoc_ring α] (k : α)
(h : ∀ (x : α), x * k = 0 → x = 0) : is_right_regular k :=
begin
refine λ x y (h' : x * k = y * k), sub_eq_zero.mp (h _ _),
rw [sub_mul, sub_eq_zero, h']
end
lemma is_regular_of_ne_zero' [non_unital_non_assoc_ring α] [no_zero_divisors α] {k : α}
(hk : k ≠ 0) : is_regular k :=
⟨is_left_regular_of_non_zero_divisor k
(λ x h, (no_zero_divisors.eq_zero_or_eq_zero_of_mul_eq_zero h).resolve_left hk),
is_right_regular_of_non_zero_divisor k
(λ x h, (no_zero_divisors.eq_zero_or_eq_zero_of_mul_eq_zero h).resolve_right hk)⟩
lemma is_regular_iff_ne_zero' [nontrivial α] [non_unital_non_assoc_ring α] [no_zero_divisors α]
{k : α} : is_regular k ↔ k ≠ 0 :=
⟨λ h, by { rintro rfl, exact not_not.mpr h.left not_is_left_regular_zero }, is_regular_of_ne_zero'⟩
/-- A ring with no zero divisors is a `cancel_monoid_with_zero`.
Note this is not an instance as it forms a typeclass loop. -/
@[reducible]
def no_zero_divisors.to_cancel_monoid_with_zero [ring α] [no_zero_divisors α] :
cancel_monoid_with_zero α :=
{ mul_left_cancel_of_ne_zero := λ a b c ha,
@is_regular.left _ _ _ (is_regular_of_ne_zero' ha) _ _,
mul_right_cancel_of_ne_zero := λ a b c hb,
@is_regular.right _ _ _ (is_regular_of_ne_zero' hb) _ _,
.. (by apply_instance : monoid_with_zero α) }
/-- A commutative ring with no zero divisors is a `cancel_comm_monoid_with_zero`.
Note this is not an instance as it forms a typeclass loop. -/
@[reducible]
def no_zero_divisors.to_cancel_comm_monoid_with_zero [comm_ring α] [no_zero_divisors α] :
cancel_comm_monoid_with_zero α :=
{ .. no_zero_divisors.to_cancel_monoid_with_zero,
.. (by apply_instance : comm_monoid_with_zero α) }
/-- A domain is a nontrivial ring with no zero divisors, i.e. satisfying
the condition `a * b = 0 ↔ a = 0 ∨ b = 0`.
This is implemented as a mixin for `ring α`.
To obtain an integral domain use `[comm_ring α] [is_domain α]`. -/
@[protect_proj] class is_domain (α : Type u) [ring α]
extends no_zero_divisors α, nontrivial α : Prop
section is_domain
@[priority 100] -- see Note [lower instance priority]
instance is_domain.to_cancel_monoid_with_zero [ring α] [is_domain α] : cancel_monoid_with_zero α :=
no_zero_divisors.to_cancel_monoid_with_zero
variables [comm_ring α] [is_domain α]
@[priority 100] -- see Note [lower instance priority]
instance is_domain.to_cancel_comm_monoid_with_zero : cancel_comm_monoid_with_zero α :=
no_zero_divisors.to_cancel_comm_monoid_with_zero
end is_domain
namespace semiconj_by
@[simp] lemma add_right [distrib R] {a x y x' y' : R}
(h : semiconj_by a x y) (h' : semiconj_by a x' y') :
semiconj_by a (x + x') (y + y') :=
by simp only [semiconj_by, left_distrib, right_distrib, h.eq, h'.eq]
@[simp] lemma add_left [distrib R] {a b x y : R}
(ha : semiconj_by a x y) (hb : semiconj_by b x y) :
semiconj_by (a + b) x y :=
by simp only [semiconj_by, left_distrib, right_distrib, ha.eq, hb.eq]
section
variables [has_mul R] [has_distrib_neg R] {a x y : R}
lemma neg_right (h : semiconj_by a x y) : semiconj_by a (-x) (-y) :=
by simp only [semiconj_by, h.eq, neg_mul, mul_neg]
@[simp] lemma neg_right_iff : semiconj_by a (-x) (-y) ↔ semiconj_by a x y :=
⟨λ h, neg_neg x ▸ neg_neg y ▸ h.neg_right, semiconj_by.neg_right⟩
lemma neg_left (h : semiconj_by a x y) : semiconj_by (-a) x y :=
by simp only [semiconj_by, h.eq, neg_mul, mul_neg]
@[simp] lemma neg_left_iff : semiconj_by (-a) x y ↔ semiconj_by a x y :=
⟨λ h, neg_neg a ▸ h.neg_left, semiconj_by.neg_left⟩
end
section
variables [mul_one_class R] [has_distrib_neg R] {a x y : R}
@[simp] lemma neg_one_right (a : R) : semiconj_by a (-1) (-1) :=
(one_right a).neg_right
@[simp] lemma neg_one_left (x : R) : semiconj_by (-1) x x :=
(semiconj_by.one_left x).neg_left
end
section
variables [non_unital_non_assoc_ring R] {a b x y x' y' : R}
@[simp] lemma sub_right (h : semiconj_by a x y) (h' : semiconj_by a x' y') :
semiconj_by a (x - x') (y - y') :=
by simpa only [sub_eq_add_neg] using h.add_right h'.neg_right
@[simp] lemma sub_left (ha : semiconj_by a x y) (hb : semiconj_by b x y) :
semiconj_by (a - b) x y :=
by simpa only [sub_eq_add_neg] using ha.add_left hb.neg_left
end
end semiconj_by
namespace commute
@[simp] theorem add_right [distrib R] {a b c : R} :
commute a b → commute a c → commute a (b + c) :=
semiconj_by.add_right
@[simp] theorem add_left [distrib R] {a b c : R} :
commute a c → commute b c → commute (a + b) c :=
semiconj_by.add_left
lemma bit0_right [distrib R] {x y : R} (h : commute x y) : commute x (bit0 y) :=
h.add_right h
lemma bit0_left [distrib R] {x y : R} (h : commute x y) : commute (bit0 x) y :=
h.add_left h
lemma bit1_right [non_assoc_semiring R] {x y : R} (h : commute x y) : commute x (bit1 y) :=
h.bit0_right.add_right (commute.one_right x)
lemma bit1_left [non_assoc_semiring R] {x y : R} (h : commute x y) : commute (bit1 x) y :=
h.bit0_left.add_left (commute.one_left y)
/-- Representation of a difference of two squares of commuting elements as a product. -/
lemma mul_self_sub_mul_self_eq [non_unital_non_assoc_ring R] {a b : R} (h : commute a b) :
a * a - b * b = (a + b) * (a - b) :=
by rw [add_mul, mul_sub, mul_sub, h.eq, sub_add_sub_cancel]
lemma mul_self_sub_mul_self_eq' [non_unital_non_assoc_ring R] {a b : R} (h : commute a b) :
a * a - b * b = (a - b) * (a + b) :=
by rw [mul_add, sub_mul, sub_mul, h.eq, sub_add_sub_cancel]
lemma mul_self_eq_mul_self_iff [non_unital_non_assoc_ring R] [no_zero_divisors R] {a b : R}
(h : commute a b) : a * a = b * b ↔ a = b ∨ a = -b :=
by rw [← sub_eq_zero, h.mul_self_sub_mul_self_eq, mul_eq_zero, or_comm, sub_eq_zero,
add_eq_zero_iff_eq_neg]
section
variables [has_mul R] [has_distrib_neg R] {a b : R}
theorem neg_right : commute a b → commute a (- b) := semiconj_by.neg_right
@[simp] theorem neg_right_iff : commute a (-b) ↔ commute a b := semiconj_by.neg_right_iff
theorem neg_left : commute a b → commute (- a) b := semiconj_by.neg_left
@[simp] theorem neg_left_iff : commute (-a) b ↔ commute a b := semiconj_by.neg_left_iff
end
section
variables [mul_one_class R] [has_distrib_neg R] {a : R}
@[simp] theorem neg_one_right (a : R) : commute a (-1) := semiconj_by.neg_one_right a
@[simp] theorem neg_one_left (a : R): commute (-1) a := semiconj_by.neg_one_left a
end
section
variables [non_unital_non_assoc_ring R] {a b c : R}
@[simp] theorem sub_right : commute a b → commute a c → commute a (b - c) := semiconj_by.sub_right
@[simp] theorem sub_left : commute a c → commute b c → commute (a - b) c := semiconj_by.sub_left
end
end commute
/-- Representation of a difference of two squares in a commutative ring as a product. -/
theorem mul_self_sub_mul_self [comm_ring R] (a b : R) : a * a - b * b = (a + b) * (a - b) :=
(commute.all a b).mul_self_sub_mul_self_eq
lemma mul_self_sub_one [non_assoc_ring R] (a : R) : a * a - 1 = (a + 1) * (a - 1) :=
by rw [←(commute.one_right a).mul_self_sub_mul_self_eq, mul_one]
lemma mul_self_eq_mul_self_iff [comm_ring R] [no_zero_divisors R] {a b : R} :
a * a = b * b ↔ a = b ∨ a = -b :=
(commute.all a b).mul_self_eq_mul_self_iff
lemma mul_self_eq_one_iff [non_assoc_ring R] [no_zero_divisors R] {a : R} :
a * a = 1 ↔ a = 1 ∨ a = -1 :=
by rw [←(commute.one_right a).mul_self_eq_mul_self_iff, mul_one]
namespace units
@[field_simps] lemma divp_add_divp [comm_ring α] (a b : α) (u₁ u₂ : αˣ) :
a /ₚ u₁ + b /ₚ u₂ = (a * u₂ + u₁ * b) /ₚ (u₁ * u₂) :=
begin
simp only [divp, add_mul, mul_inv_rev, coe_mul],
rw [mul_comm (↑u₁ * b), mul_comm b],
assoc_rw [mul_inv, mul_inv, mul_one, mul_one],
end
@[field_simps] lemma divp_sub_divp [comm_ring α] (a b : α) (u₁ u₂ : αˣ) :
(a /ₚ u₁) - (b /ₚ u₂) = ((a * u₂) - (u₁ * b)) /ₚ (u₁ * u₂) :=
by simp_rw [sub_eq_add_neg, neg_divp, divp_add_divp, mul_neg]
/-- In the unit group of an integral domain, a unit is its own inverse iff the unit is one or
one's additive inverse. -/
lemma inv_eq_self_iff [ring R] [no_zero_divisors R] (u : Rˣ) : u⁻¹ = u ↔ u = 1 ∨ u = -1 :=
begin
rw inv_eq_iff_mul_eq_one,
simp only [ext_iff],
push_cast,
exact mul_self_eq_one_iff
end
end units
/-! ### Order dual -/
instance [h : distrib α] : distrib αᵒᵈ := h
instance [has_mul α] [has_add α] [h : left_distrib_class α] : left_distrib_class αᵒᵈ := h
instance [has_mul α] [has_add α] [h : right_distrib_class α] : right_distrib_class αᵒᵈ := h
instance [h : non_unital_non_assoc_semiring α] : non_unital_non_assoc_semiring αᵒᵈ := h
instance [h : non_unital_semiring α] : non_unital_semiring αᵒᵈ := h
instance [h : non_assoc_semiring α] : non_assoc_semiring αᵒᵈ := h
instance [h : semiring α] : semiring αᵒᵈ := h
instance [h : non_unital_comm_semiring α] : non_unital_comm_semiring αᵒᵈ := h
instance [h : comm_semiring α] : comm_semiring αᵒᵈ := h
instance [has_mul α] [h : has_distrib_neg α] : has_distrib_neg αᵒᵈ := h
instance [h : non_unital_non_assoc_ring α] : non_unital_non_assoc_ring αᵒᵈ := h
instance [h : non_unital_ring α] : non_unital_ring αᵒᵈ := h
instance [h : non_assoc_ring α] : non_assoc_ring αᵒᵈ := h
instance [h : ring α] : ring αᵒᵈ := h
instance [h : non_unital_comm_ring α] : non_unital_comm_ring αᵒᵈ := h
instance [h : comm_ring α] : comm_ring αᵒᵈ := h
instance [ring α] [h : is_domain α] : is_domain αᵒᵈ := h
/-! ### Lexicographical order -/
instance [h : distrib α] : distrib (lex α) := h
instance [has_mul α] [has_add α] [h : left_distrib_class α] : left_distrib_class (lex α) := h
instance [has_mul α] [has_add α] [h : right_distrib_class α] : right_distrib_class (lex α) := h
instance [h : non_unital_non_assoc_semiring α] : non_unital_non_assoc_semiring (lex α) := h
instance [h : non_unital_semiring α] : non_unital_semiring (lex α) := h
instance [h : non_assoc_semiring α] : non_assoc_semiring (lex α) := h
instance [h : semiring α] : semiring (lex α) := h
instance [h : non_unital_comm_semiring α] : non_unital_comm_semiring (lex α) := h
instance [h : comm_semiring α] : comm_semiring (lex α) := h
instance [has_mul α] [h : has_distrib_neg α] : has_distrib_neg (lex α) := h
instance [h : non_unital_non_assoc_ring α] : non_unital_non_assoc_ring (lex α) := h
instance [h : non_unital_ring α] : non_unital_ring (lex α) := h
instance [h : non_assoc_ring α] : non_assoc_ring (lex α) := h
instance [h : ring α] : ring (lex α) := h
instance [h : non_unital_comm_ring α] : non_unital_comm_ring (lex α) := h
instance [h : comm_ring α] : comm_ring (lex α) := h
instance [ring α] [h : is_domain α] : is_domain (lex α) := h
|
b53d97c08b57893709f7e258eeca3728c8f1d4f4 | bbecf0f1968d1fba4124103e4f6b55251d08e9c4 | /src/data/nat/psub.lean | 7aff367b0e79d36d69e17a5c446ab894e06868a7 | [
"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 | 2,817 | 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.nat.basic
/-!
# Partial predecessor and partial subtraction on the natural numbers
The usual definition of natural number subtraction (`nat.sub`) returns 0 as a "garbage value" for
`a - b` when `a < b`. Similarly, `nat.pred 0` is defined to be `0`. The functions in this file
wrap the result in an `option` type instead:
## Main definitions
- `nat.ppred`: a partial predecessor operation
- `nat.psub`: a partial subtraction operation
-/
namespace nat
/-- Partial predecessor operation. Returns `ppred n = some m`
if `n = m + 1`, otherwise `none`. -/
@[simp] def ppred : ℕ → option ℕ
| 0 := none
| (n+1) := some n
/-- Partial subtraction operation. Returns `psub m n = some k`
if `m = n + k`, otherwise `none`. -/
@[simp] def psub (m : ℕ) : ℕ → option ℕ
| 0 := some m
| (n+1) := psub n >>= ppred
theorem pred_eq_ppred (n : ℕ) : pred n = (ppred n).get_or_else 0 :=
by cases n; refl
theorem sub_eq_psub (m : ℕ) : ∀ n, m - n = (psub m n).get_or_else 0
| 0 := rfl
| (n+1) := (pred_eq_ppred (m-n)).trans $
by rw [sub_eq_psub, psub]; cases psub m n; refl
@[simp] theorem ppred_eq_some {m : ℕ} : ∀ {n}, ppred n = some m ↔ succ m = n
| 0 := by split; intro h; contradiction
| (n+1) := by dsimp; split; intro h; injection h; subst n
@[simp] theorem ppred_eq_none : ∀ {n : ℕ}, ppred n = none ↔ n = 0
| 0 := by simp
| (n+1) := by dsimp; split; contradiction
theorem psub_eq_some {m : ℕ} : ∀ {n k}, psub m n = some k ↔ k + n = m
| 0 k := by simp [eq_comm]
| (n+1) k :=
begin
dsimp,
apply option.bind_eq_some.trans,
simp [psub_eq_some, add_comm, add_left_comm, nat.succ_eq_add_one]
end
theorem psub_eq_none {m n : ℕ} : psub m n = none ↔ m < n :=
begin
cases s : psub m n; simp [eq_comm],
{ show m < n, refine lt_of_not_ge (λ h, _),
cases le.dest h with k e,
injection s.symm.trans (psub_eq_some.2 $ (add_comm _ _).trans e) },
{ show n ≤ m, rw ← psub_eq_some.1 s, apply nat.le_add_left }
end
theorem ppred_eq_pred {n} (h : 0 < n) : ppred n = some (pred n) :=
ppred_eq_some.2 $ succ_pred_eq_of_pos h
theorem psub_eq_sub {m n} (h : n ≤ m) : psub m n = some (m - n) :=
psub_eq_some.2 $ nat.sub_add_cancel h
theorem psub_add (m n k) : psub m (n + k) = do x ← psub m n, psub x k :=
by induction k; simp [*, add_succ, bind_assoc]
/-- Same as `psub`, but with a more efficient implementation. -/
@[inline] def psub' (m n : ℕ) : option ℕ := if n ≤ m then some (m - n) else none
theorem psub'_eq_psub (m n) : psub' m n = psub m n :=
by rw [psub']; split_ifs;
[exact (psub_eq_sub h).symm, exact (psub_eq_none.2 (not_le.1 h)).symm]
end nat
|
56a436ccd02e05dc59a3e4cdbe2aeaabe322ae0e | 5ae26df177f810c5006841e9c73dc56e01b978d7 | /src/data/dfinsupp.lean | 1f75924873883baea97bf2e48950f5d6e904d176 | [
"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 | 32,404 | lean | /-
Copyright (c) 2018 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Kenny Lau
Dependent functions with finite support (see `data/finsupp.lean`).
-/
import data.finset data.set.finite algebra.big_operators algebra.module algebra.pi_instances
universes u u₁ u₂ v v₁ v₂ v₃ w x y l
variables (ι : Type u) (β : ι → Type v)
def decidable_zero_symm {γ : Type w} [has_zero γ] [decidable_pred (eq (0 : γ))] : decidable_pred (λ x, x = (0:γ)) :=
λ x, decidable_of_iff (0 = x) eq_comm
local attribute [instance] decidable_zero_symm
namespace dfinsupp
variable [Π i, has_zero (β i)]
structure pre : Type (max u v) :=
(to_fun : Π i, β i)
(pre_support : multiset ι)
(zero : ∀ i, i ∈ pre_support ∨ to_fun i = 0)
instance : setoid (pre ι β) :=
{ r := λ x y, ∀ i, x.to_fun i = y.to_fun i,
iseqv := ⟨λ f i, rfl, λ f g H i, (H i).symm,
λ f g h H1 H2 i, (H1 i).trans (H2 i)⟩ }
end dfinsupp
variable {ι}
@[reducible] def dfinsupp [Π i, has_zero (β i)] : Type* :=
quotient (dfinsupp.setoid ι β)
variable {β}
notation `Π₀` binders `, ` r:(scoped f, dfinsupp f) := r
infix ` →ₚ `:25 := dfinsupp
namespace dfinsupp
section basic
variables [Π i, has_zero (β i)]
variables {β₁ : ι → Type v₁} {β₂ : ι → Type v₂}
variables [Π i, has_zero (β₁ i)] [Π i, has_zero (β₂ i)]
instance : has_coe_to_fun (Π₀ i, β i) :=
⟨λ _, Π i, β i, λ f, quotient.lift_on f pre.to_fun $ λ _ _, funext⟩
instance : has_zero (Π₀ i, β i) := ⟨⟦⟨λ i, 0, ∅, λ i, or.inr rfl⟩⟧⟩
instance : inhabited (Π₀ i, β i) := ⟨0⟩
@[simp] lemma zero_apply {i : ι} : (0 : Π₀ i, β i) i = 0 := rfl
@[extensionality]
lemma ext {f g : Π₀ i, β i} (H : ∀ i, f i = g i) : f = g :=
quotient.induction_on₂ f g (λ _ _ H, quotient.sound H) H
/-- The composition of `f : β₁ → β₂` and `g : Π₀ i, β₁ i` is
`map_range f hf g : Π₀ i, β₂ i`, well defined when `f 0 = 0`. -/
def map_range (f : Π i, β₁ i → β₂ i) (hf : ∀ i, f i 0 = 0) (g : Π₀ i, β₁ i) : Π₀ i, β₂ i :=
quotient.lift_on g (λ x, ⟦(⟨λ i, f i (x.1 i), x.2,
λ i, or.cases_on (x.3 i) or.inl $ λ H, or.inr $ by rw [H, hf]⟩ : pre ι β₂)⟧) $ λ x y H,
quotient.sound $ λ i, by simp only [H i]
@[simp] lemma map_range_apply
{f : Π i, β₁ i → β₂ i} {hf : ∀ i, f i 0 = 0} {g : Π₀ i, β₁ i} {i : ι} :
map_range f hf g i = f i (g i) :=
quotient.induction_on g $ λ x, rfl
def zip_with (f : Π i, β₁ i → β₂ i → β i) (hf : ∀ i, f i 0 0 = 0) (g₁ : Π₀ i, β₁ i) (g₂ : Π₀ i, β₂ i) : (Π₀ i, β i) :=
begin
refine quotient.lift_on₂ g₁ g₂ (λ x y, ⟦(⟨λ i, f i (x.1 i) (y.1 i), x.2 + y.2,
λ i, _⟩ : pre ι β)⟧) _,
{ cases x.3 i with h1 h1,
{ left, rw multiset.mem_add, left, exact h1 },
cases y.3 i with h2 h2,
{ left, rw multiset.mem_add, right, exact h2 },
right, rw [h1, h2, hf] },
exact λ x₁ x₂ y₁ y₂ H1 H2, quotient.sound $ λ i, by simp only [H1 i, H2 i]
end
@[simp] lemma zip_with_apply
{f : Π i, β₁ i → β₂ i → β i} {hf : ∀ i, f i 0 0 = 0} {g₁ : Π₀ i, β₁ i} {g₂ : Π₀ i, β₂ i} {i : ι} :
zip_with f hf g₁ g₂ i = f i (g₁ i) (g₂ i) :=
quotient.induction_on₂ g₁ g₂ $ λ _ _, rfl
end basic
section algebra
instance [Π i, add_monoid (β i)] : has_add (Π₀ i, β i) :=
⟨zip_with (λ _, (+)) (λ _, add_zero 0)⟩
@[simp] lemma add_apply [Π i, add_monoid (β i)] {g₁ g₂ : Π₀ i, β i} {i : ι} :
(g₁ + g₂) i = g₁ i + g₂ i :=
zip_with_apply
instance [Π i, add_monoid (β i)] : add_monoid (Π₀ i, β i) :=
{ add_monoid .
zero := 0,
add := (+),
add_assoc := λ f g h, ext $ λ i, by simp only [add_apply, add_assoc],
zero_add := λ f, ext $ λ i, by simp only [add_apply, zero_apply, zero_add],
add_zero := λ f, ext $ λ i, by simp only [add_apply, zero_apply, add_zero] }
instance [Π i, add_monoid (β i)] {i : ι} : is_add_monoid_hom (λ g : Π₀ i : ι, β i, g i) :=
{ map_add := λ _ _, add_apply, map_zero := zero_apply }
instance [Π i, add_group (β i)] : has_neg (Π₀ i, β i) :=
⟨λ f, f.map_range (λ _, has_neg.neg) (λ _, neg_zero)⟩
instance [Π i, add_comm_monoid (β i)] : add_comm_monoid (Π₀ i, β i) :=
{ add_comm := λ f g, ext $ λ i, by simp only [add_apply, add_comm],
.. dfinsupp.add_monoid }
@[simp] lemma neg_apply [Π i, add_group (β i)] {g : Π₀ i, β i} {i : ι} : (- g) i = - g i :=
map_range_apply
instance [Π i, add_group (β i)] : add_group (Π₀ i, β i) :=
{ add_left_neg := λ f, ext $ λ i, by simp only [add_apply, neg_apply, zero_apply, add_left_neg],
.. dfinsupp.add_monoid,
.. (infer_instance : has_neg (Π₀ i, β i)) }
@[simp] lemma sub_apply [Π i, add_group (β i)] {g₁ g₂ : Π₀ i, β i} {i : ι} : (g₁ - g₂) i = g₁ i - g₂ i :=
by rw [sub_eq_add_neg]; simp
instance [Π i, add_comm_group (β i)] : add_comm_group (Π₀ i, β i) :=
{ add_comm := λ f g, ext $ λ i, by simp only [add_apply, add_comm],
..dfinsupp.add_group }
def to_has_scalar {γ : Type w} [ring γ] [Π i, add_comm_group (β i)] [Π i, module γ (β i)] : has_scalar γ (Π₀ i, β i) :=
⟨λc v, v.map_range (λ _, (•) c) (λ _, smul_zero _)⟩
local attribute [instance] to_has_scalar
@[simp] lemma smul_apply {γ : Type w} [ring γ] [Π i, add_comm_group (β i)] [Π i, module γ (β i)] {i : ι} {b : γ} {v : Π₀ i, β i} :
(b • v) i = b • (v i) :=
map_range_apply
def to_module {γ : Type w} [ring γ] [Π i, add_comm_group (β i)] [Π i, module γ (β i)] : module γ (Π₀ i, β i) :=
module.of_core {
smul_add := λ c x y, ext $ λ i, by simp only [add_apply, smul_apply, smul_add],
add_smul := λ c x y, ext $ λ i, by simp only [add_apply, smul_apply, add_smul],
one_smul := λ x, ext $ λ i, by simp only [smul_apply, one_smul],
mul_smul := λ r s x, ext $ λ i, by simp only [smul_apply, smul_smul],
.. (infer_instance : has_scalar γ (Π₀ i, β i)) }
end algebra
section filter_and_subtype_domain
/-- `filter p f` is the function which is `f i` if `p i` is true and 0 otherwise. -/
def filter [Π i, has_zero (β i)] (p : ι → Prop) [decidable_pred p] (f : Π₀ i, β i) : Π₀ i, β i :=
quotient.lift_on f (λ x, ⟦(⟨λ i, if p i then x.1 i else 0, x.2,
λ i, or.cases_on (x.3 i) or.inl $ λ H, or.inr $ by rw [H, if_t_t]⟩ : pre ι β)⟧) $ λ x y H,
quotient.sound $ λ i, by simp only [H i]
@[simp] lemma filter_apply [Π i, has_zero (β i)]
{p : ι → Prop} [decidable_pred p] {i : ι} {f : Π₀ i, β i} :
f.filter p i = if p i then f i else 0 :=
quotient.induction_on f $ λ x, rfl
@[simp] lemma filter_apply_pos [Π i, has_zero (β i)]
{p : ι → Prop} [decidable_pred p] {f : Π₀ i, β i} {i : ι} (h : p i) :
f.filter p i = f i :=
by simp only [filter_apply, if_pos h]
@[simp] lemma filter_apply_neg [Π i, has_zero (β i)]
{p : ι → Prop} [decidable_pred p] {f : Π₀ i, β i} {i : ι} (h : ¬ p i) :
f.filter p i = 0 :=
by simp only [filter_apply, if_neg h]
lemma filter_pos_add_filter_neg [Π i, add_monoid (β i)] {f : Π₀ i, β i}
{p : ι → Prop} [decidable_pred p] :
f.filter p + f.filter (λi, ¬ p i) = f :=
ext $ λ i, by simp only [add_apply, filter_apply]; split_ifs; simp only [add_zero, zero_add]
/-- `subtype_domain p f` is the restriction of the finitely supported function
`f` to the subtype `p`. -/
def subtype_domain [Π i, has_zero (β i)] (p : ι → Prop) [decidable_pred p]
(f : Π₀ i, β i) : Π₀ i : subtype p, β i.1 :=
begin
fapply quotient.lift_on f,
{ intro x, refine ⟦⟨λ i, x.1 i.1, (x.2.filter p).attach.map $ λ j, ⟨j.1, (multiset.mem_filter.1 j.2).2⟩, _⟩⟧,
refine λ i, or.cases_on (x.3 i.1) (λ H, _) or.inr,
left, rw multiset.mem_map, refine ⟨⟨i.1, multiset.mem_filter.2 ⟨H, i.2⟩⟩, _, subtype.eta _ _⟩,
apply multiset.mem_attach },
intros x y H,
exact quotient.sound (λ i, H i.1)
end
@[simp] lemma subtype_domain_zero [Π i, has_zero (β i)] {p : ι → Prop} [decidable_pred p] :
subtype_domain p (0 : Π₀ i, β i) = 0 :=
rfl
@[simp] lemma subtype_domain_apply [Π i, has_zero (β i)] {p : ι → Prop} [decidable_pred p]
{i : subtype p} {v : Π₀ i, β i} :
(subtype_domain p v) i = v (i.val) :=
quotient.induction_on v $ λ x, rfl
@[simp] lemma subtype_domain_add [Π i, add_monoid (β i)] {p : ι → Prop} [decidable_pred p] {v v' : Π₀ i, β i} :
(v + v').subtype_domain p = v.subtype_domain p + v'.subtype_domain p :=
ext $ λ i, by simp only [add_apply, subtype_domain_apply]
instance subtype_domain.is_add_monoid_hom [Π i, add_monoid (β i)] {p : ι → Prop} [decidable_pred p] :
is_add_monoid_hom (subtype_domain p : (Π₀ i : ι, β i) → Π₀ i : subtype p, β i) :=
{ map_add := λ _ _, subtype_domain_add, map_zero := subtype_domain_zero }
@[simp] lemma subtype_domain_neg [Π i, add_group (β i)] {p : ι → Prop} [decidable_pred p] {v : Π₀ i, β i} :
(- v).subtype_domain p = - v.subtype_domain p :=
ext $ λ i, by simp only [neg_apply, subtype_domain_apply]
@[simp] lemma subtype_domain_sub [Π i, add_group (β i)] {p : ι → Prop} [decidable_pred p] {v v' : Π₀ i, β i} :
(v - v').subtype_domain p = v.subtype_domain p - v'.subtype_domain p :=
ext $ λ i, by simp only [sub_apply, subtype_domain_apply]
end filter_and_subtype_domain
variable [decidable_eq ι]
section basic
variable [Π i, has_zero (β i)]
lemma finite_supp (f : Π₀ i, β i) : set.finite {i | f i ≠ 0} :=
quotient.induction_on f $ λ x, set.finite_subset
(finset.finite_to_set x.2.to_finset) $ λ i H,
multiset.mem_to_finset.2 $ (x.3 i).resolve_right H
def mk (s : finset ι) (x : Π i : (↑s : set ι), β i.1) : Π₀ i, β i :=
⟦⟨λ i, if H : i ∈ s then x ⟨i, H⟩ else 0, s.1,
λ i, if H : i ∈ s then or.inl H else or.inr $ dif_neg H⟩⟧
@[simp] lemma mk_apply {s : finset ι} {x : Π i : (↑s : set ι), β i.1} {i : ι} :
(mk s x : Π i, β i) i = if H : i ∈ s then x ⟨i, H⟩ else 0 :=
rfl
theorem mk_inj (s : finset ι) : function.injective (@mk ι β _ _ s) :=
begin
intros x y H,
ext i,
have h1 : (mk s x : Π i, β i) i = (mk s y : Π i, β i) i, {rw H},
cases i with i hi,
change i ∈ s at hi,
dsimp only [mk_apply, subtype.coe_mk] at h1,
simpa only [dif_pos hi] using h1
end
def single (i : ι) (b : β i) : Π₀ i, β i :=
mk (finset.singleton i) $ λ j, eq.rec_on (finset.mem_singleton.1 j.2).symm b
@[simp] lemma single_apply {i i' b} : (single i b : Π₀ i, β i) i' = (if h : i = i' then eq.rec_on h b else 0) :=
begin
dsimp only [single],
by_cases h : i = i',
{ have h1 : i' ∈ finset.singleton i, { simp only [h, finset.mem_singleton] },
simp only [mk_apply, dif_pos h, dif_pos h1] },
{ have h1 : i' ∉ finset.singleton i, { simp only [ne.symm h, finset.mem_singleton, not_false_iff] },
simp only [mk_apply, dif_neg h, dif_neg h1] }
end
@[simp] lemma single_zero {i} : (single i 0 : Π₀ i, β i) = 0 :=
quotient.sound $ λ j, if H : j ∈ finset.singleton i
then by dsimp only; rw [dif_pos H]; cases finset.mem_singleton.1 H; refl
else dif_neg H
@[simp] lemma single_eq_same {i b} : (single i b : Π₀ i, β i) i = b :=
by simp only [single_apply, dif_pos rfl]
@[simp] lemma single_eq_of_ne {i i' b} (h : i ≠ i') : (single i b : Π₀ i, β i) i' = 0 :=
by simp only [single_apply, dif_neg h]
def erase (i : ι) (f : Π₀ i, β i) : Π₀ i, β i :=
quotient.lift_on f (λ x, ⟦(⟨λ j, if j = i then 0 else x.1 j, x.2,
λ j, or.cases_on (x.3 j) or.inl $ λ H, or.inr $ by simp only [H, if_t_t]⟩ : pre ι β)⟧) $ λ x y H,
quotient.sound $ λ j, if h : j = i then by simp only [if_pos h]
else by simp only [if_neg h, H j]
@[simp] lemma erase_apply {i j : ι} {f : Π₀ i, β i} :
(f.erase i) j = if j = i then 0 else f j :=
quotient.induction_on f $ λ x, rfl
@[simp] lemma erase_same {i : ι} {f : Π₀ i, β i} : (f.erase i) i = 0 :=
by simp
@[simp] lemma erase_ne {i i' : ι} {f : Π₀ i, β i} (h : i' ≠ i) : (f.erase i) i' = f i' :=
by simp [h]
end basic
section add_monoid
variable [Π i, add_monoid (β i)]
@[simp] lemma single_add {i : ι} {b₁ b₂ : β i} : single i (b₁ + b₂) = single i b₁ + single i b₂ :=
ext $ assume i',
begin
by_cases h : i = i',
{ subst h, simp only [add_apply, single_eq_same] },
{ simp only [add_apply, single_eq_of_ne h, zero_add] }
end
lemma single_add_erase {i : ι} {f : Π₀ i, β i} : single i (f i) + f.erase i = f :=
ext $ λ i',
if h : i = i' then by subst h; simp only [add_apply, single_apply, erase_apply, dif_pos rfl, if_pos, add_zero]
else by simp only [add_apply, single_apply, erase_apply, dif_neg h, if_neg (ne.symm h), zero_add]
lemma erase_add_single {i : ι} {f : Π₀ i, β i} : f.erase i + single i (f i) = f :=
ext $ λ i',
if h : i = i' then by subst h; simp only [add_apply, single_apply, erase_apply, dif_pos rfl, if_pos, zero_add]
else by simp only [add_apply, single_apply, erase_apply, dif_neg h, if_neg (ne.symm h), add_zero]
protected theorem induction {p : (Π₀ i, β i) → Prop} (f : Π₀ i, β i)
(h0 : p 0) (ha : ∀i b (f : Π₀ i, β i), f i = 0 → b ≠ 0 → p f → p (single i b + f)) :
p f :=
begin
refine quotient.induction_on f (λ x, _),
cases x with f s H, revert f H,
apply multiset.induction_on s,
{ intros f H, convert h0, ext i, exact (H i).resolve_left id },
intros i s ih f H,
by_cases H1 : i ∈ s,
{ have H2 : ∀ j, j ∈ s ∨ f j = 0,
{ intro j, cases H j with H2 H2,
{ cases multiset.mem_cons.1 H2 with H3 H3,
{ left, rw H3, exact H1 },
{ left, exact H3 } },
right, exact H2 },
have H3 : (⟦{to_fun := f, pre_support := i :: s, zero := H}⟧ : Π₀ i, β i)
= ⟦{to_fun := f, pre_support := s, zero := H2}⟧,
{ exact quotient.sound (λ i, rfl) },
rw H3, apply ih },
have H2 : p (erase i ⟦{to_fun := f, pre_support := i :: s, zero := H}⟧),
{ dsimp only [erase, quotient.lift_on_beta],
have H2 : ∀ j, j ∈ s ∨ ite (j = i) 0 (f j) = 0,
{ intro j, cases H j with H2 H2,
{ cases multiset.mem_cons.1 H2 with H3 H3,
{ right, exact if_pos H3 },
{ left, exact H3 } },
right, split_ifs; [refl, exact H2] },
have H3 : (⟦{to_fun := λ (j : ι), ite (j = i) 0 (f j), pre_support := i :: s, zero := _}⟧ : Π₀ i, β i)
= ⟦{to_fun := λ (j : ι), ite (j = i) 0 (f j), pre_support := s, zero := H2}⟧ :=
quotient.sound (λ i, rfl),
rw H3, apply ih },
have H3 : single i _ + _ = (⟦{to_fun := f, pre_support := i :: s, zero := H}⟧ : Π₀ i, β i) := single_add_erase,
rw ← H3,
change p (single i (f i) + _),
cases classical.em (f i = 0) with h h,
{ rw [h, single_zero, zero_add], exact H2 },
refine ha _ _ _ _ h H2,
rw erase_same
end
lemma induction₂ {p : (Π₀ i, β i) → Prop} (f : Π₀ i, β i)
(h0 : p 0) (ha : ∀i b (f : Π₀ i, β i), f i = 0 → b ≠ 0 → p f → p (f + single i b)) :
p f :=
dfinsupp.induction f h0 $ λ i b f h1 h2 h3,
have h4 : f + single i b = single i b + f,
{ ext j, by_cases H : i = j,
{ subst H, simp [h1] },
{ simp [H] } },
eq.rec_on h4 $ ha i b f h1 h2 h3
end add_monoid
@[simp] lemma mk_add [Π i, add_monoid (β i)] {s : finset ι} {x y : Π i : (↑s : set ι), β i.1} :
mk s (x + y) = mk s x + mk s y :=
ext $ λ i, by simp only [add_apply, mk_apply]; split_ifs; [refl, rw zero_add]
@[simp] lemma mk_zero [Π i, has_zero (β i)] {s : finset ι} :
mk s (0 : Π i : (↑s : set ι), β i.1) = 0 :=
ext $ λ i, by simp only [mk_apply]; split_ifs; refl
@[simp] lemma mk_neg [Π i, add_group (β i)] {s : finset ι} {x : Π i : (↑s : set ι), β i.1} :
mk s (-x) = -mk s x :=
ext $ λ i, by simp only [neg_apply, mk_apply]; split_ifs; [refl, rw neg_zero]
@[simp] lemma mk_sub [Π i, add_group (β i)] {s : finset ι} {x y : Π i : (↑s : set ι), β i.1} :
mk s (x - y) = mk s x - mk s y :=
ext $ λ i, by simp only [sub_apply, mk_apply]; split_ifs; [refl, rw sub_zero]
instance [Π i, add_group (β i)] {s : finset ι} : is_add_group_hom (@mk ι β _ _ s) :=
{ map_add := λ _ _, mk_add }
section
local attribute [instance] to_module
variables (γ : Type w) [ring γ] [Π i, add_comm_group (β i)] [Π i, module γ (β i)]
include γ
@[simp] lemma mk_smul {s : finset ι} {c : γ} (x : Π i : (↑s : set ι), β i.1) :
mk s (c • x) = c • mk s x :=
ext $ λ i, by simp only [smul_apply, mk_apply]; split_ifs; [refl, rw smul_zero]
@[simp] lemma single_smul {i : ι} {c : γ} {x : β i} :
single i (c • x) = c • single i x :=
ext $ λ i, by simp only [smul_apply, single_apply]; split_ifs; [cases h, rw smul_zero]; refl
variable β
def lmk (s : finset ι) : (Π i : (↑s : set ι), β i.1) →ₗ[γ] Π₀ i, β i :=
⟨mk s, λ _ _, mk_add, λ c x, by rw [mk_smul γ x]⟩
def lsingle (i) : β i →ₗ[γ] Π₀ i, β i :=
⟨single i, λ _ _, single_add, λ _ _, single_smul _⟩
variable {β}
@[simp] lemma lmk_apply {s : finset ι} {x} : lmk β γ s x = mk s x := rfl
@[simp] lemma lsingle_apply {i : ι} {x : β i} : lsingle β γ i x = single i x := rfl
end
section support_basic
variables [Π i, has_zero (β i)] [Π i, decidable_pred (eq (0 : β i))]
def support (f : Π₀ i, β i) : finset ι :=
quotient.lift_on f (λ x, x.2.to_finset.filter $ λ i, x.1 i ≠ 0) $
begin
intros x y Hxy,
ext i, split,
{ intro H,
rcases finset.mem_filter.1 H with ⟨h1, h2⟩,
rw Hxy i at h2,
exact finset.mem_filter.2 ⟨multiset.mem_to_finset.2 $ (y.3 i).resolve_right h2, h2⟩ },
{ intro H,
rcases finset.mem_filter.1 H with ⟨h1, h2⟩,
rw ← Hxy i at h2,
exact finset.mem_filter.2 ⟨multiset.mem_to_finset.2 $ (x.3 i).resolve_right h2, h2⟩ },
end
@[simp] theorem support_mk_subset {s : finset ι} {x : Π i : (↑s : set ι), β i.1} : (mk s x).support ⊆ s :=
λ i H, multiset.mem_to_finset.1 (finset.mem_filter.1 H).1
@[simp] theorem mem_support_to_fun (f : Π₀ i, β i) (i) : i ∈ f.support ↔ f i ≠ 0 :=
begin
refine quotient.induction_on f (λ x, _),
dsimp only [support, quotient.lift_on_beta],
rw [finset.mem_filter, multiset.mem_to_finset],
exact and_iff_right_of_imp (x.3 i).resolve_right
end
theorem eq_mk_support (f : Π₀ i, β i) : f = mk f.support (λ i, f i.1) :=
by ext i; by_cases h : f i = 0; try {simp at h}; simp [h]
@[simp] lemma support_zero : (0 : Π₀ i, β i).support = ∅ := rfl
@[simp] lemma mem_support_iff (f : Π₀ i, β i) : ∀i:ι, i ∈ f.support ↔ f i ≠ 0 :=
f.mem_support_to_fun
@[simp] lemma support_eq_empty {f : Π₀ i, β i} : f.support = ∅ ↔ f = 0 :=
⟨λ H, ext $ by simpa [finset.ext] using H, by simp {contextual:=tt}⟩
instance decidable_zero : decidable_pred (eq (0 : Π₀ i, β i)) :=
λ f, decidable_of_iff _ $ support_eq_empty.trans eq_comm
lemma support_subset_iff {s : set ι} {f : Π₀ i, β i} :
↑f.support ⊆ s ↔ (∀i∉s, f i = 0) :=
by simp [set.subset_def];
exact forall_congr (assume i, @not_imp_comm _ _ (classical.dec _) (classical.dec _))
lemma support_single_ne_zero {i : ι} {b : β i} (hb : b ≠ 0) : (single i b).support = {i} :=
begin
ext j, by_cases h : i = j,
{ subst h, simp [hb] },
simp [ne.symm h, h]
end
lemma support_single_subset {i : ι} {b : β i} : (single i b).support ⊆ {i} :=
support_mk_subset
section map_range_and_zip_with
variables {β₁ : ι → Type v₁} {β₂ : ι → Type v₂}
variables [Π i, has_zero (β₁ i)] [Π i, has_zero (β₂ i)]
variables [Π i, decidable_pred (eq (0 : β₁ i))] [Π i, decidable_pred (eq (0 : β₂ i))]
lemma map_range_def {f : Π i, β₁ i → β₂ i} {hf : ∀ i, f i 0 = 0} {g : Π₀ i, β₁ i} :
map_range f hf g = mk g.support (λ i, f i.1 (g i.1)) :=
begin
ext i,
by_cases h : g i = 0,
{ simp [h, hf] },
{ simp at h, simp [h, hf] }
end
lemma support_map_range {f : Π i, β₁ i → β₂ i} {hf : ∀ i, f i 0 = 0} {g : Π₀ i, β₁ i} :
(map_range f hf g).support ⊆ g.support :=
by simp [map_range_def]
@[simp] lemma map_range_single {f : Π i, β₁ i → β₂ i} {hf : ∀ i, f i 0 = 0} {i : ι} {b : β₁ i} :
map_range f hf (single i b) = single i (f i b) :=
dfinsupp.ext $ λ i', by by_cases i = i'; [{subst i', simp}, simp [h, hf]]
lemma zip_with_def {f : Π i, β₁ i → β₂ i → β i} {hf : ∀ i, f i 0 0 = 0} {g₁ : Π₀ i, β₁ i} {g₂ : Π₀ i, β₂ i} :
zip_with f hf g₁ g₂ = mk (g₁.support ∪ g₂.support) (λ i, f i.1 (g₁ i.1) (g₂ i.1)) :=
begin
ext i,
by_cases h1 : g₁ i = 0; by_cases h2 : g₂ i = 0;
try {simp at h1 h2}; simp [h1, h2, hf]
end
lemma support_zip_with {f : Π i, β₁ i → β₂ i → β i} {hf : ∀ i, f i 0 0 = 0} {g₁ : Π₀ i, β₁ i} {g₂ : Π₀ i, β₂ i} :
(zip_with f hf g₁ g₂).support ⊆ g₁.support ∪ g₂.support :=
by simp [zip_with_def]
end map_range_and_zip_with
lemma erase_def (i : ι) (f : Π₀ i, β i) :
f.erase i = mk (f.support.erase i) (λ j, f j.1) :=
begin
ext j,
by_cases h1 : j = i; by_cases h2 : f j = 0;
try {simp at h2}; simp [h1, h2]
end
@[simp] lemma support_erase (i : ι) (f : Π₀ i, β i) :
(f.erase i).support = f.support.erase i :=
begin
ext j,
by_cases h1 : j = i; by_cases h2 : f j = 0;
try {simp at h2}; simp [h1, h2]
end
section filter_and_subtype_domain
variables {p : ι → Prop} [decidable_pred p]
lemma filter_def (f : Π₀ i, β i) :
f.filter p = mk (f.support.filter p) (λ i, f i.1) :=
by ext i; by_cases h1 : p i; by_cases h2 : f i = 0;
try {simp at h2}; simp [h1, h2]
@[simp] lemma support_filter (f : Π₀ i, β i) :
(f.filter p).support = f.support.filter p :=
by ext i; by_cases h : p i; simp [h]
lemma subtype_domain_def (f : Π₀ i, β i) :
f.subtype_domain p = mk (f.support.subtype p) (λ i, f i.1) :=
by ext i; cases i with i hi;
by_cases h1 : p i; by_cases h2 : f i = 0;
try {simp at h2}; dsimp; simp [h1, h2]
@[simp] lemma support_subtype_domain {f : Π₀ i, β i} :
(subtype_domain p f).support = f.support.subtype p :=
by ext i; cases i with i hi;
by_cases h1 : p i; by_cases h2 : f i = 0;
try {simp at h2}; dsimp; simp [h1, h2]
end filter_and_subtype_domain
end support_basic
lemma support_add [Π i, add_monoid (β i)] [Π i, decidable_pred (eq (0 : β i))] {g₁ g₂ : Π₀ i, β i} :
(g₁ + g₂).support ⊆ g₁.support ∪ g₂.support :=
support_zip_with
@[simp] lemma support_neg [Π i, add_group (β i)] [Π i, decidable_pred (eq (0 : β i))] {f : Π₀ i, β i} :
support (-f) = support f :=
by ext i; simp
local attribute [instance] dfinsupp.to_module
lemma support_smul {γ : Type w} [ring γ] [Π i, add_comm_group (β i)] [Π i, module γ (β i)]
[Π (i : ι), decidable_pred (eq (0 : β i))]
{b : γ} {v : Π₀ i, β i} : (b • v).support ⊆ v.support :=
λ x, by simp [dfinsupp.mem_support_iff, not_imp_not] {contextual := tt}
instance [decidable_eq ι] [Π i, has_zero (β i)] [Π i, decidable_eq (β i)] : decidable_eq (Π₀ i, β i) :=
assume f g, decidable_of_iff (f.support = g.support ∧ (∀i∈f.support, f i = g i))
⟨assume ⟨h₁, h₂⟩, ext $ assume i,
if h : i ∈ f.support then h₂ i h else
have hf : f i = 0, by rwa [f.mem_support_iff, not_not] at h,
have hg : g i = 0, by rwa [h₁, g.mem_support_iff, not_not] at h,
by rw [hf, hg],
by intro h; subst h; simp⟩
section prod_and_sum
variables {γ : Type w}
-- [to_additive dfinsupp.sum] for dfinsupp.prod doesn't work, the equation lemmas are not generated
/-- `sum f g` is the sum of `g i (f i)` over the support of `f`. -/
def sum [Π i, has_zero (β i)] [Π i, decidable_pred (eq (0 : β i))] [add_comm_monoid γ]
(f : Π₀ i, β i) (g : Π i, β i → γ) : γ :=
f.support.sum (λi, g i (f i))
/-- `prod f g` is the product of `g i (f i)` over the support of `f`. -/
@[to_additive dfinsupp.sum]
def prod [Π i, has_zero (β i)] [Π i, decidable_pred (eq (0 : β i))] [comm_monoid γ]
(f : Π₀ i, β i) (g : Π i, β i → γ) : γ :=
f.support.prod (λi, g i (f i))
attribute [to_additive dfinsupp.sum.equations._eqn_1] dfinsupp.prod.equations._eqn_1
@[to_additive dfinsupp.sum_map_range_index]
lemma prod_map_range_index {β₁ : ι → Type v₁} {β₂ : ι → Type v₂}
[Π i, has_zero (β₁ i)] [Π i, has_zero (β₂ i)]
[Π i, decidable_pred (eq (0 : β₁ i))] [Π i, decidable_pred (eq (0 : β₂ i))] [comm_monoid γ]
{f : Π i, β₁ i → β₂ i} {hf : ∀ i, f i 0 = 0} {g : Π₀ i, β₁ i} {h : Π i, β₂ i → γ} (h0 : ∀i, h i 0 = 1) :
(map_range f hf g).prod h = g.prod (λi b, h i (f i b)) :=
begin
rw [map_range_def],
refine (finset.prod_subset support_mk_subset _).trans _,
{ intros i h1 h2,
dsimp, simp [h1] at h2, dsimp at h2,
simp [h1, h2, h0] },
{ refine finset.prod_congr rfl _,
intros i h1,
simp [h1] }
end
@[to_additive dfinsupp.sum_zero_index]
lemma prod_zero_index [Π i, add_comm_monoid (β i)] [Π i, decidable_pred (eq (0 : β i))] [comm_monoid γ]
{h : Π i, β i → γ} : (0 : Π₀ i, β i).prod h = 1 :=
rfl
@[to_additive dfinsupp.sum_single_index]
lemma prod_single_index [Π i, has_zero (β i)] [Π i, decidable_pred (eq (0 : β i))] [comm_monoid γ]
{i : ι} {b : β i} {h : Π i, β i → γ} (h_zero : h i 0 = 1) :
(single i b).prod h = h i b :=
begin
by_cases h : b = 0,
{ simp [h, prod_zero_index, h_zero], refl },
{ simp [dfinsupp.prod, support_single_ne_zero h] }
end
@[to_additive dfinsupp.sum_neg_index]
lemma prod_neg_index [Π i, add_group (β i)] [Π i, decidable_pred (eq (0 : β i))] [comm_monoid γ]
{g : Π₀ i, β i} {h : Π i, β i → γ} (h0 : ∀i, h i 0 = 1) :
(-g).prod h = g.prod (λi b, h i (- b)) :=
prod_map_range_index h0
@[simp] lemma sum_apply {ι₁ : Type u₁} [decidable_eq ι₁] {β₁ : ι₁ → Type v₁}
[Π i₁, has_zero (β₁ i₁)] [Π i, decidable_pred (eq (0 : β₁ i))]
[Π i, add_comm_monoid (β i)]
{f : Π₀ i₁, β₁ i₁} {g : Π i₁, β₁ i₁ → Π₀ i, β i} {i₂ : ι} :
(f.sum g) i₂ = f.sum (λi₁ b, g i₁ b i₂) :=
(finset.sum_hom (λf : Π₀ i, β i, f i₂)).symm
lemma support_sum {ι₁ : Type u₁} [decidable_eq ι₁] {β₁ : ι₁ → Type v₁}
[Π i₁, has_zero (β₁ i₁)] [Π i, decidable_pred (eq (0 : β₁ i))]
[Π i, add_comm_monoid (β i)] [Π i, decidable_pred (eq (0 : β i))]
{f : Π₀ i₁, β₁ i₁} {g : Π i₁, β₁ i₁ → Π₀ i, β i} :
(f.sum g).support ⊆ f.support.bind (λi, (g i (f i)).support) :=
have ∀i₁ : ι, f.sum (λ (i : ι₁) (b : β₁ i), (g i b) i₁) ≠ 0 →
(∃ (i : ι₁), f i ≠ 0 ∧ ¬ (g i (f i)) i₁ = 0),
from assume i₁ h,
let ⟨i, hi, ne⟩ := finset.exists_ne_zero_of_sum_ne_zero h in
⟨i, (f.mem_support_iff i).mp hi, ne⟩,
by simpa [finset.subset_iff, mem_support_iff, finset.mem_bind, sum_apply] using this
@[simp] lemma sum_zero [Π i, add_comm_monoid (β i)] [Π i, decidable_pred (eq (0 : β i))]
[add_comm_monoid γ] {f : Π₀ i, β i} :
f.sum (λi b, (0 : γ)) = 0 :=
finset.sum_const_zero
@[simp] lemma sum_add [Π i, add_comm_monoid (β i)] [Π i, decidable_pred (eq (0 : β i))]
[add_comm_monoid γ] {f : Π₀ i, β i} {h₁ h₂ : Π i, β i → γ} :
f.sum (λi b, h₁ i b + h₂ i b) = f.sum h₁ + f.sum h₂ :=
finset.sum_add_distrib
@[simp] lemma sum_neg [Π i, add_comm_monoid (β i)] [Π i, decidable_pred (eq (0 : β i))]
[add_comm_group γ] {f : Π₀ i, β i} {h : Π i, β i → γ} :
f.sum (λi b, - h i b) = - f.sum h :=
finset.sum_hom (@has_neg.neg γ _)
@[to_additive dfinsupp.sum_add_index]
lemma prod_add_index [Π i, add_comm_monoid (β i)] [Π i, decidable_pred (eq (0 : β i))]
[comm_monoid γ] {f g : Π₀ i, β i}
{h : Π i, β i → γ} (h_zero : ∀i, h i 0 = 1) (h_add : ∀i b₁ b₂, h i (b₁ + b₂) = h i b₁ * h i b₂) :
(f + g).prod h = f.prod h * g.prod h :=
have f_eq : (f.support ∪ g.support).prod (λi, h i (f i)) = f.prod h,
from (finset.prod_subset (finset.subset_union_left _ _) $
by simp [mem_support_iff, h_zero] {contextual := tt}).symm,
have g_eq : (f.support ∪ g.support).prod (λi, h i (g i)) = g.prod h,
from (finset.prod_subset (finset.subset_union_right _ _) $
by simp [mem_support_iff, h_zero] {contextual := tt}).symm,
calc (f + g).support.prod (λi, h i ((f + g) i)) =
(f.support ∪ g.support).prod (λi, h i ((f + g) i)) :
finset.prod_subset support_add $
by simp [mem_support_iff, h_zero] {contextual := tt}
... = (f.support ∪ g.support).prod (λi, h i (f i)) *
(f.support ∪ g.support).prod (λi, h i (g i)) :
by simp [h_add, finset.prod_mul_distrib]
... = _ : by rw [f_eq, g_eq]
lemma sum_sub_index [Π i, add_comm_group (β i)] [Π i, decidable_pred (eq (0 : β i))]
[add_comm_group γ] {f g : Π₀ i, β i}
{h : Π i, β i → γ} (h_sub : ∀i b₁ b₂, h i (b₁ - b₂) = h i b₁ - h i b₂) :
(f - g).sum h = f.sum h - g.sum h :=
have h_zero : ∀i, h i 0 = 0,
from assume i,
have h i (0 - 0) = h i 0 - h i 0, from h_sub i 0 0,
by simpa using this,
have h_neg : ∀i b, h i (- b) = - h i b,
from assume i b,
have h i (0 - b) = h i 0 - h i b, from h_sub i 0 b,
by simpa [h_zero] using this,
have h_add : ∀i b₁ b₂, h i (b₁ + b₂) = h i b₁ + h i b₂,
from assume i b₁ b₂,
have h i (b₁ - (- b₂)) = h i b₁ - h i (- b₂), from h_sub i b₁ (-b₂),
by simpa [h_neg] using this,
by simp [@sum_add_index ι β _ γ _ _ _ f (-g) h h_zero h_add];
simp [@sum_neg_index ι β _ γ _ _ _ g h h_zero, h_neg];
simp [@sum_neg ι β _ γ _ _ _ g h]
@[to_additive dfinsupp.sum_finset_sum_index]
lemma prod_finset_sum_index {γ : Type w} {α : Type x}
[Π i, add_comm_monoid (β i)] [Π i, decidable_pred (eq (0 : β i))]
[comm_monoid γ] [decidable_eq α]
{s : finset α} {g : α → Π₀ i, β i}
{h : Π i, β i → γ} (h_zero : ∀i, h i 0 = 1) (h_add : ∀i b₁ b₂, h i (b₁ + b₂) = h i b₁ * h i b₂) :
s.prod (λi, (g i).prod h) = (s.sum g).prod h :=
finset.induction_on s
(by simp [prod_zero_index])
(by simp [prod_add_index, h_zero, h_add] {contextual := tt})
@[to_additive dfinsupp.sum_sum_index]
lemma prod_sum_index {ι₁ : Type u₁} [decidable_eq ι₁] {β₁ : ι₁ → Type v₁}
[Π i₁, has_zero (β₁ i₁)] [Π i, decidable_pred (eq (0 : β₁ i))]
[Π i, add_comm_monoid (β i)] [Π i, decidable_pred (eq (0 : β i))]
[comm_monoid γ]
{f : Π₀ i₁, β₁ i₁} {g : Π i₁, β₁ i₁ → Π₀ i, β i}
{h : Π i, β i → γ} (h_zero : ∀i, h i 0 = 1) (h_add : ∀i b₁ b₂, h i (b₁ + b₂) = h i b₁ * h i b₂) :
(f.sum g).prod h = f.prod (λi b, (g i b).prod h) :=
(prod_finset_sum_index h_zero h_add).symm
@[simp] lemma sum_single [Π i, add_comm_monoid (β i)]
[Π i, decidable_pred (eq (0 : β i))] {f : Π₀ i, β i} :
f.sum single = f :=
begin
apply dfinsupp.induction f, {rw [sum_zero_index]},
intros i b f H hb ih,
rw [sum_add_index, ih, sum_single_index],
all_goals { intros, simp }
end
@[to_additive dfinsupp.sum_subtype_domain_index]
lemma prod_subtype_domain_index [Π i, has_zero (β i)] [Π i, decidable_pred (eq (0 : β i))]
[comm_monoid γ] {v : Π₀ i, β i} {p : ι → Prop} [decidable_pred p]
{h : Π i, β i → γ} (hp : ∀x∈v.support, p x) :
(v.subtype_domain p).prod (λi b, h i.1 b) = v.prod h :=
finset.prod_bij (λp _, p.val)
(by simp)
(by simp)
(assume ⟨a₀, ha₀⟩ ⟨a₁, ha₁⟩, by simp)
(λ i hi, ⟨⟨i, hp i hi⟩, by simpa using hi, rfl⟩)
lemma subtype_domain_sum [Π i, add_comm_monoid (β i)] [Π i, decidable_pred (eq (0 : β i))]
{s : finset γ} {h : γ → Π₀ i, β i} {p : ι → Prop} [decidable_pred p] :
(s.sum h).subtype_domain p = s.sum (λc, (h c).subtype_domain p) :=
eq.symm (finset.sum_hom _)
lemma subtype_domain_finsupp_sum {δ : γ → Type x} [decidable_eq γ]
[Π c, has_zero (δ c)] [Π c, decidable_pred (eq (0 : δ c))]
[Π i, add_comm_monoid (β i)] [Π i, decidable_pred (eq (0 : β i))]
{p : ι → Prop} [decidable_pred p]
{s : Π₀ c, δ c} {h : Π c, δ c → Π₀ i, β i} :
(s.sum h).subtype_domain p = s.sum (λc d, (h c d).subtype_domain p) :=
subtype_domain_sum
end prod_and_sum
end dfinsupp
|
13e3ed87f0f4467f474bf32a802fd259fc9835c5 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/algebra/order/group/abs.lean | 890733166db8e0abf4f4b4a59b113eb438478704 | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 9,984 | 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, Johannes Hölzl
-/
import algebra.abs
import algebra.order.group.order_iso
import order.min_max
/-!
# Absolute values in ordered groups.
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
-/
variables {α : Type*}
open function
section covariant_add_le
section has_neg
/-- `abs a` is the absolute value of `a`. -/
@[to_additive "`abs a` is the absolute value of `a`",
priority 100] -- see Note [lower instance priority]
instance has_inv.to_has_abs [has_inv α] [has_sup α] : has_abs α := ⟨λ a, a ⊔ a⁻¹⟩
@[to_additive] lemma abs_eq_sup_inv [has_inv α] [has_sup α] (a : α) : |a| = a ⊔ a⁻¹ := rfl
variables [has_neg α] [linear_order α] {a b: α}
lemma abs_eq_max_neg : abs a = max a (-a) :=
rfl
lemma abs_choice (x : α) : |x| = x ∨ |x| = -x := max_choice _ _
lemma abs_le' : |a| ≤ b ↔ a ≤ b ∧ -a ≤ b := max_le_iff
lemma le_abs : a ≤ |b| ↔ a ≤ b ∨ a ≤ -b := le_max_iff
lemma le_abs_self (a : α) : a ≤ |a| := le_max_left _ _
lemma neg_le_abs_self (a : α) : -a ≤ |a| := le_max_right _ _
lemma lt_abs : a < |b| ↔ a < b ∨ a < -b := lt_max_iff
theorem abs_le_abs (h₀ : a ≤ b) (h₁ : -a ≤ b) : |a| ≤ |b| :=
(abs_le'.2 ⟨h₀, h₁⟩).trans (le_abs_self b)
lemma abs_by_cases (P : α → Prop) {a : α} (h1 : P a) (h2 : P (-a)) : P (|a|) :=
sup_ind _ _ h1 h2
end has_neg
section add_group
variables [add_group α] [linear_order α]
@[simp] lemma abs_neg (a : α) : | -a| = |a| :=
begin
rw [abs_eq_max_neg, max_comm, neg_neg, abs_eq_max_neg]
end
lemma eq_or_eq_neg_of_abs_eq {a b : α} (h : |a| = b) : a = b ∨ a = -b :=
by simpa only [← h, eq_comm, neg_eq_iff_eq_neg] using abs_choice a
lemma abs_eq_abs {a b : α} : |a| = |b| ↔ a = b ∨ a = -b :=
begin
refine ⟨λ h, _, λ h, _⟩,
{ obtain rfl | rfl := eq_or_eq_neg_of_abs_eq h;
simpa only [neg_eq_iff_eq_neg, neg_inj, or.comm] using abs_choice b },
{ cases h; simp only [h, abs_neg] },
end
lemma abs_sub_comm (a b : α) : |a - b| = |b - a| :=
calc |a - b| = | - (b - a)| : congr_arg _ (neg_sub b a).symm
... = |b - a| : abs_neg (b - a)
variables [covariant_class α α (+) (≤)] {a b c : α}
lemma abs_of_nonneg (h : 0 ≤ a) : |a| = a :=
max_eq_left $ (neg_nonpos.2 h).trans h
lemma abs_of_pos (h : 0 < a) : |a| = a :=
abs_of_nonneg h.le
lemma abs_of_nonpos (h : a ≤ 0) : |a| = -a :=
max_eq_right $ h.trans (neg_nonneg.2 h)
lemma abs_of_neg (h : a < 0) : |a| = -a :=
abs_of_nonpos h.le
lemma abs_le_abs_of_nonneg (ha : 0 ≤ a) (hab : a ≤ b) : |a| ≤ |b| :=
by rwa [abs_of_nonneg ha, abs_of_nonneg (ha.trans hab)]
@[simp] lemma abs_zero : |0| = (0:α) :=
abs_of_nonneg le_rfl
@[simp] lemma abs_pos : 0 < |a| ↔ a ≠ 0 :=
begin
rcases lt_trichotomy a 0 with (ha|rfl|ha),
{ simp [abs_of_neg ha, neg_pos, ha.ne, ha] },
{ simp },
{ simp [abs_of_pos ha, ha, ha.ne.symm] }
end
lemma abs_pos_of_pos (h : 0 < a) : 0 < |a| := abs_pos.2 h.ne.symm
lemma abs_pos_of_neg (h : a < 0) : 0 < |a| := abs_pos.2 h.ne
lemma neg_abs_le_self (a : α) : -|a| ≤ a :=
begin
cases le_total 0 a with h h,
{ calc -|a| = - a : congr_arg (has_neg.neg) (abs_of_nonneg h)
... ≤ 0 : neg_nonpos.mpr h
... ≤ a : h },
{ calc -|a| = - - a : congr_arg (has_neg.neg) (abs_of_nonpos h)
... ≤ a : (neg_neg a).le }
end
lemma add_abs_nonneg (a : α) : 0 ≤ a + |a| :=
begin
rw ←add_right_neg a,
apply add_le_add_left,
exact (neg_le_abs_self a),
end
lemma neg_abs_le_neg (a : α) : -|a| ≤ -a :=
by simpa using neg_abs_le_self (-a)
@[simp] lemma abs_nonneg (a : α) : 0 ≤ |a| :=
(le_total 0 a).elim (λ h, h.trans (le_abs_self a)) (λ h, (neg_nonneg.2 h).trans $ neg_le_abs_self a)
@[simp] lemma abs_abs (a : α) : | |a| | = |a| :=
abs_of_nonneg $ abs_nonneg a
@[simp] lemma abs_eq_zero : |a| = 0 ↔ a = 0 :=
decidable.not_iff_not.1 $ ne_comm.trans $ (abs_nonneg a).lt_iff_ne.symm.trans abs_pos
@[simp] lemma abs_nonpos_iff {a : α} : |a| ≤ 0 ↔ a = 0 :=
(abs_nonneg a).le_iff_eq.trans abs_eq_zero
variable [covariant_class α α (swap (+)) (≤)]
lemma abs_le_abs_of_nonpos (ha : a ≤ 0) (hab : b ≤ a) : |a| ≤ |b| :=
by { rw [abs_of_nonpos ha, abs_of_nonpos (hab.trans ha)], exact neg_le_neg_iff.mpr hab }
lemma abs_lt : |a| < b ↔ - b < a ∧ a < b :=
max_lt_iff.trans $ and.comm.trans $ by rw [neg_lt]
lemma neg_lt_of_abs_lt (h : |a| < b) : -b < a := (abs_lt.mp h).1
lemma lt_of_abs_lt (h : |a| < b) : a < b := (abs_lt.mp h).2
lemma max_sub_min_eq_abs' (a b : α) : max a b - min a b = |a - b| :=
begin
cases le_total a b with ab ba,
{ rw [max_eq_right ab, min_eq_left ab, abs_of_nonpos, neg_sub], rwa sub_nonpos },
{ rw [max_eq_left ba, min_eq_right ba, abs_of_nonneg], rwa sub_nonneg }
end
lemma max_sub_min_eq_abs (a b : α) : max a b - min a b = |b - a| :=
by { rw abs_sub_comm, exact max_sub_min_eq_abs' _ _ }
end add_group
end covariant_add_le
section linear_ordered_add_comm_group
variables [linear_ordered_add_comm_group α] {a b c d : α}
lemma abs_le : |a| ≤ b ↔ - b ≤ a ∧ a ≤ b := by rw [abs_le', and.comm, neg_le]
lemma le_abs' : a ≤ |b| ↔ b ≤ -a ∨ a ≤ b := by rw [le_abs, or.comm, le_neg]
lemma neg_le_of_abs_le (h : |a| ≤ b) : -b ≤ a := (abs_le.mp h).1
lemma le_of_abs_le (h : |a| ≤ b) : a ≤ b := (abs_le.mp h).2
@[to_additive] lemma apply_abs_le_mul_of_one_le' {β : Type*} [mul_one_class β] [preorder β]
[covariant_class β β (*) (≤)] [covariant_class β β (swap (*)) (≤)] {f : α → β} {a : α}
(h₁ : 1 ≤ f a) (h₂ : 1 ≤ f (-a)) :
f (|a|) ≤ f a * f (-a) :=
(le_total a 0).by_cases (λ ha, (abs_of_nonpos ha).symm ▸ le_mul_of_one_le_left' h₁)
(λ ha, (abs_of_nonneg ha).symm ▸ le_mul_of_one_le_right' h₂)
@[to_additive] lemma apply_abs_le_mul_of_one_le {β : Type*} [mul_one_class β] [preorder β]
[covariant_class β β (*) (≤)] [covariant_class β β (swap (*)) (≤)] {f : α → β}
(h : ∀ x, 1 ≤ f x) (a : α) :
f (|a|) ≤ f a * f (-a) :=
apply_abs_le_mul_of_one_le' (h _) (h _)
/--
The **triangle inequality** in `linear_ordered_add_comm_group`s.
-/
lemma abs_add (a b : α) : |a + b| ≤ |a| + |b| :=
abs_le.2 ⟨(neg_add (|a|) (|b|)).symm ▸
add_le_add (neg_le.2 $ neg_le_abs_self _) (neg_le.2 $ neg_le_abs_self _),
add_le_add (le_abs_self _) (le_abs_self _)⟩
lemma abs_add' (a b : α) : |a| ≤ |b| + |b + a| :=
by simpa using abs_add (-b) (b + a)
theorem abs_sub (a b : α) :
|a - b| ≤ |a| + |b| :=
by { rw [sub_eq_add_neg, ←abs_neg b], exact abs_add a _ }
lemma abs_sub_le_iff : |a - b| ≤ c ↔ a - b ≤ c ∧ b - a ≤ c :=
by rw [abs_le, neg_le_sub_iff_le_add, sub_le_iff_le_add', and_comm, sub_le_iff_le_add']
lemma abs_sub_lt_iff : |a - b| < c ↔ a - b < c ∧ b - a < c :=
by rw [abs_lt, neg_lt_sub_iff_lt_add', sub_lt_iff_lt_add', and_comm, sub_lt_iff_lt_add']
lemma sub_le_of_abs_sub_le_left (h : |a - b| ≤ c) : b - c ≤ a :=
sub_le_comm.1 $ (abs_sub_le_iff.1 h).2
lemma sub_le_of_abs_sub_le_right (h : |a - b| ≤ c) : a - c ≤ b :=
sub_le_of_abs_sub_le_left (abs_sub_comm a b ▸ h)
lemma sub_lt_of_abs_sub_lt_left (h : |a - b| < c) : b - c < a :=
sub_lt_comm.1 $ (abs_sub_lt_iff.1 h).2
lemma sub_lt_of_abs_sub_lt_right (h : |a - b| < c) : a - c < b :=
sub_lt_of_abs_sub_lt_left (abs_sub_comm a b ▸ h)
lemma abs_sub_abs_le_abs_sub (a b : α) : |a| - |b| ≤ |a - b| :=
sub_le_iff_le_add.2 $
calc |a| = |a - b + b| : by rw [sub_add_cancel]
... ≤ |a - b| + |b| : abs_add _ _
lemma abs_abs_sub_abs_le_abs_sub (a b : α) : | |a| - |b| | ≤ |a - b| :=
abs_sub_le_iff.2 ⟨abs_sub_abs_le_abs_sub _ _, by rw abs_sub_comm; apply abs_sub_abs_le_abs_sub⟩
lemma abs_eq (hb : 0 ≤ b) : |a| = b ↔ a = b ∨ a = -b :=
begin
refine ⟨eq_or_eq_neg_of_abs_eq, _⟩,
rintro (rfl|rfl); simp only [abs_neg, abs_of_nonneg hb]
end
lemma abs_le_max_abs_abs (hab : a ≤ b) (hbc : b ≤ c) : |b| ≤ max (|a|) (|c|) :=
abs_le'.2
⟨by simp [hbc.trans (le_abs_self c)],
by simp [(neg_le_neg_iff.mpr hab).trans (neg_le_abs_self a)]⟩
lemma min_abs_abs_le_abs_max : min (|a|) (|b|) ≤ |max a b| :=
(le_total a b).elim
(λ h, (min_le_right _ _).trans_eq $ congr_arg _ (max_eq_right h).symm)
(λ h, (min_le_left _ _).trans_eq $ congr_arg _ (max_eq_left h).symm)
lemma min_abs_abs_le_abs_min : min (|a|) (|b|) ≤ |min a b| :=
(le_total a b).elim
(λ h, (min_le_left _ _).trans_eq $ congr_arg _ (min_eq_left h).symm)
(λ h, (min_le_right _ _).trans_eq $ congr_arg _ (min_eq_right h).symm)
lemma abs_max_le_max_abs_abs : |max a b| ≤ max (|a|) (|b|) :=
(le_total a b).elim
(λ h, (congr_arg _ $ max_eq_right h).trans_le $ le_max_right _ _)
(λ h, (congr_arg _ $ max_eq_left h).trans_le $ le_max_left _ _)
lemma abs_min_le_max_abs_abs : |min a b| ≤ max (|a|) (|b|) :=
(le_total a b).elim
(λ h, (congr_arg _ $ min_eq_left h).trans_le $ le_max_left _ _)
(λ h, (congr_arg _ $ min_eq_right h).trans_le $ le_max_right _ _)
lemma eq_of_abs_sub_eq_zero {a b : α} (h : |a - b| = 0) : a = b :=
sub_eq_zero.1 $ abs_eq_zero.1 h
lemma abs_sub_le (a b c : α) : |a - c| ≤ |a - b| + |b - c| :=
calc
|a - c| = |a - b + (b - c)| : by rw [sub_add_sub_cancel]
... ≤ |a - b| + |b - c| : abs_add _ _
lemma abs_add_three (a b c : α) : |a + b + c| ≤ |a| + |b| + |c| :=
(abs_add _ _).trans (add_le_add_right (abs_add _ _) _)
lemma dist_bdd_within_interval {a b lb ub : α} (hal : lb ≤ a) (hau : a ≤ ub)
(hbl : lb ≤ b) (hbu : b ≤ ub) : |a - b| ≤ ub - lb :=
abs_sub_le_iff.2 ⟨sub_le_sub hau hbl, sub_le_sub hbu hal⟩
lemma eq_of_abs_sub_nonpos (h : |a - b| ≤ 0) : a = b :=
eq_of_abs_sub_eq_zero (le_antisymm h (abs_nonneg (a - b)))
end linear_ordered_add_comm_group
|
3f3b068c2c93a8bc7a8d537ce7ce150d884b70eb | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/nary_overload.lean | c03992d79536ae31ff23647a3a17450bb4df9449 | [
"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 | 612 | lean | prelude
constant {l} vec : Type l → Type l
constant {l} lst : Type l → Type l
constant vec.nil {A : Type} : vec A
constant lst.nil {A : Type} : lst A
constant vec.cons {A : Type} : A → vec A → vec A
constant lst.cons {A : Type} : A → lst A → lst A
notation (name := list1) `[` l:(foldr `, ` (h t, vec.cons h t) vec.nil `]`) := l
notation (name := list2) `[` l:(foldr `, ` (h t, lst.cons h t) lst.nil `]`) := l
constant A : Type
variables a b c : A
#check [a, b, c]
#check ([a, b, c] : vec A)
#check ([a, b, c] : lst A)
set_option pp.all true
#check ([a, b, c] : vec A)
#check ([a, b, c] : lst A)
|
45bffe8da79f65043aafaff35a4318bcc4d99df7 | 59aed81a2ce7741e690907fc374be338f4f88b6f | /src/math-688/lectures/lec-24.lean | ef5bbf14c2537f09f6d564b00b31cb7453f2aea8 | [] | no_license | agusakov/math-688-lean | c84d5e1423eb208a0281135f0214b91b30d0ef48 | 67dc27ebff55a74c6b5a1c469ba04e7981d2e550 | refs/heads/main | 1,679,699,340,788 | 1,616,602,782,000 | 1,616,602,782,000 | 332,894,454 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 81 | lean | /- 25 Oct 2019 -/
-- system of distinct representatives
-- hall
-- latin squares |
59320a5f3fe4923bec021a947182e69d20487123 | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /src/combinatorics/hall/basic.lean | ec49a461ad60d343fb76a738578fb3e8ac4a6f4d | [
"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 | 10,743 | lean | /-
Copyright (c) 2021 Alena Gusakov, Bhavik Mehta, Kyle Miller. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Alena Gusakov, Bhavik Mehta, Kyle Miller
-/
import combinatorics.hall.finite
import topology.category.Top.limits
/-!
# Hall's Marriage Theorem
Given a list of finite subsets $X_1, X_2, \dots, X_n$ of some given set
$S$, P. Hall in [Hall1935] gave a necessary and sufficient condition for
there to be a list of distinct elements $x_1, x_2, \dots, x_n$ with
$x_i\in X_i$ for each $i$: it is when for each $k$, the union of every
$k$ of these subsets has at least $k$ elements.
Rather than a list of finite subsets, one may consider indexed families
`t : ι → finset α` of finite subsets with `ι` a `fintype`, and then the list
of distinct representatives is given by an injective function `f : ι → α`
such that `∀ i, f i ∈ t i`, called a *matching*.
This version is formalized as `finset.all_card_le_bUnion_card_iff_exists_injective'`
in a separate module.
The theorem can be generalized to remove the constraint that `ι` be a `fintype`.
As observed in [Halpern1966], one may use the constrained version of the theorem
in a compactness argument to remove this constraint.
The formulation of compactness we use is that inverse limits of nonempty finite sets
are nonempty (`nonempty_sections_of_fintype_inverse_system`), which uses the
Tychonoff theorem.
The core of this module is constructing the inverse system: for every finite subset `ι'` of
`ι`, we can consider the matchings on the restriction of the indexed family `t` to `ι'`.
## Main statements
* `finset.all_card_le_bUnion_card_iff_exists_injective` is in terms of `t : ι → finset α`.
* `fintype.all_card_le_rel_image_card_iff_exists_injective` is in terms of a relation
`r : α → β → Prop` such that `rel.image r {a}` is a finite set for all `a : α`.
* `fintype.all_card_le_filter_rel_iff_exists_injective` is in terms of a relation
`r : α → β → Prop` on finite types, with the Hall condition given in terms of
`finset.univ.filter`.
## Todo
* The statement of the theorem in terms of bipartite graphs is in preparation.
## Tags
Hall's Marriage Theorem, indexed families
-/
open finset
universes u v
/-- The sup directed order on finsets.
TODO: remove when #9200 is merged. There are two ways `finset α` can
get a `small_category` instance (used in
`hall_matchings_functor`). The first is from the preorder on `finset
α` and the second is from this `directed_order`. These categories
should be the same, but there is a defeq issue. -/
def hall_finset_directed_order (α : Type u) : directed_order (finset α) :=
⟨λ s t, by { classical, exact ⟨s ∪ t, subset_union_left s t, subset_union_right s t⟩ }⟩
local attribute [instance] hall_finset_directed_order
/-- The set of matchings for `t` when restricted to a `finset` of `ι`. -/
def hall_matchings_on {ι : Type u} {α : Type v} (t : ι → finset α) (ι' : finset ι) :=
{f : ι' → α | function.injective f ∧ ∀ x, f x ∈ t x}
/-- Given a matching on a finset, construct the restriction of that matching to a subset. -/
def hall_matchings_on.restrict {ι : Type u} {α : Type v}
(t : ι → finset α) {ι' ι'' : finset ι} (h : ι' ⊆ ι'')
(f : hall_matchings_on t ι'') : hall_matchings_on t ι' :=
begin
refine ⟨λ i, f.val ⟨i, h i.property⟩, _⟩,
cases f.property with hinj hc,
refine ⟨_, λ i, hc ⟨i, h i.property⟩⟩,
rintro ⟨i, hi⟩ ⟨j, hj⟩ hh,
simpa only [subtype.mk_eq_mk] using hinj hh,
end
/-- When the Hall condition is satisfied, the set of matchings on a finite set is nonempty.
This is where `finset.all_card_le_bUnion_card_iff_exists_injective'` comes into the argument. -/
lemma hall_matchings_on.nonempty {ι : Type u} {α : Type v} [decidable_eq α]
(t : ι → finset α) (h : (∀ (s : finset ι), s.card ≤ (s.bUnion t).card))
(ι' : finset ι) : nonempty (hall_matchings_on t ι') :=
begin
classical,
refine ⟨classical.indefinite_description _ _⟩,
apply (all_card_le_bUnion_card_iff_exists_injective' (λ (i : ι'), t i)).mp,
intro s',
convert h (s'.image coe) using 1,
simp only [card_image_of_injective s' subtype.coe_injective],
rw image_bUnion,
congr,
end
/--
This is the `hall_matchings_on` sets assembled into a directed system.
-/
-- TODO: This takes a long time to elaborate for an unknown reason.
def hall_matchings_functor {ι : Type u} {α : Type v} (t : ι → finset α) :
(finset ι)ᵒᵖ ⥤ Type (max u v) :=
{ obj := λ ι', hall_matchings_on t ι'.unop,
map := λ ι' ι'' g f, hall_matchings_on.restrict t (category_theory.le_of_hom g.unop) f }
noncomputable instance hall_matchings_on.fintype {ι : Type u} {α : Type v}
(t : ι → finset α) (ι' : finset ι) :
fintype (hall_matchings_on t ι') :=
begin
classical,
rw hall_matchings_on,
let g : hall_matchings_on t ι' → (ι' → ι'.bUnion t),
{ rintro f i,
refine ⟨f.val i, _⟩,
rw mem_bUnion,
exact ⟨i, i.property, f.property.2 i⟩ },
apply fintype.of_injective g,
intros f f' h,
simp only [g, function.funext_iff, subtype.val_eq_coe] at h,
ext a,
exact h a,
end
/--
This is the version of **Hall's Marriage Theorem** in terms of indexed
families of finite sets `t : ι → finset α`. It states that there is a
set of distinct representatives if and only if every union of `k` of the
sets has at least `k` elements.
Recall that `s.bUnion t` is the union of all the sets `t i` for `i ∈ s`.
This theorem is bootstrapped from `finset.all_card_le_bUnion_card_iff_exists_injective'`,
which has the additional constraint that `ι` is a `fintype`.
-/
theorem finset.all_card_le_bUnion_card_iff_exists_injective
{ι : Type u} {α : Type v} [decidable_eq α] (t : ι → finset α) :
(∀ (s : finset ι), s.card ≤ (s.bUnion t).card) ↔
(∃ (f : ι → α), function.injective f ∧ ∀ x, f x ∈ t x) :=
begin
split,
{ intro h,
/- Set up the functor -/
haveI : ∀ (ι' : (finset ι)ᵒᵖ), nonempty ((hall_matchings_functor t).obj ι') :=
λ ι', hall_matchings_on.nonempty t h ι'.unop,
classical,
haveI : Π (ι' : (finset ι)ᵒᵖ), fintype ((hall_matchings_functor t).obj ι') := begin
intro ι',
rw [hall_matchings_functor],
apply_instance,
end,
/- Apply the compactness argument -/
obtain ⟨u, hu⟩ := nonempty_sections_of_fintype_inverse_system (hall_matchings_functor t),
/- Interpret the resulting section of the inverse limit -/
refine ⟨_, _, _⟩,
{ /- Build the matching function from the section -/
exact λ i, (u (opposite.op ({i} : finset ι))).val
⟨i, by simp only [opposite.unop_op, mem_singleton]⟩, },
{ /- Show that it is injective -/
intros i i',
have subi : ({i} : finset ι) ⊆ {i,i'} := by simp,
have subi' : ({i'} : finset ι) ⊆ {i,i'} := by simp,
have le : ∀ {s t : finset ι}, s ⊆ t → s ≤ t := λ _ _ h, h,
rw [←hu (category_theory.hom_of_le (le subi)).op,
←hu (category_theory.hom_of_le (le subi')).op],
let uii' := u (opposite.op ({i,i'} : finset ι)),
exact λ h, subtype.mk_eq_mk.mp (uii'.property.1 h), },
{ /- Show that it maps each index to the corresponding finite set -/
intro i,
apply (u (opposite.op ({i} : finset ι))).property.2, }, },
{ /- The reverse direction is a straightforward cardinality argument -/
rintro ⟨f, hf₁, hf₂⟩ s,
rw ←finset.card_image_of_injective s hf₁,
apply finset.card_le_of_subset,
intro _,
rw [finset.mem_image, finset.mem_bUnion],
rintros ⟨x, hx, rfl⟩,
exact ⟨x, hx, hf₂ x⟩, },
end
/-- Given a relation such that the image of every singleton set is finite, then the image of every
finite set is finite. -/
instance {α : Type u} {β : Type v} [decidable_eq β]
(r : α → β → Prop) [∀ (a : α), fintype (rel.image r {a})]
(A : finset α) : fintype (rel.image r A) :=
begin
have h : rel.image r A = (A.bUnion (λ a, (rel.image r {a}).to_finset) : set β),
{ ext, simp [rel.image], },
rw [h],
apply finset_coe.fintype,
end
/--
This is a version of **Hall's Marriage Theorem** in terms of a relation
between types `α` and `β` such that `α` is finite and the image of
each `x : α` is finite (it suffices for `β` to be finite; see
`fintype.all_card_le_filter_rel_iff_exists_injective`). There is
a transversal of the relation (an injective function `α → β` whose graph is
a subrelation of the relation) iff every subset of
`k` terms of `α` is related to at least `k` terms of `β`.
Note: if `[fintype β]`, then there exist instances for `[∀ (a : α), fintype (rel.image r {a})]`.
-/
theorem fintype.all_card_le_rel_image_card_iff_exists_injective
{α : Type u} {β : Type v} [decidable_eq β]
(r : α → β → Prop) [∀ (a : α), fintype (rel.image r {a})] :
(∀ (A : finset α), A.card ≤ fintype.card (rel.image r A)) ↔
(∃ (f : α → β), function.injective f ∧ ∀ x, r x (f x)) :=
begin
let r' := λ a, (rel.image r {a}).to_finset,
have h : ∀ (A : finset α), fintype.card (rel.image r A) = (A.bUnion r').card,
{ intro A,
rw ←set.to_finset_card,
apply congr_arg,
ext b,
simp [rel.image], },
have h' : ∀ (f : α → β) x, r x (f x) ↔ f x ∈ r' x,
{ simp [rel.image], },
simp only [h, h'],
apply finset.all_card_le_bUnion_card_iff_exists_injective,
end
/--
This is a version of **Hall's Marriage Theorem** in terms of a relation to a finite type.
There is a transversal of the relation (an injective function `α → β` whose graph is a subrelation
of the relation) iff every subset of `k` terms of `α` is related to at least `k` terms of `β`.
It is like `fintype.all_card_le_rel_image_card_iff_exists_injective` but uses `finset.filter`
rather than `rel.image`.
-/
/- TODO: decidable_pred makes Yael sad. When an appropriate decidable_rel-like exists, fix it. -/
theorem fintype.all_card_le_filter_rel_iff_exists_injective
{α : Type u} {β : Type v} [fintype β]
(r : α → β → Prop) [∀ a, decidable_pred (r a)] :
(∀ (A : finset α), A.card ≤ (univ.filter (λ (b : β), ∃ a ∈ A, r a b)).card) ↔
(∃ (f : α → β), function.injective f ∧ ∀ x, r x (f x)) :=
begin
haveI := classical.dec_eq β,
let r' := λ a, univ.filter (λ b, r a b),
have h : ∀ (A : finset α), (univ.filter (λ (b : β), ∃ a ∈ A, r a b)) = (A.bUnion r'),
{ intro A,
ext b,
simp, },
have h' : ∀ (f : α → β) x, r x (f x) ↔ f x ∈ r' x,
{ simp, },
simp_rw [h, h'],
apply finset.all_card_le_bUnion_card_iff_exists_injective,
end
|
6e2500421b6b2a0decfb21ef587a511b2b47457b | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /src/lake/Lake/Config/ExternLib.lean | a15472381bf236e767a5561a3f383ea01302fc3e | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | leanprover/lean4 | 4bdf9790294964627eb9be79f5e8f6157780b4cc | f1f9dc0f2f531af3312398999d8b8303fa5f096b | refs/heads/master | 1,693,360,665,786 | 1,693,350,868,000 | 1,693,350,868,000 | 129,571,436 | 2,827 | 311 | Apache-2.0 | 1,694,716,156,000 | 1,523,760,560,000 | Lean | UTF-8 | Lean | false | false | 1,320 | lean | /-
Copyright (c) 2022 Mac Malone. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mac Malone
-/
import Lake.Config.Package
namespace Lake
/-- An external library -- its package plus its configuration. -/
structure ExternLib where
/-- The package the library belongs to. -/
pkg : Package
/-- The external library's name. -/
name : Name
/-- The library's user-defined configuration. -/
config : ExternLibConfig pkg.name name
/-- The external libraries of the package (as an Array). -/
@[inline] def Package.externLibs (self : Package) : Array ExternLib :=
self.externLibConfigs.fold (fun a n v => a.push (⟨self, n, v⟩)) #[]
/-- Try to find a external library in the package with the given name. -/
@[inline] def Package.findExternLib? (name : Name) (self : Package) : Option ExternLib :=
self.externLibConfigs.find? name |>.map (⟨self, name, ·⟩)
namespace ExternLib
/--
The arguments to pass to `leanc` when linking the external library.
That is, the package's `moreLinkArgs`.
-/
@[inline] def linkArgs (self : ExternLib) : Array String :=
self.pkg.moreLinkArgs
/-- The name of the package target used to build the external library's static binary. -/
@[inline] def staticTargetName (self : ExternLib) : Name :=
.str self.name "static"
|
3c0e4dce524e08550f2ab8c10bcd56a0126455ed | 2c41ae31b2b771ad5646ad880201393f5269a7f0 | /Lean/Qualities/Modifiable.lean | 0b056fe0d9a4dff3c30802c4f05202c1f22ee2fc | [] | no_license | kevinsullivan/Boehm | 926f25bc6f1a8b6bd47d333d936fdfc278228312 | 55208395bff20d48a598b7fa33a4d55a2447a9cf | refs/heads/master | 1,586,127,134,302 | 1,488,252,326,000 | 1,488,252,326,000 | 32,836,930 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 665 | lean | -- Modifiable
/-
[Modifiable] is parameterized by an instance of type [SystemType], and it's a sub-attribute to [Flexible].
An instance of type [SystemType] is deemed [Modifiable] if and only if all the requirements are satisfied.
-/
import SystemModel.System
inductive Modifiable (sys_type: SystemType): Prop
| intro : (exists modifiable: sys_type ^.Contexts -> sys_type ^.Phases -> sys_type ^.Stakeholders -> @SystemInstance sys_type -> Prop,
forall c: sys_type ^.Contexts, forall p: sys_type ^.Phases,
forall s: sys_type ^.Stakeholders, forall st: @SystemInstance sys_type, modifiable c p s st) ->
Modifiable
|
2fc1bea4a1135df16ff301e55a75ccbc636c3a42 | 82e44445c70db0f03e30d7be725775f122d72f3e | /src/order/filter/pointwise.lean | ca3b347868dc342171e78cfb6899468b4a7789ad | [
"Apache-2.0"
] | permissive | stjordanis/mathlib | 51e286d19140e3788ef2c470bc7b953e4991f0c9 | 2568d41bca08f5d6bf39d915434c8447e21f42ee | refs/heads/master | 1,631,748,053,501 | 1,627,938,886,000 | 1,627,938,886,000 | 228,728,358 | 0 | 0 | Apache-2.0 | 1,576,630,588,000 | 1,576,630,587,000 | null | UTF-8 | Lean | false | false | 6,697 | lean | /-
Copyright (c) 2019 Zhouhang Zhou. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Zhouhang Zhou
-/
import algebra.pointwise
import order.filter.basic
/-!
# Pointwise operations on filters.
The pointwise operations on filters have nice properties, such as
• `map m (f₁ * f₂) = map m f₁ * map m f₂`
• `𝓝 x * 𝓝 y = 𝓝 (x * y)`
-/
open classical set
universes u v w
variables {α : Type u} {β : Type v} {γ : Type w}
open_locale classical
namespace filter
open set
@[to_additive]
instance [has_one α] : has_one (filter α) := ⟨principal 1⟩
@[simp, to_additive]
lemma mem_one [has_one α] (s : set α) : s ∈ (1 : filter α) ↔ (1:α) ∈ s :=
calc
s ∈ (1:filter α) ↔ 1 ⊆ s : iff.rfl
... ↔ (1 : α) ∈ s : by simp
@[to_additive]
instance [monoid α] : has_mul (filter α) := ⟨λf g,
{ sets := { s | ∃t₁ t₂, t₁ ∈ f ∧ t₂ ∈ g ∧ t₁ * t₂ ⊆ s },
univ_sets :=
begin
have h₁ : (∃x, x ∈ f) := ⟨univ, univ_sets f⟩,
have h₂ : (∃x, x ∈ g) := ⟨univ, univ_sets g⟩,
simpa using and.intro h₁ h₂
end,
sets_of_superset := λx y hx hxy,
begin
rcases hx with ⟨t₁, ht₁, t₂, ht₂, t₁t₂⟩,
exact ⟨t₁, ht₁, t₂, ht₂, subset.trans t₁t₂ hxy⟩
end,
inter_sets := λx y,
begin
simp only [exists_prop, mem_set_of_eq, subset_inter_iff],
rintros ⟨s₁, s₂, hs₁, hs₂, s₁s₂⟩ ⟨t₁, t₂, ht₁, ht₂, t₁t₂⟩,
exact ⟨s₁ ∩ t₁, s₂ ∩ t₂, inter_sets f hs₁ ht₁, inter_sets g hs₂ ht₂,
subset.trans (mul_subset_mul (inter_subset_left _ _) (inter_subset_left _ _)) s₁s₂,
subset.trans (mul_subset_mul (inter_subset_right _ _) (inter_subset_right _ _)) t₁t₂⟩,
end }⟩
@[to_additive]
lemma mem_mul [monoid α] {f g : filter α} {s : set α} :
s ∈ f * g ↔ ∃t₁ t₂, t₁ ∈ f ∧ t₂ ∈ g ∧ t₁ * t₂ ⊆ s := iff.rfl
@[to_additive]
lemma mul_mem_mul [monoid α] {f g : filter α} {s t : set α} (hs : s ∈ f) (ht : t ∈ g) :
s * t ∈ f * g := ⟨_, _, hs, ht, subset.refl _⟩
@[to_additive]
protected lemma mul_le_mul [monoid α] {f₁ f₂ g₁ g₂ : filter α} (hf : f₁ ≤ f₂) (hg : g₁ ≤ g₂) :
f₁ * g₁ ≤ f₂ * g₂ := assume _ ⟨s, t, hs, ht, hst⟩, ⟨s, t, hf hs, hg ht, hst⟩
@[to_additive]
lemma ne_bot.mul [monoid α] {f g : filter α} : ne_bot f → ne_bot g → ne_bot (f * g) :=
begin
simp only [forall_sets_nonempty_iff_ne_bot.symm],
rintros hf hg s ⟨a, b, ha, hb, ab⟩,
exact ((hf a ha).mul (hg b hb)).mono ab
end
@[to_additive]
protected lemma mul_assoc [monoid α] (f g h : filter α) : f * g * h = f * (g * h) :=
begin
ext s, split,
{ rintros ⟨a, b, ⟨a₁, a₂, ha₁, ha₂, a₁a₂⟩, hb, ab⟩,
refine ⟨a₁, a₂ * b, ha₁, mul_mem_mul ha₂ hb, _⟩, rw [← mul_assoc],
exact calc
a₁ * a₂ * b ⊆ a * b : mul_subset_mul a₁a₂ (subset.refl _)
... ⊆ s : ab },
{ rintros ⟨a, b, ha, ⟨b₁, b₂, hb₁, hb₂, b₁b₂⟩, ab⟩,
refine ⟨a * b₁, b₂, mul_mem_mul ha hb₁, hb₂, _⟩, rw [mul_assoc],
exact calc
a * (b₁ * b₂) ⊆ a * b : mul_subset_mul (subset.refl _) b₁b₂
... ⊆ s : ab }
end
@[to_additive]
protected lemma one_mul [monoid α] (f : filter α) : 1 * f = f :=
begin
ext s, split,
{ rintros ⟨t₁, t₂, ht₁, ht₂, t₁t₂⟩,
refine mem_sets_of_superset (mem_sets_of_superset ht₂ _) t₁t₂,
assume x hx,
exact ⟨1, x, by rwa [← mem_one], hx, one_mul _⟩ },
{ assume hs, refine ⟨(1:set α), s, mem_principal_self _, hs, by simp only [one_mul]⟩ }
end
@[to_additive]
protected lemma mul_one [monoid α] (f : filter α) : f * 1 = f :=
begin
ext s, split,
{ rintros ⟨t₁, t₂, ht₁, ht₂, t₁t₂⟩,
refine mem_sets_of_superset (mem_sets_of_superset ht₁ _) t₁t₂,
assume x hx,
exact ⟨x, 1, hx, by rwa [← mem_one], mul_one _⟩ },
{ assume hs,
refine ⟨s, (1:set α), hs, mem_principal_self _, by simp only [mul_one]⟩ }
end
@[to_additive filter.add_monoid]
instance [monoid α] : monoid (filter α) :=
{ mul_assoc := filter.mul_assoc,
one_mul := filter.one_mul,
mul_one := filter.mul_one,
.. filter.has_mul,
.. filter.has_one }
section map
variables [monoid α] [monoid β] {f : filter α} (m : mul_hom α β) (φ : α →* β)
@[to_additive]
protected lemma map_mul {f₁ f₂ : filter α} : map m (f₁ * f₂) = map m f₁ * map m f₂ :=
begin
ext s,
simp only [mem_mul], split,
{ rintro ⟨t₁, t₂, ht₁, ht₂, t₁t₂⟩,
have : m '' (t₁ * t₂) ⊆ s := subset.trans (image_subset m t₁t₂) (image_preimage_subset _ _),
refine ⟨m '' t₁, m '' t₂, image_mem_map ht₁, image_mem_map ht₂, _⟩,
rwa ← image_mul m },
{ rintro ⟨t₁, t₂, ht₁, ht₂, t₁t₂⟩,
refine ⟨m ⁻¹' t₁, m ⁻¹' t₂, ht₁, ht₂, image_subset_iff.1 _⟩,
rw image_mul m,
exact subset.trans
(mul_subset_mul (image_preimage_subset _ _) (image_preimage_subset _ _)) t₁t₂ },
end
@[to_additive]
protected lemma map_one : map φ (1:filter α) = 1 :=
le_antisymm
(le_principal_iff.2 $ mem_map_sets_iff.2 ⟨(1:set α), by simp,
by { assume x, simp [φ.map_one] }⟩)
(le_map $ assume s hs,
begin
simp only [mem_one],
exact ⟨(1:α), (mem_one s).1 hs, φ.map_one⟩
end)
/-- If `φ : α →* β` then `map_monoid_hom φ` is the monoid homomorphism
`filter α →* filter β` induced by `map φ`. -/
@[to_additive "If `φ : α →+ β` then `map_add_monoid_hom φ` is the monoid homomorphism
`filter α →+ filter β` induced by `map φ`."]
def map_monoid_hom : filter α →* filter β :=
{ to_fun := map φ,
map_one' := filter.map_one φ,
map_mul' := λ _ _, filter.map_mul φ.to_mul_hom }
-- The other direction does not hold in general.
@[to_additive]
lemma comap_mul_comap_le {f₁ f₂ : filter β} :
comap m f₁ * comap m f₂ ≤ comap m (f₁ * f₂) :=
begin
rintros s ⟨t, ⟨t₁, t₂, ht₁, ht₂, t₁t₂⟩, mt⟩,
refine ⟨m ⁻¹' t₁, m ⁻¹' t₂, ⟨t₁, ht₁, subset.refl _⟩, ⟨t₂, ht₂, subset.refl _⟩, _⟩,
have := subset.trans (preimage_mono t₁t₂) mt,
exact subset.trans (preimage_mul_preimage_subset _) this
end
@[to_additive]
lemma tendsto.mul_mul {f₁ g₁ : filter α} {f₂ g₂ : filter β} :
tendsto m f₁ f₂ → tendsto m g₁ g₂ → tendsto m (f₁ * g₁) (f₂ * g₂) :=
assume hf hg, by { rw [tendsto, filter.map_mul m], exact filter.mul_le_mul hf hg }
end map
end filter
|
cac93c3c15d5ea27cd3342b569f0f9e0136a07c6 | 31f556cdeb9239ffc2fad8f905e33987ff4feab9 | /stage0/src/Lean/Expr.lean | 6c8bb8bc52da6977384df8bd4e05c1f40a090dac | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | tobiasgrosser/lean4 | ce0fd9cca0feba1100656679bf41f0bffdbabb71 | ebdbdc10436a4d9d6b66acf78aae7a23f5bd073f | refs/heads/master | 1,673,103,412,948 | 1,664,930,501,000 | 1,664,930,501,000 | 186,870,185 | 0 | 0 | Apache-2.0 | 1,665,129,237,000 | 1,557,939,901,000 | Lean | UTF-8 | Lean | false | false | 64,151 | lean | /-
Copyright (c) 2018 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Data.KVMap
import Lean.Level
namespace Lean
/-- Literal values for `Expr`. -/
inductive Literal where
/-- Natural number literal -/
| natVal (val : Nat)
/-- String literal -/
| strVal (val : String)
deriving Inhabited, BEq, Repr
protected def Literal.hash : Literal → UInt64
| .natVal v => hash v
| .strVal v => hash v
instance : Hashable Literal := ⟨Literal.hash⟩
/--
Total order on `Expr` literal values.
Natural number values are smaller than string literal values.
-/
def Literal.lt : Literal → Literal → Bool
| .natVal _, .strVal _ => true
| .natVal v₁, .natVal v₂ => v₁ < v₂
| .strVal v₁, .strVal v₂ => v₁ < v₂
| _, _ => false
instance : LT Literal := ⟨fun a b => a.lt b⟩
instance (a b : Literal) : Decidable (a < b) :=
inferInstanceAs (Decidable (a.lt b))
/--
Arguments in forallE binders can be labelled as implicit or explicit.
Each `lam` or `forallE` binder comes with a `binderInfo` argument (stored in ExprData).
This can be set to
- `default` -- `(x : α)`
- `implicit` -- `{x : α}`
- `strict_implicit` -- `⦃x : α⦄`
- `inst_implicit` -- `[x : α]`.
- `aux_decl` -- Auxillary definitions are helper methods that
Lean generates. `aux_decl` is used for `_match`, `_fun_match`,
`_let_match` and the self reference that appears in recursive pattern matching.
The difference between implicit `{}` and strict-implicit `⦃⦄` is how
implicit arguments are treated that are *not* followed by explicit arguments.
`{}` arguments are applied eagerly, while `⦃⦄` arguments are left partially applied:
```
def foo {x : Nat} : Nat := x
def bar ⦃x : Nat⦄ : Nat := x
#check foo -- foo : Nat
#check bar -- bar : ⦃x : Nat⦄ → Nat
```
See also the Lean manual: https://leanprover.github.io/lean4/doc/expressions.html#implicit-arguments
-/
inductive BinderInfo where
/-- Default binder annotation, e.g. `(x : α)` -/
| default
/-- Implicit binder annotation, e.g., `{x : α}` -/
| implicit
/-- Strict implict binder annotation, e.g., `{{ x : α }}` -/
| strictImplicit
/-- Local instance binder annotataion, e.g., `[Decidable α]` -/
| instImplicit
/--
Auxiliary declarations used by Lean when elaborating recursive declarations.
When defining a function such as
```
def f : Nat → Nat
| 0 => 1
| x+1 => (x+1)*f x
```
Lean adds a local declaration `f : Nat → Nat` to the local context (`LocalContext`)
with `BinderInfo` set to `auxDecl`.
This local declaration is later removed by the termination checker.
-/
| auxDecl
deriving Inhabited, BEq, Repr
def BinderInfo.hash : BinderInfo → UInt64
| .default => 947
| .implicit => 1019
| .strictImplicit => 1087
| .instImplicit => 1153
| .auxDecl => 1229
/--
Return `true` if the given `BinderInfo` does not correspond to an implicit binder annotation
(i.e., `implicit`, `strictImplicit`, or `instImplicit`).
-/
def BinderInfo.isExplicit : BinderInfo → Bool
| .implicit => false
| .strictImplicit => false
| .instImplicit => false
| _ => true
instance : Hashable BinderInfo := ⟨BinderInfo.hash⟩
/-- Return `true` if the given `BinderInfo` is an instance implicit annotation (e.g., `[Decidable α]`) -/
def BinderInfo.isInstImplicit : BinderInfo → Bool
| BinderInfo.instImplicit => true
| _ => false
/-- Return `true` if the given `BinderInfo` is a regular implicit annotation (e.g., `{α : Type u}`) -/
def BinderInfo.isImplicit : BinderInfo → Bool
| BinderInfo.implicit => true
| _ => false
/-- Return `true` if the given `BinderInfo` is a strict implicit annotation (e.g., `{{α : Type u}}`) -/
def BinderInfo.isStrictImplicit : BinderInfo → Bool
| BinderInfo.strictImplicit => true
| _ => false
def BinderInfo.isAuxDecl : BinderInfo → Bool
| BinderInfo.auxDecl => true
| _ => false
/-- Expression metadata. Used with the `Expr.mdata` constructor. -/
abbrev MData := KVMap
abbrev MData.empty : MData := {}
/--
Cached hash code, cached results, and other data for `Expr`.
- hash : 32-bits
- approxDepth : 8-bits -- the approximate depth is used to minimize the number of hash collisions
- hasFVar : 1-bit -- does it contain free variables?
- hasExprMVar : 1-bit -- does it contain metavariables?
- hasLevelMVar : 1-bit -- does it contain level metavariables?
- hasLevelParam : 1-bit -- does it contain level parameters?
- looseBVarRange : 20-bits
Remark: this is mostly an internal datastructure used to implement `Expr`,
most will never have to use it.
-/
def Expr.Data := UInt64
instance: Inhabited Expr.Data :=
inferInstanceAs (Inhabited UInt64)
def Expr.Data.hash (c : Expr.Data) : UInt64 :=
c.toUInt32.toUInt64
instance : BEq Expr.Data where
beq (a b : UInt64) := a == b
def Expr.Data.approxDepth (c : Expr.Data) : UInt8 :=
((c.shiftRight 32).land 255).toUInt8
def Expr.Data.looseBVarRange (c : Expr.Data) : UInt32 :=
(c.shiftRight 44).toUInt32
def Expr.Data.hasFVar (c : Expr.Data) : Bool :=
((c.shiftRight 40).land 1) == 1
def Expr.Data.hasExprMVar (c : Expr.Data) : Bool :=
((c.shiftRight 41).land 1) == 1
def Expr.Data.hasLevelMVar (c : Expr.Data) : Bool :=
((c.shiftRight 42).land 1) == 1
def Expr.Data.hasLevelParam (c : Expr.Data) : Bool :=
((c.shiftRight 43).land 1) == 1
@[extern c inline "(uint64_t)#1"]
def BinderInfo.toUInt64 : BinderInfo → UInt64
| .default => 0
| .implicit => 1
| .strictImplicit => 2
| .instImplicit => 3
| .auxDecl => 4
def Expr.mkData
(h : UInt64) (looseBVarRange : Nat := 0) (approxDepth : UInt32 := 0)
(hasFVar hasExprMVar hasLevelMVar hasLevelParam : Bool := false)
: Expr.Data :=
let approxDepth : UInt8 := if approxDepth > 255 then 255 else approxDepth.toUInt8
assert! (looseBVarRange ≤ Nat.pow 2 20 - 1)
let r : UInt64 :=
h.toUInt32.toUInt64 +
approxDepth.toUInt64.shiftLeft 32 +
hasFVar.toUInt64.shiftLeft 40 +
hasExprMVar.toUInt64.shiftLeft 41 +
hasLevelMVar.toUInt64.shiftLeft 42 +
hasLevelParam.toUInt64.shiftLeft 43 +
looseBVarRange.toUInt64.shiftLeft 44
r
/-- Optimized version of `Expr.mkData` for applications. -/
@[inline] def Expr.mkAppData (fData : Data) (aData : Data) : Data :=
let depth := (max fData.approxDepth.toUInt16 aData.approxDepth.toUInt16) + 1
let approxDepth := if depth > 255 then 255 else depth.toUInt8
let looseBVarRange := max fData.looseBVarRange aData.looseBVarRange
let hash := mixHash fData aData
let fData : UInt64 := fData
let aData : UInt64 := aData
assert! (looseBVarRange ≤ (Nat.pow 2 20 - 1).toUInt32)
((fData ||| aData) &&& ((15 : UInt64) <<< (40 : UInt64))) ||| hash.toUInt32.toUInt64 ||| (approxDepth.toUInt64 <<< (32 : UInt64)) ||| (looseBVarRange.toUInt64 <<< (44 : UInt64))
@[inline] def Expr.mkDataForBinder (h : UInt64) (looseBVarRange : Nat) (approxDepth : UInt32) (hasFVar hasExprMVar hasLevelMVar hasLevelParam : Bool) : Expr.Data :=
Expr.mkData h looseBVarRange approxDepth hasFVar hasExprMVar hasLevelMVar hasLevelParam
@[inline] def Expr.mkDataForLet (h : UInt64) (looseBVarRange : Nat) (approxDepth : UInt32) (hasFVar hasExprMVar hasLevelMVar hasLevelParam : Bool) : Expr.Data :=
Expr.mkData h looseBVarRange approxDepth hasFVar hasExprMVar hasLevelMVar hasLevelParam
instance : Repr Expr.Data where
reprPrec v prec := Id.run do
let mut r := "Expr.mkData " ++ toString v.hash
if v.looseBVarRange != 0 then
r := r ++ " (looseBVarRange := " ++ toString v.looseBVarRange ++ ")"
if v.approxDepth != 0 then
r := r ++ " (approxDepth := " ++ toString v.approxDepth ++ ")"
if v.hasFVar then
r := r ++ " (hasFVar := " ++ toString v.hasFVar ++ ")"
if v.hasExprMVar then
r := r ++ " (hasExprMVar := " ++ toString v.hasExprMVar ++ ")"
if v.hasLevelMVar then
r := r ++ " (hasLevelMVar := " ++ toString v.hasLevelMVar ++ ")"
Repr.addAppParen r prec
open Expr
/--
The unique free variable identifier. It is just a hierarchical name,
but we wrap it in `FVarId` to make sure they don't get mixed up with `MVarId`.
This is not the user-facing name for a free variable. This information is stored
in the local context (`LocalContext`). The unique identifiers are generated using
a `NameGenerator`.
-/
structure FVarId where
name : Name
deriving Inhabited, BEq, Hashable
instance : Repr FVarId where
reprPrec n p := reprPrec n.name p
/--
A set of unique free variable identifiers.
This is a persistent data structure implemented using red-black trees. -/
def FVarIdSet := RBTree FVarId (Name.quickCmp ·.name ·.name)
deriving Inhabited, EmptyCollection
instance : ForIn m FVarIdSet FVarId := inferInstanceAs (ForIn _ (RBTree ..) ..)
/--
A set of unique free variable identifiers implemented using hashtables.
Hashtables are faster than red-black trees if they are used linearly.
They are not persistent data-structures. -/
def FVarIdHashSet := HashSet FVarId
deriving Inhabited, EmptyCollection
/--
A mapping from free variable identifiers to values of type `α`.
This is a persistent data structure implemented using red-black trees. -/
def FVarIdMap (α : Type) := RBMap FVarId α (Name.quickCmp ·.name ·.name)
instance : EmptyCollection (FVarIdMap α) := inferInstanceAs (EmptyCollection (RBMap ..))
instance : Inhabited (FVarIdMap α) where
default := {}
/-- Universe metavariable Id -/
structure MVarId where
name : Name
deriving Inhabited, BEq, Hashable, Repr
instance : Repr MVarId where
reprPrec n p := reprPrec n.name p
def MVarIdSet := RBTree MVarId (Name.quickCmp ·.name ·.name)
deriving Inhabited, EmptyCollection
instance : ForIn m MVarIdSet MVarId := inferInstanceAs (ForIn _ (RBTree ..) ..)
def MVarIdMap (α : Type) := RBMap MVarId α (Name.quickCmp ·.name ·.name)
instance : EmptyCollection (MVarIdMap α) := inferInstanceAs (EmptyCollection (RBMap ..))
instance : ForIn m (MVarIdMap α) (MVarId × α) := inferInstanceAs (ForIn _ (RBMap ..) ..)
instance : Inhabited (MVarIdMap α) where
default := {}
/--
Lean expressions. This data structure is used in the kernel and
elaborator. However, expressions sent to the kernel should not
contain metavariables.
Remark: we use the `E` suffix (short for `Expr`) to avoid collision with keywords.
We considered using «...», but it is too inconvenient to use.
-/
inductive Expr where
/--
The `bvar` constructor represents bound variables, i.e. occurrences
of a variable in the expression where there is a variable binder
above it (i.e. introduced by a `lam`, `forallE`, or `letE`).
The `deBruijnIndex` parameter is the *de-Bruijn* index for the bound
variable. See [here](https://en.wikipedia.org/wiki/De_Bruijn_index)
for additional information on de-Bruijn indexes.
For example, consider the expression `fun x : Nat => forall y : Nat, x = y`.
The `x` and `y` variables in the equality expression are constructed
using `bvar` and bound to the binders introduced by the earlier
`lam` and `forallE` constructors. Here is the corresponding `Expr` representation
for the same expression:
```lean
.lam `x (.const `Nat [])
(.forallE `y (.const `Nat [])
(.app (.app (.app (.const `Eq [.succ .zero]) (.const `Nat [])) (.bvar 1)) (.bvar 0))
.default)
.default
```
-/
| bvar (deBruijnIndex : Nat)
/--
The `fvar` constructor represent free variables. These /free/ variable
occurrences are not bound by an earlier `lam`, `forallE`, or `letE`
contructor and its binder exists in a local context only.
Note that Lean uses the /locally nameless approach/. See [here](https://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.365.2479&rep=rep1&type=pdf)
for additional details.
When "visiting" the body of a binding expression (i.e. `lam`, `forallE`, or `letE`),
bound variables are converted into free variables using a unique identifier,
and their user-facing name, type, value (for `LetE`), and binder annotation
are stored in the `LocalContext`.
-/
| fvar (fvarId : FVarId)
/--
Metavariables are used to represent "holes" in expressions, and goals in the
tactic framework. Metavariable declarations are stored in the `MetavarContext`.
Metavariables are used during elaboration, and are not allowed in the kernel,
or in the code generator.
-/
| mvar (mvarId : MVarId)
/--
Used for `Type u`, `Sort u`, and `Prop`:
- `Prop` is represented as `.sort .zero`,
- `Sort u` as ``.sort (.param `u)``, and
- `Type u` as ``.sort (.succ (.param `u))``
-/
| sort (u : Level)
/--
A (universe polymorphic) constant that has been defined earlier in the module or
by another imported module. For example, `@Eq.{1}` is represented
as ``Expr.const `Eq [.succ .zero]``, and `@Array.map.{0, 0}` is represented
as ``Expr.const `Array.map [.zero, .zero]``.
-/
| const (declName : Name) (us : List Level)
/--
A function application.
For example, the natural number one, i.e. `Nat.succ Nat.zero` is represented as
`Expr.app (.const `Nat.succ []) (.const .zero [])`
Note that multiple arguments are represented using partial application.
For example, the two argument application `f x y` is represented as
`Expr.app (.app f x) y`.
-/
| app (fn : Expr) (arg : Expr)
/--
A lambda abstraction (aka anonymous functions). It introduces a new binder for
variable `x` in scope for the lambda body.
For example, the expression `fun x : Nat => x` is represented as
```
Expr.lam `x (.const `Nat []) (.bvar 0) .default
```
-/
| lam (binderName : Name) (binderType : Expr) (body : Expr) (binderInfo : BinderInfo)
/--
A dependent arrow `(a : α) → β)` (aka forall-expression) where `β` may dependent
on `a`. Note that this constructor is also used to represent non-dependent arrows
where `β` does not depend on `a`.
For example:
- `forall x : Prop, x ∧ x`:
```lean
Expr.forallE `x (.sort .zero)
(.app (.app (.const `And []) (.bvar 0)) (.bvar 0)) .default
```
- `Nat → Bool`:
```lean
Expr.forallE `a (.const `Nat [])
(.const `Bool []) .default
```
-/
| forallE (binderName : Name) (binderType : Expr) (body : Expr) (binderInfo : BinderInfo)
/--
Let-expressions.
**IMPORTANT**: The `nonDep` flag is for "local" use only. That is, a module should not "trust" its value for any purpose.
In the intended use-case, the compiler will set this flag, and be responsible for maintaining it.
Other modules may not preserve its value while applying transformations.
Given an environment, a metavariable context, and a local context,
we say a let-expression `let x : t := v; e` is non-dependent when it is equivalent
to `(fun x : t => e) v`. Here is an example of a dependent let-expression
`let n : Nat := 2; fun (a : Array Nat n) (b : Array Nat 2) => a = b` is type correct,
but `(fun (n : Nat) (a : Array Nat n) (b : Array Nat 2) => a = b) 2` is not.
The let-expression `let x : Nat := 2; Nat.succ x` is represented as
```
Expr.letE `x (.const `Nat []) (.lit (.natVal 2)) (.bvar 0) true
```
-/
| letE (declName : Name) (type : Expr) (value : Expr) (body : Expr) (nonDep : Bool)
/--
Natural number and string literal values.
They are not really needed, but provide a more compact representation in memory
for these two kinds of literals, and are used to implement efficient reduction
in the elaborator and kernel. The "raw" natural number `2` can be represented
as `Expr.lit (.natVal 2)`. Note that, it is definitionally equal to:
```lean
Expr.app (.const `Nat.succ []) (.app (.const `Nat.succ []) (.const `Nat.zero []))
```
-/
| lit : Literal → Expr
/--
Metadata (aka annotations).
We use annotations to provide hints to the pretty-printer,
store references to `Syntax` nodes, position information, and save information for
elaboration procedures (e.g., we use the `inaccessible` annotation during elaboration to
mark `Expr`s that correspond to inaccessible patterns).
Note that `Expr.mdata data e` is definitionally equal to `e`.
-/
| mdata (data : MData) (expr : Expr)
/--
Projection-expressions. They are redundant, but are used to create more compact
terms, speedup reduction, and implement eta for structures.
The type of `struct` must be an structure-like inductive type. That is, it has only one
constructor, is not recursive, and it is not an inductive predicate. The kernel and elaborators
check whether the `typeName` matches the type of `struct`, and whether the (zero-based) index
is valid (i.e., it is smaller than the numbef of constructor fields).
When exporting Lean developments to other systems, `proj` can be replaced with `typeName`.`rec`
applications.
Example, given `a : Nat x Bool`, `a.1` is represented as
```
.proj `Prod 0 a
```
-/
| proj (typeName : Name) (idx : Nat) (struct : Expr)
with
@[computedField, extern c inline "lean_ctor_get_uint64(#1, lean_ctor_num_objs(#1)*sizeof(void*))"]
data : @& Expr → Data
| .const n lvls => mkData (mixHash 5 <| mixHash (hash n) (hash lvls)) 0 0 false false (lvls.any Level.hasMVar) (lvls.any Level.hasParam)
| .bvar idx => mkData (mixHash 7 <| hash idx) (idx+1)
| .sort lvl => mkData (mixHash 11 <| hash lvl) 0 0 false false lvl.hasMVar lvl.hasParam
| .fvar fvarId => mkData (mixHash 13 <| hash fvarId) 0 0 true
| .mvar fvarId => mkData (mixHash 17 <| hash fvarId) 0 0 false true
| .mdata _m e =>
let d := e.data.approxDepth.toUInt32+1
mkData (mixHash d.toUInt64 <| e.data.hash) e.data.looseBVarRange.toNat d e.data.hasFVar e.data.hasExprMVar e.data.hasLevelMVar e.data.hasLevelParam
| .proj s i e =>
let d := e.data.approxDepth.toUInt32+1
mkData (mixHash d.toUInt64 <| mixHash (hash s) <| mixHash (hash i) e.data.hash)
e.data.looseBVarRange.toNat d e.data.hasFVar e.data.hasExprMVar e.data.hasLevelMVar e.data.hasLevelParam
| .app f a => mkAppData f.data a.data
| .lam _ t b _ =>
let d := (max t.data.approxDepth.toUInt32 b.data.approxDepth.toUInt32) + 1
mkDataForBinder (mixHash d.toUInt64 <| mixHash t.data.hash b.data.hash)
(max t.data.looseBVarRange.toNat (b.data.looseBVarRange.toNat - 1))
d
(t.data.hasFVar || b.data.hasFVar)
(t.data.hasExprMVar || b.data.hasExprMVar)
(t.data.hasLevelMVar || b.data.hasLevelMVar)
(t.data.hasLevelParam || b.data.hasLevelParam)
| .forallE _ t b _ =>
let d := (max t.data.approxDepth.toUInt32 b.data.approxDepth.toUInt32) + 1
mkDataForBinder (mixHash d.toUInt64 <| mixHash t.data.hash b.data.hash)
(max t.data.looseBVarRange.toNat (b.data.looseBVarRange.toNat - 1))
d
(t.data.hasFVar || b.data.hasFVar)
(t.data.hasExprMVar || b.data.hasExprMVar)
(t.data.hasLevelMVar || b.data.hasLevelMVar)
(t.data.hasLevelParam || b.data.hasLevelParam)
| .letE _ t v b _ =>
let d := (max (max t.data.approxDepth.toUInt32 v.data.approxDepth.toUInt32) b.data.approxDepth.toUInt32) + 1
mkDataForLet (mixHash d.toUInt64 <| mixHash t.data.hash <| mixHash v.data.hash b.data.hash)
(max (max t.data.looseBVarRange.toNat v.data.looseBVarRange.toNat) (b.data.looseBVarRange.toNat - 1))
d
(t.data.hasFVar || v.data.hasFVar || b.data.hasFVar)
(t.data.hasExprMVar || v.data.hasExprMVar || b.data.hasExprMVar)
(t.data.hasLevelMVar || v.data.hasLevelMVar || b.data.hasLevelMVar)
(t.data.hasLevelParam || v.data.hasLevelParam || b.data.hasLevelParam)
| .lit l => mkData (mixHash 3 (hash l))
deriving Inhabited, Repr
namespace Expr
/-- The constructor name for the given expression. This is used for debugging purposes. -/
def ctorName : Expr → String
| bvar .. => "bvar"
| fvar .. => "fvar"
| mvar .. => "mvar"
| sort .. => "sort"
| const .. => "const"
| app .. => "app"
| lam .. => "lam"
| forallE .. => "forallE"
| letE .. => "letE"
| lit .. => "lit"
| mdata .. => "mdata"
| proj .. => "proj"
protected def hash (e : Expr) : UInt64 :=
e.data.hash
instance : Hashable Expr := ⟨Expr.hash⟩
/--
Return `true` if `e` contains free variables.
This is a constant time operation.
-/
def hasFVar (e : Expr) : Bool :=
e.data.hasFVar
/--
Return `true` if `e` contains expression metavariables.
This is a constant time operation.
-/
def hasExprMVar (e : Expr) : Bool :=
e.data.hasExprMVar
/--
Return `true` if `e` contains universe (aka `Level`) metavariables.
This is a constant time operation.
-/
def hasLevelMVar (e : Expr) : Bool :=
e.data.hasLevelMVar
/--
Does the expression contain level (aka universe) or expression metavariables?
This is a constant time operation.
-/
def hasMVar (e : Expr) : Bool :=
let d := e.data
d.hasExprMVar || d.hasLevelMVar
/--
Return true if `e` contains universe level parameters.
This is a constant time operation.
-/
def hasLevelParam (e : Expr) : Bool :=
e.data.hasLevelParam
/--
Return the approximated depth of an expression. This information is used to compute
the expression hash code, and speedup comparisons.
This is a constant time operation. We say it is approximate because it maxes out at `255`.
-/
def approxDepth (e : Expr) : UInt32 :=
e.data.approxDepth.toUInt32
/--
The range of de-Bruijn variables that are loose.
That is, bvars that are not bound by a binder.
For example, `bvar i` has range `i + 1` and
an expression with no loose bvars has range `0`.
-/
def looseBVarRange (e : Expr) : Nat :=
e.data.looseBVarRange.toNat
/--
Return the binder information if `e` is a lambda or forall expression, and `.default` otherwise.
-/
def binderInfo (e : Expr) : BinderInfo :=
match e with
| .forallE _ _ _ bi => bi
| .lam _ _ _ bi => bi
| _ => .default
/-!
Export functions.
-/
@[export lean_expr_hash] def hashEx : Expr → UInt64 := hash
@[export lean_expr_has_fvar] def hasFVarEx : Expr → Bool := hasFVar
@[export lean_expr_has_expr_mvar] def hasExprMVarEx : Expr → Bool := hasExprMVar
@[export lean_expr_has_level_mvar] def hasLevelMVarEx : Expr → Bool := hasLevelMVar
@[export lean_expr_has_mvar] def hasMVarEx : Expr → Bool := hasMVar
@[export lean_expr_has_level_param] def hasLevelParamEx : Expr → Bool := hasLevelParam
@[export lean_expr_loose_bvar_range] def looseBVarRangeEx (e : Expr) : UInt32 := e.data.looseBVarRange
@[export lean_expr_binder_info] def binderInfoEx : Expr → BinderInfo := binderInfo
end Expr
/-- `mkConst declName us` return `.const declName us`. -/
def mkConst (declName : Name) (us : List Level := []) : Expr :=
.const declName us
/-- Return the type of a literal value. -/
def Literal.type : Literal → Expr
| .natVal _ => mkConst `Nat
| .strVal _ => mkConst `String
@[export lean_lit_type]
def Literal.typeEx : Literal → Expr := Literal.type
/-- `.bvar idx` is now the preferred form. -/
def mkBVar (idx : Nat) : Expr :=
.bvar idx
/-- `.sort u` is now the preferred form. -/
def mkSort (u : Level) : Expr :=
.sort u
/--
`.fvar fvarId` is now the preferred form.
This function is seldom used, free variables are often automatically created using the
telescope functions (e.g., `forallTelescope` and `lambdaTelescope`) at `MetaM`.
-/
def mkFVar (fvarId : FVarId) : Expr :=
.fvar fvarId
/--
`.mvar mvarId` is now the preferred form.
This function is seldom used, metavariables are often created using functions such
as `mkFresheExprMVar` at `MetaM`.
-/
def mkMVar (mvarId : MVarId) : Expr :=
.mvar mvarId
/--
`.mdata m e` is now the preferred form.
-/
def mkMData (m : MData) (e : Expr) : Expr :=
.mdata m e
/--
`.proj structName idx struct` is now the preferred form.
-/
def mkProj (structName : Name) (idx : Nat) (struct : Expr) : Expr :=
.proj structName idx struct
/--
`.app f a` is now the preferred form.
-/
def mkApp (f a : Expr) : Expr :=
.app f a
/--
`.lam x t b bi` is now the preferred form.
-/
def mkLambda (x : Name) (bi : BinderInfo) (t : Expr) (b : Expr) : Expr :=
.lam x t b bi
/--
`.forallE x t b bi` is now the preferred form.
-/
def mkForall (x : Name) (bi : BinderInfo) (t : Expr) (b : Expr) : Expr :=
.forallE x t b bi
/-- Return `Unit -> type`. Do not confuse with `Thunk type` -/
def mkSimpleThunkType (type : Expr) : Expr :=
mkForall Name.anonymous .default (mkConst `Unit) type
/-- Return `fun (_ : Unit), e` -/
def mkSimpleThunk (type : Expr) : Expr :=
mkLambda `_ BinderInfo.default (mkConst `Unit) type
/--
`.letE x t v b nonDep` is now the preferred form.
-/
def mkLet (x : Name) (t : Expr) (v : Expr) (b : Expr) (nonDep : Bool := false) : Expr :=
.letE x t v b nonDep
def mkAppB (f a b : Expr) := mkApp (mkApp f a) b
def mkApp2 (f a b : Expr) := mkAppB f a b
def mkApp3 (f a b c : Expr) := mkApp (mkAppB f a b) c
def mkApp4 (f a b c d : Expr) := mkAppB (mkAppB f a b) c d
def mkApp5 (f a b c d e : Expr) := mkApp (mkApp4 f a b c d) e
def mkApp6 (f a b c d e₁ e₂ : Expr) := mkAppB (mkApp4 f a b c d) e₁ e₂
def mkApp7 (f a b c d e₁ e₂ e₃ : Expr) := mkApp3 (mkApp4 f a b c d) e₁ e₂ e₃
def mkApp8 (f a b c d e₁ e₂ e₃ e₄ : Expr) := mkApp4 (mkApp4 f a b c d) e₁ e₂ e₃ e₄
def mkApp9 (f a b c d e₁ e₂ e₃ e₄ e₅ : Expr) := mkApp5 (mkApp4 f a b c d) e₁ e₂ e₃ e₄ e₅
def mkApp10 (f a b c d e₁ e₂ e₃ e₄ e₅ e₆ : Expr) := mkApp6 (mkApp4 f a b c d) e₁ e₂ e₃ e₄ e₅ e₆
/--
`.lit l` is now the preferred form.
-/
def mkLit (l : Literal) : Expr :=
.lit l
/--
Return the "raw" natural number `.lit (.natVal n)`.
This is not the default representation used by the Lean frontend.
See `mkNatLit`.
-/
def mkRawNatLit (n : Nat) : Expr :=
mkLit (.natVal n)
/--
Return a natural number literal used in the frontend. It is a `OfNat.ofNat` application.
Recall that all theorems and definitions containing numeric literals are encoded using
`OfNat.ofNat` applications in the frontend.
-/
def mkNatLit (n : Nat) : Expr :=
let r := mkRawNatLit n
mkApp3 (mkConst ``OfNat.ofNat [levelZero]) (mkConst ``Nat) r (mkApp (mkConst ``instOfNatNat) r)
/-- Return the string literal `.lit (.strVal s)` -/
def mkStrLit (s : String) : Expr :=
mkLit (.strVal s)
@[export lean_expr_mk_bvar] def mkBVarEx : Nat → Expr := mkBVar
@[export lean_expr_mk_fvar] def mkFVarEx : FVarId → Expr := mkFVar
@[export lean_expr_mk_mvar] def mkMVarEx : MVarId → Expr := mkMVar
@[export lean_expr_mk_sort] def mkSortEx : Level → Expr := mkSort
@[export lean_expr_mk_const] def mkConstEx (c : Name) (lvls : List Level) : Expr := mkConst c lvls
@[export lean_expr_mk_app] def mkAppEx : Expr → Expr → Expr := mkApp
@[export lean_expr_mk_lambda] def mkLambdaEx (n : Name) (d b : Expr) (bi : BinderInfo) : Expr := mkLambda n bi d b
@[export lean_expr_mk_forall] def mkForallEx (n : Name) (d b : Expr) (bi : BinderInfo) : Expr := mkForall n bi d b
@[export lean_expr_mk_let] def mkLetEx (n : Name) (t v b : Expr) : Expr := mkLet n t v b
@[export lean_expr_mk_lit] def mkLitEx : Literal → Expr := mkLit
@[export lean_expr_mk_mdata] def mkMDataEx : MData → Expr → Expr := mkMData
@[export lean_expr_mk_proj] def mkProjEx : Name → Nat → Expr → Expr := mkProj
/-- `mkAppN f #[a₀, ..., aₙ]` ==> `f a₀ a₁ .. aₙ`-/
def mkAppN (f : Expr) (args : Array Expr) : Expr :=
args.foldl mkApp f
private partial def mkAppRangeAux (n : Nat) (args : Array Expr) (i : Nat) (e : Expr) : Expr :=
if i < n then mkAppRangeAux n args (i+1) (mkApp e (args.get! i)) else e
/-- `mkAppRange f i j #[a_1, ..., a_i, ..., a_j, ... ]` ==> the expression `f a_i ... a_{j-1}` -/
def mkAppRange (f : Expr) (i j : Nat) (args : Array Expr) : Expr :=
mkAppRangeAux j args i f
/-- Same as `mkApp f args` but reversing `args`. -/
def mkAppRev (fn : Expr) (revArgs : Array Expr) : Expr :=
revArgs.foldr (fun a r => mkApp r a) fn
namespace Expr
-- TODO: implement it in Lean
@[extern "lean_expr_dbg_to_string"]
opaque dbgToString (e : @& Expr) : String
/-- A total order for expressions. We say it is quick because it first compares the hashcodes. -/
@[extern "lean_expr_quick_lt"]
opaque quickLt (a : @& Expr) (b : @& Expr) : Bool
/-- A total order for expressions that takes the structure into account (e.g., variable names). -/
@[extern "lean_expr_lt"]
opaque lt (a : @& Expr) (b : @& Expr) : Bool
/--
Return true iff `a` and `b` are alpha equivalent.
Binder annotations are ignored.
-/
@[extern "lean_expr_eqv"]
opaque eqv (a : @& Expr) (b : @& Expr) : Bool
instance : BEq Expr where
beq := Expr.eqv
/--
Return true iff `a` and `b` are equal.
Binder names and annotations are taking into account.
-/
@[extern "lean_expr_equal"]
opaque equal (a : @& Expr) (b : @& Expr) : Bool
/-- Return `true` if the given expression is a `.sort ..` -/
def isSort : Expr → Bool
| sort .. => true
| _ => false
/-- Return `true` if the given expression is of the form `.sort (.succ ..)`. -/
def isType : Expr → Bool
| sort (.succ ..) => true
| _ => false
/-- Return `true` if the given expression is of the form `.sort (.succ .zero)`. -/
def isType0 : Expr → Bool
| sort (.succ .zero) => true
| _ => false
/-- Return `true` if the given expression is a `.sort .zero` -/
def isProp : Expr → Bool
| sort (.zero ..) => true
| _ => false
/-- Return `true` if the given expression is a bound variable. -/
def isBVar : Expr → Bool
| bvar .. => true
| _ => false
/-- Return `true` if the given expression is a metavariable. -/
def isMVar : Expr → Bool
| mvar .. => true
| _ => false
/-- Return `true` if the given expression is a free variable. -/
def isFVar : Expr → Bool
| fvar .. => true
| _ => false
/-- Return `true` if the given expression is an application. -/
def isApp : Expr → Bool
| app .. => true
| _ => false
/-- Return `true` if the given expression is a projection `.proj ..` -/
def isProj : Expr → Bool
| proj .. => true
| _ => false
/-- Return `true` if the given expression is a constant. -/
def isConst : Expr → Bool
| const .. => true
| _ => false
/--
Return `true` if the given expression is a constant of the give name.
Examples:
- `` (.const `Nat []).isConstOf `Nat `` is `true`
- `` (.const `Nat []).isConstOf `False `` is `false`
-/
def isConstOf : Expr → Name → Bool
| const n .., m => n == m
| _, _ => false
/--
Return `true` if the given expression is a free variable with the given id.
Examples:
- `isFVarOf (.fvar id) id` is `true`
- ``isFVarOf (.fvar id) id'`` is `false`
- ``isFVarOf (.sort levelZero) id`` is `false`
-/
def isFVarOf : Expr → FVarId → Bool
| .fvar fvarId, fvarId' => fvarId == fvarId'
| _, _ => false
/-- Return `true` if the given expression is a forall-expression aka (dependent) arrow. -/
def isForall : Expr → Bool
| forallE .. => true
| _ => false
/-- Return `true` if the given expression is a lambda abstraction aka anonymous function. -/
def isLambda : Expr → Bool
| lam .. => true
| _ => false
/-- Return `true` if the given expression is a forall or lambda expression. -/
def isBinding : Expr → Bool
| lam .. => true
| forallE .. => true
| _ => false
/-- Return `true` if the given expression is a let-expression. -/
def isLet : Expr → Bool
| letE .. => true
| _ => false
/-- Return `true` if the given expression is a metadata. -/
def isMData : Expr → Bool
| mdata .. => true
| _ => false
/-- Return `true` if the given expression is a literal value. -/
def isLit : Expr → Bool
| lit .. => true
| _ => false
/--
Return the "body" of a forall expression.
Example: let `e` be the representation for `forall (p : Prop) (q : Prop), p ∧ q`, then
`getForallBody e` returns ``.app (.app (.const `And []) (.bvar 1)) (.bvar 0)``
-/
def getForallBody : Expr → Expr
| forallE _ _ b .. => getForallBody b
| e => e
def getForallBodyMaxDepth : (maxDepth : Nat) → Expr → Expr
| (n+1), forallE _ _ b _ => getForallBodyMaxDepth n b
| 0, e => e
| _, e => e
/-- Given a sequence of nested foralls `(a₁ : α₁) → ... → (aₙ : αₙ) → _`,
returns the names `[a₁, ... aₙ]`. -/
def getForallBinderNames : Expr → List Name
| forallE n _ b _ => n :: getForallBinderNames b
| _ => []
/--
If the given expression is a sequence of
function applications `f a₁ .. aₙ`, return `f`.
Otherwise return the input expression.
-/
def getAppFn : Expr → Expr
| app f _ => getAppFn f
| e => e
private def getAppNumArgsAux : Expr → Nat → Nat
| app f _, n => getAppNumArgsAux f (n+1)
| _, n => n
/-- Counts the number `n` of arguments for an expression `f a₁ .. aₙ`. -/
def getAppNumArgs (e : Expr) : Nat :=
getAppNumArgsAux e 0
private def getAppArgsAux : Expr → Array Expr → Nat → Array Expr
| app f a, as, i => getAppArgsAux f (as.set! i a) (i-1)
| _, as, _ => as
/-- Given `f a₁ a₂ ... aₙ`, returns `#[a₁, ..., aₙ]` -/
@[inline] def getAppArgs (e : Expr) : Array Expr :=
let dummy := mkSort levelZero
let nargs := e.getAppNumArgs
getAppArgsAux e (mkArray nargs dummy) (nargs-1)
private def getAppRevArgsAux : Expr → Array Expr → Array Expr
| app f a, as => getAppRevArgsAux f (as.push a)
| _, as => as
/-- Same as `getAppArgs` but reverse the output array. -/
@[inline] def getAppRevArgs (e : Expr) : Array Expr :=
getAppRevArgsAux e (Array.mkEmpty e.getAppNumArgs)
@[specialize] def withAppAux (k : Expr → Array Expr → α) : Expr → Array Expr → Nat → α
| app f a, as, i => withAppAux k f (as.set! i a) (i-1)
| f, as, _ => k f as
/-- Given `e = f a₁ a₂ ... aₙ`, returns `k f #[a₁, ..., aₙ]`. -/
@[inline] def withApp (e : Expr) (k : Expr → Array Expr → α) : α :=
let dummy := mkSort levelZero
let nargs := e.getAppNumArgs
withAppAux k e (mkArray nargs dummy) (nargs-1)
/-- Given `e = fn a₁ ... aₙ`, runs `f` on `fn` and each of the arguments `aᵢ` and
makes a new function application with the results. -/
def traverseApp {M} [Monad M]
(f : Expr → M Expr) (e : Expr) : M Expr :=
e.withApp fun fn args => mkAppN <$> f fn <*> args.mapM f
@[specialize] private def withAppRevAux (k : Expr → Array Expr → α) : Expr → Array Expr → α
| app f a, as => withAppRevAux k f (as.push a)
| f, as => k f as
/-- Same as `withApp` but with arguments reversed. -/
@[inline] def withAppRev (e : Expr) (k : Expr → Array Expr → α) : α :=
withAppRevAux k e (Array.mkEmpty e.getAppNumArgs)
def getRevArgD : Expr → Nat → Expr → Expr
| app _ a, 0, _ => a
| app f _, i+1, v => getRevArgD f i v
| _, _, v => v
def getRevArg! : Expr → Nat → Expr
| app _ a, 0 => a
| app f _, i+1 => getRevArg! f i
| _, _ => panic! "invalid index"
/-- Given `f a₀ a₁ ... aₙ`, returns the `i`th argument or panics if out of bounds. -/
@[inline] def getArg! (e : Expr) (i : Nat) (n := e.getAppNumArgs) : Expr :=
getRevArg! e (n - i - 1)
/-- Given `f a₀ a₁ ... aₙ`, returns the `i`th argument or returns `v₀` if out of bounds. -/
@[inline] def getArgD (e : Expr) (i : Nat) (v₀ : Expr) (n := e.getAppNumArgs) : Expr :=
getRevArgD e (n - i - 1) v₀
/-- Given `f a₀ a₁ ... aₙ`, returns true if `f` is a constant with name `n`. -/
def isAppOf (e : Expr) (n : Name) : Bool :=
match e.getAppFn with
| const c _ => c == n
| _ => false
/--
Given `f a₁ ... aᵢ`, returns true if `f` is a constant
with name `n` and has the correct number of arguments.
-/
def isAppOfArity : Expr → Name → Nat → Bool
| const c _, n, 0 => c == n
| app f _, n, a+1 => isAppOfArity f n a
| _, _, _ => false
/-- Similar to `isAppOfArity` but skips `Expr.mdata`. -/
def isAppOfArity' : Expr → Name → Nat → Bool
| mdata _ b , n, a => isAppOfArity' b n a
| const c _, n, 0 => c == n
| app f _, n, a+1 => isAppOfArity' f n a
| _, _, _ => false
def appFn! : Expr → Expr
| app f _ => f
| _ => panic! "application expected"
def appArg! : Expr → Expr
| app _ a => a
| _ => panic! "application expected"
def appFn!' : Expr → Expr
| mdata _ b => appFn!' b
| app f _ => f
| _ => panic! "application expected"
def appArg!' : Expr → Expr
| mdata _ b => appArg!' b
| app _ a => a
| _ => panic! "application expected"
def sortLevel! : Expr → Level
| sort u => u
| _ => panic! "sort expected"
def litValue! : Expr → Literal
| lit v => v
| _ => panic! "literal expected"
def isNatLit : Expr → Bool
| lit (Literal.natVal _) => true
| _ => false
def natLit? : Expr → Option Nat
| lit (Literal.natVal v) => v
| _ => none
def isStringLit : Expr → Bool
| lit (Literal.strVal _) => true
| _ => false
def isCharLit (e : Expr) : Bool :=
e.isAppOfArity ``Char.ofNat 1 && e.appArg!.isNatLit
def constName! : Expr → Name
| const n _ => n
| _ => panic! "constant expected"
def constName? : Expr → Option Name
| const n _ => some n
| _ => none
def constLevels! : Expr → List Level
| const _ ls => ls
| _ => panic! "constant expected"
def bvarIdx! : Expr → Nat
| bvar idx => idx
| _ => panic! "bvar expected"
def fvarId! : Expr → FVarId
| fvar n => n
| _ => panic! "fvar expected"
def mvarId! : Expr → MVarId
| mvar n => n
| _ => panic! "mvar expected"
def bindingName! : Expr → Name
| forallE n _ _ _ => n
| lam n _ _ _ => n
| _ => panic! "binding expected"
def bindingDomain! : Expr → Expr
| forallE _ d _ _ => d
| lam _ d _ _ => d
| _ => panic! "binding expected"
def bindingBody! : Expr → Expr
| forallE _ _ b _ => b
| lam _ _ b _ => b
| _ => panic! "binding expected"
def bindingInfo! : Expr → BinderInfo
| forallE _ _ _ bi => bi
| lam _ _ _ bi => bi
| _ => panic! "binding expected"
def letName! : Expr → Name
| letE n .. => n
| _ => panic! "let expression expected"
def letType! : Expr → Expr
| letE _ t .. => t
| _ => panic! "let expression expected"
def letValue! : Expr → Expr
| letE _ _ v .. => v
| _ => panic! "let expression expected"
def letBody! : Expr → Expr
| letE _ _ _ b .. => b
| _ => panic! "let expression expected"
def consumeMData : Expr → Expr
| mdata _ e => consumeMData e
| e => e
def mdataExpr! : Expr → Expr
| mdata _ e => e
| _ => panic! "mdata expression expected"
def projExpr! : Expr → Expr
| proj _ _ e => e
| _ => panic! "proj expression expected"
def projIdx! : Expr → Nat
| proj _ i _ => i
| _ => panic! "proj expression expected"
def hasLooseBVars (e : Expr) : Bool :=
e.looseBVarRange > 0
/--
Return `true` if `e` is a non-dependent arrow.
Remark: the following function assumes `e` does not have loose bound variables.
-/
def isArrow (e : Expr) : Bool :=
match e with
| forallE _ _ b _ => !b.hasLooseBVars
| _ => false
@[extern "lean_expr_has_loose_bvar"]
opaque hasLooseBVar (e : @& Expr) (bvarIdx : @& Nat) : Bool
/-- Return true if `e` contains the loose bound variable `bvarIdx` in an explicit parameter, or in the range if `tryRange == true`. -/
def hasLooseBVarInExplicitDomain : Expr → Nat → Bool → Bool
| Expr.forallE _ d b bi, bvarIdx, tryRange =>
(bi.isExplicit && hasLooseBVar d bvarIdx) || hasLooseBVarInExplicitDomain b (bvarIdx+1) tryRange
| e, bvarIdx, tryRange => tryRange && hasLooseBVar e bvarIdx
/--
Lower the loose bound variables `>= s` in `e` by `d`.
That is, a loose bound variable `bvar i`.
`i >= s` is mapped into `bvar (i-d)`.
Remark: if `s < d`, then result is `e`
-/
@[extern "lean_expr_lower_loose_bvars"]
opaque lowerLooseBVars (e : @& Expr) (s d : @& Nat) : Expr
/--
Lift loose bound variables `>= s` in `e` by `d`. -/
@[extern "lean_expr_lift_loose_bvars"]
opaque liftLooseBVars (e : @& Expr) (s d : @& Nat) : Expr
/--
`inferImplicit e numParams considerRange` updates the first `numParams` parameter binder annotations of the `e` forall type.
It marks any parameter with an explicit binder annotation if there is another explicit arguments that depends on it or
the resulting type if `considerRange == true`.
Remark: we use this function to infer the bind annotations of inductive datatype constructors, and structure projections.
When the `{}` annotation is used in these commands, we set `considerRange == false`.
-/
def inferImplicit : Expr → Nat → Bool → Expr
| Expr.forallE n d b bi, i+1, considerRange =>
let b := inferImplicit b i considerRange
let newInfo := if bi.isExplicit && hasLooseBVarInExplicitDomain b 0 considerRange then BinderInfo.implicit else bi
mkForall n newInfo d b
| e, 0, _ => e
| e, _, _ => e
/--
Instantiate the loose bound variables in `e` using `subst`.
That is, a loose `Expr.bvar i` is replaced with `subst[i]`.
-/
@[extern "lean_expr_instantiate"]
opaque instantiate (e : @& Expr) (subst : @& Array Expr) : Expr
@[extern "lean_expr_instantiate1"]
opaque instantiate1 (e : @& Expr) (subst : @& Expr) : Expr
/-- Similar to instantiate, but `Expr.bvar i` is replaced with `subst[subst.size - i - 1]` -/
@[extern "lean_expr_instantiate_rev"]
opaque instantiateRev (e : @& Expr) (subst : @& Array Expr) : Expr
/--
Similar to `instantiate`, but consider only the variables `xs` in the range `[beginIdx, endIdx)`.
Function panics if `beginIdx <= endIdx <= xs.size` does not hold.
-/
@[extern "lean_expr_instantiate_range"]
opaque instantiateRange (e : @& Expr) (beginIdx endIdx : @& Nat) (xs : @& Array Expr) : Expr
/--
Similar to `instantiateRev`, but consider only the variables `xs` in the range `[beginIdx, endIdx)`.
Function panics if `beginIdx <= endIdx <= xs.size` does not hold.
-/
@[extern "lean_expr_instantiate_rev_range"]
opaque instantiateRevRange (e : @& Expr) (beginIdx endIdx : @& Nat) (xs : @& Array Expr) : Expr
/-- Replace free (or meta) variables `xs` with loose bound variables. -/
@[extern "lean_expr_abstract"]
opaque abstract (e : @& Expr) (xs : @& Array Expr) : Expr
/-- Similar to `abstract`, but consider only the first `min n xs.size` entries in `xs`. -/
@[extern "lean_expr_abstract_range"]
opaque abstractRange (e : @& Expr) (n : @& Nat) (xs : @& Array Expr) : Expr
/-- Replace occurrences of the free variable `fvar` in `e` with `v` -/
def replaceFVar (e : Expr) (fvar : Expr) (v : Expr) : Expr :=
(e.abstract #[fvar]).instantiate1 v
/-- Replace occurrences of the free variable `fvarId` in `e` with `v` -/
def replaceFVarId (e : Expr) (fvarId : FVarId) (v : Expr) : Expr :=
replaceFVar e (mkFVar fvarId) v
/-- Replace occurrences of the free variables `fvars` in `e` with `vs` -/
def replaceFVars (e : Expr) (fvars : Array Expr) (vs : Array Expr) : Expr :=
(e.abstract fvars).instantiateRev vs
instance : ToString Expr where
toString := Expr.dbgToString
/-- Returns true when the expression does not have any sub-expressions. -/
def isAtomic : Expr → Bool
| Expr.const .. => true
| Expr.sort .. => true
| Expr.bvar .. => true
| Expr.lit .. => true
| Expr.mvar .. => true
| Expr.fvar .. => true
| _ => false
end Expr
def mkDecIsTrue (pred proof : Expr) :=
mkAppB (mkConst `Decidable.isTrue) pred proof
def mkDecIsFalse (pred proof : Expr) :=
mkAppB (mkConst `Decidable.isFalse) pred proof
abbrev ExprMap (α : Type) := HashMap Expr α
abbrev PersistentExprMap (α : Type) := PHashMap Expr α
abbrev ExprSet := HashSet Expr
abbrev PersistentExprSet := PHashSet Expr
abbrev PExprSet := PersistentExprSet
/-- Auxiliary type for forcing `==` to be structural equality for `Expr` -/
structure ExprStructEq where
val : Expr
deriving Inhabited
instance : Coe Expr ExprStructEq := ⟨ExprStructEq.mk⟩
namespace ExprStructEq
protected def beq : ExprStructEq → ExprStructEq → Bool
| ⟨e₁⟩, ⟨e₂⟩ => Expr.equal e₁ e₂
protected def hash : ExprStructEq → UInt64
| ⟨e⟩ => e.hash
instance : BEq ExprStructEq := ⟨ExprStructEq.beq⟩
instance : Hashable ExprStructEq := ⟨ExprStructEq.hash⟩
instance : ToString ExprStructEq := ⟨fun e => toString e.val⟩
end ExprStructEq
abbrev ExprStructMap (α : Type) := HashMap ExprStructEq α
abbrev PersistentExprStructMap (α : Type) := PHashMap ExprStructEq α
namespace Expr
private partial def mkAppRevRangeAux (revArgs : Array Expr) (start : Nat) (b : Expr) (i : Nat) : Expr :=
if i == start then b
else
let i := i - 1
mkAppRevRangeAux revArgs start (mkApp b (revArgs.get! i)) i
/-- `mkAppRevRange f b e args == mkAppRev f (revArgs.extract b e)` -/
def mkAppRevRange (f : Expr) (beginIdx endIdx : Nat) (revArgs : Array Expr) : Expr :=
mkAppRevRangeAux revArgs beginIdx f endIdx
/--
If `f` is a lambda expression, than "beta-reduce" it using `revArgs`.
This function is often used with `getAppRev` or `withAppRev`.
Examples:
- `betaRev (fun x y => t x y) #[]` ==> `fun x y => t x y`
- `betaRev (fun x y => t x y) #[a]` ==> `fun y => t a y`
- `betaRev (fun x y => t x y) #[a, b]` ==> `t b a`
- `betaRev (fun x y => t x y) #[a, b, c, d]` ==> `t d c b a`
Suppose `t` is `(fun x y => t x y) a b c d`, then
`args := t.getAppRev` is `#[d, c, b, a]`,
and `betaRev (fun x y => t x y) #[d, c, b, a]` is `t a b c d`.
If `useZeta` is true, the function also performs zeta-reduction (reduction of let binders) to create further
opportunities for beta reduction.
-/
partial def betaRev (f : Expr) (revArgs : Array Expr) (useZeta := false) (preserveMData := false) : Expr :=
if revArgs.size == 0 then f
else
let sz := revArgs.size
let rec go (e : Expr) (i : Nat) : Expr :=
match e with
| Expr.lam _ _ b _ =>
if i + 1 < sz then
go b (i+1)
else
let n := sz - (i + 1)
mkAppRevRange (b.instantiateRange n sz revArgs) 0 n revArgs
| Expr.letE _ _ v b _ =>
if useZeta && i < sz then
go (b.instantiate1 v) i
else
let n := sz - i
mkAppRevRange (e.instantiateRange n sz revArgs) 0 n revArgs
| Expr.mdata k b =>
if preserveMData then
let n := sz - i
mkMData k (mkAppRevRange (b.instantiateRange n sz revArgs) 0 n revArgs)
else
go b i
| b =>
let n := sz - i
mkAppRevRange (b.instantiateRange n sz revArgs) 0 n revArgs
go f 0
/--
Apply the given arguments to `f`, beta-reducing if `f` is a
lambda expression. See docstring for `betaRev` for examples.
-/
def beta (f : Expr) (args : Array Expr) : Expr :=
betaRev f args.reverse
/--
Return true if the given expression is the function of an expression that is target for (head) beta reduction.
If `useZeta = true`, then `let`-expressions are visited. That is, it assumes
that zeta-reduction (aka let-expansion) is going to be used.
See `isHeadBetaTarget`.
-/
def isHeadBetaTargetFn (useZeta : Bool) : Expr → Bool
| Expr.lam .. => true
| Expr.letE _ _ _ b _ => useZeta && isHeadBetaTargetFn useZeta b
| Expr.mdata _ b => isHeadBetaTargetFn useZeta b
| _ => false
/-- `(fun x => e) a` ==> `e[x/a]`. -/
def headBeta (e : Expr) : Expr :=
let f := e.getAppFn
if f.isHeadBetaTargetFn false then betaRev f e.getAppRevArgs else e
/--
Return true if the given expression is a target for (head) beta reduction.
If `useZeta = true`, then `let`-expressions are visited. That is, it assumes
that zeta-reduction (aka let-expansion) is going to be used.
-/
def isHeadBetaTarget (e : Expr) (useZeta := false) : Bool :=
e.isApp && e.getAppFn.isHeadBetaTargetFn useZeta
private def etaExpandedBody : Expr → Nat → Nat → Option Expr
| app f (bvar j), n+1, i => if j == i then etaExpandedBody f n (i+1) else none
| _, _+1, _ => none
| f, 0, _ => if f.hasLooseBVars then none else some f
private def etaExpandedAux : Expr → Nat → Option Expr
| lam _ _ b _, n => etaExpandedAux b (n+1)
| e, n => etaExpandedBody e n 0
/--
If `e` is of the form `(fun x₁ ... xₙ => f x₁ ... xₙ)` and `f` does not contain `x₁`, ..., `xₙ`,
then return `some f`. Otherwise, return `none`.
It assumes `e` does not have loose bound variables.
Remark: `ₙ` may be 0
-/
def etaExpanded? (e : Expr) : Option Expr :=
etaExpandedAux e 0
/-- Similar to `etaExpanded?`, but only succeeds if `ₙ ≥ 1`. -/
def etaExpandedStrict? : Expr → Option Expr
| lam _ _ b _ => etaExpandedAux b 1
| _ => none
/-- Return `some e'` if `e` is of the form `optParam _ e'` -/
def getOptParamDefault? (e : Expr) : Option Expr :=
if e.isAppOfArity ``optParam 2 then
some e.appArg!
else
none
/-- Return `some e'` if `e` is of the form `autoParam _ e'` -/
def getAutoParamTactic? (e : Expr) : Option Expr :=
if e.isAppOfArity ``autoParam 2 then
some e.appArg!
else
none
/-- Return `true` if `e` is of the form `outParam _` -/
@[export lean_is_out_param]
def isOutParam (e : Expr) : Bool :=
e.isAppOfArity ``outParam 1
/-- Return `true` if `e` is of the form `optParam _ _` -/
def isOptParam (e : Expr) : Bool :=
e.isAppOfArity ``optParam 2
/-- Return `true` if `e` is of the form `autoParam _ _` -/
def isAutoParam (e : Expr) : Bool :=
e.isAppOfArity ``autoParam 2
/--
Remove `outParam`, `optParam`, and `autoParam` applications/annotations from `e`.
Note that it does not remove nested annotations.
Examples:
- Given `e` of the form `outParam (optParam Nat b)`, `consumeTypeAnnotations e = b`.
- Given `e` of the form `Nat → outParam (optParam Nat b)`, `consumeTypeAnnotations e = e`.
-/
@[export lean_expr_consume_type_annotations]
partial def consumeTypeAnnotations (e : Expr) : Expr :=
if e.isOptParam || e.isAutoParam then
consumeTypeAnnotations e.appFn!.appArg!
else if e.isOutParam then
consumeTypeAnnotations e.appArg!
else
e
/--
Remove metadata annotations and `outParam`, `optParam`, and `autoParam` applications/annotations from `e`.
Note that it does not remove nested annotations.
Examples:
- Given `e` of the form `outParam (optParam Nat b)`, `cleanupAnnotations e = b`.
- Given `e` of the form `Nat → outParam (optParam Nat b)`, `cleanupAnnotations e = e`.
-/
partial def cleanupAnnotations (e : Expr) : Expr :=
let e' := e.consumeMData.consumeTypeAnnotations
if e' == e then e else cleanupAnnotations e'
/-- Return true iff `e` contains a free variable which statisfies `p`. -/
@[inline] def hasAnyFVar (e : Expr) (p : FVarId → Bool) : Bool :=
let rec @[specialize] visit (e : Expr) := if !e.hasFVar then false else
match e with
| Expr.forallE _ d b _ => visit d || visit b
| Expr.lam _ d b _ => visit d || visit b
| Expr.mdata _ e => visit e
| Expr.letE _ t v b _ => visit t || visit v || visit b
| Expr.app f a => visit f || visit a
| Expr.proj _ _ e => visit e
| Expr.fvar fvarId => p fvarId
| _ => false
visit e
/-- Return `true` if `e` contains the given free variable. -/
def containsFVar (e : Expr) (fvarId : FVarId) : Bool :=
e.hasAnyFVar (· == fvarId)
/-!
The update functions try to avoid allocating new values using pointer equality.
Note that if the `update*!` functions are used under a match-expression,
the compiler will eliminate the double-match.
-/
@[inline] private unsafe def updateApp!Impl (e : Expr) (newFn : Expr) (newArg : Expr) : Expr :=
match e with
| app fn arg => if ptrEq fn newFn && ptrEq arg newArg then e else mkApp newFn newArg
| _ => panic! "application expected"
@[implementedBy updateApp!Impl]
def updateApp! (e : Expr) (newFn : Expr) (newArg : Expr) : Expr :=
match e with
| app _ _ => mkApp newFn newArg
| _ => panic! "application expected"
@[inline] private unsafe def updateConst!Impl (e : Expr) (newLevels : List Level) : Expr :=
match e with
| const n ls => if ptrEqList ls newLevels then e else mkConst n newLevels
| _ => panic! "constant expected"
@[implementedBy updateConst!Impl]
def updateConst! (e : Expr) (newLevels : List Level) : Expr :=
match e with
| const n _ => mkConst n newLevels
| _ => panic! "constant expected"
@[inline] private unsafe def updateSort!Impl (e : Expr) (u' : Level) : Expr :=
match e with
| sort u => if ptrEq u u' then e else mkSort u'
| _ => panic! "level expected"
@[implementedBy updateSort!Impl]
def updateSort! (e : Expr) (newLevel : Level) : Expr :=
match e with
| sort _ => mkSort newLevel
| _ => panic! "level expected"
@[inline] private unsafe def updateMData!Impl (e : Expr) (newExpr : Expr) : Expr :=
match e with
| mdata d a => if ptrEq a newExpr then e else mkMData d newExpr
| _ => panic! "mdata expected"
@[implementedBy updateMData!Impl]
def updateMData! (e : Expr) (newExpr : Expr) : Expr :=
match e with
| mdata d _ => mkMData d newExpr
| _ => panic! "mdata expected"
@[inline] private unsafe def updateProj!Impl (e : Expr) (newExpr : Expr) : Expr :=
match e with
| proj s i a => if ptrEq a newExpr then e else mkProj s i newExpr
| _ => panic! "proj expected"
@[implementedBy updateProj!Impl]
def updateProj! (e : Expr) (newExpr : Expr) : Expr :=
match e with
| proj s i _ => mkProj s i newExpr
| _ => panic! "proj expected"
@[inline] private unsafe def updateForall!Impl (e : Expr) (newBinfo : BinderInfo) (newDomain : Expr) (newBody : Expr) : Expr :=
match e with
| forallE n d b bi =>
if ptrEq d newDomain && ptrEq b newBody && bi == newBinfo then
e
else
mkForall n newBinfo newDomain newBody
| _ => panic! "forall expected"
@[implementedBy updateForall!Impl]
def updateForall! (e : Expr) (newBinfo : BinderInfo) (newDomain : Expr) (newBody : Expr) : Expr :=
match e with
| forallE n _ _ _ => mkForall n newBinfo newDomain newBody
| _ => panic! "forall expected"
@[inline] def updateForallE! (e : Expr) (newDomain : Expr) (newBody : Expr) : Expr :=
match e with
| forallE n d b bi => updateForall! (forallE n d b bi) bi newDomain newBody
| _ => panic! "forall expected"
@[inline] private unsafe def updateLambda!Impl (e : Expr) (newBinfo : BinderInfo) (newDomain : Expr) (newBody : Expr) : Expr :=
match e with
| lam n d b bi =>
if ptrEq d newDomain && ptrEq b newBody && bi == newBinfo then
e
else
mkLambda n newBinfo newDomain newBody
| _ => panic! "lambda expected"
@[implementedBy updateLambda!Impl]
def updateLambda! (e : Expr) (newBinfo : BinderInfo) (newDomain : Expr) (newBody : Expr) : Expr :=
match e with
| lam n _ _ _ => mkLambda n newBinfo newDomain newBody
| _ => panic! "lambda expected"
@[inline] def updateLambdaE! (e : Expr) (newDomain : Expr) (newBody : Expr) : Expr :=
match e with
| lam n d b bi => updateLambda! (lam n d b bi) bi newDomain newBody
| _ => panic! "lambda expected"
@[inline] private unsafe def updateLet!Impl (e : Expr) (newType : Expr) (newVal : Expr) (newBody : Expr) : Expr :=
match e with
| letE n t v b nonDep =>
if ptrEq t newType && ptrEq v newVal && ptrEq b newBody then
e
else
letE n newType newVal newBody nonDep
| _ => panic! "let expression expected"
@[implementedBy updateLet!Impl]
def updateLet! (e : Expr) (newType : Expr) (newVal : Expr) (newBody : Expr) : Expr :=
match e with
| letE n _ _ _ c => letE n newType newVal newBody c
| _ => panic! "let expression expected"
def updateFn : Expr → Expr → Expr
| e@(app f a), g => e.updateApp! (updateFn f g) a
| _, g => g
/--
Eta reduction. If `e` is of the form `(fun x => f x)`, then return `f`.
-/
partial def eta (e : Expr) : Expr :=
match e with
| Expr.lam _ d b _ =>
let b' := b.eta
match b' with
| .app f (.bvar 0) =>
if !f.hasLooseBVar 0 then
f.lowerLooseBVars 1 1
else
e.updateLambdaE! d b'
| _ => e.updateLambdaE! d b'
| _ => e
/--
Instantiate level parameters
-/
@[inline] def instantiateLevelParamsCore (s : Name → Option Level) (e : Expr) : Expr :=
let rec @[specialize] visit (e : Expr) : Expr :=
if !e.hasLevelParam then e
else match e with
| lam _ d b _ => e.updateLambdaE! (visit d) (visit b)
| forallE _ d b _ => e.updateForallE! (visit d) (visit b)
| letE _ t v b _ => e.updateLet! (visit t) (visit v) (visit b)
| app f a => e.updateApp! (visit f) (visit a)
| proj _ _ s => e.updateProj! (visit s)
| mdata _ b => e.updateMData! (visit b)
| const _ us => e.updateConst! (us.map (fun u => u.instantiateParams s))
| sort u => e.updateSort! (u.instantiateParams s)
| e => e
visit e
private def getParamSubst : List Name → List Level → Name → Option Level
| p::ps, u::us, p' => if p == p' then some u else getParamSubst ps us p'
| _, _, _ => none
/--
Instantiate univeres level parameters names `paramNames` with `lvls` in `e`.
If the two lists have different length, the smallest one is used.
-/
def instantiateLevelParams (e : Expr) (paramNames : List Name) (lvls : List Level) : Expr :=
instantiateLevelParamsCore (getParamSubst paramNames lvls) e
private partial def getParamSubstArray (ps : Array Name) (us : Array Level) (p' : Name) (i : Nat) : Option Level :=
if h : i < ps.size then
let p := ps.get ⟨i, h⟩
if h : i < us.size then
let u := us.get ⟨i, h⟩
if p == p' then some u else getParamSubstArray ps us p' (i+1)
else none
else none
/--
Instantiate univeres level parameters names `paramNames` with `lvls` in `e`.
If the two arrays have different length, the smallest one is used.
-/
def instantiateLevelParamsArray (e : Expr) (paramNames : Array Name) (lvls : Array Level) : Expr :=
instantiateLevelParamsCore (fun p => getParamSubstArray paramNames lvls p 0) e
/--
Annotate `e` with the given option.
The information is stored using metadata around `e`.
-/
def setOption (e : Expr) (optionName : Name) [KVMap.Value α] (val : α) : Expr :=
mkMData (MData.empty.set optionName val) e
/--
Annotate `e` with `pp.explicit := flag`
The delaborator uses `pp` options.
-/
def setPPExplicit (e : Expr) (flag : Bool) :=
e.setOption `pp.explicit flag
/--
Annotate `e` with `pp.universes := flag`
The delaborator uses `pp` options.
-/
def setPPUniverses (e : Expr) (flag : Bool) :=
e.setOption `pp.universes flag
/--
If `e` is an application `f a_1 ... a_n` annotate `f`, `a_1` ... `a_n` with `pp.explicit := false`,
and annotate `e` with `pp.explicit := true`.
-/
def setAppPPExplicit (e : Expr) : Expr :=
match e with
| app .. =>
let f := e.getAppFn.setPPExplicit false
let args := e.getAppArgs.map (·.setPPExplicit false)
mkAppN f args |>.setPPExplicit true
| _ => e
/--
Similar for `setAppPPExplicit`, but only annotate children with `pp.explicit := false` if
`e` does not contain metavariables.
-/
def setAppPPExplicitForExposingMVars (e : Expr) : Expr :=
match e with
| app .. =>
let f := e.getAppFn.setPPExplicit false
let args := e.getAppArgs.map fun arg => if arg.hasMVar then arg else arg.setPPExplicit false
mkAppN f args |>.setPPExplicit true
| _ => e
end Expr
/--
Annotate `e` with the given annotation name `kind`.
It uses metadata to store the annotation.
-/
def mkAnnotation (kind : Name) (e : Expr) : Expr :=
mkMData (KVMap.empty.insert kind (DataValue.ofBool true)) e
/--
Return `some e'` if `e = mkAnnotation kind e'`
-/
def annotation? (kind : Name) (e : Expr) : Option Expr :=
match e with
| .mdata d b => if d.size == 1 && d.getBool kind false then some b else none
| _ => none
/--
Annotate `e` with the `let_fun` annotation. This annotation is used as hint for the delaborator.
If `e` is of the form `(fun x : t => b) v`, then `mkLetFunAnnotation e` is delaborated at
`let_fun x : t := v; b`
-/
def mkLetFunAnnotation (e : Expr) : Expr :=
mkAnnotation `let_fun e
/--
Return `some e'` if `e = mkLetFunAnnotation e'`
-/
def letFunAnnotation? (e : Expr) : Option Expr :=
annotation? `let_fun e
/--
Return true if `e = mkLetFunAnnotation e'`, and `e'` is of the form `(fun x : t => b) v`
-/
def isLetFun (e : Expr) : Bool :=
match letFunAnnotation? e with
| none => false
| some e => e.isApp && e.appFn!.isLambda
/--
Auxiliary annotation used to mark terms marked with the "inaccessible" annotation `.(t)` and
`_` in patterns.
-/
def mkInaccessible (e : Expr) : Expr :=
mkAnnotation `_inaccessible e
/-- Return `some e'` if `e = mkInaccessible e'`. -/
def inaccessible? (e : Expr) : Option Expr :=
annotation? `_inaccessible e
private def patternRefAnnotationKey := `_patWithRef
/--
During elaboration expressions corresponding to pattern matching terms
are annotated with `Syntax` objects. This function returns `some (stx, p')` if
`p` is the pattern `p'` annotated with `stx`
-/
def patternWithRef? (p : Expr) : Option (Syntax × Expr) :=
match p with
| Expr.mdata d _ =>
match d.find patternRefAnnotationKey with
| some (DataValue.ofSyntax stx) => some (stx, p.mdataExpr!)
| _ => none
| _ => none
/--
Annotate the pattern `p` with `stx`. This is an auxiliary annotation
for producing better hover information.
-/
def mkPatternWithRef (p : Expr) (stx : Syntax) : Expr :=
if patternWithRef? p |>.isSome then
p
else
mkMData (KVMap.empty.insert patternRefAnnotationKey (DataValue.ofSyntax stx)) p
/-- Return `some p` if `e` is an annotated pattern (`inaccessible?` or `patternWithRef?`) -/
def patternAnnotation? (e : Expr) : Option Expr :=
if let some e := inaccessible? e then
some e
else if let some (_, e) := patternWithRef? e then
some e
else
none
/--
Annotate `e` with the LHS annotation. The delaborator displays
expressions of the form `lhs = rhs` as `lhs` when they have this annotation.
This is used to implement the infoview for the `conv` mode.
This version of `mkLHSGoal` does not check that the argument is an equality.
-/
def mkLHSGoalRaw (e : Expr) : Expr :=
mkAnnotation `_lhsGoal e
/-- Return `some lhs` if `e = mkLHSGoal e'`, where `e'` is of the form `lhs = rhs`. -/
def isLHSGoal? (e : Expr) : Option Expr :=
match annotation? `_lhsGoal e with
| none => none
| some e =>
if e.isAppOfArity `Eq 3 then
some e.appFn!.appArg!
else
none
/--
Polymorphic operation for generating unique/fresh free variable identifiers.
It is available in any monad `m` that implements the inferface `MonadNameGenerator`.
-/
def mkFreshFVarId [Monad m] [MonadNameGenerator m] : m FVarId :=
return { name := (← mkFreshId) }
/--
Polymorphic operation for generating unique/fresh metavariable identifiers.
It is available in any monad `m` that implements the inferface `MonadNameGenerator`.
-/
def mkFreshMVarId [Monad m] [MonadNameGenerator m] : m MVarId :=
return { name := (← mkFreshId) }
/--
Polymorphic operation for generating unique/fresh universe metavariable identifiers.
It is available in any monad `m` that implements the inferface `MonadNameGenerator`.
-/
def mkFreshLMVarId [Monad m] [MonadNameGenerator m] : m LMVarId :=
return { name := (← mkFreshId) }
/-- Return `Not p` -/
def mkNot (p : Expr) : Expr := mkApp (mkConst ``Not) p
/-- Return `p ∨ q` -/
def mkOr (p q : Expr) : Expr := mkApp2 (mkConst ``Or) p q
/-- Return `p ∧ q` -/
def mkAnd (p q : Expr) : Expr := mkApp2 (mkConst ``And) p q
/-- Return `Classical.em p` -/
def mkEM (p : Expr) : Expr := mkApp (mkConst ``Classical.em) p
end Lean
|
545a9fef237659acef21afc2cdd6278b1be2ab8d | efa51dd2edbbbbd6c34bd0ce436415eb405832e7 | /20150803_CADE/examples/ex1.lean | 012c6069bc647419c3881613df81d098d7afe8f1 | [
"Apache-2.0"
] | permissive | leanprover/presentations | dd031a05bcb12c8855676c77e52ed84246bd889a | 3ce2d132d299409f1de269fa8e95afa1333d644e | refs/heads/master | 1,688,703,388,796 | 1,686,838,383,000 | 1,687,465,742,000 | 29,750,158 | 12 | 9 | Apache-2.0 | 1,540,211,670,000 | 1,422,042,683,000 | Lean | UTF-8 | Lean | false | false | 373 | lean | import data.vector
open nat vector
check λ x, x + 1
check vector bool 10
check [1, 2, 3]
check [(1:nat), 2, 3]
check nat → nat
check Π (k : nat), vector bool k
check λ (n : nat) (v : vector nat n), cons 0 v
definition id₁ (A : Type) (a : A) : A :=
a
definition id₂.{u} (A : Type.{u}) (a : A) : A :=
a
set_option pp.universes true
check id₁
check id₂
|
7d2389c4d4205ac2f21f7bc12921cec7fcf48cb1 | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/linear_algebra/bilinear_map.lean | e64e0bf6ecaa3ef1079c5751dbd76df339d2ef3f | [
"Apache-2.0"
] | permissive | robertylewis/mathlib | 3d16e3e6daf5ddde182473e03a1b601d2810952c | 1d13f5b932f5e40a8308e3840f96fc882fae01f0 | refs/heads/master | 1,651,379,945,369 | 1,644,276,960,000 | 1,644,276,960,000 | 98,875,504 | 0 | 0 | Apache-2.0 | 1,644,253,514,000 | 1,501,495,700,000 | Lean | UTF-8 | Lean | false | false | 11,360 | lean | /-
Copyright (c) 2018 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau, Mario Carneiro
-/
import linear_algebra.basic
/-!
# Basics on bilinear maps
This file provides basics on bilinear maps. The most general form considered are maps that are
semilinear in both arguments. They are of type `M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P`, where `M` and `N`
are modules over `R` and `S` respectively, `P` is a module over both `R₂` and `S₂` with
commuting actions, and `ρ₁₂ : R →+* R₂` and `σ₁₂ : S →+* S₂`.
## Main declarations
* `linear_map.mk₂`: a constructor for bilinear maps,
taking an unbundled function together with proof witnesses of bilinearity
* `linear_map.flip`: turns a bilinear map `M × N → P` into `N × M → P`
* `linear_map.lcomp` and `linear_map.llcomp`: composition of linear maps as a bilinear map
* `linear_map.compl₂`: composition of a bilinear map `M × N → P` with a linear map `Q → M`
* `linear_map.compr₂`: composition of a bilinear map `M × N → P` with a linear map `Q → N`
* `linear_map.lsmul`: scalar multiplication as a bilinear map `R × M → M`
## Tags
bilinear
-/
namespace linear_map
section semiring
-- the `ₗ` subscript variables are for special cases about linear (as opposed to semilinear) maps
variables {R : Type*} [semiring R] {S : Type*} [semiring S]
variables {R₂ : Type*} [semiring R₂] {S₂ : Type*} [semiring S₂]
variables {M : Type*} {N : Type*} {P : Type*}
variables {M₂ : Type*} {N₂ : Type*} {P₂ : Type*}
variables {Nₗ : Type*} {Pₗ : Type*}
variables {M' : Type*} {N' : Type*} {P' : Type*}
variables [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P]
variables [add_comm_monoid M₂] [add_comm_monoid N₂] [add_comm_monoid P₂]
variables [add_comm_monoid Nₗ] [add_comm_monoid Pₗ]
variables [add_comm_group M'] [add_comm_group N'] [add_comm_group P']
variables [module R M] [module S N] [module R₂ P] [module S₂ P]
variables [module R M₂] [module S N₂] [module R P₂] [module S₂ P₂]
variables [module R Pₗ] [module S Pₗ]
variables [module R M'] [module S N'] [module R₂ P'] [module S₂ P']
variables [smul_comm_class S₂ R₂ P] [smul_comm_class S R Pₗ] [smul_comm_class S₂ R₂ P']
variables [smul_comm_class S₂ R P₂]
variables {ρ₁₂ : R →+* R₂} {σ₁₂ : S →+* S₂}
variables (ρ₁₂ σ₁₂)
/-- Create a bilinear map from a function that is semilinear in each component.
See `mk₂'` and `mk₂` for the linear case. -/
def mk₂'ₛₗ (f : M → N → P)
(H1 : ∀ m₁ m₂ n, f (m₁ + m₂) n = f m₁ n + f m₂ n)
(H2 : ∀ (c:R) m n, f (c • m) n = (ρ₁₂ c) • f m n)
(H3 : ∀ m n₁ n₂, f m (n₁ + n₂) = f m n₁ + f m n₂)
(H4 : ∀ (c:S) m n, f m (c • n) = (σ₁₂ c) • f m n) : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P :=
{ to_fun := λ m, { to_fun := f m, map_add' := H3 m, map_smul' := λ c, H4 c m},
map_add' := λ m₁ m₂, linear_map.ext $ H1 m₁ m₂,
map_smul' := λ c m, linear_map.ext $ H2 c m }
variables {ρ₁₂ σ₁₂}
@[simp] theorem mk₂'ₛₗ_apply
(f : M → N → P) {H1 H2 H3 H4} (m : M) (n : N) :
(mk₂'ₛₗ ρ₁₂ σ₁₂ f H1 H2 H3 H4 : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P) m n = f m n := rfl
variables (R S)
/-- Create a bilinear map from a function that is linear in each component.
See `mk₂` for the special case where both arguments come from modules over the same ring. -/
def mk₂' (f : M → N → Pₗ)
(H1 : ∀ m₁ m₂ n, f (m₁ + m₂) n = f m₁ n + f m₂ n)
(H2 : ∀ (c:R) m n, f (c • m) n = c • f m n)
(H3 : ∀ m n₁ n₂, f m (n₁ + n₂) = f m n₁ + f m n₂)
(H4 : ∀ (c:S) m n, f m (c • n) = c • f m n) : M →ₗ[R] N →ₗ[S] Pₗ :=
mk₂'ₛₗ (ring_hom.id R) (ring_hom.id S) f H1 H2 H3 H4
variables {R S}
@[simp] theorem mk₂'_apply
(f : M → N → Pₗ) {H1 H2 H3 H4} (m : M) (n : N) :
(mk₂' R S f H1 H2 H3 H4 : M →ₗ[R] N →ₗ[S] Pₗ) m n = f m n := rfl
theorem ext₂ {f g : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P}
(H : ∀ m n, f m n = g m n) : f = g :=
linear_map.ext (λ m, linear_map.ext $ λ n, H m n)
section
local attribute [instance] smul_comm_class.symm
/-- Given a linear map from `M` to linear maps from `N` to `P`, i.e., a bilinear map from `M × N` to
`P`, change the order of variables and get a linear map from `N` to linear maps from `M` to `P`. -/
def flip (f : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P) : N →ₛₗ[σ₁₂] M →ₛₗ[ρ₁₂] P :=
mk₂'ₛₗ σ₁₂ ρ₁₂ (λ n m, f m n)
(λ n₁ n₂ m, (f m).map_add _ _)
(λ c n m, (f m).map_smulₛₗ _ _)
(λ n m₁ m₂, by rw f.map_add; refl)
(λ c n m, by rw f.map_smulₛₗ; refl)
end
@[simp] theorem flip_apply (f : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P) (m : M) (n : N) : flip f n m = f m n := rfl
open_locale big_operators
variables {R}
theorem flip_inj {f g : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P} (H : flip f = flip g) : f = g :=
ext₂ $ λ m n, show flip f n m = flip g n m, by rw H
theorem map_zero₂ (f : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P) (y) : f 0 y = 0 :=
(flip f y).map_zero
theorem map_neg₂ (f : M' →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P') (x y) : f (-x) y = -f x y :=
(flip f y).map_neg _
theorem map_sub₂ (f : M' →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P') (x y z) : f (x - y) z = f x z - f y z :=
(flip f z).map_sub _ _
theorem map_add₂ (f : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P) (x₁ x₂ y) : f (x₁ + x₂) y = f x₁ y + f x₂ y :=
(flip f y).map_add _ _
theorem map_smul₂ (f : M₂ →ₗ[R] N₂ →ₛₗ[σ₁₂] P₂) (r : R) (x y) : f (r • x) y = r • f x y :=
(flip f y).map_smul _ _
theorem map_smulₛₗ₂ (f : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P) (r : R) (x y) : f (r • x) y = (ρ₁₂ r) • f x y :=
(flip f y).map_smulₛₗ _ _
theorem map_sum₂ {ι : Type*} (f : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P) (t : finset ι) (x : ι → M) (y) :
f (∑ i in t, x i) y = ∑ i in t, f (x i) y :=
(flip f y).map_sum
end semiring
section comm_semiring
variables {R : Type*} [comm_semiring R] {R₂ : Type*} [comm_semiring R₂]
variables {R₃ : Type*} [comm_semiring R₃] {R₄ : Type*} [comm_semiring R₄]
variables {M : Type*} {N : Type*} {P : Type*} {Q : Type*}
variables {Nₗ : Type*} {Pₗ : Type*} {Qₗ : Type*}
variables [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] [add_comm_monoid Q]
variables [add_comm_monoid Nₗ] [add_comm_monoid Pₗ] [add_comm_monoid Qₗ]
variables [module R M] [module R₂ N] [module R₃ P] [module R₄ Q]
variables [module R Nₗ] [module R Pₗ] [module R Qₗ]
variables {σ₁₂ : R →+* R₂} {σ₂₃ : R₂ →+* R₃} {σ₁₃ : R →+* R₃}
variables {σ₄₂ : R₄ →+* R₂} {σ₄₃ : R₄ →+* R₃}
variables [ring_hom_comp_triple σ₁₂ σ₂₃ σ₁₃] [ring_hom_comp_triple σ₄₂ σ₂₃ σ₄₃]
variables (R)
/-- Create a bilinear map from a function that is linear in each component.
This is a shorthand for `mk₂'` for the common case when `R = S`. -/
def mk₂ (f : M → Nₗ → Pₗ)
(H1 : ∀ m₁ m₂ n, f (m₁ + m₂) n = f m₁ n + f m₂ n)
(H2 : ∀ (c:R) m n, f (c • m) n = c • f m n)
(H3 : ∀ m n₁ n₂, f m (n₁ + n₂) = f m n₁ + f m n₂)
(H4 : ∀ (c:R) m n, f m (c • n) = c • f m n) : M →ₗ[R] Nₗ →ₗ[R] Pₗ :=
mk₂' R R f H1 H2 H3 H4
@[simp] theorem mk₂_apply
(f : M → Nₗ → Pₗ) {H1 H2 H3 H4} (m : M) (n : Nₗ) :
(mk₂ R f H1 H2 H3 H4 : M →ₗ[R] Nₗ →ₗ[R] Pₗ) m n = f m n := rfl
variables (R M N P)
/-- Given a linear map from `M` to linear maps from `N` to `P`, i.e., a bilinear map `M → N → P`,
change the order of variables and get a linear map from `N` to linear maps from `M` to `P`. -/
def lflip : (M →ₛₗ[σ₁₃] N →ₛₗ[σ₂₃] P) →ₗ[R₃] N →ₛₗ[σ₂₃] M →ₛₗ[σ₁₃] P :=
{ to_fun := flip, map_add' := λ _ _, rfl, map_smul' := λ _ _, rfl }
variables {R M N P}
variables (f : M →ₛₗ[σ₁₃] N →ₛₗ[σ₂₃] P)
@[simp] theorem lflip_apply (m : M) (n : N) : lflip R M N P f n m = f m n := rfl
variables (R Pₗ)
/-- Composing a linear map `M → N` and a linear map `N → P` to form a linear map `M → P`. -/
def lcomp (f : M →ₗ[R] Nₗ) : (Nₗ →ₗ[R] Pₗ) →ₗ[R] M →ₗ[R] Pₗ :=
flip $ linear_map.comp (flip id) f
variables {R Pₗ}
@[simp] theorem lcomp_apply (f : M →ₗ[R] Nₗ) (g : Nₗ →ₗ[R] Pₗ) (x : M) :
lcomp R Pₗ f g x = g (f x) := rfl
variables (P σ₂₃)
/-- Composing a semilinear map `M → N` and a semilinear map `N → P` to form a semilinear map
`M → P` is itself a linear map. -/
def lcompₛₗ (f : M →ₛₗ[σ₁₂] N) : (N →ₛₗ[σ₂₃] P) →ₗ[R₃] M →ₛₗ[σ₁₃] P :=
flip $ linear_map.comp (flip id) f
variables {P σ₂₃}
include σ₁₃
@[simp] theorem lcompₛₗ_apply (f : M →ₛₗ[σ₁₂] N) (g : N →ₛₗ[σ₂₃] P) (x : M) :
lcompₛₗ P σ₂₃ f g x = g (f x) := rfl
omit σ₁₃
variables (R M Nₗ Pₗ)
/-- Composing a linear map `M → N` and a linear map `N → P` to form a linear map `M → P`. -/
def llcomp : (Nₗ →ₗ[R] Pₗ) →ₗ[R] (M →ₗ[R] Nₗ) →ₗ[R] M →ₗ[R] Pₗ :=
flip { to_fun := lcomp R Pₗ,
map_add' := λ f f', ext₂ $ λ g x, g.map_add _ _,
map_smul' := λ (c : R) f, ext₂ $ λ g x, g.map_smul _ _ }
variables {R M Nₗ Pₗ}
section
@[simp] theorem llcomp_apply (f : Nₗ →ₗ[R] Pₗ) (g : M →ₗ[R] Nₗ) (x : M) :
llcomp R M Nₗ Pₗ f g x = f (g x) := rfl
end
/-- Composing a linear map `Q → N` and a bilinear map `M → N → P` to
form a bilinear map `M → Q → P`. -/
def compl₂ (g : Q →ₛₗ[σ₄₂] N) : M →ₛₗ[σ₁₃] Q →ₛₗ[σ₄₃] P := (lcompₛₗ _ _ g).comp f
include σ₄₃
@[simp] theorem compl₂_apply (g : Q →ₛₗ[σ₄₂] N) (m : M) (q : Q) :
f.compl₂ g m q = f m (g q) := rfl
omit σ₄₃
/-- Composing a linear map `P → Q` and a bilinear map `M → N → P` to
form a bilinear map `M → N → Q`. -/
def compr₂ (f : M →ₗ[R] Nₗ →ₗ[R] Pₗ) (g : Pₗ →ₗ[R] Qₗ) : M →ₗ[R] Nₗ →ₗ[R] Qₗ :=
(llcomp R Nₗ Pₗ Qₗ g) ∘ₗ f
@[simp] theorem compr₂_apply (f : M →ₗ[R] Nₗ →ₗ[R] Pₗ) (g : Pₗ →ₗ[R] Qₗ) (m : M) (n : Nₗ) :
f.compr₂ g m n = g (f m n) := rfl
variables (R M)
/-- Scalar multiplication as a bilinear map `R → M → M`. -/
def lsmul : R →ₗ[R] M →ₗ[R] M :=
mk₂ R (•) add_smul (λ _ _ _, mul_smul _ _ _) smul_add
(λ r s m, by simp only [smul_smul, smul_eq_mul, mul_comm])
variables {R M}
@[simp] theorem lsmul_apply (r : R) (m : M) : lsmul R M r m = r • m := rfl
end comm_semiring
section comm_ring
variables {R M : Type*} [comm_ring R] [add_comm_group M] [module R M]
lemma lsmul_injective [no_zero_smul_divisors R M] {x : R} (hx : x ≠ 0) :
function.injective (lsmul R M x) :=
smul_right_injective _ hx
lemma ker_lsmul [no_zero_smul_divisors R M] {a : R} (ha : a ≠ 0) :
(linear_map.lsmul R M a).ker = ⊥ :=
linear_map.ker_eq_bot_of_injective (linear_map.lsmul_injective ha)
end comm_ring
end linear_map
|
949af2d0c366d3a837d694ea30c98445b229d9d7 | c777c32c8e484e195053731103c5e52af26a25d1 | /src/ring_theory/valuation/ramification_group.lean | 9276b19d54fb134f4e2cdcea6ae60a20d5bc33fa | [
"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 | 1,957 | lean | /-
Copyright (c) 2022 Michail Karatarakis. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Michail Karatarakis
-/
import ring_theory.ideal.local_ring
import ring_theory.valuation.valuation_subring
/-!
# Ramification groups
The decomposition subgroup and inertia subgroups.
TODO: Define higher ramification groups in lower numbering
-/
namespace valuation_subring
open_locale pointwise
variables (K : Type*) {L : Type*} [field K] [field L] [algebra K L]
/-- The decomposition subgroup defined as the stabilizer of the action
on the type of all valuation subrings of the field. -/
@[reducible] def decomposition_subgroup (A : valuation_subring L) :
subgroup (L ≃ₐ[K] L) :=
mul_action.stabilizer (L ≃ₐ[K] L) A
/-- The valuation subring `A` (considered as a subset of `L`)
is stable under the action of the decomposition group. -/
def sub_mul_action (A : valuation_subring L) :
sub_mul_action (A.decomposition_subgroup K) L :=
{ carrier := A,
smul_mem' := λ g l h, set.mem_of_mem_of_subset (set.smul_mem_smul_set h) g.prop.le }
/-- The multiplicative action of the decomposition subgroup on `A`. -/
instance decomposition_subgroup_mul_semiring_action (A : valuation_subring L) :
mul_semiring_action (A.decomposition_subgroup K) A :=
{ smul_add := λ g k l, subtype.ext $ smul_add g k l,
smul_zero := λ g, subtype.ext $ smul_zero g,
smul_one := λ g, subtype.ext $ smul_one g,
smul_mul := λ g k l, subtype.ext $ smul_mul' g k l,
..(sub_mul_action.mul_action (A.sub_mul_action K)) }
/-- The inertia subgroup defined as the kernel of the group homomorphism from
the decomposition subgroup to the group of automorphisms of the residue field of `A`. -/
def inertia_subgroup (A : valuation_subring L) :
subgroup (A.decomposition_subgroup K) :=
monoid_hom.ker $
mul_semiring_action.to_ring_aut (A.decomposition_subgroup K) (local_ring.residue_field A)
end valuation_subring
|
b7b47009ae28a29d81040070026140d52a279264 | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/ring_theory/adjoin/basic.lean | ce319ead8ed1bf7c739bd01177a7aebe883c68d9 | [
"Apache-2.0"
] | permissive | jjgarzella/mathlib | 96a345378c4e0bf26cf604aed84f90329e4896a2 | 395d8716c3ad03747059d482090e2bb97db612c8 | refs/heads/master | 1,686,480,124,379 | 1,625,163,323,000 | 1,625,163,323,000 | 281,190,421 | 2 | 0 | Apache-2.0 | 1,595,268,170,000 | 1,595,268,169,000 | null | UTF-8 | Lean | false | false | 16,763 | lean | /-
Copyright (c) 2019 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau
-/
import ring_theory.polynomial.basic
import algebra.algebra.subalgebra
/-!
# Adjoining elements to form subalgebras
This file develops the basic theory of subalgebras of an R-algebra generated
by a set of elements. A basic interface for `adjoin` is set up, and various
results about finitely-generated subalgebras and submodules are proved.
## Definitions
* `fg (S : subalgebra R A)` : A predicate saying that the subalgebra is finitely-generated
as an A-algebra
## Tags
adjoin, algebra, finitely-generated algebra
-/
universes u v w
open submodule
namespace algebra
variables {R : Type u} {A : Type v} {B : Type w}
section semiring
variables [comm_semiring R] [semiring A] [semiring B]
variables [algebra R A] [algebra R B] {s t : set A}
open subsemiring
theorem subset_adjoin : s ⊆ adjoin R s :=
algebra.gc.le_u_l s
theorem adjoin_le {S : subalgebra R A} (H : s ⊆ S) : adjoin R s ≤ S :=
algebra.gc.l_le H
theorem adjoin_le_iff {S : subalgebra R A} : adjoin R s ≤ S ↔ s ⊆ S:=
algebra.gc _ _
theorem adjoin_mono (H : s ⊆ t) : adjoin R s ≤ adjoin R t :=
algebra.gc.monotone_l H
theorem adjoin_eq_of_le (S : subalgebra R A) (h₁ : s ⊆ S) (h₂ : S ≤ adjoin R s) : adjoin R s = S :=
le_antisymm (adjoin_le h₁) h₂
theorem adjoin_eq (S : subalgebra R A) : adjoin R ↑S = S :=
adjoin_eq_of_le _ (set.subset.refl _) subset_adjoin
theorem adjoin_induction {p : A → Prop} {x : A} (h : x ∈ adjoin R s) (Hs : ∀ x ∈ s, p x)
(Halg : ∀ r, p (algebra_map R A r))
(Hadd : ∀ x y, p x → p y → p (x + y))
(Hmul : ∀ x y, p x → p y → p (x * y)) : p x :=
let S : subalgebra R A :=
{ carrier := p, mul_mem' := Hmul, add_mem' := Hadd, algebra_map_mem' := Halg } in
adjoin_le (show s ≤ S, from Hs) h
lemma adjoin_union (s t : set A) : adjoin R (s ∪ t) = adjoin R s ⊔ adjoin R t :=
(algebra.gc : galois_connection _ (coe : subalgebra R A → set A)).l_sup
variables (R A)
@[simp] theorem adjoin_empty : adjoin R (∅ : set A) = ⊥ :=
show adjoin R ⊥ = ⊥, by { apply galois_connection.l_bot, exact algebra.gc }
variables (R) {A} (s)
theorem adjoin_eq_span : (adjoin R s).to_submodule = span R (submonoid.closure s) :=
begin
apply le_antisymm,
{ intros r hr, rcases subsemiring.mem_closure_iff_exists_list.1 hr with ⟨L, HL, rfl⟩, clear hr,
induction L with hd tl ih, { exact zero_mem _ },
rw list.forall_mem_cons at HL,
rw [list.map_cons, list.sum_cons],
refine submodule.add_mem _ _ (ih HL.2),
replace HL := HL.1, clear ih tl,
suffices : ∃ z r (hr : r ∈ submonoid.closure s), has_scalar.smul z r = list.prod hd,
{ rcases this with ⟨z, r, hr, hzr⟩, rw ← hzr,
exact smul_mem _ _ (subset_span hr) },
induction hd with hd tl ih, { exact ⟨1, 1, (submonoid.closure s).one_mem', one_smul _ _⟩ },
rw list.forall_mem_cons at HL,
rcases (ih HL.2) with ⟨z, r, hr, hzr⟩, rw [list.prod_cons, ← hzr],
rcases HL.1 with ⟨hd, rfl⟩ | hs,
{ refine ⟨hd * z, r, hr, _⟩,
rw [algebra.smul_def, algebra.smul_def, (algebra_map _ _).map_mul, _root_.mul_assoc] },
{ exact ⟨z, hd * r, submonoid.mul_mem _ (submonoid.subset_closure hs) hr,
(mul_smul_comm _ _ _).symm⟩ } },
refine span_le.2 _,
change submonoid.closure s ≤ (adjoin R s).to_subsemiring.to_submonoid,
exact submonoid.closure_le.2 subset_adjoin
end
lemma span_le_adjoin (s : set A) : span R s ≤ (adjoin R s).to_submodule :=
span_le.mpr subset_adjoin
lemma adjoin_to_submodule_le {s : set A} {t : submodule R A} :
(adjoin R s).to_submodule ≤ t ↔ ↑(submonoid.closure s) ⊆ (t : set A) :=
by rw [adjoin_eq_span, span_le]
lemma adjoin_eq_span_of_subset {s : set A} (hs : ↑(submonoid.closure s) ⊆ (span R s : set A)) :
(adjoin R s).to_submodule = span R s :=
le_antisymm ((adjoin_to_submodule_le R).mpr hs) (span_le_adjoin R s)
lemma adjoin_image (f : A →ₐ[R] B) (s : set A) :
adjoin R (f '' s) = (adjoin R s).map f :=
le_antisymm (adjoin_le $ set.image_subset _ subset_adjoin) $
subalgebra.map_le.2 $ adjoin_le $ set.image_subset_iff.1 subset_adjoin
@[simp] lemma adjoin_insert_adjoin (x : A) :
adjoin R (insert x ↑(adjoin R s)) = adjoin R (insert x s) :=
le_antisymm
(adjoin_le (set.insert_subset.mpr
⟨subset_adjoin (set.mem_insert _ _), adjoin_mono (set.subset_insert _ _)⟩))
(algebra.adjoin_mono (set.insert_subset_insert algebra.subset_adjoin))
lemma adjoint_prod_le (s : set A) (t : set B) :
adjoin R (set.prod s t) ≤ (adjoin R s).prod (adjoin R t) :=
adjoin_le $ set.prod_mono subset_adjoin subset_adjoin
lemma adjoin_inl_union_inr_le_prod (s) (t) :
adjoin R (linear_map.inl R A B '' (s ∪ {1}) ∪
linear_map.inr R A B '' (t ∪ {1})) ≤ (adjoin R s).prod (adjoin R t) :=
begin
rw [set.image_union, set.image_union],
refine adjoin_le (λ x hx, subalgebra.mem_prod.2 _),
rcases hx with (⟨x₁, ⟨hx₁, rfl⟩⟩ | ⟨x₂, ⟨hx₂, rfl⟩⟩) | (⟨x₃, ⟨hx₃, rfl⟩⟩ | ⟨x₄, ⟨hx₄, rfl⟩⟩),
{ exact ⟨subset_adjoin hx₁, subalgebra.zero_mem _⟩ },
{ rw set.mem_singleton_iff.1 hx₂,
exact ⟨subalgebra.one_mem _, subalgebra.zero_mem _⟩ },
{ exact ⟨subalgebra.zero_mem _, subset_adjoin hx₃⟩ },
{ rw set.mem_singleton_iff.1 hx₄,
exact ⟨subalgebra.zero_mem _, subalgebra.one_mem _⟩ }
end
lemma mem_adjoin_of_map_mul {s} {x : A} {f : A →ₗ[R] B} (hf : ∀ a₁ a₂, f(a₁ * a₂) = f a₁ * f a₂)
(h : x ∈ adjoin R s) : f x ∈ adjoin R (f '' (s ∪ {1})) :=
begin
refine @adjoin_induction R A _ _ _ _ (λ a, f a ∈ adjoin R (f '' (s ∪ {1}))) x h
(λ a ha, subset_adjoin ⟨a, ⟨set.subset_union_left _ _ ha, rfl⟩⟩)
(λ r, _)
(λ y z hy hz, by simpa [hy, hz] using subalgebra.add_mem _ hy hz)
(λ y z hy hz, by simpa [hy, hz, hf y z] using subalgebra.mul_mem _ hy hz),
have : f 1 ∈ adjoin R (f '' (s ∪ {1})) :=
subset_adjoin ⟨1, ⟨set.subset_union_right _ _ $ set.mem_singleton 1, rfl⟩⟩,
replace this := subalgebra.smul_mem (adjoin R (f '' (s ∪ {1}))) this r,
convert this,
rw algebra_map_eq_smul_one,
exact f.map_smul _ _
end
lemma adjoin_inl_union_inr_eq_prod (s) (t) :
adjoin R (linear_map.inl R A B '' (s ∪ {1}) ∪
linear_map.inr R A B '' (t ∪ {1})) = (adjoin R s).prod (adjoin R t) :=
begin
let P := adjoin R (linear_map.inl R A B '' (s ∪ {1}) ∪ linear_map.inr R A B '' (t ∪ {1})),
refine le_antisymm (adjoin_inl_union_inr_le_prod R s t) _,
rintro ⟨a, b⟩ ⟨ha, hb⟩,
have Ha : (a, (0 : B)) ∈ adjoin R ((linear_map.inl R A B) '' (s ∪ {1})) :=
mem_adjoin_of_map_mul R (linear_map.inl_map_mul) ha,
have Hb : ((0 : A), b) ∈ adjoin R ((linear_map.inr R A B) '' (t ∪ {1})) :=
mem_adjoin_of_map_mul R (linear_map.inr_map_mul) hb,
replace Ha : (a, (0 : B)) ∈ P :=
adjoin_mono (set.subset_union_of_subset_left (set.subset.refl _) _) Ha,
replace Hb : ((0 : A), b) ∈ P :=
adjoin_mono (set.subset_union_of_subset_right (set.subset.refl _) _) Hb,
simpa using subalgebra.add_mem _ Ha Hb
end
end semiring
section comm_semiring
variables [comm_semiring R] [comm_semiring A]
variables [algebra R A] {s t : set A}
open subsemiring
variables (R s t)
theorem adjoin_union_eq_under : adjoin R (s ∪ t) = (adjoin R s).under (adjoin (adjoin R s) t) :=
le_antisymm
(closure_mono $ set.union_subset
(set.range_subset_iff.2 $ λ r, or.inl ⟨algebra_map R (adjoin R s) r, rfl⟩)
(set.union_subset_union_left _ $ λ x hxs, ⟨⟨_, subset_adjoin hxs⟩, rfl⟩))
(closure_le.2 $ set.union_subset
(set.range_subset_iff.2 $ λ x, adjoin_mono (set.subset_union_left _ _) x.2)
(set.subset.trans (set.subset_union_right _ _) subset_adjoin))
theorem adjoin_eq_range :
adjoin R s = (mv_polynomial.aeval (coe : s → A)).range :=
le_antisymm
(adjoin_le $ λ x hx, ⟨mv_polynomial.X ⟨x, hx⟩, mv_polynomial.eval₂_X _ _ _⟩)
(λ x ⟨p, (hp : mv_polynomial.aeval coe p = x)⟩, hp ▸ mv_polynomial.induction_on p
(λ r, by { rw [mv_polynomial.aeval_def, mv_polynomial.eval₂_C],
exact (adjoin R s).algebra_map_mem r })
(λ p q hp hq, by rw alg_hom.map_add; exact subalgebra.add_mem _ hp hq)
(λ p ⟨n, hn⟩ hp, by rw [alg_hom.map_mul, mv_polynomial.aeval_def _ (mv_polynomial.X _),
mv_polynomial.eval₂_X]; exact subalgebra.mul_mem _ hp (subset_adjoin hn)))
theorem adjoin_singleton_eq_range (x : A) : adjoin R {x} = (polynomial.aeval x).range :=
le_antisymm
(adjoin_le $ set.singleton_subset_iff.2 ⟨polynomial.X, polynomial.eval₂_X _ _⟩)
(λ y ⟨p, (hp : polynomial.aeval x p = y)⟩, hp ▸ polynomial.induction_on p
(λ r, by { rw [polynomial.aeval_def, polynomial.eval₂_C],
exact (adjoin R _).algebra_map_mem r })
(λ p q hp hq, by rw alg_hom.map_add; exact subalgebra.add_mem _ hp hq)
(λ n r ih, by { rw [pow_succ', ← mul_assoc, alg_hom.map_mul,
polynomial.aeval_def _ polynomial.X, polynomial.eval₂_X],
exact subalgebra.mul_mem _ ih (subset_adjoin rfl) }))
lemma adjoin_singleton_one : adjoin R ({1} : set A) = ⊥ :=
eq_bot_iff.2 $ adjoin_le $ set.singleton_subset_iff.2 $ set_like.mem_coe.2 $ one_mem _
theorem adjoin_union_coe_submodule : (adjoin R (s ∪ t)).to_submodule =
(adjoin R s).to_submodule * (adjoin R t).to_submodule :=
begin
rw [adjoin_eq_span, adjoin_eq_span, adjoin_eq_span, span_mul_span],
congr' 1 with z, simp [submonoid.closure_union, submonoid.mem_sup, set.mem_mul]
end
end comm_semiring
section ring
variables [comm_ring R] [ring A]
variables [algebra R A] {s t : set A}
variables {R s t}
open ring
theorem adjoin_int (s : set R) : adjoin ℤ s = subalgebra_of_is_subring (closure s) :=
le_antisymm (adjoin_le subset_closure) (closure_subset subset_adjoin : closure s ≤ adjoin ℤ s)
theorem mem_adjoin_iff {s : set A} {x : A} :
x ∈ adjoin R s ↔ x ∈ closure (set.range (algebra_map R A) ∪ s) :=
⟨λ hx, subsemiring.closure_induction hx subset_closure is_add_submonoid.zero_mem
is_submonoid.one_mem (λ _ _, is_add_submonoid.add_mem) (λ _ _, is_submonoid.mul_mem),
suffices closure (set.range ⇑(algebra_map R A) ∪ s) ⊆ adjoin R s, from @this x,
closure_subset subsemiring.subset_closure⟩
theorem adjoin_eq_ring_closure (s : set A) :
(adjoin R s : set A) = closure (set.range (algebra_map R A) ∪ s) :=
set.ext $ λ x, mem_adjoin_iff
end ring
section comm_ring
variables [comm_ring R] [comm_ring A]
variables [algebra R A] {s t : set A}
variables {R s t}
open ring
theorem fg_trans (h1 : (adjoin R s).to_submodule.fg)
(h2 : (adjoin (adjoin R s) t).to_submodule.fg) :
(adjoin R (s ∪ t)).to_submodule.fg :=
begin
rcases fg_def.1 h1 with ⟨p, hp, hp'⟩,
rcases fg_def.1 h2 with ⟨q, hq, hq'⟩,
refine fg_def.2 ⟨p * q, hp.mul hq, le_antisymm _ _⟩,
{ rw [span_le],
rintros _ ⟨x, y, hx, hy, rfl⟩,
change x * y ∈ _,
refine is_submonoid.mul_mem _ _,
{ have : x ∈ (adjoin R s).to_submodule,
{ rw ← hp', exact subset_span hx },
exact adjoin_mono (set.subset_union_left _ _) this },
have : y ∈ (adjoin (adjoin R s) t).to_submodule,
{ rw ← hq', exact subset_span hy },
change y ∈ adjoin R (s ∪ t), rwa adjoin_union_eq_under },
{ intros r hr,
change r ∈ adjoin R (s ∪ t) at hr,
rw adjoin_union_eq_under at hr,
change r ∈ (adjoin (adjoin R s) t).to_submodule at hr,
haveI := classical.dec_eq A,
haveI := classical.dec_eq R,
rw [← hq', ← set.image_id q, finsupp.mem_span_image_iff_total (adjoin R s)] at hr,
rcases hr with ⟨l, hlq, rfl⟩,
have := @finsupp.total_apply A A (adjoin R s),
rw [this, finsupp.sum],
refine sum_mem _ _,
intros z hz, change (l z).1 * _ ∈ _,
have : (l z).1 ∈ (adjoin R s).to_submodule := (l z).2,
rw [← hp', ← set.image_id p, finsupp.mem_span_image_iff_total R] at this,
rcases this with ⟨l2, hlp, hl⟩,
have := @finsupp.total_apply A A R,
rw this at hl,
rw [←hl, finsupp.sum_mul],
refine sum_mem _ _,
intros t ht, change _ * _ ∈ _, rw smul_mul_assoc, refine smul_mem _ _ _,
exact subset_span ⟨t, z, hlp ht, hlq hz, rfl⟩ }
end
end comm_ring
end algebra
namespace subalgebra
variables {R : Type u} {A : Type v} {B : Type w}
variables [comm_semiring R] [semiring A] [algebra R A] [semiring B] [algebra R B]
/-- A subalgebra `S` is finitely generated if there exists `t : finset A` such that
`algebra.adjoin R t = S`. -/
def fg (S : subalgebra R A) : Prop :=
∃ t : finset A, algebra.adjoin R ↑t = S
lemma fg_adjoin_finset (s : finset A) : (algebra.adjoin R (↑s : set A)).fg :=
⟨s, rfl⟩
theorem fg_def {S : subalgebra R A} : S.fg ↔ ∃ t : set A, set.finite t ∧ algebra.adjoin R t = S :=
⟨λ ⟨t, ht⟩, ⟨↑t, set.finite_mem_finset t, ht⟩,
λ ⟨t, ht1, ht2⟩, ⟨ht1.to_finset, by rwa set.finite.coe_to_finset⟩⟩
theorem fg_bot : (⊥ : subalgebra R A).fg :=
⟨∅, algebra.adjoin_empty R A⟩
theorem fg_of_fg_to_submodule {S : subalgebra R A} : S.to_submodule.fg → S.fg :=
λ ⟨t, ht⟩, ⟨t, le_antisymm
(algebra.adjoin_le (λ x hx, show x ∈ S.to_submodule, from ht ▸ subset_span hx)) $
show S.to_submodule ≤ (algebra.adjoin R ↑t).to_submodule,
from (λ x hx, span_le.mpr
(λ x hx, algebra.subset_adjoin hx)
(show x ∈ span R ↑t, by { rw ht, exact hx }))⟩
theorem fg_of_noetherian [is_noetherian R A] (S : subalgebra R A) : S.fg :=
fg_of_fg_to_submodule (is_noetherian.noetherian S.to_submodule)
lemma fg_of_submodule_fg (h : (⊤ : submodule R A).fg) : (⊤ : subalgebra R A).fg :=
let ⟨s, hs⟩ := h in ⟨s, to_submodule_injective $
by { rw [algebra.top_to_submodule, eq_top_iff, ← hs, span_le], exact algebra.subset_adjoin }⟩
lemma fg_prod {S : subalgebra R A} {T : subalgebra R B} (hS : S.fg) (hT : T.fg) : (S.prod T).fg :=
begin
obtain ⟨s, hs⟩ := fg_def.1 hS,
obtain ⟨t, ht⟩ := fg_def.1 hT,
rw [← hs.2, ← ht.2],
exact fg_def.2 ⟨(linear_map.inl R A B '' (s ∪ {1})) ∪ (linear_map.inr R A B '' (t ∪ {1})),
set.finite.union (set.finite.image _ (set.finite.union hs.1 (set.finite_singleton _)))
(set.finite.image _ (set.finite.union ht.1 (set.finite_singleton _))),
algebra.adjoin_inl_union_inr_eq_prod R s t⟩
end
section
open_locale classical
lemma fg_map (S : subalgebra R A) (f : A →ₐ[R] B) (hs : S.fg) : (S.map f).fg :=
let ⟨s, hs⟩ := hs in ⟨s.image f, by rw [finset.coe_image, algebra.adjoin_image, hs]⟩
end
lemma fg_of_fg_map (S : subalgebra R A) (f : A →ₐ[R] B) (hf : function.injective f)
(hs : (S.map f).fg) : S.fg :=
let ⟨s, hs⟩ := hs in ⟨s.preimage f $ λ _ _ _ _ h, hf h, map_injective f hf $
by { rw [← algebra.adjoin_image, finset.coe_preimage, set.image_preimage_eq_of_subset, hs],
rw [← alg_hom.coe_range, ← algebra.adjoin_le_iff, hs, ← algebra.map_top], exact map_mono le_top }⟩
lemma fg_top (S : subalgebra R A) : (⊤ : subalgebra R S).fg ↔ S.fg :=
⟨λ h, by { rw [← S.range_val, ← algebra.map_top], exact fg_map _ _ h },
λ h, fg_of_fg_map _ S.val subtype.val_injective $ by { rw [algebra.map_top, range_val], exact h }⟩
lemma induction_on_adjoin [is_noetherian R A] (P : subalgebra R A → Prop)
(base : P ⊥) (ih : ∀ (S : subalgebra R A) (x : A), P S → P (algebra.adjoin R (insert x S)))
(S : subalgebra R A) : P S :=
begin
classical,
obtain ⟨t, rfl⟩ := S.fg_of_noetherian,
refine finset.induction_on t _ _,
{ simpa using base },
intros x t hxt h,
convert ih _ x h using 1,
rw [finset.coe_insert, algebra.adjoin_insert_adjoin]
end
end subalgebra
variables {R : Type u} {A : Type v} {B : Type w}
variables [comm_ring R] [comm_ring A] [comm_ring B] [algebra R A] [algebra R B]
/-- The image of a Noetherian R-algebra under an R-algebra map is a Noetherian ring. -/
instance alg_hom.is_noetherian_ring_range (f : A →ₐ[R] B) [is_noetherian_ring A] :
is_noetherian_ring f.range :=
is_noetherian_ring_range f.to_ring_hom
theorem is_noetherian_ring_of_fg {S : subalgebra R A} (HS : S.fg)
[is_noetherian_ring R] : is_noetherian_ring S :=
let ⟨t, ht⟩ := HS in ht ▸ (algebra.adjoin_eq_range R (↑t : set A)).symm ▸
by haveI : is_noetherian_ring (mv_polynomial (↑t : set A) R) :=
mv_polynomial.is_noetherian_ring;
convert alg_hom.is_noetherian_ring_range _; apply_instance
theorem is_noetherian_ring_closure (s : set R) (hs : s.finite) :
@@is_noetherian_ring (ring.closure s) subset.ring :=
show is_noetherian_ring (subalgebra_of_is_subring (ring.closure s)), from
algebra.adjoin_int s ▸ is_noetherian_ring_of_fg (subalgebra.fg_def.2 ⟨s, hs, rfl⟩)
|
6601f39d3068583a4729665a4e2bb2902a14a383 | dd0f5513e11c52db157d2fcc8456d9401a6cd9da | /11_Tactic-Style_Proofs.org.20.lean | e620cc3dd0ab1e72114a274ef4f702b3b11ef3b9 | [] | no_license | cjmazey/lean-tutorial | ba559a49f82aa6c5848b9bf17b7389bf7f4ba645 | 381f61c9fcac56d01d959ae0fa6e376f2c4e3b34 | refs/heads/master | 1,610,286,098,832 | 1,447,124,923,000 | 1,447,124,923,000 | 43,082,433 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 388 | lean | import standard
import data.nat
open nat
variables x y z w : ℕ
-- BEGIN
example : x = x :=
begin
revert x, -- goal is ⊢ ∀ (x : ℕ), x = x
intro y, -- goal is y : ℕ ⊢ y = y
apply rfl
end
example (H : x = y) : y = x :=
begin
revert H, -- goal is x y : ℕ ⊢ x = y → y = x
intro H1, -- goal is x y : ℕ, H1 : x = y ⊢ y = x
apply (eq.symm H1)
end
-- END
|
41e8dde2443a2291658dce6d04c07d774331d39e | 7cef822f3b952965621309e88eadf618da0c8ae9 | /src/algebra/category/CommRing/limits.lean | 224ad6a597088d02d246b6aa88225ab1cea8c38f | [
"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 | 4,926 | 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 algebra.category.CommRing.basic
import category_theory.limits.types
import category_theory.limits.preserves
import ring_theory.subring
import algebra.pi_instances
/-!
# 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.
## Further work
A lot of this should be generalised / automated, as it's quite common for concrete
categories that the forgetful functor preserves limits.
-/
open category_theory
open category_theory.limits
universe u
namespace CommRing
variables {J : Type u} [small_category J]
instance comm_ring_obj (F : J ⥤ CommRing.{u}) (j) :
comm_ring ((F ⋙ forget CommRing).obj j) :=
by { change comm_ring (F.obj j), apply_instance }
instance sections_submonoid (F : J ⥤ CommRing.{u}) :
is_submonoid (F ⋙ forget CommRing).sections :=
{ one_mem := λ j j' f,
begin
erw [functor.comp_map, forget_map_eq_coe, (F.map f).map_one],
refl
end,
mul_mem := λ a b ah bh j j' f,
begin
erw [functor.comp_map, forget_map_eq_coe, (F.map f).map_mul],
dsimp [functor.sections] at ah,
rw ah f,
dsimp [functor.sections] at bh,
rw bh f,
refl,
end }
instance sections_add_submonoid (F : J ⥤ CommRing.{u}) :
is_add_submonoid (F ⋙ forget CommRing).sections :=
{ zero_mem := λ j j' f,
begin
erw [functor.comp_map, forget_map_eq_coe, (F.map f).map_zero],
refl,
end,
add_mem := λ a b ah bh j j' f,
begin
erw [functor.comp_map, forget_map_eq_coe, (F.map f).map_add],
dsimp [functor.sections] at ah,
rw ah f,
dsimp [functor.sections] at bh,
rw bh f,
refl,
end }
instance sections_add_subgroup (F : J ⥤ CommRing.{u}) :
is_add_subgroup (F ⋙ forget CommRing).sections :=
{ neg_mem := λ a ah j j' f,
begin
erw [functor.comp_map, forget_map_eq_coe, (F.map f).map_neg],
dsimp [functor.sections] at ah,
rw ah f,
refl,
end,
..(CommRing.sections_add_submonoid F) }
instance sections_subring (F : J ⥤ CommRing.{u}) :
is_subring (F ⋙ forget CommRing).sections :=
{ ..(CommRing.sections_submonoid F),
..(CommRing.sections_add_subgroup F) }
instance limit_comm_ring (F : J ⥤ CommRing.{u}) :
comm_ring (limit (F ⋙ forget CommRing)) :=
@subtype.comm_ring ((Π (j : J), (F ⋙ forget _).obj j)) (by apply_instance) _
(by convert (CommRing.sections_subring F))
instance limit_π_is_ring_hom (F : J ⥤ CommRing.{u}) (j) :
is_ring_hom (limit.π (F ⋙ forget CommRing) j) :=
{ map_one := by { simp only [types.types_limit_π], refl },
map_mul := λ x y, by { simp only [types.types_limit_π], refl },
map_add := λ x y, by { simp only [types.types_limit_π], refl } }
namespace CommRing_has_limits
-- The next two definitions are used in the construction of `has_limits CommRing`.
-- 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 `CommRing`.
(Internal use only; use the limits API.)
-/
def limit (F : J ⥤ CommRing.{u}) : cone F :=
{ X := ⟨limit (F ⋙ forget _), by apply_instance⟩,
π :=
{ app := λ j, ring_hom.of $ limit.π (F ⋙ forget _) j,
naturality' := λ j j' f,
ring_hom.coe_inj ((limit.cone (F ⋙ forget _)).π.naturality f) } }
/--
Witness that the limit cone in `CommRing` is a limit cone.
(Internal use only; use the limits API.)
-/
def limit_is_limit (F : J ⥤ CommRing.{u}) : is_limit (limit F) :=
begin
refine is_limit.of_faithful
(forget CommRing) (limit.is_limit _)
(λ s, ⟨_, _, _, _, _⟩) (λ s, rfl); dsimp,
{ apply subtype.eq, funext, dsimp,
erw (s.π.app j).map_one, refl },
{ intros x y, apply subtype.eq, funext, dsimp,
erw (s.π.app j).map_mul, refl },
{ apply subtype.eq, funext, dsimp,
erw (s.π.app j).map_zero, refl },
{ intros x y, apply subtype.eq, funext, dsimp,
erw (s.π.app j).map_add, refl }
end
end CommRing_has_limits
open CommRing_has_limits
/-- The category of commutative rings has all limits. -/
instance CommRing_has_limits : has_limits.{u} CommRing.{u} :=
{ has_limits_of_shape := λ J 𝒥,
{ has_limit := λ F, by exactI
{ cone := limit F,
is_limit := limit_is_limit F } } }
/--
The forgetful functor from commutative rings to types preserves all limits. (That is, the underlying
types could have been computed instead as limits in the category of types.)
-/
instance forget_preserves_limits : preserves_limits (forget CommRing.{u}) :=
{ preserves_limits_of_shape := λ J 𝒥,
{ preserves_limit := λ F,
by exactI preserves_limit_of_preserves_limit_cone
(limit.is_limit F) (limit.is_limit (F ⋙ forget _)) } }
end CommRing
|
547ee3683f938b55216ef82499c396176b1b50c4 | 8e381650eb2c1c5361be64ff97e47d956bf2ab9f | /src/spectrum_of_a_ring/quasi_compact.lean | 91d188cf06a717ed9c9c03276f0c0ed8e737effd | [] | no_license | alreadydone/lean-scheme | 04c51ab08eca7ccf6c21344d45d202780fa667af | 52d7624f57415eea27ed4dfa916cd94189221a1c | refs/heads/master | 1,599,418,221,423 | 1,562,248,559,000 | 1,562,248,559,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 9,268 | lean | /-
Spec(R) is quasi-compact.
https://stacks.math.columbia.edu/tag/00E8
-/
import topology.basic
import linear_algebra.linear_combination
import to_mathlib.opens
import to_mathlib.ideals
import sheaves.covering.covering
import sheaves.covering.covering_on_standard_basis
import sheaves.sheaf_on_standard_basis
import spectrum_of_a_ring.standard_basis
import spectrum_of_a_ring.induced_continuous_map
import spectrum_of_a_ring.induced_homeomorphism
import spectrum_of_a_ring.structure_presheaf
import spectrum_of_a_ring.structure_presheaf_localization
noncomputable theory
local attribute [instance] classical.prop_decidable
universe u
open topological_space lattice classical localization localization_alt
variables {α : Type u} [comm_ring α]
section refinement
local attribute [instance] classical.prop_decidable
parameters (X : Type u) [T : topological_space X]
parameters (B : set (opens X)) [HB : opens.is_basis B]
include T HB
lemma refine_cover_with_basis (OC : covering opens.univ)
: ∃ (D : set (opens X)),
(D ⊆ B)
∧ (∀ V ∈ D, ∃ i, V ⊆ OC.Uis i)
∧ (Sup D = opens.univ) :=
begin
existsi [λ V, V ∈ B ∧ ∃ i : OC.γ, V ⊆ OC.Uis i],
refine ⟨_, _, _⟩,
{ intros U HU,
exact HU.1, },
{ intros V HV,
exact HV.2, },
{ apply opens.ext,
apply set.ext,
intros x,
split,
{ intros Hx,
simp [opens.univ], },
{ intros Hx,
rw ←OC.Hcov at Hx,
rcases Hx with ⟨U, HU, HxU⟩,
rcases HU with ⟨OU, HOU, HOUval⟩,
rcases HOU with ⟨i, HOU⟩,
rw ←HOUval at HxU,
have HU' := opens.is_basis_iff_nbhd.1 HB HxU,
rcases HU' with ⟨U', ⟨BU', HxU', HU'OU⟩⟩,
use U',
simp,
refine ⟨⟨_, _⟩, _⟩,
{ exact U'.2, },
{ rw ←HOU at HU'OU,
exact ⟨BU', ⟨i, HU'OU⟩⟩, },
{ exact HxU', } } }
end
end refinement
-- A cover by basis elements has a finite subcover.
section quasi_compact
variables (R : Type u) [comm_ring R]
lemma D_fs_quasi_compact :
∀ S : set R, ⋃₀ (Spec.D' '' S) = Spec.univ R →
∃ F ⊆ S,
set.finite F
∧ ⋃₀ (Spec.D' '' F) = Spec.univ R :=
begin
rintros S HScov,
-- We get that V(S) = ∅.
have HVS : Spec.V S = ∅,
rw Spec.D'.union at HScov,
rw ←set.compl_compl (Spec.V S),
rw HScov,
exact set.compl_univ,
rw Spec.V.set_eq_span at HVS,
-- It follows that (S) = R.
have HST := (Spec.V.empty_iff_ideal_top _).1 HVS,
have Hone : (1 : R) ∈ ideal.span S := by simp [HST],
-- Deduce that 1 = Σrᵢfᵢ for some {f₁, ..., fₙ}.
have Hlc := mem_span_iff_lc.1 Hone,
rcases Hlc with ⟨lc, Hlc, H⟩,
have Hfs := (@_root_.lc.mem_supported _ _ _ _ _ _ _).1 Hlc,
use ↑lc.support,
refine ⟨_, ⟨_, _⟩⟩,
{ -- {f₁, ..., fₙ} ⊆ S.
exact Hfs, },
{ -- Prove it's finite.
apply set.finite_mem_finset, },
{ -- ⋃ D(fᵢ) = Spec(R)
rw Spec.D'.union,
simp [Spec.univ],
rw ←set.compl_empty,
congr,
rw Spec.V.set_eq_span,
rw Spec.V.empty_iff_ideal_top,
suffices Hsuff : (1:R) ∈ ideal.span (↑(lc.support) : set R),
rw ((ideal.eq_top_iff_one _).2 Hsuff),
rw lc.total_apply at H,
rw ←H,
simp [finsupp.sum],
apply ideal.span_mem_finset, }
end
lemma D_fs.subset : ∀ {D}, D ⊆ D_fs R → ∃ S, (Spec.DO R '' S) = D :=
begin
intros D HD,
use {f : R | ∃ U : opens (Spec R), U ∈ D ∧ U.1 = Spec.D' f },
apply set.ext,
intros x,
split,
{ intros Hx,
rcases Hx with ⟨f, ⟨Hf, Hx⟩⟩,
rcases Hf with ⟨Df, ⟨HDf, HDfval⟩⟩,
rw ←Hx,
have Heq : Df = Spec.DO R f,
apply opens.ext,
exact HDfval,
rw ←Heq,
exact HDf, },
{ intros Hx,
have HxD := HD Hx,
rcases HxD with ⟨f, Hf⟩,
simp,
use [f, x],
{ exact ⟨Hx, by rw Hf; simp [Spec.DO]⟩, },
{ exact Hf.symm, } }
end
lemma Spec.DO.val_eq_D' : subtype.val ∘ Spec.DO R = Spec.D' :=
begin
rw function.funext_iff,
intros f,
simp [Spec.DO],
end
lemma Spec.quasi_compact.aux : compact (Spec.univ R) :=
begin
rw compact_iff_finite_subcover,
intros C HC Hcov,
replace Hcov := set.subset.antisymm Hcov (λ x Hx, trivial),
let OC := covering.from_cover (@opens.univ (Spec R) _) C HC Hcov,
have BDfs : opens.is_basis (D_fs R) := D_fs_basis R,
have BC := @refine_cover_with_basis (Spec R) _ (D_fs R) BDfs OC,
rcases BC with ⟨D, ⟨BD, HDUi, HUD⟩⟩,
have HS := D_fs.subset R BD,
rcases HS with ⟨S, HS⟩,
rw ←HS at HUD,
replace HUD := subtype.ext.1 HUD,
rw opens.Sup_s at HUD,
rw ←set.image_comp at HUD,
rw Spec.DO.val_eq_D' at HUD,
have HF := D_fs_quasi_compact R S HUD,
rcases HF with ⟨F, HFS, ⟨HFfin, HFcov⟩⟩,
have HUD : ∀ {U}, U ∈ Spec.DO R '' F → U ∈ D,
intros U HU,
rcases HU with ⟨f, ⟨Hf, HU⟩⟩,
replace Hf := HFS Hf,
rw ←HS,
exact ⟨f, ⟨Hf, HU⟩⟩,
let Fisaux : ∀ {U}, U ∈ (Spec.DO R '' F) → set (Spec R) :=
λ U HU, (OC.Uis (classical.some (HDUi U (HUD HU)))).1,
let Finsprop := λ U HU, classical.some_spec (HDUi U (HUD HU)),
let Fis : { f // f ∈ F } → set (Spec R) :=
λ U, Fisaux ⟨U, ⟨U.2, rfl⟩⟩,
use [set.range Fis],
have HFis : set.range Fis ⊆ C,
intros U HU,
rcases HU with ⟨f, Hf⟩,
rw ←Hf,
simp [Fis],
apply covering.from_cover.Uis,
use [HFis],
split,
{ constructor,
replace HFfin := set.finite.fintype HFfin,
apply @set.fintype_range _ _ _ Fis HFfin, },
{ intros x Hx,
have Hx' := Hx,
have HUis : (⋃OC.Uis).val = Spec.univ R := (subtype.ext.1 OC.Hcov),
rw ←HFcov at Hx,
rcases Hx with ⟨U, ⟨⟨f, ⟨Hf, HDf⟩⟩, HxU⟩⟩,
rw ←HDf at HxU,
use [Fis ⟨f, Hf⟩],
use [⟨f, Hf⟩],
have HDfUi := Finsprop ⟨Spec.D' f, D_fs_open R f⟩ ⟨f, ⟨Hf, rfl⟩⟩,
simp [Fis],
exact HDfUi HxU, },
end
lemma Spec.compact : compact_space (Spec R) :=
begin
constructor,
apply Spec.quasi_compact.aux,
end
-- This is what we really need.
-- D(f) = ⋃i=1,..,n D(gi)
lemma lemma_standard_open
{U : opens (Spec R)} (BU : U ∈ D_fs R) (OC : covering_standard_basis (D_fs R) (Spec.DO R (some BU)))
: ∃ (γf : Type u) (Hf : fintype γf) (ρ : γf → OC.γ),
Spec.DO R (some BU) ⊆ ⋃ (λ i, Spec.DO R (some (OC.BUis (ρ i)))) :=
begin
let f := some BU,
let Rf := localization R (S U),
have Hf : U.1 = Spec.D' f,
rw some_spec BU,
simp [f, Spec.DO],
have HOCUis : ∀ i, OC.Uis i = Spec.DO R (some (OC.BUis i)),
intros i,
rw ←some_spec (OC.BUis i),
have HRf : is_localization_data (powers f) (localization.of : R → Rf)
:= structure_presheaf.localization BU,
let g : R → Rf := of,
let φ : Spec Rf → Spec R := Zariski.induced g,
have Hcompact := Spec.quasi_compact.aux Rf,
have HcompactDf : compact (Spec.D' f),
rw ←phi_image_Df HRf,
exact compact_image Hcompact (Zariski.induced.continuous g),
let Uis : set (set (Spec R)) := set.range (subtype.val ∘ OC.Uis),
have OUis : ∀ (t : set (Spec R)), t ∈ Uis → is_open t,
intros t Ht,
rcases Ht with ⟨i, Ht⟩,
rw ←Ht,
simp,
exact (OC.Uis i).2,
have HUis : ⋃₀ Uis = (⋃ OC.Uis).val,
simp,
apply set.ext,
intros x,
split,
{ rintros ⟨Ui, ⟨⟨i, HUi⟩, HxUi⟩⟩,
exact ⟨Ui, ⟨OC.Uis i, ⟨⟨i, rfl⟩, HUi⟩⟩, HxUi⟩, },
{ rintros ⟨Ui, ⟨OUi, ⟨⟨i, HOUi⟩, HUi⟩⟩, HxUi⟩,
rw ←HOUi at HUi,
exact ⟨Ui, ⟨⟨i, HUi⟩, HxUi⟩⟩, },
have HDfUis : Spec.D' f ⊆ ⋃₀ Uis,
rw [HUis, OC.Hcov],
simp [f, Spec.DO, set.subset.refl],
have Hfincov
:= @compact_elim_finite_subcover (Spec R) _ (Spec.D' f) Uis HcompactDf OUis HDfUis,
rcases Hfincov with ⟨Uis', HUis', ⟨HfinUis', Hfincov⟩⟩,
have HUis'fintype := set.finite.fintype HfinUis',
let ρ : Uis' → OC.γ := λ V, some (HUis' V.2),
use [Uis', HUis'fintype, ρ],
intros x Hx,
dsimp only [Spec.DO] at Hx,
replace Hx := Hfincov Hx,
rcases Hx with ⟨Ui, ⟨HUi', HxUi⟩⟩,
use Ui,
have HUi : Ui ∈ subtype.val '' set.range (λ (i : Uis'), Spec.DO R (some (OC.BUis (ρ i)))),
use [OC.Uis (ρ ⟨Ui, HUi'⟩)],
split,
{ use ⟨Ui, HUi'⟩,
dsimp [ρ],
rw ←HOCUis (ρ ⟨Ui, HUi'⟩), },
{ exact some_spec (HUis' HUi'), },
use HUi,
exact HxUi,
end
theorem structure_presheaf_on_basis_is_compact
: sheaf_on_standard_basis.basis_is_compact (D_fs_standard_basis R) :=
begin
rintros U BU ⟨⟨γ, Uis, Hcov⟩, BUis⟩,
dsimp only [subtype.coe_mk] at *,
rw some_spec BU at Hcov,
rcases (lemma_standard_open R BU ⟨⟨Uis, Hcov⟩, BUis⟩) with ⟨γf, Hγf, ρ, H⟩,
use [γf, Hγf, ρ],
apply le_antisymm,
{ intros x Hx,
rcases Hx with ⟨Ui, ⟨⟨OUi, ⟨⟨i, Hi⟩, HUival⟩⟩, HxUi⟩⟩,
dsimp at Hi,
rw ←some_spec BU at Hcov,
rw ←Hcov,
rw ←Hi at HUival,
use [Ui, ⟨Uis (ρ i), ⟨⟨ρ i, rfl⟩, HUival⟩⟩, HxUi], },
{ have HUis : Uis = λ i, Spec.DO R (some (BUis i)),
apply funext,
intros i,
rw ←some_spec (BUis i),
rw HUis,
dsimp [function.comp],
rw some_spec BU,
exact H, },
end
end quasi_compact
|
4a2925c45d1772305b41efa49daea49445a595ac | 618003631150032a5676f229d13a079ac875ff77 | /src/category_theory/opposites.lean | 43cfe83ca57f045dfa2d94512388501e78b3fbd9 | [
"Apache-2.0"
] | permissive | awainverse/mathlib | 939b68c8486df66cfda64d327ad3d9165248c777 | ea76bd8f3ca0a8bf0a166a06a475b10663dec44a | refs/heads/master | 1,659,592,962,036 | 1,590,987,592,000 | 1,590,987,592,000 | 268,436,019 | 1 | 0 | Apache-2.0 | 1,590,990,500,000 | 1,590,990,500,000 | null | UTF-8 | Lean | false | false | 9,642 | 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.types
import category_theory.equivalence
import data.opposite
universes v₁ v₂ u₁ u₂ -- declare the `v`'s first; see `category_theory.category` for an explanation
namespace category_theory
open opposite
variables {C : Type u₁}
section has_hom
variables [has_hom.{v₁} C]
/-- The hom types of the opposite of a category (or graph).
As with the objects, we'll make this irreducible below.
Use `f.op` and `f.unop` to convert between morphisms of C
and morphisms of Cᵒᵖ.
-/
instance has_hom.opposite : has_hom Cᵒᵖ :=
{ hom := λ X Y, unop Y ⟶ unop X }
def has_hom.hom.op {X Y : C} (f : X ⟶ Y) : op Y ⟶ op X := f
def has_hom.hom.unop {X Y : Cᵒᵖ} (f : X ⟶ Y) : unop Y ⟶ unop X := f
attribute [irreducible] has_hom.opposite
lemma has_hom.hom.op_inj {X Y : C} :
function.injective (has_hom.hom.op : (X ⟶ Y) → (op Y ⟶ op X)) :=
λ _ _ H, congr_arg has_hom.hom.unop H
lemma has_hom.hom.unop_inj {X Y : Cᵒᵖ} :
function.injective (has_hom.hom.unop : (X ⟶ Y) → (unop Y ⟶ unop X)) :=
λ _ _ H, congr_arg has_hom.hom.op H
@[simp] lemma has_hom.hom.unop_op {X Y : C} {f : X ⟶ Y} : f.op.unop = f := rfl
@[simp] lemma has_hom.hom.op_unop {X Y : Cᵒᵖ} {f : X ⟶ Y} : f.unop.op = f := rfl
end has_hom
variables [category.{v₁} C]
instance category.opposite : category.{v₁} Cᵒᵖ :=
{ comp := λ _ _ _ f g, (g.unop ≫ f.unop).op,
id := λ X, (𝟙 (unop X)).op }
@[simp] lemma op_comp {X Y Z : C} {f : X ⟶ Y} {g : Y ⟶ Z} :
(f ≫ g).op = g.op ≫ f.op := rfl
@[simp] lemma op_id {X : C} : (𝟙 X).op = 𝟙 (op X) := rfl
@[simp] lemma unop_comp {X Y Z : Cᵒᵖ} {f : X ⟶ Y} {g : Y ⟶ Z} :
(f ≫ g).unop = g.unop ≫ f.unop := rfl
@[simp] lemma unop_id {X : Cᵒᵖ} : (𝟙 X).unop = 𝟙 (unop X) := rfl
@[simp] lemma unop_id_op {X : C} : (𝟙 (op X)).unop = 𝟙 X := rfl
@[simp] lemma op_id_unop {X : Cᵒᵖ} : (𝟙 (unop X)).op = 𝟙 X := rfl
/-- The functor from the double-opposite of a category to the underlying category. -/
@[simps]
def op_op : (Cᵒᵖ)ᵒᵖ ⥤ C :=
{ obj := λ X, unop (unop X),
map := λ X Y f, f.unop.unop }
/-- The functor from a category to its double-opposite. -/
@[simps]
def unop_unop : C ⥤ Cᵒᵖᵒᵖ :=
{ obj := λ X, op (op X),
map := λ X Y f, f.op.op }
/-- The double opposite category is equivalent to the original. -/
@[simps]
def op_op_equivalence : Cᵒᵖᵒᵖ ≌ C :=
{ functor := op_op,
inverse := unop_unop,
unit_iso := iso.refl (𝟭 Cᵒᵖᵒᵖ),
counit_iso := iso.refl (unop_unop ⋙ op_op) }
def is_iso_of_op {X Y : C} (f : X ⟶ Y) [is_iso f.op] : is_iso f :=
{ inv := (inv (f.op)).unop,
hom_inv_id' := has_hom.hom.op_inj (by simp),
inv_hom_id' := has_hom.hom.op_inj (by simp) }
namespace functor
section
variables {D : Type u₂} [category.{v₂} D]
variables {C D}
protected definition op (F : C ⥤ D) : Cᵒᵖ ⥤ Dᵒᵖ :=
{ obj := λ X, op (F.obj (unop X)),
map := λ X Y f, (F.map f.unop).op }
@[simp] lemma op_obj (F : C ⥤ D) (X : Cᵒᵖ) : (F.op).obj X = op (F.obj (unop X)) := rfl
@[simp] lemma op_map (F : C ⥤ D) {X Y : Cᵒᵖ} (f : X ⟶ Y) : (F.op).map f = (F.map f.unop).op := rfl
protected definition unop (F : Cᵒᵖ ⥤ Dᵒᵖ) : C ⥤ D :=
{ obj := λ X, unop (F.obj (op X)),
map := λ X Y f, (F.map f.op).unop }
@[simp] lemma unop_obj (F : Cᵒᵖ ⥤ Dᵒᵖ) (X : C) : (F.unop).obj X = unop (F.obj (op X)) := rfl
@[simp] lemma unop_map (F : Cᵒᵖ ⥤ Dᵒᵖ) {X Y : C} (f : X ⟶ Y) : (F.unop).map f = (F.map f.op).unop := rfl
variables (C D)
definition op_hom : (C ⥤ D)ᵒᵖ ⥤ (Cᵒᵖ ⥤ Dᵒᵖ) :=
{ obj := λ F, (unop F).op,
map := λ F G α,
{ app := λ X, (α.unop.app (unop X)).op,
naturality' := λ X Y f, has_hom.hom.unop_inj $ eq.symm (α.unop.naturality f.unop) } }
@[simp] lemma op_hom.obj (F : (C ⥤ D)ᵒᵖ) : (op_hom C D).obj F = (unop F).op := rfl
@[simp] lemma op_hom.map_app {F G : (C ⥤ D)ᵒᵖ} (α : F ⟶ G) (X : Cᵒᵖ) :
((op_hom C D).map α).app X = (α.unop.app (unop X)).op := rfl
definition op_inv : (Cᵒᵖ ⥤ Dᵒᵖ) ⥤ (C ⥤ D)ᵒᵖ :=
{ obj := λ F, op F.unop,
map := λ F G α, has_hom.hom.op
{ app := λ X, (α.app (op X)).unop,
naturality' := λ X Y f, has_hom.hom.op_inj $ eq.symm (α.naturality f.op) } }
@[simp] lemma op_inv.obj (F : Cᵒᵖ ⥤ Dᵒᵖ) : (op_inv C D).obj F = op F.unop := rfl
@[simp] lemma op_inv.map_app {F G : Cᵒᵖ ⥤ Dᵒᵖ} (α : F ⟶ G) (X : C) :
(((op_inv C D).map α).unop).app X = (α.app (op X)).unop := rfl
-- TODO show these form an equivalence
variables {C D}
protected definition left_op (F : C ⥤ Dᵒᵖ) : Cᵒᵖ ⥤ D :=
{ obj := λ X, unop (F.obj (unop X)),
map := λ X Y f, (F.map f.unop).unop }
@[simp] lemma left_op_obj (F : C ⥤ Dᵒᵖ) (X : Cᵒᵖ) : (F.left_op).obj X = unop (F.obj (unop X)) := rfl
@[simp] lemma left_op_map (F : C ⥤ Dᵒᵖ) {X Y : Cᵒᵖ} (f : X ⟶ Y) :
(F.left_op).map f = (F.map f.unop).unop :=
rfl
protected definition right_op (F : Cᵒᵖ ⥤ D) : C ⥤ Dᵒᵖ :=
{ obj := λ X, op (F.obj (op X)),
map := λ X Y f, (F.map f.op).op }
@[simp] lemma right_op_obj (F : Cᵒᵖ ⥤ D) (X : C) : (F.right_op).obj X = op (F.obj (op X)) := rfl
@[simp] lemma right_op_map (F : Cᵒᵖ ⥤ D) {X Y : C} (f : X ⟶ Y) :
(F.right_op).map f = (F.map f.op).op :=
rfl
-- TODO show these form an equivalence
instance {F : C ⥤ D} [full F] : full F.op :=
{ preimage := λ X Y f, (F.preimage f.unop).op }
instance {F : C ⥤ D} [faithful F] : faithful F.op :=
{ injectivity' := λ X Y f g h,
has_hom.hom.unop_inj $ by simpa using injectivity F (has_hom.hom.op_inj h) }
/-- If F is faithful then the right_op of F is also faithful. -/
instance right_op_faithful {F : Cᵒᵖ ⥤ D} [faithful F] : faithful F.right_op :=
{ injectivity' := λ X Y f g h, has_hom.hom.op_inj (injectivity F (has_hom.hom.op_inj h)) }
/-- If F is faithful then the left_op of F is also faithful. -/
instance left_op_faithful {F : C ⥤ Dᵒᵖ} [faithful F] : faithful F.left_op :=
{ injectivity' := λ X Y f g h, has_hom.hom.unop_inj (injectivity F (has_hom.hom.unop_inj h)) }
end
end functor
namespace nat_trans
variables {D : Type u₂} [category.{v₂} D]
section
variables {F G : C ⥤ D}
local attribute [semireducible] has_hom.opposite
@[simps] protected definition op (α : F ⟶ G) : G.op ⟶ F.op :=
{ app := λ X, (α.app (unop X)).op,
naturality' := begin tidy, erw α.naturality, refl, end }
@[simp] lemma op_id (F : C ⥤ D) : nat_trans.op (𝟙 F) = 𝟙 (F.op) := rfl
@[simps] protected definition unop (α : F.op ⟶ G.op) : G ⟶ F :=
{ app := λ X, (α.app (op X)).unop,
naturality' :=
begin
intros X Y f,
have := congr_arg has_hom.hom.op (α.naturality f.op),
dsimp at this,
erw this,
refl,
end }
@[simp] lemma unop_id (F : C ⥤ D) : nat_trans.unop (𝟙 F.op) = 𝟙 F := rfl
end
section
variables {F G : C ⥤ Dᵒᵖ}
local attribute [semireducible] has_hom.opposite
protected definition left_op (α : F ⟶ G) : G.left_op ⟶ F.left_op :=
{ app := λ X, (α.app (unop X)).unop,
naturality' := begin tidy, erw α.naturality, refl, end }
@[simp] lemma left_op_app (α : F ⟶ G) (X) :
(nat_trans.left_op α).app X = (α.app (unop X)).unop :=
rfl
protected definition right_op (α : F.left_op ⟶ G.left_op) : G ⟶ F :=
{ app := λ X, (α.app (op X)).op,
naturality' :=
begin
intros X Y f,
have := congr_arg has_hom.hom.op (α.naturality f.op),
dsimp at this,
erw this
end }
@[simp] lemma right_op_app (α : F.left_op ⟶ G.left_op) (X) :
(nat_trans.right_op α).app X = (α.app (op X)).op :=
rfl
end
end nat_trans
namespace iso
variables {X Y : C}
protected definition op (α : X ≅ Y) : op Y ≅ op X :=
{ hom := α.hom.op,
inv := α.inv.op,
hom_inv_id' := has_hom.hom.unop_inj α.inv_hom_id,
inv_hom_id' := has_hom.hom.unop_inj α.hom_inv_id }
@[simp] lemma op_hom {α : X ≅ Y} : α.op.hom = α.hom.op := rfl
@[simp] lemma op_inv {α : X ≅ Y} : α.op.inv = α.inv.op := rfl
end iso
namespace nat_iso
variables {D : Type u₂} [category.{v₂} D]
variables {F G : C ⥤ D}
/-- The natural isomorphism between opposite functors `G.op ≅ F.op` induced by a natural
isomorphism between the original functors `F ≅ G`. -/
protected definition op (α : F ≅ G) : G.op ≅ F.op :=
{ hom := nat_trans.op α.hom,
inv := nat_trans.op α.inv,
hom_inv_id' := begin ext, dsimp, rw ←op_comp, rw inv_hom_id_app, refl, end,
inv_hom_id' := begin ext, dsimp, rw ←op_comp, rw hom_inv_id_app, refl, end }
@[simp] lemma op_hom (α : F ≅ G) : (nat_iso.op α).hom = nat_trans.op α.hom := rfl
@[simp] lemma op_inv (α : F ≅ G) : (nat_iso.op α).inv = nat_trans.op α.inv := rfl
/-- The natural isomorphism between functors `G ≅ F` induced by a natural isomorphism
between the opposite functors `F.op ≅ G.op`. -/
protected definition unop (α : F.op ≅ G.op) : G ≅ F :=
{ hom := nat_trans.unop α.hom,
inv := nat_trans.unop α.inv,
hom_inv_id' := begin ext, dsimp, rw ←unop_comp, rw inv_hom_id_app, refl, end,
inv_hom_id' := begin ext, dsimp, rw ←unop_comp, rw hom_inv_id_app, refl, end }
@[simp] lemma unop_hom (α : F.op ≅ G.op) : (nat_iso.unop α).hom = nat_trans.unop α.hom := rfl
@[simp] lemma unop_inv (α : F.op ≅ G.op) : (nat_iso.unop α).inv = nat_trans.unop α.inv := rfl
end nat_iso
end category_theory
|
ce6f17ed53f689eddd1a53259dc371e8010f24fc | 26ac254ecb57ffcb886ff709cf018390161a9225 | /src/linear_algebra/finsupp_vector_space.lean | 3054643132c4e85190c9216834a9b8220aba0bec | [
"Apache-2.0"
] | permissive | eric-wieser/mathlib | 42842584f584359bbe1fc8b88b3ff937c8acd72d | d0df6b81cd0920ad569158c06a3fd5abb9e63301 | refs/heads/master | 1,669,546,404,255 | 1,595,254,668,000 | 1,595,254,668,000 | 281,173,504 | 0 | 0 | Apache-2.0 | 1,595,263,582,000 | 1,595,263,581,000 | null | UTF-8 | Lean | false | false | 7,252 | lean | /-
Copyright (c) 2019 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Johannes Hölzl
Linear structures on function with finite support `ι →₀ β`.
-/
import data.mv_polynomial
import linear_algebra.dimension
noncomputable theory
local attribute [instance, priority 100] classical.prop_decidable
open set linear_map submodule
namespace finsupp
section ring
variables {R : Type*} {M : Type*} {ι : Type*}
variables [ring R] [add_comm_group M] [module R M]
lemma linear_independent_single {φ : ι → Type*}
{f : Π ι, φ ι → M} (hf : ∀i, linear_independent R (f i)) :
linear_independent R (λ ix : Σ i, φ i, single ix.1 (f ix.1 ix.2)) :=
begin
apply @linear_independent_Union_finite R _ _ _ _ ι φ (λ i x, single i (f i x)),
{ assume i,
have h_disjoint : disjoint (span R (range (f i))) (ker (lsingle i)),
{ rw ker_lsingle,
exact disjoint_bot_right },
apply linear_independent.image (hf i) h_disjoint },
{ intros i t ht hit,
refine (disjoint_lsingle_lsingle {i} t (disjoint_singleton_left.2 hit)).mono _ _,
{ rw span_le,
simp only [supr_singleton],
rw range_coe,
apply range_comp_subset_range },
{ refine supr_le_supr (λ i, supr_le_supr _),
intros hi,
rw span_le,
rw range_coe,
apply range_comp_subset_range } }
end
open linear_map submodule
lemma is_basis_single {φ : ι → Type*} (f : Π ι, φ ι → M)
(hf : ∀i, is_basis R (f i)) :
is_basis R (λ ix : Σ i, φ i, single ix.1 (f ix.1 ix.2)) :=
begin
split,
{ apply linear_independent_single,
exact λ i, (hf i).1 },
{ rw [range_sigma_eq_Union_range, span_Union],
simp only [image_univ.symm, λ i, image_comp (single i) (f i), span_single_image],
simp only [image_univ, (hf _).2, map_top, supr_lsingle_range] }
end
lemma is_basis_single_one : is_basis R (λ i : ι, single i (1 : R)) :=
by convert (is_basis_single (λ (i : ι) (x : unit), (1 : R)) (λ i, is_basis_singleton_one R)).comp
(λ i : ι, ⟨i, ()⟩) ⟨λ _ _, and.left ∘ sigma.mk.inj, λ ⟨i, ⟨⟩⟩, ⟨i, rfl⟩⟩
end ring
section comm_ring
variables {R : Type*} {M : Type*} {N : Type*} {ι : Type*} {κ : Type*}
variables [comm_ring R] [add_comm_group M] [module R M] [add_comm_group N] [module R N]
/-- If b : ι → M and c : κ → N are bases then so is λ i, b i.1 ⊗ₜ c i.2 : ι × κ → M ⊗ N. -/
lemma is_basis.tensor_product {b : ι → M} (hb : is_basis R b) {c : κ → N} (hc : is_basis R c) :
is_basis R (λ i : ι × κ, b i.1 ⊗ₜ[R] c i.2) :=
by { convert linear_equiv.is_basis is_basis_single_one
((tensor_product.congr (module_equiv_finsupp hb) (module_equiv_finsupp hc)).trans $
(finsupp_tensor_finsupp _ _ _ _ _).trans $
lcongr (equiv.refl _) (tensor_product.lid R R)).symm,
ext ⟨i, k⟩, rw [function.comp_apply, linear_equiv.eq_symm_apply], simp }
end comm_ring
section dim
universes u v
variables {K : Type u} {V : Type v} {ι : Type v}
variables [field K] [add_comm_group V] [vector_space K V]
lemma dim_eq : vector_space.dim K (ι →₀ V) = cardinal.mk ι * vector_space.dim K V :=
begin
rcases exists_is_basis K V with ⟨bs, hbs⟩,
rw [← cardinal.lift_inj, cardinal.lift_mul, ← hbs.mk_eq_dim,
← (is_basis_single _ (λa:ι, hbs)).mk_eq_dim, ← cardinal.sum_mk,
← cardinal.lift_mul, cardinal.lift_inj],
{ simp only [cardinal.mk_image_eq (single_injective.{u u} _), cardinal.sum_const] }
end
end dim
end finsupp
section vector_space
/- We use `universe variables` instead of `universes` here because universes introduced by the
`universes` keyword do not get replaced by metavariables once a lemma has been proven. So if you
prove a lemma using universe `u`, you can only apply it to universe `u` in other lemmas of the
same section. -/
universe variables u v w
variables {K : Type u} {V V₁ V₂ : Type v} {V' : Type w}
variables [field K]
variables [add_comm_group V] [vector_space K V]
variables [add_comm_group V₁] [vector_space K V₁]
variables [add_comm_group V₂] [vector_space K V₂]
variables [add_comm_group V'] [vector_space K V']
open vector_space
lemma equiv_of_dim_eq_lift_dim
(h : cardinal.lift.{v w} (dim K V) = cardinal.lift.{w v} (dim K V')) :
nonempty (V ≃ₗ[K] V') :=
begin
haveI := classical.dec_eq V,
haveI := classical.dec_eq V',
rcases exists_is_basis K V with ⟨m, hm⟩,
rcases exists_is_basis K V' with ⟨m', hm'⟩,
rw [←cardinal.lift_inj.1 hm.mk_eq_dim, ←cardinal.lift_inj.1 hm'.mk_eq_dim] at h,
rcases quotient.exact h with ⟨e⟩,
let e := (equiv.ulift.symm.trans e).trans equiv.ulift,
exact ⟨((module_equiv_finsupp hm).trans
(finsupp.dom_lcongr e)).trans
(module_equiv_finsupp hm').symm⟩,
end
def equiv_of_dim_eq_dim (h : dim K V₁ = dim K V₂) : V₁ ≃ₗ[K] V₂ :=
begin
classical,
exact classical.choice (equiv_of_dim_eq_lift_dim (cardinal.lift_inj.2 h))
end
def fin_dim_vectorspace_equiv (n : ℕ)
(hn : (dim K V) = n) : V ≃ₗ[K] (fin n → K) :=
begin
have : cardinal.lift.{v u} (n : cardinal.{v}) = cardinal.lift.{u v} (n : cardinal.{u}),
by simp,
have hn := cardinal.lift_inj.{v u}.2 hn,
rw this at hn,
rw ←@dim_fin_fun K _ n at hn,
exact classical.choice (equiv_of_dim_eq_lift_dim hn),
end
lemma eq_bot_iff_dim_eq_zero (p : submodule K V) (h : dim K p = 0) : p = ⊥ :=
begin
have : dim K p = dim K (⊥ : submodule K V) := by rwa [dim_bot],
let e := equiv_of_dim_eq_dim this,
exact e.eq_bot_of_equiv _
end
lemma injective_of_surjective (f : V₁ →ₗ[K] V₂)
(hV₁ : dim K V₁ < cardinal.omega) (heq : dim K V₂ = dim K V₁) (hf : f.range = ⊤) : f.ker = ⊥ :=
have hk : dim K f.ker < cardinal.omega := lt_of_le_of_lt (dim_submodule_le _) hV₁,
begin
rcases cardinal.lt_omega.1 hV₁ with ⟨d₁, eq₁⟩,
rcases cardinal.lt_omega.1 hk with ⟨d₂, eq₂⟩,
have : 0 = d₂,
{ have := dim_eq_of_surjective f (linear_map.range_eq_top.1 hf),
rw [heq, eq₁, eq₂, ← nat.cast_add, cardinal.nat_cast_inj] at this,
exact nat.add_left_cancel this },
refine eq_bot_iff_dim_eq_zero _ _,
rw [eq₂, ← this, nat.cast_zero]
end
end vector_space
section vector_space
universes u
open vector_space
variables {K V : Type u} [field K] [add_comm_group V] [vector_space K V]
lemma cardinal_mk_eq_cardinal_mk_field_pow_dim (h : dim K V < cardinal.omega) :
cardinal.mk V = cardinal.mk K ^ dim K V :=
begin
rcases exists_is_basis K V with ⟨s, hs⟩,
have : nonempty (fintype s),
{ rwa [← cardinal.lt_omega_iff_fintype, cardinal.lift_inj.1 hs.mk_eq_dim] },
cases this with hsf, letI := hsf,
calc cardinal.mk V = cardinal.mk (s →₀ K) : quotient.sound ⟨(module_equiv_finsupp hs).to_equiv⟩
... = cardinal.mk (s → K) : quotient.sound ⟨finsupp.equiv_fun_on_fintype⟩
... = _ : by rw [← cardinal.lift_inj.1 hs.mk_eq_dim, cardinal.power_def]
end
lemma cardinal_lt_omega_of_dim_lt_omega [fintype K] (h : dim K V < cardinal.omega) :
cardinal.mk V < cardinal.omega :=
begin
rw [cardinal_mk_eq_cardinal_mk_field_pow_dim h],
exact cardinal.power_lt_omega (cardinal.lt_omega_iff_fintype.2 ⟨infer_instance⟩) h
end
end vector_space
|
ebe557ef20f3f77323364dbb07d2bc4ae8039a64 | e00ea76a720126cf9f6d732ad6216b5b824d20a7 | /src/category_theory/limits/shapes/kernels.lean | c111ff3c5d2e2751f9adfdb65da2749bd453a255 | [
"Apache-2.0"
] | permissive | vaibhavkarve/mathlib | a574aaf68c0a431a47fa82ce0637f0f769826bfe | 17f8340912468f49bdc30acdb9a9fa02eeb0473a | refs/heads/master | 1,621,263,802,637 | 1,585,399,588,000 | 1,585,399,588,000 | 250,833,447 | 0 | 0 | Apache-2.0 | 1,585,410,341,000 | 1,585,410,341,000 | null | UTF-8 | Lean | false | false | 9,708 | lean | /-
Copyright (c) 2019 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison, Markus Himmel
-/
import category_theory.limits.shapes.zero
import category_theory.limits.shapes.equalizers
/-!
# Kernels and cokernels
In a category with zero morphisms, the kernel of a morphism `f : X ⟶ Y` is just the equalizer of `f`
and `0 : X ⟶ Y`. (Similarly the cokernel is the coequalizer.)
We don't yet prove much here, just provide
* `kernel : (X ⟶ Y) → C`
* `kernel.ι : kernel f ⟶ X`
* `kernel.condition : kernel.ι f ≫ f = 0` and
* `kernel.lift (k : W ⟶ X) (h : k ≫ f = 0) : W ⟶ kernel f` (as well as the dual versions)
## Main statements
Besides the definition and lifts,
* `kernel.ι_zero_is_iso`: a kernel map of a zero morphism is an isomorphism
* `kernel.is_limit_cone_zero_cone`: if our category has a zero object, then the map from the zero
obect is a kernel map of any monomorphism
## Future work
* TODO: images and coimages, and then abelian categories.
* TODO: connect this with existing working in the group theory and ring theory libraries.
## Implementation notes
As with the other special shapes in the limits library, all the definitions here are given as
`abbreviation`s of the general statements for limits, so all the `simp` lemmas and theorems about
general limits can be used.
## References
* [F. Borceux, *Handbook of Categorical Algebra 2*][borceux-vol2]
-/
universes v u
open category_theory
open category_theory.limits.walking_parallel_pair
namespace category_theory.limits
variables {C : Type u} [𝒞 : category.{v} C]
include 𝒞
variables {X Y : C} (f : X ⟶ Y)
section
variables [has_zero_morphisms.{v} C]
/-- A kernel fork is just a fork where the second morphism is a zero morphism. -/
abbreviation kernel_fork := fork f 0
variables {f}
@[simp, reassoc] lemma kernel_fork.condition (s : kernel_fork f) : fork.ι s ≫ f = 0 :=
by erw [fork.condition, has_zero_morphisms.comp_zero]
@[simp] lemma kernel_fork.app_one (s : kernel_fork f) : s.π.app one = 0 :=
by erw [←cone_parallel_pair_left, kernel_fork.condition]; refl
/-- A morphism `ι` satisfying `ι ≫ f = 0` determines a kernel fork over `f`. -/
abbreviation kernel_fork.of_ι {Z : C} (ι : Z ⟶ X) (w : ι ≫ f = 0) : kernel_fork f :=
fork.of_ι ι $ by rw [w, has_zero_morphisms.comp_zero]
end
section
variables [has_zero_morphisms.{v} C] [has_limit (parallel_pair f 0)]
/-- The kernel of a morphism, expressed as the equalizer with the 0 morphism. -/
abbreviation kernel : C := equalizer f 0
/-- The map from `kernel f` into the source of `f`. -/
abbreviation kernel.ι : kernel f ⟶ X := equalizer.ι f 0
@[simp, reassoc] lemma kernel.condition : kernel.ι f ≫ f = 0 :=
kernel_fork.condition _
/-- Given any morphism `k` so `k ≫ f = 0`, `k` factors through `kernel f`. -/
abbreviation kernel.lift {W : C} (k : W ⟶ X) (h : k ≫ f = 0) : W ⟶ kernel f :=
limit.lift (parallel_pair f 0) (kernel_fork.of_ι k h)
/-- Every kernel of the zero morphism is an isomorphism -/
def kernel.ι_zero_is_iso [has_limit (parallel_pair (0 : X ⟶ Y) 0)] :
is_iso (kernel.ι (0 : X ⟶ Y)) :=
by { apply limit_cone_parallel_pair_self_is_iso, apply limit.is_limit }
end
section has_zero_object
variables [has_zero_object.{v} C]
local attribute [instance] has_zero_object.has_zero
variables [has_zero_morphisms.{v} C]
/-- The morphism from the zero object determines a cone on a kernel diagram -/
def kernel.zero_cone : cone (parallel_pair f 0) :=
{ X := 0,
π := { app := λ j, 0 }}
/-- The map from the zero object is a kernel of a monomorphism -/
def kernel.is_limit_cone_zero_cone [mono f] : is_limit (kernel.zero_cone f) :=
fork.is_limit.mk _ (λ s, 0)
(λ s, by { erw has_zero_morphisms.zero_comp,
convert (@zero_of_comp_mono _ _ _ _ _ _ _ f _ _).symm,
exact kernel_fork.condition _ })
(λ _ _ _, has_zero_object.zero_of_to_zero _)
/-- The kernel of a monomorphism is isomorphic to the zero object -/
def kernel.of_mono [has_limit (parallel_pair f 0)] [mono f] : kernel f ≅ 0 :=
functor.map_iso (cones.forget _) $ is_limit.unique_up_to_iso
(limit.is_limit (parallel_pair f 0)) (kernel.is_limit_cone_zero_cone f)
/-- The kernel morphism of a monomorphism is a zero morphism -/
lemma kernel.ι_of_mono [has_limit (parallel_pair f 0)] [mono f] : kernel.ι f = 0 :=
by rw [←category.id_comp _ (kernel.ι f), ←iso.hom_inv_id (kernel.of_mono f), category.assoc,
has_zero_object.zero_of_to_zero (kernel.of_mono f).hom, has_zero_morphisms.zero_comp]
end has_zero_object
section
variables (X) (Y) [has_zero_morphisms.{v} C]
/-- The kernel morphism of a zero morphism is an isomorphism -/
def kernel.ι_of_zero [has_limit (parallel_pair (0 : X ⟶ Y) 0)] : is_iso (kernel.ι (0 : X ⟶ Y)) :=
equalizer.ι_of_self _
end
section
variables [has_zero_morphisms.{v} C]
/-- A cokernel cofork is just a cofork where the second morphism is a zero morphism. -/
abbreviation cokernel_cofork := cofork f 0
variables {f}
@[simp, reassoc] lemma cokernel_cofork.condition (s : cokernel_cofork f) : f ≫ cofork.π s = 0 :=
by erw [cofork.condition, has_zero_morphisms.zero_comp]
@[simp] lemma cokernel_cofork.app_zero (s : cokernel_cofork f) : s.ι.app zero = 0 :=
by erw [←cocone_parallel_pair_left, cokernel_cofork.condition]; refl
/-- A morphism `π` satisfying `f ≫ π = 0` determines a cokernel cofork on `f`. -/
abbreviation cokernel_cofork.of_π {Z : C} (π : Y ⟶ Z) (w : f ≫ π = 0) : cokernel_cofork f :=
cofork.of_π π $ by rw [w, has_zero_morphisms.zero_comp]
end
section
variables [has_zero_morphisms.{v} C] [has_colimit (parallel_pair f 0)]
/-- The cokernel of a morphism, expressed as the coequalizer with the 0 morphism. -/
abbreviation cokernel : C := coequalizer f 0
/-- The map from the target of `f` to `cokernel f`. -/
abbreviation cokernel.π : Y ⟶ cokernel f := coequalizer.π f 0
@[simp, reassoc] lemma cokernel.condition : f ≫ cokernel.π f = 0 :=
cokernel_cofork.condition _
/-- Given any morphism `k` so `f ≫ k = 0`, `k` factors through `cokernel f`. -/
abbreviation cokernel.desc {W : C} (k : Y ⟶ W) (h : f ≫ k = 0) : cokernel f ⟶ W :=
colimit.desc (parallel_pair f 0) (cokernel_cofork.of_π k h)
end
section has_zero_object
variables [has_zero_object.{v} C]
local attribute [instance] has_zero_object.has_zero
variable [has_zero_morphisms.{v} C]
/-- The morphism to the zero object determines a cocone on a cokernel diagram -/
def cokernel.zero_cocone : cocone (parallel_pair f 0) :=
{ X := 0,
ι := { app := λ j, 0 } }
/-- The morphism to the zero object is a cokernel of an epimorphism -/
def cokernel.is_colimit_cocone_zero_cocone [epi f] : is_colimit (cokernel.zero_cocone f) :=
cofork.is_colimit.mk _ (λ s, 0)
(λ s, by { erw has_zero_morphisms.zero_comp,
convert (@zero_of_comp_epi _ _ _ _ _ _ f _ _ _).symm,
exact cokernel_cofork.condition _ })
(λ _ _ _, has_zero_object.zero_of_from_zero _)
/-- The cokernel of an epimorphism is isomorphic to the zero object -/
def cokernel.of_epi [has_colimit (parallel_pair f 0)] [epi f] : cokernel f ≅ 0 :=
functor.map_iso (cocones.forget _) $ is_colimit.unique_up_to_iso
(colimit.is_colimit (parallel_pair f 0)) (cokernel.is_colimit_cocone_zero_cocone f)
/-- The cokernel morphism if an epimorphism is a zero morphism -/
lemma cokernel.π_of_epi [has_colimit (parallel_pair f 0)] [epi f] : cokernel.π f = 0 :=
by rw [←category.comp_id _ (cokernel.π f), ←iso.hom_inv_id (cokernel.of_epi f), ←category.assoc,
has_zero_object.zero_of_from_zero (cokernel.of_epi f).inv, has_zero_morphisms.comp_zero]
end has_zero_object
section
variables (X) (Y) [has_zero_morphisms.{v} C]
/-- The cokernel of a zero morphism is an isomorphism -/
def cokernel.π_of_zero [has_colimit (parallel_pair (0 : X ⟶ Y) 0)] :
is_iso (cokernel.π (0 : X ⟶ Y)) :=
coequalizer.π_of_self _
end
section has_zero_object
variables [has_zero_object.{v} C]
local attribute [instance] has_zero_object.has_zero
variables [has_zero_morphisms.{v} C]
/-- The kernel of the cokernel of an epimorphism is an isomorphism -/
instance kernel.of_cokernel_of_epi [has_colimit (parallel_pair f 0)]
[has_limit (parallel_pair (cokernel.π f) 0)] [epi f] : is_iso (kernel.ι (cokernel.π f)) :=
equalizer.ι_of_self' _ _ $ cokernel.π_of_epi f
/-- The cokernel of the kernel of a monomorphism is an isomorphism -/
instance cokernel.of_kernel_of_mono [has_limit (parallel_pair f 0)]
[has_colimit (parallel_pair (kernel.ι f) 0)] [mono f] : is_iso (cokernel.π (kernel.ι f)) :=
coequalizer.π_of_self' _ _ $ kernel.ι_of_mono f
end has_zero_object
end category_theory.limits
namespace category_theory.limits
variables (C : Type u) [𝒞 : category.{v} C]
include 𝒞
variables [has_zero_morphisms.{v} C]
/-- `has_kernels` represents a choice of kernel for every morphism -/
class has_kernels :=
(has_limit : Π {X Y : C} (f : X ⟶ Y), has_limit (parallel_pair f 0))
/-- `has_cokernels` represents a choice of cokernel for every morphism -/
class has_cokernels :=
(has_colimit : Π {X Y : C} (f : X ⟶ Y), has_colimit (parallel_pair f 0))
attribute [instance] has_kernels.has_limit has_cokernels.has_colimit
/-- Kernels are finite limits, so if `C` has all finite limits, it also has all kernels -/
def has_kernels_of_has_finite_limits [has_finite_limits.{v} C] : has_kernels.{v} C :=
{ has_limit := infer_instance }
/-- Cokernels are finite limits, so if `C` has all finite colimits, it also has all cokernels -/
def has_cokernels_of_has_finite_colimits [has_finite_colimits.{v} C] : has_cokernels.{v} C :=
{ has_colimit := infer_instance }
end category_theory.limits
|
0a321f19dcc9d27976af02e2c3267b631507ae7d | 07f5f86b00fed90a419ccda4298d8b795a68f657 | /library/init/data/bool/lemmas.lean | c5d85710b8ac2cedd6e19537fbaf41a2ed35e571 | [
"Apache-2.0"
] | permissive | VBaratham/lean | 8ec5c3167b4835cfbcd7f25e2173d61ad9416b3a | 450ca5834c1c35318e4b47d553bb9820c1b3eee7 | refs/heads/master | 1,629,649,471,814 | 1,512,060,373,000 | 1,512,060,469,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 4,657 | lean | /-
Copyright (c) 2017 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
prelude
import init.data.bool.basic init.meta
attribute [simp] cond bor band bnot bxor
@[simp] lemma {u} cond_a_a {α : Type u} (b : bool) (a : α) : cond b a a = a :=
by cases b; simp
@[simp] lemma band_self (b : bool) : b && b = b :=
by cases b; simp
@[simp] lemma band_tt (b : bool) : b && tt = b :=
by cases b; simp
@[simp] lemma band_ff (b : bool) : b && ff = ff :=
by cases b; simp
@[simp] lemma tt_band (b : bool) : tt && b = b :=
by cases b; simp
@[simp] lemma ff_band (b : bool) : ff && b = ff :=
by cases b; simp
@[simp] lemma bor_self (b : bool) : b || b = b :=
by cases b; simp
@[simp] lemma bor_tt (b : bool) : b || tt = tt :=
by cases b; simp
@[simp] lemma bor_ff (b : bool) : b || ff = b :=
by cases b; simp
@[simp] lemma tt_bor (b : bool) : tt || b = tt :=
by cases b; simp
@[simp] lemma ff_bor (b : bool) : ff || b = b :=
by cases b; simp
@[simp] lemma bxor_self (b : bool) : bxor b b = ff :=
by cases b; simp
@[simp] lemma bxor_tt (b : bool) : bxor b tt = bnot b :=
by cases b; simp
@[simp] lemma bxor_ff (b : bool) : bxor b ff = b :=
by cases b; simp
@[simp] lemma tt_bxor (b : bool) : bxor tt b = bnot b :=
by cases b; simp
@[simp] lemma ff_bxor (b : bool) : bxor ff b = b :=
by cases b; simp
@[simp] lemma bnot_bnot (b : bool) : bnot (bnot b) = b :=
by cases b; simp
@[simp] lemma tt_eq_ff_eq_false : ¬(tt = ff) :=
by contradiction
@[simp] lemma ff_eq_tt_eq_false : ¬(ff = tt) :=
by contradiction
@[simp] lemma eq_ff_eq_not_eq_tt (b : bool) : (¬(b = tt)) = (b = ff) :=
by cases b; simp
@[simp] lemma eq_tt_eq_not_eq_ff (b : bool) : (¬(b = ff)) = (b = tt) :=
by cases b; simp
lemma eq_ff_of_not_eq_tt {b : bool} : (¬(b = tt)) → (b = ff) :=
eq.mp (eq_ff_eq_not_eq_tt b)
lemma eq_tt_of_not_eq_ff {b : bool} : (¬(b = ff)) → (b = tt) :=
eq.mp (eq_tt_eq_not_eq_ff b)
@[simp] lemma band_eq_true_eq_eq_tt_and_eq_tt (a b : bool) : (a && b = tt) = (a = tt ∧ b = tt) :=
by cases a; cases b; simp
@[simp] lemma bor_eq_true_eq_eq_tt_or_eq_tt (a b : bool) : (a || b = tt) = (a = tt ∨ b = tt) :=
by cases a; cases b; simp
@[simp] lemma bnot_eq_true_eq_eq_ff (a : bool) : (bnot a = tt) = (a = ff) :=
by cases a; simp
@[simp] lemma band_eq_false_eq_eq_ff_or_eq_ff (a b : bool) : (a && b = ff) = (a = ff ∨ b = ff) :=
by cases a; cases b; simp
@[simp] lemma bor_eq_false_eq_eq_ff_and_eq_ff (a b : bool) : (a || b = ff) = (a = ff ∧ b = ff) :=
by cases a; cases b; simp
@[simp] lemma bnot_eq_ff_eq_eq_tt (a : bool) : (bnot a = ff) = (a = tt) :=
by cases a; simp
@[simp] lemma coe_ff : ↑ff = false :=
show (ff = tt) = false, by simp
@[simp] lemma coe_tt : ↑tt = true :=
show (tt = tt) = true, by simp
theorem to_bool_iff (p : Prop) [d : decidable p] : to_bool p ↔ p :=
match d with
| is_true hp := ⟨λh, hp, λ_, rfl⟩
| is_false hnp := ⟨λh, bool.no_confusion h, λhp, absurd hp hnp⟩
end
theorem to_bool_true {p : Prop} [decidable p] : p → to_bool p := (to_bool_iff p).2
theorem to_bool_tt {p : Prop} [decidable p] : p → to_bool p = tt := to_bool_true
theorem of_to_bool_true {p : Prop} [decidable p] : to_bool p → p := (to_bool_iff p).1
theorem bool_iff_false {b : bool} : ¬ b ↔ b = ff := by cases b; exact dec_trivial
theorem bool_eq_false {b : bool} : ¬ b → b = ff := bool_iff_false.1
theorem to_bool_ff_iff (p : Prop) [decidable p] : to_bool p = ff ↔ ¬p :=
bool_iff_false.symm.trans (not_congr (to_bool_iff _))
theorem to_bool_ff {p : Prop} [decidable p] : ¬p → to_bool p = ff := (to_bool_ff_iff p).2
theorem of_to_bool_ff {p : Prop} [decidable p] : to_bool p = ff → ¬p := (to_bool_ff_iff p).1
theorem to_bool_congr {p q : Prop} [decidable p] [decidable q] (h : p ↔ q) : to_bool p = to_bool q :=
begin
ginduction to_bool q with h',
exact to_bool_ff (mt h.1 $ of_to_bool_ff h'),
exact to_bool_true (h.2 $ of_to_bool_true h')
end
@[simp] theorem bor_coe_iff (a b : bool) : a || b ↔ a ∨ b :=
by cases a; cases b; exact dec_trivial
@[simp] theorem band_coe_iff (a b : bool) : a && b ↔ a ∧ b :=
by cases a; cases b; exact dec_trivial
@[simp] theorem bxor_coe_iff (a b : bool) : bxor a b ↔ xor a b :=
by cases a; cases b; exact dec_trivial
@[simp] theorem ite_eq_tt_distrib (c : Prop) [decidable c] (a b : bool) : ((if c then a else b) = tt) = (if c then a = tt else b = tt) :=
by by_cases c with h; simp [h]
@[simp] theorem ite_eq_ff_distrib (c : Prop) [decidable c] (a b : bool) : ((if c then a else b) = ff) = (if c then a = ff else b = ff) :=
by by_cases c with h; simp [h]
|
7bc75dcbb3f80c753524b741c3f4598a911cabe8 | 1dd482be3f611941db7801003235dc84147ec60a | /src/tactic/interactive.lean | 5fc5dba72da16c2cd7ae9f0abeed214b61af22ad | [
"Apache-2.0"
] | permissive | sanderdahmen/mathlib | 479039302bd66434bb5672c2a4cecf8d69981458 | 8f0eae75cd2d8b7a083cf935666fcce4565df076 | refs/heads/master | 1,587,491,322,775 | 1,549,672,060,000 | 1,549,672,060,000 | 169,748,224 | 0 | 0 | Apache-2.0 | 1,549,636,694,000 | 1,549,636,694,000 | null | UTF-8 | Lean | false | false | 25,478 | lean | /-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Simon Hudon, Sebastien Gouezel, Scott Morrison
-/
import data.dlist data.dlist.basic data.prod category.basic
tactic.basic tactic.rcases tactic.generalize_proofs
tactic.split_ifs logic.basic tactic.ext tactic.tauto
tactic.replacer tactic.simpa tactic.squeeze
open lean
open lean.parser
local postfix `?`:9001 := optional
local postfix *:9001 := many
namespace tactic
namespace interactive
open interactive interactive.types expr
/--
The `rcases` tactic is the same as `cases`, but with more flexibility in the
`with` pattern syntax to allow for recursive case splitting. The pattern syntax
uses the following recursive grammar:
```
patt ::= (patt_list "|")* patt_list
patt_list ::= id | "_" | "⟨" (patt ",")* patt "⟩"
```
A pattern like `⟨a, b, c⟩ | ⟨d, e⟩` will do a split over the inductive datatype,
naming the first three parameters of the first constructor as `a,b,c` and the
first two of the second constructor `d,e`. If the list is not as long as the
number of arguments to the constructor or the number of constructors, the
remaining variables will be automatically named. If there are nested brackets
such as `⟨⟨a⟩, b | c⟩ | d` then these will cause more case splits as necessary.
If there are too many arguments, such as `⟨a, b, c⟩` for splitting on
`∃ x, ∃ y, p x`, then it will be treated as `⟨a, ⟨b, c⟩⟩`, splitting the last
parameter as necessary.
`rcases` also has special support for quotient types: quotient induction into Prop works like
matching on the constructor `quot.mk`.
`rcases? e` will perform case splits on `e` in the same way as `rcases e`,
but rather than accepting a pattern, it does a maximal cases and prints the
pattern that would produce this case splitting. The default maximum depth is 5,
but this can be modified with `rcases? e : n`.
-/
meta def rcases : parse rcases_parse → tactic unit
| (p, sum.inl ids) := tactic.rcases p ids
| (p, sum.inr depth) := do
patt ← tactic.rcases_hint p depth,
pe ← pp p,
trace $ ↑"snippet: rcases " ++ pe ++ " with " ++ to_fmt patt
/--
The `rintro` tactic is a combination of the `intros` tactic with `rcases` to
allow for destructuring patterns while introducing variables. See `rcases` for
a description of supported patterns. For example, `rintros (a | ⟨b, c⟩) ⟨d, e⟩`
will introduce two variables, and then do case splits on both of them producing
two subgoals, one with variables `a d e` and the other with `b c d e`.
`rintro?` will introduce and case split on variables in the same way as
`rintro`, but will also print the `rintro` invocation that would have the same
result. Like `rcases?`, `rintro? : n` allows for modifying the
depth of splitting; the default is 5.
-/
meta def rintro : parse rintro_parse → tactic unit
| (sum.inl []) := intros []
| (sum.inl l) := tactic.rintro l
| (sum.inr depth) := do
ps ← tactic.rintro_hint depth,
trace $ ↑"snippet: rintro" ++ format.join (ps.map $ λ p,
format.space ++ format.group (p.format tt))
/-- Alias for `rintro`. -/
meta def rintros := rintro
/-- `try_for n { tac }` executes `tac` for `n` ticks, otherwise uses `sorry` to close the goal.
Never fails. Useful for debugging. -/
meta def try_for (max : parse parser.pexpr) (tac : itactic) : tactic unit :=
do max ← i_to_expr_strict max >>= tactic.eval_expr nat,
λ s, match _root_.try_for max (tac s) with
| some r := r
| none := (tactic.trace "try_for timeout, using sorry" >> admit) s
end
/-- Multiple subst. `substs x y z` is the same as `subst x, subst y, subst z`. -/
meta def substs (l : parse ident*) : tactic unit :=
l.mmap' (λ h, get_local h >>= tactic.subst) >> try (tactic.reflexivity reducible)
/-- Unfold coercion-related definitions -/
meta def unfold_coes (loc : parse location) : tactic unit :=
unfold [
``coe, ``coe_t, ``has_coe_t.coe, ``coe_b,``has_coe.coe,
``lift, ``has_lift.lift, ``lift_t, ``has_lift_t.lift,
``coe_fn, ``has_coe_to_fun.coe, ``coe_sort, ``has_coe_to_sort.coe] loc
/-- Unfold auxiliary definitions associated with the current declaration. -/
meta def unfold_aux : tactic unit :=
do tgt ← target,
name ← decl_name,
let to_unfold := (tgt.list_names_with_prefix name),
guard (¬ to_unfold.empty),
-- should we be using simp_lemmas.mk_default?
simp_lemmas.mk.dsimplify to_unfold.to_list tgt >>= tactic.change
/-- For debugging only. This tactic checks the current state for any
missing dropped goals and restores them. Useful when there are no
goals to solve but "result contains meta-variables". -/
meta def recover : tactic unit :=
metavariables >>= tactic.set_goals
/-- Like `try { tac }`, but in the case of failure it continues
from the failure state instead of reverting to the original state. -/
meta def continue (tac : itactic) : tactic unit :=
λ s, result.cases_on (tac s)
(λ a, result.success ())
(λ e ref, result.success ())
/-- Move goal `n` to the front. -/
meta def swap (n := 2) : tactic unit :=
do gs ← get_goals,
match gs.nth (n-1) with
| (some g) := set_goals (g :: gs.remove_nth (n-1))
| _ := skip
end
/-- Generalize proofs in the goal, naming them with the provided list. -/
meta def generalize_proofs : parse ident_* → tactic unit :=
tactic.generalize_proofs
/-- Clear all hypotheses starting with `_`, like `_match` and `_let_match`. -/
meta def clear_ : tactic unit := tactic.repeat $ do
l ← local_context,
l.reverse.mfirst $ λ h, do
name.mk_string s p ← return $ local_pp_name h,
guard (s.front = '_'),
cl ← infer_type h >>= is_class, guard (¬ cl),
tactic.clear h
/--
Same as the `congr` tactic, but takes an optional argument which gives
the depth of recursive applications. This is useful when `congr`
is too aggressive in breaking down the goal. For example, given
`⊢ f (g (x + y)) = f (g (y + x))`, `congr'` produces the goals `⊢ x = y`
and `⊢ y = x`, while `congr' 2` produces the intended `⊢ x + y = y + x`. -/
meta def congr' : parse (with_desc "n" small_nat)? → tactic unit
| (some 0) := failed
| o := focus1 (assumption <|> (congr_core >>
all_goals (reflexivity <|> `[apply proof_irrel_heq] <|>
`[apply proof_irrel] <|> try (congr' (nat.pred <$> o)))))
/--
Acts like `have`, but removes a hypothesis with the same name as
this one. For example if the state is `h : p ⊢ goal` and `f : p → q`,
then after `replace h := f h` the goal will be `h : q ⊢ goal`,
where `have h := f h` would result in the state `h : p, h : q ⊢ goal`.
This can be used to simulate the `specialize` and `apply at` tactics
of Coq. -/
meta def replace (h : parse ident?) (q₁ : parse (tk ":" *> texpr)?) (q₂ : parse $ (tk ":=" *> texpr)?) : tactic unit :=
do let h := h.get_or_else `this,
old ← try_core (get_local h),
«have» h q₁ q₂,
match old, q₂ with
| none, _ := skip
| some o, some _ := tactic.clear o
| some o, none := swap >> tactic.clear o >> swap
end
/--
`apply_assumption` looks for an assumption of the form `... → ∀ _, ... → head`
where `head` matches the current goal.
alternatively, when encountering an assumption of the form `sg₀ → ¬ sg₁`,
after the main approach failed, the goal is dismissed and `sg₀` and `sg₁`
are made into the new goal.
optional arguments:
- asms: list of rules to consider instead of the local constants
- tac: a tactic to run on each subgoals after applying an assumption; if
this tactic fails, the corresponding assumption will be rejected and
the next one will be attempted.
-/
meta def apply_assumption
(asms : tactic (list expr) := local_context)
(tac : tactic unit := return ()) : tactic unit :=
tactic.apply_assumption asms tac
open nat
meta def mk_assumption_set (no_dflt : bool) (hs : list simp_arg_type) (attr : list name): tactic (list expr) :=
do (hs, gex, hex, all_hyps) ← decode_simp_arg_list hs,
hs ← hs.mmap i_to_expr_for_apply,
l ← attr.mmap $ λ a, attribute.get_instances a,
let l := l.join,
m ← list.mmap mk_const l,
let hs := (hs ++ m).filter $ λ h, expr.const_name h ∉ gex,
hs ← if no_dflt then
return hs
else
do { congr_fun ← mk_const `congr_fun,
congr_arg ← mk_const `congr_arg,
return (congr_fun :: congr_arg :: hs) },
if ¬ no_dflt ∨ all_hyps then do
ctx ← local_context,
return $ hs.append (ctx.filter (λ h, h.local_uniq_name ∉ hex)) -- remove local exceptions
else return hs
/--
`solve_by_elim` calls `apply_assumption` on the main goal to find an assumption whose head matches
and then repeatedly calls `apply_assumption` on the generated subgoals until no subgoals remain,
performing at most `max_rep` recursive steps.
`solve_by_elim` discharges the current goal or fails
`solve_by_elim` performs back-tracking if `apply_assumption` chooses an unproductive assumption
By default, the assumptions passed to apply_assumption are the local context, `congr_fun` and
`congr_arg`.
`solve_by_elim [h₁, h₂, ..., hᵣ]` also applies the named lemmas.
`solve_by_elim with attr₁ ... attrᵣ also applied all lemmas tagged with the specified attributes.
`solve_by_elim only [h₁, h₂, ..., hᵣ]` does not include the local context, `congr_fun`, or `congr_arg`
unless they are explicitly included.
`solve_by_elim [-id]` removes a specified assumption.
optional arguments:
- discharger: a subsidiary tactic to try at each step (e.g. `cc` may be helpful)
- max_rep: number of attempts at discharging generated sub-goals
-/
meta def solve_by_elim (no_dflt : parse only_flag) (hs : parse simp_arg_list) (attr_names : parse with_ident_list) (opt : by_elim_opt := { }) : tactic unit :=
do asms ← mk_assumption_set no_dflt hs attr_names,
tactic.solve_by_elim { assumptions := return asms ..opt }
/--
`tautology` breaks down assumptions of the form `_ ∧ _`, `_ ∨ _`, `_ ↔ _` and `∃ _, _`
and splits a goal of the form `_ ∧ _`, `_ ↔ _` or `∃ _, _` until it can be discharged
using `reflexivity` or `solve_by_elim`
-/
meta def tautology (c : parse $ (tk "!")?) := tactic.tautology c.is_some
/-- Shorter name for the tactic `tautology`. -/
meta def tauto (c : parse $ (tk "!")?) := tautology c
/-- Make every propositions in the context decidable -/
meta def classical := tactic.classical
private meta def generalize_arg_p_aux : pexpr → parser (pexpr × name)
| (app (app (macro _ [const `eq _ ]) h) (local_const x _ _ _)) := pure (h, x)
| _ := fail "parse error"
private meta def generalize_arg_p : parser (pexpr × name) :=
with_desc "expr = id" $ parser.pexpr 0 >>= generalize_arg_p_aux
lemma {u} generalize_a_aux {α : Sort u}
(h : ∀ x : Sort u, (α → x) → x) : α := h α id
/--
Like `generalize` but also considers assumptions
specified by the user. The user can also specify to
omit the goal.
-/
meta def generalize_hyp (h : parse ident?) (_ : parse $ tk ":")
(p : parse generalize_arg_p)
(l : parse location) :
tactic unit :=
do h' ← get_unused_name `h,
x' ← get_unused_name `x,
g ← if ¬ l.include_goal then
do refine ``(generalize_a_aux _),
some <$> (prod.mk <$> tactic.intro x' <*> tactic.intro h')
else pure none,
n ← l.get_locals >>= tactic.revert_lst,
generalize h () p,
intron n,
match g with
| some (x',h') :=
do tactic.apply h',
tactic.clear h',
tactic.clear x'
| none := return ()
end
/--
Similar to `refine` but generates equality proof obligations
for every discrepancy between the goal and the type of the rule.
-/
meta def convert (sym : parse (with_desc "←" (tk "<-")?)) (r : parse texpr) (n : parse (tk "using" *> small_nat)?) : tactic unit :=
do v ← mk_mvar,
if sym.is_some
then refine ``(eq.mp %%v %%r)
else refine ``(eq.mpr %%v %%r),
gs ← get_goals,
set_goals [v],
congr' n,
gs' ← get_goals,
set_goals $ gs' ++ gs
meta def clean_ids : list name :=
[``id, ``id_rhs, ``id_delta, ``hidden]
/--
Remove identity functions from a term. These are normally
automatically generated with terms like `show t, from p` or
`(p : t)` which translate to some variant on `@id t p` in
order to retain the type. -/
meta def clean (q : parse texpr) : tactic unit :=
do tgt : expr ← target,
e ← i_to_expr_strict ``(%%q : %%tgt),
tactic.exact $ e.replace (λ e n,
match e with
| (app (app (const n _) _) e') :=
if n ∈ clean_ids then some e' else none
| (app (lam _ _ _ (var 0)) e') := some e'
| _ := none
end)
meta def source_fields (missing : list name) (e : pexpr) : tactic (list (name × pexpr)) :=
do e ← to_expr e,
t ← infer_type e,
let struct_n : name := t.get_app_fn.const_name,
fields ← expanded_field_list struct_n,
let exp_fields := fields.filter (λ x, x.2 ∈ missing),
exp_fields.mmap $ λ ⟨p,n⟩,
(prod.mk n ∘ to_pexpr) <$> mk_mapp (n.update_prefix p) [none,some e]
meta def collect_struct' : pexpr → state_t (list $ expr×structure_instance_info) tactic pexpr | e :=
do some str ← pure (e.get_structure_instance_info)
| e.traverse collect_struct',
v ← monad_lift mk_mvar,
modify (list.cons (v,str)),
pure $ to_pexpr v
meta def collect_struct (e : pexpr) : tactic $ pexpr × list (expr×structure_instance_info) :=
prod.map id list.reverse <$> (collect_struct' e).run []
meta def refine_one (str : structure_instance_info) :
tactic $ list (expr×structure_instance_info) :=
do tgt ← target,
let struct_n : name := tgt.get_app_fn.const_name,
exp_fields ← expanded_field_list struct_n,
let missing_f := exp_fields.filter (λ f, (f.2 : name) ∉ str.field_names),
(src_field_names,src_field_vals) ← (@list.unzip name _ ∘ list.join) <$> str.sources.mmap (source_fields $ missing_f.map prod.snd),
let provided := exp_fields.filter (λ f, (f.2 : name) ∈ str.field_names),
let missing_f' := missing_f.filter (λ x, x.2 ∉ src_field_names),
vs ← mk_mvar_list missing_f'.length,
(field_values,new_goals) ← list.unzip <$> (str.field_values.mmap collect_struct : tactic _),
e' ← to_expr $ pexpr.mk_structure_instance
{ struct := some struct_n
, field_names := str.field_names ++ missing_f'.map prod.snd ++ src_field_names
, field_values := field_values ++ vs.map to_pexpr ++ src_field_vals },
tactic.exact e',
gs ← with_enable_tags (
mzip_with (λ (n : name × name) v, do
set_goals [v],
try (interactive.unfold (provided.map $ λ ⟨s,f⟩, f.update_prefix s) (loc.ns [none])),
apply_auto_param
<|> apply_opt_param
<|> (set_main_tag [`_field,n.2,n.1]),
get_goals)
missing_f' vs),
set_goals gs.join,
return new_goals.join
meta def refine_recursively : expr × structure_instance_info → tactic (list expr) | (e,str) :=
do set_goals [e],
rs ← refine_one str,
gs ← get_goals,
gs' ← rs.mmap refine_recursively,
return $ gs'.join ++ gs
/--
`refine_struct { .. }` acts like `refine` but works only with structure instance
literals. It creates a goal for each missing field and tags it with the name of the
field so that `have_field` can be used to generically refer to the field currently
being refined.
As an example, we can use `refine_struct` to automate the construction semigroup
instances:
```
refine_struct ( { .. } : semigroup α ),
-- case semigroup, mul
-- α : Type u,
-- ⊢ α → α → α
-- case semigroup, mul_assoc
-- α : Type u,
-- ⊢ ∀ (a b c : α), a * b * c = a * (b * c)
```
-/
meta def refine_struct : parse texpr → tactic unit | e :=
do (x,xs) ← collect_struct e,
refine x,
gs ← get_goals,
xs' ← xs.mmap refine_recursively,
set_goals (xs'.join ++ gs)
/--
`guard_hyp h := t` fails if the hypothesis `h` does not have type `t`.
We use this tactic for writing tests.
Fixes `guard_hyp` by instantiating meta variables
-/
meta def guard_hyp' (n : parse ident) (p : parse $ tk ":=" *> texpr) : tactic unit :=
do h ← get_local n >>= infer_type >>= instantiate_mvars, guard_expr_eq h p
meta def guard_hyp_nums (n : ℕ) : tactic unit :=
do k ← local_context,
guard (n = k.length) <|> fail format!"{k.length} hypotheses found"
meta def guard_tags (tags : parse ident*) : tactic unit :=
do (t : list name) ← get_main_tag,
guard (t = tags)
meta def get_current_field : tactic name :=
do [_,field,str] ← get_main_tag,
expr.const_name <$> resolve_name (field.update_prefix str)
meta def field (n : parse ident) (tac : itactic) : tactic unit :=
do gs ← get_goals,
ts ← gs.mmap get_tag,
([g],gs') ← pure $ (list.zip gs ts).partition (λ x, x.snd.nth 1 = some n),
set_goals [g.1],
tac, done,
set_goals $ gs'.map prod.fst
/--
`have_field`, used after `refine_struct _` poses `field` as a local constant
with the type of the field of the current goal:
```
refine_struct ({ .. } : semigroup α),
{ have_field, ... },
{ have_field, ... },
```
behaves like
```
refine_struct ({ .. } : semigroup α),
{ have field := @semigroup.mul, ... },
{ have field := @semigroup.mul_assoc, ... },
```
-/
meta def have_field : tactic unit :=
propagate_tags $
get_current_field
>>= mk_const
>>= note `field none
>> return ()
/-- `apply_field` functions as `have_field, apply field, clear field` -/
meta def apply_field : tactic unit :=
propagate_tags $
get_current_field >>= applyc
/--`apply_rules hs n`: apply the list of rules `hs` (given as pexpr) and `assumption` on the
first goal and the resulting subgoals, iteratively, at most `n` times.
`n` is 50 by default. `hs` can contain user attributes: in this case all theorems with this
attribute are added to the list of rules.
example, with or without user attribute:
```
@[user_attribute]
meta def mono_rules : user_attribute :=
{ name := `mono_rules,
descr := "lemmas usable to prove monotonicity" }
attribute [mono_rules] add_le_add mul_le_mul_of_nonneg_right
lemma my_test {a b c d e : real} (h1 : a ≤ b) (h2 : c ≤ d) (h3 : 0 ≤ e) :
a + c * e + a + c + 0 ≤ b + d * e + b + d + e :=
by apply_rules mono_rules
-- any of the following lines would also work:
-- add_le_add (add_le_add (add_le_add (add_le_add h1 (mul_le_mul_of_nonneg_right h2 h3)) h1 ) h2) h3
-- by apply_rules [add_le_add, mul_le_mul_of_nonneg_right]
-- by apply_rules [mono_rules]
```
-/
meta def apply_rules (hs : parse pexpr_list_or_texpr) (n : nat := 50) : tactic unit :=
tactic.apply_rules hs n
meta def return_cast (f : option expr) (t : option (expr × expr))
(es : list (expr × expr × expr))
(e x x' eq_h : expr) :
tactic (option (expr × expr) × list (expr × expr × expr)) :=
(do guard (¬ e.has_var),
unify x x',
u ← mk_meta_univ,
f ← f <|> mk_mapp ``_root_.id [(expr.sort u : expr)],
t' ← infer_type e,
some (f',t) ← pure t | return (some (f,t'), (e,x',eq_h) :: es),
infer_type e >>= is_def_eq t,
unify f f',
return (some (f,t), (e,x',eq_h) :: es)) <|>
return (t, es)
meta def list_cast_of_aux (x : expr) (t : option (expr × expr))
(es : list (expr × expr × expr)) :
expr → tactic (option (expr × expr) × list (expr × expr × expr))
| e@`(cast %%eq_h %%x') := return_cast none t es e x x' eq_h
| e@`(eq.mp %%eq_h %%x') := return_cast none t es e x x' eq_h
| e@`(eq.mpr %%eq_h %%x') := mk_eq_symm eq_h >>= return_cast none t es e x x'
| e@`(@eq.subst %%α %%p %%a %%b %%eq_h %%x') := return_cast p t es e x x' eq_h
| e@`(@eq.substr %%α %%p %%a %%b %%eq_h %%x') := mk_eq_symm eq_h >>= return_cast p t es e x x'
| e@`(@eq.rec %%α %%a %%f %%x' _ %%eq_h) := return_cast f t es e x x' eq_h
| e@`(@eq.rec_on %%α %%a %%f %%b %%eq_h %%x') := return_cast f t es e x x' eq_h
| e := return (t,es)
meta def list_cast_of (x tgt : expr) : tactic (list (expr × expr × expr)) :=
(list.reverse ∘ prod.snd) <$> tgt.mfold (none, []) (λ e i es, list_cast_of_aux x es.1 es.2 e)
private meta def h_generalize_arg_p_aux : pexpr → parser (pexpr × name)
| (app (app (macro _ [const `heq _ ]) h) (local_const x _ _ _)) := pure (h, x)
| _ := fail "parse error"
private meta def h_generalize_arg_p : parser (pexpr × name) :=
with_desc "expr == id" $ parser.pexpr 0 >>= h_generalize_arg_p_aux
/--
`h_generalize Hx : e == x` matches on `cast _ e` in the goal and replaces it with
`x`. It also adds `Hx : e == x` as an assumption. If `cast _ e` appears multiple
times (not necessarily with the same proof), they are all replaced by `x`. `cast`
`eq.mp`, `eq.mpr`, `eq.subst`, `eq.substr`, `eq.rec` and `eq.rec_on` are all treated
as casts.
`h_generalize Hx : e == x with h` adds hypothesis `α = β` with `e : α, x : β`.
`h_generalize Hx : e == x with _` chooses automatically chooses the name of
assumption `α = β`.
`h_generalize! Hx : e == x` reverts `Hx`.
when `Hx` is omitted, assumption `Hx : e == x` is not added.
-/
meta def h_generalize (rev : parse (tk "!")?)
(h : parse ident_?)
(_ : parse (tk ":"))
(arg : parse h_generalize_arg_p)
(eqs_h : parse ( (tk "with" >> pure <$> ident_) <|> pure [])) :
tactic unit :=
do let (e,n) := arg,
let h' := if h = `_ then none else h,
h' ← (h' : tactic name) <|> get_unused_name ("h" ++ n.to_string : string),
e ← to_expr e,
tgt ← target,
((e,x,eq_h)::es) ← list_cast_of e tgt | fail "no cast found",
interactive.generalize h' () (to_pexpr e, n),
asm ← get_local h',
v ← get_local n,
hs ← es.mmap (λ ⟨e,_⟩, mk_app `eq [e,v]),
(eqs_h.zip [e]).mmap' (λ ⟨h,e⟩, do
h ← if h ≠ `_ then pure h else get_unused_name `h,
() <$ note h none eq_h ),
hs.mmap' (λ h,
do h' ← assert `h h,
tactic.exact asm,
try (rewrite_target h'),
tactic.clear h' ),
when h.is_some (do
(to_expr ``(heq_of_eq_rec_left %%eq_h %%asm)
<|> to_expr ``(heq_of_eq_mp %%eq_h %%asm))
>>= note h' none >> pure ()),
tactic.clear asm,
when rev.is_some (interactive.revert [n])
/-- `choose a b h using hyp` takes an hypothesis `hyp` of the form
`∀ (x : X) (y : Y), ∃ (a : A) (b : B), P x y a b` for some `P : X → Y → A → B → Prop` and outputs
into context a function `a : X → Y → A`, `b : X → Y → B` and a proposition `h` stating
`∀ (x : X) (y : Y), P x y (a x y) (b x y)`. It presumably also works with dependent versions.
Example:
```lean
example (h : ∀n m : ℕ, ∃i j, m = n + i ∨ m + j = n) : true :=
begin
choose i j h using h,
guard_hyp i := ℕ → ℕ → ℕ,
guard_hyp j := ℕ → ℕ → ℕ,
guard_hyp h := ∀ (n m : ℕ), m = n + i n m ∨ m + j n m = n,
trivial
end
```
-/
meta def choose (first : parse ident) (names : parse ident*) (tgt : parse (tk "using" *> texpr)?) :
tactic unit := do
tgt ← match tgt with
| none := get_local `this
| some e := tactic.i_to_expr_strict e
end,
tactic.choose tgt (first :: names),
try (tactic.clear tgt)
meta def guard_expr_eq' (t : expr) (p : parse $ tk ":=" *> texpr) : tactic unit :=
do e ← to_expr p, is_def_eq t e
/--
`guard_target t` fails if the target of the main goal is not `t`.
We use this tactic for writing tests.
-/
meta def guard_target' (p : parse texpr) : tactic unit :=
do t ← target, guard_expr_eq' t p
/--
a weaker version of `trivial` that tries to solve the goal by reflexivity or by reducing it to true,
unfolding only `reducible` constants. -/
meta def triv : tactic unit :=
tactic.triv' <|> tactic.reflexivity reducible <|> tactic.contradiction <|> fail "triv tactic failed"
/--
Similar to `existsi`. `use x` will instantiate the first term of an `∃` or `Σ` goal with `x`.
Unlike `existsi`, `x` is elaborated with respect to the expected type.
`use` will alternatively take a list of terms `[x0, ..., xn]`.
`use` will work with constructors of arbitrary inductive types.
Examples:
example (α : Type) : ∃ S : set α, S = S :=
by use ∅
example : ∃ x : ℤ, x = x :=
by use 42
example : ∃ a b c : ℤ, a + b + c = 6 :=
by use [1, 2, 3]
example : ∃ p : ℤ × ℤ, p.1 = 1 :=
by use ⟨1, 42⟩
example : Σ x y : ℤ, (ℤ × ℤ) × ℤ :=
by use [1, 2, 3, 4, 5]
inductive foo
| mk : ℕ → bool × ℕ → ℕ → foo
example : foo :=
by use [100, tt, 4, 3]
-/
meta def use (l : parse pexpr_list_or_texpr) : tactic unit :=
tactic.use l >> try triv
/--
`clear_aux_decl` clears every `aux_decl` in the local context for the current goal.
This includes the induction hypothesis when using the equation compiler and
`_let_match` and `_fun_match`.
It is useful when using a tactic such as `finish`, `simp *` or `subst` that may use these
auxiliary declarations, and produce an error saying the recursion is not well founded.
-/
meta def clear_aux_decl : tactic unit := tactic.clear_aux_decl
/--
`set a := t with h` is a variant of `let a := t` that adds the hypothesis `h : a = t` to the local context.
`set a := t with h⁻¹` will add `h : t = a` instead.
`set! a := t with h` will try to replace `t` with `a` in the goal and all hypotheses.
-/
meta def set (h_simp : parse (tk "!")?) (a : parse ident) (_ : parse (tk ":=")) (v : parse texpr)
(h : parse (tk "with" >> ident)) (h_symm : parse (tk "⁻¹")?) :=
do e ← i_to_expr v, tactic.set a h e h_simp.is_some h_symm.is_some
end interactive
end tactic
|
897bd11909cfa30ef1230dae56c32dd7045ace78 | 618003631150032a5676f229d13a079ac875ff77 | /src/category_theory/concrete_category/unbundled_hom.lean | b3c8a315cf23de892a1f1358a6e673ae4b93a6e4 | [
"Apache-2.0"
] | permissive | awainverse/mathlib | 939b68c8486df66cfda64d327ad3d9165248c777 | ea76bd8f3ca0a8bf0a166a06a475b10663dec44a | refs/heads/master | 1,659,592,962,036 | 1,590,987,592,000 | 1,590,987,592,000 | 268,436,019 | 1 | 0 | Apache-2.0 | 1,590,990,500,000 | 1,590,990,500,000 | null | UTF-8 | Lean | false | false | 2,191 | lean | /-
Copyright (c) 2019 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov
-/
import category_theory.concrete_category.bundled_hom
/-!
# Category instances for structures that use unbundled homs
This file provides basic infrastructure to define concrete
categories using unbundled homs (see `class unbundled_hom`), and
define forgetful functors between them (see
`unbundled_hom.mk_has_forget₂`).
-/
universes v u
namespace category_theory
/-- A class for unbundled homs used to define a category. `hom` must
take two types `α`, `β` and instances of the corresponding structures,
and return a predicate on `α → β`. -/
class unbundled_hom {c : Type u → Type u} (hom : Π {α β}, c α → c β → (α → β) → Prop) :=
(hom_id [] : ∀ {α} (ia : c α), hom ia ia id)
(hom_comp [] : ∀ {α β γ} {Iα : c α} {Iβ : c β} {Iγ : c γ} {g : β → γ} {f : α → β}
(hg : hom Iβ Iγ g) (hf : hom Iα Iβ f), hom Iα Iγ (g ∘ f))
namespace unbundled_hom
variables (c : Type u → Type u) (hom : Π ⦃α β⦄, c α → c β → (α → β) → Prop) [𝒞 : unbundled_hom hom]
include 𝒞
instance bundled_hom : bundled_hom (λ α β (Iα : c α) (Iβ : c β), subtype (hom Iα Iβ)) :=
{ to_fun := λ _ _ _ _, subtype.val,
id := λ α Iα, ⟨id, hom_id hom Iα⟩,
id_to_fun := by intros; refl,
comp := λ _ _ _ _ _ _ g f, ⟨g.1 ∘ f.1, hom_comp c g.2 f.2⟩,
comp_to_fun := by intros; refl,
hom_ext := by intros; apply subtype.eq }
section has_forget₂
variables {c hom} {c' : Type u → Type u} {hom' : Π ⦃α β⦄, c' α → c' β → (α → β) → Prop}
[𝒞' : unbundled_hom hom']
include 𝒞'
variables (obj : Π ⦃α⦄, c α → c' α)
(map : ∀ ⦃α β Iα Iβ f⦄, @hom α β Iα Iβ f → hom' (obj Iα) (obj Iβ) f)
/-- A custom constructor for forgetful functor between concrete categories defined using `unbundled_hom`. -/
def mk_has_forget₂ : has_forget₂ (bundled c) (bundled c') :=
bundled_hom.mk_has_forget₂ obj (λ X Y f, ⟨f.val, map f.property⟩) (λ _ _ _, rfl)
end has_forget₂
end unbundled_hom
end category_theory
|
29dc7dc2c780fd049c038ffcf5a2ce611227840f | d1a52c3f208fa42c41df8278c3d280f075eb020c | /tests/lean/run/etaStruct.lean | 051033751527ccc15cef2f41604ecd850cc8a9be | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | cipher1024/lean4 | 6e1f98bb58e7a92b28f5364eb38a14c8d0aae393 | 69114d3b50806264ef35b57394391c3e738a9822 | refs/heads/master | 1,642,227,983,603 | 1,642,011,696,000 | 1,642,011,696,000 | 228,607,691 | 0 | 0 | Apache-2.0 | 1,576,584,269,000 | 1,576,584,268,000 | null | UTF-8 | Lean | false | false | 1,977 | lean | example (x : α × β) : x = (x.1, x.2) :=
rfl -- Should work with eta for structures
example (x : Unit) : x = ⟨⟩ :=
rfl -- Should work with eta for structures
structure Equiv (α : Sort u) (β : Sort v) where
toFun : α → β
invFun : β → α
left_inv : ∀ x, invFun (toFun x) = x
right_inv : ∀ x, toFun (invFun x) = x
infix:50 "≃" => Equiv
def Equiv.symm (e : α ≃ β) : β ≃ α :=
{ toFun := e.invFun
invFun := e.toFun
left_inv := e.right_inv
right_inv := e.left_inv }
theorem Equiv.symm.symm (e : α ≃ β) : e.symm.symm = e :=
rfl -- Should work with eta for structures
structure Bla where
x : Nat
def Bla.toNat (b : Bla) : Nat := b.x
def Nat.toBla (x : Nat) : Bla := { x }
example (b : Bla) : b.toNat.toBla = b :=
rfl -- Should work with eta for structures
example (b : Bla) : b.toNat.toBla = b := by
cases b
rfl
example (x : Unit × α) : x = ((), x.2) := rfl
example (x : (_ : True ∨ False) ×' α) : x = ⟨Or.inl ⟨⟩, x.2⟩ := rfl
example (p : α × α → Prop) (h : ∀ x y, p (x, y)) : p z := h z.1 _
class TopologicalSpace (α : Type)
structure Homeomorph (α β : Type) [TopologicalSpace α] [TopologicalSpace β] extends Equiv α β where
continuousToFun : True
continuousInv : True
def Homeomorph.symm [TopologicalSpace α] [TopologicalSpace β] (f : Homeomorph α β) : Homeomorph β α where
toFun := f.invFun
invFun := f.toFun
left_inv := sorry
right_inv := sorry
continuousToFun := f.continuousInv
continuousInv := sorry
example [TopologicalSpace α] [TopologicalSpace β] (f : Homeomorph α β) :
f.symm.symm = f := rfl -- fails
def frob : Nat × Nat → Nat × Nat
| (x, y) => (x + y, 42)
example (x : Nat × Nat) : (frob x).2 = 42 := rfl
example (x y : Unit) : x = y := rfl
constant f : Nat → Unit
constant g : Nat → Unit
example (x y : Nat) : f x = f y := rfl
example (x y : Nat) : f x = g y := rfl
|
f12ca373dbdedfe73df3a22a9910aa484e30ae34 | 9dd3f3912f7321eb58ee9aa8f21778ad6221f87c | /library/tools/super/prover.lean | 64f82a7a4e25d6702a99b37ef8619a2646fc0e14 | [
"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 | 3,678 | lean | /-
Copyright (c) 2016 Gabriel Ebner. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Gabriel Ebner
-/
import .clause .prover_state
import .misc_preprocessing
import .selection
import .trim
-- default inferences
-- 0
import .clausifier
-- 10
import .demod
import .inhabited
import .datatypes
-- 20
import .subsumption
-- 30
import .splitting
-- 40
import .factoring
import .resolution
import .superposition
import .equality
import .simp
import .defs
open monad tactic expr
declare_trace super
namespace super
meta def trace_clauses : prover unit :=
do state ← state_t.read, trace state
meta def run_prover_loop
(literal_selection : selection_strategy)
(clause_selection : clause_selection_strategy)
(preprocessing_rules : list (prover unit))
(inference_rules : list inference)
: ℕ → prover (option expr) | i := do
sequence' preprocessing_rules,
new ← take_newly_derived, for' new register_as_passive,
when (is_trace_enabled_for `super) $ for' new $ λn,
tactic.trace { n with c := { (n^.c) with proof := const (mk_simple_name "derived") [] } },
needs_sat_run ← flip monad.lift state_t.read (λst, st^.needs_sat_run),
if needs_sat_run then do
res ← do_sat_run,
match res with
| some proof := return (some proof)
| none := do
model ← flip monad.lift state_t.read (λst, st^.current_model),
when (is_trace_enabled_for `super) (do
pp_model ← pp (model^.to_list^.for (λlit, if lit.2 = tt then lit.1 else not_ lit.1)),
trace $ to_fmt "sat model: " ++ pp_model),
run_prover_loop i
end
else do
passive ← get_passive,
if rb_map.size passive = 0 then return none else do
given_name ← clause_selection i,
given ← option.to_monad (rb_map.find passive given_name),
-- trace_clauses,
remove_passive given_name,
given ← literal_selection given,
when (is_trace_enabled_for `super) (do
fmt ← pp given, trace (to_fmt "given: " ++ fmt)),
add_active given,
seq_inferences inference_rules given,
run_prover_loop (i+1)
meta def default_preprocessing : list (prover unit) :=
[
clausify_pre,
clause_normalize_pre,
factor_dup_lits_pre,
remove_duplicates_pre,
refl_r_pre,
diff_constr_eq_l_pre,
tautology_removal_pre,
subsumption_interreduction_pre,
forward_subsumption_pre,
return ()
]
end super
open super
meta def super (sos_lemmas : list expr) : tactic unit := with_trim $ do
as_refutation, local_false ← target,
clauses ← clauses_of_context,
sos_clauses ← monad.for sos_lemmas (clause.of_proof local_false),
initial_state ← prover_state.initial local_false (clauses ++ sos_clauses),
inf_names ← attribute.get_instances `super.inf,
infs ← for inf_names $ λn, eval_expr inf_decl (const n []),
infs ← return $ list.map inf_decl.inf $ list.sort_on inf_decl.prio infs,
res ← run_prover_loop selection21 (age_weight_clause_selection 3 4)
default_preprocessing infs
0 initial_state,
match res with
| (some empty_clause, st) := apply empty_clause
| (none, saturation) := do sat_fmt ← pp saturation,
fail $ to_fmt "saturation:" ++ format.line ++ sat_fmt
end
namespace tactic.interactive
open lean.parser
open interactive
open interactive.types
meta def with_lemmas (ls : parse $ many ident) : tactic unit := monad.for' ls $ λl, do
p ← mk_const l,
t ← infer_type p,
n ← get_unused_name p^.get_app_fn^.const_name none,
tactic.assertv n t p
meta def super (extra_clause_names : parse $ many ident)
(extra_lemma_names : parse with_ident_list) : tactic unit := do
with_lemmas extra_clause_names,
extra_lemmas ← monad.for extra_lemma_names mk_const,
_root_.super extra_lemmas
end tactic.interactive
|
47e4a0df0d0a859d1d12cc8fc54d40dc8e625093 | 491068d2ad28831e7dade8d6dff871c3e49d9431 | /hott/types/pi.hlean | 217c024287e4e0904360af401a3df08e7b43835f | [
"Apache-2.0"
] | permissive | davidmueller13/lean | 65a3ed141b4088cd0a268e4de80eb6778b21a0e9 | c626e2e3c6f3771e07c32e82ee5b9e030de5b050 | refs/heads/master | 1,611,278,313,401 | 1,444,021,177,000 | 1,444,021,177,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 10,880 | hlean | /-
Copyright (c) 2014-15 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Floris van Doorn
Partially ported from Coq HoTT
Theorems about pi-types (dependent function spaces)
-/
import types.sigma arity
open eq equiv is_equiv funext sigma unit bool is_trunc prod
namespace pi
variables {A A' : Type} {B : A → Type} {B' : A' → Type} {C : Πa, B a → Type}
{D : Πa b, C a b → Type}
{a a' a'' : A} {b b₁ b₂ : B a} {b' : B a'} {b'' : B a''} {f g : Πa, B a}
/- Paths -/
/-
Paths [p : f ≈ g] in a function type [Πx:X, P x] are equivalent to functions taking values
in path types, [H : Πx:X, f x ≈ g x], or concisely, [H : f ~ g].
This equivalence, however, is just the combination of [apd10] and function extensionality
[funext], and as such, [eq_of_homotopy]
Now we show how these things compute.
-/
definition apd10_eq_of_homotopy (h : f ~ g) : apd10 (eq_of_homotopy h) ~ h :=
apd10 (right_inv apd10 h)
definition eq_of_homotopy_eta (p : f = g) : eq_of_homotopy (apd10 p) = p :=
left_inv apd10 p
definition eq_of_homotopy_idp (f : Πa, B a) : eq_of_homotopy (λx : A, refl (f x)) = refl f :=
!eq_of_homotopy_eta
/-
The identification of the path space of a dependent function space,
up to equivalence, is of course just funext.
-/
definition eq_equiv_homotopy (f g : Πx, B x) : (f = g) ≃ (f ~ g) :=
equiv.mk apd10 _
definition pi_eq_equiv (f g : Πx, B x) : (f = g) ≃ (f ~ g) := !eq_equiv_homotopy
definition is_equiv_eq_of_homotopy (f g : Πx, B x)
: is_equiv (eq_of_homotopy : f ~ g → f = g) :=
_
definition homotopy_equiv_eq (f g : Πx, B x) : (f ~ g) ≃ (f = g) :=
equiv.mk eq_of_homotopy _
/- Transport -/
definition pi_transport (p : a = a') (f : Π(b : B a), C a b)
: (transport (λa, Π(b : B a), C a b) p f) ~ (λb, !tr_inv_tr ▸ (p ▸D (f (p⁻¹ ▸ b)))) :=
by induction p; reflexivity
/- A special case of [transport_pi] where the type [B] does not depend on [A],
and so it is just a fixed type [B]. -/
definition pi_transport_constant {C : A → A' → Type} (p : a = a') (f : Π(b : A'), C a b) (b : A')
: (transport _ p f) b = p ▸ (f b) :=
by induction p; reflexivity
/- Pathovers -/
definition pi_pathover {f : Πb, C a b} {g : Πb', C a' b'} {p : a = a'}
(r : Π(b : B a) (b' : B a') (q : b =[p] b'), f b =[apo011 C p q] g b') : f =[p] g :=
begin
cases p, apply pathover_idp_of_eq,
apply eq_of_homotopy, intro b,
apply eq_of_pathover_idp, apply r
end
-- a version where C is uncurried, but where the conclusion of r is still a proper pathover
-- instead of a heterogenous equality
definition pi_pathover' {C : (Σa, B a) → Type} {f : Πb, C ⟨a, b⟩} {g : Πb', C ⟨a', b'⟩}
{p : a = a'} (r : Π(b : B a) (b' : B a') (q : b =[p] b'), f b =[dpair_eq_dpair p q] g b')
: f =[p] g :=
begin
cases p, apply pathover_idp_of_eq,
apply eq_of_homotopy, intro b,
apply (@eq_of_pathover_idp _ C), exact (r b b (pathover.idpatho b)),
end
definition pi_pathover_left {f : Πb, C a b} {g : Πb', C a' b'} {p : a = a'}
(r : Π(b : B a), f b =[apo011 C p !pathover_tr] g (p ▸ b)) : f =[p] g :=
begin
cases p, apply pathover_idp_of_eq,
apply eq_of_homotopy, intro b,
apply eq_of_pathover_idp, apply r
end
definition pi_pathover_right {f : Πb, C a b} {g : Πb', C a' b'} {p : a = a'}
(r : Π(b' : B a'), f (p⁻¹ ▸ b') =[apo011 C p !tr_pathover] g b') : f =[p] g :=
begin
cases p, apply pathover_idp_of_eq,
apply eq_of_homotopy, intro b,
apply eq_of_pathover_idp, apply r
end
definition pi_pathover_constant {C : A → A' → Type} {f : Π(b : A'), C a b}
{g : Π(b : A'), C a' b} {p : a = a'}
(r : Π(b : A'), f b =[p] g b) : f =[p] g :=
begin
cases p, apply pathover_idp_of_eq,
apply eq_of_homotopy, intro b,
exact eq_of_pathover_idp (r b),
end
/- Maps on paths -/
/- The action of maps given by lambda. -/
definition ap_lambdaD {C : A' → Type} (p : a = a') (f : Πa b, C b) :
ap (λa b, f a b) p = eq_of_homotopy (λb, ap (λa, f a b) p) :=
begin
apply (eq.rec_on p),
apply inverse,
apply eq_of_homotopy_idp
end
/- Dependent paths -/
/- with more implicit arguments the conclusion of the following theorem is
(Π(b : B a), transportD B C p b (f b) = g (transport B p b)) ≃
(transport (λa, Π(b : B a), C a b) p f = g) -/
definition heq_piD (p : a = a') (f : Π(b : B a), C a b)
(g : Π(b' : B a'), C a' b') : (Π(b : B a), p ▸D (f b) = g (p ▸ b)) ≃ (p ▸ f = g) :=
eq.rec_on p (λg, !homotopy_equiv_eq) g
definition heq_pi {C : A → Type} (p : a = a') (f : Π(b : B a), C a)
(g : Π(b' : B a'), C a') : (Π(b : B a), p ▸ (f b) = g (p ▸ b)) ≃ (p ▸ f = g) :=
eq.rec_on p (λg, !homotopy_equiv_eq) g
section
open sigma sigma.ops
/- more implicit arguments:
(Π(b : B a), transport C (sigma_eq p idp) (f b) = g (p ▸ b)) ≃
(Π(b : B a), transportD B (λ(a : A) (b : B a), C ⟨a, b⟩) p b (f b) = g (transport B p b)) -/
definition heq_pi_sigma {C : (Σa, B a) → Type} (p : a = a')
(f : Π(b : B a), C ⟨a, b⟩) (g : Π(b' : B a'), C ⟨a', b'⟩) :
(Π(b : B a), (sigma_eq p !pathover_tr) ▸ (f b) = g (p ▸ b)) ≃
(Π(b : B a), p ▸D (f b) = g (p ▸ b)) :=
eq.rec_on p (λg, !equiv.refl) g
end
/- Functorial action -/
variables (f0 : A' → A) (f1 : Π(a':A'), B (f0 a') → B' a')
/- The functoriality of [forall] is slightly subtle: it is contravariant in the domain type and covariant in the codomain, but the codomain is dependent on the domain. -/
definition pi_functor [unfold-full] : (Π(a:A), B a) → (Π(a':A'), B' a') := λg a', f1 a' (g (f0 a'))
definition ap_pi_functor {g g' : Π(a:A), B a} (h : g ~ g')
: ap (pi_functor f0 f1) (eq_of_homotopy h)
= eq_of_homotopy (λa':A', (ap (f1 a') (h (f0 a')))) :=
begin
apply (is_equiv_rect (@apd10 A B g g')), intro p, clear h,
cases p,
apply concat,
exact (ap (ap (pi_functor f0 f1)) (eq_of_homotopy_idp g)),
apply symm, apply eq_of_homotopy_idp
end
/- Equivalences -/
definition is_equiv_pi_functor [instance] [constructor] [H0 : is_equiv f0]
[H1 : Πa', is_equiv (f1 a')] : is_equiv (pi_functor f0 f1) :=
begin
apply (adjointify (pi_functor f0 f1) (pi_functor f0⁻¹
(λ(a : A) (b' : B' (f0⁻¹ a)), transport B (right_inv f0 a) ((f1 (f0⁻¹ a))⁻¹ b')))),
begin
intro h, apply eq_of_homotopy, intro a', esimp,
rewrite [adj f0 a',-tr_compose,fn_tr_eq_tr_fn _ f1,right_inv (f1 _)],
apply apd
end,
begin
intro h, apply eq_of_homotopy, intro a, esimp,
rewrite [left_inv (f1 _)],
apply apd
end
end
definition pi_equiv_pi_of_is_equiv [constructor] [H : is_equiv f0]
[H1 : Πa', is_equiv (f1 a')] : (Πa, B a) ≃ (Πa', B' a') :=
equiv.mk (pi_functor f0 f1) _
definition pi_equiv_pi [constructor] (f0 : A' ≃ A) (f1 : Πa', (B (to_fun f0 a') ≃ B' a'))
: (Πa, B a) ≃ (Πa', B' a') :=
pi_equiv_pi_of_is_equiv (to_fun f0) (λa', to_fun (f1 a'))
definition pi_equiv_pi_id [constructor] {P Q : A → Type} (g : Πa, P a ≃ Q a)
: (Πa, P a) ≃ (Πa, Q a) :=
pi_equiv_pi equiv.refl g
/- Equivalence if one of the types is contractible -/
definition pi_equiv_of_is_contr_left [constructor] (B : A → Type) [H : is_contr A]
: (Πa, B a) ≃ B (center A) :=
begin
fapply equiv.MK,
{ intro f, exact f (center A)},
{ intro b a, exact (center_eq a) ▸ b},
{ intro b, rewrite [hprop_eq_of_is_contr (center_eq (center A)) idp]},
{ intro f, apply eq_of_homotopy, intro a, induction (center_eq a),
rewrite [hprop_eq_of_is_contr (center_eq (center A)) idp]}
end
definition pi_equiv_of_is_contr_right [constructor] [H : Πa, is_contr (B a)]
: (Πa, B a) ≃ unit :=
begin
fapply equiv.MK,
{ intro f, exact star},
{ intro u a, exact !center},
{ intro u, induction u, reflexivity},
{ intro f, apply eq_of_homotopy, intro a, apply is_hprop.elim}
end
/- Interaction with other type constructors -/
-- most of these are in the file of the other type constructor
definition pi_empty_left [constructor] (B : empty → Type) : (Πx, B x) ≃ unit :=
begin
fapply equiv.MK,
{ intro f, exact star},
{ intro x y, contradiction},
{ intro x, induction x, reflexivity},
{ intro f, apply eq_of_homotopy, intro y, contradiction},
end
definition pi_unit_left [constructor] (B : unit → Type) : (Πx, B x) ≃ B star :=
!pi_equiv_of_is_contr_left
definition pi_bool_left [constructor] (B : bool → Type) : (Πx, B x) ≃ B ff × B tt :=
begin
fapply equiv.MK,
{ intro f, exact (f ff, f tt)},
{ intro x b, induction x, induction b: assumption},
{ intro x, induction x, reflexivity},
{ intro f, apply eq_of_homotopy, intro b, induction b: reflexivity},
end
/- Truncatedness: any dependent product of n-types is an n-type -/
theorem is_trunc_pi (B : A → Type) (n : trunc_index)
[H : ∀a, is_trunc n (B a)] : is_trunc n (Πa, B a) :=
begin
revert B H,
eapply (trunc_index.rec_on n),
{intro B H,
fapply is_contr.mk,
intro a, apply center,
intro f, apply eq_of_homotopy,
intro x, apply (center_eq (f x))},
{intro n IH B H,
fapply is_trunc_succ_intro, intro f g,
fapply is_trunc_equiv_closed,
apply equiv.symm, apply eq_equiv_homotopy,
apply IH,
intro a,
show is_trunc n (f a = g a), from
is_trunc_eq n (f a) (g a)}
end
local attribute is_trunc_pi [instance]
theorem is_trunc_pi_eq [instance] [priority 500] (n : trunc_index) (f g : Πa, B a)
[H : ∀a, is_trunc n (f a = g a)] : is_trunc n (f = g) :=
begin
apply is_trunc_equiv_closed_rev,
apply eq_equiv_homotopy
end
theorem is_trunc_not [instance] (n : trunc_index) (A : Type) : is_trunc (n.+1) ¬A :=
by unfold not;exact _
theorem is_hprop_pi_eq [instance] [priority 490] (a : A) : is_hprop (Π(a' : A), a = a') :=
is_hprop_of_imp_is_contr
( assume (f : Πa', a = a'),
assert H : is_contr A, from is_contr.mk a f,
_)
theorem is_hprop_neg (A : Type) : is_hprop (¬A) := _
/- Symmetry of Π -/
definition is_equiv_flip [instance] {P : A → A' → Type}
: is_equiv (@function.flip A A' P) :=
begin
fapply is_equiv.mk,
exact (@function.flip _ _ (function.flip P)),
repeat (intro f; apply idp)
end
definition pi_comm_equiv {P : A → A' → Type} : (Πa b, P a b) ≃ (Πb a, P a b) :=
equiv.mk (@function.flip _ _ P) _
end pi
attribute pi.is_trunc_pi [instance] [priority 1520]
|
c747b86f7eb7bafeae5f36c71dd07c6b44f57ca3 | 92b1c7f0343a6a5cd36bc0f623a7490da3f1e0f3 | /src/stump/setup_properties.lean | 36aa1dad4c595b6aa4b42adca8c0ffde93d4e779 | [
"Apache-2.0"
] | permissive | jtristan/stump-learnable | 717453eb590af16e60c7d3806cc9e66492fab091 | aa3c089f41602efa08d31ef6b41e549456186d57 | refs/heads/master | 1,625,630,634,360 | 1,607,552,106,000 | 1,607,552,106,000 | 218,629,406 | 15 | 2 | null | null | null | null | UTF-8 | Lean | false | false | 2,976 | lean | /-
Copyright © 2019, Oracle and/or its affiliates. All rights reserved.
-/
import .setup_definition
import ..lib.util
open set
open measure_theory
open probability_measure
local attribute [instance] classical.prop_decidable
namespace stump
variables (μ: probability_measure ℍ) (target: ℍ)
lemma label_correct:
∀ x, (label target x).snd = tt ↔ x ≤ target :=
begin
intros,
split; intro,
{
unfold label at a,
simp at a,
unfold rle at a,
tidy,
},
{
unfold label,
simp,
unfold rle,
tidy,
}
end
lemma error_interval_1:
∀ h, h ≤ target → error μ target h = μ (Ioc h target) :=
begin
intros,
unfold error,
have SETEQ: error_set h target = Ioc h target,
{
unfold error_set,
unfold Ioc,
unfold label,
unfold rle,
rw ext_iff,
intro,
simp at *,
split; intro,
{
rw not_eq_prop at a_1,
cases a_1; simp at a_1; cases a_1,
{
finish,
},
{
split,
{
exact lt_of_le_of_lt a a_1_right
},
{
transitivity h; assumption,
},
},
},
{
cases a_1,
finish,
},
},
exact congr_arg μ SETEQ,
end
lemma error_interval_2:
∀ h, h > target → error μ target h = μ (Ioc target h) :=
begin
intros,
unfold error,
have SETEQ: error_set h target = Ioc target h,
{
unfold error_set,
unfold Ioc,
unfold label,
unfold rle,
rw ext_iff,
intro,
simp at *,
split; intro,
{
rw not_eq_prop at a_1,
cases a_1; simp at a_1; cases a_1,
{
split,
{
by_contradiction,
have FOO: target < x,
{
transitivity h; try {assumption},
},
contradiction,
},
{
transitivity target; try {assumption},
have FOO: target < h,
{
exact mem_Ioi.mp a,
},
exact le_of_lt a,
},
},
{
split,
{
exact mem_Ioi.mp a_1_right,
},
{
assumption,
},
},
},
{
cases a_1,
finish,
},
},
exact congr_arg μ SETEQ,
end
lemma error_mono:
∀ c₁, ∀ c₂,
c₁ ≤ c₂ →
c₂ ≤ target →
error μ target c₂ ≤ error μ target c₁ :=
begin
intros,
rw error_interval_1,
rw error_interval_1,
apply probability_measure.prob_mono,
exact Ioc_subset_Ioc_left a,
transitivity c₂; assumption,
assumption,
end
lemma error_mono_interval:
∀ c₁, ∀ c₂,
c₁ ≤ c₂ →
c₂ ≤ target →
μ (Ioc c₂ target) ≤ μ (Ioc c₁ target) :=
begin
intros,
rw ← error_interval_1; try {assumption},
rw ← error_interval_1,
apply error_mono; try {assumption},
transitivity c₂; try {assumption},
end
lemma error_max:
error μ target 0 = μ (Ioc 0 target) :=
begin
apply error_interval_1,
tidy,
end
end stump |
ab12db27237c3acd7816f5204f307d5e51f12a02 | 75db7e3219bba2fbf41bf5b905f34fcb3c6ca3f2 | /library/data/set/basic.lean | 5e536c3d8c1fd1e477a4cf6e6a87befc5d2f035e | [
"Apache-2.0"
] | permissive | jroesch/lean | 30ef0860fa905d35b9ad6f76de1a4f65c9af6871 | 3de4ec1a6ce9a960feb2a48eeea8b53246fa34f2 | refs/heads/master | 1,586,090,835,348 | 1,455,142,203,000 | 1,455,142,277,000 | 51,536,958 | 1 | 0 | null | 1,455,215,811,000 | 1,455,215,811,000 | null | UTF-8 | Lean | false | false | 30,768 | lean | /-
Copyright (c) 2014 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Jeremy Avigad, Leonardo de Moura
-/
import logic.connectives logic.identities algebra.binary
open eq.ops binary function
definition set (X : Type) := X → Prop
namespace set
variable {X : Type}
/- membership and subset -/
definition mem (x : X) (a : set X) := a x
infix ∈ := mem
notation a ∉ b := ¬ mem a b
theorem ext {a b : set X} (H : ∀x, x ∈ a ↔ x ∈ b) : a = b :=
funext (take x, propext (H x))
definition subset (a b : set X) := ∀⦃x⦄, x ∈ a → x ∈ b
infix ⊆ := subset
definition superset (s t : set X) : Prop := t ⊆ s
infix ⊇ := superset
theorem subset.refl (a : set X) : a ⊆ a := take x, assume H, H
theorem subset.trans {a b c : set X} (subab : a ⊆ b) (subbc : b ⊆ c) : a ⊆ c :=
take x, assume ax, subbc (subab ax)
theorem subset.antisymm {a b : set X} (h₁ : a ⊆ b) (h₂ : b ⊆ a) : a = b :=
ext (λ x, iff.intro (λ ina, h₁ ina) (λ inb, h₂ inb))
-- an alterantive name
theorem eq_of_subset_of_subset {a b : set X} (h₁ : a ⊆ b) (h₂ : b ⊆ a) : a = b :=
subset.antisymm h₁ h₂
theorem mem_of_subset_of_mem {s₁ s₂ : set X} {a : X} : s₁ ⊆ s₂ → a ∈ s₁ → a ∈ s₂ :=
assume h₁ h₂, h₁ _ h₂
/- strict subset -/
definition strict_subset (a b : set X) := a ⊆ b ∧ a ≠ b
infix ` ⊂ `:50 := strict_subset
theorem strict_subset.irrefl (a : set X) : ¬ a ⊂ a :=
assume h, absurd rfl (and.elim_right h)
/- bounded quantification -/
abbreviation bounded_forall (a : set X) (P : X → Prop) := ∀⦃x⦄, x ∈ a → P x
notation `forallb` binders `∈` a `, ` r:(scoped:1 P, P) := bounded_forall a r
notation `∀₀` binders `∈` a `, ` r:(scoped:1 P, P) := bounded_forall a r
abbreviation bounded_exists (a : set X) (P : X → Prop) := ∃⦃x⦄, x ∈ a ∧ P x
notation `existsb` binders `∈` a `, ` r:(scoped:1 P, P) := bounded_exists a r
notation `∃₀` binders `∈` a `, ` r:(scoped:1 P, P) := bounded_exists a r
theorem bounded_exists.intro {P : X → Prop} {s : set X} {x : X} (xs : x ∈ s) (Px : P x) :
∃₀ x ∈ s, P x :=
exists.intro x (and.intro xs Px)
lemma bounded_forall_congr {A : Type} {S : set A} {P Q : A → Prop} (H : ∀₀ x∈S, P x ↔ Q x) :
(∀₀ x ∈ S, P x) = (∀₀ x ∈ S, Q x) :=
begin
apply propext,
apply forall_congr,
intros x,
apply imp_congr_right,
apply H
end
lemma bounded_exists_congr {A : Type} {S : set A} {P Q : A → Prop} (H : ∀₀ x∈S, P x ↔ Q x) :
(∃₀ x ∈ S, P x) = (∃₀ x ∈ S, Q x) :=
begin
apply propext,
apply exists_congr,
intros x,
apply and_congr_right,
apply H
end
section
open classical
lemma not_bounded_exists {A : Type} {S : set A} {P : A → Prop} :
(¬ (∃₀ x ∈ S, P x)) = (∀₀ x ∈ S, ¬ P x) :=
begin
rewrite forall_iff_not_exists,
apply propext,
apply forall_congr,
intro x,
rewrite not_and_iff_not_or_not,
rewrite imp_iff_not_or
end
lemma not_bounded_forall {A : Type} {S : set A} {P : A → Prop} :
(¬ (∀₀ x ∈ S, P x)) = (∃₀ x ∈ S, ¬ P x) :=
calc (¬ (∀₀ x ∈ S, P x)) = ¬ ¬ (∃₀ x ∈ S, ¬ P x) :
begin
rewrite not_bounded_exists,
apply (congr_arg not),
apply bounded_forall_congr,
intros x H,
rewrite not_not_iff
end
... = (∃₀ x ∈ S, ¬ P x) : by (rewrite not_not_iff)
end
/- empty set -/
definition empty : set X := λx, false
notation `∅` := empty
theorem not_mem_empty (x : X) : ¬ (x ∈ ∅) :=
assume H : x ∈ ∅, H
theorem mem_empty_eq (x : X) : x ∈ ∅ = false := rfl
theorem eq_empty_of_forall_not_mem {s : set X} (H : ∀ x, x ∉ s) : s = ∅ :=
ext (take x, iff.intro
(assume xs, absurd xs (H x))
(assume xe, absurd xe !not_mem_empty))
section
open classical
theorem exists_mem_of_ne_empty {s : set X} (H : s ≠ ∅) : ∃ x, x ∈ s :=
by_contradiction (assume H', H (eq_empty_of_forall_not_mem (forall_not_of_not_exists H')))
end
theorem empty_subset (s : set X) : ∅ ⊆ s :=
take x, assume H, false.elim H
theorem eq_empty_of_subset_empty {s : set X} (H : s ⊆ ∅) : s = ∅ :=
subset.antisymm H (empty_subset s)
theorem subset_empty_iff (s : set X) : s ⊆ ∅ ↔ s = ∅ :=
iff.intro eq_empty_of_subset_empty (take xeq, by rewrite xeq; apply subset.refl ∅)
lemma bounded_forall_empty_iff {P : X → Prop} :
(∀₀x∈∅, P x) ↔ true :=
iff.intro (take H, true.intro) (take H, by contradiction)
/- universal set -/
definition univ : set X := λx, true
theorem mem_univ (x : X) : x ∈ univ := trivial
theorem mem_univ_iff (x : X) : x ∈ univ ↔ true := !iff.refl
theorem mem_univ_eq (x : X) : x ∈ univ = true := rfl
theorem empty_ne_univ [h : inhabited X] : (empty : set X) ≠ univ :=
assume H : empty = univ,
absurd (mem_univ (inhabited.value h)) (eq.rec_on H (not_mem_empty _))
theorem subset_univ (s : set X) : s ⊆ univ := λ x H, trivial
theorem eq_univ_of_univ_subset {s : set X} (H : univ ⊆ s) : s = univ :=
eq_of_subset_of_subset (subset_univ s) H
theorem eq_univ_of_forall {s : set X} (H : ∀ x, x ∈ s) : s = univ :=
ext (take x, iff.intro (assume H', trivial) (assume H', H x))
/- union -/
definition union (a b : set X) : set X := λx, x ∈ a ∨ x ∈ b
notation a ∪ b := union a b
theorem mem_union_left {x : X} {a : set X} (b : set X) : x ∈ a → x ∈ a ∪ b :=
assume h, or.inl h
theorem mem_union_right {x : X} {b : set X} (a : set X) : x ∈ b → x ∈ a ∪ b :=
assume h, or.inr h
theorem mem_unionl {x : X} {a b : set X} : x ∈ a → x ∈ a ∪ b :=
assume h, or.inl h
theorem mem_unionr {x : X} {a b : set X} : x ∈ b → x ∈ a ∪ b :=
assume h, or.inr h
theorem mem_or_mem_of_mem_union {x : X} {a b : set X} (H : x ∈ a ∪ b) : x ∈ a ∨ x ∈ b := H
theorem mem_union.elim {x : X} {a b : set X} {P : Prop}
(H₁ : x ∈ a ∪ b) (H₂ : x ∈ a → P) (H₃ : x ∈ b → P) : P :=
or.elim H₁ H₂ H₃
theorem mem_union_iff (x : X) (a b : set X) : x ∈ a ∪ b ↔ x ∈ a ∨ x ∈ b := !iff.refl
theorem mem_union_eq (x : X) (a b : set X) : x ∈ a ∪ b = (x ∈ a ∨ x ∈ b) := rfl
theorem union_self (a : set X) : a ∪ a = a :=
ext (take x, !or_self)
theorem union_empty (a : set X) : a ∪ ∅ = a :=
ext (take x, !or_false)
theorem empty_union (a : set X) : ∅ ∪ a = a :=
ext (take x, !false_or)
theorem union_comm (a b : set X) : a ∪ b = b ∪ a :=
ext (take x, or.comm)
theorem union_assoc (a b c : set X) : (a ∪ b) ∪ c = a ∪ (b ∪ c) :=
ext (take x, or.assoc)
theorem union_left_comm (s₁ s₂ s₃ : set X) : s₁ ∪ (s₂ ∪ s₃) = s₂ ∪ (s₁ ∪ s₃) :=
!left_comm union_comm union_assoc s₁ s₂ s₃
theorem union_right_comm (s₁ s₂ s₃ : set X) : (s₁ ∪ s₂) ∪ s₃ = (s₁ ∪ s₃) ∪ s₂ :=
!right_comm union_comm union_assoc s₁ s₂ s₃
theorem subset_union_left (s t : set X) : s ⊆ s ∪ t := λ x H, or.inl H
theorem subset_union_right (s t : set X) : t ⊆ s ∪ t := λ x H, or.inr H
theorem union_subset {s t r : set X} (sr : s ⊆ r) (tr : t ⊆ r) : s ∪ t ⊆ r :=
λ x xst, or.elim xst (λ xs, sr xs) (λ xt, tr xt)
/- intersection -/
definition inter (a b : set X) : set X := λx, x ∈ a ∧ x ∈ b
notation a ∩ b := inter a b
theorem mem_inter_iff (x : X) (a b : set X) : x ∈ a ∩ b ↔ x ∈ a ∧ x ∈ b := !iff.refl
theorem mem_inter_eq (x : X) (a b : set X) : x ∈ a ∩ b = (x ∈ a ∧ x ∈ b) := rfl
theorem mem_inter {x : X} {a b : set X} (Ha : x ∈ a) (Hb : x ∈ b) : x ∈ a ∩ b :=
and.intro Ha Hb
theorem mem_of_mem_inter_left {x : X} {a b : set X} (H : x ∈ a ∩ b) : x ∈ a :=
and.left H
theorem mem_of_mem_inter_right {x : X} {a b : set X} (H : x ∈ a ∩ b) : x ∈ b :=
and.right H
theorem inter_self (a : set X) : a ∩ a = a :=
ext (take x, !and_self)
theorem inter_empty (a : set X) : a ∩ ∅ = ∅ :=
ext (take x, !and_false)
theorem empty_inter (a : set X) : ∅ ∩ a = ∅ :=
ext (take x, !false_and)
theorem inter_comm (a b : set X) : a ∩ b = b ∩ a :=
ext (take x, !and.comm)
theorem inter_assoc (a b c : set X) : (a ∩ b) ∩ c = a ∩ (b ∩ c) :=
ext (take x, !and.assoc)
theorem inter_left_comm (s₁ s₂ s₃ : set X) : s₁ ∩ (s₂ ∩ s₃) = s₂ ∩ (s₁ ∩ s₃) :=
!left_comm inter_comm inter_assoc s₁ s₂ s₃
theorem inter_right_comm (s₁ s₂ s₃ : set X) : (s₁ ∩ s₂) ∩ s₃ = (s₁ ∩ s₃) ∩ s₂ :=
!right_comm inter_comm inter_assoc s₁ s₂ s₃
theorem inter_univ (a : set X) : a ∩ univ = a :=
ext (take x, !and_true)
theorem univ_inter (a : set X) : univ ∩ a = a :=
ext (take x, !true_and)
theorem inter_subset_left (s t : set X) : s ∩ t ⊆ s := λ x H, and.left H
theorem inter_subset_right (s t : set X) : s ∩ t ⊆ t := λ x H, and.right H
theorem subset_inter {s t r : set X} (rs : r ⊆ s) (rt : r ⊆ t) : r ⊆ s ∩ t :=
λ x xr, and.intro (rs xr) (rt xr)
/- distributivity laws -/
theorem inter_distrib_left (s t u : set X) : s ∩ (t ∪ u) = (s ∩ t) ∪ (s ∩ u) :=
ext (take x, !and.left_distrib)
theorem inter_distrib_right (s t u : set X) : (s ∪ t) ∩ u = (s ∩ u) ∪ (t ∩ u) :=
ext (take x, !and.right_distrib)
theorem union_distrib_left (s t u : set X) : s ∪ (t ∩ u) = (s ∪ t) ∩ (s ∪ u) :=
ext (take x, !or.left_distrib)
theorem union_distrib_right (s t u : set X) : (s ∩ t) ∪ u = (s ∪ u) ∩ (t ∪ u) :=
ext (take x, !or.right_distrib)
/- set-builder notation -/
-- {x : X | P}
definition set_of (P : X → Prop) : set X := P
notation `{` binder ` | ` r:(scoped:1 P, set_of P) `}` := r
-- {x ∈ s | P}
definition sep (P : X → Prop) (s : set X) : set X := λx, x ∈ s ∧ P x
notation `{` binder ` ∈ ` s ` | ` r:(scoped:1 p, sep p s) `}` := r
/- insert -/
definition insert (x : X) (a : set X) : set X := {y : X | y = x ∨ y ∈ a}
-- '{x, y, z}
notation `'{`:max a:(foldr `, ` (x b, insert x b) ∅) `}`:0 := a
theorem subset_insert (x : X) (a : set X) : a ⊆ insert x a :=
take y, assume ys, or.inr ys
theorem mem_insert (x : X) (s : set X) : x ∈ insert x s :=
or.inl rfl
theorem mem_insert_of_mem {x : X} {s : set X} (y : X) : x ∈ s → x ∈ insert y s :=
assume h, or.inr h
theorem eq_or_mem_of_mem_insert {x a : X} {s : set X} : x ∈ insert a s → x = a ∨ x ∈ s :=
assume h, h
theorem mem_of_mem_insert_of_ne {x a : X} {s : set X} (xin : x ∈ insert a s) : x ≠ a → x ∈ s :=
or_resolve_right (eq_or_mem_of_mem_insert xin)
theorem mem_insert_eq (x a : X) (s : set X) : x ∈ insert a s = (x = a ∨ x ∈ s) :=
propext (iff.intro !eq_or_mem_of_mem_insert
(or.rec (λH', (eq.substr H' !mem_insert)) !mem_insert_of_mem))
theorem insert_eq_of_mem {a : X} {s : set X} (H : a ∈ s) : insert a s = s :=
ext (λ x, eq.substr (mem_insert_eq x a s)
(or_iff_right_of_imp (λH1, eq.substr H1 H)))
theorem insert.comm (x y : X) (s : set X) : insert x (insert y s) = insert y (insert x s) :=
ext (take a, by rewrite [*mem_insert_eq, propext !or.left_comm])
-- useful in proofs by induction
theorem forall_of_forall_insert {P : X → Prop} {a : X} {s : set X}
(H : ∀ x, x ∈ insert a s → P x) :
∀ x, x ∈ s → P x :=
λ x xs, H x (!mem_insert_of_mem xs)
lemma bounded_forall_insert_iff {P : X → Prop} {a : X} {s : set X} :
(∀₀x ∈ insert a s, P x) ↔ P a ∧ (∀₀x ∈ s, P x) :=
begin
apply iff.intro, all_goals (intro H),
{ apply and.intro,
{ apply H, apply mem_insert },
{ intro x Hx, apply H, apply mem_insert_of_mem, assumption } },
{ intro x Hx, cases Hx with eq Hx,
{ cases eq, apply (and.elim_left H) },
{ apply (and.elim_right H), assumption } }
end
/- singleton -/
theorem mem_singleton_iff (a b : X) : a ∈ '{b} ↔ a = b :=
iff.intro
(assume ainb, or.elim ainb (λ aeqb, aeqb) (λ f, false.elim f))
(assume aeqb, or.inl aeqb)
theorem mem_singleton (a : X) : a ∈ '{a} := !mem_insert
theorem eq_of_mem_singleton {x y : X} (h : x ∈ '{y}) : x = y :=
or.elim (eq_or_mem_of_mem_insert h)
(suppose x = y, this)
(suppose x ∈ ∅, absurd this !not_mem_empty)
theorem mem_singleton_of_eq {x y : X} (H : x = y) : x ∈ '{y} :=
eq.symm H ▸ mem_singleton y
theorem insert_eq (x : X) (s : set X) : insert x s = '{x} ∪ s :=
ext (take y, iff.intro
(suppose y ∈ insert x s,
or.elim this (suppose y = x, or.inl (or.inl this)) (suppose y ∈ s, or.inr this))
(suppose y ∈ '{x} ∪ s,
or.elim this
(suppose y ∈ '{x}, or.inl (eq_of_mem_singleton this))
(suppose y ∈ s, or.inr this)))
theorem pair_eq_singleton (a : X) : '{a, a} = '{a} :=
by rewrite [insert_eq_of_mem !mem_singleton]
theorem singleton_ne_empty (a : X) : '{a} ≠ ∅ :=
begin
intro H,
apply not_mem_empty a,
rewrite -H,
apply mem_insert
end
/- separation -/
theorem mem_sep {s : set X} {P : X → Prop} {x : X} (xs : x ∈ s) (Px : P x) : x ∈ {x ∈ s | P x} :=
and.intro xs Px
theorem eq_sep_of_subset {s t : set X} (ssubt : s ⊆ t) : s = {x ∈ t | x ∈ s} :=
ext (take x, iff.intro
(suppose x ∈ s, and.intro (ssubt this) this)
(suppose x ∈ {x ∈ t | x ∈ s}, and.right this))
theorem mem_sep_iff {s : set X} {P : X → Prop} {x : X} : x ∈ {x ∈ s | P x} ↔ x ∈ s ∧ P x :=
!iff.refl
theorem sep_subset (s : set X) (P : X → Prop) : {x ∈ s | P x} ⊆ s :=
take x, assume H, and.left H
/- complement -/
definition complement (s : set X) : set X := {x | x ∉ s}
prefix `-` := complement
theorem mem_comp {s : set X} {x : X} (H : x ∉ s) : x ∈ -s := H
theorem not_mem_of_mem_comp {s : set X} {x : X} (H : x ∈ -s) : x ∉ s := H
theorem mem_comp_iff (s : set X) (x : X) : x ∈ -s ↔ x ∉ s := !iff.refl
theorem inter_comp_self (s : set X) : s ∩ -s = ∅ :=
ext (take x, !and_not_self_iff)
theorem comp_inter_self (s : set X) : -s ∩ s = ∅ :=
ext (take x, !not_and_self_iff)
/- some classical identities -/
section
open classical
theorem comp_empty : -(∅ : set X) = univ :=
ext (take x, iff.intro (assume H, trivial) (assume H, not_false))
theorem comp_union (s t : set X) : -(s ∪ t) = -s ∩ -t :=
ext (take x, !not_or_iff_not_and_not)
theorem comp_comp (s : set X) : -(-s) = s :=
ext (take x, !not_not_iff)
theorem comp_inter (s t : set X) : -(s ∩ t) = -s ∪ -t :=
ext (take x, !not_and_iff_not_or_not)
theorem comp_univ : -(univ : set X) = ∅ :=
by rewrite [-comp_empty, comp_comp]
theorem union_eq_comp_comp_inter_comp (s t : set X) : s ∪ t = -(-s ∩ -t) :=
ext (take x, !or_iff_not_and_not)
theorem inter_eq_comp_comp_union_comp (s t : set X) : s ∩ t = -(-s ∪ -t) :=
ext (take x, !and_iff_not_or_not)
theorem union_comp_self (s : set X) : s ∪ -s = univ :=
ext (take x, !or_not_self_iff)
theorem comp_union_self (s : set X) : -s ∪ s = univ :=
ext (take x, !not_or_self_iff)
theorem complement_compose_complement :
#function complement ∘ complement = @id (set X) :=
funext (λ s, comp_comp s)
end
/- set difference -/
definition diff (s t : set X) : set X := {x ∈ s | x ∉ t}
infix `\`:70 := diff
theorem mem_diff {s t : set X} {x : X} (H1 : x ∈ s) (H2 : x ∉ t) : x ∈ s \ t :=
and.intro H1 H2
theorem mem_of_mem_diff {s t : set X} {x : X} (H : x ∈ s \ t) : x ∈ s :=
and.left H
theorem not_mem_of_mem_diff {s t : set X} {x : X} (H : x ∈ s \ t) : x ∉ t :=
and.right H
theorem mem_diff_iff (s t : set X) (x : X) : x ∈ s \ t ↔ x ∈ s ∧ x ∉ t := !iff.refl
theorem mem_diff_eq (s t : set X) (x : X) : x ∈ s \ t = (x ∈ s ∧ x ∉ t) := rfl
theorem diff_eq (s t : set X) : s \ t = s ∩ -t := rfl
theorem union_diff_cancel {s t : set X} [dec : Π x, decidable (x ∈ s)] (H : s ⊆ t) : s ∪ (t \ s) = t :=
ext (take x, iff.intro
(assume H1 : x ∈ s ∪ (t \ s), or.elim H1 (assume H2, !H H2) (assume H2, and.left H2))
(assume H1 : x ∈ t,
decidable.by_cases
(suppose x ∈ s, or.inl this)
(suppose x ∉ s, or.inr (and.intro H1 this))))
theorem diff_subset (s t : set X) : s \ t ⊆ s := inter_subset_left s _
theorem comp_eq_univ_diff (s : set X) : -s = univ \ s :=
ext (take x, iff.intro (assume H, and.intro trivial H) (assume H, and.right H))
/- powerset -/
definition powerset (s : set X) : set (set X) := {x : set X | x ⊆ s}
prefix `𝒫`:100 := powerset
theorem mem_powerset {x s : set X} (H : x ⊆ s) : x ∈ 𝒫 s := H
theorem subset_of_mem_powerset {x s : set X} (H : x ∈ 𝒫 s) : x ⊆ s := H
theorem mem_powerset_iff (x s : set X) : x ∈ 𝒫 s ↔ x ⊆ s := !iff.refl
/- function image -/
section image
variables {Y Z : Type}
abbreviation eq_on (f1 f2 : X → Y) (a : set X) : Prop :=
∀₀ x ∈ a, f1 x = f2 x
definition image (f : X → Y) (a : set X) : set Y := {y : Y | ∃x, x ∈ a ∧ f x = y}
infix `'` := image
theorem image_eq_image_of_eq_on {f1 f2 : X → Y} {a : set X} (H1 : eq_on f1 f2 a) :
f1 ' a = f2 ' a :=
ext (take y, iff.intro
(assume H2,
obtain x (H3 : x ∈ a ∧ f1 x = y), from H2,
have H4 : x ∈ a, from and.left H3,
have H5 : f2 x = y, from (H1 H4)⁻¹ ⬝ and.right H3,
exists.intro x (and.intro H4 H5))
(assume H2,
obtain x (H3 : x ∈ a ∧ f2 x = y), from H2,
have H4 : x ∈ a, from and.left H3,
have H5 : f1 x = y, from (H1 H4) ⬝ and.right H3,
exists.intro x (and.intro H4 H5)))
theorem mem_image {f : X → Y} {a : set X} {x : X} {y : Y}
(H1 : x ∈ a) (H2 : f x = y) : y ∈ f ' a :=
exists.intro x (and.intro H1 H2)
theorem mem_image_of_mem (f : X → Y) {x : X} {a : set X} (H : x ∈ a) : f x ∈ image f a :=
mem_image H rfl
lemma image_compose (f : Y → Z) (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 (Hy₁ : y ∈ g ' a) (Hy₂ : f y = z), from Hz,
obtain x (Hz₁ : x ∈ a) (Hz₂ : g x = y), from Hy₁,
show z ∈ (f ∘ g) ' a, from mem_image Hz₁ (Hz₂⁻¹ ▸ Hy₂)))
lemma image_subset {a b : set X} (f : X → Y) (H : a ⊆ b) : f ' a ⊆ f ' b :=
take y, assume Hy : y ∈ f ' a,
obtain x (Hx₁ : x ∈ a) (Hx₂ : f x = y), from Hy,
mem_image (H Hx₁) Hx₂
theorem image_union (f : X → Y) (s t : set X) :
image f (s ∪ t) = image f s ∪ image f t :=
ext (take y, iff.intro
(assume H : y ∈ image f (s ∪ t),
obtain x [(xst : x ∈ s ∪ t) (fxy : f x = y)], from H,
or.elim xst
(assume xs, or.inl (mem_image xs fxy))
(assume xt, or.inr (mem_image xt fxy)))
(assume H : y ∈ image f s ∪ image f t,
or.elim H
(assume yifs : y ∈ image f s,
obtain x [(xs : x ∈ s) (fxy : f x = y)], from yifs,
mem_image (or.inl xs) fxy)
(assume yift : y ∈ image f t,
obtain x [(xt : x ∈ t) (fxy : f x = y)], from yift,
mem_image (or.inr xt) fxy)))
theorem image_empty (f : X → Y) : image f ∅ = ∅ :=
eq_empty_of_forall_not_mem
(take y, suppose y ∈ image f ∅,
obtain x [(H : x ∈ empty) H'], from this,
H)
theorem mem_image_complement (t : set X) (S : set (set X)) :
t ∈ complement ' S ↔ -t ∈ S :=
iff.intro
(suppose t ∈ complement ' S,
obtain t' [(Ht' : t' ∈ S) (Ht : -t' = t)], from this,
show -t ∈ S, by rewrite [-Ht, comp_comp]; exact Ht')
(suppose -t ∈ S,
have -(-t) ∈ complement 'S, from mem_image_of_mem complement this,
show t ∈ complement 'S, from comp_comp t ▸ this)
theorem image_id (s : set X) : id ' s = s :=
ext (take x, iff.intro
(suppose x ∈ id ' s,
obtain x' [(Hx' : x' ∈ s) (x'eq : x' = x)], from this,
show x ∈ s, by rewrite [-x'eq]; apply Hx')
(suppose x ∈ s, mem_image_of_mem id this))
theorem complement_complement_image (S : set (set X)) :
complement ' (complement ' S) = S :=
by rewrite [-image_compose, complement_compose_complement, image_id]
lemma bounded_forall_image_of_bounded_forall {f : X → Y} {S : set X} {P : Y → Prop}
(H : ∀₀ x ∈ S, P (f x)) : ∀₀ y ∈ f ' S, P y :=
begin
intro x' Hx;
cases Hx with x Hx;
cases Hx with Hx eq;
rewrite (eq⁻¹);
apply H;
assumption
end
lemma bounded_forall_image_iff {f : X → Y} {S : set X} {P : Y → Prop} :
(∀₀ y ∈ f ' S, P y) ↔ (∀₀ x ∈ S, P (f x)) :=
iff.intro (take H x Hx, H _ (!mem_image_of_mem `x ∈ S`)) bounded_forall_image_of_bounded_forall
lemma image_insert_eq {f : X → Y} {a : X} {S : set X} :
f ' insert a S = insert (f a) (f ' S) :=
begin
apply set.ext,
intro x, apply iff.intro, all_goals (intros H),
{ cases H with y Hy, cases Hy with Hy eq, rewrite (eq⁻¹), cases Hy with y_eq,
{ rewrite y_eq, apply mem_insert },
{ apply mem_insert_of_mem, apply mem_image_of_mem, assumption } },
{ cases H with eq Hx,
{ rewrite eq, apply mem_image_of_mem, apply mem_insert },
{ cases Hx with y Hy, cases Hy with Hy eq,
rewrite (eq⁻¹), apply mem_image_of_mem, apply mem_insert_of_mem, assumption } }
end
end image
/- function pre image -/
definition preimage {A B:Type} (f : A → B) (Y : set B) : set A := { x | f x ∈ Y }
lemma image_subset_iff {A B : Type} {f : A → B} {X : set A} {Y : set B} :
f ' X ⊆ Y ↔ X ⊆ preimage f Y :=
@bounded_forall_image_iff A B f X Y
/- collections of disjoint sets -/
definition disjoint_sets (S : set (set X)) : Prop := ∀ a b, a ∈ S → b ∈ S → a ≠ b → a ∩ b = ∅
theorem disjoint_sets_empty : disjoint_sets (∅ : set (set X)) :=
take a b, assume H, !not.elim !not_mem_empty H
theorem disjoint_sets_union {s t : set (set X)} (Hs : disjoint_sets s) (Ht : disjoint_sets t)
(H : ∀ x y, x ∈ s ∧ y ∈ t → x ∩ y = ∅) :
disjoint_sets (s ∪ t) :=
take a b, assume Ha Hb Hneq, or.elim Ha
(assume H1, or.elim Hb
(suppose b ∈ s, (Hs a b) H1 this Hneq)
(suppose b ∈ t, (H a b) (and.intro H1 this)))
(assume H2, or.elim Hb
(suppose b ∈ s, !inter_comm ▸ ((H b a) (and.intro this H2)))
(suppose b ∈ t, (Ht a b) H2 this Hneq))
theorem disjoint_sets_singleton (s : set (set X)) : disjoint_sets '{s} :=
take a b, assume Ha Hb Hneq,
absurd (eq.trans ((iff.elim_left !mem_singleton_iff) Ha) ((iff.elim_left !mem_singleton_iff) Hb)⁻¹)
Hneq
/- large unions -/
section large_unions
variables {I : Type}
variable a : set I
variable b : I → set X
variable C : set (set X)
definition sUnion : set X := {x : X | ∃₀ c ∈ C, x ∈ c}
definition sInter : set X := {x : X | ∀₀ c ∈ C, x ∈ c}
prefix `⋃₀`:110 := sUnion
prefix `⋂₀`:110 := sInter
definition Union : set X := {x : X | ∃i, x ∈ b i}
definition Inter : set X := {x : X | ∀i, x ∈ b i}
notation `⋃` binders `, ` r:(scoped f, Union f) := r
notation `⋂` binders `, ` r:(scoped f, Inter f) := r
definition bUnion : set X := {x : X | ∃₀ i ∈ a, x ∈ b i}
definition bInter : set X := {x : X | ∀₀ i ∈ a, x ∈ b i}
notation `⋃` binders ` ∈ ` s `, ` r:(scoped f, bUnion s f) := r
notation `⋂` binders ` ∈ ` s `, ` r:(scoped f, bInter s f) := r
end large_unions
-- sUnion and sInter: a collection (set) of sets
theorem mem_sUnion {x : X} {t : set X} {S : set (set X)} (Hx : x ∈ t) (Ht : t ∈ S) :
x ∈ ⋃₀ S :=
exists.intro t (and.intro Ht Hx)
theorem mem_sInter {x : X} {t : set X} {S : set (set X)} (H : ∀₀ t ∈ S, x ∈ t) :
x ∈ ⋂₀ S :=
H
theorem sInter_subset_of_mem {S : set (set X)} {t : set X} (tS : t ∈ S) :
(⋂₀ S) ⊆ t :=
take x, assume H, H t tS
theorem subset_sUnion_of_mem {S : set (set X)} {t : set X} (tS : t ∈ S) :
t ⊆ (⋃₀ S) :=
take x, assume H, exists.intro t (and.intro tS H)
theorem sUnion_empty : ⋃₀ ∅ = (∅ : set X) :=
eq_empty_of_forall_not_mem
(take x, suppose x ∈ sUnion ∅,
obtain t [(Ht : t ∈ ∅) Ht'], from this,
show false, from Ht)
theorem sInter_empty : ⋂₀ ∅ = (univ : set X) :=
eq_univ_of_forall (λ x s H, false.elim H)
theorem sUnion_singleton (s : set X) : ⋃₀ '{s} = s :=
ext (take x, iff.intro
(suppose x ∈ sUnion '{s},
obtain u [(Hu : u ∈ '{s}) (xu : x ∈ u)], from this,
have u = s, from eq_of_mem_singleton Hu,
show x ∈ s, using this, by rewrite -this; apply xu)
(suppose x ∈ s,
mem_sUnion this (mem_singleton s)))
theorem sInter_singleton (s : set X) : ⋂₀ '{s} = s :=
ext (take x, iff.intro
(suppose x ∈ ⋂₀ '{s}, show x ∈ s, from this (mem_singleton s))
(suppose x ∈ s, take u, suppose u ∈ '{s},
show x ∈ u, by+ rewrite [eq_of_mem_singleton this]; assumption))
theorem sUnion_union (S T : set (set X)) : ⋃₀ (S ∪ T) = ⋃₀ S ∪ ⋃₀ T :=
ext (take x, iff.intro
(suppose x ∈ sUnion (S ∪ T),
obtain u [(Hu : u ∈ S ∪ T) (xu : x ∈ u)], from this,
or.elim Hu
(assume uS, or.inl (mem_sUnion xu uS))
(assume uT, or.inr (mem_sUnion xu uT)))
(suppose x ∈ sUnion S ∪ sUnion T,
or.elim this
(suppose x ∈ sUnion S,
obtain u [(uS : u ∈ S) (xu : x ∈ u)], from this,
mem_sUnion xu (or.inl uS))
(suppose x ∈ sUnion T,
obtain u [(uT : u ∈ T) (xu : x ∈ u)], from this,
mem_sUnion xu (or.inr uT))))
theorem sInter_union (S T : set (set X)) : ⋂₀ (S ∪ T) = ⋂₀ S ∩ ⋂₀ T :=
ext (take x, iff.intro
(assume H : x ∈ ⋂₀ (S ∪ T),
and.intro (λ u uS, H (or.inl uS)) (λ u uT, H (or.inr uT)))
(assume H : x ∈ ⋂₀ S ∩ ⋂₀ T,
take u, suppose u ∈ S ∪ T, or.elim this (λ uS, and.left H u uS) (λ uT, and.right H u uT)))
theorem sUnion_insert (s : set X) (T : set (set X)) :
⋃₀ (insert s T) = s ∪ ⋃₀ T :=
by rewrite [insert_eq, sUnion_union, sUnion_singleton]
theorem sInter_insert (s : set X) (T : set (set X)) :
⋂₀ (insert s T) = s ∩ ⋂₀ T :=
by rewrite [insert_eq, sInter_union, sInter_singleton]
theorem comp_sUnion (S : set (set X)) :
- ⋃₀ S = ⋂₀ (complement ' S) :=
ext (take x, iff.intro
(assume H : x ∈ -(⋃₀ S),
take t, suppose t ∈ complement ' S,
obtain t' [(Ht' : t' ∈ S) (Ht : -t' = t)], from this,
have x ∈ -t', from suppose x ∈ t', H (mem_sUnion this Ht'),
show x ∈ t, using this, by rewrite -Ht; apply this)
(assume H : x ∈ ⋂₀ (complement ' S),
suppose x ∈ ⋃₀ S,
obtain t [(tS : t ∈ S) (xt : x ∈ t)], from this,
have -t ∈ complement ' S, from mem_image_of_mem complement tS,
have x ∈ -t, from H this,
show false, proof this xt qed))
theorem sUnion_eq_comp_sInter_comp (S : set (set X)) :
⋃₀ S = - ⋂₀ (complement ' S) :=
by rewrite [-comp_comp, comp_sUnion]
theorem comp_sInter (S : set (set X)) :
- ⋂₀ S = ⋃₀ (complement ' S) :=
by rewrite [sUnion_eq_comp_sInter_comp, complement_complement_image]
theorem sInter_eq_comp_sUnion_comp (S : set (set X)) :
⋂₀ S = -(⋃₀ (complement ' S)) :=
by rewrite [-comp_comp, comp_sInter]
-- Union and Inter: a family of sets indexed by a type
theorem Union_subset {I : Type} {b : I → set X} {c : set X} (H : ∀ i, b i ⊆ c) : (⋃ i, b i) ⊆ c :=
take x,
suppose x ∈ Union b,
obtain i (Hi : x ∈ b i), from this,
show x ∈ c, from H i Hi
theorem subset_Inter {I : Type} {b : I → set X} {c : set X} (H : ∀ i, c ⊆ b i) : c ⊆ ⋂ i, b i :=
λ x cx i, H i cx
theorem Union_eq_sUnion_image {X I : Type} (s : I → set X) : (⋃ i, s i) = ⋃₀ (s ' univ) :=
ext (take x, iff.intro
(suppose x ∈ Union s,
obtain i (Hi : x ∈ s i), from this,
mem_sUnion Hi (mem_image_of_mem s trivial))
(suppose x ∈ sUnion (s ' univ),
obtain t [(Ht : t ∈ s ' univ) (Hx : x ∈ t)], from this,
obtain i [univi (Hi : s i = t)], from Ht,
exists.intro i (show x ∈ s i, by rewrite Hi; apply Hx)))
theorem Inter_eq_sInter_image {X I : Type} (s : I → set X) : (⋂ i, s i) = ⋂₀ (s ' univ) :=
ext (take x, iff.intro
(assume H : x ∈ Inter s,
take t,
suppose t ∈ s 'univ,
obtain i [univi (Hi : s i = t)], from this,
show x ∈ t, by rewrite -Hi; exact H i)
(assume H : x ∈ ⋂₀ (s ' univ),
take i,
have s i ∈ s ' univ, from mem_image_of_mem s trivial,
show x ∈ s i, from H this))
theorem comp_Union {X I : Type} (s : I → set X) : - (⋃ i, s i) = (⋂ i, - s i) :=
by rewrite [Union_eq_sUnion_image, comp_sUnion, -image_compose, -Inter_eq_sInter_image]
theorem comp_Inter {X I : Type} (s : I → set X) : -(⋂ i, s i) = (⋃ i, - s i) :=
by rewrite [Inter_eq_sInter_image, comp_sInter, -image_compose, -Union_eq_sUnion_image]
theorem Union_eq_comp_Inter_comp {X I : Type} (s : I → set X) : (⋃ i, s i) = - (⋂ i, - s i) :=
by rewrite [-comp_comp, comp_Union]
theorem Inter_eq_comp_Union_comp {X I : Type} (s : I → set X) : (⋂ i, s i) = - (⋃ i, -s i) :=
by rewrite [-comp_comp, comp_Inter]
-- these are useful for turning binary union / intersection into countable ones
definition bin_ext (s t : set X) (n : ℕ) : set X :=
nat.cases_on n s (λ m, t)
lemma Union_bin_ext (s t : set X) : (⋃ i, bin_ext s t i) = s ∪ t :=
ext (take x, iff.intro
(assume H,
obtain i (Hi : x ∈ (bin_ext s t) i), from H,
by cases i; apply or.inl Hi; apply or.inr Hi)
(assume H,
or.elim H
(suppose x ∈ s, exists.intro 0 this)
(suppose x ∈ t, exists.intro 1 this)))
lemma Inter_bin_ext (s t : set X) : (⋂ i, bin_ext s t i) = s ∩ t :=
ext (take x, iff.intro
(assume H, and.intro (H 0) (H 1))
(assume H, by intro i; cases i;
apply and.elim_left H; apply and.elim_right H))
-- bUnion and bInter: a family of sets indexed by a set ("b" is for bounded)
variable {Y : Type}
theorem mem_bUnion {s : set X} {f : X → set Y} {x : X} {y : Y}
(xs : x ∈ s) (yfx : y ∈ f x) :
y ∈ ⋃ x ∈ s, f x :=
exists.intro x (and.intro xs yfx)
theorem mem_bInter {s : set X} {f : X → set Y} {y : Y} (H : ∀₀ x ∈ s, y ∈ f x) :
y ∈ ⋂ x ∈ s, f x :=
H
theorem bUnion_subset {s : set X} {t : set Y} {f : X → set Y} (H : ∀₀ x ∈ s, f x ⊆ t) :
(⋃ x ∈ s, f x) ⊆ t :=
take y, assume Hy,
obtain x [xs yfx], from Hy,
show y ∈ t, from H xs yfx
theorem subset_bInter {s : set X} {t : set Y} {f : X → set Y} (H : ∀₀ x ∈ s, t ⊆ f x) :
t ⊆ ⋂ x ∈ s, f x :=
take y, assume yt, take x, assume xs, H xs yt
theorem subset_bUnion_of_mem {s : set X} {f : X → set Y} {x : X} (xs : x ∈ s) :
f x ⊆ ⋃ x ∈ s, f x :=
take y, assume Hy, mem_bUnion xs Hy
theorem bInter_subset_of_mem {s : set X} {f : X → set Y} {x : X} (xs : x ∈ s) :
(⋂ x ∈ s, f x) ⊆ f x :=
take y, assume Hy, Hy x xs
end set
|
9d245f1b228f8831d44634d8a7e7525d495e8b29 | c777c32c8e484e195053731103c5e52af26a25d1 | /src/linear_algebra/matrix/hermitian.lean | b4a8e6b46e124827892a514160af2ea946c0d758 | [
"Apache-2.0"
] | permissive | kbuzzard/mathlib | 2ff9e85dfe2a46f4b291927f983afec17e946eb8 | 58537299e922f9c77df76cb613910914a479c1f7 | refs/heads/master | 1,685,313,702,744 | 1,683,974,212,000 | 1,683,974,212,000 | 128,185,277 | 1 | 0 | null | 1,522,920,600,000 | 1,522,920,600,000 | null | UTF-8 | Lean | false | false | 9,446 | lean | /-
Copyright (c) 2022 Alexander Bentkamp. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Alexander Bentkamp
-/
import analysis.inner_product_space.pi_L2
/-! # Hermitian matrices
This file defines hermitian matrices and some basic results about them.
See also `is_self_adjoint`, which generalizes this definition to other star rings.
## Main definition
* `matrix.is_hermitian` : a matrix `A : matrix n n α` is hermitian if `Aᴴ = A`.
## Tags
self-adjoint matrix, hermitian matrix
-/
namespace matrix
variables {α β : Type*} {m n : Type*} {A : matrix n n α}
open_locale matrix
local notation `⟪`x`, `y`⟫` := @inner α _ _ x y
section has_star
variables [has_star α] [has_star β]
/-- A matrix is hermitian if it is equal to its conjugate transpose. On the reals, this definition
captures symmetric matrices. -/
def is_hermitian (A : matrix n n α) : Prop := Aᴴ = A
lemma is_hermitian.eq {A : matrix n n α} (h : A.is_hermitian) : Aᴴ = A := h
protected lemma is_hermitian.is_self_adjoint {A : matrix n n α} (h : A.is_hermitian) :
is_self_adjoint A := h
@[ext]
lemma is_hermitian.ext {A : matrix n n α} : (∀ i j, star (A j i) = A i j) → A.is_hermitian :=
by { intros h, ext i j, exact h i j }
lemma is_hermitian.apply {A : matrix n n α} (h : A.is_hermitian) (i j : n) : star (A j i) = A i j :=
congr_fun (congr_fun h _) _
lemma is_hermitian.ext_iff {A : matrix n n α} : A.is_hermitian ↔ ∀ i j, star (A j i) = A i j :=
⟨is_hermitian.apply, is_hermitian.ext⟩
@[simp] lemma is_hermitian.map {A : matrix n n α} (h : A.is_hermitian) (f : α → β)
(hf : function.semiconj f star star) :
(A.map f).is_hermitian :=
(conj_transpose_map f hf).symm.trans $ h.eq.symm ▸ rfl
lemma is_hermitian.transpose {A : matrix n n α} (h : A.is_hermitian) :
Aᵀ.is_hermitian :=
by { rw [is_hermitian, conj_transpose, transpose_map], congr, exact h }
@[simp] lemma is_hermitian_transpose_iff (A : matrix n n α) :
Aᵀ.is_hermitian ↔ A.is_hermitian :=
⟨by { intro h, rw [← transpose_transpose A], exact is_hermitian.transpose h },
is_hermitian.transpose⟩
lemma is_hermitian.conj_transpose {A : matrix n n α} (h : A.is_hermitian) :
Aᴴ.is_hermitian :=
h.transpose.map _ $ λ _, rfl
@[simp] lemma is_hermitian.submatrix {A : matrix n n α} (h : A.is_hermitian) (f : m → n) :
(A.submatrix f f).is_hermitian :=
(conj_transpose_submatrix _ _ _).trans (h.symm ▸ rfl)
@[simp] lemma is_hermitian_submatrix_equiv {A : matrix n n α} (e : m ≃ n) :
(A.submatrix e e).is_hermitian ↔ A.is_hermitian :=
⟨λ h, by simpa using h.submatrix e.symm, λ h, h.submatrix _⟩
end has_star
section has_involutive_star
variables [has_involutive_star α]
@[simp] lemma is_hermitian_conj_transpose_iff (A : matrix n n α) :
Aᴴ.is_hermitian ↔ A.is_hermitian :=
is_self_adjoint.star_iff
/-- A block matrix `A.from_blocks B C D` is hermitian,
if `A` and `D` are hermitian and `Bᴴ = C`. -/
lemma is_hermitian.from_blocks
{A : matrix m m α} {B : matrix m n α} {C : matrix n m α} {D : matrix n n α}
(hA : A.is_hermitian) (hBC : Bᴴ = C) (hD : D.is_hermitian) :
(A.from_blocks B C D).is_hermitian :=
begin
have hCB : Cᴴ = B,
{ rw [← hBC, conj_transpose_conj_transpose] },
unfold matrix.is_hermitian,
rw from_blocks_conj_transpose,
congr;
assumption
end
/-- This is the `iff` version of `matrix.is_hermitian.from_blocks`. -/
lemma is_hermitian_from_blocks_iff
{A : matrix m m α} {B : matrix m n α} {C : matrix n m α} {D : matrix n n α} :
(A.from_blocks B C D).is_hermitian ↔ A.is_hermitian ∧ Bᴴ = C ∧ Cᴴ = B ∧ D.is_hermitian :=
⟨λ h, ⟨congr_arg to_blocks₁₁ h, congr_arg to_blocks₂₁ h,
congr_arg to_blocks₁₂ h, congr_arg to_blocks₂₂ h⟩,
λ ⟨hA, hBC, hCB, hD⟩, is_hermitian.from_blocks hA hBC hD⟩
end has_involutive_star
section add_monoid
variables [add_monoid α] [star_add_monoid α] [add_monoid β] [star_add_monoid β]
/-- A diagonal matrix is hermitian if the entries are self-adjoint -/
lemma is_hermitian_diagonal_of_self_adjoint [decidable_eq n]
(v : n → α) (h : is_self_adjoint v) :
(diagonal v).is_hermitian :=
-- TODO: add a `pi.has_trivial_star` instance and remove the `funext`
(diagonal_conj_transpose v).trans $ congr_arg _ h
/-- A diagonal matrix is hermitian if the entries have the trivial `star` operation
(such as on the reals). -/
@[simp] lemma is_hermitian_diagonal [has_trivial_star α] [decidable_eq n] (v : n → α) :
(diagonal v).is_hermitian :=
is_hermitian_diagonal_of_self_adjoint _ (is_self_adjoint.all _)
@[simp] lemma is_hermitian_zero :
(0 : matrix n n α).is_hermitian :=
is_self_adjoint_zero _
@[simp] lemma is_hermitian.add {A B : matrix n n α} (hA : A.is_hermitian) (hB : B.is_hermitian) :
(A + B).is_hermitian :=
is_self_adjoint.add hA hB
end add_monoid
section add_comm_monoid
variables [add_comm_monoid α] [star_add_monoid α]
lemma is_hermitian_add_transpose_self (A : matrix n n α) :
(A + Aᴴ).is_hermitian :=
is_self_adjoint_add_star_self A
lemma is_hermitian_transpose_add_self (A : matrix n n α) :
(Aᴴ + A).is_hermitian :=
is_self_adjoint_star_add_self A
end add_comm_monoid
section add_group
variables [add_group α] [star_add_monoid α]
@[simp] lemma is_hermitian.neg {A : matrix n n α} (h : A.is_hermitian) :
(-A).is_hermitian :=
is_self_adjoint.neg h
@[simp] lemma is_hermitian.sub {A B : matrix n n α} (hA : A.is_hermitian) (hB : B.is_hermitian) :
(A - B).is_hermitian :=
is_self_adjoint.sub hA hB
end add_group
section non_unital_semiring
variables [non_unital_semiring α] [star_ring α] [non_unital_semiring β] [star_ring β]
/-- Note this is more general than `is_self_adjoint.mul_star_self` as `B` can be rectangular. -/
lemma is_hermitian_mul_conj_transpose_self [fintype n] (A : matrix m n α) :
(A ⬝ Aᴴ).is_hermitian :=
by rw [is_hermitian, conj_transpose_mul, conj_transpose_conj_transpose]
/-- Note this is more general than `is_self_adjoint.star_mul_self` as `B` can be rectangular. -/
lemma is_hermitian_transpose_mul_self [fintype m] (A : matrix m n α) :
(Aᴴ ⬝ A).is_hermitian :=
by rw [is_hermitian, conj_transpose_mul, conj_transpose_conj_transpose]
/-- Note this is more general than `is_self_adjoint.conjugate'` as `B` can be rectangular. -/
lemma is_hermitian_conj_transpose_mul_mul [fintype m] {A : matrix m m α} (B : matrix m n α)
(hA : A.is_hermitian) : (Bᴴ ⬝ A ⬝ B).is_hermitian :=
by simp only [is_hermitian, conj_transpose_mul, conj_transpose_conj_transpose, hA.eq,
matrix.mul_assoc]
/-- Note this is more general than `is_self_adjoint.conjugate` as `B` can be rectangular. -/
lemma is_hermitian_mul_mul_conj_transpose [fintype m] {A : matrix m m α} (B : matrix n m α)
(hA : A.is_hermitian) : (B ⬝ A ⬝ Bᴴ).is_hermitian :=
by simp only [is_hermitian, conj_transpose_mul, conj_transpose_conj_transpose, hA.eq,
matrix.mul_assoc]
end non_unital_semiring
section semiring
variables [semiring α] [star_ring α] [semiring β] [star_ring β]
/-- Note this is more general for matrices than `is_self_adjoint_one` as it does not
require `fintype n`, which is necessary for `monoid (matrix n n R)`. -/
@[simp] lemma is_hermitian_one [decidable_eq n] :
(1 : matrix n n α).is_hermitian :=
conj_transpose_one
end semiring
section comm_ring
variables [comm_ring α] [star_ring α]
lemma is_hermitian.inv [fintype m] [decidable_eq m] {A : matrix m m α}
(hA : A.is_hermitian) : A⁻¹.is_hermitian :=
by simp [is_hermitian, conj_transpose_nonsing_inv, hA.eq]
@[simp] lemma is_hermitian_inv [fintype m] [decidable_eq m] (A : matrix m m α) [invertible A]:
(A⁻¹).is_hermitian ↔ A.is_hermitian :=
⟨λ h, by {rw [← inv_inv_of_invertible A], exact is_hermitian.inv h }, is_hermitian.inv⟩
lemma is_hermitian.adjugate [fintype m] [decidable_eq m] {A : matrix m m α}
(hA : A.is_hermitian) : A.adjugate.is_hermitian :=
by simp [is_hermitian, adjugate_conj_transpose, hA.eq]
end comm_ring
section is_R_or_C
open is_R_or_C
variables [is_R_or_C α] [is_R_or_C β]
/-- The diagonal elements of a complex hermitian matrix are real. -/
lemma is_hermitian.coe_re_apply_self {A : matrix n n α} (h : A.is_hermitian) (i : n) :
(re (A i i) : α) = A i i :=
by rw [←conj_eq_iff_re, ←star_def, ←conj_transpose_apply, h.eq]
/-- The diagonal elements of a complex hermitian matrix are real. -/
lemma is_hermitian.coe_re_diag {A : matrix n n α} (h : A.is_hermitian) :
(λ i, (re (A.diag i) : α)) = A.diag :=
funext h.coe_re_apply_self
/-- A matrix is hermitian iff the corresponding linear map is self adjoint. -/
lemma is_hermitian_iff_is_symmetric [fintype n] [decidable_eq n] {A : matrix n n α} :
is_hermitian A ↔ A.to_euclidean_lin.is_symmetric :=
begin
rw [linear_map.is_symmetric, (pi_Lp.equiv 2 (λ _ : n, α)).symm.surjective.forall₂],
simp only [to_euclidean_lin_pi_Lp_equiv_symm, euclidean_space.inner_pi_Lp_equiv_symm,
to_lin'_apply, star_mul_vec, dot_product_mul_vec],
split,
{ rintro (h : Aᴴ = A) x y,
rw h },
{ intro h,
ext i j,
simpa only [(pi.single_star i 1).symm, ← star_mul_vec, mul_one, dot_product_single,
single_vec_mul, star_one, one_mul] using
h (@pi.single _ _ _ (λ i, add_zero_class.to_has_zero α) i 1)
(@pi.single _ _ _ (λ i, add_zero_class.to_has_zero α) j 1) }
end
end is_R_or_C
end matrix
|
8d661ea380ccf1a54b3bf040258abdc674ac25e9 | bb31430994044506fa42fd667e2d556327e18dfe | /src/algebra/ring/ulift.lean | 6336fa3f6fe76e587e1cf0aa5facf88bd104e867 | [
"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 | 5,288 | lean | /-
Copyright (c) 2020 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import algebra.group.ulift
import algebra.field.defs
import algebra.ring.equiv
/-!
# `ulift` instances for ring
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file defines instances for ring, semiring and related structures on `ulift` types.
(Recall `ulift α` is just a "copy" of a type `α` in a higher universe.)
We also provide `ulift.ring_equiv : ulift R ≃+* R`.
-/
universes u v
variables {α : Type u} {x y : ulift.{v} α}
namespace ulift
instance mul_zero_class [mul_zero_class α] : mul_zero_class (ulift α) :=
by refine_struct { zero := (0 : ulift α), mul := (*), .. }; tactic.pi_instance_derive_field
instance distrib [distrib α] : distrib (ulift α) :=
by refine_struct { add := (+), mul := (*), .. }; tactic.pi_instance_derive_field
instance non_unital_non_assoc_semiring [non_unital_non_assoc_semiring α] :
non_unital_non_assoc_semiring (ulift α) :=
by refine_struct { zero := (0 : ulift α), add := (+), mul := (*),
nsmul := add_monoid.nsmul, };
tactic.pi_instance_derive_field
instance non_assoc_semiring [non_assoc_semiring α] : non_assoc_semiring (ulift α) :=
by refine_struct { zero := (0 : ulift α), one := 1, add := (+), mul := (*),
nsmul := add_monoid.nsmul, .. ulift.add_monoid_with_one };
tactic.pi_instance_derive_field
instance non_unital_semiring [non_unital_semiring α] : non_unital_semiring (ulift α) :=
by refine_struct { zero := (0 : ulift α), add := (+), mul := (*),
nsmul := add_monoid.nsmul, };
tactic.pi_instance_derive_field
instance semiring [semiring α] : semiring (ulift α) :=
by refine_struct { zero := (0 : ulift α), one := 1, add := (+), mul := (*),
nsmul := add_monoid.nsmul, npow := monoid.npow, .. ulift.add_monoid_with_one };
tactic.pi_instance_derive_field
/--
The ring equivalence between `ulift α` and `α`.
-/
def ring_equiv [non_unital_non_assoc_semiring α] : ulift α ≃+* α :=
{ to_fun := ulift.down,
inv_fun := ulift.up,
map_mul' := λ x y, rfl,
map_add' := λ x y, rfl,
left_inv := by tidy,
right_inv := by tidy, }
instance non_unital_comm_semiring [non_unital_comm_semiring α] :
non_unital_comm_semiring (ulift α) :=
by refine_struct { zero := (0 : ulift α), add := (+), mul := (*), nsmul := add_monoid.nsmul };
tactic.pi_instance_derive_field
instance comm_semiring [comm_semiring α] : comm_semiring (ulift α) :=
by refine_struct { zero := (0 : ulift α), one := 1, add := (+), mul := (*),
nsmul := add_monoid.nsmul, npow := monoid.npow, .. ulift.semiring };
tactic.pi_instance_derive_field
instance non_unital_non_assoc_ring [non_unital_non_assoc_ring α] :
non_unital_non_assoc_ring (ulift α) :=
by refine_struct { zero := (0 : ulift α), add := (+), mul := (*), sub := has_sub.sub,
neg := has_neg.neg, nsmul := add_monoid.nsmul, zsmul := sub_neg_monoid.zsmul };
tactic.pi_instance_derive_field
instance non_unital_ring [non_unital_ring α] :
non_unital_ring (ulift α) :=
by refine_struct { zero := (0 : ulift α), add := (+), mul := (*), sub := has_sub.sub,
neg := has_neg.neg, nsmul := add_monoid.nsmul, zsmul := sub_neg_monoid.zsmul };
tactic.pi_instance_derive_field
instance non_assoc_ring [non_assoc_ring α] :
non_assoc_ring (ulift α) :=
by refine_struct { zero := (0 : ulift α), one := 1, add := (+), mul := (*), sub := has_sub.sub,
neg := has_neg.neg, nsmul := add_monoid.nsmul, zsmul := sub_neg_monoid.zsmul,
.. ulift.add_group_with_one };
tactic.pi_instance_derive_field
instance ring [ring α] : ring (ulift α) :=
by refine_struct { zero := (0 : ulift α), one := 1, add := (+), mul := (*), sub := has_sub.sub,
neg := has_neg.neg, nsmul := add_monoid.nsmul, npow := monoid.npow,
zsmul := sub_neg_monoid.zsmul, .. ulift.semiring, .. ulift.add_group_with_one };
tactic.pi_instance_derive_field
instance non_unital_comm_ring [non_unital_comm_ring α] : non_unital_comm_ring (ulift α) :=
by refine_struct { zero := (0 : ulift α), add := (+), mul := (*), sub := has_sub.sub,
neg := has_neg.neg, nsmul := add_monoid.nsmul, zsmul := sub_neg_monoid.zsmul };
tactic.pi_instance_derive_field
instance comm_ring [comm_ring α] : comm_ring (ulift α) :=
by refine_struct { .. ulift.ring };
tactic.pi_instance_derive_field
instance [has_rat_cast α] : has_rat_cast (ulift α) :=
⟨λ a, ulift.up (coe a)⟩
@[simp] lemma rat_cast_down [has_rat_cast α] (n : ℚ) : ulift.down (n : ulift α) = n :=
rfl
instance field [field α] : field (ulift α) :=
begin
have of_rat_mk : ∀ a b h1 h2, ((⟨a, b, h1, h2⟩ : ℚ) : ulift α) = ↑a * (↑b)⁻¹,
{ intros a b h1 h2,
ext,
rw [rat_cast_down, mul_down, inv_down, nat_cast_down, int_cast_down],
exact field.rat_cast_mk a b h1 h2 },
refine_struct { zero := (0 : ulift α), inv := has_inv.inv, div := has_div.div,
zpow := λ n a, ulift.up (a.down ^ n), rat_cast := coe, rat_cast_mk := of_rat_mk, qsmul := (•),
.. @ulift.nontrivial α _, .. ulift.comm_ring }; tactic.pi_instance_derive_field,
-- `mul_inv_cancel` requires special attention: it leaves the goal `∀ {a}, a ≠ 0 → a * a⁻¹ = 1`.
cases a,
tauto
end
end ulift
|
838a7e3c7739f057416cdc7f1ddb2771e462a738 | fef48cac17c73db8662678da38fd75888db97560 | /src/point5.lean | 7e03f702b34e98a58643cf2a6d033cd48b34c35f | [] | no_license | kbuzzard/lean-squares-in-fibonacci | 6c0d924f799d6751e19798bb2530ee602ec7087e | 8cea20e5ce88ab7d17b020932d84d316532a84a8 | refs/heads/master | 1,584,524,504,815 | 1,582,387,156,000 | 1,582,387,156,000 | 134,576,655 | 3 | 1 | null | 1,541,538,497,000 | 1,527,083,406,000 | Lean | UTF-8 | Lean | false | false | 1,587 | lean | import definitions
import fib_mod
import data.int.modeq
lemma luc_odd_of_not_3_div (n : ℕ) : luc (3 * n + 1) % 2 = 1 ∧
luc (3 * n + 2) % 2 = 1 :=
begin
split,
{ rw ←luc_mod_eq,
rw luc_mod_2,
simp,refl,
},
{ rw ←luc_mod_eq,
rw luc_mod_2,
simp,refl,
}
end
--Prove that v m is not a multiple of 3 if 4 divides m.
lemma luc_coprime_to_3_of_4_div (n : ℕ) : luc (4 * n) % 3 ≠ 0 :=
begin
rw ←luc_mod_eq,
rw luc_mod_3,
-- cases n even or odd
--case on (n % 2 = 1)
suffices H : n % 2 = 0 ∨ n % 2 = 1,
cases H,
{ -- n % 2 = 0
suffices H2 : 4 * n % 8 = 0,
rw H2,
exact dec_trivial,
change n ≡ 0 [MOD 2] at H,
show 4 * n ≡ 0 [MOD 8],
have a : 2∣n, from nat.modeq.modeq_zero_iff.1 H,
rw nat.modeq.modeq_zero_iff,
change 4*2 ∣ 4 * n,
have q : 4 > 0, by norm_num,
rw nat.mul_dvd_mul_iff_left q,
exact a,
},
{
suffices H1: 4 * n % 8 = 4,
rw H1,
exact dec_trivial,
have h2 := nat.mod_add_div n 2,
rw H at h2,
rw [←h2,mul_add,←mul_assoc],
show (4 + 8 * _) % 8 = 4,
rw nat.add_mul_mod_self_left,
exact dec_trivial,
},
generalize H: n % 2 = k,
have q2: k < 2,
{
have q3: 2 > 0, from dec_trivial,
have q4 : n % 2 < 2, from nat.mod_lt n q3,
rw H at q4,
exact q4,
},
{
clear H,
revert q2 k,
exact dec_trivial,
},
end
/-
#check nat.mul_dvd_mul_iff_left
#check int.coe_nat_dvd
-/
--n : ℕ,
--H : n % 2 = 0
--⊢ 4 * n % 8 = 0
--#check nat.mod
--Prove that v m ≡ 7 mod 8 if m ≡ 4 mod 12 or m ≡ 8 mod 12.
|
95e3683be31edb87ae1d8f668e4ba17f5e26c64f | 367134ba5a65885e863bdc4507601606690974c1 | /src/topology/metric_space/hausdorff_distance.lean | 5f5f3a0f63b7bf091a89909b48e66d3caccb442a | [
"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 | 30,949 | lean | /-
Copyright (c) 2019 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Sébastien Gouëzel
-/
import topology.metric_space.isometry
import topology.instances.ennreal
/-!
# Hausdorff distance
The Hausdorff distance on subsets of a metric (or emetric) space.
Given two subsets `s` and `t` of a metric space, their Hausdorff distance is the smallest `d`
such that any point `s` is within `d` of a point in `t`, and conversely. This quantity
is often infinite (think of `s` bounded and `t` unbounded), and therefore better
expressed in the setting of emetric spaces.
## Main definitions
This files introduces:
* `inf_edist x s`, the infimum edistance of a point `x` to a set `s` in an emetric space
* `Hausdorff_edist s t`, the Hausdorff edistance of two sets in an emetric space
* Versions of these notions on metric spaces, called respectively `inf_dist` and
`Hausdorff_dist`.
-/
noncomputable theory
open_locale classical nnreal ennreal
universes u v w
open classical set function topological_space filter
namespace emetric
section inf_edist
variables {α : Type u} {β : Type v} [emetric_space α] [emetric_space β] {x y : α} {s t : set α}
{Φ : α → β}
/-! ### Distance of a point to a set as a function into `ℝ≥0∞`. -/
/-- The minimal edistance of a point to a set -/
def inf_edist (x : α) (s : set α) : ℝ≥0∞ := ⨅ y ∈ s, edist x y
@[simp] lemma inf_edist_empty : inf_edist x ∅ = ∞ := infi_emptyset
lemma le_inf_edist {d} : d ≤ inf_edist x s ↔ ∀ y ∈ s, d ≤ edist x y :=
by simp only [inf_edist, le_infi_iff]
/-- The edist to a union is the minimum of the edists -/
@[simp] lemma inf_edist_union : inf_edist x (s ∪ t) = inf_edist x s ⊓ inf_edist x t :=
infi_union
/-- The edist to a singleton is the edistance to the single point of this singleton -/
@[simp] lemma inf_edist_singleton : inf_edist x {y} = edist x y :=
infi_singleton
/-- The edist to a set is bounded above by the edist to any of its points -/
lemma inf_edist_le_edist_of_mem (h : y ∈ s) : inf_edist x s ≤ edist x y :=
binfi_le _ h
/-- If a point `x` belongs to `s`, then its edist to `s` vanishes -/
lemma inf_edist_zero_of_mem (h : x ∈ s) : inf_edist x s = 0 :=
nonpos_iff_eq_zero.1 $ @edist_self _ _ x ▸ inf_edist_le_edist_of_mem h
/-- The edist is monotonous with respect to inclusion -/
lemma inf_edist_le_inf_edist_of_subset (h : s ⊆ t) : inf_edist x t ≤ inf_edist x s :=
infi_le_infi_of_subset h
/-- If the edist to a set is `< r`, there exists a point in the set at edistance `< r` -/
lemma exists_edist_lt_of_inf_edist_lt {r : ℝ≥0∞} (h : inf_edist x s < r) :
∃y∈s, edist x y < r :=
by simpa only [inf_edist, infi_lt_iff] using h
/-- The edist of `x` to `s` is bounded by the sum of the edist of `y` to `s` and
the edist from `x` to `y` -/
lemma inf_edist_le_inf_edist_add_edist : inf_edist x s ≤ inf_edist y s + edist x y :=
calc (⨅ z ∈ s, edist x z) ≤ ⨅ z ∈ s, edist y z + edist x y :
binfi_le_binfi $ λ z hz, (edist_triangle _ _ _).trans_eq (add_comm _ _)
... = (⨅ z ∈ s, edist y z) + edist x y : by simp only [ennreal.infi_add]
/-- The edist to a set depends continuously on the point -/
lemma continuous_inf_edist : continuous (λx, inf_edist x s) :=
continuous_of_le_add_edist 1 (by simp) $
by simp only [one_mul, inf_edist_le_inf_edist_add_edist, forall_2_true_iff]
/-- The edist to a set and to its closure coincide -/
lemma inf_edist_closure : inf_edist x (closure s) = inf_edist x s :=
begin
refine le_antisymm (inf_edist_le_inf_edist_of_subset subset_closure) _,
refine ennreal.le_of_forall_pos_le_add (λε εpos h, _),
have εpos' : (0 : ℝ≥0∞) < ε := by simpa,
have : inf_edist x (closure s) < inf_edist x (closure s) + ε/2 :=
ennreal.lt_add_right h (ennreal.half_pos εpos'),
rcases exists_edist_lt_of_inf_edist_lt this with ⟨y, ycs, hy⟩,
-- y : α, ycs : y ∈ closure s, hy : edist x y < inf_edist x (closure s) + ↑ε / 2
rcases emetric.mem_closure_iff.1 ycs (ε/2) (ennreal.half_pos εpos') with ⟨z, zs, dyz⟩,
-- z : α, zs : z ∈ s, dyz : edist y z < ↑ε / 2
calc inf_edist x s ≤ edist x z : inf_edist_le_edist_of_mem zs
... ≤ edist x y + edist y z : edist_triangle _ _ _
... ≤ (inf_edist x (closure s) + ε / 2) + (ε/2) : add_le_add (le_of_lt hy) (le_of_lt dyz)
... = inf_edist x (closure s) + ↑ε : by rw [add_assoc, ennreal.add_halves]
end
/-- A point belongs to the closure of `s` iff its infimum edistance to this set vanishes -/
lemma mem_closure_iff_inf_edist_zero : x ∈ closure s ↔ inf_edist x s = 0 :=
⟨λh, by rw ← inf_edist_closure; exact inf_edist_zero_of_mem h,
λh, emetric.mem_closure_iff.2 $ λε εpos, exists_edist_lt_of_inf_edist_lt (by rwa h)⟩
/-- Given a closed set `s`, a point belongs to `s` iff its infimum edistance to this set vanishes -/
lemma mem_iff_ind_edist_zero_of_closed (h : is_closed s) : x ∈ s ↔ inf_edist x s = 0 :=
begin
convert ← mem_closure_iff_inf_edist_zero,
exact h.closure_eq
end
/-- The infimum edistance is invariant under isometries -/
lemma inf_edist_image (hΦ : isometry Φ) :
inf_edist (Φ x) (Φ '' t) = inf_edist x t :=
by simp only [inf_edist, infi_image, hΦ.edist_eq]
end inf_edist --section
/-! ### The Hausdorff distance as a function into `ℝ≥0∞`. -/
/-- The Hausdorff edistance between two sets is the smallest `r` such that each set
is contained in the `r`-neighborhood of the other one -/
@[irreducible] def Hausdorff_edist {α : Type u} [emetric_space α] (s t : set α) : ℝ≥0∞ :=
(⨆ x ∈ s, inf_edist x t) ⊔ (⨆ y ∈ t, inf_edist y s)
lemma Hausdorff_edist_def {α : Type u} [emetric_space α] (s t : set α) :
Hausdorff_edist s t = (⨆ x ∈ s, inf_edist x t) ⊔ (⨆ y ∈ t, inf_edist y s) :=
by rw Hausdorff_edist
section Hausdorff_edist
variables {α : Type u} {β : Type v} [emetric_space α] [emetric_space β]
{x y : α} {s t u : set α} {Φ : α → β}
/-- The Hausdorff edistance of a set to itself vanishes -/
@[simp] lemma Hausdorff_edist_self : Hausdorff_edist s s = 0 :=
begin
simp only [Hausdorff_edist_def, sup_idem, ennreal.supr_eq_zero],
exact λ x hx, inf_edist_zero_of_mem hx
end
/-- The Haudorff edistances of `s` to `t` and of `t` to `s` coincide -/
lemma Hausdorff_edist_comm : Hausdorff_edist s t = Hausdorff_edist t s :=
by unfold Hausdorff_edist; apply sup_comm
/-- Bounding the Hausdorff edistance by bounding the edistance of any point
in each set to the other set -/
lemma Hausdorff_edist_le_of_inf_edist {r : ℝ≥0∞}
(H1 : ∀x ∈ s, inf_edist x t ≤ r) (H2 : ∀x ∈ t, inf_edist x s ≤ r) :
Hausdorff_edist s t ≤ r :=
begin
simp only [Hausdorff_edist, sup_le_iff, supr_le_iff],
exact ⟨H1, H2⟩
end
/-- Bounding the Hausdorff edistance by exhibiting, for any point in each set,
another point in the other set at controlled distance -/
lemma Hausdorff_edist_le_of_mem_edist {r : ℝ≥0∞}
(H1 : ∀x ∈ s, ∃y ∈ t, edist x y ≤ r) (H2 : ∀x ∈ t, ∃y ∈ s, edist x y ≤ r) :
Hausdorff_edist s t ≤ r :=
begin
refine Hausdorff_edist_le_of_inf_edist _ _,
{ assume x xs,
rcases H1 x xs with ⟨y, yt, hy⟩,
exact le_trans (inf_edist_le_edist_of_mem yt) hy },
{ assume x xt,
rcases H2 x xt with ⟨y, ys, hy⟩,
exact le_trans (inf_edist_le_edist_of_mem ys) hy }
end
/-- The distance to a set is controlled by the Hausdorff distance -/
lemma inf_edist_le_Hausdorff_edist_of_mem (h : x ∈ s) : inf_edist x t ≤ Hausdorff_edist s t :=
begin
rw Hausdorff_edist_def,
refine le_trans _ le_sup_left,
exact le_bsupr x h
end
/-- If the Hausdorff distance is `<r`, then any point in one of the sets has
a corresponding point at distance `<r` in the other set -/
lemma exists_edist_lt_of_Hausdorff_edist_lt {r : ℝ≥0∞} (h : x ∈ s)
(H : Hausdorff_edist s t < r) :
∃y∈t, edist x y < r :=
exists_edist_lt_of_inf_edist_lt $ calc
inf_edist x t ≤ Hausdorff_edist s t : inf_edist_le_Hausdorff_edist_of_mem h
... < r : H
/-- The distance from `x` to `s` or `t` is controlled in terms of the Hausdorff distance
between `s` and `t` -/
lemma inf_edist_le_inf_edist_add_Hausdorff_edist :
inf_edist x t ≤ inf_edist x s + Hausdorff_edist s t :=
ennreal.le_of_forall_pos_le_add $ λε εpos h, begin
have εpos' : (0 : ℝ≥0∞) < ε := by simpa,
have : inf_edist x s < inf_edist x s + ε/2 :=
ennreal.lt_add_right (ennreal.add_lt_top.1 h).1 (ennreal.half_pos εpos'),
rcases exists_edist_lt_of_inf_edist_lt this with ⟨y, ys, dxy⟩,
-- y : α, ys : y ∈ s, dxy : edist x y < inf_edist x s + ↑ε / 2
have : Hausdorff_edist s t < Hausdorff_edist s t + ε/2 :=
ennreal.lt_add_right (ennreal.add_lt_top.1 h).2 (ennreal.half_pos εpos'),
rcases exists_edist_lt_of_Hausdorff_edist_lt ys this with ⟨z, zt, dyz⟩,
-- z : α, zt : z ∈ t, dyz : edist y z < Hausdorff_edist s t + ↑ε / 2
calc inf_edist x t ≤ edist x z : inf_edist_le_edist_of_mem zt
... ≤ edist x y + edist y z : edist_triangle _ _ _
... ≤ (inf_edist x s + ε/2) + (Hausdorff_edist s t + ε/2) : add_le_add dxy.le dyz.le
... = inf_edist x s + Hausdorff_edist s t + ε :
by simp [ennreal.add_halves, add_comm, add_left_comm]
end
/-- The Hausdorff edistance is invariant under eisometries -/
lemma Hausdorff_edist_image (h : isometry Φ) :
Hausdorff_edist (Φ '' s) (Φ '' t) = Hausdorff_edist s t :=
by simp only [Hausdorff_edist_def, supr_image, inf_edist_image h]
/-- The Hausdorff distance is controlled by the diameter of the union -/
lemma Hausdorff_edist_le_ediam (hs : s.nonempty) (ht : t.nonempty) :
Hausdorff_edist s t ≤ diam (s ∪ t) :=
begin
rcases hs with ⟨x, xs⟩,
rcases ht with ⟨y, yt⟩,
refine Hausdorff_edist_le_of_mem_edist _ _,
{ intros z hz,
exact ⟨y, yt, edist_le_diam_of_mem (subset_union_left _ _ hz) (subset_union_right _ _ yt)⟩ },
{ intros z hz,
exact ⟨x, xs, edist_le_diam_of_mem (subset_union_right _ _ hz) (subset_union_left _ _ xs)⟩ }
end
/-- The Hausdorff distance satisfies the triangular inequality -/
lemma Hausdorff_edist_triangle : Hausdorff_edist s u ≤ Hausdorff_edist s t + Hausdorff_edist t u :=
begin
rw Hausdorff_edist_def,
simp only [sup_le_iff, supr_le_iff],
split,
show ∀x ∈ s, inf_edist x u ≤ Hausdorff_edist s t + Hausdorff_edist t u, from λx xs, calc
inf_edist x u ≤ inf_edist x t + Hausdorff_edist t u : inf_edist_le_inf_edist_add_Hausdorff_edist
... ≤ Hausdorff_edist s t + Hausdorff_edist t u :
add_le_add_right (inf_edist_le_Hausdorff_edist_of_mem xs) _,
show ∀x ∈ u, inf_edist x s ≤ Hausdorff_edist s t + Hausdorff_edist t u, from λx xu, calc
inf_edist x s ≤ inf_edist x t + Hausdorff_edist t s : inf_edist_le_inf_edist_add_Hausdorff_edist
... ≤ Hausdorff_edist u t + Hausdorff_edist t s :
add_le_add_right (inf_edist_le_Hausdorff_edist_of_mem xu) _
... = Hausdorff_edist s t + Hausdorff_edist t u : by simp [Hausdorff_edist_comm, add_comm]
end
/-- Two sets are at zero Hausdorff edistance if and only if they have the same closure -/
lemma Hausdorff_edist_zero_iff_closure_eq_closure :
Hausdorff_edist s t = 0 ↔ closure s = closure t :=
calc Hausdorff_edist s t = 0 ↔ s ⊆ closure t ∧ t ⊆ closure s :
by simp only [Hausdorff_edist_def, ennreal.sup_eq_zero, ennreal.supr_eq_zero,
← mem_closure_iff_inf_edist_zero, subset_def]
... ↔ closure s = closure t :
⟨λ h, subset.antisymm (closure_minimal h.1 is_closed_closure)
(closure_minimal h.2 is_closed_closure),
λ h, ⟨h ▸ subset_closure, h.symm ▸ subset_closure⟩⟩
/-- The Hausdorff edistance between a set and its closure vanishes -/
@[simp, priority 1100]
lemma Hausdorff_edist_self_closure : Hausdorff_edist s (closure s) = 0 :=
by rw [Hausdorff_edist_zero_iff_closure_eq_closure, closure_closure]
/-- Replacing a set by its closure does not change the Hausdorff edistance. -/
@[simp] lemma Hausdorff_edist_closure₁ : Hausdorff_edist (closure s) t = Hausdorff_edist s t :=
begin
refine le_antisymm _ _,
{ calc _ ≤ Hausdorff_edist (closure s) s + Hausdorff_edist s t : Hausdorff_edist_triangle
... = Hausdorff_edist s t : by simp [Hausdorff_edist_comm] },
{ calc _ ≤ Hausdorff_edist s (closure s) + Hausdorff_edist (closure s) t :
Hausdorff_edist_triangle
... = Hausdorff_edist (closure s) t : by simp }
end
/-- Replacing a set by its closure does not change the Hausdorff edistance. -/
@[simp] lemma Hausdorff_edist_closure₂ : Hausdorff_edist s (closure t) = Hausdorff_edist s t :=
by simp [@Hausdorff_edist_comm _ _ s _]
/-- The Hausdorff edistance between sets or their closures is the same -/
@[simp] lemma Hausdorff_edist_closure :
Hausdorff_edist (closure s) (closure t) = Hausdorff_edist s t :=
by simp
/-- Two closed sets are at zero Hausdorff edistance if and only if they coincide -/
lemma Hausdorff_edist_zero_iff_eq_of_closed (hs : is_closed s) (ht : is_closed t) :
Hausdorff_edist s t = 0 ↔ s = t :=
by rw [Hausdorff_edist_zero_iff_closure_eq_closure, hs.closure_eq, ht.closure_eq]
/-- The Haudorff edistance to the empty set is infinite -/
lemma Hausdorff_edist_empty (ne : s.nonempty) : Hausdorff_edist s ∅ = ∞ :=
begin
rcases ne with ⟨x, xs⟩,
have : inf_edist x ∅ ≤ Hausdorff_edist s ∅ := inf_edist_le_Hausdorff_edist_of_mem xs,
simpa using this,
end
/-- If a set is at finite Hausdorff edistance of a nonempty set, it is nonempty -/
lemma nonempty_of_Hausdorff_edist_ne_top (hs : s.nonempty) (fin : Hausdorff_edist s t ≠ ⊤) :
t.nonempty :=
t.eq_empty_or_nonempty.elim (λ ht, (fin $ ht.symm ▸ Hausdorff_edist_empty hs).elim) id
lemma empty_or_nonempty_of_Hausdorff_edist_ne_top (fin : Hausdorff_edist s t ≠ ⊤) :
s = ∅ ∧ t = ∅ ∨ s.nonempty ∧ t.nonempty :=
begin
cases s.eq_empty_or_nonempty with hs hs,
{ cases t.eq_empty_or_nonempty with ht ht,
{ exact or.inl ⟨hs, ht⟩ },
{ rw Hausdorff_edist_comm at fin,
exact or.inr ⟨nonempty_of_Hausdorff_edist_ne_top ht fin, ht⟩ } },
{ exact or.inr ⟨hs, nonempty_of_Hausdorff_edist_ne_top hs fin⟩ }
end
end Hausdorff_edist -- section
end emetric --namespace
/-! Now, we turn to the same notions in metric spaces. To avoid the difficulties related to
`Inf` and `Sup` on `ℝ` (which is only conditionally complete), we use the notions in `ℝ≥0∞`
formulated in terms of the edistance, and coerce them to `ℝ`.
Then their properties follow readily from the corresponding properties in `ℝ≥0∞`,
modulo some tedious rewriting of inequalities from one to the other. -/
namespace metric
section
variables {α : Type u} {β : Type v} [metric_space α] [metric_space β]
{s t u : set α} {x y : α} {Φ : α → β}
open emetric
/-! ### Distance of a point to a set as a function into `ℝ`. -/
/-- The minimal distance of a point to a set -/
def inf_dist (x : α) (s : set α) : ℝ := ennreal.to_real (inf_edist x s)
/-- the minimal distance is always nonnegative -/
lemma inf_dist_nonneg : 0 ≤ inf_dist x s := by simp [inf_dist]
/-- the minimal distance to the empty set is 0 (if you want to have the more reasonable
value ∞ instead, use `inf_edist`, which takes values in ℝ≥0∞) -/
@[simp] lemma inf_dist_empty : inf_dist x ∅ = 0 :=
by simp [inf_dist]
/-- In a metric space, the minimal edistance to a nonempty set is finite -/
lemma inf_edist_ne_top (h : s.nonempty) : inf_edist x s ≠ ⊤ :=
begin
rcases h with ⟨y, hy⟩,
apply lt_top_iff_ne_top.1,
calc inf_edist x s ≤ edist x y : inf_edist_le_edist_of_mem hy
... < ⊤ : lt_top_iff_ne_top.2 (edist_ne_top _ _)
end
/-- The minimal distance of a point to a set containing it vanishes -/
lemma inf_dist_zero_of_mem (h : x ∈ s) : inf_dist x s = 0 :=
by simp [inf_edist_zero_of_mem h, inf_dist]
/-- The minimal distance to a singleton is the distance to the unique point in this singleton -/
@[simp] lemma inf_dist_singleton : inf_dist x {y} = dist x y :=
by simp [inf_dist, inf_edist, dist_edist]
/-- The minimal distance to a set is bounded by the distance to any point in this set -/
lemma inf_dist_le_dist_of_mem (h : y ∈ s) : inf_dist x s ≤ dist x y :=
begin
rw [dist_edist, inf_dist,
ennreal.to_real_le_to_real (inf_edist_ne_top ⟨_, h⟩) (edist_ne_top _ _)],
exact inf_edist_le_edist_of_mem h
end
/-- The minimal distance is monotonous with respect to inclusion -/
lemma inf_dist_le_inf_dist_of_subset (h : s ⊆ t) (hs : s.nonempty) :
inf_dist x t ≤ inf_dist x s :=
begin
have ht : t.nonempty := hs.mono h,
rw [inf_dist, inf_dist, ennreal.to_real_le_to_real (inf_edist_ne_top ht) (inf_edist_ne_top hs)],
exact inf_edist_le_inf_edist_of_subset h
end
/-- If the minimal distance to a set is `<r`, there exists a point in this set at distance `<r` -/
lemma exists_dist_lt_of_inf_dist_lt {r : real} (h : inf_dist x s < r) (hs : s.nonempty) :
∃y∈s, dist x y < r :=
begin
have rpos : 0 < r := lt_of_le_of_lt inf_dist_nonneg h,
have : inf_edist x s < ennreal.of_real r,
{ rwa [inf_dist, ← ennreal.to_real_of_real (le_of_lt rpos),
ennreal.to_real_lt_to_real (inf_edist_ne_top hs)] at h,
simp },
rcases exists_edist_lt_of_inf_edist_lt this with ⟨y, ys, hy⟩,
rw [edist_dist, ennreal.of_real_lt_of_real_iff rpos] at hy,
exact ⟨y, ys, hy⟩,
end
/-- The minimal distance from `x` to `s` is bounded by the distance from `y` to `s`, modulo
the distance between `x` and `y` -/
lemma inf_dist_le_inf_dist_add_dist : inf_dist x s ≤ inf_dist y s + dist x y :=
begin
cases s.eq_empty_or_nonempty with hs hs,
{ by simp [hs, dist_nonneg] },
{ rw [inf_dist, inf_dist, dist_edist,
← ennreal.to_real_add (inf_edist_ne_top hs) (edist_ne_top _ _),
ennreal.to_real_le_to_real (inf_edist_ne_top hs)],
{ apply inf_edist_le_inf_edist_add_edist },
{ simp [ennreal.add_eq_top, inf_edist_ne_top hs, edist_ne_top] }}
end
variable (s)
/-- The minimal distance to a set is Lipschitz in point with constant 1 -/
lemma lipschitz_inf_dist_pt : lipschitz_with 1 (λx, inf_dist x s) :=
lipschitz_with.of_le_add $ λ x y, inf_dist_le_inf_dist_add_dist
/-- The minimal distance to a set is uniformly continuous in point -/
lemma uniform_continuous_inf_dist_pt :
uniform_continuous (λx, inf_dist x s) :=
(lipschitz_inf_dist_pt s).uniform_continuous
/-- The minimal distance to a set is continuous in point -/
lemma continuous_inf_dist_pt : continuous (λx, inf_dist x s) :=
(uniform_continuous_inf_dist_pt s).continuous
variable {s}
/-- The minimal distance to a set and its closure coincide -/
lemma inf_dist_eq_closure : inf_dist x (closure s) = inf_dist x s :=
by simp [inf_dist, inf_edist_closure]
/-- A point belongs to the closure of `s` iff its infimum distance to this set vanishes -/
lemma mem_closure_iff_inf_dist_zero (h : s.nonempty) : x ∈ closure s ↔ inf_dist x s = 0 :=
by simp [mem_closure_iff_inf_edist_zero, inf_dist, ennreal.to_real_eq_zero_iff, inf_edist_ne_top h]
/-- Given a closed set `s`, a point belongs to `s` iff its infimum distance to this set vanishes -/
lemma mem_iff_inf_dist_zero_of_closed (h : is_closed s) (hs : s.nonempty) :
x ∈ s ↔ inf_dist x s = 0 :=
begin
have := @mem_closure_iff_inf_dist_zero _ _ s x hs,
rwa h.closure_eq at this
end
/-- The infimum distance is invariant under isometries -/
lemma inf_dist_image (hΦ : isometry Φ) :
inf_dist (Φ x) (Φ '' t) = inf_dist x t :=
by simp [inf_dist, inf_edist_image hΦ]
/-! ### Distance of a point to a set as a function into `ℝ≥0`. -/
/-- The minimal distance of a point to a set as a `ℝ≥0` -/
def inf_nndist (x : α) (s : set α) : ℝ≥0 := ennreal.to_nnreal (inf_edist x s)
@[simp] lemma coe_inf_nndist : (inf_nndist x s : ℝ) = inf_dist x s := rfl
/-- The minimal distance to a set (as `ℝ≥0`) is Lipschitz in point with constant 1 -/
lemma lipschitz_inf_nndist_pt (s : set α) : lipschitz_with 1 (λx, inf_nndist x s) :=
lipschitz_with.of_le_add $ λ x y, inf_dist_le_inf_dist_add_dist
/-- The minimal distance to a set (as `ℝ≥0`) is uniformly continuous in point -/
lemma uniform_continuous_inf_nndist_pt (s : set α) :
uniform_continuous (λx, inf_nndist x s) :=
(lipschitz_inf_nndist_pt s).uniform_continuous
/-- The minimal distance to a set (as `ℝ≥0`) is continuous in point -/
lemma continuous_inf_nndist_pt (s : set α) : continuous (λx, inf_nndist x s) :=
(uniform_continuous_inf_nndist_pt s).continuous
/-! ### The Hausdorff distance as a function into `ℝ`. -/
/-- The Hausdorff distance between two sets is the smallest nonnegative `r` such that each set is
included in the `r`-neighborhood of the other. If there is no such `r`, it is defined to
be `0`, arbitrarily -/
def Hausdorff_dist (s t : set α) : ℝ := ennreal.to_real (Hausdorff_edist s t)
/-- The Hausdorff distance is nonnegative -/
lemma Hausdorff_dist_nonneg : 0 ≤ Hausdorff_dist s t :=
by simp [Hausdorff_dist]
/-- If two sets are nonempty and bounded in a metric space, they are at finite Hausdorff
edistance. -/
lemma Hausdorff_edist_ne_top_of_nonempty_of_bounded (hs : s.nonempty) (ht : t.nonempty)
(bs : bounded s) (bt : bounded t) : Hausdorff_edist s t ≠ ⊤ :=
begin
rcases hs with ⟨cs, hcs⟩,
rcases ht with ⟨ct, hct⟩,
rcases (bounded_iff_subset_ball ct).1 bs with ⟨rs, hrs⟩,
rcases (bounded_iff_subset_ball cs).1 bt with ⟨rt, hrt⟩,
have : Hausdorff_edist s t ≤ ennreal.of_real (max rs rt),
{ apply Hausdorff_edist_le_of_mem_edist,
{ assume x xs,
existsi [ct, hct],
have : dist x ct ≤ max rs rt := le_trans (hrs xs) (le_max_left _ _),
rwa [edist_dist, ennreal.of_real_le_of_real_iff],
exact le_trans dist_nonneg this },
{ assume x xt,
existsi [cs, hcs],
have : dist x cs ≤ max rs rt := le_trans (hrt xt) (le_max_right _ _),
rwa [edist_dist, ennreal.of_real_le_of_real_iff],
exact le_trans dist_nonneg this }},
exact ennreal.lt_top_iff_ne_top.1 (lt_of_le_of_lt this (by simp [lt_top_iff_ne_top]))
end
/-- The Hausdorff distance between a set and itself is zero -/
@[simp] lemma Hausdorff_dist_self_zero : Hausdorff_dist s s = 0 :=
by simp [Hausdorff_dist]
/-- The Hausdorff distance from `s` to `t` and from `t` to `s` coincide -/
lemma Hausdorff_dist_comm : Hausdorff_dist s t = Hausdorff_dist t s :=
by simp [Hausdorff_dist, Hausdorff_edist_comm]
/-- The Hausdorff distance to the empty set vanishes (if you want to have the more reasonable
value ∞ instead, use `Hausdorff_edist`, which takes values in ℝ≥0∞) -/
@[simp] lemma Hausdorff_dist_empty : Hausdorff_dist s ∅ = 0 :=
begin
cases s.eq_empty_or_nonempty with h h,
{ simp [h] },
{ simp [Hausdorff_dist, Hausdorff_edist_empty h] }
end
/-- The Hausdorff distance to the empty set vanishes (if you want to have the more reasonable
value ∞ instead, use `Hausdorff_edist`, which takes values in ℝ≥0∞) -/
@[simp] lemma Hausdorff_dist_empty' : Hausdorff_dist ∅ s = 0 :=
by simp [Hausdorff_dist_comm]
/-- Bounding the Hausdorff distance by bounding the distance of any point
in each set to the other set -/
lemma Hausdorff_dist_le_of_inf_dist {r : ℝ} (hr : 0 ≤ r)
(H1 : ∀x ∈ s, inf_dist x t ≤ r) (H2 : ∀x ∈ t, inf_dist x s ≤ r) :
Hausdorff_dist s t ≤ r :=
begin
by_cases h1 : Hausdorff_edist s t = ⊤,
by rwa [Hausdorff_dist, h1, ennreal.top_to_real],
cases s.eq_empty_or_nonempty with hs hs,
by rwa [hs, Hausdorff_dist_empty'],
cases t.eq_empty_or_nonempty with ht ht,
by rwa [ht, Hausdorff_dist_empty],
have : Hausdorff_edist s t ≤ ennreal.of_real r,
{ apply Hausdorff_edist_le_of_inf_edist _ _,
{ assume x hx,
have I := H1 x hx,
rwa [inf_dist, ← ennreal.to_real_of_real hr,
ennreal.to_real_le_to_real (inf_edist_ne_top ht) ennreal.of_real_ne_top] at I },
{ assume x hx,
have I := H2 x hx,
rwa [inf_dist, ← ennreal.to_real_of_real hr,
ennreal.to_real_le_to_real (inf_edist_ne_top hs) ennreal.of_real_ne_top] at I }},
rwa [Hausdorff_dist, ← ennreal.to_real_of_real hr,
ennreal.to_real_le_to_real h1 ennreal.of_real_ne_top]
end
/-- Bounding the Hausdorff distance by exhibiting, for any point in each set,
another point in the other set at controlled distance -/
lemma Hausdorff_dist_le_of_mem_dist {r : ℝ} (hr : 0 ≤ r)
(H1 : ∀x ∈ s, ∃y ∈ t, dist x y ≤ r) (H2 : ∀x ∈ t, ∃y ∈ s, dist x y ≤ r) :
Hausdorff_dist s t ≤ r :=
begin
apply Hausdorff_dist_le_of_inf_dist hr,
{ assume x xs,
rcases H1 x xs with ⟨y, yt, hy⟩,
exact le_trans (inf_dist_le_dist_of_mem yt) hy },
{ assume x xt,
rcases H2 x xt with ⟨y, ys, hy⟩,
exact le_trans (inf_dist_le_dist_of_mem ys) hy }
end
/-- The Hausdorff distance is controlled by the diameter of the union -/
lemma Hausdorff_dist_le_diam (hs : s.nonempty) (bs : bounded s) (ht : t.nonempty) (bt : bounded t) :
Hausdorff_dist s t ≤ diam (s ∪ t) :=
begin
rcases hs with ⟨x, xs⟩,
rcases ht with ⟨y, yt⟩,
refine Hausdorff_dist_le_of_mem_dist diam_nonneg _ _,
{ exact λz hz, ⟨y, yt, dist_le_diam_of_mem (bounded_union.2 ⟨bs, bt⟩)
(subset_union_left _ _ hz) (subset_union_right _ _ yt)⟩ },
{ exact λz hz, ⟨x, xs, dist_le_diam_of_mem (bounded_union.2 ⟨bs, bt⟩)
(subset_union_right _ _ hz) (subset_union_left _ _ xs)⟩ }
end
/-- The distance to a set is controlled by the Hausdorff distance -/
lemma inf_dist_le_Hausdorff_dist_of_mem (hx : x ∈ s) (fin : Hausdorff_edist s t ≠ ⊤) :
inf_dist x t ≤ Hausdorff_dist s t :=
begin
have ht : t.nonempty := nonempty_of_Hausdorff_edist_ne_top ⟨x, hx⟩ fin,
rw [Hausdorff_dist, inf_dist, ennreal.to_real_le_to_real (inf_edist_ne_top ht) fin],
exact inf_edist_le_Hausdorff_edist_of_mem hx
end
/-- If the Hausdorff distance is `<r`, then any point in one of the sets is at distance
`<r` of a point in the other set -/
lemma exists_dist_lt_of_Hausdorff_dist_lt {r : ℝ} (h : x ∈ s) (H : Hausdorff_dist s t < r)
(fin : Hausdorff_edist s t ≠ ⊤) : ∃y∈t, dist x y < r :=
begin
have r0 : 0 < r := lt_of_le_of_lt (Hausdorff_dist_nonneg) H,
have : Hausdorff_edist s t < ennreal.of_real r,
by rwa [Hausdorff_dist, ← ennreal.to_real_of_real (le_of_lt r0),
ennreal.to_real_lt_to_real fin (ennreal.of_real_ne_top)] at H,
rcases exists_edist_lt_of_Hausdorff_edist_lt h this with ⟨y, hy, yr⟩,
rw [edist_dist, ennreal.of_real_lt_of_real_iff r0] at yr,
exact ⟨y, hy, yr⟩
end
/-- If the Hausdorff distance is `<r`, then any point in one of the sets is at distance
`<r` of a point in the other set -/
lemma exists_dist_lt_of_Hausdorff_dist_lt' {r : ℝ} (h : y ∈ t) (H : Hausdorff_dist s t < r)
(fin : Hausdorff_edist s t ≠ ⊤) : ∃x∈s, dist x y < r :=
begin
rw Hausdorff_dist_comm at H,
rw Hausdorff_edist_comm at fin,
simpa [dist_comm] using exists_dist_lt_of_Hausdorff_dist_lt h H fin
end
/-- The infimum distance to `s` and `t` are the same, up to the Hausdorff distance
between `s` and `t` -/
lemma inf_dist_le_inf_dist_add_Hausdorff_dist (fin : Hausdorff_edist s t ≠ ⊤) :
inf_dist x t ≤ inf_dist x s + Hausdorff_dist s t :=
begin
rcases empty_or_nonempty_of_Hausdorff_edist_ne_top fin with ⟨hs,ht⟩|⟨hs,ht⟩,
{ simp only [hs, ht, Hausdorff_dist_empty, inf_dist_empty, zero_add] },
rw [inf_dist, inf_dist, Hausdorff_dist, ← ennreal.to_real_add (inf_edist_ne_top hs) fin,
ennreal.to_real_le_to_real (inf_edist_ne_top ht)],
{ exact inf_edist_le_inf_edist_add_Hausdorff_edist },
{ exact ennreal.add_ne_top.2 ⟨inf_edist_ne_top hs, fin⟩ }
end
/-- The Hausdorff distance is invariant under isometries -/
lemma Hausdorff_dist_image (h : isometry Φ) :
Hausdorff_dist (Φ '' s) (Φ '' t) = Hausdorff_dist s t :=
by simp [Hausdorff_dist, Hausdorff_edist_image h]
/-- The Hausdorff distance satisfies the triangular inequality -/
lemma Hausdorff_dist_triangle (fin : Hausdorff_edist s t ≠ ⊤) :
Hausdorff_dist s u ≤ Hausdorff_dist s t + Hausdorff_dist t u :=
begin
by_cases Hausdorff_edist s u = ⊤,
{ calc Hausdorff_dist s u = 0 + 0 : by simp [Hausdorff_dist, h]
... ≤ Hausdorff_dist s t + Hausdorff_dist t u :
add_le_add (Hausdorff_dist_nonneg) (Hausdorff_dist_nonneg) },
{ have Dtu : Hausdorff_edist t u < ⊤ := calc
Hausdorff_edist t u ≤ Hausdorff_edist t s + Hausdorff_edist s u : Hausdorff_edist_triangle
... = Hausdorff_edist s t + Hausdorff_edist s u : by simp [Hausdorff_edist_comm]
... < ⊤ : by simp [ennreal.add_lt_top]; simp [ennreal.lt_top_iff_ne_top, h, fin],
rw [Hausdorff_dist, Hausdorff_dist, Hausdorff_dist,
← ennreal.to_real_add fin (lt_top_iff_ne_top.1 Dtu), ennreal.to_real_le_to_real h],
{ exact Hausdorff_edist_triangle },
{ simp [ennreal.add_eq_top, lt_top_iff_ne_top.1 Dtu, fin] }}
end
/-- The Hausdorff distance satisfies the triangular inequality -/
lemma Hausdorff_dist_triangle' (fin : Hausdorff_edist t u ≠ ⊤) :
Hausdorff_dist s u ≤ Hausdorff_dist s t + Hausdorff_dist t u :=
begin
rw Hausdorff_edist_comm at fin,
have I : Hausdorff_dist u s ≤ Hausdorff_dist u t + Hausdorff_dist t s :=
Hausdorff_dist_triangle fin,
simpa [add_comm, Hausdorff_dist_comm] using I
end
/-- The Hausdorff distance between a set and its closure vanish -/
@[simp, priority 1100]
lemma Hausdorff_dist_self_closure : Hausdorff_dist s (closure s) = 0 :=
by simp [Hausdorff_dist]
/-- Replacing a set by its closure does not change the Hausdorff distance. -/
@[simp] lemma Hausdorff_dist_closure₁ : Hausdorff_dist (closure s) t = Hausdorff_dist s t :=
by simp [Hausdorff_dist]
/-- Replacing a set by its closure does not change the Hausdorff distance. -/
@[simp] lemma Hausdorff_dist_closure₂ : Hausdorff_dist s (closure t) = Hausdorff_dist s t :=
by simp [Hausdorff_dist]
/-- The Hausdorff distance between two sets and their closures coincide -/
@[simp] lemma Hausdorff_dist_closure :
Hausdorff_dist (closure s) (closure t) = Hausdorff_dist s t :=
by simp [Hausdorff_dist]
/-- Two sets are at zero Hausdorff distance if and only if they have the same closures -/
lemma Hausdorff_dist_zero_iff_closure_eq_closure (fin : Hausdorff_edist s t ≠ ⊤) :
Hausdorff_dist s t = 0 ↔ closure s = closure t :=
by simp [Hausdorff_edist_zero_iff_closure_eq_closure.symm, Hausdorff_dist,
ennreal.to_real_eq_zero_iff, fin]
/-- Two closed sets are at zero Hausdorff distance if and only if they coincide -/
lemma Hausdorff_dist_zero_iff_eq_of_closed (hs : is_closed s) (ht : is_closed t)
(fin : Hausdorff_edist s t ≠ ⊤) : Hausdorff_dist s t = 0 ↔ s = t :=
by simp [(Hausdorff_edist_zero_iff_eq_of_closed hs ht).symm, Hausdorff_dist,
ennreal.to_real_eq_zero_iff, fin]
end --section
end metric --namespace
|
f58fd6363dd82e01fa3e0e77a244cc79f53f49b7 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/playground/tst.lean | 0a0f5ab140e52a75cdb658c8cd9dd9fba4093bea | [
"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 | 255 | lean | def tst (n : Nat) : Nat :=
let xs := List.repeat 1 n in
xs.foldl (+) 0
def perf (n : Nat) : IO Unit :=
do v ← pure $ tst n,
IO.println ("Result " ++ toString v)
def main (xs : List String) : IO UInt32 :=
timeit "tst" (perf xs.head.toNat) *>
pure 0
|
95e0cbde3b0c5e38ffc469236cdc6e2e8003a5d2 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /src/lake/Lake/Build/Imports.lean | 392b16277073f5260144d367a7e4f500c7153a98 | [
"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 | 2,680 | lean | /-
Copyright (c) 2022 Mac Malone. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mac Malone
-/
import Lake.Build.Index
/-!
Definitions to support `lake print-paths` builds.
-/
open System
namespace Lake
/--
Construct an `Array` of `Module`s for the workspace-local modules of
a `List` of import strings.
-/
def Workspace.processImportList
(imports : List String) (self : Workspace) : Array Module := Id.run do
let mut localImports := #[]
for imp in imports do
if let some mod := self.findModule? imp.toName then
localImports := localImports.push mod
return localImports
/--
Recursively build a set of imported modules and return their build jobs,
the build jobs of their precompiled modules and the build jobs of said modules'
external libraries.
-/
def recBuildImports (imports : Array Module)
: IndexBuildM (Array (BuildJob Unit) × Array (BuildJob Dynlib) × Array (BuildJob Dynlib)) := do
let mut modJobs := #[]
let mut precompileImports := OrdModuleSet.empty
for mod in imports do
if mod.shouldPrecompile then
precompileImports := precompileImports.appendArray (← mod.transImports.fetch) |>.insert mod
else
precompileImports := precompileImports.appendArray (← mod.precompileImports.fetch)
modJobs := modJobs.push <| ← mod.leanBin.fetch
let pkgs := precompileImports.foldl (·.insert ·.pkg) OrdPackageSet.empty |>.toArray
let externJobs ← pkgs.concatMapM (·.externLibs.mapM (·.dynlib.fetch))
let precompileJobs ← precompileImports.toArray.mapM (·.dynlib.fetch)
return (modJobs, precompileJobs, externJobs)
/--
Builds the workspace-local modules of list of imports.
Used by `lake print-paths` to build modules for the Lean server.
Returns the set of module dynlibs built (so they can be loaded by the server).
Builds only module `.olean` and `.ilean` files if the package is configured
as "Lean-only". Otherwise, also builds `.c` files.
-/
def buildImportsAndDeps (imports : List String) : BuildM (Array FilePath) := do
let ws ← getWorkspace
if imports.isEmpty then
-- build the package's (and its dependencies') `extraDepTarget`
ws.root.extraDep.build >>= (·.materialize)
return #[]
else
-- build local imports from list
let mods := ws.processImportList imports
let (modJobs, precompileJobs, externLibJobs) ←
recBuildImports mods |>.run.run
modJobs.forM (·.await)
let modLibs ← precompileJobs.mapM (·.await <&> (·.path))
let externLibs ← externLibJobs.mapM (·.await <&> (·.path))
-- NOTE: Lean wants the external library symbols before module symbols
return externLibs ++ modLibs
|
4a4e821161e50e78e6d6ce8e52ede8172457adc7 | a7eef317ddec01b9fc6cfbb876fe7ac00f205ac7 | /test/mk_iff_of_inductive.lean | f31e1b6c7ba9c817838cd1213acdea1ee7f4e0e3 | [
"Apache-2.0"
] | permissive | kmill/mathlib | ea5a007b67ae4e9e18dd50d31d8aa60f650425ee | 1a419a9fea7b959317eddd556e1bb9639f4dcc05 | refs/heads/master | 1,668,578,197,719 | 1,593,629,163,000 | 1,593,629,163,000 | 276,482,939 | 0 | 0 | null | 1,593,637,960,000 | 1,593,637,959,000 | null | UTF-8 | Lean | false | false | 743 | lean | import tactic.mk_iff_of_inductive_prop
import data.list
import data.list.perm
import data.multiset.basic
mk_iff_of_inductive_prop list.chain test.chain_iff
mk_iff_of_inductive_prop false test.false_iff
mk_iff_of_inductive_prop true test.true_iff
mk_iff_of_inductive_prop nonempty test.non_empty_iff
mk_iff_of_inductive_prop and test.and_iff
mk_iff_of_inductive_prop or test.or_iff
mk_iff_of_inductive_prop eq test.eq_iff
mk_iff_of_inductive_prop heq test.heq_iff
mk_iff_of_inductive_prop list.perm test.perm_iff
mk_iff_of_inductive_prop list.pairwise test.pairwise_iff
inductive test.is_true (p : Prop) : Prop
| triviality : p → test.is_true
mk_iff_of_inductive_prop test.is_true test.is_true_iff
|
5827cea4863e95d0ed1f5dbbb08de512e925704a | c777c32c8e484e195053731103c5e52af26a25d1 | /src/analysis/calculus/formal_multilinear_series.lean | 36c44df149a6e72d14bc54ae506eb3dcbaba4459 | [
"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 | 12,351 | lean | /-
Copyright (c) 2019 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sébastien Gouëzel
-/
import analysis.normed_space.multilinear
/-!
# Formal multilinear series
In this file we define `formal_multilinear_series 𝕜 E F` to be a family of `n`-multilinear maps for
all `n`, designed to model the sequence of derivatives of a function. In other files we use this
notion to define `C^n` functions (called `cont_diff` in `mathlib`) and analytic functions.
## Notations
We use the notation `E [×n]→L[𝕜] F` for the space of continuous multilinear maps on `E^n` with
values in `F`. This is the space in which the `n`-th derivative of a function from `E` to `F` lives.
## Tags
multilinear, formal series
-/
noncomputable theory
open set fin
open_locale topology
variables {𝕜 𝕜' E F G : Type*}
section
variables [comm_ring 𝕜]
[add_comm_group E] [module 𝕜 E] [topological_space E] [topological_add_group E]
[has_continuous_const_smul 𝕜 E]
[add_comm_group F] [module 𝕜 F] [topological_space F] [topological_add_group F]
[has_continuous_const_smul 𝕜 F]
[add_comm_group G] [module 𝕜 G] [topological_space G] [topological_add_group G]
[has_continuous_const_smul 𝕜 G]
/-- A formal multilinear series over a field `𝕜`, from `E` to `F`, is given by a family of
multilinear maps from `E^n` to `F` for all `n`. -/
@[derive add_comm_group, nolint unused_arguments]
def formal_multilinear_series (𝕜 : Type*) (E : Type*) (F : Type*)
[ring 𝕜]
[add_comm_group E] [module 𝕜 E] [topological_space E] [topological_add_group E]
[has_continuous_const_smul 𝕜 E]
[add_comm_group F] [module 𝕜 F] [topological_space F] [topological_add_group F]
[has_continuous_const_smul 𝕜 F] :=
Π (n : ℕ), (E [×n]→L[𝕜] F)
instance : inhabited (formal_multilinear_series 𝕜 E F) := ⟨0⟩
section module
/- `derive` is not able to find the module structure, probably because Lean is confused by the
dependent types. We register it explicitly. -/
instance : module 𝕜 (formal_multilinear_series 𝕜 E F) :=
begin
letI : Π n, module 𝕜 (continuous_multilinear_map 𝕜 (λ (i : fin n), E) F) :=
λ n, by apply_instance,
refine pi.module _ _ _,
end
end module
namespace formal_multilinear_series
protected lemma ext_iff {p q : formal_multilinear_series 𝕜 E F} : p = q ↔ ∀ n, p n = q n :=
function.funext_iff
protected lemma ne_iff {p q : formal_multilinear_series 𝕜 E F} : p ≠ q ↔ ∃ n, p n ≠ q n :=
function.ne_iff
/-- Killing the zeroth coefficient in a formal multilinear series -/
def remove_zero (p : formal_multilinear_series 𝕜 E F) : formal_multilinear_series 𝕜 E F
| 0 := 0
| (n + 1) := p (n + 1)
@[simp] lemma remove_zero_coeff_zero (p : formal_multilinear_series 𝕜 E F) :
p.remove_zero 0 = 0 := rfl
@[simp] lemma remove_zero_coeff_succ (p : formal_multilinear_series 𝕜 E F) (n : ℕ) :
p.remove_zero (n+1) = p (n+1) := rfl
lemma remove_zero_of_pos (p : formal_multilinear_series 𝕜 E F) {n : ℕ} (h : 0 < n) :
p.remove_zero n = p n :=
by { rw ← nat.succ_pred_eq_of_pos h, refl }
/-- Convenience congruence lemma stating in a dependent setting that, if the arguments to a formal
multilinear series are equal, then the values are also equal. -/
lemma congr (p : formal_multilinear_series 𝕜 E F) {m n : ℕ} {v : fin m → E} {w : fin n → E}
(h1 : m = n) (h2 : ∀ (i : ℕ) (him : i < m) (hin : i < n), v ⟨i, him⟩ = w ⟨i, hin⟩) :
p m v = p n w :=
by { cases h1, congr' with ⟨i, hi⟩, exact h2 i hi hi }
/-- Composing each term `pₙ` in a formal multilinear series with `(u, ..., u)` where `u` is a fixed
continuous linear map, gives a new formal multilinear series `p.comp_continuous_linear_map u`. -/
def comp_continuous_linear_map (p : formal_multilinear_series 𝕜 F G) (u : E →L[𝕜] F) :
formal_multilinear_series 𝕜 E G :=
λ n, (p n).comp_continuous_linear_map (λ (i : fin n), u)
@[simp] lemma comp_continuous_linear_map_apply
(p : formal_multilinear_series 𝕜 F G) (u : E →L[𝕜] F) (n : ℕ) (v : fin n → E) :
(p.comp_continuous_linear_map u) n v = p n (u ∘ v) := rfl
variables (𝕜) [comm_ring 𝕜'] [has_smul 𝕜 𝕜']
variables [module 𝕜' E] [has_continuous_const_smul 𝕜' E] [is_scalar_tower 𝕜 𝕜' E]
variables [module 𝕜' F] [has_continuous_const_smul 𝕜' F] [is_scalar_tower 𝕜 𝕜' F]
/-- Reinterpret a formal `𝕜'`-multilinear series as a formal `𝕜`-multilinear series. -/
@[simp] protected def restrict_scalars (p : formal_multilinear_series 𝕜' E F) :
formal_multilinear_series 𝕜 E F :=
λ n, (p n).restrict_scalars 𝕜
end formal_multilinear_series
end
namespace formal_multilinear_series
variables [nontrivially_normed_field 𝕜]
[normed_add_comm_group E] [normed_space 𝕜 E]
[normed_add_comm_group F] [normed_space 𝕜 F]
[normed_add_comm_group G] [normed_space 𝕜 G]
variables (p : formal_multilinear_series 𝕜 E F)
/-- Forgetting the zeroth term in a formal multilinear series, and interpreting the following terms
as multilinear maps into `E →L[𝕜] F`. If `p` corresponds to the Taylor series of a function, then
`p.shift` is the Taylor series of the derivative of the function. -/
def shift : formal_multilinear_series 𝕜 E (E →L[𝕜] F) :=
λn, (p n.succ).curry_right
/-- Adding a zeroth term to a formal multilinear series taking values in `E →L[𝕜] F`. This
corresponds to starting from a Taylor series for the derivative of a function, and building a Taylor
series for the function itself. -/
def unshift (q : formal_multilinear_series 𝕜 E (E →L[𝕜] F)) (z : F) :
formal_multilinear_series 𝕜 E F
| 0 := (continuous_multilinear_curry_fin0 𝕜 E F).symm z
| (n + 1) := continuous_multilinear_curry_right_equiv' 𝕜 n E F (q n)
end formal_multilinear_series
namespace continuous_linear_map
variables [comm_ring 𝕜]
[add_comm_group E] [module 𝕜 E] [topological_space E] [topological_add_group E]
[has_continuous_const_smul 𝕜 E]
[add_comm_group F] [module 𝕜 F] [topological_space F] [topological_add_group F]
[has_continuous_const_smul 𝕜 F]
[add_comm_group G] [module 𝕜 G] [topological_space G] [topological_add_group G]
[has_continuous_const_smul 𝕜 G]
/-- Composing each term `pₙ` in a formal multilinear series with a continuous linear map `f` on the
left gives a new formal multilinear series `f.comp_formal_multilinear_series p` whose general term
is `f ∘ pₙ`. -/
def comp_formal_multilinear_series (f : F →L[𝕜] G) (p : formal_multilinear_series 𝕜 E F) :
formal_multilinear_series 𝕜 E G :=
λ n, f.comp_continuous_multilinear_map (p n)
@[simp] lemma comp_formal_multilinear_series_apply
(f : F →L[𝕜] G) (p : formal_multilinear_series 𝕜 E F) (n : ℕ) :
(f.comp_formal_multilinear_series p) n = f.comp_continuous_multilinear_map (p n) :=
rfl
lemma comp_formal_multilinear_series_apply'
(f : F →L[𝕜] G) (p : formal_multilinear_series 𝕜 E F) (n : ℕ) (v : fin n → E) :
(f.comp_formal_multilinear_series p) n v = f (p n v) :=
rfl
end continuous_linear_map
namespace formal_multilinear_series
section order
variables [comm_ring 𝕜] {n : ℕ}
[add_comm_group E] [module 𝕜 E] [topological_space E] [topological_add_group E]
[has_continuous_const_smul 𝕜 E]
[add_comm_group F] [module 𝕜 F] [topological_space F] [topological_add_group F]
[has_continuous_const_smul 𝕜 F]
{p : formal_multilinear_series 𝕜 E F}
/-- The index of the first non-zero coefficient in `p` (or `0` if all coefficients are zero). This
is the order of the isolated zero of an analytic function `f` at a point if `p` is the Taylor
series of `f` at that point. -/
noncomputable def order (p : formal_multilinear_series 𝕜 E F) : ℕ :=
Inf { n | p n ≠ 0 }
@[simp] lemma order_zero : (0 : formal_multilinear_series 𝕜 E F).order = 0 := by simp [order]
lemma ne_zero_of_order_ne_zero (hp : p.order ≠ 0) : p ≠ 0 :=
λ h, by simpa [h] using hp
lemma order_eq_find [decidable_pred (λ n, p n ≠ 0)] (hp : ∃ n, p n ≠ 0) :
p.order = nat.find hp :=
by simp [order, Inf, hp]
lemma order_eq_find' [decidable_pred (λ n, p n ≠ 0)] (hp : p ≠ 0) :
p.order = nat.find (formal_multilinear_series.ne_iff.mp hp) :=
order_eq_find _
lemma order_eq_zero_iff (hp : p ≠ 0) : p.order = 0 ↔ p 0 ≠ 0 :=
begin
classical,
have : ∃ n, p n ≠ 0 := formal_multilinear_series.ne_iff.mp hp,
simp [order_eq_find this, hp]
end
lemma order_eq_zero_iff' : p.order = 0 ↔ p = 0 ∨ p 0 ≠ 0 :=
by { by_cases h : p = 0; simp [h, order_eq_zero_iff] }
lemma apply_order_ne_zero (hp : p ≠ 0) : p p.order ≠ 0 :=
begin
classical,
let h := formal_multilinear_series.ne_iff.mp hp,
exact (order_eq_find h).symm ▸ nat.find_spec h
end
lemma apply_order_ne_zero' (hp : p.order ≠ 0) : p p.order ≠ 0 :=
apply_order_ne_zero (ne_zero_of_order_ne_zero hp)
lemma apply_eq_zero_of_lt_order (hp : n < p.order) : p n = 0 :=
begin
by_cases p = 0,
{ simp [h] },
{ classical,
rw [order_eq_find' h] at hp,
simpa using nat.find_min _ hp }
end
end order
section coef
variables [nontrivially_normed_field 𝕜]
[normed_add_comm_group E] [normed_space 𝕜 E] {s : E}
{p : formal_multilinear_series 𝕜 𝕜 E} {f : 𝕜 → E}
{n : ℕ} {z z₀ : 𝕜} {y : fin n → 𝕜}
open_locale big_operators
/-- The `n`th coefficient of `p` when seen as a power series. -/
def coeff (p : formal_multilinear_series 𝕜 𝕜 E) (n : ℕ) : E := p n 1
lemma mk_pi_field_coeff_eq (p : formal_multilinear_series 𝕜 𝕜 E) (n : ℕ) :
continuous_multilinear_map.mk_pi_field 𝕜 (fin n) (p.coeff n) = p n :=
(p n).mk_pi_field_apply_one_eq_self
@[simp] lemma apply_eq_prod_smul_coeff : p n y = (∏ i, y i) • p.coeff n :=
begin
convert (p n).to_multilinear_map.map_smul_univ y 1,
funext; simp only [pi.one_apply, algebra.id.smul_eq_mul, mul_one],
end
lemma coeff_eq_zero : p.coeff n = 0 ↔ p n = 0 :=
by rw [← mk_pi_field_coeff_eq p, continuous_multilinear_map.mk_pi_field_eq_zero_iff]
@[simp] lemma apply_eq_pow_smul_coeff : p n (λ _, z) = z ^ n • p.coeff n :=
by simp
@[simp] lemma norm_apply_eq_norm_coef : ‖p n‖ = ‖coeff p n‖ :=
by rw [← mk_pi_field_coeff_eq p, continuous_multilinear_map.norm_mk_pi_field]
end coef
section fslope
variables [nontrivially_normed_field 𝕜]
[normed_add_comm_group E] [normed_space 𝕜 E]
{p : formal_multilinear_series 𝕜 𝕜 E} {n : ℕ}
/-- The formal counterpart of `dslope`, corresponding to the expansion of `(f z - f 0) / z`. If `f`
has `p` as a power series, then `dslope f` has `fslope p` as a power series. -/
noncomputable def fslope (p : formal_multilinear_series 𝕜 𝕜 E) : formal_multilinear_series 𝕜 𝕜 E :=
λ n, (p (n + 1)).curry_left 1
@[simp] lemma coeff_fslope : p.fslope.coeff n = p.coeff (n + 1) :=
begin
have : @fin.cons n (λ _, 𝕜) 1 (1 : fin n → 𝕜) = 1 := fin.cons_self_tail 1,
simp only [fslope, coeff, continuous_multilinear_map.curry_left_apply, this],
end
@[simp] lemma coeff_iterate_fslope (k n : ℕ) :
(fslope^[k] p).coeff n = p.coeff (n + k) :=
by induction k with k ih generalizing p; refl <|> simpa [ih]
end fslope
end formal_multilinear_series
section const
/-- The formal multilinear series where all terms of positive degree are equal to zero, and the term
of degree zero is `c`. It is the power series expansion of the constant function equal to `c`
everywhere. -/
def const_formal_multilinear_series (𝕜 : Type*) [nontrivially_normed_field 𝕜]
(E : Type*) [normed_add_comm_group E] [normed_space 𝕜 E] [has_continuous_const_smul 𝕜 E]
[topological_add_group E] {F : Type*} [normed_add_comm_group F] [topological_add_group F]
[normed_space 𝕜 F] [has_continuous_const_smul 𝕜 F] (c : F) : formal_multilinear_series 𝕜 E F
| 0 := continuous_multilinear_map.curry0 _ _ c
| _ := 0
@[simp] lemma const_formal_multilinear_series_apply [nontrivially_normed_field 𝕜]
[normed_add_comm_group E] [normed_add_comm_group F] [normed_space 𝕜 E] [normed_space 𝕜 F]
{c : F} {n : ℕ} (hn : n ≠ 0) :
const_formal_multilinear_series 𝕜 E c n = 0 :=
nat.cases_on n (λ hn, (hn rfl).elim) (λ _ _, rfl) hn
end const
|
461b21ca06cd7724cc7fadb6111f8f2dbda28f34 | b24beef0a8b1a8e92be756a25aa78e24908b2b14 | /src/hints/thursday/afternoon/category_theory/exercise1/hint3.lean | 22e9c98b677f402fabb057f7a3cc198203353264 | [] | permissive | ChristopheMargerin/lftcm2020 | 14967e74cbe92a7b61d32d8130f32cfa09b5172b | 589180047fa4fdfb3179636db58b0b0320549871 | refs/heads/master | 1,668,536,269,632 | 1,594,891,664,000 | 1,594,891,664,000 | 280,112,730 | 0 | 0 | MIT | 1,594,891,963,000 | 1,594,891,962,000 | null | UTF-8 | Lean | false | false | 579 | lean | import category_theory.isomorphism
import category_theory.yoneda
open category_theory
open opposite
variables {C : Type*} [category C]
def iso_of_hom_iso_attempt (X Y : C) (h : yoneda.obj X ≅ yoneda.obj Y) : X ≅ Y :=
{ hom :=
begin
apply (h.app (op X)).hom,
exact 𝟙 X,
-- If you've haven't done this, you should now learn how to "golf" this proof
-- into a single line "term mode" proof.
end,
inv :=
begin
-- It's pretty similar the other way.
apply (h.app (op Y)).inv,
sorry
end,
hom_inv_id' := sorry,
inv_hom_id' := sorry, }
|
95b8523c7d09980669930151f50281d97cd23ba8 | 9b9a16fa2cb737daee6b2785474678b6fa91d6d4 | /src/order/filter/partial.lean | 776ace7b71330c6457689dabf1dbbbdbc9fd4179 | [
"Apache-2.0"
] | permissive | johoelzl/mathlib | 253f46daa30b644d011e8e119025b01ad69735c4 | 592e3c7a2dfbd5826919b4605559d35d4d75938f | refs/heads/master | 1,625,657,216,488 | 1,551,374,946,000 | 1,551,374,946,000 | 98,915,829 | 0 | 0 | Apache-2.0 | 1,522,917,267,000 | 1,501,524,499,000 | Lean | UTF-8 | Lean | false | false | 8,427 | lean | /-
Copyright (c) 2019 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad
Extends `tendsto` to relations and partial functions.
-/
import .basic
universes u v w
namespace filter
variables {α : Type u} {β : Type v} {γ : Type w}
/-
Relations.
-/
def rmap (r : rel α β) (f : filter α) : filter β :=
{ sets := r.core ⁻¹' f.sets,
univ_sets := by { simp [rel.core], apply univ_mem_sets },
sets_of_superset := assume s t hs st, mem_sets_of_superset hs $ rel.core_mono _ st,
inter_sets := by { simp [set.preimage, rel.core_inter], exact λ s t, inter_mem_sets } }
theorem rmap_sets (r : rel α β) (f : filter α) : (rmap r f).sets = r.core ⁻¹' f.sets := rfl
@[simp]
theorem mem_rmap (r : rel α β) (l : filter α) (s : set β) :
s ∈ (l.rmap r).sets ↔ r.core s ∈ l.sets :=
iff.refl _
@[simp]
theorem rmap_rmap (r : rel α β) (s : rel β γ) (l : filter α) :
rmap s (rmap r l) = rmap (r.comp s) l :=
filter_eq $
by simp [rmap_sets, set.preimage, rel.core_comp]
@[simp]
lemma rmap_compose (r : rel α β) (s : rel β γ) : rmap s ∘ rmap r = rmap (r.comp s) :=
funext $ rmap_rmap _ _
def rtendsto (r : rel α β) (l₁ : filter α) (l₂ : filter β) := l₁.rmap r ≤ l₂
theorem rtendsto_def (r : rel α β) (l₁ : filter α) (l₂ : filter β) :
rtendsto r l₁ l₂ ↔ ∀ s ∈ l₂.sets, r.core s ∈ l₁.sets :=
iff.refl _
def rcomap (r : rel α β) (f : filter β) : filter α :=
{ sets := rel.image (λ s t, r.core s ⊆ t) f.sets,
univ_sets := ⟨set.univ, univ_mem_sets, set.subset_univ _⟩,
sets_of_superset := assume a b ⟨a', ha', ma'a⟩ ab, ⟨a', ha', set.subset.trans ma'a ab⟩,
inter_sets := assume a b ⟨a', ha₁, ha₂⟩ ⟨b', hb₁, hb₂⟩,
⟨a' ∩ b', inter_mem_sets ha₁ hb₁,
set.subset.trans (by rw rel.core_inter)
(set.inter_subset_inter ha₂ hb₂)⟩ }
theorem rcomap_sets (r : rel α β) (f : filter β) :
(rcomap r f).sets = rel.image (λ s t, r.core s ⊆ t) f.sets := rfl
@[simp]
theorem rcomap_rcomap (r : rel α β) (s : rel β γ) (l : filter γ) :
rcomap r (rcomap s l) = rcomap (r.comp s) l :=
filter_eq $
begin
ext t, simp [rcomap_sets, rel.image, rel.core_comp], split,
{ rintros ⟨u, ⟨v, vsets, hv⟩, h⟩,
exact ⟨v, vsets, set.subset.trans (rel.core_mono _ hv) h⟩ },
rintros ⟨t, tsets, ht⟩,
exact ⟨rel.core s t, ⟨t, tsets, set.subset.refl _⟩, ht⟩
end
@[simp]
lemma rcomap_compose (r : rel α β) (s : rel β γ) : rcomap r ∘ rcomap s = rcomap (r.comp s) :=
funext $ rcomap_rcomap _ _
theorem rtendsto_iff_le_comap (r : rel α β) (l₁ : filter α) (l₂ : filter β) :
rtendsto r l₁ l₂ ↔ l₁ ≤ l₂.rcomap r :=
begin
rw rtendsto_def, simp [filter.le_def, rcomap, rel.mem_image], split,
intros h s t tl₂ h',
{ exact mem_sets_of_superset (h t tl₂) h' },
intros h t tl₂,
apply h _ t tl₂ (set.subset.refl _),
end
-- Interestingly, there does not seem to be a way to express this relation using a forward map.
-- Given a filter `f` on `α`, we want a filter `f'` on `β` such that `r.preimage s ∈ f.sets` if
-- and only if `s ∈ f'`. But the intersection of two sets satsifying the lhs may be empty.
def rcomap' (r : rel α β) (f : filter β) : filter α :=
{ sets := rel.image (λ s t, r.preimage s ⊆ t) f.sets,
univ_sets := ⟨set.univ, univ_mem_sets, set.subset_univ _⟩,
sets_of_superset := assume a b ⟨a', ha', ma'a⟩ ab, ⟨a', ha', set.subset.trans ma'a ab⟩,
inter_sets := assume a b ⟨a', ha₁, ha₂⟩ ⟨b', hb₁, hb₂⟩,
⟨a' ∩ b', inter_mem_sets ha₁ hb₁,
set.subset.trans (@rel.preimage_inter _ _ r _ _)
(set.inter_subset_inter ha₂ hb₂)⟩ }
@[simp]
def mem_rcomap' (r : rel α β) (l : filter β) (s : set α) :
s ∈ (l.rcomap' r).sets ↔ ∃ t ∈ l.sets, rel.preimage r t ⊆ s :=
iff.refl _
theorem rcomap'_sets (r : rel α β) (f : filter β) :
(rcomap' r f).sets = rel.image (λ s t, r.preimage s ⊆ t) f.sets := rfl
@[simp]
theorem rcomap'_rcomap' (r : rel α β) (s : rel β γ) (l : filter γ) :
rcomap' r (rcomap' s l) = rcomap' (r.comp s) l :=
filter_eq $
begin
ext t, simp [rcomap'_sets, rel.image, rel.preimage_comp], split,
{ rintros ⟨u, ⟨v, vsets, hv⟩, h⟩,
exact ⟨v, vsets, set.subset.trans (rel.preimage_mono _ hv) h⟩ },
rintros ⟨t, tsets, ht⟩,
exact ⟨rel.preimage s t, ⟨t, tsets, set.subset.refl _⟩, ht⟩
end
@[simp]
lemma rcomap'_compose (r : rel α β) (s : rel β γ) : rcomap' r ∘ rcomap' s = rcomap' (r.comp s) :=
funext $ rcomap'_rcomap' _ _
def rtendsto' (r : rel α β) (l₁ : filter α) (l₂ : filter β) := l₁ ≤ l₂.rcomap' r
theorem rtendsto'_def (r : rel α β) (l₁ : filter α) (l₂ : filter β) :
rtendsto' r l₁ l₂ ↔ ∀ s ∈ l₂.sets, r.preimage s ∈ l₁.sets :=
begin
unfold rtendsto', unfold rcomap', simp [le_def, rel.mem_image], split,
{ intros h s hs, apply (h _ _ hs (set.subset.refl _)) },
intros h s t ht h', apply mem_sets_of_superset (h t ht) h'
end
theorem tendsto_iff_rtendsto (l₁ : filter α) (l₂ : filter β) (f : α → β) :
tendsto f l₁ l₂ ↔ rtendsto (function.graph f) l₁ l₂ :=
by { simp [tendsto_def, function.graph, rtendsto_def, rel.core, set.preimage] }
theorem tendsto_iff_rtendsto' (l₁ : filter α) (l₂ : filter β) (f : α → β) :
tendsto f l₁ l₂ ↔ rtendsto' (function.graph f) l₁ l₂ :=
by { simp [tendsto_def, function.graph, rtendsto'_def, rel.preimage_def, set.preimage] }
/-
Partial functions.
-/
def pmap (f : α →. β) (l : filter α) : filter β :=
filter.rmap f.graph' l
@[simp]
def mem_pmap (f : α →. β) (l : filter α) (s : set β) : s ∈ (l.pmap f).sets ↔ f.core s ∈ l.sets :=
iff.refl _
def ptendsto (f : α →. β) (l₁ : filter α) (l₂ : filter β) := l₁.pmap f ≤ l₂
theorem ptendsto_def (f : α →. β) (l₁ : filter α) (l₂ : filter β) :
ptendsto f l₁ l₂ ↔ ∀ s ∈ l₂.sets, f.core s ∈ l₁.sets :=
iff.refl _
theorem ptendsto_iff_rtendsto (l₁ : filter α) (l₂ : filter β) (f : α →. β) :
ptendsto f l₁ l₂ ↔ rtendsto f.graph' l₁ l₂ :=
iff.refl _
theorem pmap_res (l : filter α) (s : set α) (f : α → β) :
pmap (pfun.res f s) l = map f (l ⊓ principal s) :=
filter_eq $
begin
apply set.ext, intro t, simp [pfun.core_res], split,
{ intro h, constructor, split, { exact h },
constructor, split, { reflexivity },
simp [set.inter_distrib_right], apply set.inter_subset_left },
rintro ⟨t₁, h₁, t₂, h₂, h₃⟩, apply mem_sets_of_superset h₁, rw ← set.inter_subset,
exact set.subset.trans (set.inter_subset_inter_right _ h₂) h₃
end
theorem tendsto_iff_ptendsto (l₁ : filter α) (l₂ : filter β) (s : set α) (f : α → β) :
tendsto f (l₁ ⊓ principal s) l₂ ↔ ptendsto (pfun.res f s) l₁ l₂ :=
by simp only [tendsto, ptendsto, pmap_res]
theorem tendsto_iff_ptendsto_univ (l₁ : filter α) (l₂ : filter β) (f : α → β) :
tendsto f l₁ l₂ ↔ ptendsto (pfun.res f set.univ) l₁ l₂ :=
by { rw ← tendsto_iff_ptendsto, simp [principal_univ] }
def pcomap' (f : α →. β) (l : filter β) : filter α :=
filter.rcomap' f.graph' l
def ptendsto' (f : α →. β) (l₁ : filter α) (l₂ : filter β) := l₁ ≤ l₂.rcomap' f.graph'
theorem ptendsto'_def (f : α →. β) (l₁ : filter α) (l₂ : filter β) :
ptendsto' f l₁ l₂ ↔ ∀ s ∈ l₂.sets, f.preimage s ∈ l₁.sets :=
rtendsto'_def _ _ _
theorem ptendsto_of_ptendsto' {f : α →. β} {l₁ : filter α} {l₂ : filter β} :
ptendsto' f l₁ l₂ → ptendsto f l₁ l₂ :=
begin
rw [ptendsto_def, ptendsto'_def],
assume h s sl₂,
exacts mem_sets_of_superset (h s sl₂) (pfun.preimage_subset_core _ _),
end
theorem ptendsto'_of_ptendsto {f : α →. β} {l₁ : filter α} {l₂ : filter β} (h : f.dom ∈ l₁.sets) :
ptendsto f l₁ l₂ → ptendsto' f l₁ l₂ :=
begin
rw [ptendsto_def, ptendsto'_def],
assume h' s sl₂,
rw pfun.preimage_eq,
show pfun.core f s ∩ pfun.dom f ∈ l₁.sets,
exact inter_mem_sets (h' s sl₂) h
end
end filter
|
e6b4397270e2ce03b669ac4cbe6becbd95875e84 | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/data/nat/multiplicity.lean | bbbc4bfc0b283d9692249d35ebb94a049af90570 | [
"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 | 11,148 | 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 data.nat.bitwise
import data.nat.parity
import data.nat.log
import ring_theory.int.basic
import algebra.big_operators.intervals
/-!
# Natural number multiplicity
This file contains lemmas about the multiplicity function
(the maximum prime power divding a number).
# Main results
There are natural number versions of some basic lemmas about multiplicity.
There are also lemmas about the multiplicity of primes in factorials and in binomial coefficients.
-/
open finset nat multiplicity
open_locale big_operators nat
namespace nat
/-- The multiplicity of a divisor `m` of `n`, is the cardinality of the set of
positive natural numbers `i` such that `p ^ i` divides `n`. The set is expressed
by filtering `Ico 1 b` where `b` is any bound greater than `log m n` -/
lemma multiplicity_eq_card_pow_dvd {m n b : ℕ} (hm1 : m ≠ 1) (hn0 : 0 < n) (hb : log m n < b):
multiplicity m n = ↑((finset.Ico 1 b).filter (λ i, m ^ i ∣ n)).card :=
calc multiplicity m n = ↑(Ico 1 $ ((multiplicity m n).get (finite_nat_iff.2 ⟨hm1, hn0⟩) + 1)).card :
by simp
... = ↑((finset.Ico 1 b).filter (λ i, m ^ i ∣ n)).card : congr_arg coe $ congr_arg card $
finset.ext $ λ i,
have hmn : ¬ m ^ (log m n).succ ∣ n,
from if hm0 : m = 0
then λ _, by cases n; simp [*, lt_irrefl, pow_succ'] at *
else mt (le_of_dvd hn0) (not_le_of_lt $ pow_succ_log_gt_self m n
(hm1.symm.le_iff_lt.mp (zero_lt_iff.mpr hm0.intro)) hn0),
⟨λ hi, begin
simp only [Ico.mem, mem_filter, lt_succ_iff] at *,
exact ⟨⟨hi.1, lt_of_le_of_lt hi.2 $
lt_of_lt_of_le (by rw [← enat.coe_lt_coe, enat.coe_get,
multiplicity_lt_iff_neg_dvd]; exact hmn)
hb⟩,
by rw [pow_dvd_iff_le_multiplicity];
rw [← @enat.coe_le_coe i, enat.coe_get] at hi; exact hi.2⟩
end,
begin
simp only [Ico.mem, mem_filter, lt_succ_iff, and_imp, true_and] { contextual := tt },
assume h1i hib hmin,
rwa [← enat.coe_le_coe, enat.coe_get, ← pow_dvd_iff_le_multiplicity]
end⟩
namespace prime
lemma multiplicity_one {p : ℕ} (hp : p.prime) : multiplicity p 1 = 0 :=
multiplicity.one_right (prime_iff.mp hp).not_unit
lemma multiplicity_mul {p m n : ℕ} (hp : p.prime) :
multiplicity p (m * n) = multiplicity p m + multiplicity p n :=
multiplicity.mul $ prime_iff.mp hp
lemma multiplicity_pow {p m n : ℕ} (hp : p.prime) :
multiplicity p (m ^ n) = n • (multiplicity p m) :=
multiplicity.pow $ prime_iff.mp hp
lemma multiplicity_self {p : ℕ} (hp : p.prime) : multiplicity p p = 1 :=
multiplicity_self (prime_iff.mp hp).not_unit hp.ne_zero
lemma multiplicity_pow_self {p n : ℕ} (hp : p.prime) : multiplicity p (p ^ n) = n :=
multiplicity_pow_self hp.ne_zero (prime_iff.mp hp).not_unit n
/-- The multiplicity of a prime in `n!` is the sum of the quotients `n / p ^ i`.
This sum is expressed over the set `Ico 1 b` where `b` is any bound greater than `log p n` -/
lemma multiplicity_factorial {p : ℕ} (hp : p.prime) :
∀ {n b : ℕ}, log p n < b → multiplicity p n! = (∑ i in Ico 1 b, n / p ^ i : ℕ)
| 0 b hb := by simp [Ico, hp.multiplicity_one]
| (n+1) b hb :=
calc multiplicity p (n+1)! = multiplicity p n! + multiplicity p (n+1) :
by rw [factorial_succ, hp.multiplicity_mul, add_comm]
... = (∑ i in Ico 1 b, n / p ^ i : ℕ) + ((finset.Ico 1 b).filter (λ i, p ^ i ∣ n+1)).card :
by rw [multiplicity_factorial (lt_of_le_of_lt log_le_log_succ hb),
← multiplicity_eq_card_pow_dvd (ne_of_gt hp.one_lt) (succ_pos _) hb]
... = (∑ i in Ico 1 b, (n / p ^ i + if p^i ∣ n+1 then 1 else 0) : ℕ) :
by rw [sum_add_distrib, sum_boole]; simp
... = (∑ i in Ico 1 b, (n + 1) / p ^ i : ℕ) :
congr_arg coe $ finset.sum_congr rfl (by intros; simp [nat.succ_div]; congr)
/-- The multiplicity of `p` in `(p(n+1))!` is one more than the sum
of the multiplicities of `p` in `(p * n)!` and `n + 1`. -/
lemma multiplicity_factorial_mul_succ {n p : ℕ} (hp : p.prime) :
multiplicity p (p * (n + 1))! = multiplicity p (p * n)! + multiplicity p (n + 1) + 1 :=
begin
have hp' := prime_iff.mp hp,
have h0 : 2 ≤ p := hp.two_le,
have h1 : 1 ≤ p * n + 1 := le_add_left _ _,
have h2 : p * n + 1 ≤ p * (n + 1), linarith,
have h3 : p * n + 1 ≤ p * (n + 1) + 1, linarith,
have hm : multiplicity p (p * n)! ≠ ⊤,
{ rw [ne.def, eq_top_iff_not_finite, not_not, finite_nat_iff],
exact ⟨hp.ne_one, factorial_pos _⟩ },
revert hm,
have h4 : ∀ m ∈ Ico (p * n + 1) (p * (n + 1)), multiplicity p m = 0,
{ intros m hm, apply multiplicity_eq_zero_of_not_dvd,
rw [← exists_lt_and_lt_iff_not_dvd _ (pos_iff_ne_zero.mpr hp.ne_zero)], rw [Ico.mem] at hm,
exact ⟨n, lt_of_succ_le hm.1, hm.2⟩ },
simp_rw [← prod_Ico_id_eq_factorial, multiplicity.finset.prod hp', ← sum_Ico_consecutive _ h1 h3,
add_assoc], intro h,
rw [enat.add_left_cancel_iff h, sum_Ico_succ_top h2, multiplicity.mul hp',
hp.multiplicity_self, sum_congr rfl h4, sum_const_zero, zero_add,
add_comm (1 : enat)]
end
/-- The multiplicity of `p` in `(pn)!` is `n` more than that of `n!`. -/
lemma multiplicity_factorial_mul {n p : ℕ} (hp : p.prime) :
multiplicity p (p * n)! = multiplicity p n! + n :=
begin
induction n with n ih,
{ simp },
{ simp only [succ_eq_add_one, multiplicity.mul, hp, prime_iff.mp hp, ih,
multiplicity_factorial_mul_succ, ←add_assoc, enat.coe_one, enat.coe_add, factorial_succ],
congr' 1,
rw [add_comm, add_assoc] }
end
/-- A prime power divides `n!` iff it is at most the sum of the quotients `n / p ^ i`.
This sum is expressed over the set `Ico 1 b` where `b` is any bound greater than `log p n` -/
lemma pow_dvd_factorial_iff {p : ℕ} {n r b : ℕ} (hp : p.prime) (hbn : log p n < b) :
p ^ r ∣ n! ↔ r ≤ ∑ i in Ico 1 b, n / p ^ i :=
by rw [← enat.coe_le_coe, ← hp.multiplicity_factorial hbn, ← pow_dvd_iff_le_multiplicity]
lemma multiplicity_choose_aux {p n b k : ℕ} (hp : p.prime) (hkn : k ≤ n) :
∑ i in finset.Ico 1 b, n / p ^ i =
∑ i in finset.Ico 1 b, k / p ^ i + ∑ i in finset.Ico 1 b, (n - k) / p ^ i +
((finset.Ico 1 b).filter (λ i, p ^ i ≤ k % p ^ i + (n - k) % p ^ i)).card :=
calc ∑ i in finset.Ico 1 b, n / p ^ i
= ∑ i in finset.Ico 1 b, (k + (n - k)) / p ^ i :
by simp only [nat.add_sub_cancel' hkn]
... = ∑ i in finset.Ico 1 b, (k / p ^ i + (n - k) / p ^ i +
if p ^ i ≤ k % p ^ i + (n - k) % p ^ i then 1 else 0) :
by simp only [nat.add_div (pow_pos hp.pos _)]
... = _ : by simp [sum_add_distrib, sum_boole]
/-- The multiplity of `p` in `choose n k` is the number of carries when `k` and `n - k`
are added in base `p`. The set is expressed by filtering `Ico 1 b` where `b`
is any bound greater than `log p n`. -/
lemma multiplicity_choose {p n k b : ℕ} (hp : p.prime) (hkn : k ≤ n) (hnb : log p n < b) :
multiplicity p (choose n k) =
((Ico 1 b).filter (λ i, p ^ i ≤ k % p ^ i + (n - k) % p ^ i)).card :=
have h₁ : multiplicity p (choose n k) + multiplicity p (k! * (n - k)!) =
((finset.Ico 1 b).filter (λ i, p ^ i ≤ k % p ^ i + (n - k) % p ^ i)).card +
multiplicity p (k! * (n - k)!),
begin
rw [← hp.multiplicity_mul, ← mul_assoc, choose_mul_factorial_mul_factorial hkn,
hp.multiplicity_factorial hnb, hp.multiplicity_mul,
hp.multiplicity_factorial ((log_le_log_of_le hkn).trans_lt hnb),
hp.multiplicity_factorial (lt_of_le_of_lt (log_le_log_of_le (nat.sub_le_self _ _)) hnb),
multiplicity_choose_aux hp hkn],
simp [add_comm],
end,
(enat.add_right_cancel_iff
(enat.ne_top_iff_dom.2 $
by exact finite_nat_iff.2
⟨ne_of_gt hp.one_lt, mul_pos (factorial_pos k) (factorial_pos (n - k))⟩)).1
h₁
/-- A lower bound on the multiplicity of `p` in `choose n k`. -/
lemma multiplicity_le_multiplicity_choose_add {p : ℕ} (hp : p.prime) (n k : ℕ) :
multiplicity p n ≤ multiplicity p (choose n k) + multiplicity p k :=
if hkn : n < k then by simp [choose_eq_zero_of_lt hkn]
else if hk0 : k = 0 then by simp [hk0]
else if hn0 : n = 0 then by cases k; simp [hn0, *] at *
else begin
rw [multiplicity_choose hp (le_of_not_gt hkn) (lt_succ_self _),
multiplicity_eq_card_pow_dvd (ne_of_gt hp.one_lt) (nat.pos_of_ne_zero hk0)
(lt_succ_of_le (log_le_log_of_le (le_of_not_gt hkn))),
multiplicity_eq_card_pow_dvd (ne_of_gt hp.one_lt) (nat.pos_of_ne_zero hn0) (lt_succ_self _),
← enat.coe_add, enat.coe_le_coe],
calc ((Ico 1 (log p n).succ).filter (λ i, p ^ i ∣ n)).card
≤ ((Ico 1 (log p n).succ).filter (λ i, p ^ i ≤ k % p ^ i + (n - k) % p ^ i) ∪
(Ico 1 (log p n).succ).filter (λ i, p ^ i ∣ k) ).card :
card_le_of_subset $ λ i, begin
have := @le_mod_add_mod_of_dvd_add_of_not_dvd k (n - k) (p ^ i),
simp [nat.add_sub_cancel' (le_of_not_gt hkn)] at * {contextual := tt},
tauto
end
... ≤ ((Ico 1 (log p n).succ).filter (λ i, p ^ i ≤ k % p ^ i + (n - k) % p ^ i)).card +
((Ico 1 (log p n).succ).filter (λ i, p ^ i ∣ k)).card :
card_union_le _ _
end
lemma multiplicity_choose_prime_pow {p n k : ℕ} (hp : p.prime)
(hkn : k ≤ p ^ n) (hk0 : 0 < k) :
multiplicity p (choose (p ^ n) k) + multiplicity p k = n :=
le_antisymm
(have hdisj : disjoint
((Ico 1 n.succ).filter (λ i, p ^ i ≤ k % p ^ i + (p ^ n - k) % p ^ i))
((Ico 1 n.succ).filter (λ i, p ^ i ∣ k)),
by simp [disjoint_right, *, dvd_iff_mod_eq_zero, nat.mod_lt _ (pow_pos hp.pos _)]
{contextual := tt},
begin
rw [multiplicity_choose hp hkn (lt_succ_self _),
multiplicity_eq_card_pow_dvd (ne_of_gt hp.one_lt) hk0
(lt_succ_of_le (log_le_log_of_le hkn)),
← enat.coe_add, enat.coe_le_coe, log_pow _ _ hp.one_lt,
← card_disjoint_union hdisj, filter_union_right],
have filter_le_Ico := (Ico 1 n.succ).card_filter_le _,
rwa Ico.card 1 n.succ at filter_le_Ico,
end)
(by rw [← hp.multiplicity_pow_self];
exact multiplicity_le_multiplicity_choose_add hp _ _)
end prime
lemma multiplicity_two_factorial_lt : ∀ {n : ℕ} (h : n ≠ 0), multiplicity 2 n! < n :=
begin
have h2 := prime_iff.mp prime_two,
refine binary_rec _ _,
{ contradiction },
{ intros b n ih h,
by_cases hn : n = 0,
{ subst hn, simp at h, simp [h, one_right h2.not_unit, enat.zero_lt_one] },
have : multiplicity 2 (2 * n)! < (2 * n : ℕ),
{ rw [prime_two.multiplicity_factorial_mul],
refine (enat.add_lt_add_right (ih hn) (enat.coe_ne_top _)).trans_le _,
rw [two_mul], norm_cast },
cases b,
{ simpa [bit0_eq_two_mul n] },
{ suffices : multiplicity 2 (2 * n + 1) + multiplicity 2 (2 * n)! < ↑(2 * n) + 1,
{ simpa [succ_eq_add_one, multiplicity.mul, h2, prime_two, nat.bit1_eq_succ_bit0,
bit0_eq_two_mul n] },
rw [multiplicity_eq_zero_of_not_dvd (two_not_dvd_two_mul_add_one n), zero_add],
refine this.trans _, exact_mod_cast lt_succ_self _ }}
end
end nat
|
eb26be5c5c9d82b75160775d0579f1567f574154 | 130c49f47783503e462c16b2eff31933442be6ff | /stage0/src/Lean/Meta/PPGoal.lean | 8e981cd5ddc22f6869d45f47ad1763980a9d52eb | [
"Apache-2.0"
] | permissive | Hazel-Brown/lean4 | 8aa5860e282435ffc30dcdfccd34006c59d1d39c | 79e6732fc6bbf5af831b76f310f9c488d44e7a16 | refs/heads/master | 1,689,218,208,951 | 1,629,736,869,000 | 1,629,736,896,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 9,302 | lean | /-
Copyright (c) 2020 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
-/
import Lean.Meta.InferType
namespace Lean.Meta
register_builtin_option pp.auxDecls : Bool := {
defValue := false
group := "pp"
descr := "display auxiliary declarations used to compile recursive functions"
}
register_builtin_option pp.inaccessibleNames : Bool := {
defValue := false
group := "pp"
descr := "display inaccessible declarations in the local context"
}
def withPPInaccessibleNamesImp (flag : Bool) (x : MetaM α) : MetaM α :=
withTheReader Core.Context (fun ctx => { ctx with options := pp.inaccessibleNames.setIfNotSet ctx.options flag }) x
def withPPInaccessibleNames [MonadControlT MetaM m] [Monad m] (x : m α) (flag := true) : m α :=
mapMetaM (withPPInaccessibleNamesImp flag) x
namespace ToHide
structure State where
hiddenInaccessibleProp : NameSet := {} -- FVarIds of Propostions with inaccessible names but containing only visible names. We show only their types
hiddenInaccessible : NameSet := {} -- FVarIds with inaccessible names, but not in hiddenInaccessibleProp
modified : Bool := false
structure Context where
goalTarget : Expr
abbrev M := ReaderT Context $ StateRefT State MetaM
/- Return true if `fvarId` is marked as an hidden inaccessible or inaccessible proposition -/
def isMarked (fvarId : FVarId) : M Bool := do
let s ← get
return s.hiddenInaccessible.contains fvarId || s.hiddenInaccessibleProp.contains fvarId
/- If `fvarId` isMarked, then unmark it. -/
def unmark (fvarId : FVarId) : M Unit := do
modify fun s => {
hiddenInaccessible := s.hiddenInaccessible.erase fvarId
hiddenInaccessibleProp := s.hiddenInaccessibleProp.erase fvarId
modified := true
}
def moveToHiddeProp (fvarId : FVarId) : M Unit := do
modify fun s => {
hiddenInaccessible := s.hiddenInaccessible.erase fvarId
hiddenInaccessibleProp := s.hiddenInaccessibleProp.insert fvarId
modified := true
}
/- Return true if the given local declaration has a "visible dependency", that is, it contains
a free variable that is `hiddenInaccessible`
Recall that hiddenInaccessibleProps are visible, only their names are hidden -/
def hasVisibleDep (localDecl : LocalDecl) : M Bool := do
let s ← get
return (← getMCtx).findLocalDeclDependsOn localDecl fun fvarId =>
!s.hiddenInaccessible.contains fvarId
/- Return true if the given local declaration has a "nonvisible dependency", that is, it contains
a free variable that is `hiddenInaccessible` or `hiddenInaccessibleProp` -/
def hasInaccessibleNameDep (localDecl : LocalDecl) : M Bool := do
let s ← get
return (← getMCtx).findLocalDeclDependsOn localDecl fun fvarId =>
s.hiddenInaccessible.contains fvarId || s.hiddenInaccessibleProp.contains fvarId
/- If `e` is visible, then any inaccessible in `e` marked as hidden should be unmarked. -/
partial def visitVisibleExpr (e : Expr) : M Unit := do
visit (← instantiateMVars e) |>.run
where
visit (e : Expr) : MonadCacheT Expr Unit M Unit := do
if e.hasFVar then
checkCache e fun _ => do
match e with
| Expr.forallE _ d b _ => visit d; visit b
| Expr.lam _ d b _ => visit d; visit b
| Expr.letE _ t v b _ => visit t; visit v; visit b
| Expr.app f a _ => visit f; visit a
| Expr.mdata _ b _ => visit b
| Expr.proj _ _ b _ => visit b
| Expr.fvar fvarId _ => if (← isMarked fvarId) then unmark fvarId
| _ => pure ()
def fixpointStep : M Unit := do
visitVisibleExpr (← read).goalTarget -- The goal target is a visible forward dependency
(← getLCtx).forM fun localDecl => do
let fvarId := localDecl.fvarId
if (← get).hiddenInaccessible.contains fvarId then
if (← hasVisibleDep localDecl) then
/- localDecl is marked to be hidden, but it has a (backward) visible dependency. -/
unmark fvarId
if (← isProp localDecl.type) then
unless (← hasInaccessibleNameDep localDecl) do
moveToHiddeProp fvarId
else
visitVisibleExpr localDecl.type
match localDecl.value? with
| some value => visitVisibleExpr value
| _ => pure ()
partial def fixpoint : M Unit := do
modify fun s => { s with modified := false }
fixpointStep
if (← get).modified then
fixpoint
/-
If pp.inaccessibleNames == false, then collect two sets of `FVarId`s : `hiddenInaccessible` and `hiddenInaccessibleProp`
1- `hiddenInaccessible` contains `FVarId`s of free variables with inaccessible names that
a) are not propositions or are propositions containing "visible" names.
2- `hiddenInaccessibleProp` contains `FVarId`s of free variables with inaccessible names that are propositions
containing "visible" names.
Both sets do not contain `FVarId`s that contain visible backward or forward dependencies.
The `goalTarget` counts as a forward dependency.
We say a name is visible if it is a free variable with FVarId not in `hiddenInaccessible` nor `hiddenInaccessibleProp`
-/
def collect (goalTarget : Expr) : MetaM (NameSet × NameSet) := do
if pp.inaccessibleNames.get (← getOptions) then
/- Don't hide inaccessible names when `pp.inaccessibleNames` is set to true. -/
return ({}, {})
else
let lctx ← getLCtx
let hiddenInaccessible := lctx.foldl (init := {}) fun hiddenInaccessible localDecl => do
if localDecl.userName.isInaccessibleUserName then
hiddenInaccessible.insert localDecl.fvarId
else
hiddenInaccessible
let (_, s) ← fixpoint.run { goalTarget := goalTarget } |>.run { hiddenInaccessible := hiddenInaccessible }
return (s.hiddenInaccessible, s.hiddenInaccessibleProp)
end ToHide
private def addLine (fmt : Format) : Format :=
if fmt.isNil then fmt else fmt ++ Format.line
def ppGoal (mvarId : MVarId) : MetaM Format := do
match (← getMCtx).findDecl? mvarId with
| none => pure "unknown goal"
| some mvarDecl => do
let indent := 2 -- Use option
let ppAuxDecls := pp.auxDecls.get (← getOptions)
let lctx := mvarDecl.lctx
let lctx := lctx.sanitizeNames.run' { options := (← getOptions) }
withLCtx lctx mvarDecl.localInstances do
let (hidden, hiddenProp) ← ToHide.collect mvarDecl.type
-- The followint two `let rec`s are being used to control the generated code size.
-- Then should be remove after we rewrite the compiler in Lean
let rec pushPending (ids : List Name) (type? : Option Expr) (fmt : Format) : MetaM Format :=
if ids.isEmpty then
pure fmt
else
let fmt := addLine fmt
match ids, type? with
| [], _ => pure fmt
| _, none => pure fmt
| _, some type => do
let typeFmt ← ppExpr type
pure $ fmt ++ (Format.joinSep ids.reverse (format " ") ++ " :" ++ Format.nest indent (Format.line ++ typeFmt)).group
let rec ppVars (varNames : List Name) (prevType? : Option Expr) (fmt : Format) (localDecl : LocalDecl) : MetaM (List Name × Option Expr × Format) := do
if hiddenProp.contains localDecl.fvarId then
let fmt ← pushPending varNames prevType? fmt
let fmt := addLine fmt
let type ← instantiateMVars localDecl.type
let typeFmt ← ppExpr type
let fmt := fmt ++ " : " ++ typeFmt
pure ([], none, fmt)
else
match localDecl with
| LocalDecl.cdecl _ _ varName type _ =>
let varName := varName.simpMacroScopes
let type ← instantiateMVars type
if prevType? == none || prevType? == some type then
pure (varName :: varNames, some type, fmt)
else do
let fmt ← pushPending varNames prevType? fmt
pure ([varName], some type, fmt)
| LocalDecl.ldecl _ _ varName type val _ => do
let varName := varName.simpMacroScopes
let fmt ← pushPending varNames prevType? fmt
let fmt := addLine fmt
let type ← instantiateMVars type
let val ← instantiateMVars val
let typeFmt ← ppExpr type
let valFmt ← ppExpr val
let fmt := fmt ++ (format varName ++ " : " ++ typeFmt ++ " :=" ++ Format.nest indent (Format.line ++ valFmt)).group
pure ([], none, fmt)
let (varNames, type?, fmt) ← lctx.foldlM (init := ([], none, Format.nil)) fun (varNames, prevType?, fmt) (localDecl : LocalDecl) =>
if !ppAuxDecls && localDecl.isAuxDecl || hidden.contains localDecl.fvarId then
pure (varNames, prevType?, fmt)
else
ppVars varNames prevType? fmt localDecl
let fmt ← pushPending varNames type? fmt
let fmt := addLine fmt
let typeFmt ← ppExpr mvarDecl.type
let fmt := fmt ++ "⊢" ++ " " ++ Format.nest indent typeFmt
match mvarDecl.userName with
| Name.anonymous => pure fmt
| name => return "case " ++ format name.eraseMacroScopes ++ Format.line ++ fmt
end Lean.Meta
|
42a46e88d722207b5ba42b52cb92445e6c98e354 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/topology/category/Top/basic.lean | e8ad26812fb9773351d1e4ea81370656653acc7e | [] | 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,049 | lean | /-
Copyright (c) 2017 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Patrick Massot, Scott Morrison, Mario Carneiro
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.category_theory.concrete_category.unbundled_hom
import Mathlib.topology.continuous_map
import Mathlib.topology.opens
import Mathlib.PostPort
universes u u_1
namespace Mathlib
/-- The category of topological spaces and continuous maps. -/
def Top :=
category_theory.bundled topological_space
namespace Top
protected instance bundled_hom : category_theory.bundled_hom continuous_map :=
category_theory.bundled_hom.mk continuous_map.to_fun continuous_map.id continuous_map.comp
protected instance has_coe_to_sort : has_coe_to_sort Top :=
category_theory.bundled.has_coe_to_sort
protected instance topological_space_unbundled (x : Top) : topological_space ↥x :=
category_theory.bundled.str x
@[simp] theorem id_app (X : Top) (x : ↥X) : coe_fn 𝟙 x = x :=
rfl
@[simp] theorem comp_app {X : Top} {Y : Top} {Z : Top} (f : X ⟶ Y) (g : Y ⟶ Z) (x : ↥X) : coe_fn (f ≫ g) x = coe_fn g (coe_fn f x) :=
rfl
/-- Construct a bundled `Top` from the underlying type and the typeclass. -/
def of (X : Type u) [topological_space X] : Top :=
category_theory.bundled.mk X
protected instance topological_space (X : Top) : topological_space ↥X :=
category_theory.bundled.str X
@[simp] theorem coe_of (X : Type u) [topological_space X] : ↥(of X) = X :=
rfl
protected instance inhabited : Inhabited Top :=
{ default := of empty }
/-- The discrete topology on any type. -/
def discrete : Type u ⥤ Top :=
category_theory.functor.mk (fun (X : Type u) => category_theory.bundled.mk X)
fun (X Y : Type u) (f : X ⟶ Y) => continuous_map.mk f
/-- The trivial topology on any type. -/
def trivial : Type u ⥤ Top :=
category_theory.functor.mk (fun (X : Type u) => category_theory.bundled.mk X)
fun (X Y : Type u) (f : X ⟶ Y) => continuous_map.mk f
|
3df6fd542a1cd4055d6b9d746f2e8ecae19dca3a | 80cc5bf14c8ea85ff340d1d747a127dcadeb966f | /src/set_theory/cardinal.lean | 3a94ffc0e2b52bb64cb64eb89efa4bf8515ba78e | [
"Apache-2.0"
] | permissive | lacker/mathlib | f2439c743c4f8eb413ec589430c82d0f73b2d539 | ddf7563ac69d42cfa4a1bfe41db1fed521bd795f | refs/heads/master | 1,671,948,326,773 | 1,601,479,268,000 | 1,601,479,268,000 | 298,686,743 | 0 | 0 | Apache-2.0 | 1,601,070,794,000 | 1,601,070,794,000 | null | UTF-8 | Lean | false | false | 46,601 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Johannes Hölzl, Mario Carneiro
-/
import data.set.countable
import set_theory.schroeder_bernstein
import data.fintype.card
/-!
# Cardinal Numbers
We define cardinal numbers as a quotient of types under the equivalence relation of equinumerity.
We define the order on cardinal numbers, define omega, and do basic cardinal arithmetic:
addition, multiplication, power, cardinal successor, minimum, supremum,
infinitary sums and products
The fact that the cardinality of `α × α` coincides with that of `α` when `α` is infinite is not
proved in this file, as it relies on facts on well-orders. Instead, it is in
`cardinal_ordinal.lean` (together with many other facts on cardinals, for instance the
cardinality of `list α`).
## Implementation notes
* There is a type of cardinal numbers in every universe level: `cardinal.{u} : Type (u + 1)`
is the quotient of types in `Type u`.
There is a lift operation lifting cardinal numbers to a higher level.
* Cardinal arithmetic specifically for infinite cardinals (like `κ * κ = κ`) is in the file
`set_theory/ordinal.lean`, because concepts from that file are used in the proof.
## References
* <https://en.wikipedia.org/wiki/Cardinal_number>
## Tags
cardinal number, cardinal arithmetic, cardinal exponentiation, omega
-/
open function set
open_locale classical
universes u v w x
variables {α β : Type u}
/-- The equivalence relation on types given by equivalence (bijective correspondence) of types.
Quotienting by this equivalence relation gives the cardinal numbers.
-/
instance cardinal.is_equivalent : setoid (Type u) :=
{ r := λα β, nonempty (α ≃ β),
iseqv := ⟨λα,
⟨equiv.refl α⟩,
λα β ⟨e⟩, ⟨e.symm⟩,
λα β γ ⟨e₁⟩ ⟨e₂⟩, ⟨e₁.trans e₂⟩⟩ }
/-- `cardinal.{u}` is the type of cardinal numbers in `Type u`,
defined as the quotient of `Type u` by existence of an equivalence
(a bijection with explicit inverse). -/
def cardinal : Type (u + 1) := quotient cardinal.is_equivalent
namespace cardinal
/-- The cardinal number of a type -/
def mk : Type u → cardinal := quotient.mk
localized "notation `#` := cardinal.mk" in cardinal
protected lemma eq : mk α = mk β ↔ nonempty (α ≃ β) := quotient.eq
@[simp] theorem mk_def (α : Type u) : @eq cardinal ⟦α⟧ (mk α) := rfl
@[simp] theorem mk_out (c : cardinal) : mk (c.out) = c := quotient.out_eq _
/-- We define the order on cardinal numbers by `mk α ≤ mk β` if and only if
there exists an embedding (injective function) from α to β. -/
instance : has_le cardinal.{u} :=
⟨λq₁ q₂, quotient.lift_on₂ q₁ q₂ (λα β, nonempty $ α ↪ β) $
assume α β γ δ ⟨e₁⟩ ⟨e₂⟩,
propext ⟨assume ⟨e⟩, ⟨e.congr e₁ e₂⟩, assume ⟨e⟩, ⟨e.congr e₁.symm e₂.symm⟩⟩⟩
theorem mk_le_of_injective {α β : Type u} {f : α → β} (hf : injective f) : mk α ≤ mk β :=
⟨⟨f, hf⟩⟩
theorem mk_le_of_surjective {α β : Type u} {f : α → β} (hf : surjective f) : mk β ≤ mk α :=
⟨embedding.of_surjective f hf⟩
theorem le_mk_iff_exists_set {c : cardinal} {α : Type u} :
c ≤ mk α ↔ ∃ p : set α, mk p = c :=
⟨quotient.induction_on c $ λ β ⟨⟨f, hf⟩⟩,
⟨set.range f, eq.symm $ quot.sound ⟨equiv.set.range f hf⟩⟩,
λ ⟨p, e⟩, e ▸ ⟨⟨subtype.val, λ a b, subtype.eq⟩⟩⟩
theorem out_embedding {c c' : cardinal} : c ≤ c' ↔ nonempty (c.out ↪ c'.out) :=
by { transitivity _, rw [←quotient.out_eq c, ←quotient.out_eq c'], refl }
instance : linear_order cardinal.{u} :=
{ le := (≤),
le_refl := by rintros ⟨α⟩; exact ⟨embedding.refl _⟩,
le_trans := by rintros ⟨α⟩ ⟨β⟩ ⟨γ⟩ ⟨e₁⟩ ⟨e₂⟩; exact ⟨e₁.trans e₂⟩,
le_antisymm := by rintros ⟨α⟩ ⟨β⟩ ⟨e₁⟩ ⟨e₂⟩; exact quotient.sound (e₁.antisymm e₂),
le_total := by rintros ⟨α⟩ ⟨β⟩; exact embedding.total }
noncomputable instance : decidable_linear_order cardinal.{u} := classical.DLO _
noncomputable instance : distrib_lattice cardinal.{u} := by apply_instance -- short-circuit type class inference
instance : has_zero cardinal.{u} := ⟨⟦pempty⟧⟩
instance : inhabited cardinal.{u} := ⟨0⟩
theorem ne_zero_iff_nonempty {α : Type u} : mk α ≠ 0 ↔ nonempty α :=
not_iff_comm.1
⟨λ h, quotient.sound ⟨(equiv.empty_of_not_nonempty h).trans equiv.empty_equiv_pempty⟩,
λ e, let ⟨h⟩ := quotient.exact e in λ ⟨a⟩, (h a).elim⟩
instance : has_one cardinal.{u} := ⟨⟦punit⟧⟩
instance : nontrivial cardinal.{u} :=
⟨⟨1, 0, ne_zero_iff_nonempty.2 ⟨punit.star⟩⟩⟩
theorem le_one_iff_subsingleton {α : Type u} : mk α ≤ 1 ↔ subsingleton α :=
⟨λ ⟨f⟩, ⟨λ a b, f.injective (subsingleton.elim _ _)⟩,
λ ⟨h⟩, ⟨⟨λ a, punit.star, λ a b _, h _ _⟩⟩⟩
theorem one_lt_iff_nontrivial {α : Type u} : 1 < mk α ↔ nontrivial α :=
by { rw [← not_iff_not, not_nontrivial_iff_subsingleton, ← le_one_iff_subsingleton], simp }
instance : has_add cardinal.{u} :=
⟨λq₁ q₂, quotient.lift_on₂ q₁ q₂ (λα β, mk (α ⊕ β)) $ assume α β γ δ ⟨e₁⟩ ⟨e₂⟩,
quotient.sound ⟨equiv.sum_congr e₁ e₂⟩⟩
@[simp] theorem add_def (α β) : mk α + mk β = mk (α ⊕ β) := rfl
instance : has_mul cardinal.{u} :=
⟨λq₁ q₂, quotient.lift_on₂ q₁ q₂ (λα β, mk (α × β)) $ assume α β γ δ ⟨e₁⟩ ⟨e₂⟩,
quotient.sound ⟨equiv.prod_congr e₁ e₂⟩⟩
@[simp] theorem mul_def (α β : Type u) : mk α * mk β = mk (α × β) := rfl
private theorem add_comm (a b : cardinal.{u}) : a + b = b + a :=
quotient.induction_on₂ a b $ assume α β, quotient.sound ⟨equiv.sum_comm α β⟩
private theorem mul_comm (a b : cardinal.{u}) : a * b = b * a :=
quotient.induction_on₂ a b $ assume α β, quotient.sound ⟨equiv.prod_comm α β⟩
private theorem zero_add (a : cardinal.{u}) : 0 + a = a :=
quotient.induction_on a $ assume α, quotient.sound ⟨equiv.pempty_sum α⟩
private theorem zero_mul (a : cardinal.{u}) : 0 * a = 0 :=
quotient.induction_on a $ assume α, quotient.sound ⟨equiv.pempty_prod α⟩
private theorem one_mul (a : cardinal.{u}) : 1 * a = a :=
quotient.induction_on a $ assume α, quotient.sound ⟨equiv.punit_prod α⟩
private theorem left_distrib (a b c : cardinal.{u}) : a * (b + c) = a * b + a * c :=
quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.prod_sum_distrib α β γ⟩
instance : comm_semiring cardinal.{u} :=
{ zero := 0,
one := 1,
add := (+),
mul := (*),
zero_add := zero_add,
add_zero := assume a, by rw [add_comm a 0, zero_add a],
add_assoc := λa b c, quotient.induction_on₃ a b c $ assume α β γ,
quotient.sound ⟨equiv.sum_assoc α β γ⟩,
add_comm := add_comm,
zero_mul := zero_mul,
mul_zero := assume a, by rw [mul_comm a 0, zero_mul a],
one_mul := one_mul,
mul_one := assume a, by rw [mul_comm a 1, one_mul a],
mul_assoc := λa b c, quotient.induction_on₃ a b c $ assume α β γ,
quotient.sound ⟨equiv.prod_assoc α β γ⟩,
mul_comm := mul_comm,
left_distrib := left_distrib,
right_distrib := assume a b c,
by rw [mul_comm (a + b) c, left_distrib c a b, mul_comm c a, mul_comm c b] }
/-- The cardinal exponential. `mk α ^ mk β` is the cardinal of `β → α`. -/
protected def power (a b : cardinal.{u}) : cardinal.{u} :=
quotient.lift_on₂ a b (λα β, mk (β → α)) $ assume α₁ α₂ β₁ β₂ ⟨e₁⟩ ⟨e₂⟩,
quotient.sound ⟨equiv.arrow_congr e₂ e₁⟩
instance : has_pow cardinal cardinal := ⟨cardinal.power⟩
local infixr ^ := @has_pow.pow cardinal cardinal cardinal.has_pow
@[simp] theorem power_def (α β) : mk α ^ mk β = mk (β → α) := rfl
@[simp] theorem power_zero {a : cardinal} : a ^ 0 = 1 :=
quotient.induction_on a $ assume α, quotient.sound
⟨equiv.pempty_arrow_equiv_punit α⟩
@[simp] theorem power_one {a : cardinal} : a ^ 1 = a :=
quotient.induction_on a $ assume α, quotient.sound
⟨equiv.punit_arrow_equiv α⟩
@[simp] theorem one_power {a : cardinal} : 1 ^ a = 1 :=
quotient.induction_on a $ assume α, quotient.sound
⟨equiv.arrow_punit_equiv_punit α⟩
@[simp] theorem prop_eq_two : mk (ulift Prop) = 2 :=
quot.sound ⟨equiv.ulift.trans $ equiv.Prop_equiv_bool.trans equiv.bool_equiv_punit_sum_punit⟩
@[simp] theorem zero_power {a : cardinal} : a ≠ 0 → 0 ^ a = 0 :=
quotient.induction_on a $ assume α heq,
nonempty.rec_on (ne_zero_iff_nonempty.1 heq) $ assume a,
quotient.sound ⟨equiv.equiv_pempty $ assume f, pempty.rec (λ _, false) (f a)⟩
theorem power_ne_zero {a : cardinal} (b) : a ≠ 0 → a ^ b ≠ 0 :=
quotient.induction_on₂ a b $ λ α β h,
let ⟨a⟩ := ne_zero_iff_nonempty.1 h in
ne_zero_iff_nonempty.2 ⟨λ _, a⟩
theorem mul_power {a b c : cardinal} : (a * b) ^ c = a ^ c * b ^ c :=
quotient.induction_on₃ a b c $ assume α β γ,
quotient.sound ⟨equiv.arrow_prod_equiv_prod_arrow α β γ⟩
theorem power_add {a b c : cardinal} : a ^ (b + c) = a ^ b * a ^ c :=
quotient.induction_on₃ a b c $ assume α β γ,
quotient.sound ⟨equiv.sum_arrow_equiv_prod_arrow β γ α⟩
theorem power_mul {a b c : cardinal} : (a ^ b) ^ c = a ^ (b * c) :=
by rw [_root_.mul_comm b c];
from (quotient.induction_on₃ a b c $ assume α β γ,
quotient.sound ⟨equiv.arrow_arrow_equiv_prod_arrow γ β α⟩)
@[simp] lemma pow_cast_right (κ : cardinal.{u}) :
∀ n : ℕ, (κ ^ (↑n : cardinal.{u})) = @has_pow.pow _ _ monoid.has_pow κ n
| 0 := by simp
| (_+1) := by rw [nat.cast_succ, power_add, power_one, _root_.mul_comm, pow_succ, pow_cast_right]
section order_properties
open sum
theorem zero_le : ∀(a : cardinal), 0 ≤ a :=
by rintro ⟨α⟩; exact ⟨embedding.of_not_nonempty $ λ ⟨a⟩, a.elim⟩
theorem le_zero (a : cardinal) : a ≤ 0 ↔ a = 0 :=
by simp [le_antisymm_iff, zero_le]
theorem pos_iff_ne_zero {o : cardinal} : 0 < o ↔ o ≠ 0 :=
by simp [lt_iff_le_and_ne, eq_comm, zero_le]
@[simp] theorem zero_lt_one : (0 : cardinal) < 1 :=
lt_of_le_of_ne (zero_le _) zero_ne_one
lemma zero_power_le (c : cardinal.{u}) : (0 : cardinal.{u}) ^ c ≤ 1 :=
by { by_cases h : c = 0, rw [h, power_zero], rw [zero_power h], apply zero_le }
theorem add_le_add : ∀{a b c d : cardinal}, a ≤ b → c ≤ d → a + c ≤ b + d :=
by rintros ⟨α⟩ ⟨β⟩ ⟨γ⟩ ⟨δ⟩ ⟨e₁⟩ ⟨e₂⟩; exact ⟨e₁.sum_map e₂⟩
theorem add_le_add_left (a) {b c : cardinal} : b ≤ c → a + b ≤ a + c :=
add_le_add (le_refl _)
theorem add_le_add_right {a b : cardinal} (c) (h : a ≤ b) : a + c ≤ b + c :=
add_le_add h (le_refl _)
theorem le_add_right (a b : cardinal) : a ≤ a + b :=
by simpa using add_le_add_left a (zero_le b)
theorem le_add_left (a b : cardinal) : a ≤ b + a :=
by simpa using add_le_add_right a (zero_le b)
theorem mul_le_mul : ∀{a b c d : cardinal}, a ≤ b → c ≤ d → a * c ≤ b * d :=
by rintros ⟨α⟩ ⟨β⟩ ⟨γ⟩ ⟨δ⟩ ⟨e₁⟩ ⟨e₂⟩; exact ⟨e₁.prod_map e₂⟩
theorem mul_le_mul_left (a) {b c : cardinal} : b ≤ c → a * b ≤ a * c :=
mul_le_mul (le_refl _)
theorem mul_le_mul_right {a b : cardinal} (c) (h : a ≤ b) : a * c ≤ b * c :=
mul_le_mul h (le_refl _)
theorem power_le_power_left : ∀{a b c : cardinal}, a ≠ 0 → b ≤ c → a ^ b ≤ a ^ c :=
by rintros ⟨α⟩ ⟨β⟩ ⟨γ⟩ hα ⟨e⟩; exact
let ⟨a⟩ := ne_zero_iff_nonempty.1 hα in
⟨@embedding.arrow_congr_right _ _ _ ⟨a⟩ e⟩
theorem power_le_max_power_one {a b c : cardinal} (h : b ≤ c) : a ^ b ≤ max (a ^ c) 1 :=
begin
by_cases ha : a = 0,
simp [ha, zero_power_le],
exact le_trans (power_le_power_left ha h) (le_max_left _ _)
end
theorem power_le_power_right {a b c : cardinal} : a ≤ b → a ^ c ≤ b ^ c :=
quotient.induction_on₃ a b c $ assume α β γ ⟨e⟩, ⟨embedding.arrow_congr_left e⟩
theorem le_iff_exists_add {a b : cardinal} : a ≤ b ↔ ∃ c, b = a + c :=
⟨quotient.induction_on₂ a b $ λ α β ⟨⟨f, hf⟩⟩,
have (α ⊕ ((range f)ᶜ : set β)) ≃ β, from
(equiv.sum_congr (equiv.set.range f hf) (equiv.refl _)).trans $
(equiv.set.sum_compl (range f)),
⟨⟦↥(range f)ᶜ⟧, quotient.sound ⟨this.symm⟩⟩,
λ ⟨c, e⟩, add_zero a ▸ e.symm ▸ add_le_add_left _ (zero_le _)⟩
end order_properties
instance : order_bot cardinal.{u} :=
{ bot := 0, bot_le := zero_le, ..cardinal.linear_order }
instance : canonically_ordered_add_monoid cardinal.{u} :=
{ add_le_add_left := λ a b h c, add_le_add_left _ h,
lt_of_add_lt_add_left := λ a b c, lt_imp_lt_of_le_imp_le (add_le_add_left _),
le_iff_exists_add := @le_iff_exists_add,
..cardinal.order_bot,
..cardinal.comm_semiring, ..cardinal.linear_order }
theorem cantor : ∀(a : cardinal.{u}), a < 2 ^ a :=
by rw ← prop_eq_two; rintros ⟨a⟩; exact ⟨
⟨⟨λ a b, ⟨a = b⟩, λ a b h, cast (ulift.up.inj (@congr_fun _ _ _ _ h b)).symm rfl⟩⟩,
λ ⟨⟨f, hf⟩⟩, cantor_injective (λ s, f (λ a, ⟨s a⟩)) $
λ s t h, by funext a; injection congr_fun (hf h) a⟩
instance : no_top_order cardinal.{u} :=
{ no_top := λ a, ⟨_, cantor a⟩, ..cardinal.linear_order }
/-- The minimum cardinal in a family of cardinals (the existence
of which is provided by `injective_min`). -/
noncomputable def min {ι} (I : nonempty ι) (f : ι → cardinal) : cardinal :=
f $ classical.some $
@embedding.min_injective _ (λ i, (f i).out) I
theorem min_eq {ι} (I) (f : ι → cardinal) : ∃ i, min I f = f i :=
⟨_, rfl⟩
theorem min_le {ι I} (f : ι → cardinal) (i) : min I f ≤ f i :=
by rw [← mk_out (min I f), ← mk_out (f i)]; exact
let ⟨g⟩ := classical.some_spec
(@embedding.min_injective _ (λ i, (f i).out) I) in
⟨g i⟩
theorem le_min {ι I} {f : ι → cardinal} {a} : a ≤ min I f ↔ ∀ i, a ≤ f i :=
⟨λ h i, le_trans h (min_le _ _),
λ h, let ⟨i, e⟩ := min_eq I f in e.symm ▸ h i⟩
protected theorem wf : @well_founded cardinal.{u} (<) :=
⟨λ a, classical.by_contradiction $ λ h,
let ι := {c :cardinal // ¬ acc (<) c},
f : ι → cardinal := subtype.val,
⟨⟨c, hc⟩, hi⟩ := @min_eq ι ⟨⟨_, h⟩⟩ f in
hc (acc.intro _ (λ j ⟨_, h'⟩,
classical.by_contradiction $ λ hj, h' $
by have := min_le f ⟨j, hj⟩; rwa hi at this))⟩
instance has_wf : @has_well_founded cardinal.{u} := ⟨(<), cardinal.wf⟩
instance wo : @is_well_order cardinal.{u} (<) := ⟨cardinal.wf⟩
/-- The successor cardinal - the smallest cardinal greater than
`c`. This is not the same as `c + 1` except in the case of finite `c`. -/
noncomputable def succ (c : cardinal) : cardinal :=
@min {c' // c < c'} ⟨⟨_, cantor _⟩⟩ subtype.val
theorem lt_succ_self (c : cardinal) : c < succ c :=
by cases min_eq _ _ with s e; rw [succ, e]; exact s.2
theorem succ_le {a b : cardinal} : succ a ≤ b ↔ a < b :=
⟨lt_of_lt_of_le (lt_succ_self _), λ h,
by exact min_le _ (subtype.mk b h)⟩
theorem lt_succ {a b : cardinal} : a < succ b ↔ a ≤ b :=
by rw [← not_le, succ_le, not_lt]
theorem add_one_le_succ (c : cardinal) : c + 1 ≤ succ c :=
begin
refine quot.induction_on c (λ α, _) (lt_succ_self c),
refine quot.induction_on (succ (quot.mk setoid.r α)) (λ β h, _),
cases h.left with f,
have : ¬ surjective f := λ hn,
ne_of_lt h (quotient.sound ⟨equiv.of_bijective f ⟨f.injective, hn⟩⟩),
cases not_forall.1 this with b nex,
refine ⟨⟨sum.rec (by exact f) _, _⟩⟩,
{ exact λ _, b },
{ intros a b h, rcases a with a|⟨⟨⟨⟩⟩⟩; rcases b with b|⟨⟨⟨⟩⟩⟩,
{ rw f.injective h },
{ exact nex.elim ⟨_, h⟩ },
{ exact nex.elim ⟨_, h.symm⟩ },
{ refl } }
end
lemma succ_ne_zero (c : cardinal) : succ c ≠ 0 :=
by { rw [←pos_iff_ne_zero, lt_succ], apply zero_le }
/-- The indexed sum of cardinals is the cardinality of the
indexed disjoint union, i.e. sigma type. -/
def sum {ι} (f : ι → cardinal) : cardinal := mk Σ i, (f i).out
theorem le_sum {ι} (f : ι → cardinal) (i) : f i ≤ sum f :=
by rw ← quotient.out_eq (f i); exact
⟨⟨λ a, ⟨i, a⟩, λ a b h, eq_of_heq $ by injection h⟩⟩
@[simp] theorem sum_mk {ι} (f : ι → Type*) : sum (λ i, mk (f i)) = mk (Σ i, f i) :=
quot.sound ⟨equiv.sigma_congr_right $ λ i,
classical.choice $ quotient.exact $ quot.out_eq $ mk (f i)⟩
theorem sum_const (ι : Type u) (a : cardinal.{u}) : sum (λ _:ι, a) = mk ι * a :=
quotient.induction_on a $ λ α, by simp; exact
quotient.sound ⟨equiv.sigma_equiv_prod _ _⟩
theorem sum_le_sum {ι} (f g : ι → cardinal) (H : ∀ i, f i ≤ g i) : sum f ≤ sum g :=
⟨(embedding.refl _).sigma_map $ λ i, classical.choice $
by have := H i; rwa [← quot.out_eq (f i), ← quot.out_eq (g i)] at this⟩
/-- The indexed supremum of cardinals is the smallest cardinal above
everything in the family. -/
noncomputable def sup {ι} (f : ι → cardinal) : cardinal :=
@min {c // ∀ i, f i ≤ c} ⟨⟨sum f, le_sum f⟩⟩ (λ a, a.1)
theorem le_sup {ι} (f : ι → cardinal) (i) : f i ≤ sup f :=
by dsimp [sup]; cases min_eq _ _ with c hc; rw hc; exact c.2 i
theorem sup_le {ι} {f : ι → cardinal} {a} : sup f ≤ a ↔ ∀ i, f i ≤ a :=
⟨λ h i, le_trans (le_sup _ _) h,
λ h, by dsimp [sup]; change a with (⟨a, h⟩:subtype _).1; apply min_le⟩
theorem sup_le_sup {ι} (f g : ι → cardinal) (H : ∀ i, f i ≤ g i) : sup f ≤ sup g :=
sup_le.2 $ λ i, le_trans (H i) (le_sup _ _)
theorem sup_le_sum {ι} (f : ι → cardinal) : sup f ≤ sum f :=
sup_le.2 $ le_sum _
theorem sum_le_sup {ι : Type u} (f : ι → cardinal.{u}) : sum f ≤ mk ι * sup.{u u} f :=
by rw ← sum_const; exact sum_le_sum _ _ (le_sup _)
theorem sup_eq_zero {ι} {f : ι → cardinal} (h : ι → false) : sup f = 0 :=
by { rw [←le_zero, sup_le], intro x, exfalso, exact h x }
/-- The indexed product of cardinals is the cardinality of the Pi type
(dependent product). -/
def prod {ι : Type u} (f : ι → cardinal) : cardinal := mk (Π i, (f i).out)
@[simp] theorem prod_mk {ι} (f : ι → Type*) : prod (λ i, mk (f i)) = mk (Π i, f i) :=
quot.sound ⟨equiv.Pi_congr_right $ λ i,
classical.choice $ quotient.exact $ mk_out $ mk (f i)⟩
theorem prod_const (ι : Type u) (a : cardinal.{u}) : prod (λ _:ι, a) = a ^ mk ι :=
quotient.induction_on a $ by simp
theorem prod_le_prod {ι} (f g : ι → cardinal) (H : ∀ i, f i ≤ g i) : prod f ≤ prod g :=
⟨embedding.Pi_congr_right $ λ i, classical.choice $
by have := H i; rwa [← mk_out (f i), ← mk_out (g i)] at this⟩
theorem prod_ne_zero {ι} (f : ι → cardinal) : prod f ≠ 0 ↔ ∀ i, f i ≠ 0 :=
begin
conv in (f _) {rw ← mk_out (f i)},
simp [prod, ne_zero_iff_nonempty, -mk_out, -ne.def],
exact ⟨λ ⟨F⟩ i, ⟨F i⟩, λ h, ⟨λ i, classical.choice (h i)⟩⟩,
end
theorem prod_eq_zero {ι} (f : ι → cardinal) : prod f = 0 ↔ ∃ i, f i = 0 :=
not_iff_not.1 $ by simpa using prod_ne_zero f
/-- The universe lift operation on cardinals. You can specify the universes explicitly with
`lift.{u v} : cardinal.{u} → cardinal.{max u v}` -/
def lift (c : cardinal.{u}) : cardinal.{max u v} :=
quotient.lift_on c (λ α, ⟦ulift α⟧) $ λ α β ⟨e⟩,
quotient.sound ⟨equiv.ulift.trans $ e.trans equiv.ulift.symm⟩
theorem lift_mk (α) : lift.{u v} (mk α) = mk (ulift.{v u} α) := rfl
theorem lift_umax : lift.{u (max u v)} = lift.{u v} :=
funext $ λ a, quot.induction_on a $ λ α,
quotient.sound ⟨equiv.ulift.trans equiv.ulift.symm⟩
theorem lift_id' (a : cardinal) : lift a = a :=
quot.induction_on a $ λ α, quot.sound ⟨equiv.ulift⟩
@[simp] theorem lift_id : ∀ a, lift.{u u} a = a := lift_id'.{u u}
@[simp] theorem lift_lift (a : cardinal) : lift.{(max u v) w} (lift.{u v} a) = lift.{u (max v w)} a :=
quot.induction_on a $ λ α,
quotient.sound ⟨equiv.ulift.trans $ equiv.ulift.trans equiv.ulift.symm⟩
theorem lift_mk_le {α : Type u} {β : Type v} :
lift.{u (max v w)} (mk α) ≤ lift.{v (max u w)} (mk β) ↔ nonempty (α ↪ β) :=
⟨λ ⟨f⟩, ⟨embedding.congr equiv.ulift equiv.ulift f⟩,
λ ⟨f⟩, ⟨embedding.congr equiv.ulift.symm equiv.ulift.symm f⟩⟩
theorem lift_mk_eq {α : Type u} {β : Type v} :
lift.{u (max v w)} (mk α) = lift.{v (max u w)} (mk β) ↔ nonempty (α ≃ β) :=
quotient.eq.trans
⟨λ ⟨f⟩, ⟨equiv.ulift.symm.trans $ f.trans equiv.ulift⟩,
λ ⟨f⟩, ⟨equiv.ulift.trans $ f.trans equiv.ulift.symm⟩⟩
@[simp] theorem lift_le {a b : cardinal} : lift a ≤ lift b ↔ a ≤ b :=
quotient.induction_on₂ a b $ λ α β,
by rw ← lift_umax; exact lift_mk_le
@[simp] theorem lift_inj {a b : cardinal} : lift a = lift b ↔ a = b :=
by simp [le_antisymm_iff]
@[simp] theorem lift_lt {a b : cardinal} : lift a < lift b ↔ a < b :=
by simp [lt_iff_le_not_le, -not_le]
@[simp] theorem lift_zero : lift 0 = 0 :=
quotient.sound ⟨equiv.ulift.trans equiv.pempty_equiv_pempty⟩
@[simp] theorem lift_one : lift 1 = 1 :=
quotient.sound ⟨equiv.ulift.trans equiv.punit_equiv_punit⟩
@[simp] theorem lift_add (a b) : lift (a + b) = lift a + lift b :=
quotient.induction_on₂ a b $ λ α β,
quotient.sound ⟨equiv.ulift.trans (equiv.sum_congr equiv.ulift equiv.ulift).symm⟩
@[simp] theorem lift_mul (a b) : lift (a * b) = lift a * lift b :=
quotient.induction_on₂ a b $ λ α β,
quotient.sound ⟨equiv.ulift.trans (equiv.prod_congr equiv.ulift equiv.ulift).symm⟩
@[simp] theorem lift_power (a b) : lift (a ^ b) = lift a ^ lift b :=
quotient.induction_on₂ a b $ λ α β,
quotient.sound ⟨equiv.ulift.trans (equiv.arrow_congr equiv.ulift equiv.ulift).symm⟩
@[simp] theorem lift_two_power (a) : lift (2 ^ a) = 2 ^ lift a :=
by simp [bit0]
@[simp] theorem lift_min {ι I} (f : ι → cardinal) : lift (min I f) = min I (lift ∘ f) :=
le_antisymm (le_min.2 $ λ a, lift_le.2 $ min_le _ a) $
let ⟨i, e⟩ := min_eq I (lift ∘ f) in
by rw e; exact lift_le.2 (le_min.2 $ λ j, lift_le.1 $
by have := min_le (lift ∘ f) j; rwa e at this)
theorem lift_down {a : cardinal.{u}} {b : cardinal.{max u v}} :
b ≤ lift a → ∃ a', lift a' = b :=
quotient.induction_on₂ a b $ λ α β,
by dsimp; rw [← lift_id (mk β), ← lift_umax, ← lift_umax.{u v}, lift_mk_le]; exact
λ ⟨f⟩, ⟨mk (set.range f), eq.symm $ lift_mk_eq.2
⟨embedding.equiv_of_surjective
(embedding.cod_restrict _ f set.mem_range_self)
$ λ ⟨a, ⟨b, e⟩⟩, ⟨b, subtype.eq e⟩⟩⟩
theorem le_lift_iff {a : cardinal.{u}} {b : cardinal.{max u v}} :
b ≤ lift a ↔ ∃ a', lift a' = b ∧ a' ≤ a :=
⟨λ h, let ⟨a', e⟩ := lift_down h in ⟨a', e, lift_le.1 $ e.symm ▸ h⟩,
λ ⟨a', e, h⟩, e ▸ lift_le.2 h⟩
theorem lt_lift_iff {a : cardinal.{u}} {b : cardinal.{max u v}} :
b < lift a ↔ ∃ a', lift a' = b ∧ a' < a :=
⟨λ h, let ⟨a', e⟩ := lift_down (le_of_lt h) in
⟨a', e, lift_lt.1 $ e.symm ▸ h⟩,
λ ⟨a', e, h⟩, e ▸ lift_lt.2 h⟩
@[simp] theorem lift_succ (a) : lift (succ a) = succ (lift a) :=
le_antisymm
(le_of_not_gt $ λ h, begin
rcases lt_lift_iff.1 h with ⟨b, e, h⟩,
rw [lt_succ, ← lift_le, e] at h,
exact not_lt_of_le h (lt_succ_self _)
end)
(succ_le.2 $ lift_lt.2 $ lt_succ_self _)
@[simp] theorem lift_max {a : cardinal.{u}} {b : cardinal.{v}} :
lift.{u (max v w)} a = lift.{v (max u w)} b ↔ lift.{u v} a = lift.{v u} b :=
calc lift.{u (max v w)} a = lift.{v (max u w)} b
↔ lift.{(max u v) w} (lift.{u v} a)
= lift.{(max u v) w} (lift.{v u} b) : by simp
... ↔ lift.{u v} a = lift.{v u} b : lift_inj
theorem mk_prod {α : Type u} {β : Type v} :
mk (α × β) = lift.{u v} (mk α) * lift.{v u} (mk β) :=
quotient.sound ⟨equiv.prod_congr (equiv.ulift).symm (equiv.ulift).symm⟩
theorem sum_const_eq_lift_mul (ι : Type u) (a : cardinal.{v}) :
sum (λ _:ι, a) = lift.{u v} (mk ι) * lift.{v u} a :=
begin
apply quotient.induction_on a,
intro α,
simp only [cardinal.mk_def, cardinal.sum_mk, cardinal.lift_id],
convert mk_prod using 1,
exact quotient.sound ⟨equiv.sigma_equiv_prod ι α⟩,
end
/-- `ω` is the smallest infinite cardinal, also known as ℵ₀. -/
def omega : cardinal.{u} := lift (mk ℕ)
lemma mk_nat : mk nat = omega := (lift_id _).symm
theorem omega_ne_zero : omega ≠ 0 :=
ne_zero_iff_nonempty.2 ⟨⟨0⟩⟩
theorem omega_pos : 0 < omega :=
pos_iff_ne_zero.2 omega_ne_zero
@[simp] theorem lift_omega : lift omega = omega := lift_lift _
/- properties about the cast from nat -/
@[simp] theorem mk_fin : ∀ (n : ℕ), mk (fin n) = n
| 0 := quotient.sound ⟨(equiv.pempty_of_not_nonempty $ λ ⟨h⟩, h.elim0)⟩
| (n+1) := by rw [nat.cast_succ, ← mk_fin]; exact
quotient.sound (fintype.card_eq.1 $ by simp)
@[simp] theorem lift_nat_cast (n : ℕ) : lift n = n :=
by induction n; simp *
lemma lift_eq_nat_iff {a : cardinal.{u}} {n : ℕ} : lift.{u v} a = n ↔ a = n :=
by rw [← lift_nat_cast.{u v} n, lift_inj]
lemma nat_eq_lift_eq_iff {n : ℕ} {a : cardinal.{u}} :
(n : cardinal) = lift.{u v} a ↔ (n : cardinal) = a :=
by rw [← lift_nat_cast.{u v} n, lift_inj]
theorem lift_mk_fin (n : ℕ) : lift (mk (fin n)) = n := by simp
theorem fintype_card (α : Type u) [fintype α] : mk α = fintype.card α :=
by rw [← lift_mk_fin.{u}, ← lift_id (mk α), lift_mk_eq.{u 0 u}];
exact fintype.card_eq.1 (by simp)
theorem card_le_of_finset {α} (s : finset α) :
(s.card : cardinal) ≤ cardinal.mk α :=
begin
rw (_ : (s.card : cardinal) = cardinal.mk (↑s : set α)),
{ exact ⟨function.embedding.subtype _⟩ },
rw [cardinal.fintype_card, fintype.card_coe]
end
@[simp, norm_cast] theorem nat_cast_pow {m n : ℕ} : (↑(pow m n) : cardinal) = m ^ n :=
by induction n; simp [pow_succ', -_root_.add_comm, power_add, *]
@[simp, norm_cast] theorem nat_cast_le {m n : ℕ} : (m : cardinal) ≤ n ↔ m ≤ n :=
by rw [← lift_mk_fin, ← lift_mk_fin, lift_le]; exact
⟨λ ⟨⟨f, hf⟩⟩, begin
have : _ = fintype.card _ := finset.card_image_of_injective finset.univ hf,
simp at this,
rw [← fintype.card_fin n, ← this],
exact finset.card_le_of_subset (finset.subset_univ _)
end,
λ h, ⟨⟨λ i, ⟨i.1, lt_of_lt_of_le i.2 h⟩, λ a b h,
have _, from fin.veq_of_eq h, fin.eq_of_veq this⟩⟩⟩
@[simp, norm_cast] theorem nat_cast_lt {m n : ℕ} : (m : cardinal) < n ↔ m < n :=
by simp [lt_iff_le_not_le, -not_le]
@[simp, norm_cast] theorem nat_cast_inj {m n : ℕ} : (m : cardinal) = n ↔ m = n :=
by simp [le_antisymm_iff]
@[simp, norm_cast, priority 900] theorem nat_succ (n : ℕ) : (n.succ : cardinal) = succ n :=
le_antisymm (add_one_le_succ _) (succ_le.2 $ nat_cast_lt.2 $ nat.lt_succ_self _)
@[simp] theorem succ_zero : succ 0 = 1 :=
by norm_cast
theorem card_le_of {α : Type u} {n : ℕ} (H : ∀ s : finset α, s.card ≤ n) :
# α ≤ n :=
begin
refine lt_succ.1 (lt_of_not_ge $ λ hn, _),
rw [← cardinal.nat_succ, ← cardinal.lift_mk_fin n.succ] at hn,
cases hn with f,
refine not_lt_of_le (H $ finset.univ.map f) _,
rw [finset.card_map, ← fintype.card, fintype.card_ulift, fintype.card_fin],
exact n.lt_succ_self
end
theorem cantor' (a) {b : cardinal} (hb : 1 < b) : a < b ^ a :=
by rw [← succ_le, (by norm_cast : succ 1 = 2)] at hb;
exact lt_of_lt_of_le (cantor _) (power_le_power_right hb)
theorem one_le_iff_pos {c : cardinal} : 1 ≤ c ↔ 0 < c :=
by rw [← succ_zero, succ_le]
theorem one_le_iff_ne_zero {c : cardinal} : 1 ≤ c ↔ c ≠ 0 :=
by rw [one_le_iff_pos, pos_iff_ne_zero]
theorem nat_lt_omega (n : ℕ) : (n : cardinal.{u}) < omega :=
succ_le.1 $ by rw [← nat_succ, ← lift_mk_fin, omega, lift_mk_le.{0 0 u}]; exact
⟨⟨coe, λ a b, fin.ext⟩⟩
@[simp] theorem one_lt_omega : 1 < omega :=
by simpa using nat_lt_omega 1
theorem lt_omega {c : cardinal.{u}} : c < omega ↔ ∃ n : ℕ, c = n :=
⟨λ h, begin
rcases lt_lift_iff.1 h with ⟨c, rfl, h'⟩,
rcases le_mk_iff_exists_set.1 h'.1 with ⟨S, rfl⟩,
suffices : finite S,
{ cases this, resetI,
existsi fintype.card S,
rw [← lift_nat_cast.{0 u}, lift_inj, fintype_card S] },
by_contra nf,
have P : ∀ (n : ℕ) (IH : ∀ i<n, S), ∃ a : S, ¬ ∃ y h, IH y h = a :=
λ n IH,
let g : {i | i < n} → S := λ ⟨i, h⟩, IH i h in
not_forall.1 (λ h, nf
⟨fintype.of_surjective g (λ a, subtype.exists.2 (h a))⟩),
let F : ℕ → S := nat.lt_wf.fix (λ n IH, classical.some (P n IH)),
refine not_le_of_lt h' ⟨⟨F, _⟩⟩,
suffices : ∀ (n : ℕ) (m < n), F m ≠ F n,
{ refine λ m n, not_imp_not.1 (λ ne, _),
rcases lt_trichotomy m n with h|h|h,
{ exact this n m h },
{ contradiction },
{ exact (this m n h).symm } },
intros n m h,
have := classical.some_spec (P n (λ y _, F y)),
rw [← show F n = classical.some (P n (λ y _, F y)),
from nat.lt_wf.fix_eq (λ n IH, classical.some (P n IH)) n] at this,
exact λ e, this ⟨m, h, e⟩,
end, λ ⟨n, e⟩, e.symm ▸ nat_lt_omega _⟩
theorem omega_le {c : cardinal.{u}} : omega ≤ c ↔ ∀ n : ℕ, (n:cardinal) ≤ c :=
⟨λ h n, le_trans (le_of_lt (nat_lt_omega _)) h,
λ h, le_of_not_lt $ λ hn, begin
rcases lt_omega.1 hn with ⟨n, rfl⟩,
exact not_le_of_lt (nat.lt_succ_self _) (nat_cast_le.1 (h (n+1)))
end⟩
theorem lt_omega_iff_fintype {α : Type u} : mk α < omega ↔ nonempty (fintype α) :=
lt_omega.trans ⟨λ ⟨n, e⟩, begin
rw [← lift_mk_fin n] at e,
cases quotient.exact e with f,
exact ⟨fintype.of_equiv _ f.symm⟩
end, λ ⟨_⟩, by exactI ⟨_, fintype_card _⟩⟩
theorem lt_omega_iff_finite {α} {S : set α} : mk S < omega ↔ finite S :=
lt_omega_iff_fintype
instance can_lift_cardinal_nat : can_lift cardinal ℕ :=
⟨ coe, λ x, x < omega, λ x hx, let ⟨n, hn⟩ := lt_omega.mp hx in ⟨n, hn.symm⟩⟩
theorem add_lt_omega {a b : cardinal} (ha : a < omega) (hb : b < omega) : a + b < omega :=
match a, b, lt_omega.1 ha, lt_omega.1 hb with
| _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat.cast_add]; apply nat_lt_omega
end
lemma add_lt_omega_iff {a b : cardinal} : a + b < omega ↔ a < omega ∧ b < omega :=
⟨λ h, ⟨lt_of_le_of_lt (le_add_right _ _) h, lt_of_le_of_lt (le_add_left _ _) h⟩,
λ⟨h1, h2⟩, add_lt_omega h1 h2⟩
theorem mul_lt_omega {a b : cardinal} (ha : a < omega) (hb : b < omega) : a * b < omega :=
match a, b, lt_omega.1 ha, lt_omega.1 hb with
| _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat.cast_mul]; apply nat_lt_omega
end
lemma mul_lt_omega_iff {a b : cardinal} : a * b < omega ↔ a = 0 ∨ b = 0 ∨ a < omega ∧ b < omega :=
begin
split,
{ intro h, by_cases ha : a = 0, { left, exact ha },
right, by_cases hb : b = 0, { left, exact hb },
right, rw [← ne, ← one_le_iff_ne_zero] at ha hb, split,
{ rw [← mul_one a], refine lt_of_le_of_lt (mul_le_mul (le_refl a) hb) h },
{ rw [← _root_.one_mul b], refine lt_of_le_of_lt (mul_le_mul ha (le_refl b)) h }},
rintro (rfl|rfl|⟨ha,hb⟩); simp only [*, mul_lt_omega, omega_pos, _root_.zero_mul, mul_zero]
end
lemma mul_lt_omega_iff_of_ne_zero {a b : cardinal} (ha : a ≠ 0) (hb : b ≠ 0) :
a * b < omega ↔ a < omega ∧ b < omega :=
by simp [mul_lt_omega_iff, ha, hb]
theorem power_lt_omega {a b : cardinal} (ha : a < omega) (hb : b < omega) : a ^ b < omega :=
match a, b, lt_omega.1 ha, lt_omega.1 hb with
| _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat_cast_pow]; apply nat_lt_omega
end
lemma eq_one_iff_subsingleton_and_nonempty {α : Type*} :
mk α = 1 ↔ (subsingleton α ∧ nonempty α) :=
calc mk α = 1 ↔ mk α ≤ 1 ∧ ¬mk α < 1 : eq_iff_le_not_lt
... ↔ subsingleton α ∧ nonempty α :
begin
apply and_congr le_one_iff_subsingleton,
push_neg,
rw [one_le_iff_ne_zero, ne_zero_iff_nonempty]
end
theorem infinite_iff {α : Type u} : infinite α ↔ omega ≤ mk α :=
by rw [←not_lt, lt_omega_iff_fintype, not_nonempty_fintype]
lemma countable_iff (s : set α) : countable s ↔ mk s ≤ omega :=
begin
rw [countable_iff_exists_injective], split,
rintro ⟨f, hf⟩, exact ⟨embedding.trans ⟨f, hf⟩ equiv.ulift.symm.to_embedding⟩,
rintro ⟨f'⟩, cases embedding.trans f' equiv.ulift.to_embedding with f hf, exact ⟨f, hf⟩
end
lemma denumerable_iff {α : Type u} : nonempty (denumerable α) ↔ mk α = omega :=
⟨λ⟨h⟩, quotient.sound $ by exactI ⟨ (denumerable.eqv α).trans equiv.ulift.symm ⟩,
λ h, by { cases quotient.exact h with f, exact ⟨denumerable.mk' $ f.trans equiv.ulift⟩ }⟩
lemma mk_int : mk ℤ = omega :=
denumerable_iff.mp ⟨by apply_instance⟩
lemma mk_pnat : mk ℕ+ = omega :=
denumerable_iff.mp ⟨by apply_instance⟩
lemma two_le_iff : (2 : cardinal) ≤ mk α ↔ ∃x y : α, x ≠ y :=
begin
split,
{ rintro ⟨f⟩, refine ⟨f $ sum.inl ⟨⟩, f $ sum.inr ⟨⟩, _⟩, intro h, cases f.2 h },
{ rintro ⟨x, y, h⟩, by_contra h',
rw [not_le, ←nat.cast_two, nat_succ, lt_succ, nat.cast_one, le_one_iff_subsingleton] at h',
apply h, exactI subsingleton.elim _ _ }
end
lemma two_le_iff' (x : α) : (2 : cardinal) ≤ mk α ↔ ∃y : α, x ≠ y :=
begin
rw [two_le_iff],
split,
{ rintro ⟨y, z, h⟩, refine classical.by_cases (λ(h' : x = y), _) (λ h', ⟨y, h'⟩),
rw [←h'] at h, exact ⟨z, h⟩ },
{ rintro ⟨y, h⟩, exact ⟨x, y, h⟩ }
end
/-- König's theorem -/
theorem sum_lt_prod {ι} (f g : ι → cardinal) (H : ∀ i, f i < g i) : sum f < prod g :=
lt_of_not_ge $ λ ⟨F⟩, begin
have : inhabited (Π (i : ι), (g i).out),
{ refine ⟨λ i, classical.choice $ ne_zero_iff_nonempty.1 _⟩,
rw mk_out,
exact ne_of_gt (lt_of_le_of_lt (zero_le _) (H i)) }, resetI,
let G := inv_fun F,
have sG : surjective G := inv_fun_surjective F.2,
choose C hc using show ∀ i, ∃ b, ∀ a, G ⟨i, a⟩ i ≠ b,
{ assume i,
simp only [- not_exists, not_exists.symm, not_forall.symm],
refine λ h, not_le_of_lt (H i) _,
rw [← mk_out (f i), ← mk_out (g i)],
exact ⟨embedding.of_surjective _ h⟩ },
exact (let ⟨⟨i, a⟩, h⟩ := sG C in hc i a (congr_fun h _))
end
@[simp] theorem mk_empty : mk empty = 0 :=
fintype_card empty
@[simp] theorem mk_pempty : mk pempty = 0 :=
fintype_card pempty
@[simp] theorem mk_plift_of_false {p : Prop} (h : ¬ p) : mk (plift p) = 0 :=
quotient.sound ⟨equiv.plift.trans $ equiv.equiv_pempty h⟩
theorem mk_unit : mk unit = 1 :=
(fintype_card unit).trans nat.cast_one
@[simp] theorem mk_punit : mk punit = 1 :=
(fintype_card punit).trans nat.cast_one
@[simp] theorem mk_singleton {α : Type u} (x : α) : mk ({x} : set α) = 1 :=
quotient.sound ⟨equiv.set.singleton x⟩
@[simp] theorem mk_plift_of_true {p : Prop} (h : p) : mk (plift p) = 1 :=
quotient.sound ⟨equiv.plift.trans $ equiv.prop_equiv_punit h⟩
@[simp] theorem mk_bool : mk bool = 2 :=
quotient.sound ⟨equiv.bool_equiv_punit_sum_punit⟩
@[simp] theorem mk_Prop : mk Prop = 2 :=
(quotient.sound ⟨equiv.Prop_equiv_bool⟩ : mk Prop = mk bool).trans mk_bool
@[simp] theorem mk_option {α : Type u} : mk (option α) = mk α + 1 :=
quotient.sound ⟨equiv.option_equiv_sum_punit α⟩
theorem mk_list_eq_sum_pow (α : Type u) : mk (list α) = sum (λ n : ℕ, (mk α)^(n:cardinal.{u})) :=
calc mk (list α)
= mk (Σ n, vector α n) : quotient.sound ⟨(equiv.sigma_preimage_equiv list.length).symm⟩
... = mk (Σ n, fin n → α) : quotient.sound ⟨equiv.sigma_congr_right $ λ n,
⟨vector.nth, vector.of_fn, vector.of_fn_nth, λ f, funext $ vector.nth_of_fn f⟩⟩
... = mk (Σ n : ℕ, ulift.{u} (fin n) → α) : quotient.sound ⟨equiv.sigma_congr_right $ λ n,
equiv.arrow_congr equiv.ulift.symm (equiv.refl α)⟩
... = sum (λ n : ℕ, (mk α)^(n:cardinal.{u})) : by simp only [(lift_mk_fin _).symm, lift_mk, power_def, sum_mk]
theorem mk_quot_le {α : Type u} {r : α → α → Prop} : mk (quot r) ≤ mk α :=
mk_le_of_surjective quot.exists_rep
theorem mk_quotient_le {α : Type u} {s : setoid α} : mk (quotient s) ≤ mk α :=
mk_quot_le
theorem mk_subtype_le {α : Type u} (p : α → Prop) : mk (subtype p) ≤ mk α :=
⟨embedding.subtype p⟩
theorem mk_subtype_le_of_subset {α : Type u} {p q : α → Prop} (h : ∀ ⦃x⦄, p x → q x) :
mk (subtype p) ≤ mk (subtype q) :=
⟨embedding.subtype_map (embedding.refl α) h⟩
@[simp] theorem mk_emptyc (α : Type u) : mk (∅ : set α) = 0 :=
quotient.sound ⟨equiv.set.pempty α⟩
lemma mk_emptyc_iff {α : Type u} {s : set α} : mk s = 0 ↔ s = ∅ :=
begin
split,
{ intro h,
have h2 : cardinal.mk s = cardinal.mk pempty, by simp [h],
refine set.eq_empty_iff_forall_not_mem.mpr (λ _ hx, _),
rcases cardinal.eq.mp h2 with ⟨f, _⟩,
cases f ⟨_, hx⟩ },
{ intro, convert mk_emptyc _ }
end
theorem mk_univ {α : Type u} : mk (@univ α) = mk α :=
quotient.sound ⟨equiv.set.univ α⟩
theorem mk_image_le {α β : Type u} {f : α → β} {s : set α} : mk (f '' s) ≤ mk s :=
mk_le_of_surjective surjective_onto_image
theorem mk_image_le_lift {α : Type u} {β : Type v} {f : α → β} {s : set α} :
lift.{v u} (mk (f '' s)) ≤ lift.{u v} (mk s) :=
lift_mk_le.{v u 0}.mpr ⟨embedding.of_surjective _ surjective_onto_image⟩
theorem mk_range_le {α β : Type u} {f : α → β} : mk (range f) ≤ mk α :=
mk_le_of_surjective surjective_onto_range
lemma mk_range_eq (f : α → β) (h : injective f) : mk (range f) = mk α :=
quotient.sound ⟨(equiv.set.range f h).symm⟩
lemma mk_range_eq_of_injective {α : Type u} {β : Type v} {f : α → β} (hf : injective f) :
lift.{v u} (mk (range f)) = lift.{u v} (mk α) :=
begin
have := (@lift_mk_eq.{v u max u v} (range f) α).2 ⟨(equiv.set.range f hf).symm⟩,
simp only [lift_umax.{u v}, lift_umax.{v u}] at this,
exact this
end
lemma mk_range_eq_lift {α : Type u} {β : Type v} {f : α → β} (hf : injective f) :
lift.{v (max u w)} (# (range f)) = lift.{u (max v w)} (# α) :=
lift_mk_eq.mpr ⟨(equiv.set.range f hf).symm⟩
theorem mk_image_eq {α β : Type u} {f : α → β} {s : set α} (hf : injective f) :
mk (f '' s) = mk s :=
quotient.sound ⟨(equiv.set.image f s hf).symm⟩
theorem mk_Union_le_sum_mk {α ι : Type u} {f : ι → set α} : mk (⋃ i, f i) ≤ sum (λ i, mk (f i)) :=
calc mk (⋃ i, f i) ≤ mk (Σ i, f i) : mk_le_of_surjective (set.sigma_to_Union_surjective f)
... = sum (λ i, mk (f i)) : (sum_mk _).symm
theorem mk_Union_eq_sum_mk {α ι : Type u} {f : ι → set α} (h : ∀i j, i ≠ j → disjoint (f i) (f j)) :
mk (⋃ i, f i) = sum (λ i, mk (f i)) :=
calc mk (⋃ i, f i) = mk (Σi, f i) : quot.sound ⟨set.Union_eq_sigma_of_disjoint h⟩
... = sum (λi, mk (f i)) : (sum_mk _).symm
lemma mk_Union_le {α ι : Type u} (f : ι → set α) :
mk (⋃ i, f i) ≤ mk ι * cardinal.sup.{u u} (λ i, mk (f i)) :=
le_trans mk_Union_le_sum_mk (sum_le_sup _)
lemma mk_sUnion_le {α : Type u} (A : set (set α)) :
mk (⋃₀ A) ≤ mk A * cardinal.sup.{u u} (λ s : A, mk s) :=
by { rw [sUnion_eq_Union], apply mk_Union_le }
lemma mk_bUnion_le {ι α : Type u} (A : ι → set α) (s : set ι) :
mk (⋃(x ∈ s), A x) ≤ mk s * cardinal.sup.{u u} (λ x : s, mk (A x.1)) :=
by { rw [bUnion_eq_Union], apply mk_Union_le }
@[simp] lemma finset_card {α : Type u} {s : finset α} : ↑(finset.card s) = mk (↑s : set α) :=
by rw [fintype_card, nat_cast_inj, fintype.card_coe]
lemma finset_card_lt_omega (s : finset α) : mk (↑s : set α) < omega :=
by { rw [lt_omega_iff_fintype], exact ⟨finset.subtype.fintype s⟩ }
theorem mk_union_add_mk_inter {α : Type u} {S T : set α} :
mk (S ∪ T : set α) + mk (S ∩ T : set α) = mk S + mk T :=
quot.sound ⟨equiv.set.union_sum_inter S T⟩
/-- The cardinality of a union is at most the sum of the cardinalities
of the two sets. -/
lemma mk_union_le {α : Type u} (S T : set α) : mk (S ∪ T : set α) ≤ mk S + mk T :=
@mk_union_add_mk_inter α S T ▸ le_add_right (mk (S ∪ T : set α)) (mk (S ∩ T : set α))
theorem mk_union_of_disjoint {α : Type u} {S T : set α} (H : disjoint S T) :
mk (S ∪ T : set α) = mk S + mk T :=
quot.sound ⟨equiv.set.union H⟩
lemma mk_sum_compl {α} (s : set α) : #s + #(sᶜ : set α) = #α :=
quotient.sound ⟨equiv.set.sum_compl s⟩
lemma mk_le_mk_of_subset {α} {s t : set α} (h : s ⊆ t) : mk s ≤ mk t :=
⟨set.embedding_of_subset s t h⟩
lemma mk_subtype_mono {p q : α → Prop} (h : ∀x, p x → q x) : mk {x // p x} ≤ mk {x // q x} :=
⟨embedding_of_subset _ _ h⟩
lemma mk_set_le (s : set α) : mk s ≤ mk α :=
mk_subtype_le s
lemma mk_image_eq_lift {α : Type u} {β : Type v} (f : α → β) (s : set α) (h : injective f) :
lift.{v u} (mk (f '' s)) = lift.{u v} (mk s) :=
lift_mk_eq.{v u 0}.mpr ⟨(equiv.set.image f s h).symm⟩
lemma mk_image_eq_of_inj_on_lift {α : Type u} {β : Type v} (f : α → β) (s : set α)
(h : inj_on f s) : lift.{v u} (mk (f '' s)) = lift.{u v} (mk s) :=
lift_mk_eq.{v u 0}.mpr ⟨(equiv.set.image_of_inj_on f s h).symm⟩
lemma mk_image_eq_of_inj_on {α β : Type u} (f : α → β) (s : set α) (h : inj_on f s) :
mk (f '' s) = mk s :=
quotient.sound ⟨(equiv.set.image_of_inj_on f s h).symm⟩
lemma mk_subtype_of_equiv {α β : Type u} (p : β → Prop) (e : α ≃ β) :
mk {a : α // p (e a)} = mk {b : β // p b} :=
quotient.sound ⟨equiv.subtype_equiv_of_subtype e⟩
lemma mk_sep (s : set α) (t : α → Prop) : mk ({ x ∈ s | t x } : set α) = mk { x : s | t x.1 } :=
quotient.sound ⟨equiv.set.sep s t⟩
lemma mk_preimage_of_injective_lift {α : Type u} {β : Type v} (f : α → β) (s : set β)
(h : injective f) : lift.{u v} (mk (f ⁻¹' s)) ≤ lift.{v u} (mk s) :=
begin
rw lift_mk_le.{u v 0}, use subtype.coind (λ x, f x.1) (λ x, x.2),
apply subtype.coind_injective, exact h.comp subtype.val_injective
end
lemma mk_preimage_of_subset_range_lift {α : Type u} {β : Type v} (f : α → β) (s : set β)
(h : s ⊆ range f) : lift.{v u} (mk s) ≤ lift.{u v} (mk (f ⁻¹' s)) :=
begin
rw lift_mk_le.{v u 0},
refine ⟨⟨_, _⟩⟩,
{ rintro ⟨y, hy⟩, rcases classical.subtype_of_exists (h hy) with ⟨x, rfl⟩, exact ⟨x, hy⟩ },
rintro ⟨y, hy⟩ ⟨y', hy'⟩, dsimp,
rcases classical.subtype_of_exists (h hy) with ⟨x, rfl⟩,
rcases classical.subtype_of_exists (h hy') with ⟨x', rfl⟩,
simp, intro hxx', rw hxx'
end
lemma mk_preimage_of_injective_of_subset_range_lift {β : Type v} (f : α → β) (s : set β)
(h : injective f) (h2 : s ⊆ range f) : lift.{u v} (mk (f ⁻¹' s)) = lift.{v u} (mk s) :=
le_antisymm (mk_preimage_of_injective_lift f s h) (mk_preimage_of_subset_range_lift f s h2)
lemma mk_preimage_of_injective (f : α → β) (s : set β) (h : injective f) :
mk (f ⁻¹' s) ≤ mk s :=
by { convert mk_preimage_of_injective_lift.{u u} f s h using 1; rw [lift_id] }
lemma mk_preimage_of_subset_range (f : α → β) (s : set β)
(h : s ⊆ range f) : mk s ≤ mk (f ⁻¹' s) :=
by { convert mk_preimage_of_subset_range_lift.{u u} f s h using 1; rw [lift_id] }
lemma mk_preimage_of_injective_of_subset_range (f : α → β) (s : set β)
(h : injective f) (h2 : s ⊆ range f) : mk (f ⁻¹' s) = mk s :=
by { convert mk_preimage_of_injective_of_subset_range_lift.{u u} f s h h2 using 1; rw [lift_id] }
lemma mk_subset_ge_of_subset_image_lift {α : Type u} {β : Type v} (f : α → β) {s : set α}
{t : set β} (h : t ⊆ f '' s) :
lift.{v u} (mk t) ≤ lift.{u v} (mk ({ x ∈ s | f x ∈ t } : set α)) :=
by { rw [image_eq_range] at h, convert mk_preimage_of_subset_range_lift _ _ h using 1, rw [mk_sep], refl }
lemma mk_subset_ge_of_subset_image (f : α → β) {s : set α} {t : set β} (h : t ⊆ f '' s) :
mk t ≤ mk ({ x ∈ s | f x ∈ t } : set α) :=
by { rw [image_eq_range] at h, convert mk_preimage_of_subset_range _ _ h using 1, rw [mk_sep], refl }
theorem le_mk_iff_exists_subset {c : cardinal} {α : Type u} {s : set α} :
c ≤ mk s ↔ ∃ p : set α, p ⊆ s ∧ mk p = c :=
begin
rw [le_mk_iff_exists_set, ←subtype.exists_set_subtype],
apply exists_congr, intro t, rw [mk_image_eq], apply subtype.val_injective
end
/-- The function α^{<β}, defined to be sup_{γ < β} α^γ.
We index over {s : set β.out // mk s < β } instead of {γ // γ < β}, because the latter lives in a
higher universe -/
noncomputable def powerlt (α β : cardinal.{u}) : cardinal.{u} :=
sup.{u u} (λ(s : {s : set β.out // mk s < β}), α ^ mk.{u} s)
infix ` ^< `:80 := powerlt
theorem powerlt_aux {c c' : cardinal} (h : c < c') :
∃(s : {s : set c'.out // mk s < c'}), mk s = c :=
begin
cases out_embedding.mp (le_of_lt h) with f,
have : mk ↥(range ⇑f) = c, { rwa [mk_range_eq, mk, quotient.out_eq c], exact f.2 },
exact ⟨⟨range f, by convert h⟩, this⟩
end
lemma le_powerlt {c₁ c₂ c₃ : cardinal} (h : c₂ < c₃) : c₁ ^ c₂ ≤ c₁ ^< c₃ :=
by { rcases powerlt_aux h with ⟨s, rfl⟩, apply le_sup _ s }
lemma powerlt_le {c₁ c₂ c₃ : cardinal} : c₁ ^< c₂ ≤ c₃ ↔ ∀(c₄ < c₂), c₁ ^ c₄ ≤ c₃ :=
begin
rw [powerlt, sup_le],
split,
{ intros h c₄ hc₄, rcases powerlt_aux hc₄ with ⟨s, rfl⟩, exact h s },
intros h s, exact h _ s.2
end
lemma powerlt_le_powerlt_left {a b c : cardinal} (h : b ≤ c) : a ^< b ≤ a ^< c :=
by { rw [powerlt, sup_le], rintro ⟨s, hs⟩, apply le_powerlt, exact lt_of_lt_of_le hs h }
lemma powerlt_succ {c₁ c₂ : cardinal} (h : c₁ ≠ 0) : c₁ ^< c₂.succ = c₁ ^ c₂ :=
begin
apply le_antisymm,
{ rw powerlt_le, intros c₃ h2, apply power_le_power_left h, rwa [←lt_succ] },
{ apply le_powerlt, apply lt_succ_self }
end
lemma powerlt_max {c₁ c₂ c₃ : cardinal} : c₁ ^< max c₂ c₃ = max (c₁ ^< c₂) (c₁ ^< c₃) :=
by { cases le_total c₂ c₃; simp only [max_eq_left, max_eq_right, h, powerlt_le_powerlt_left] }
lemma zero_powerlt {a : cardinal} (h : a ≠ 0) : 0 ^< a = 1 :=
begin
apply le_antisymm,
{ rw [powerlt_le], intros c hc, apply zero_power_le },
convert le_powerlt (pos_iff_ne_zero.2 h), rw [power_zero]
end
lemma powerlt_zero {a : cardinal} : a ^< 0 = 0 :=
by { apply sup_eq_zero, rintro ⟨x, hx⟩, rw [←not_le] at hx, apply hx, apply zero_le }
end cardinal
|
b91f1f5863224dbde87376556d267b83fedae8fc | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/ring_theory/polynomial/gauss_lemma.lean | 9f906469e6c2bb9a53f1a598df60bcfddb8544d0 | [
"Apache-2.0"
] | permissive | robertylewis/mathlib | 3d16e3e6daf5ddde182473e03a1b601d2810952c | 1d13f5b932f5e40a8308e3840f96fc882fae01f0 | refs/heads/master | 1,651,379,945,369 | 1,644,276,960,000 | 1,644,276,960,000 | 98,875,504 | 0 | 0 | Apache-2.0 | 1,644,253,514,000 | 1,501,495,700,000 | Lean | UTF-8 | Lean | false | false | 7,973 | lean | /-
Copyright (c) 2020 Aaron Anderson. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Aaron Anderson
-/
import ring_theory.int.basic
import ring_theory.localization
/-!
# Gauss's Lemma
Gauss's Lemma is one of a few results pertaining to irreducibility of primitive polynomials.
## Main Results
- `polynomial.is_primitive.irreducible_iff_irreducible_map_fraction_map`:
A primitive polynomial is irreducible iff it is irreducible in a fraction field.
- `polynomial.is_primitive.int.irreducible_iff_irreducible_map_cast`:
A primitive polynomial over `ℤ` is irreducible iff it is irreducible over `ℚ`.
- `polynomial.is_primitive.dvd_iff_fraction_map_dvd_fraction_map`:
Two primitive polynomials divide each other iff they do in a fraction field.
- `polynomial.is_primitive.int.dvd_iff_map_cast_dvd_map_cast`:
Two primitive polynomials over `ℤ` divide each other if they do in `ℚ`.
-/
open_locale non_zero_divisors
variables {R : Type*} [comm_ring R] [is_domain R]
namespace polynomial
section normalized_gcd_monoid
variable [normalized_gcd_monoid R]
section
variables {S : Type*} [comm_ring S] [is_domain S] {φ : R →+* S} (hinj : function.injective φ)
variables {f : polynomial R} (hf : f.is_primitive)
include hinj hf
lemma is_primitive.is_unit_iff_is_unit_map_of_injective :
is_unit f ↔ is_unit (map φ f) :=
begin
refine ⟨(map_ring_hom φ).is_unit_map, λ h, _⟩,
rcases is_unit_iff.1 h with ⟨_, ⟨u, rfl⟩, hu⟩,
have hdeg := degree_C u.ne_zero,
rw [hu, degree_map_eq_of_injective hinj] at hdeg,
rw [eq_C_of_degree_eq_zero hdeg, is_primitive_iff_content_eq_one,
content_C, normalize_eq_one] at hf,
rwa [eq_C_of_degree_eq_zero hdeg, is_unit_C],
end
lemma is_primitive.irreducible_of_irreducible_map_of_injective (h_irr : irreducible (map φ f)) :
irreducible f :=
begin
refine ⟨λ h, h_irr.not_unit (is_unit.map ((map_ring_hom φ).to_monoid_hom) h), _⟩,
intros a b h,
rcases h_irr.is_unit_or_is_unit (by rw [h, map_mul]) with hu | hu,
{ left,
rwa (hf.is_primitive_of_dvd (dvd.intro _ h.symm)).is_unit_iff_is_unit_map_of_injective hinj },
right,
rwa (hf.is_primitive_of_dvd (dvd.intro_left _ h.symm)).is_unit_iff_is_unit_map_of_injective hinj
end
end
section fraction_map
variables {K : Type*} [field K] [algebra R K] [is_fraction_ring R K]
lemma is_primitive.is_unit_iff_is_unit_map {p : polynomial R} (hp : p.is_primitive) :
is_unit p ↔ is_unit (p.map (algebra_map R K)) :=
hp.is_unit_iff_is_unit_map_of_injective (is_fraction_ring.injective _ _)
open is_localization
lemma is_unit_or_eq_zero_of_is_unit_integer_normalization_prim_part
{p : polynomial K} (h0 : p ≠ 0) (h : is_unit (integer_normalization R⁰ p).prim_part) :
is_unit p :=
begin
rcases is_unit_iff.1 h with ⟨_, ⟨u, rfl⟩, hu⟩,
obtain ⟨⟨c, c0⟩, hc⟩ := integer_normalization_map_to_map R⁰ p,
rw [subtype.coe_mk, algebra.smul_def, algebra_map_apply] at hc,
apply is_unit_of_mul_is_unit_right,
rw [← hc, (integer_normalization R⁰ p).eq_C_content_mul_prim_part, ← hu,
← ring_hom.map_mul, is_unit_iff],
refine ⟨algebra_map R K ((integer_normalization R⁰ p).content * ↑u),
is_unit_iff_ne_zero.2 (λ con, _), by simp⟩,
replace con := (algebra_map R K).injective_iff.1 (is_fraction_ring.injective _ _) _ con,
rw [mul_eq_zero, content_eq_zero_iff, is_fraction_ring.integer_normalization_eq_zero_iff] at con,
rcases con with con | con,
{ apply h0 con },
{ apply units.ne_zero _ con },
end
/-- **Gauss's Lemma** states that a primitive polynomial is irreducible iff it is irreducible in the
fraction field. -/
theorem is_primitive.irreducible_iff_irreducible_map_fraction_map
{p : polynomial R} (hp : p.is_primitive) :
irreducible p ↔ irreducible (p.map (algebra_map R K)) :=
begin
refine ⟨λ hi, ⟨λ h, hi.not_unit (hp.is_unit_iff_is_unit_map.2 h), λ a b hab, _⟩,
hp.irreducible_of_irreducible_map_of_injective (is_fraction_ring.injective _ _)⟩,
obtain ⟨⟨c, c0⟩, hc⟩ := integer_normalization_map_to_map R⁰ a,
obtain ⟨⟨d, d0⟩, hd⟩ := integer_normalization_map_to_map R⁰ b,
rw [algebra.smul_def, algebra_map_apply, subtype.coe_mk] at hc hd,
rw mem_non_zero_divisors_iff_ne_zero at c0 d0,
have hcd0 : c * d ≠ 0 := mul_ne_zero c0 d0,
rw [ne.def, ← C_eq_zero] at hcd0,
have h1 : C c * C d * p = integer_normalization R⁰ a * integer_normalization R⁰ b,
{ apply map_injective (algebra_map R K) (is_fraction_ring.injective _ _) _,
rw [map_mul, map_mul, map_mul, hc, hd, map_C, map_C, hab],
ring },
obtain ⟨u, hu⟩ : associated (c * d) (content (integer_normalization R⁰ a) *
content (integer_normalization R⁰ b)),
{ rw [← dvd_dvd_iff_associated, ← normalize_eq_normalize_iff, normalize.map_mul,
normalize.map_mul, normalize_content, normalize_content,
← mul_one (normalize c * normalize d), ← hp.content_eq_one, ← content_C, ← content_C,
← content_mul, ← content_mul, ← content_mul, h1] },
rw [← ring_hom.map_mul, eq_comm,
(integer_normalization R⁰ a).eq_C_content_mul_prim_part,
(integer_normalization R⁰ b).eq_C_content_mul_prim_part, mul_assoc,
mul_comm _ (C _ * _), ← mul_assoc, ← mul_assoc, ← ring_hom.map_mul, ← hu, ring_hom.map_mul,
mul_assoc, mul_assoc, ← mul_assoc (C ↑u)] at h1,
have h0 : (a ≠ 0) ∧ (b ≠ 0),
{ classical,
rw [ne.def, ne.def, ← decidable.not_or_iff_and_not, ← mul_eq_zero, ← hab],
intro con,
apply hp.ne_zero (map_injective (algebra_map R K) (is_fraction_ring.injective _ _) _),
simp [con] },
rcases hi.is_unit_or_is_unit (mul_left_cancel₀ hcd0 h1).symm with h | h,
{ right,
apply is_unit_or_eq_zero_of_is_unit_integer_normalization_prim_part h0.2
(is_unit_of_mul_is_unit_right h) },
{ left,
apply is_unit_or_eq_zero_of_is_unit_integer_normalization_prim_part h0.1 h },
end
lemma is_primitive.dvd_of_fraction_map_dvd_fraction_map {p q : polynomial R}
(hp : p.is_primitive) (hq : q.is_primitive)
(h_dvd : p.map (algebra_map R K) ∣ q.map (algebra_map R K)) : p ∣ q :=
begin
rcases h_dvd with ⟨r, hr⟩,
obtain ⟨⟨s, s0⟩, hs⟩ := integer_normalization_map_to_map R⁰ r,
rw [subtype.coe_mk, algebra.smul_def, algebra_map_apply] at hs,
have h : p ∣ q * C s,
{ use (integer_normalization R⁰ r),
apply map_injective (algebra_map R K) (is_fraction_ring.injective _ _),
rw [map_mul, map_mul, hs, hr, mul_assoc, mul_comm r],
simp },
rw [← hp.dvd_prim_part_iff_dvd, prim_part_mul, hq.prim_part_eq,
associated.dvd_iff_dvd_right] at h,
{ exact h },
{ symmetry,
rcases is_unit_prim_part_C s with ⟨u, hu⟩,
use u,
rw hu },
iterate 2 { apply mul_ne_zero hq.ne_zero,
rw [ne.def, C_eq_zero],
contrapose! s0,
simp [s0, mem_non_zero_divisors_iff_ne_zero] }
end
variables (K)
lemma is_primitive.dvd_iff_fraction_map_dvd_fraction_map {p q : polynomial R}
(hp : p.is_primitive) (hq : q.is_primitive) :
(p ∣ q) ↔ (p.map (algebra_map R K) ∣ q.map (algebra_map R K)) :=
⟨λ ⟨a,b⟩, ⟨a.map (algebra_map R K), b.symm ▸ map_mul (algebra_map R K)⟩,
λ h, hp.dvd_of_fraction_map_dvd_fraction_map hq h⟩
end fraction_map
/-- **Gauss's Lemma** for `ℤ` states that a primitive integer polynomial is irreducible iff it is
irreducible over `ℚ`. -/
theorem is_primitive.int.irreducible_iff_irreducible_map_cast
{p : polynomial ℤ} (hp : p.is_primitive) :
irreducible p ↔ irreducible (p.map (int.cast_ring_hom ℚ)) :=
hp.irreducible_iff_irreducible_map_fraction_map
lemma is_primitive.int.dvd_iff_map_cast_dvd_map_cast (p q : polynomial ℤ)
(hp : p.is_primitive) (hq : q.is_primitive) :
(p ∣ q) ↔ (p.map (int.cast_ring_hom ℚ) ∣ q.map (int.cast_ring_hom ℚ)) :=
hp.dvd_iff_fraction_map_dvd_fraction_map ℚ hq
end normalized_gcd_monoid
end polynomial
|
3b1d5aaf7051c00d2abc86e643611debfdb3883b | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/algebra/big_operators/ring_equiv.lean | 35864956133cf46ee314301b397a93fa5808e8c9 | [
"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 | 1,801 | lean | /-
Copyright (c) 2018 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Callum Sutton, Yury Kudryashov
-/
import algebra.big_operators.basic
import algebra.ring.equiv
/-!
# Results about mapping big operators across ring equivalences
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
-/
namespace ring_equiv
open_locale big_operators
variables {α R S : Type*}
protected lemma map_list_prod [semiring R] [semiring S] (f : R ≃+* S) (l : list R) :
f l.prod = (l.map f).prod := map_list_prod f l
protected lemma map_list_sum [non_assoc_semiring R] [non_assoc_semiring S] (f : R ≃+* S)
(l : list R) : f l.sum = (l.map f).sum := map_list_sum f l
/-- An isomorphism into the opposite ring acts on the product by acting on the reversed elements -/
protected lemma unop_map_list_prod [semiring R] [semiring S] (f : R ≃+* Sᵐᵒᵖ) (l : list R) :
mul_opposite.unop (f l.prod) = (l.map (mul_opposite.unop ∘ f)).reverse.prod :=
unop_map_list_prod f l
protected lemma map_multiset_prod [comm_semiring R] [comm_semiring S] (f : R ≃+* S)
(s : multiset R) : f s.prod = (s.map f).prod := map_multiset_prod f s
protected lemma map_multiset_sum [non_assoc_semiring R] [non_assoc_semiring S]
(f : R ≃+* S) (s : multiset R) : f s.sum = (s.map f).sum := map_multiset_sum f s
protected lemma map_prod [comm_semiring R] [comm_semiring S] (g : R ≃+* S) (f : α → R)
(s : finset α) : g (∏ x in s, f x) = ∏ x in s, g (f x) :=
map_prod g f s
protected lemma map_sum [non_assoc_semiring R] [non_assoc_semiring S]
(g : R ≃+* S) (f : α → R) (s : finset α) : g (∑ x in s, f x) = ∑ x in s, g (f x) :=
map_sum g f s
end ring_equiv
|
d3fba713415235690423bd7de6b2d680c949ebde | a7eef317ddec01b9fc6cfbb876fe7ac00f205ac7 | /src/linear_algebra/finite_dimensional.lean | 52d797dbcbd35705404eed0cfef8b9f3522eabc4 | [
"Apache-2.0"
] | permissive | kmill/mathlib | ea5a007b67ae4e9e18dd50d31d8aa60f650425ee | 1a419a9fea7b959317eddd556e1bb9639f4dcc05 | refs/heads/master | 1,668,578,197,719 | 1,593,629,163,000 | 1,593,629,163,000 | 276,482,939 | 0 | 0 | null | 1,593,637,960,000 | 1,593,637,959,000 | null | UTF-8 | Lean | false | false | 25,640 | 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
/-!
# 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_finite_basis` states that the existence of a finite basis 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_finite_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
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_finite_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 finite basis, then it is finite-dimensional, finset style. -/
lemma of_finset_basis {b : finset V} (h : is_basis K (coe : (↑b : set V) -> V)) :
finite_dimensional K V :=
iff_fg.2 $ ⟨b, by {convert h.2, simp} ⟩
/-- 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
/-- 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 zero_ne_one)]
/-- 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_finite_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 }
-- Note here we've restricted the universe levels of `ι` and `V` to be the same, for convenience.
lemma cardinal_mk_le_findim_of_linear_independent
[finite_dimensional K V] {ι : Type v} {b : ι → V} (h : linear_independent K b) :
cardinal.mk ι ≤ findim K V :=
begin
convert cardinal_le_dim_of_linear_independent h,
rw ←findim_eq_dim K V
end
-- Note here we've restricted the universe levels of `ι` and `V` to be the same, for convenience.
lemma fintype_card_le_findim_of_linear_independent
[finite_dimensional K V] {ι : Type v} [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
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, 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₀, add_left_injective (-x₀)⟩,
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*} [discrete_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 (submodule.span K ({x} : set V)) := by {apply span_of_finite, simp}
end finite_dimensional
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) }⟩
/-- 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 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 _ _ }
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,
rcases exists_is_basis_finite K V with ⟨s, s_basis, s_finite⟩,
letI : fintype s := s_finite.fintype,
have A : findim K V = fintype.card s := findim_eq_card_basis s_basis,
have : is_basis K (λx:s, f (subtype.val x)) := f.is_basis s_basis,
have B : findim K V₂ = fintype.card s := findim_eq_card_basis this,
rw [A, B]
end
end linear_equiv
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
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 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
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
end zero_dim
|
ec0cfdc745e1f83d621b56db7f7ae8cc9113d870 | 0845ae2ca02071debcfd4ac24be871236c01784f | /tests/bench/rbmap.library.lean | f8d4a94cfd0a94da1560d6090ce7d63c3dd71a50 | [
"Apache-2.0"
] | permissive | GaloisInc/lean4 | 74c267eb0e900bfaa23df8de86039483ecbd60b7 | 228ddd5fdcd98dd4e9c009f425284e86917938aa | refs/heads/master | 1,643,131,356,301 | 1,562,715,572,000 | 1,562,715,572,000 | 192,390,898 | 0 | 0 | null | 1,560,792,750,000 | 1,560,792,749,000 | null | UTF-8 | Lean | false | false | 390 | lean | @[reducible] def Map : Type := RBMap Nat Bool (fun a b => a < b)
def mkMapAux : Nat → Map → Map
| 0 m := m
| (n+1) m := mkMapAux n (m.insert n (n % 10 = 0))
def mkMap (n : Nat) :=
mkMapAux n {}
def main (xs : List String) : IO UInt32 :=
let m := mkMap xs.head.toNat;
let v := m.fold (fun (r : Nat) (k : Nat) (v : Bool) => if v then r + 1 else r) 0;
IO.println (toString v) *>
pure 0
|
240ae88acffbeb0be068d7a0c36c42c888ee0c42 | 947b78d97130d56365ae2ec264df196ce769371a | /tests/lean/classBadOutParam.lean | 2ffb6389de7a9b7977e8decd02abd3905359a3a5 | [
"Apache-2.0"
] | permissive | shyamalschandra/lean4 | 27044812be8698f0c79147615b1d5090b9f4b037 | 6e7a883b21eaf62831e8111b251dc9b18f40e604 | refs/heads/master | 1,671,417,126,371 | 1,601,859,995,000 | 1,601,860,020,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 215 | lean | new_frontend
class C1 (x : outParam Nat) (y : { n : Nat // n > x }) (α : Type) := -- should fail
(val : α)
class C2 (x : outParam Nat) (y : outParam { n : Nat // n > x }) (α : Type) := -- should work
(val : α)
|
7c1d4bce69f90541767aacbe3a91eb046afb69b8 | 9028d228ac200bbefe3a711342514dd4e4458bff | /src/algebra/ordered_field.lean | 685d8b2f6a2d6f9ba1d0fb6a46229333a69313ce | [
"Apache-2.0"
] | permissive | mcncm/mathlib | 8d25099344d9d2bee62822cb9ed43aa3e09fa05e | fde3d78cadeec5ef827b16ae55664ef115e66f57 | refs/heads/master | 1,672,743,316,277 | 1,602,618,514,000 | 1,602,618,514,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 24,366 | 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
/-!
### 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.
* `discrete_linear_ordered_field`: the class of linear ordered fields where the inequality is
decidable.
-/
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 : α}
/-!
### 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 :=
mul_pos ha (inv_pos.2 hb)
lemma div_pos_of_neg_of_neg (ha : a < 0) (hb : b < 0) : 0 < a / b :=
mul_pos_of_neg_of_neg ha (inv_lt_zero.2 hb)
lemma div_neg_of_neg_of_pos (ha : a < 0) (hb : 0 < b) : a / b < 0 :=
mul_neg_of_neg_of_pos ha (inv_pos.2 hb)
lemma div_neg_of_pos_of_neg (ha : 0 < a) (hb : b < 0) : a / b < 0 :=
mul_neg_of_pos_of_neg ha (inv_lt_zero.2 hb)
lemma div_nonneg (ha : 0 ≤ a) (hb : 0 ≤ b) : 0 ≤ a / b :=
mul_nonneg ha (inv_nonneg.2 hb)
lemma div_nonneg_of_nonpos (ha : a ≤ 0) (hb : b ≤ 0) : 0 ≤ a / b :=
mul_nonneg_of_nonpos_of_nonpos ha (inv_nonpos.2 hb)
lemma div_nonpos_of_nonpos_of_nonneg (ha : a ≤ 0) (hb : 0 ≤ b) : a / b ≤ 0 :=
mul_nonpos_of_nonpos_of_nonneg ha (inv_nonneg.2 hb)
lemma div_nonpos_of_nonneg_of_nonpos (ha : 0 ≤ a) (hb : b ≤ 0) : a / b ≤ 0 :=
mul_nonpos_of_nonneg_of_nonpos ha (inv_nonpos.2 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 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_iff_of_nonneg_of_le (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'] }
/-!
### 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]
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 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)
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 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.
-/
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
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 :=
mul_le_mul_of_nonneg_right hab (inv_nonneg.2 hc)
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 :=
(mul_lt_mul_left ha).trans (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]
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 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
/-!
### Miscellaneous lemmas
-/
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) :=
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) :=
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] }
end linear_ordered_field
/-- A discrete linear ordered field is a field with a decidable linear order respecting the
operations. -/
@[protect_proj] class discrete_linear_ordered_field (α : Type*)
extends linear_ordered_field α, decidable_linear_ordered_comm_ring α
section discrete_linear_ordered_field
variables [discrete_linear_ordered_field α]
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 : α →* α).map_div abs_zero a b
lemma abs_one_div (a : α) : abs (1 / a) = 1 / abs a :=
by rw [abs_div, abs_of_nonneg (zero_le_one : 1 ≥ (0 : α))]
lemma abs_inv (a : α) : abs a⁻¹ = (abs a)⁻¹ :=
by rw [inv_eq_one_div, abs_one_div, inv_eq_one_div]
end discrete_linear_ordered_field
|
be7958683d2b7454a275d54d6bda81ee3b059d8b | a46270e2f76a375564f3b3e9c1bf7b635edc1f2c | /8.9.2.lean | ee645c59c8dee73f48cbf7780d33a3bf9efa5b71 | [
"CC0-1.0"
] | permissive | wudcscheme/lean-exercise | 88ea2506714eac343de2a294d1132ee8ee6d3a20 | 5b23b9be3d361fff5e981d5be3a0a1175504b9f6 | refs/heads/master | 1,678,958,930,293 | 1,583,197,205,000 | 1,583,197,205,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 4,666 | lean | namespace hidden
-- BEGIN
inductive nat : Type
| zero : nat
| succ : nat → nat
-- END
@[pattern]
def Z := nat.zero
@[pattern]
def S := nat.succ
def K₁ := S Z
def K₂ := S K₁
def K₃ := S K₂
def K₄ := S K₃
def K₅ := S K₄
def pred: nat -> nat
| Z := Z
| (S n) := n
.
theorem pr₀ : pred Z = Z := rfl.
theorem pr₁ : pred K₁ = Z := rfl.
theorem pr₂ : pred K₂ = K₁ := rfl.
theorem pred_succ_zero (n: nat): pred (S n) = n := rfl.
def sub: nat -> nat -> nat
| n Z := n
| n (S m) := pred (sub n m)
.
#reduce sub Z K₂
#reduce sub K₅ K₂
example: sub Z K₅ = Z := rfl.
theorem sub_n_0: ∀(n: nat), sub n Z = n
| Z := rfl
| (S n) := rfl
theorem sub_0_m: ∀ (m:nat), sub Z m = Z
| Z := rfl
| (S m) := by rw[sub, sub_0_m]; reflexivity.
lemma sub_succ (n m: nat): sub (S n) (S m) = sub n m := begin
induction m,
case nat.zero: {
reflexivity
},
case nat.succ: m ih {
have: sub (S n) (S (S m)) = pred (sub (S n) (S m)), from rfl,
have: sub (S n) (S (S m)) = pred (sub n m), by rw[this, ih],
have: pred (sub n m) = sub n (S m), by reflexivity,
assumption
}
end
theorem sub_n_n: ∀(n: nat), sub n n = Z
| Z := rfl
| (S n) := by rw[sub_succ, sub_n_n]
.
def add: nat -> nat -> nat
| m Z := m
| m (S n) := S (add m n)
.
lemma add_n_succ (m n: nat): add m (S n) = S (add m n) := rfl.
lemma add_m_succ (m: nat): ∀ (n: nat), add (S m) n = S (add m n)
| Z := rfl
| (S n) := begin
simp [add_n_succ],
rw add_m_succ,
end
lemma add_m_0 (m: nat): add m Z = m := rfl.
lemma add_0_n: ∀ (n: nat), add Z n = n
| Z := rfl
| (S n) := by simp [add_n_succ, add_0_n n]
.
theorem add_assoc (a b: nat): ∀(c: nat), add (add a b) c = add a (add b c)
| Z := rfl
| (S c) := by simp[add_n_succ, add_assoc c]
.
theorem add_comm (m: nat): ∀(n: nat), add m n = add n m
| Z := by simp[add_m_0, add_0_n]
| (S n) := by simp[add_n_succ, add_m_succ, add_comm n]
.
#reduce add K₁ K₂
def mul: nat -> nat -> nat
| _ Z := Z
| m (S n) := add m (mul m n)
.
#reduce mul Z K₂
#reduce mul K₂ Z
#reduce mul K₁ K₂
#reduce mul K₂ K₂
#reduce mul K₅ K₂
lemma mul_succ_n (m n: nat): mul m (S n) = add m (mul m n) := rfl.
lemma mul_succ_m (m: nat): ∀ (n: nat), mul (S m) n = add (mul m n) n
| Z := rfl
| (S n) := by simp[mul_succ_n, mul_succ_m n, add_n_succ, add_m_succ, add_assoc]
.
theorem mul_m_0 (m: nat): mul m Z = Z := rfl.
theorem mul_0_n: ∀ (n: nat), mul Z n = Z
| Z := rfl
| (S n) := by simp[mul_succ_n, mul_0_n n]; reflexivity
.
theorem mul_m_1 (m: nat): mul m K₁ = m := rfl
theorem mul_1_n (n: nat): mul K₁ n = n := begin
rw [K₁],
simp [mul_succ_m, mul_0_n, add_0_n],
end
theorem mul_comm (m: nat): ∀(n: nat), mul m n = mul n m
| Z := by simp[mul_m_0, mul_0_n]
| (S n) := by simp [mul_succ_n, mul_succ_m, mul_comm n, add_comm]
.
theorem mul_dist (b c: nat): ∀ (a: nat), mul a (add b c) = add (mul a b) (mul a c)
| Z := by simp [mul_0_n]; reflexivity
| (S a) := begin
simp[mul_succ_m, add_assoc, mul_dist a],
rw [<-add_assoc (mul a c), add_comm (mul a c), <-add_assoc b],
end
theorem mul_assoc (a b: nat): ∀(c: nat), mul (mul a b) c = mul a (mul b c)
| Z := rfl
| (S c) := by simp[mul_succ_n, mul_assoc c, mul_dist]
.
theorem succ_nonzero (n: nat): S n ≠ Z := by trivial.
def nonzero := {n: nat // n ≠ Z}
def nonzero.mk (n: nat) (h: n ≠ Z): nonzero := ⟨n,h⟩
def nz := nonzero.mk.
#check nz K₂ (by apply succ_nonzero)
def pow: nonzero -> nat -> nat
| _ Z := K₁
| m (S n) := mul m.val (pow m n)
def nzK₁ := nz (S Z) (by apply succ_nonzero)
def nzK₂ := nz (S K₁) (by apply succ_nonzero)
def nzK₃ := nz (S K₂) (by apply succ_nonzero)
def nzK₄ := nz (S K₃) (by apply succ_nonzero)
def nzK₅ := nz (S K₄) (by apply succ_nonzero)
#reduce pow nzK₂ Z
#reduce pow nzK₁ K₂
#reduce pow nzK₂ K₂
#reduce pow nzK₃ K₂
theorem pow_by_0 (m: nonzero): pow m Z = K₁ := rfl.
theorem pow_by_1 (m: nonzero): pow m K₁ = m.val := rfl.
theorem pow_by_succ (m: nonzero) (n: nat): pow m (S n) = mul m.val (pow m n) := rfl.
theorem pow_of_1: ∀ (n: nat), pow nzK₁ n = K₁
| Z := rfl
| (S n) := begin
have o: nzK₁.val = K₁, from rfl,
have: pow nzK₁ (S n) = mul nzK₁.val (pow nzK₁ n), by rw [pow_by_succ],
simp [o, mul_1_n] at this,
simp [pow_of_1 n] at this, assumption
end
theorem pow_by_add (m: nonzero) (a: nat): ∀(b: nat), pow m (add a b) = mul (pow m a) (pow m b)
| Z := rfl
| (S b) := by simp [add_n_succ, pow_by_succ, pow_by_add b, mul_comm, mul_assoc].
end hidden |
638d75333d1d8710e19a906f72d9d3963faa52b1 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/category_theory/monoidal/types.lean | 0888239c85b809bfe5e5b2fc9441e52de89ac775 | [] | 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,084 | lean | /-
Copyright (c) 2018 Michael Jendrusch. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Michael Jendrusch, Scott Morrison
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.category_theory.monoidal.of_chosen_finite_products
import Mathlib.category_theory.limits.shapes.finite_products
import Mathlib.category_theory.limits.shapes.types
import Mathlib.PostPort
universes u
namespace Mathlib
/-!
# The category of types is a symmetric monoidal category
-/
namespace category_theory.monoidal
protected instance types_monoidal : monoidal_category (Type u) :=
monoidal_of_chosen_finite_products limits.types.terminal_limit_cone limits.types.binary_product_limit_cone
protected instance types_symmetric : symmetric_category (Type u) :=
symmetric_of_chosen_finite_products limits.types.terminal_limit_cone limits.types.binary_product_limit_cone
@[simp] theorem tensor_apply {W : Type u} {X : Type u} {Y : Type u} {Z : Type u} (f : W ⟶ X) (g : Y ⟶ Z) (p : W ⊗ Y) : monoidal_category.tensor_hom f g p = (f (prod.fst p), g (prod.snd p)) :=
rfl
@[simp] theorem left_unitor_hom_apply {X : Type u} {x : X} {p : PUnit} : iso.hom λ_ (p, x) = x :=
rfl
@[simp] theorem left_unitor_inv_apply {X : Type u} {x : X} : iso.inv λ_ x = (PUnit.unit, x) :=
rfl
@[simp] theorem right_unitor_hom_apply {X : Type u} {x : X} {p : PUnit} : iso.hom ρ_ (x, p) = x :=
rfl
@[simp] theorem right_unitor_inv_apply {X : Type u} {x : X} : iso.inv ρ_ x = (x, PUnit.unit) :=
rfl
@[simp] theorem associator_hom_apply {X : Type u} {Y : Type u} {Z : Type u} {x : X} {y : Y} {z : Z} : iso.hom α_ ((x, y), z) = (x, y, z) :=
rfl
@[simp] theorem associator_inv_apply {X : Type u} {Y : Type u} {Z : Type u} {x : X} {y : Y} {z : Z} : iso.inv α_ (x, y, z) = ((x, y), z) :=
rfl
@[simp] theorem braiding_hom_apply {X : Type u} {Y : Type u} {x : X} {y : Y} : iso.hom β_ (x, y) = (y, x) :=
rfl
@[simp] theorem braiding_inv_apply {X : Type u} {Y : Type u} {x : X} {y : Y} : iso.inv β_ (y, x) = (x, y) :=
rfl
|
52389e286addc1fc0fbec90669a37a2f134700e9 | 57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d | /stage0/src/Lean/Environment.lean | 88ecd0806392565426854bfd790d38486c679b54 | [
"Apache-2.0"
] | permissive | collares/lean4 | 861a9269c4592bce49b71059e232ff0bfe4594cc | 52a4f535d853a2c7c7eea5fee8a4fa04c682c1ee | refs/heads/master | 1,691,419,031,324 | 1,618,678,138,000 | 1,618,678,138,000 | 358,989,750 | 0 | 0 | Apache-2.0 | 1,618,696,333,000 | 1,618,696,333,000 | null | UTF-8 | Lean | false | false | 30,202 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Std.Data.HashMap
import Lean.Data.SMap
import Lean.Declaration
import Lean.LocalContext
import Lean.Util.Path
import Lean.Util.FindExpr
import Lean.Util.Profile
namespace Lean
/- Opaque environment extension state. -/
constant EnvExtensionStateSpec : PointedType.{0}
def EnvExtensionState : Type := EnvExtensionStateSpec.type
instance : Inhabited EnvExtensionState where
default := EnvExtensionStateSpec.val
def ModuleIdx := Nat
instance : Inhabited ModuleIdx := inferInstanceAs (Inhabited Nat)
abbrev ConstMap := SMap Name ConstantInfo
structure Import where
module : Name
runtimeOnly : Bool := false
instance : ToString Import := ⟨fun imp => toString imp.module ++ if imp.runtimeOnly then " (runtime)" else ""⟩
/--
A compacted region holds multiple Lean objects in a contiguous memory region, which can be read/written to/from disk.
Objects inside the region do not have reference counters and cannot be freed individually. The contents of .olean
files are compacted regions. -/
def CompactedRegion := USize
/-- Free a compacted region and its contents. No live references to the contents may exist at the time of invocation. -/
@[extern 2 "lean_compacted_region_free"]
unsafe constant CompactedRegion.free : CompactedRegion → IO Unit
/- Environment fields that are not used often. -/
structure EnvironmentHeader where
trustLevel : UInt32 := 0
quotInit : Bool := false
mainModule : Name := arbitrary
imports : Array Import := #[] -- direct imports
regions : Array CompactedRegion := #[] -- compacted regions of all imported modules
moduleNames : Array Name := #[] -- names of all imported modules
deriving Inhabited
open Std (HashMap)
structure Environment where
const2ModIdx : HashMap Name ModuleIdx
constants : ConstMap
extensions : Array EnvExtensionState
header : EnvironmentHeader := {}
deriving Inhabited
namespace Environment
def addAux (env : Environment) (cinfo : ConstantInfo) : Environment :=
{ env with constants := env.constants.insert cinfo.name cinfo }
@[export lean_environment_find]
def find? (env : Environment) (n : Name) : Option ConstantInfo :=
/- It is safe to use `find'` because we never overwrite imported declarations. -/
env.constants.find?' n
def contains (env : Environment) (n : Name) : Bool :=
env.constants.contains n
def imports (env : Environment) : Array Import :=
env.header.imports
def allImportedModuleNames (env : Environment) : Array Name :=
env.header.moduleNames
@[export lean_environment_set_main_module]
def setMainModule (env : Environment) (m : Name) : Environment :=
{ env with header := { env.header with mainModule := m } }
@[export lean_environment_main_module]
def mainModule (env : Environment) : Name :=
env.header.mainModule
@[export lean_environment_mark_quot_init]
private def markQuotInit (env : Environment) : Environment :=
{ env with header := { env.header with quotInit := true } }
@[export lean_environment_quot_init]
private def isQuotInit (env : Environment) : Bool :=
env.header.quotInit
@[export lean_environment_trust_level]
private def getTrustLevel (env : Environment) : UInt32 :=
env.header.trustLevel
def getModuleIdxFor? (env : Environment) (c : Name) : Option ModuleIdx :=
env.const2ModIdx.find? c
def isConstructor (env : Environment) (c : Name) : Bool :=
match env.find? c with
| ConstantInfo.ctorInfo _ => true
| _ => false
end Environment
inductive KernelException where
| unknownConstant (env : Environment) (name : Name)
| alreadyDeclared (env : Environment) (name : Name)
| declTypeMismatch (env : Environment) (decl : Declaration) (givenType : Expr)
| declHasMVars (env : Environment) (name : Name) (expr : Expr)
| declHasFVars (env : Environment) (name : Name) (expr : Expr)
| funExpected (env : Environment) (lctx : LocalContext) (expr : Expr)
| typeExpected (env : Environment) (lctx : LocalContext) (expr : Expr)
| letTypeMismatch (env : Environment) (lctx : LocalContext) (name : Name) (givenType : Expr) (expectedType : Expr)
| exprTypeMismatch (env : Environment) (lctx : LocalContext) (expr : Expr) (expectedType : Expr)
| appTypeMismatch (env : Environment) (lctx : LocalContext) (app : Expr) (funType : Expr) (argType : Expr)
| invalidProj (env : Environment) (lctx : LocalContext) (proj : Expr)
| other (msg : String)
namespace Environment
/- Type check given declaration and add it to the environment -/
@[extern "lean_add_decl"]
constant addDecl (env : Environment) (decl : @& Declaration) : Except KernelException Environment
/- Compile the given declaration, it assumes the declaration has already been added to the environment using `addDecl`. -/
@[extern "lean_compile_decl"]
constant compileDecl (env : Environment) (opt : @& Options) (decl : @& Declaration) : Except KernelException Environment
def addAndCompile (env : Environment) (opt : Options) (decl : Declaration) : Except KernelException Environment := do
let env ← addDecl env decl
compileDecl env opt decl
end Environment
/- Interface for managing environment extensions. -/
structure EnvExtensionInterface where
ext : Type → Type
inhabitedExt {σ} : Inhabited σ → Inhabited (ext σ)
registerExt {σ} (mkInitial : IO σ) : IO (ext σ)
setState {σ} (e : ext σ) (env : Environment) : σ → Environment
modifyState {σ} (e : ext σ) (env : Environment) : (σ → σ) → Environment
getState {σ} (e : ext σ) (env : Environment) : σ
mkInitialExtStates : IO (Array EnvExtensionState)
instance : Inhabited EnvExtensionInterface where
default := {
ext := id,
inhabitedExt := id,
registerExt := fun mk => mk,
setState := fun _ env _ => env,
modifyState := fun _ env _ => env,
getState := fun ext _ => ext,
mkInitialExtStates := pure #[]
}
/- Unsafe implementation of `EnvExtensionInterface` -/
namespace EnvExtensionInterfaceUnsafe
structure Ext (σ : Type) where
idx : Nat
mkInitial : IO σ
deriving Inhabited
private def mkEnvExtensionsRef : IO (IO.Ref (Array (Ext EnvExtensionState))) := IO.mkRef #[]
@[builtinInit mkEnvExtensionsRef] private constant envExtensionsRef : IO.Ref (Array (Ext EnvExtensionState))
unsafe def setState {σ} (ext : Ext σ) (env : Environment) (s : σ) : Environment :=
{ env with extensions := env.extensions.set! ext.idx (unsafeCast s) }
@[inline] unsafe def modifyState {σ : Type} (ext : Ext σ) (env : Environment) (f : σ → σ) : Environment :=
{ env with
extensions := env.extensions.modify ext.idx fun s =>
let s : σ := unsafeCast s;
let s : σ := f s;
unsafeCast s }
unsafe def getState {σ} (ext : Ext σ) (env : Environment) : σ :=
let s : EnvExtensionState := env.extensions.get! ext.idx
unsafeCast s
unsafe def registerExt {σ} (mkInitial : IO σ) : IO (Ext σ) := do
let initializing ← IO.initializing
unless initializing do throw (IO.userError "failed to register environment, extensions can only be registered during initialization")
let exts ← envExtensionsRef.get
let idx := exts.size
let ext : Ext σ := {
idx := idx,
mkInitial := mkInitial,
}
envExtensionsRef.modify fun exts => exts.push (unsafeCast ext)
pure ext
def mkInitialExtStates : IO (Array EnvExtensionState) := do
let exts ← envExtensionsRef.get
exts.mapM fun ext => ext.mkInitial
unsafe def imp : EnvExtensionInterface := {
ext := Ext,
inhabitedExt := fun _ => ⟨arbitrary⟩,
registerExt := registerExt,
setState := setState,
modifyState := modifyState,
getState := getState,
mkInitialExtStates := mkInitialExtStates
}
end EnvExtensionInterfaceUnsafe
@[implementedBy EnvExtensionInterfaceUnsafe.imp]
constant EnvExtensionInterfaceImp : EnvExtensionInterface
def EnvExtension (σ : Type) : Type := EnvExtensionInterfaceImp.ext σ
namespace EnvExtension
instance {σ} [s : Inhabited σ] : Inhabited (EnvExtension σ) := EnvExtensionInterfaceImp.inhabitedExt s
def setState {σ : Type} (ext : EnvExtension σ) (env : Environment) (s : σ) : Environment := EnvExtensionInterfaceImp.setState ext env s
def modifyState {σ : Type} (ext : EnvExtension σ) (env : Environment) (f : σ → σ) : Environment := EnvExtensionInterfaceImp.modifyState ext env f
def getState {σ : Type} (ext : EnvExtension σ) (env : Environment) : σ := EnvExtensionInterfaceImp.getState ext env
end EnvExtension
/- Environment extensions can only be registered during initialization.
Reasons:
1- Our implementation assumes the number of extensions does not change after an environment object is created.
2- We do not use any synchronization primitive to access `envExtensionsRef`. -/
def registerEnvExtension {σ : Type} (mkInitial : IO σ) : IO (EnvExtension σ) := EnvExtensionInterfaceImp.registerExt mkInitial
private def mkInitialExtensionStates : IO (Array EnvExtensionState) := EnvExtensionInterfaceImp.mkInitialExtStates
@[export lean_mk_empty_environment]
def mkEmptyEnvironment (trustLevel : UInt32 := 0) : IO Environment := do
let initializing ← IO.initializing
if initializing then throw (IO.userError "environment objects cannot be created during initialization")
let exts ← mkInitialExtensionStates
pure {
const2ModIdx := {},
constants := {},
header := { trustLevel := trustLevel },
extensions := exts
}
structure PersistentEnvExtensionState (α : Type) (σ : Type) where
importedEntries : Array (Array α) -- entries per imported module
state : σ
structure ImportM.Context where
env : Environment
opts : Options
abbrev ImportM := ReaderT Lean.ImportM.Context IO
/- An environment extension with support for storing/retrieving entries from a .olean file.
- α is the type of the entries that are stored in .olean files.
- β is the type of values used to update the state.
- σ is the actual state.
Remark: for most extensions α and β coincide.
Note that `addEntryFn` is not in `IO`. This is intentional, and allows us to write simple functions such as
```
def addAlias (env : Environment) (a : Name) (e : Name) : Environment :=
aliasExtension.addEntry env (a, e)
```
without using `IO`. We have many functions like `addAlias`.
`α` and ‵β` do not coincide for extensions where the data used to update the state contains, for example,
closures which we currently cannot store in files. -/
structure PersistentEnvExtension (α : Type) (β : Type) (σ : Type) where
toEnvExtension : EnvExtension (PersistentEnvExtensionState α σ)
name : Name
addImportedFn : Array (Array α) → ImportM σ
addEntryFn : σ → β → σ
exportEntriesFn : σ → Array α
statsFn : σ → Format
/- Opaque persistent environment extension entry. -/
constant EnvExtensionEntrySpec : PointedType.{0}
def EnvExtensionEntry : Type := EnvExtensionEntrySpec.type
instance : Inhabited EnvExtensionEntry := ⟨EnvExtensionEntrySpec.val⟩
instance {α σ} [Inhabited σ] : Inhabited (PersistentEnvExtensionState α σ) :=
⟨{importedEntries := #[], state := arbitrary }⟩
instance {α β σ} [Inhabited σ] : Inhabited (PersistentEnvExtension α β σ) where
default := {
toEnvExtension := arbitrary,
name := arbitrary,
addImportedFn := fun _ => arbitrary,
addEntryFn := fun s _ => s,
exportEntriesFn := fun _ => #[],
statsFn := fun _ => Format.nil
}
namespace PersistentEnvExtension
def getModuleEntries {α β σ : Type} (ext : PersistentEnvExtension α β σ) (env : Environment) (m : ModuleIdx) : Array α :=
(ext.toEnvExtension.getState env).importedEntries.get! m
def addEntry {α β σ : Type} (ext : PersistentEnvExtension α β σ) (env : Environment) (b : β) : Environment :=
ext.toEnvExtension.modifyState env fun s =>
let state := ext.addEntryFn s.state b;
{ s with state := state }
def getState {α β σ : Type} (ext : PersistentEnvExtension α β σ) (env : Environment) : σ :=
(ext.toEnvExtension.getState env).state
def setState {α β σ : Type} (ext : PersistentEnvExtension α β σ) (env : Environment) (s : σ) : Environment :=
ext.toEnvExtension.modifyState env $ fun ps => { ps with state := s }
def modifyState {α β σ : Type} (ext : PersistentEnvExtension α β σ) (env : Environment) (f : σ → σ) : Environment :=
ext.toEnvExtension.modifyState env $ fun ps => { ps with state := f (ps.state) }
end PersistentEnvExtension
builtin_initialize persistentEnvExtensionsRef : IO.Ref (Array (PersistentEnvExtension EnvExtensionEntry EnvExtensionEntry EnvExtensionState)) ← IO.mkRef #[]
structure PersistentEnvExtensionDescr (α β σ : Type) where
name : Name
mkInitial : IO σ
addImportedFn : Array (Array α) → ImportM σ
addEntryFn : σ → β → σ
exportEntriesFn : σ → Array α
statsFn : σ → Format := fun _ => Format.nil
unsafe def registerPersistentEnvExtensionUnsafe {α β σ : Type} [Inhabited σ] (descr : PersistentEnvExtensionDescr α β σ) : IO (PersistentEnvExtension α β σ) := do
let pExts ← persistentEnvExtensionsRef.get
if pExts.any (fun ext => ext.name == descr.name) then throw (IO.userError s!"invalid environment extension, '{descr.name}' has already been used")
let ext ← registerEnvExtension do
let initial ← descr.mkInitial
let s : PersistentEnvExtensionState α σ := {
importedEntries := #[],
state := initial
}
pure s
let pExt : PersistentEnvExtension α β σ := {
toEnvExtension := ext,
name := descr.name,
addImportedFn := descr.addImportedFn,
addEntryFn := descr.addEntryFn,
exportEntriesFn := descr.exportEntriesFn,
statsFn := descr.statsFn
}
persistentEnvExtensionsRef.modify fun pExts => pExts.push (unsafeCast pExt)
return pExt
@[implementedBy registerPersistentEnvExtensionUnsafe]
constant registerPersistentEnvExtension {α β σ : Type} [Inhabited σ] (descr : PersistentEnvExtensionDescr α β σ) : IO (PersistentEnvExtension α β σ)
/- Simple PersistentEnvExtension that implements exportEntriesFn using a list of entries. -/
def SimplePersistentEnvExtension (α σ : Type) := PersistentEnvExtension α α (List α × σ)
@[specialize] def mkStateFromImportedEntries {α σ : Type} (addEntryFn : σ → α → σ) (initState : σ) (as : Array (Array α)) : σ :=
as.foldl (fun r es => es.foldl (fun r e => addEntryFn r e) r) initState
structure SimplePersistentEnvExtensionDescr (α σ : Type) where
name : Name
addEntryFn : σ → α → σ
addImportedFn : Array (Array α) → σ
toArrayFn : List α → Array α := fun es => es.toArray
def registerSimplePersistentEnvExtension {α σ : Type} [Inhabited σ] (descr : SimplePersistentEnvExtensionDescr α σ) : IO (SimplePersistentEnvExtension α σ) :=
registerPersistentEnvExtension {
name := descr.name,
mkInitial := pure ([], descr.addImportedFn #[]),
addImportedFn := fun as => pure ([], descr.addImportedFn as),
addEntryFn := fun s e => match s with
| (entries, s) => (e::entries, descr.addEntryFn s e),
exportEntriesFn := fun s => descr.toArrayFn s.1.reverse,
statsFn := fun s => format "number of local entries: " ++ format s.1.length
}
namespace SimplePersistentEnvExtension
instance {α σ : Type} [Inhabited σ] : Inhabited (SimplePersistentEnvExtension α σ) :=
inferInstanceAs (Inhabited (PersistentEnvExtension α α (List α × σ)))
def getEntries {α σ : Type} (ext : SimplePersistentEnvExtension α σ) (env : Environment) : List α :=
(PersistentEnvExtension.getState ext env).1
def getState {α σ : Type} (ext : SimplePersistentEnvExtension α σ) (env : Environment) : σ :=
(PersistentEnvExtension.getState ext env).2
def setState {α σ : Type} (ext : SimplePersistentEnvExtension α σ) (env : Environment) (s : σ) : Environment :=
PersistentEnvExtension.modifyState ext env (fun ⟨entries, _⟩ => (entries, s))
def modifyState {α σ : Type} (ext : SimplePersistentEnvExtension α σ) (env : Environment) (f : σ → σ) : Environment :=
PersistentEnvExtension.modifyState ext env (fun ⟨entries, s⟩ => (entries, f s))
end SimplePersistentEnvExtension
/-- Environment extension for tagging declarations.
Declarations must only be tagged in the module where they were declared. -/
def TagDeclarationExtension := SimplePersistentEnvExtension Name NameSet
def mkTagDeclarationExtension (name : Name) : IO TagDeclarationExtension :=
registerSimplePersistentEnvExtension {
name := name,
addImportedFn := fun as => {},
addEntryFn := fun s n => s.insert n,
toArrayFn := fun es => es.toArray.qsort Name.quickLt
}
namespace TagDeclarationExtension
instance : Inhabited TagDeclarationExtension :=
inferInstanceAs (Inhabited (SimplePersistentEnvExtension Name NameSet))
def tag (ext : TagDeclarationExtension) (env : Environment) (n : Name) : Environment :=
ext.addEntry env n
def isTagged (ext : TagDeclarationExtension) (env : Environment) (n : Name) : Bool :=
match env.getModuleIdxFor? n with
| some modIdx => (ext.getModuleEntries env modIdx).binSearchContains n Name.quickLt
| none => (ext.getState env).contains n
end TagDeclarationExtension
/-- Environment extension for mapping declarations to values. -/
def MapDeclarationExtension (α : Type) := SimplePersistentEnvExtension (Name × α) (NameMap α)
def mkMapDeclarationExtension [Inhabited α] (name : Name) : IO (MapDeclarationExtension α) :=
registerSimplePersistentEnvExtension {
name := name,
addImportedFn := fun as => {},
addEntryFn := fun s n => s.insert n.1 n.2 ,
toArrayFn := fun es => es.toArray.qsort (fun a b => Name.quickLt a.1 b.1)
}
namespace MapDeclarationExtension
instance : Inhabited (MapDeclarationExtension α) :=
inferInstanceAs (Inhabited (SimplePersistentEnvExtension ..))
def insert (ext : MapDeclarationExtension α) (env : Environment) (declName : Name) (val : α) : Environment :=
ext.addEntry env (declName, val)
def find? [Inhabited α] (ext : MapDeclarationExtension α) (env : Environment) (declName : Name) : Option α :=
match env.getModuleIdxFor? declName with
| some modIdx =>
match (ext.getModuleEntries env modIdx).binSearch (declName, arbitrary) (fun a b => Name.quickLt a.1 b.1) with
| some e => some e.2
| none => none
| none => (ext.getState env).find? declName
def contains [Inhabited α] (ext : MapDeclarationExtension α) (env : Environment) (declName : Name) : Bool :=
match env.getModuleIdxFor? declName with
| some modIdx => (ext.getModuleEntries env modIdx).binSearchContains (declName, arbitrary) (fun a b => Name.quickLt a.1 b.1)
| none => (ext.getState env).contains declName
end MapDeclarationExtension
/- Content of a .olean file.
We use `compact.cpp` to generate the image of this object in disk. -/
structure ModuleData where
imports : Array Import
constants : Array ConstantInfo
entries : Array (Name × Array EnvExtensionEntry)
instance : Inhabited ModuleData :=
⟨{imports := arbitrary, constants := arbitrary, entries := arbitrary }⟩
@[extern 3 "lean_save_module_data"]
constant saveModuleData (fname : @& String) (m : ModuleData) : IO Unit
@[extern 2 "lean_read_module_data"]
constant readModuleData (fname : @& String) : IO (ModuleData × CompactedRegion)
/--
Free compacted regions of imports. No live references to imported objects may exist at the time of invocation; in
particular, `env` should be the last reference to any `Environment` derived from these imports. -/
@[noinline, export lean_environment_free_regions]
unsafe def Environment.freeRegions (env : Environment) : IO Unit :=
/-
NOTE: This assumes `env` is not inferred as a borrowed parameter, and is freed after extracting the `header` field.
Otherwise, we would encounter undefined behavior when the constant map in `env`, which may reference objects in
compacted regions, is freed after the regions.
In the currently produced IR, we indeed see:
```
def Lean.Environment.freeRegions (x_1 : obj) (x_2 : obj) : obj :=
let x_3 : obj := proj[3] x_1;
inc x_3;
dec x_1;
...
```
TODO: statically check for this. -/
env.header.regions.forM CompactedRegion.free
def mkModuleData (env : Environment) : IO ModuleData := do
let pExts ← persistentEnvExtensionsRef.get
let entries : Array (Name × Array EnvExtensionEntry) := pExts.size.fold
(fun i result =>
let state := (pExts.get! i).getState env
let exportEntriesFn := (pExts.get! i).exportEntriesFn
let extName := (pExts.get! i).name
result.push (extName, exportEntriesFn state))
#[]
pure {
imports := env.header.imports,
constants := env.constants.foldStage2 (fun cs _ c => cs.push c) #[],
entries := entries
}
@[export lean_write_module]
def writeModule (env : Environment) (fname : String) : IO Unit := do
let modData ← mkModuleData env; saveModuleData fname modData
private partial def getEntriesFor (mod : ModuleData) (extId : Name) (i : Nat) : Array EnvExtensionEntry :=
if i < mod.entries.size then
let curr := mod.entries.get! i;
if curr.1 == extId then curr.2 else getEntriesFor mod extId (i+1)
else
#[]
private def setImportedEntries (env : Environment) (mods : Array ModuleData) : IO Environment := do
let mut env := env
let pExtDescrs ← persistentEnvExtensionsRef.get
for mod in mods do
for extDescr in pExtDescrs do
let entries := getEntriesFor mod extDescr.name 0
env ← extDescr.toEnvExtension.modifyState env fun s => { s with importedEntries := s.importedEntries.push entries }
return env
private def finalizePersistentExtensions (env : Environment) (opts : Options) : IO Environment := do
let mut env := env
let pExtDescrs ← persistentEnvExtensionsRef.get
for extDescr in pExtDescrs do
let s := extDescr.toEnvExtension.getState env
let newState ← extDescr.addImportedFn s.importedEntries { env := env, opts := opts }
env ← extDescr.toEnvExtension.setState env { s with state := newState }
return env
structure ImportState where
moduleNameSet : NameSet := {}
moduleNames : Array Name := #[]
moduleData : Array ModuleData := #[]
regions : Array CompactedRegion := #[]
@[export lean_import_modules]
partial def importModules (imports : List Import) (opts : Options) (trustLevel : UInt32 := 0) : IO Environment := profileitIO "import" opts do
let (_, s) ← importMods imports |>.run {}
-- (moduleNames, mods, regions)
let mut modIdx : Nat := 0
let mut const2ModIdx : HashMap Name ModuleIdx := {}
let mut constants : ConstMap := SMap.empty
for mod in s.moduleData do
for cinfo in mod.constants do
const2ModIdx := const2ModIdx.insert cinfo.name modIdx
if constants.contains cinfo.name then throw (IO.userError s!"import failed, environment already contains '{cinfo.name}'")
constants := constants.insert cinfo.name cinfo
modIdx := modIdx + 1
constants := constants.switch
let exts ← mkInitialExtensionStates
let env : Environment := {
const2ModIdx := const2ModIdx,
constants := constants,
extensions := exts,
header := {
quotInit := !imports.isEmpty, -- We assume `core.lean` initializes quotient module
trustLevel := trustLevel,
imports := imports.toArray,
regions := s.regions,
moduleNames := s.moduleNames
}
}
let env ← setImportedEntries env s.moduleData
let env ← finalizePersistentExtensions env opts
pure env
where
importMods : List Import → StateRefT ImportState IO Unit
| [] => pure ()
| i::is => do
if i.runtimeOnly || (← get).moduleNameSet.contains i.module then
importMods is
else do
modify fun s => { s with moduleNameSet := s.moduleNameSet.insert i.module }
let mFile ← findOLean i.module
unless (← IO.fileExists mFile) do
throw $ IO.userError s!"object file '{mFile}' of module {i.module} does not exist"
let (mod, region) ← readModuleData mFile
importMods mod.imports.toList
modify fun s => { s with
moduleData := s.moduleData.push mod
regions := s.regions.push region
moduleNames := s.moduleNames.push i.module
}
importMods is
/--
Create environment object from imports and free compacted regions after calling `act`. No live references to the
environment object or imported objects may exist after `act` finishes. -/
unsafe def withImportModules {α : Type} (imports : List Import) (opts : Options) (trustLevel : UInt32 := 0) (x : Environment → IO α) : IO α := do
let env ← importModules imports opts trustLevel
try x env finally env.freeRegions
builtin_initialize namespacesExt : SimplePersistentEnvExtension Name NameSet ←
registerSimplePersistentEnvExtension {
name := `namespaces,
addImportedFn := fun as => mkStateFromImportedEntries NameSet.insert {} as,
addEntryFn := fun s n => s.insert n
}
namespace Environment
def registerNamespace (env : Environment) (n : Name) : Environment :=
if (namespacesExt.getState env).contains n then env else namespacesExt.addEntry env n
def isNamespace (env : Environment) (n : Name) : Bool :=
(namespacesExt.getState env).contains n
def getNamespaceSet (env : Environment) : NameSet :=
namespacesExt.getState env
private def isNamespaceName : Name → Bool
| Name.str Name.anonymous _ _ => true
| Name.str p _ _ => isNamespaceName p
| _ => false
private def registerNamePrefixes : Environment → Name → Environment
| env, Name.str p _ _ => if isNamespaceName p then registerNamePrefixes (registerNamespace env p) p else env
| env, _ => env
@[export lean_environment_add]
def add (env : Environment) (cinfo : ConstantInfo) : Environment :=
let env := registerNamePrefixes env cinfo.name
env.addAux cinfo
@[export lean_display_stats]
def displayStats (env : Environment) : IO Unit := do
let pExtDescrs ← persistentEnvExtensionsRef.get
let numModules := ((pExtDescrs.get! 0).toEnvExtension.getState env).importedEntries.size;
IO.println ("direct imports: " ++ toString env.header.imports);
IO.println ("number of imported modules: " ++ toString numModules);
IO.println ("number of consts: " ++ toString env.constants.size);
IO.println ("number of imported consts: " ++ toString env.constants.stageSizes.1);
IO.println ("number of local consts: " ++ toString env.constants.stageSizes.2);
IO.println ("number of buckets for imported consts: " ++ toString env.constants.numBuckets);
IO.println ("trust level: " ++ toString env.header.trustLevel);
IO.println ("number of extensions: " ++ toString env.extensions.size);
pExtDescrs.forM $ fun extDescr => do
IO.println ("extension '" ++ toString extDescr.name ++ "'")
let s := extDescr.toEnvExtension.getState env
let fmt := extDescr.statsFn s.state
unless fmt.isNil do IO.println (" " ++ toString (Format.nest 2 (extDescr.statsFn s.state)))
IO.println (" number of imported entries: " ++ toString (s.importedEntries.foldl (fun sum es => sum + es.size) 0))
@[extern "lean_eval_const"]
unsafe constant evalConst (α) (env : @& Environment) (opts : @& Options) (constName : @& Name) : Except String α
private def throwUnexpectedType {α} (typeName : Name) (constName : Name) : ExceptT String Id α :=
throw ("unexpected type at '" ++ toString constName ++ "', `" ++ toString typeName ++ "` expected")
/-- Like `evalConst`, but first check that `constName` indeed is a declaration of type `typeName`.
This function is still unsafe because it cannot guarantee that `typeName` is in fact the name of the type `α`. -/
unsafe def evalConstCheck (α) (env : Environment) (opts : Options) (typeName : Name) (constName : Name) : ExceptT String Id α :=
match env.find? constName with
| none => throw ("unknow constant '" ++ toString constName ++ "'")
| some info =>
match info.type with
| Expr.const c _ _ =>
if c != typeName then throwUnexpectedType typeName constName
else env.evalConst α opts constName
| _ => throwUnexpectedType typeName constName
def hasUnsafe (env : Environment) (e : Expr) : Bool :=
let c? := e.find? $ fun e => match e with
| Expr.const c _ _ =>
match env.find? c with
| some cinfo => cinfo.isUnsafe
| none => false
| _ => false;
c?.isSome
end Environment
namespace Kernel
/- Kernel API -/
/--
Kernel isDefEq predicate. We use it mainly for debugging purposes.
Recall that the Kernel type checker does not support metavariables.
When implementing automation, consider using the `MetaM` methods. -/
@[extern "lean_kernel_is_def_eq"]
constant isDefEq (env : Environment) (lctx : LocalContext) (a b : Expr) : Bool
/--
Kernel WHNF function. We use it mainly for debugging purposes.
Recall that the Kernel type checker does not support metavariables.
When implementing automation, consider using the `MetaM` methods. -/
@[extern "lean_kernel_whnf"]
constant whnf (env : Environment) (lctx : LocalContext) (a : Expr) : Expr
end Kernel
class MonadEnv (m : Type → Type) where
getEnv : m Environment
modifyEnv : (Environment → Environment) → m Unit
export MonadEnv (getEnv modifyEnv)
instance (m n) [MonadLift m n] [MonadEnv m] : MonadEnv n where
getEnv := liftM (getEnv : m Environment)
modifyEnv := fun f => liftM (modifyEnv f : m Unit)
end Lean
|
5cb0aa9b898c9defaa07c66cf3e7da420b3bad46 | 8e2026ac8a0660b5a490dfb895599fb445bb77a0 | /library/init/native/cf.lean | de058db705dabf060597b9f75483fa64aa34f6e4 | [
"Apache-2.0"
] | permissive | pcmoritz/lean | 6a8575115a724af933678d829b4f791a0cb55beb | 35eba0107e4cc8a52778259bb5392300267bfc29 | refs/heads/master | 1,607,896,326,092 | 1,490,752,175,000 | 1,490,752,175,000 | 86,612,290 | 0 | 0 | null | 1,490,809,641,000 | 1,490,809,641,000 | null | UTF-8 | Lean | false | false | 2,484 | 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
}
|
2f374c61184d06975487c400003896a7ebe44b3d | 69d4931b605e11ca61881fc4f66db50a0a875e39 | /src/category_theory/yoneda.lean | 0461b7bce1d68d0656d6f1de4fd46d8980753f44 | [
"Apache-2.0"
] | permissive | abentkamp/mathlib | d9a75d291ec09f4637b0f30cc3880ffb07549ee5 | 5360e476391508e092b5a1e5210bd0ed22dc0755 | refs/heads/master | 1,682,382,954,948 | 1,622,106,077,000 | 1,622,106,077,000 | 149,285,665 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 9,944 | 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.hom_functor
/-!
# The Yoneda embedding
The Yoneda embedding as a functor `yoneda : C ⥤ (Cᵒᵖ ⥤ Type v₁)`,
along with an instance that it is `fully_faithful`.
Also the Yoneda lemma, `yoneda_lemma : (yoneda_pairing C) ≅ (yoneda_evaluation C)`.
## References
* [Stacks: Opposite Categories and the Yoneda Lemma](https://stacks.math.columbia.edu/tag/001L)
-/
namespace category_theory
open opposite
universes v₁ u₁ u₂-- morphism levels before object levels. See note [category_theory universes].
variables {C : Type u₁} [category.{v₁} C]
/--
The Yoneda embedding, as a functor from `C` into presheaves on `C`.
See https://stacks.math.columbia.edu/tag/001O.
-/
@[simps]
def yoneda : C ⥤ (Cᵒᵖ ⥤ Type v₁) :=
{ obj := λ X,
{ obj := λ Y, unop Y ⟶ X,
map := λ Y Y' f g, f.unop ≫ g,
map_comp' := λ _ _ _ f g, begin ext, dsimp, erw [category.assoc] end,
map_id' := λ Y, begin ext, dsimp, erw [category.id_comp] end },
map := λ X X' f, { app := λ Y g, g ≫ f } }
/--
The co-Yoneda embedding, as a functor from `Cᵒᵖ` into co-presheaves on `C`.
-/
@[simps] def coyoneda : Cᵒᵖ ⥤ (C ⥤ Type v₁) :=
{ obj := λ X,
{ obj := λ Y, unop X ⟶ Y,
map := λ Y Y' f g, g ≫ f,
map_comp' := λ _ _ _ f g, begin ext1, dsimp, erw [category.assoc] end,
map_id' := λ Y, begin ext1, dsimp, erw [category.comp_id] end },
map := λ X X' f, { app := λ Y g, f.unop ≫ g },
map_comp' := λ _ _ _ f g, begin ext, dsimp, erw [category.assoc] end,
map_id' := λ X, begin ext, dsimp, erw [category.id_comp] end }
namespace yoneda
lemma obj_map_id {X Y : C} (f : op X ⟶ op Y) :
((@yoneda C _).obj X).map f (𝟙 X) = ((@yoneda C _).map f.unop).app (op Y) (𝟙 Y) :=
by obviously
@[simp] lemma naturality {X Y : C} (α : yoneda.obj X ⟶ yoneda.obj Y)
{Z Z' : C} (f : Z ⟶ Z') (h : Z' ⟶ X) : f ≫ α.app (op Z') h = α.app (op Z) (f ≫ h) :=
(functor_to_types.naturality _ _ α f.op h).symm
/--
The Yoneda embedding is full.
See https://stacks.math.columbia.edu/tag/001P.
-/
instance yoneda_full : full (@yoneda C _) :=
{ preimage := λ X Y f, (f.app (op X)) (𝟙 X) }
/--
The Yoneda embedding is faithful.
See https://stacks.math.columbia.edu/tag/001P.
-/
instance yoneda_faithful : faithful (@yoneda C _) :=
{ map_injective' := λ X Y f g p,
begin
injection p with h,
convert (congr_fun (congr_fun h (op X)) (𝟙 X)); dsimp; simp,
end }
/-- Extensionality via Yoneda. The typical usage would be
```
-- Goal is `X ≅ Y`
apply yoneda.ext,
-- Goals are now functions `(Z ⟶ X) → (Z ⟶ Y)`, `(Z ⟶ Y) → (Z ⟶ X)`, and the fact that these
functions are inverses and natural in `Z`.
```
-/
def ext (X Y : C)
(p : Π {Z : C}, (Z ⟶ X) → (Z ⟶ Y)) (q : Π {Z : C}, (Z ⟶ Y) → (Z ⟶ X))
(h₁ : Π {Z : C} (f : Z ⟶ X), q (p f) = f) (h₂ : Π {Z : C} (f : Z ⟶ Y), p (q f) = f)
(n : Π {Z Z' : C} (f : Z' ⟶ Z) (g : Z ⟶ X), p (f ≫ g) = f ≫ p g) : X ≅ Y :=
@preimage_iso _ _ _ _ yoneda _ _ _ _
(nat_iso.of_components (λ Z, { hom := p, inv := q, }) (by tidy))
/--
If `yoneda.map f` is an isomorphism, so was `f`.
-/
lemma is_iso {X Y : C} (f : X ⟶ Y) [is_iso (yoneda.map f)] : is_iso f :=
is_iso_of_fully_faithful yoneda f
end yoneda
namespace coyoneda
@[simp] lemma naturality {X Y : Cᵒᵖ} (α : coyoneda.obj X ⟶ coyoneda.obj Y)
{Z Z' : C} (f : Z' ⟶ Z) (h : unop X ⟶ Z') : (α.app Z' h) ≫ f = α.app Z (h ≫ f) :=
begin erw [functor_to_types.naturality], refl end
instance coyoneda_full : full (@coyoneda C _) :=
{ preimage := λ X Y f, ((f.app (unop X)) (𝟙 _)).op }
instance coyoneda_faithful : faithful (@coyoneda C _) :=
{ map_injective' := λ X Y f g p,
begin
injection p with h,
have t := (congr_fun (congr_fun h (unop X)) (𝟙 _)),
simpa using congr_arg quiver.hom.op t,
end }
/--
If `coyoneda.map f` is an isomorphism, so was `f`.
-/
lemma is_iso {X Y : Cᵒᵖ} (f : X ⟶ Y) [is_iso (coyoneda.map f)] : is_iso f :=
is_iso_of_fully_faithful coyoneda f
-- No need to use Cᵒᵖ here, works with any category
/-- A Type-valued presheaf `P` is isomorphic to the composition of `P` with the
coyoneda functor coming from `punit`. -/
@[simps] def iso_comp_punit (P : C ⥤ Type v₁) : (P ⋙ coyoneda.obj (op punit.{v₁+1})) ≅ P :=
{ hom := { app := λ X f, f punit.star},
inv := { app := λ X a _, a } }
end coyoneda
/--
A presheaf `F` is representable if there is object `X` so `F ≅ yoneda.obj X`.
See https://stacks.math.columbia.edu/tag/001Q.
-/
-- TODO should we make this a Prop, merely asserting existence of such an object?
class representable (F : Cᵒᵖ ⥤ Type v₁) :=
(X : C)
(w : yoneda.obj X ≅ F)
end category_theory
namespace category_theory
-- For the rest of the file, we are using product categories,
-- so need to restrict to the case morphisms are in 'Type', not 'Sort'.
universes v₁ u₁ u₂ -- morphism levels before object levels. See note [category_theory universes].
open opposite
variables (C : Type u₁) [category.{v₁} C]
-- We need to help typeclass inference with some awkward universe levels here.
instance prod_category_instance_1 : category ((Cᵒᵖ ⥤ Type v₁) × Cᵒᵖ) :=
category_theory.prod.{(max u₁ v₁) v₁} (Cᵒᵖ ⥤ Type v₁) Cᵒᵖ
instance prod_category_instance_2 : category (Cᵒᵖ × (Cᵒᵖ ⥤ Type v₁)) :=
category_theory.prod.{v₁ (max u₁ v₁)} Cᵒᵖ (Cᵒᵖ ⥤ Type v₁)
open yoneda
/--
The "Yoneda evaluation" functor, which sends `X : Cᵒᵖ` and `F : Cᵒᵖ ⥤ Type`
to `F.obj X`, functorially in both `X` and `F`.
-/
def yoneda_evaluation : Cᵒᵖ × (Cᵒᵖ ⥤ Type v₁) ⥤ Type (max u₁ v₁) :=
evaluation_uncurried Cᵒᵖ (Type v₁) ⋙ ulift_functor.{u₁}
@[simp] lemma yoneda_evaluation_map_down
(P Q : Cᵒᵖ × (Cᵒᵖ ⥤ Type v₁)) (α : P ⟶ Q) (x : (yoneda_evaluation C).obj P) :
((yoneda_evaluation C).map α x).down = α.2.app Q.1 (P.2.map α.1 x.down) := rfl
/--
The "Yoneda pairing" functor, which sends `X : Cᵒᵖ` and `F : Cᵒᵖ ⥤ Type`
to `yoneda.op.obj X ⟶ F`, functorially in both `X` and `F`.
-/
def yoneda_pairing : Cᵒᵖ × (Cᵒᵖ ⥤ Type v₁) ⥤ Type (max u₁ v₁) :=
functor.prod yoneda.op (𝟭 (Cᵒᵖ ⥤ Type v₁)) ⋙ functor.hom (Cᵒᵖ ⥤ Type v₁)
@[simp] lemma yoneda_pairing_map
(P Q : Cᵒᵖ × (Cᵒᵖ ⥤ Type v₁)) (α : P ⟶ Q) (β : (yoneda_pairing C).obj P) :
(yoneda_pairing C).map α β = yoneda.map α.1.unop ≫ β ≫ α.2 := rfl
/--
The Yoneda lemma asserts that that the Yoneda pairing
`(X : Cᵒᵖ, F : Cᵒᵖ ⥤ Type) ↦ (yoneda.obj (unop X) ⟶ F)`
is naturally isomorphic to the evaluation `(X, F) ↦ F.obj X`.
See https://stacks.math.columbia.edu/tag/001P.
-/
def yoneda_lemma : yoneda_pairing C ≅ yoneda_evaluation C :=
{ hom :=
{ app := λ F x, ulift.up ((x.app F.1) (𝟙 (unop F.1))),
naturality' :=
begin
intros X Y f, ext, dsimp,
erw [category.id_comp, ←functor_to_types.naturality],
simp only [category.comp_id, yoneda_obj_map],
end },
inv :=
{ app := λ F x,
{ app := λ X a, (F.2.map a.op) x.down,
naturality' :=
begin
intros X Y f, ext, dsimp,
rw [functor_to_types.map_comp_apply]
end },
naturality' :=
begin
intros X Y f, ext, dsimp,
rw [←functor_to_types.naturality, functor_to_types.map_comp_apply]
end },
hom_inv_id' :=
begin
ext, dsimp,
erw [←functor_to_types.naturality,
obj_map_id],
simp only [yoneda_map_app, quiver.hom.unop_op],
erw [category.id_comp],
end,
inv_hom_id' :=
begin
ext, dsimp,
rw [functor_to_types.map_id_apply]
end }.
variables {C}
/--
The isomorphism between `yoneda.obj X ⟶ F` and `F.obj (op X)`
(we need to insert a `ulift` to get the universes right!)
given by the Yoneda lemma.
-/
@[simp] def yoneda_sections (X : C) (F : Cᵒᵖ ⥤ Type v₁) :
(yoneda.obj X ⟶ F) ≅ ulift.{u₁} (F.obj (op X)) :=
(yoneda_lemma C).app (op X, F)
/--
We have a type-level equivalence between natural transformations from the yoneda embedding
and elements of `F.obj X`, without any universe switching.
-/
def yoneda_equiv {X : C} {F : Cᵒᵖ ⥤ Type v₁} : (yoneda.obj X ⟶ F) ≃ F.obj (op X) :=
(yoneda_sections X F).to_equiv.trans equiv.ulift
lemma yoneda_equiv_naturality {X Y : C} {F : Cᵒᵖ ⥤ Type v₁} (f : yoneda.obj X ⟶ F) (g : Y ⟶ X) :
F.map g.op (yoneda_equiv f) = yoneda_equiv (yoneda.map g ≫ f) :=
begin
change (f.app (op X) ≫ F.map g.op) (𝟙 X) = f.app (op Y) (𝟙 Y ≫ g),
rw ← f.naturality,
dsimp,
simp,
end
@[simp]
lemma yoneda_equiv_apply {X : C} {F : Cᵒᵖ ⥤ Type v₁} (f : yoneda.obj X ⟶ F) :
yoneda_equiv f = f.app (op X) (𝟙 X) :=
rfl
@[simp]
lemma yoneda_equiv_symm_app_apply {X : C} {F : Cᵒᵖ ⥤ Type v₁} (x : F.obj (op X))
(Y : Cᵒᵖ) (f : Y.unop ⟶ X) :
(yoneda_equiv.symm x).app Y f = F.map f.op x :=
rfl
/--
When `C` is a small category, we can restate the isomorphism from `yoneda_sections`
without having to change universes.
-/
def yoneda_sections_small {C : Type u₁} [small_category C] (X : C)
(F : Cᵒᵖ ⥤ Type u₁) :
(yoneda.obj X ⟶ F) ≅ F.obj (op X) :=
yoneda_sections X F ≪≫ ulift_trivial _
@[simp]
lemma yoneda_sections_small_hom {C : Type u₁} [small_category C] (X : C)
(F : Cᵒᵖ ⥤ Type u₁) (f : yoneda.obj X ⟶ F) :
(yoneda_sections_small X F).hom f = f.app _ (𝟙 _) :=
rfl
@[simp]
lemma yoneda_sections_small_inv_app_apply {C : Type u₁} [small_category C] (X : C)
(F : Cᵒᵖ ⥤ Type u₁) (t : F.obj (op X)) (Y : Cᵒᵖ) (f : Y.unop ⟶ X) :
((yoneda_sections_small X F).inv t).app Y f = F.map f.op t :=
rfl
end category_theory
|
ccb43c40772550afcdaa1cf55aa8241863eba1ec | 4efff1f47634ff19e2f786deadd394270a59ecd2 | /src/category_theory/limits/shapes/products.lean | f71d67f1da345592aa57664a0739c55fc3a48ec1 | [
"Apache-2.0"
] | permissive | agjftucker/mathlib | d634cd0d5256b6325e3c55bb7fb2403548371707 | 87fe50de17b00af533f72a102d0adefe4a2285e8 | refs/heads/master | 1,625,378,131,941 | 1,599,166,526,000 | 1,599,166,526,000 | 160,748,509 | 0 | 0 | Apache-2.0 | 1,544,141,789,000 | 1,544,141,789,000 | null | UTF-8 | Lean | false | false | 4,402 | lean | /-
Copyright (c) 2018 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import category_theory.limits.limits
import category_theory.discrete_category
universes v u
open category_theory
namespace category_theory.limits
variables {β : Type v}
variables {C : Type u} [category.{v} C]
-- We don't need an analogue of `pair` (for binary products), `parallel_pair` (for equalizers),
-- or `(co)span`, since we already have `discrete.functor`.
abbreviation fan (f : β → C) := cone (discrete.functor f)
abbreviation cofan (f : β → C) := cocone (discrete.functor f)
def fan.mk {f : β → C} {P : C} (p : Π b, P ⟶ f b) : fan f :=
{ X := P,
π := { app := p } }
def cofan.mk {f : β → C} {P : C} (p : Π b, f b ⟶ P) : cofan f :=
{ X := P,
ι := { app := p } }
@[simp] lemma fan.mk_π_app {f : β → C} {P : C} (p : Π b, P ⟶ f b) (b : β) : (fan.mk p).π.app b = p b := rfl
@[simp] lemma cofan.mk_π_app {f : β → C} {P : C} (p : Π b, f b ⟶ P) (b : β) : (cofan.mk p).ι.app b = p b := rfl
/-- An abbreviation for `has_limit (discrete.functor f)`. -/
abbreviation has_product (f : β → C) := has_limit (discrete.functor f)
/-- An abbreviation for `has_colimit (discrete.functor f)`. -/
abbreviation has_coproduct (f : β → C) := has_colimit (discrete.functor f)
section
variables (C)
/-- An abbreviation for `has_limits_of_shape (discrete f)`. -/
abbreviation has_products_of_shape (β : Type v) := has_limits_of_shape.{v} (discrete β)
/-- An abbreviation for `has_colimits_of_shape (discrete f)`. -/
abbreviation has_coproducts_of_shape (β : Type v) := has_colimits_of_shape.{v} (discrete β)
end
/-- `pi_obj f` computes the product of a family of elements `f`. (It is defined as an abbreviation
for `limit (discrete.functor f)`, so for most facts about `pi_obj f`, you will just use general facts
about limits.) -/
abbreviation pi_obj (f : β → C) [has_product f] := limit (discrete.functor f)
/-- `sigma_obj f` computes the coproduct of a family of elements `f`. (It is defined as an abbreviation
for `colimit (discrete.functor f)`, so for most facts about `sigma_obj f`, you will just use general facts
about colimits.) -/
abbreviation sigma_obj (f : β → C) [has_coproduct f] := colimit (discrete.functor f)
notation `∏ ` f:20 := pi_obj f
notation `∐ ` f:20 := sigma_obj f
abbreviation pi.π (f : β → C) [has_product f] (b : β) : ∏ f ⟶ f b :=
limit.π (discrete.functor f) b
abbreviation sigma.ι (f : β → C) [has_coproduct f] (b : β) : f b ⟶ ∐ f :=
colimit.ι (discrete.functor f) b
abbreviation pi.lift {f : β → C} [has_product f] {P : C} (p : Π b, P ⟶ f b) : P ⟶ ∏ f :=
limit.lift _ (fan.mk p)
abbreviation sigma.desc {f : β → C} [has_coproduct f] {P : C} (p : Π b, f b ⟶ P) : ∐ f ⟶ P :=
colimit.desc _ (cofan.mk p)
/--
Construct a morphism between categorical products (indexed by the same type)
from a family of morphisms between the factors.
-/
abbreviation pi.map {f g : β → C} [has_products_of_shape β C]
(p : Π b, f b ⟶ g b) : ∏ f ⟶ ∏ g :=
lim.map (discrete.nat_trans p)
/--
Construct an isomorphism between categorical products (indexed by the same type)
from a family of isomorphisms between the factors.
-/
abbreviation pi.map_iso {f g : β → C} [has_products_of_shape β C]
(p : Π b, f b ≅ g b) : ∏ f ≅ ∏ g :=
lim.map_iso (discrete.nat_iso p)
/--
Construct a morphism between categorical coproducts (indexed by the same type)
from a family of morphisms between the factors.
-/
abbreviation sigma.map {f g : β → C} [has_coproducts_of_shape β C]
(p : Π b, f b ⟶ g b) : ∐ f ⟶ ∐ g :=
colim.map (discrete.nat_trans p)
/--
Construct an isomorphism between categorical coproducts (indexed by the same type)
from a family of isomorphisms between the factors.
-/
abbreviation sigma.map_iso {f g : β → C} [has_coproducts_of_shape β C]
(p : Π b, f b ≅ g b) : ∐ f ≅ ∐ g :=
colim.map_iso (discrete.nat_iso p)
variables (C)
/-- An abbreviation for `Π J, has_limits_of_shape (discrete J) C` -/
abbreviation has_products := Π (J : Type v), has_limits_of_shape (discrete J) C
/-- An abbreviation for `Π J, has_colimits_of_shape (discrete J) C` -/
abbreviation has_coproducts := Π (J : Type v), has_colimits_of_shape (discrete J) C
end category_theory.limits
|
909dce2bbf32e79c977d012a1a489595b586c2f8 | 6dc0c8ce7a76229dd81e73ed4474f15f88a9e294 | /src/Lean/PrettyPrinter/Basic.lean | b94542cc7aad685e982cb6b35a7af3e4bc22538d | [
"Apache-2.0"
] | permissive | williamdemeo/lean4 | 72161c58fe65c3ad955d6a3050bb7d37c04c0d54 | 6d00fcf1d6d873e195f9220c668ef9c58e9c4a35 | refs/heads/master | 1,678,305,356,877 | 1,614,708,995,000 | 1,614,708,995,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,098 | lean | /-
Copyright (c) 2020 Sebastian Ullrich. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sebastian Ullrich
-/
import Lean.InternalExceptionId
import Lean.KeyedDeclsAttribute
namespace Lean
namespace PrettyPrinter
/- Auxiliary internal exception for backtracking the pretty printer.
See `orelse.parenthesizer` for example -/
builtin_initialize backtrackExceptionId : InternalExceptionId ← registerInternalExceptionId `backtrackFormatter
unsafe def runForNodeKind {α} (attr : KeyedDeclsAttribute α) (k : SyntaxNodeKind) (interp : ParserDescr → CoreM α) : CoreM α := do
match attr.getValues (← getEnv) k with
| p::_ => pure p
| _ =>
-- assume `k` is from a `ParserDescr`, in which case we assume it's also the declaration name
let info ← getConstInfo k
if info.type.isConstOf ``ParserDescr || info.type.isConstOf ``TrailingParserDescr then
let d ← evalConst ParserDescr k
interp d
else
throwError! "no declaration of attribute [{attr.defn.name}] found for '{k}'"
end PrettyPrinter
end Lean
|
42768df71161e72a8c1b14d5cf0aef4c815df0cb | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/topology/algebra/module/character_space.lean | df3da5dab22e6bf180fe0fd86fc0716f2346ce76 | [
"Apache-2.0"
] | permissive | jcommelin/mathlib | d8456447c36c176e14d96d9e76f39841f69d2d9b | ee8279351a2e434c2852345c51b728d22af5a156 | refs/heads/master | 1,664,782,136,488 | 1,663,638,983,000 | 1,663,638,983,000 | 132,563,656 | 0 | 0 | Apache-2.0 | 1,663,599,929,000 | 1,525,760,539,000 | Lean | UTF-8 | Lean | false | false | 8,176 | lean | /-
Copyright (c) 2022 Frédéric Dupuis. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Frédéric Dupuis
-/
import topology.algebra.module.weak_dual
import algebra.algebra.spectrum
import topology.continuous_function.algebra
/-!
# Character space of a topological algebra
The character space of a topological algebra is the subset of elements of the weak dual that
are also algebra homomorphisms. This space is used in the Gelfand transform, which gives an
isomorphism between a commutative C⋆-algebra and continuous functions on the character space
of the algebra. This, in turn, is used to construct the continuous functional calculus on
C⋆-algebras.
## Implementation notes
We define `character_space 𝕜 A` as a subset of the weak dual, which automatically puts the
correct topology on the space. We then define `to_alg_hom` which provides the algebra homomorphism
corresponding to any element. We also provide `to_clm` which provides the element as a
continuous linear map. (Even though `weak_dual 𝕜 A` is a type copy of `A →L[𝕜] 𝕜`, this is
often more convenient.)
## Tags
character space, Gelfand transform, functional calculus
-/
namespace weak_dual
/-- The character space of a topological algebra is the subset of elements of the weak dual that
are also algebra homomorphisms. -/
def character_space (𝕜 : Type*) (A : Type*) [comm_semiring 𝕜] [topological_space 𝕜]
[has_continuous_add 𝕜] [has_continuous_const_smul 𝕜 𝕜]
[non_unital_non_assoc_semiring A] [topological_space A] [module 𝕜 A] :=
{φ : weak_dual 𝕜 A | (φ ≠ 0) ∧ (∀ (x y : A), φ (x * y) = (φ x) * (φ y))}
variables {𝕜 : Type*} {A : Type*}
namespace character_space
section non_unital_non_assoc_semiring
variables [comm_semiring 𝕜] [topological_space 𝕜] [has_continuous_add 𝕜]
[has_continuous_const_smul 𝕜 𝕜] [non_unital_non_assoc_semiring A] [topological_space A]
[module 𝕜 A]
@[simp, norm_cast, protected]
lemma coe_coe (φ : character_space 𝕜 A) : ⇑(φ : weak_dual 𝕜 A) = φ := rfl
/-- Elements of the character space are continuous linear maps. -/
instance : continuous_linear_map_class (character_space 𝕜 A) 𝕜 A 𝕜 :=
{ coe := λ φ, (φ : A → 𝕜),
coe_injective' := λ φ ψ h, by { ext, exact congr_fun h x },
map_smulₛₗ := λ φ, (φ : weak_dual 𝕜 A).map_smul,
map_add := λ φ, (φ : weak_dual 𝕜 A).map_add,
map_continuous := λ φ, (φ : weak_dual 𝕜 A).cont }
/-- An element of the character space, as a continuous linear map. -/
def to_clm (φ : character_space 𝕜 A) : A →L[𝕜] 𝕜 := (φ : weak_dual 𝕜 A)
@[simp] lemma coe_to_clm (φ : character_space 𝕜 A) : ⇑(to_clm φ) = φ := rfl
/-- Elements of the character space are non-unital algebra homomorphisms. -/
instance : non_unital_alg_hom_class (character_space 𝕜 A) 𝕜 A 𝕜 :=
{ map_smul := λ φ, map_smul φ,
map_zero := λ φ, map_zero φ,
map_mul := λ φ, φ.prop.2,
.. character_space.continuous_linear_map_class }
/-- An element of the character space, as an non-unital algebra homomorphism. -/
def to_non_unital_alg_hom (φ : character_space 𝕜 A) : A →ₙₐ[𝕜] 𝕜 :=
{ to_fun := (φ : A → 𝕜),
map_mul' := map_mul φ,
map_smul' := map_smul φ,
map_zero' := map_zero φ,
map_add' := map_add φ }
@[simp]
lemma coe_to_non_unital_alg_hom (φ : character_space 𝕜 A) : ⇑(to_non_unital_alg_hom φ) = φ := rfl
variables (𝕜 A)
lemma union_zero :
character_space 𝕜 A ∪ {0} = {φ : weak_dual 𝕜 A | ∀ (x y : A), φ (x * y) = (φ x) * (φ y)} :=
le_antisymm
(by { rintros φ (hφ | h₀), { exact hφ.2 }, { exact λ x y, by simp [set.eq_of_mem_singleton h₀] }})
(λ φ hφ, or.elim (em $ φ = 0) (λ h₀, or.inr h₀) (λ h₀, or.inl ⟨h₀, hφ⟩))
/-- The `character_space 𝕜 A` along with `0` is always a closed set in `weak_dual 𝕜 A`. -/
lemma union_zero_is_closed [t2_space 𝕜] [has_continuous_mul 𝕜] :
is_closed (character_space 𝕜 A ∪ {0}) :=
begin
simp only [union_zero, set.set_of_forall],
exact is_closed_Inter (λ x, is_closed_Inter $ λ y, is_closed_eq (eval_continuous _) $
(eval_continuous _).mul (eval_continuous _))
end
end non_unital_non_assoc_semiring
section unital
variables [comm_ring 𝕜] [no_zero_divisors 𝕜] [topological_space 𝕜] [has_continuous_add 𝕜]
[has_continuous_const_smul 𝕜 𝕜] [topological_space A] [semiring A] [algebra 𝕜 A]
/-- In a unital algebra, elements of the character space are algebra homomorphisms. -/
instance : alg_hom_class (character_space 𝕜 A) 𝕜 A 𝕜 :=
have map_one' : ∀ φ : character_space 𝕜 A, φ 1 = 1 := λ φ,
begin
have h₁ : (φ 1) * (1 - φ 1) = 0 := by rw [mul_sub, sub_eq_zero, mul_one, ←map_mul φ, one_mul],
rcases mul_eq_zero.mp h₁ with h₂ | h₂,
{ have : ∀ a, φ (a * 1) = 0 := λ a, by simp only [map_mul φ, h₂, mul_zero],
exact false.elim (φ.prop.1 $ continuous_linear_map.ext $ by simpa only [mul_one] using this) },
{ exact (sub_eq_zero.mp h₂).symm },
end,
{ map_one := map_one',
commutes := λ φ r,
begin
{ rw [algebra.algebra_map_eq_smul_one, algebra.id.map_eq_id, ring_hom.id_apply],
change ((φ : weak_dual 𝕜 A) : A →L[𝕜] 𝕜) (r • 1) = r,
rw [map_smul, algebra.id.smul_eq_mul, character_space.coe_coe, map_one' φ, mul_one] },
end,
.. character_space.non_unital_alg_hom_class }
/-- An element of the character space of a unital algebra, as an algebra homomorphism. -/
@[simps] def to_alg_hom (φ : character_space 𝕜 A) : A →ₐ[𝕜] 𝕜 :=
{ map_one' := map_one φ,
commutes' := alg_hom_class.commutes φ,
..to_non_unital_alg_hom φ }
lemma eq_set_map_one_map_mul [nontrivial 𝕜] : character_space 𝕜 A =
{φ : weak_dual 𝕜 A | (φ 1 = 1) ∧ (∀ (x y : A), φ (x * y) = (φ x) * (φ y))} :=
begin
ext x,
refine ⟨λ h, ⟨map_one (⟨x, h⟩ : character_space 𝕜 A), h.2⟩, λ h, ⟨_, h.2⟩⟩,
rintro rfl,
simpa using h.1,
end
/-- under suitable mild assumptions on `𝕜`, the character space is a closed set in
`weak_dual 𝕜 A`. -/
lemma is_closed [nontrivial 𝕜] [t2_space 𝕜] [has_continuous_mul 𝕜] :
is_closed (character_space 𝕜 A) :=
begin
rw [eq_set_map_one_map_mul, set.set_of_and],
refine is_closed.inter (is_closed_eq (eval_continuous _) continuous_const) _,
simpa only [(union_zero 𝕜 A).symm] using union_zero_is_closed _ _,
end
end unital
section ring
variables [comm_ring 𝕜] [no_zero_divisors 𝕜] [topological_space 𝕜] [has_continuous_add 𝕜]
[has_continuous_const_smul 𝕜 𝕜] [topological_space A] [ring A] [algebra 𝕜 A]
lemma apply_mem_spectrum [nontrivial 𝕜] (φ : character_space 𝕜 A) (a : A) : φ a ∈ spectrum 𝕜 a :=
alg_hom.apply_mem_spectrum φ a
end ring
end character_space
section gelfand_transform
open continuous_map
variables (𝕜 A) [comm_ring 𝕜] [no_zero_divisors 𝕜] [topological_space 𝕜]
[topological_ring 𝕜] [topological_space A] [semiring A] [algebra 𝕜 A]
/-- The **Gelfand transform** is an algebra homomorphism (over `𝕜`) from a topological `𝕜`-algebra
`A` into the `𝕜`-algebra of continuous `𝕜`-valued functions on the `character_space 𝕜 A`.
The character space itself consists of all algebra homomorphisms from `A` to `𝕜`. -/
@[simps] def gelfand_transform : A →ₐ[𝕜] C(character_space 𝕜 A, 𝕜) :=
{ to_fun := λ a,
{ to_fun := λ φ, φ a,
continuous_to_fun := (eval_continuous a).comp continuous_induced_dom },
map_one' := by {ext, simp only [coe_mk, coe_one, pi.one_apply, map_one a] },
map_mul' := λ a b, by {ext, simp only [map_mul, coe_mk, coe_mul, pi.mul_apply] },
map_zero' := by {ext, simp only [map_zero, coe_mk, coe_mul, coe_zero, pi.zero_apply], },
map_add' := λ a b, by {ext, simp only [map_add, coe_mk, coe_add, pi.add_apply] },
commutes' := λ k, by {ext, simp only [alg_hom_class.commutes, algebra.id.map_eq_id,
ring_hom.id_apply, coe_mk, algebra_map_apply, algebra.id.smul_eq_mul, mul_one] } }
end gelfand_transform
end weak_dual
|
764dc74933dffca3f0d36cf4d9914451826eb52d | 08bd4ba4ca87dba1f09d2c96a26f5d65da81f4b4 | /src/Lean/Server/Watchdog.lean | f46cb068a0427800a9aaf0d1317b56c92fc06688 | [
"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 | 29,961 | lean | /-
Copyright (c) 2020 Marc Huisinga. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Marc Huisinga, Wojciech Nawrocki
-/
import Init.System.IO
import Init.Data.ByteArray
import Lean.Data.RBMap
import Lean.Util.Paths
import Lean.Data.FuzzyMatching
import Lean.Data.Json
import Lean.Data.Lsp
import Lean.Server.Utils
import Lean.Server.Requests
import Lean.Server.References
/-!
For general server architecture, see `README.md`. This module implements the watchdog process.
## Watchdog state
Most LSP clients only send us file diffs, so to facilitate sending entire file contents to freshly restarted
workers, the watchdog needs to maintain the current state of each file. It can also use this state to detect changes
to the header and thus restart the corresponding worker, freeing its imports.
TODO(WN):
We may eventually want to keep track of approximately (since this isn't knowable exactly) where in the file a worker
crashed. Then on restart, we tell said worker to only parse up to that point and query the user about how to proceed
(continue OR allow the user to fix the bug and then continue OR ..). Without this, if the crash is deterministic,
users may be confused about why the server seemingly stopped working for a single file.
## Watchdog <-> worker communication
The watchdog process and its file worker processes communicate via LSP. If the necessity arises,
we might add non-standard commands similarly based on JSON-RPC. Most requests and notifications
are forwarded to the corresponding file worker process, with the exception of these notifications:
- textDocument/didOpen: Launch the file worker, create the associated watchdog state and launch a task to
asynchronously receive LSP packets from the worker (e.g. request responses).
- textDocument/didChange: Update the local file state so that it can be resent to restarted workers.
Then forward the `didChange` notification.
- textDocument/didClose: Signal a shutdown to the file worker and remove the associated watchdog state.
Moreover, we don't implement the full protocol at this level:
- Upon starting, the `initialize` request is forwarded to the worker, but it must not respond with its server
capabilities. Consequently, the watchdog will not send an `initialized` notification to the worker.
- After `initialize`, the watchdog sends the corresponding `didOpen` notification with the full current state of
the file. No additional `didOpen` notifications will be forwarded to the worker process.
- `$/cancelRequest` notifications are forwarded to all file workers.
- File workers are always terminated with an `exit` notification, without previously receiving a `shutdown` request.
Similarly, they never receive a `didClose` notification.
## Watchdog <-> client communication
The watchdog itself should implement the LSP standard as closely as possible. However we reserve the right to add
non-standard extensions in case they're needed, for example to communicate tactic state.
-/
namespace Lean.Server.Watchdog
open IO
open Lsp
open JsonRpc
open System.Uri
section Utils
def workerCfg : Process.StdioConfig := {
stdin := Process.Stdio.piped
stdout := Process.Stdio.piped
-- We pass workers' stderr through to the editor.
stderr := Process.Stdio.inherit
}
/-- Events that worker-specific tasks signal to the main thread. -/
inductive WorkerEvent where
| terminated
| importsChanged
| crashed (e : IO.Error)
| ioError (e : IO.Error)
inductive WorkerState where
/-- The watchdog can detect a crashed file worker in two places: When trying to send a message to the file worker
and when reading a request reply.
In the latter case, the forwarding task terminates and delegates a `crashed` event to the main task.
Then, in both cases, the file worker has its state set to `crashed` and requests that are in-flight are errored.
Upon receiving the next packet for that file worker, the file worker is restarted and the packet is forwarded
to it. If the crash was detected while writing a packet, we queue that packet until the next packet for the file
worker arrives. -/
| crashed (queuedMsgs : Array JsonRpc.Message)
| running
abbrev PendingRequestMap := RBMap RequestID JsonRpc.Message compare
end Utils
section FileWorker
structure FileWorker where
doc : DocumentMeta
proc : Process.Child workerCfg
commTask : Task WorkerEvent
state : WorkerState
-- This should not be mutated outside of namespace FileWorker, as it is used as shared mutable state
/-- The pending requests map contains all requests
that have been received from the LSP client, but were not answered yet.
We need them for forwaring cancellation requests to the correct worker as well as cleanly aborting
requests on worker crashes. -/
pendingRequestsRef : IO.Ref PendingRequestMap
namespace FileWorker
def stdin (fw : FileWorker) : FS.Stream :=
FS.Stream.ofHandle fw.proc.stdin
def stdout (fw : FileWorker) : FS.Stream :=
FS.Stream.ofHandle fw.proc.stdout
def erasePendingRequest (fw : FileWorker) (id : RequestID) : IO Unit :=
fw.pendingRequestsRef.modify fun pendingRequests => pendingRequests.erase id
def errorPendingRequests (fw : FileWorker) (hError : FS.Stream) (code : ErrorCode) (msg : String) : IO Unit := do
let pendingRequests ← fw.pendingRequestsRef.modifyGet (fun pendingRequests => (pendingRequests, RBMap.empty))
for ⟨id, _⟩ in pendingRequests do
hError.writeLspResponseError { id := id, code := code, message := msg }
end FileWorker
end FileWorker
section ServerM
abbrev FileWorkerMap := RBMap DocumentUri FileWorker compare
structure ServerContext where
hIn : FS.Stream
hOut : FS.Stream
hLog : FS.Stream
/-- Command line arguments. -/
args : List String
fileWorkersRef : IO.Ref FileWorkerMap
/-- We store these to pass them to workers. -/
initParams : InitializeParams
workerPath : System.FilePath
srcSearchPath : System.SearchPath
references : IO.Ref References
abbrev ServerM := ReaderT ServerContext IO
def updateFileWorkers (val : FileWorker) : ServerM Unit := do
(←read).fileWorkersRef.modify (fun fileWorkers => fileWorkers.insert val.doc.uri val)
def findFileWorker? (uri : DocumentUri) : ServerM (Option FileWorker) :=
return (← (←read).fileWorkersRef.get).find? uri
def findFileWorker! (uri : DocumentUri) : ServerM FileWorker := do
let some fw ← findFileWorker? uri
| throwServerError s!"cannot find open document '{uri}'"
return fw
def eraseFileWorker (uri : DocumentUri) : ServerM Unit := do
let s ← read
s.fileWorkersRef.modify (fun fileWorkers => fileWorkers.erase uri)
if let some path := fileUriToPath? uri then
if let some module ← searchModuleNameOfFileName path s.srcSearchPath then
s.references.modify fun refs => refs.removeWorkerRefs module
def log (msg : String) : ServerM Unit := do
let st ← read
st.hLog.putStrLn msg
st.hLog.flush
def handleIleanInfoUpdate (fw : FileWorker) (params : LeanIleanInfoParams) : ServerM Unit := do
let s ← read
if let some path := fileUriToPath? fw.doc.uri then
if let some module ← searchModuleNameOfFileName path s.srcSearchPath then
s.references.modify fun refs => refs.updateWorkerRefs module params.version params.references
def handleIleanInfoFinal (fw : FileWorker) (params : LeanIleanInfoParams) : ServerM Unit := do
let s ← read
if let some path := fileUriToPath? fw.doc.uri then
if let some module ← searchModuleNameOfFileName path s.srcSearchPath then
s.references.modify fun refs => refs.finalizeWorkerRefs module params.version params.references
/-- Creates a Task which forwards a worker's messages into the output stream until an event
which must be handled in the main watchdog thread (e.g. an I/O error) happens. -/
private partial def forwardMessages (fw : FileWorker) : ServerM (Task WorkerEvent) := do
let o := (←read).hOut
let rec loop : ServerM WorkerEvent := do
try
let msg ← fw.stdout.readLspMessage
-- Re. `o.writeLspMessage msg`:
-- Writes to Lean I/O channels are atomic, so these won't trample on each other.
match msg with
| Message.response id _ => do
fw.erasePendingRequest id
o.writeLspMessage msg
| Message.responseError id _ _ _ => do
fw.erasePendingRequest id
o.writeLspMessage msg
| Message.notification "$/lean/ileanInfoUpdate" params =>
if let some params := params then
if let Except.ok params := FromJson.fromJson? <| ToJson.toJson params then
handleIleanInfoUpdate fw params
| Message.notification "$/lean/ileanInfoFinal" params =>
if let some params := params then
if let Except.ok params := FromJson.fromJson? <| ToJson.toJson params then
handleIleanInfoFinal fw params
| _ => o.writeLspMessage msg
catch err =>
-- If writeLspMessage from above errors we will block here, but the main task will
-- quit eventually anyways if that happens
let exitCode ← fw.proc.wait
match exitCode with
| 0 =>
-- Worker was terminated
fw.errorPendingRequests o ErrorCode.contentModified
(s!"The file worker for {fw.doc.uri} has been terminated. Either the header has changed,"
++ " or the file was closed, or the server is shutting down.")
-- one last message to clear the diagnostics for this file so that stale errors
-- do not remain in the editor forever.
publishDiagnostics fw.doc #[] o
return WorkerEvent.terminated
| 2 =>
return .importsChanged
| _ =>
-- Worker crashed
fw.errorPendingRequests o (if exitCode = 1 then ErrorCode.workerExited else ErrorCode.workerCrashed)
s!"Server process for {fw.doc.uri} crashed, {if exitCode = 1 then "see stderr for exception" else "likely due to a stack overflow or a bug"}."
publishProgressAtPos fw.doc 0 o (kind := LeanFileProgressKind.fatalError)
return WorkerEvent.crashed err
loop
let task ← IO.asTask (loop $ ←read) Task.Priority.dedicated
return task.map fun
| Except.ok ev => ev
| Except.error e => WorkerEvent.ioError e
def startFileWorker (m : DocumentMeta) : ServerM Unit := do
publishProgressAtPos m 0 (← read).hOut
let st ← read
let workerProc ← Process.spawn {
toStdioConfig := workerCfg
cmd := st.workerPath.toString
args := #["--worker"] ++ st.args.toArray ++ #[m.uri]
}
let pendingRequestsRef ← IO.mkRef (RBMap.empty : PendingRequestMap)
-- The task will never access itself, so this is fine
let fw : FileWorker := {
doc := m
proc := workerProc
commTask := Task.pure WorkerEvent.terminated
state := WorkerState.running
pendingRequestsRef := pendingRequestsRef
}
let commTask ← forwardMessages fw
let fw : FileWorker := { fw with commTask := commTask }
fw.stdin.writeLspRequest ⟨0, "initialize", st.initParams⟩
fw.stdin.writeLspNotification {
method := "textDocument/didOpen"
param := {
textDocument := {
uri := m.uri
languageId := "lean"
version := m.version
text := m.text.source
} : DidOpenTextDocumentParams
}
}
updateFileWorkers fw
def terminateFileWorker (uri : DocumentUri) : ServerM Unit := do
let fw ← findFileWorker! uri
try
fw.stdin.writeLspMessage (Message.notification "exit" none)
catch _ =>
/- The file worker must have crashed just when we were about to terminate it!
That's fine - just forget about it then.
(on didClose we won't need the crashed file worker anymore,
when the header changed we'll start a new one right after
anyways and when we're shutting down the server
it's over either way.) -/
return
eraseFileWorker uri
def handleCrash (uri : DocumentUri) (queuedMsgs : Array JsonRpc.Message) : ServerM Unit := do
updateFileWorkers { ←findFileWorker! uri with state := WorkerState.crashed queuedMsgs }
/-- Tries to write a message, sets the state of the FileWorker to `crashed` if it does not succeed
and restarts the file worker if the `crashed` flag was already set. Just logs an error if there
is no FileWorker at this `uri`.
Messages that couldn't be sent can be queued up via the queueFailedMessage flag and
will be discharged after the FileWorker is restarted. -/
def tryWriteMessage (uri : DocumentUri) (msg : JsonRpc.Message) (queueFailedMessage := true) (restartCrashedWorker := false) :
ServerM Unit := do
let some fw ← findFileWorker? uri
| do
(←read).hLog.putStrLn s!"Cannot send message to unknown document '{uri}':\n{(toJson msg).compress}"
return
match fw.state with
| WorkerState.crashed queuedMsgs =>
let mut queuedMsgs := queuedMsgs
if queueFailedMessage then
queuedMsgs := queuedMsgs.push msg
if !restartCrashedWorker then
return
-- restart the crashed FileWorker
eraseFileWorker uri
startFileWorker fw.doc
let newFw ← findFileWorker! uri
let mut crashedMsgs := #[]
-- try to discharge all queued msgs, tracking the ones that we can't discharge
for msg in queuedMsgs do
try
newFw.stdin.writeLspMessage msg
catch _ =>
crashedMsgs := crashedMsgs.push msg
if ¬ crashedMsgs.isEmpty then
handleCrash uri crashedMsgs
| WorkerState.running =>
let initialQueuedMsgs :=
if queueFailedMessage then
#[msg]
else
#[]
try
fw.stdin.writeLspMessage msg
catch _ =>
handleCrash uri initialQueuedMsgs
end ServerM
section RequestHandling
open FuzzyMatching
def findDefinitions (p : TextDocumentPositionParams) : ServerM <| Array Location := do
let mut definitions := #[]
if let some path := fileUriToPath? p.textDocument.uri then
let srcSearchPath := (← read).srcSearchPath
if let some module ← searchModuleNameOfFileName path srcSearchPath then
let references ← (← read).references.get
for ident in references.findAt module p.position do
if let some definition ← references.definitionOf? ident srcSearchPath then
definitions := definitions.push definition
return definitions
def handleReference (p : ReferenceParams) : ServerM (Array Location) := do
let mut result := #[]
if let some path := fileUriToPath? p.textDocument.uri then
let srcSearchPath := (← read).srcSearchPath
if let some module ← searchModuleNameOfFileName path srcSearchPath then
let references ← (← read).references.get
for ident in references.findAt module p.position do
let identRefs ← references.referringTo module ident srcSearchPath p.context.includeDeclaration
result := result.append identRefs
return result
def handleWorkspaceSymbol (p : WorkspaceSymbolParams) : ServerM (Array SymbolInformation) := do
if p.query.isEmpty then
return #[]
let references ← (← read).references.get
let srcSearchPath := (← read).srcSearchPath
let symbols ← references.definitionsMatching srcSearchPath (maxAmount? := none)
fun name =>
let name := privateToUserName? name |>.getD name
if let some score := fuzzyMatchScoreWithThreshold? p.query name.toString then
some (name.toString, score)
else
none
return symbols
|>.qsort (fun ((_, s1), _) ((_, s2), _) => s1 > s2)
|>.extract 0 100 -- max amount
|>.map fun ((name, _), location) =>
{ name, kind := SymbolKind.constant, location }
end RequestHandling
section NotificationHandling
def handleDidOpen (p : DidOpenTextDocumentParams) : ServerM Unit :=
let doc := p.textDocument
/- NOTE(WN): `toFileMap` marks line beginnings as immediately following
"\n", which should be enough to handle both LF and CRLF correctly.
This is because LSP always refers to characters by (line, column),
so if we get the line number correct it shouldn't matter that there
is a CR there. -/
startFileWorker ⟨doc.uri, doc.version, doc.text.toFileMap⟩
def handleDidChange (p : DidChangeTextDocumentParams) : ServerM Unit := do
let doc := p.textDocument
let changes := p.contentChanges
let fw ← findFileWorker! p.textDocument.uri
let oldDoc := fw.doc
let newVersion := doc.version?.getD 0
if changes.isEmpty then
return
let newDocText := foldDocumentChanges changes oldDoc.text
let newDoc : DocumentMeta := ⟨doc.uri, newVersion, newDocText⟩
updateFileWorkers { fw with doc := newDoc }
tryWriteMessage doc.uri (Notification.mk "textDocument/didChange" p) (restartCrashedWorker := true)
def handleDidClose (p : DidCloseTextDocumentParams) : ServerM Unit :=
terminateFileWorker p.textDocument.uri
def handleDidChangeWatchedFiles (p : DidChangeWatchedFilesParams) : ServerM Unit := do
let references := (← read).references
let oleanSearchPath ← Lean.searchPathRef.get
let ileans ← oleanSearchPath.findAllWithExt "ilean"
for change in p.changes do
if let some path := fileUriToPath? change.uri then
if let FileChangeType.Deleted := change.type then
references.modify (fun r => r.removeIlean path)
else if ileans.contains path then
let ilean ← Ilean.load path
if let FileChangeType.Changed := change.type then
references.modify (fun r => r.removeIlean path |>.addIlean path ilean)
else
references.modify (fun r => r.addIlean path ilean)
def handleCancelRequest (p : CancelParams) : ServerM Unit := do
let fileWorkers ← (←read).fileWorkersRef.get
for ⟨uri, fw⟩ in fileWorkers do
-- Cancelled requests still require a response, so they can't be removed
-- from the pending requests map.
if (← fw.pendingRequestsRef.get).contains p.id then
tryWriteMessage uri (Notification.mk "$/cancelRequest" p) (queueFailedMessage := false)
def forwardNotification {α : Type} [ToJson α] [FileSource α] (method : String) (params : α) : ServerM Unit :=
tryWriteMessage (fileSource params) (Notification.mk method params) (queueFailedMessage := true)
end NotificationHandling
section MessageHandling
def parseParams (paramType : Type) [FromJson paramType] (params : Json) : ServerM paramType :=
match fromJson? params with
| Except.ok parsed => pure parsed
| Except.error inner => throwServerError s!"Got param with wrong structure: {params.compress}\n{inner}"
def forwardRequestToWorker (id : RequestID) (method : String) (params : Json) : ServerM Unit := do
let uri: DocumentUri ←
-- This request is handled specially.
if method == "$/lean/rpc/connect" then
let ps ← parseParams Lsp.RpcConnectParams params
pure <| fileSource ps
else match (← routeLspRequest method params) with
| Except.error e =>
(←read).hOut.writeLspResponseError <| e.toLspResponseError id
return
| Except.ok uri => pure uri
let some fw ← findFileWorker? uri
/- Clients may send requests to closed files, which we respond to with an error.
For example, VSCode sometimes sends requests just after closing a file,
and RPC clients may also do so, e.g. due to remaining timers. -/
| do
(←read).hOut.writeLspResponseError
{ id := id
/- Some clients (VSCode) also send requests *before* opening a file. We reply
with `contentModified` as that does not display a "request failed" popup. -/
code := ErrorCode.contentModified
message := s!"Cannot process request to closed file '{uri}'" }
return
let r := Request.mk id method params
fw.pendingRequestsRef.modify (·.insert id r)
tryWriteMessage uri r
def handleRequest (id : RequestID) (method : String) (params : Json) : ServerM Unit := do
let handle α β [FromJson α] [ToJson β] (handler : α → ServerM β) : ServerM Unit := do
let hOut := (← read).hOut
try
let params ← parseParams α params
let result ← handler params
hOut.writeLspResponse ⟨id, result⟩
catch
-- TODO Do fancier error handling, like in file worker?
| e => hOut.writeLspResponseError {
id := id
code := ErrorCode.internalError
message := s!"Failed to process request {id}: {e}"
}
-- If a definition is in a different, modified file, the ilean data should
-- have the correct location while the olean still has outdated info from
-- the last compilation. This is easier than catching the client's reply and
-- fixing the definition's location afterwards, but it doesn't work for
-- go-to-type-definition.
if method == "textDocument/definition" || method == "textDocument/declaration" then
let params ← parseParams TextDocumentPositionParams params
let definitions ← findDefinitions params
if !definitions.isEmpty then
(← read).hOut.writeLspResponse ⟨id, definitions⟩
return
match method with
| "textDocument/references" => handle ReferenceParams (Array Location) handleReference
| "workspace/symbol" => handle WorkspaceSymbolParams (Array SymbolInformation) handleWorkspaceSymbol
| _ => forwardRequestToWorker id method params
def handleNotification (method : String) (params : Json) : ServerM Unit := do
let handle := (fun α [FromJson α] (handler : α → ServerM Unit) => parseParams α params >>= handler)
match method with
| "textDocument/didOpen" => handle _ handleDidOpen
| "textDocument/didChange" => handle DidChangeTextDocumentParams handleDidChange
| "textDocument/didClose" => handle DidCloseTextDocumentParams handleDidClose
| "workspace/didChangeWatchedFiles" => handle DidChangeWatchedFilesParams handleDidChangeWatchedFiles
| "$/cancelRequest" => handle CancelParams handleCancelRequest
| "$/lean/rpc/connect" => handle RpcConnectParams (forwardNotification method)
| "$/lean/rpc/release" => handle RpcReleaseParams (forwardNotification method)
| "$/lean/rpc/keepAlive" => handle RpcKeepAliveParams (forwardNotification method)
| _ =>
if !"$/".isPrefixOf method then -- implementation-dependent notifications can be safely ignored
(←read).hLog.putStrLn s!"Got unsupported notification: {method}"
end MessageHandling
section MainLoop
def shutdown : ServerM Unit := do
let fileWorkers ← (←read).fileWorkersRef.get
for ⟨uri, _⟩ in fileWorkers do
terminateFileWorker uri
for ⟨_, fw⟩ in fileWorkers do
discard <| IO.wait fw.commTask
inductive ServerEvent where
| workerEvent (fw : FileWorker) (ev : WorkerEvent)
| clientMsg (msg : JsonRpc.Message)
| clientError (e : IO.Error)
def runClientTask : ServerM (Task ServerEvent) := do
let st ← read
let readMsgAction : IO ServerEvent := do
/- Runs asynchronously. -/
let msg ← st.hIn.readLspMessage
pure <| ServerEvent.clientMsg msg
let clientTask := (← IO.asTask readMsgAction).map fun
| Except.ok ev => ev
| Except.error e => ServerEvent.clientError e
return clientTask
partial def mainLoop (clientTask : Task ServerEvent) : ServerM Unit := do
let st ← read
let workers ← st.fileWorkersRef.get
let mut workerTasks := #[]
for (_, fw) in workers do
if let WorkerState.running := fw.state then
workerTasks := workerTasks.push <| fw.commTask.map (ServerEvent.workerEvent fw)
let ev ← IO.waitAny (clientTask :: workerTasks.toList)
match ev with
| ServerEvent.clientMsg msg =>
match msg with
| Message.request id "shutdown" _ =>
shutdown
st.hOut.writeLspResponse ⟨id, Json.null⟩
| Message.request id method (some params) =>
handleRequest id method (toJson params)
mainLoop (←runClientTask)
| Message.response .. =>
-- TODO: handle client responses
mainLoop (←runClientTask)
| Message.responseError _ _ e .. =>
throwServerError s!"Unhandled response error: {e}"
| Message.notification method (some params) =>
handleNotification method (toJson params)
mainLoop (←runClientTask)
| _ => throwServerError "Got invalid JSON-RPC message"
| ServerEvent.clientError e => throw e
| ServerEvent.workerEvent fw ev =>
match ev with
| WorkerEvent.ioError e =>
throwServerError s!"IO error while processing events for {fw.doc.uri}: {e}"
| WorkerEvent.crashed _ =>
handleCrash fw.doc.uri #[]
mainLoop clientTask
| WorkerEvent.terminated =>
throwServerError "Internal server error: got termination event for worker that should have been removed"
| .importsChanged =>
startFileWorker fw.doc
mainLoop clientTask
end MainLoop
def mkLeanServerCapabilities : ServerCapabilities := {
textDocumentSync? := some {
openClose := true
change := TextDocumentSyncKind.incremental
willSave := false
willSaveWaitUntil := false
save? := none
}
-- refine
completionProvider? := some {
triggerCharacters? := some #["."]
}
hoverProvider := true
declarationProvider := true
definitionProvider := true
typeDefinitionProvider := true
referencesProvider := true
workspaceSymbolProvider := true
documentHighlightProvider := true
documentSymbolProvider := true
foldingRangeProvider := true
semanticTokensProvider? := some {
legend := {
tokenTypes := SemanticTokenType.names
tokenModifiers := SemanticTokenModifier.names
}
full := true
range := true
}
codeActionProvider? := some {
resolveProvider? := true,
codeActionKinds? := some #["quickfix", "refactor"]
}
}
def initAndRunWatchdogAux : ServerM Unit := do
let st ← read
try
discard $ st.hIn.readLspNotificationAs "initialized" InitializedParams
let clientTask ← runClientTask
mainLoop clientTask
catch err =>
shutdown
throw err
/- NOTE(WN): It looks like instead of sending the `exit` notification,
VSCode just closes the stream. In that case, pretend we got an `exit`. -/
let Message.notification "exit" none ←
try st.hIn.readLspMessage
catch _ => pure (Message.notification "exit" none)
| throwServerError "Got `shutdown` request, expected an `exit` notification"
def findWorkerPath : IO System.FilePath := do
let mut workerPath ← IO.appPath
if let some path := (←IO.getEnv "LEAN_SYSROOT") then
workerPath := System.FilePath.mk path / "bin" / "lean" |>.withExtension System.FilePath.exeExtension
if let some path := (←IO.getEnv "LEAN_WORKER_PATH") then
workerPath := System.FilePath.mk path
return workerPath
def loadReferences : IO References := do
let oleanSearchPath ← Lean.searchPathRef.get
let mut refs := References.empty
for path in ← oleanSearchPath.findAllWithExt "ilean" do
try
refs := refs.addIlean path (← Ilean.load path)
catch _ =>
-- could be a race with the build system, for example
-- ilean load errors should not be fatal, but we *should* log them
-- when we add logging to the server
pure ()
return refs
def initAndRunWatchdog (args : List String) (i o e : FS.Stream) : IO Unit := do
let workerPath ← findWorkerPath
let srcSearchPath ← initSrcSearchPath (← getBuildDir)
let references ← IO.mkRef (← loadReferences)
let fileWorkersRef ← IO.mkRef (RBMap.empty : FileWorkerMap)
let i ← maybeTee "wdIn.txt" false i
let o ← maybeTee "wdOut.txt" true o
let e ← maybeTee "wdErr.txt" true e
let initRequest ← i.readLspRequestAs "initialize" InitializeParams
o.writeLspResponse {
id := initRequest.id
result := {
capabilities := mkLeanServerCapabilities
serverInfo? := some {
name := "Lean 4 Server"
version? := "0.1.1"
}
: InitializeResult
}
}
o.writeLspRequest {
id := RequestID.str "register_ilean_watcher"
method := "client/registerCapability"
param := some {
registrations := #[ {
id := "ilean_watcher"
method := "workspace/didChangeWatchedFiles"
registerOptions := some <| toJson {
watchers := #[ { globPattern := "**/*.ilean" } ]
: DidChangeWatchedFilesRegistrationOptions }
} ]
: RegistrationParams }
}
ReaderT.run initAndRunWatchdogAux {
hIn := i
hOut := o
hLog := e
args := args
fileWorkersRef := fileWorkersRef
initParams := initRequest.param
workerPath
srcSearchPath
references
: ServerContext
}
@[export lean_server_watchdog_main]
def watchdogMain (args : List String) : IO UInt32 := do
let i ← IO.getStdin
let o ← IO.getStdout
let e ← IO.getStderr
try
initAndRunWatchdog args i o e
return 0
catch err =>
e.putStrLn s!"Watchdog error: {err}"
return 1
end Lean.Server.Watchdog
|
7ded9f40b5efc19ace32351eb5cc8046bbec45ab | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/tactic/omega/nat/dnf_auto.lean | 6fd66f0e9308a5d5bf830f92385c1705d8249c30 | [] | 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,778 | lean | /-
Copyright (c) 2019 Seul Baek. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Seul Baek
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.tactic.omega.clause
import Mathlib.tactic.omega.nat.form
import Mathlib.PostPort
namespace Mathlib
/-
DNF transformation.
-/
namespace omega
namespace nat
@[simp] def dnf_core : preform → List clause := sorry
theorem exists_clause_holds_core {v : ℕ → ℕ} {p : preform} :
preform.neg_free p →
preform.sub_free p →
preform.holds v p →
∃ (c : clause), ∃ (H : c ∈ dnf_core p), clause.holds (fun (x : ℕ) => ↑(v x)) c :=
sorry
def term.vars_core (is : List ℤ) : List Bool := list.map (fun (i : ℤ) => ite (i = 0) false tt) is
/-- Return a list of bools that encodes which variables have nonzero coefficients -/
def term.vars (t : term) : List Bool := term.vars_core (prod.snd t)
def bools.or : List Bool → List Bool → List Bool := sorry
/-- Return a list of bools that encodes which variables have nonzero coefficients in any one of the input terms -/
def terms.vars : List term → List Bool := sorry
def nonneg_consts_core : ℕ → List Bool → List term := sorry
def nonneg_consts (bs : List Bool) : List term := nonneg_consts_core 0 bs
def nonnegate : clause → clause := sorry
/-- DNF transformation -/
def dnf (p : preform) : List clause := list.map nonnegate (dnf_core p)
theorem holds_nonneg_consts_core {v : ℕ → ℤ} (h1 : ∀ (x : ℕ), 0 ≤ v x) (m : ℕ) (bs : List Bool)
(t : term) (H : t ∈ nonneg_consts_core m bs) : 0 ≤ term.val v t :=
sorry
theorem holds_nonneg_consts {v : ℕ → ℤ} {bs : List Bool} :
(∀ (x : ℕ), 0 ≤ v x) → ∀ (t : term), t ∈ nonneg_consts bs → 0 ≤ term.val v t :=
fun (ᾰ : ∀ (x : ℕ), 0 ≤ v x) =>
idRhs (∀ (t : term), t ∈ nonneg_consts_core 0 bs → 0 ≤ term.val (fun (x : ℕ) => v x) t)
(holds_nonneg_consts_core ᾰ 0 bs)
theorem exists_clause_holds {v : ℕ → ℕ} {p : preform} :
preform.neg_free p →
preform.sub_free p →
preform.holds v p →
∃ (c : clause), ∃ (H : c ∈ dnf p), clause.holds (fun (x : ℕ) => ↑(v x)) c :=
sorry
theorem exists_clause_sat {p : preform} :
preform.neg_free p →
preform.sub_free p → preform.sat p → ∃ (c : clause), ∃ (H : c ∈ dnf p), clause.sat c :=
sorry
theorem unsat_of_unsat_dnf (p : preform) :
preform.neg_free p → preform.sub_free p → clauses.unsat (dnf p) → preform.unsat p :=
fun (hnf : preform.neg_free p) (hsf : preform.sub_free p) (h1 : clauses.unsat (dnf p)) =>
id fun (h2 : preform.sat p) => h1 (exists_clause_sat hnf hsf h2)
end Mathlib |
79a2d30211aa0545fafc6420e8f39bb31c3ad15c | ae9f8bf05de0928a4374adc7d6b36af3411d3400 | /src/formal_ml/nnreal.lean | 7367106a0fdc2fe2828cb24a2b6e1fc623e9f19d | [
"Apache-2.0"
] | permissive | NeoTim/formal-ml | bc42cf6beba9cd2ed56c1cd054ab4eb5402ed445 | c9cbad2837104160a9832a29245471468748bb8d | refs/heads/master | 1,671,549,160,900 | 1,601,362,989,000 | 1,601,362,989,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 4,566 | lean | /-
Copyright 2020 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-/
import data.real.nnreal
import data.real.ennreal
import data.complex.exponential
import formal_ml.nat
lemma nnreal_add_sub_right (a b c:nnreal):a + b = c → c - b = a :=
begin
intro A1,
--apply linarith [A1],
have A2:(a + b) - b = a,
{
apply nnreal.add_sub_cancel,
},
rw A1 at A2,
exact A2,
end
lemma nnreal_add_sub_left (a b c:nnreal):a + b = c → c - a = b :=
begin
intro A1,
apply nnreal_add_sub_right,
rw nnreal.comm_semiring.add_comm,
exact A1,
end
lemma nnreal_sub_le_left (a b c:nnreal):b ≤ c → (a - c ≤ a - b) :=
begin
intro A1,
apply nnreal.of_real_le_of_real,
apply sub_le_sub_left,
apply A1,
end
noncomputable def nnreal.exp (x:real):nnreal := nnreal.of_real (real.exp x)
lemma nnreal_exp_eq (x:real):↑(nnreal.exp x) = real.exp x :=
begin
unfold nnreal.exp,
rw nnreal.coe_of_real,
apply le_of_lt,
apply real.exp_pos,
end
-- This one is hard (and technically has nothing to do with nnreal).
-- The rest are easy after it is finished.
-- A standard proof would be to calculate the first and second derivative.
-- If you prove that the second derivative is non-negative, then there is a minimum
-- where the first derivative is zero. In this way you can establish that the minimum
-- is at zero, and it is zero.
-- Note this should solve the problem. however, there is a TODO.
-- My current thinking about the proof:
lemma nnreal_pow_succ (x:nnreal) (k:ℕ):x ^ nat.succ k = x * (x ^ k) :=
begin
refl,
end
lemma nnreal_pow_mono (x y:nnreal) (k:ℕ):x ≤ y → x^k ≤ y^k :=
begin
intro A1,
induction k,
{
simp,
},
{
rw nnreal_pow_succ,
rw nnreal_pow_succ,
apply mul_le_mul,
{
exact A1,
},
{
apply k_ih,
},
{
simp,
},
{
simp,
},
}
end
lemma nnreal_eq (x y:nnreal):(x:real) = (y:real) → x = y :=
begin
intro A1,
apply nnreal.eq,
apply A1,
end
lemma nnreal_exp_pow (x:real) (k:ℕ): nnreal.exp (k * x) = (nnreal.exp x)^k :=
begin
apply nnreal.eq,
rw nnreal.coe_pow,
rw nnreal_exp_eq,
rw nnreal_exp_eq,
apply real.exp_nat_mul,
end
lemma to_ennreal_def (x:nnreal):(x:ennreal)= some x :=
begin
refl
end
lemma nnreal_lt_ennreal_top (x:nnreal):(x:ennreal) < (⊤:ennreal) :=
begin
rw to_ennreal_def,
apply with_top.some_lt_none,
end
lemma nnreal_lt_some_ennreal (x y:nnreal):(x < y) → (x:ennreal) < (some y:ennreal) :=
begin
intro A1,
apply ennreal.coe_lt_coe.mpr,
apply A1,
end
lemma some_ennreal_lt_nnreal (x y:nnreal):(x:ennreal) < (some y:ennreal) → (x < y) :=
begin
intro A1,
apply ennreal.coe_lt_coe.mp,
apply A1,
end
lemma nnreal_add_eq_zero_iff (a b:nnreal): a + b = 0 ↔ a = 0 ∧ b = 0 :=
begin
simp,
end
--Holds true for all commutative semirings?
lemma nnreal_add_monoid_smul_def{n:ℕ} {c:nnreal}: n •ℕ c = ↑(n) * c :=
begin
induction n,
{
simp,
},
{
simp,
}
end
lemma nnreal_sub_le_sub_of_le {a b c:nnreal}:b ≤ c → a - c ≤ a - b :=
begin
intro A1,
have A2:(a ≤ b)∨ (b ≤ a) := linear_order.le_total a b,
have A3:(a ≤ c)∨ (c ≤ a) := linear_order.le_total a c,
cases A2,
{
rw nnreal.sub_eq_zero,
simp,
apply le_trans A2 A1,
},
{
cases A3,
{
rw nnreal.sub_eq_zero,
simp,
exact A3,
},
rw ← nnreal.coe_le_coe,
rw nnreal.coe_sub,
rw nnreal.coe_sub,
apply sub_le_sub_left,
rw nnreal.coe_le_coe,
exact A1,
exact A2,
exact A3,
},
end
lemma nnreal_sub_lt_sub_of_lt {a b c:nnreal}:b < c → b < a → a - c < a - b :=
begin
intros A1 A2,
--have A2:(a ≤ b)∨ (b ≤ a) := linear_order.le_total a b,
have A3:(a ≤ c)∨ (c ≤ a) := linear_order.le_total a c,
{
cases A3,
{
rw nnreal.sub_eq_zero A3,
apply nnreal.sub_pos.mpr A2,
},
rw ← nnreal.coe_lt_coe,
rw nnreal.coe_sub,
rw nnreal.coe_sub,
apply sub_lt_sub_left,
rw nnreal.coe_lt_coe,
exact A1,
apply (le_of_lt A2),
exact A3,
},
end
|
13ee6ecf99c9656c64fc6cc0d0967b88e425bc26 | d5b53bc87e7f4dda87570c8ef6ee4b4de685f315 | /src/cohomology.lean | 21d67cb7bb07f583ebc26f981bdc870bf9062b64 | [] | no_license | Shenyang1995/M4R | 3bec366fba7262ed29d7f64b4ba7cc978494c022 | a6a3399c4d1935b39a22f64c30f293ef2a32fdeb | refs/heads/master | 1,597,008,096,640 | 1,591,722,931,000 | 1,591,722,931,000 | 214,177,424 | 5 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 981 | lean | --import G_module.hom
import cochain
import algebra.pi_instances
import add_group_hom.basic
import add_subquotient.basic
variables (n:ℕ )(G : Type*) [group G] (M : Type*) [add_comm_group M] [G_module G M]
(N : Type*) [add_comm_group N] [G_module G N]
def cocycle := (add_group_hom.ker (d (n+1) G M))
def coboundary := add_group_hom.range (d n G M)
theorem cob_sub_of_coc: coboundary n G M ≤ cocycle n G M:=
range_d_sub_ker_d _ G M
def cohomology : add_subquotient (cochain (n + 1) G M) :=
{bottom := coboundary n G M,
top := cocycle n G M,
incl := cob_sub_of_coc n G M}
def h0 : add_subquotient (cochain 0 G M):=
{bottom := ⊥ ,
top := (add_group_hom.ker (d 0 G M)),
incl := begin
show ⊥ ⊆ add_group_hom.ker (d 0 G M),
intro a,
intro ha,
rw add_subgroup.mem_coe,
have h1:a=0,
exact ha,
rw add_group_hom.mem_ker,
rw h1,
show d.to_fun 0=0,
exact (d 0 G M).map_zero',
end}
--def H_n : add_subquotient (cochain n G M):= if n=0 then h0 G M else cohomology (n-1) G M
|
4ce39cedb9ed7017a5270928dc0ee18a97089822 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/ring_theory/valuation/valuation_subring.lean | 5c5257f1ee706e22e92bf13696666193efbbc191 | [
"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 | 29,184 | lean | /-
Copyright (c) 2022 Adam Topaz. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Adam Topaz, Junyan Xu, Jack McKoen
-/
import ring_theory.valuation.valuation_ring
import ring_theory.localization.as_subring
import ring_theory.subring.pointwise
import algebraic_geometry.prime_spectrum.basic
/-!
# Valuation subrings of a field
## Projects
The order structure on `valuation_subring K`.
-/
open_locale classical
noncomputable theory
variables (K : Type*) [field K]
/-- A valuation subring of a field `K` is a subring `A` such that for every `x : K`,
either `x ∈ A` or `x⁻¹ ∈ A`. -/
structure valuation_subring extends subring K :=
(mem_or_inv_mem' : ∀ x : K, x ∈ carrier ∨ x⁻¹ ∈ carrier)
namespace valuation_subring
variables {K} (A : valuation_subring K)
instance : set_like (valuation_subring K) K :=
{ coe := λ A, A.to_subring,
coe_injective' := by { rintro ⟨⟨⟩⟩ ⟨⟨⟩⟩ _, congr' } }
@[simp] lemma mem_carrier (x : K) : x ∈ A.carrier ↔ x ∈ A := iff.refl _
@[simp] lemma mem_to_subring (x : K) : x ∈ A.to_subring ↔ x ∈ A := iff.refl _
@[ext] lemma ext (A B : valuation_subring K)
(h : ∀ x, x ∈ A ↔ x ∈ B) : A = B := set_like.ext h
lemma zero_mem : (0 : K) ∈ A := A.to_subring.zero_mem
lemma one_mem : (1 : K) ∈ A := A.to_subring.one_mem
lemma add_mem (x y : K) : x ∈ A → y ∈ A → x + y ∈ A := A.to_subring.add_mem
lemma mul_mem (x y : K) : x ∈ A → y ∈ A → x * y ∈ A := A.to_subring.mul_mem
lemma neg_mem (x : K) : x ∈ A → (-x) ∈ A := A.to_subring.neg_mem
lemma mem_or_inv_mem (x : K) : x ∈ A ∨ x⁻¹ ∈ A := A.mem_or_inv_mem' _
lemma to_subring_injective : function.injective (to_subring : valuation_subring K → subring K) :=
λ x y h, by { cases x, cases y, congr' }
instance : comm_ring A := show comm_ring A.to_subring, by apply_instance
instance : is_domain A := show is_domain A.to_subring, by apply_instance
instance : has_top (valuation_subring K) := has_top.mk $
{ mem_or_inv_mem' := λ x, or.inl trivial,
..(⊤ : subring K) }
lemma mem_top (x : K) : x ∈ (⊤ : valuation_subring K) := trivial
lemma le_top : A ≤ ⊤ := λ a ha, mem_top _
instance : order_top (valuation_subring K) :=
{ top := ⊤,
le_top := le_top }
instance : inhabited (valuation_subring K) := ⟨⊤⟩
instance : valuation_ring A :=
{ cond := λ a b,
begin
by_cases (b : K) = 0, { use 0, left, ext, simp [h] },
by_cases (a : K) = 0, { use 0, right, ext, simp [h] },
cases A.mem_or_inv_mem (a/b) with hh hh,
{ use ⟨a/b, hh⟩, right, ext, field_simp, ring },
{ rw (show (a/b : K)⁻¹ = b/a, by field_simp) at hh,
use ⟨b/a, hh⟩, left, ext, field_simp, ring },
end }
instance : algebra A K :=
show algebra A.to_subring K, by apply_instance
@[simp]
lemma algebra_map_apply (a : A) : algebra_map A K a = a := rfl
instance : is_fraction_ring A K :=
{ map_units := λ ⟨y, hy⟩,
(units.mk0 (y : K) (λ c, non_zero_divisors.ne_zero hy $ subtype.ext c)).is_unit,
surj := λ z, begin
by_cases z = 0, { use (0, 1), simp [h] },
cases A.mem_or_inv_mem z with hh hh,
{ use (⟨z, hh⟩, 1), simp },
{ refine ⟨⟨1, ⟨⟨_, hh⟩, _⟩⟩, mul_inv_cancel h⟩,
exact mem_non_zero_divisors_iff_ne_zero.2 (λ c, h (inv_eq_zero.mp (congr_arg coe c))) },
end,
eq_iff_exists := λ a b, ⟨ λ h, ⟨1, by { ext, simpa using h }⟩, λ ⟨c, h⟩,
congr_arg coe ((mul_eq_mul_right_iff.1 h).resolve_right (non_zero_divisors.ne_zero c.2)) ⟩ }
/-- The value group of the valuation associated to `A`. Note: it is actually a group with zero. -/
@[derive linear_ordered_comm_group_with_zero]
def value_group := valuation_ring.value_group A K
/-- Any valuation subring of `K` induces a natural valuation on `K`. -/
def valuation : valuation K A.value_group := valuation_ring.valuation A K
instance inhabited_value_group : inhabited A.value_group := ⟨A.valuation 0⟩
lemma valuation_le_one (a : A) : A.valuation a ≤ 1 :=
(valuation_ring.mem_integer_iff A K _).2 ⟨a, rfl⟩
lemma mem_of_valuation_le_one (x : K) (h : A.valuation x ≤ 1) : x ∈ A :=
let ⟨a, ha⟩ := (valuation_ring.mem_integer_iff A K x).1 h in ha ▸ a.2
lemma valuation_le_one_iff (x : K) : A.valuation x ≤ 1 ↔ x ∈ A :=
⟨mem_of_valuation_le_one _ _, λ ha, A.valuation_le_one ⟨x, ha⟩⟩
lemma valuation_eq_iff (x y : K) : A.valuation x = A.valuation y ↔
∃ a : Aˣ, (a : K) * y = x := quotient.eq'
lemma valuation_le_iff (x y : K) : A.valuation x ≤ A.valuation y ↔
∃ a : A, (a : K) * y = x := iff.rfl
lemma valuation_surjective : function.surjective A.valuation := surjective_quot_mk _
lemma valuation_unit (a : Aˣ) : A.valuation a = 1 :=
by { rw [← A.valuation.map_one, valuation_eq_iff], use a, simp }
lemma valuation_eq_one_iff (a : A) : is_unit a ↔ A.valuation a = 1 :=
⟨ λ h, A.valuation_unit h.unit,
λ h, begin
have ha : (a : K) ≠ 0,
{ intro c, rw [c, A.valuation.map_zero] at h, exact zero_ne_one h },
have ha' : (a : K)⁻¹ ∈ A,
{ rw [← valuation_le_one_iff, map_inv₀, h, inv_one] },
apply is_unit_of_mul_eq_one a ⟨a⁻¹, ha'⟩, ext, field_simp,
end ⟩
lemma valuation_lt_one_or_eq_one (a : A) : A.valuation a < 1 ∨ A.valuation a = 1 :=
lt_or_eq_of_le (A.valuation_le_one a)
lemma valuation_lt_one_iff (a : A) : a ∈ local_ring.maximal_ideal A ↔ A.valuation a < 1 :=
begin
rw local_ring.mem_maximal_ideal,
dsimp [nonunits], rw valuation_eq_one_iff,
exact (A.valuation_le_one a).lt_iff_ne.symm,
end
/-- A subring `R` of `K` such that for all `x : K` either `x ∈ R` or `x⁻¹ ∈ R` is
a valuation subring of `K`. -/
def of_subring (R : subring K) (hR : ∀ x : K, x ∈ R ∨ x⁻¹ ∈ R) : valuation_subring K :=
{ mem_or_inv_mem' := hR, ..R }
@[simp]
lemma mem_of_subring (R : subring K) (hR : ∀ x : K, x ∈ R ∨ x⁻¹ ∈ R) (x : K) :
x ∈ of_subring R hR ↔ x ∈ R := iff.refl _
/-- An overring of a valuation ring is a valuation ring. -/
def of_le (R : valuation_subring K) (S : subring K) (h : R.to_subring ≤ S) :
valuation_subring K :=
{ mem_or_inv_mem' := λ x, (R.mem_or_inv_mem x).imp (@h x) (@h _), ..S}
section order
instance : semilattice_sup (valuation_subring K) :=
{ sup := λ R S, of_le R (R.to_subring ⊔ S.to_subring) $ le_sup_left,
le_sup_left := λ R S x hx, (le_sup_left : R.to_subring ≤ R.to_subring ⊔ S.to_subring) hx,
le_sup_right := λ R S x hx, (le_sup_right : S.to_subring ≤ R.to_subring ⊔ S.to_subring) hx,
sup_le := λ R S T hR hT x hx, (sup_le hR hT : R.to_subring ⊔ S.to_subring ≤ T.to_subring) hx,
..(infer_instance : partial_order (valuation_subring K)) }
/-- The ring homomorphism induced by the partial order. -/
def inclusion (R S : valuation_subring K) (h : R ≤ S) : R →+* S :=
subring.inclusion h
/-- The canonical ring homomorphism from a valuation ring to its field of fractions. -/
def subtype (R : valuation_subring K) : R →+* K :=
subring.subtype R.to_subring
/-- The canonical map on value groups induced by a coarsening of valuation rings. -/
def map_of_le (R S : valuation_subring K) (h : R ≤ S) :
R.value_group →*₀ S.value_group :=
{ to_fun := quotient.map' id $ λ x y ⟨u, hu⟩, ⟨units.map (R.inclusion S h).to_monoid_hom u, hu⟩,
map_zero' := rfl,
map_one' := rfl,
map_mul' := by { rintro ⟨⟩ ⟨⟩, refl } }
@[mono]
lemma monotone_map_of_le (R S : valuation_subring K) (h : R ≤ S) :
monotone (R.map_of_le S h) :=
by { rintros ⟨⟩ ⟨⟩ ⟨a, ha⟩, exact ⟨R.inclusion S h a, ha⟩ }
@[simp]
lemma map_of_le_comp_valuation (R S : valuation_subring K) (h : R ≤ S) :
R.map_of_le S h ∘ R.valuation = S.valuation := by { ext, refl }
@[simp]
lemma map_of_le_valuation_apply (R S : valuation_subring K) (h : R ≤ S) (x : K) :
R.map_of_le S h (R.valuation x) = S.valuation x := rfl
/-- The ideal corresponding to a coarsening of a valuation ring. -/
def ideal_of_le (R S : valuation_subring K) (h : R ≤ S) : ideal R :=
(local_ring.maximal_ideal S).comap (R.inclusion S h)
instance prime_ideal_of_le (R S : valuation_subring K) (h : R ≤ S) :
(ideal_of_le R S h).is_prime := (local_ring.maximal_ideal S).comap_is_prime _
/-- The coarsening of a valuation ring associated to a prime ideal. -/
def of_prime (A : valuation_subring K) (P : ideal A) [P.is_prime] :
valuation_subring K :=
of_le A (localization.subalgebra.of_field K _ P.prime_compl_le_non_zero_divisors).to_subring $
λ a ha, subalgebra.algebra_map_mem _ (⟨a, ha⟩ : A)
instance of_prime_algebra (A : valuation_subring K) (P : ideal A) [P.is_prime] :
algebra A (A.of_prime P) := subalgebra.algebra _
instance of_prime_scalar_tower (A : valuation_subring K) (P : ideal A) [P.is_prime] :
is_scalar_tower A (A.of_prime P) K := is_scalar_tower.subalgebra' A K K _
instance of_prime_localization (A : valuation_subring K) (P : ideal A) [P.is_prime] :
is_localization.at_prime (A.of_prime P) P :=
by apply localization.subalgebra.is_localization_of_field K
lemma le_of_prime (A : valuation_subring K) (P : ideal A) [P.is_prime] :
A ≤ of_prime A P :=
λ a ha, subalgebra.algebra_map_mem _ (⟨a, ha⟩ : A)
lemma of_prime_valuation_eq_one_iff_mem_prime_compl
(A : valuation_subring K)
(P : ideal A) [P.is_prime] (x : A) :
(of_prime A P).valuation x = 1 ↔ x ∈ P.prime_compl :=
begin
rw [← is_localization.at_prime.is_unit_to_map_iff (A.of_prime P) P x, valuation_eq_one_iff], refl,
end
@[simp]
lemma ideal_of_le_of_prime (A : valuation_subring K) (P : ideal A) [P.is_prime] :
ideal_of_le A (of_prime A P) (le_of_prime A P) = P :=
by { ext, apply is_localization.at_prime.to_map_mem_maximal_iff }
@[simp]
lemma of_prime_ideal_of_le (R S : valuation_subring K) (h : R ≤ S) :
of_prime R (ideal_of_le R S h) = S :=
begin
ext x, split,
{ rintro ⟨a, r, hr, rfl⟩, apply mul_mem, { exact h a.2 },
{ rw [← valuation_le_one_iff, map_inv₀, ← inv_one, inv_le_inv₀],
{ exact not_lt.1 ((not_iff_not.2 $ valuation_lt_one_iff S _).1 hr) },
{ intro hh, erw [valuation.zero_iff, subring.coe_eq_zero_iff] at hh,
apply hr, rw hh, apply ideal.zero_mem (R.ideal_of_le S h) },
{ exact one_ne_zero } } },
{ intro hx, by_cases hr : x ∈ R, { exact R.le_of_prime _ hr },
have : x ≠ 0 := λ h, hr (by { rw h, exact R.zero_mem }),
replace hr := (R.mem_or_inv_mem x).resolve_left hr,
{ use [1, x⁻¹, hr], split,
{ change (⟨x⁻¹, h hr⟩ : S) ∉ nonunits S,
erw [mem_nonunits_iff, not_not],
apply is_unit_of_mul_eq_one _ (⟨x, hx⟩ : S),
ext, field_simp },
{ field_simp } } },
end
lemma of_prime_le_of_le (P Q : ideal A) [P.is_prime] [Q.is_prime]
(h : P ≤ Q) : of_prime A Q ≤ of_prime A P :=
λ x ⟨a, s, hs, he⟩, ⟨a, s, λ c, hs (h c), he⟩
lemma ideal_of_le_le_of_le (R S : valuation_subring K)
(hR : A ≤ R) (hS : A ≤ S) (h : R ≤ S) :
ideal_of_le A S hS ≤ ideal_of_le A R hR :=
λ x hx, (valuation_lt_one_iff R _).2 begin
by_contra c, push_neg at c, replace c := monotone_map_of_le R S h c,
rw [(map_of_le _ _ _).map_one, map_of_le_valuation_apply] at c,
apply not_le_of_lt ((valuation_lt_one_iff S _).1 hx) c,
end
/-- The equivalence between coarsenings of a valuation ring and its prime ideals.-/
@[simps]
def prime_spectrum_equiv :
prime_spectrum A ≃ { S | A ≤ S } :=
{ to_fun := λ P, ⟨of_prime A P.as_ideal, le_of_prime _ _⟩,
inv_fun := λ S, ⟨ideal_of_le _ S S.2, infer_instance⟩,
left_inv := λ P, by { ext1, simp },
right_inv := λ S, by { ext1, simp } }
/-- An ordered variant of `prime_spectrum_equiv`. -/
@[simps]
def prime_spectrum_order_equiv : (prime_spectrum A)ᵒᵈ ≃o {S | A ≤ S} :=
{ map_rel_iff' := λ P Q,
⟨ λ h, begin
have := ideal_of_le_le_of_le A _ _ _ _ h,
iterate 2 { erw ideal_of_le_of_prime at this },
exact this,
end,
λ h, by { apply of_prime_le_of_le, exact h } ⟩,
..(prime_spectrum_equiv A) }
instance linear_order_overring : linear_order { S | A ≤ S } :=
{ le_total :=
let i : is_total (prime_spectrum A) (≤) := ⟨λ ⟨x, _⟩ ⟨y, _⟩, has_le.le.is_total.total x y⟩ in
by exactI (prime_spectrum_order_equiv A).symm.to_rel_embedding.is_total.total,
decidable_le := infer_instance,
..(infer_instance : partial_order _) }
end order
end valuation_subring
namespace valuation
variables {K} {Γ Γ₁ Γ₂ : Type*}
[linear_ordered_comm_group_with_zero Γ]
[linear_ordered_comm_group_with_zero Γ₁]
[linear_ordered_comm_group_with_zero Γ₂]
(v : valuation K Γ)
(v₁ : valuation K Γ₁)
(v₂ : valuation K Γ₂)
/-- The valuation subring associated to a valuation. -/
def valuation_subring : valuation_subring K :=
{ mem_or_inv_mem' := begin
intros x,
cases le_or_lt (v x) 1,
{ left, exact h },
{ right, change v x⁻¹ ≤ 1,
rw [map_inv₀ v, ← inv_one, inv_le_inv₀],
{ exact le_of_lt h },
{ intro c, simpa [c] using h },
{ exact one_ne_zero } }
end,
.. v.integer }
@[simp]
lemma mem_valuation_subring_iff (x : K) : x ∈ v.valuation_subring ↔ v x ≤ 1 := iff.refl _
lemma is_equiv_iff_valuation_subring : v₁.is_equiv v₂ ↔
v₁.valuation_subring = v₂.valuation_subring :=
begin
split,
{ intros h, ext x, specialize h x 1, simpa using h },
{ intros h, apply is_equiv_of_val_le_one,
intros x,
have : x ∈ v₁.valuation_subring ↔ x ∈ v₂.valuation_subring, by rw h,
simpa using this }
end
lemma is_equiv_valuation_valuation_subring :
v.is_equiv v.valuation_subring.valuation :=
begin
rw [is_equiv_iff_val_le_one],
intro x,
rw valuation_subring.valuation_le_one_iff,
refl,
end
end valuation
namespace valuation_subring
variables {K} (A : valuation_subring K)
@[simp]
lemma valuation_subring_valuation : A.valuation.valuation_subring = A :=
by { ext, rw ← A.valuation_le_one_iff, refl }
section unit_group
/-- The unit group of a valuation subring, as a subgroup of `Kˣ`. -/
def unit_group : subgroup Kˣ :=
(A.valuation.to_monoid_with_zero_hom.to_monoid_hom.comp (units.coe_hom K)).ker
@[simp] lemma mem_unit_group_iff (x : Kˣ) : x ∈ A.unit_group ↔ A.valuation x = 1 := iff.rfl
/-- For a valuation subring `A`, `A.unit_group` agrees with the units of `A`. -/
def unit_group_mul_equiv : A.unit_group ≃* Aˣ :=
{ to_fun := λ x,
{ val := ⟨x, mem_of_valuation_le_one A _ x.prop.le⟩,
inv := ⟨↑(x⁻¹), mem_of_valuation_le_one _ _ (x⁻¹).prop.le⟩,
val_inv := subtype.ext (units.mul_inv x),
inv_val := subtype.ext (units.inv_mul x) },
inv_fun := λ x, ⟨units.map A.subtype.to_monoid_hom x, A.valuation_unit x⟩,
left_inv := λ a, by { ext, refl },
right_inv := λ a, by { ext, refl },
map_mul' := λ a b, by { ext, refl } }
@[simp]
lemma coe_unit_group_mul_equiv_apply (a : A.unit_group) :
(A.unit_group_mul_equiv a : K) = a := rfl
@[simp]
lemma coe_unit_group_mul_equiv_symm_apply (a : Aˣ) :
(A.unit_group_mul_equiv.symm a : K) = a := rfl
lemma unit_group_le_unit_group {A B : valuation_subring K} :
A.unit_group ≤ B.unit_group ↔ A ≤ B :=
begin
split,
{ intros h x hx,
rw [← A.valuation_le_one_iff x, le_iff_lt_or_eq] at hx,
by_cases h_1 : x = 0, { simp only [h_1, zero_mem] },
by_cases h_2 : 1 + x = 0,
{ simp only [← add_eq_zero_iff_neg_eq.1 h_2, neg_mem _ _ (one_mem _)] },
cases hx,
{ have := h (show (units.mk0 _ h_2) ∈ A.unit_group, from A.valuation.map_one_add_of_lt hx),
simpa using B.add_mem _ _
(show 1 + x ∈ B, from set_like.coe_mem ((B.unit_group_mul_equiv ⟨_, this⟩) : B))
(B.neg_mem _ B.one_mem) },
{ have := h (show (units.mk0 x h_1) ∈ A.unit_group, from hx),
refine set_like.coe_mem ((B.unit_group_mul_equiv ⟨_, this⟩) : B) } },
{ rintros h x (hx : A.valuation x = 1),
apply_fun A.map_of_le B h at hx,
simpa using hx }
end
lemma unit_group_injective : function.injective (unit_group : valuation_subring K → subgroup _) :=
λ A B h, by { simpa only [le_antisymm_iff, unit_group_le_unit_group] using h}
lemma eq_iff_unit_group {A B : valuation_subring K} :
A = B ↔ A.unit_group = B.unit_group :=
unit_group_injective.eq_iff.symm
/-- The map on valuation subrings to their unit groups is an order embedding. -/
def unit_group_order_embedding : valuation_subring K ↪o subgroup Kˣ :=
{ to_fun := λ A, A.unit_group,
inj' := unit_group_injective,
map_rel_iff' := λ A B, unit_group_le_unit_group }
lemma unit_group_strict_mono : strict_mono (unit_group : valuation_subring K → subgroup _) :=
unit_group_order_embedding.strict_mono
end unit_group
section nonunits
/-- The nonunits of a valuation subring of `K`, as a subsemigroup of `K`-/
def nonunits : subsemigroup K :=
{ carrier := { x | A.valuation x < 1 },
mul_mem' := λ a b ha hb, (mul_lt_mul₀ ha hb).trans_eq $ mul_one _ }
lemma mem_nonunits_iff {x : K} : x ∈ A.nonunits ↔ A.valuation x < 1 := iff.rfl
lemma nonunits_le_nonunits {A B : valuation_subring K} :
B.nonunits ≤ A.nonunits ↔ A ≤ B :=
begin
split,
{ intros h x hx,
by_cases h_1 : x = 0, { simp only [h_1, zero_mem] },
rw [← valuation_le_one_iff, ← not_lt, valuation.one_lt_val_iff _ h_1] at hx ⊢,
by_contra h_2, from hx (h h_2) },
{ intros h x hx,
by_contra h_1, from not_lt.2 (monotone_map_of_le _ _ h (not_lt.1 h_1)) hx }
end
lemma nonunits_injective :
function.injective (nonunits : valuation_subring K → subsemigroup _) :=
λ A B h, by { simpa only [le_antisymm_iff, nonunits_le_nonunits] using h.symm }
lemma nonunits_inj {A B : valuation_subring K} : A.nonunits = B.nonunits ↔ A = B :=
nonunits_injective.eq_iff
/-- The map on valuation subrings to their nonunits is a dual order embedding. -/
def nonunits_order_embedding :
valuation_subring K ↪o (subsemigroup K)ᵒᵈ :=
{ to_fun := λ A, A.nonunits,
inj' := nonunits_injective,
map_rel_iff' := λ A B, nonunits_le_nonunits }
variables {A}
/-- The elements of `A.nonunits` are those of the maximal ideal of `A` after coercion to `K`.
See also `mem_nonunits_iff_exists_mem_maximal_ideal`, which gets rid of the coercion to `K`,
at the expense of a more complicated right hand side.
-/
theorem coe_mem_nonunits_iff {a : A} : (a : K) ∈ A.nonunits ↔ a ∈ local_ring.maximal_ideal A :=
(valuation_lt_one_iff _ _).symm
lemma nonunits_le : A.nonunits ≤ A.to_subring.to_submonoid.to_subsemigroup :=
λ a ha, (A.valuation_le_one_iff _).mp (A.mem_nonunits_iff.mp ha).le
lemma nonunits_subset : (A.nonunits : set K) ⊆ A := nonunits_le
/-- The elements of `A.nonunits` are those of the maximal ideal of `A`.
See also `coe_mem_nonunits_iff`, which has a simpler right hand side but requires the element
to be in `A` already.
-/
theorem mem_nonunits_iff_exists_mem_maximal_ideal {a : K} :
a ∈ A.nonunits ↔ ∃ ha, (⟨a, ha⟩ : A) ∈ local_ring.maximal_ideal A :=
⟨λ h, ⟨nonunits_subset h, coe_mem_nonunits_iff.mp h⟩,
λ ⟨ha, h⟩, coe_mem_nonunits_iff.mpr h⟩
/-- `A.nonunits` agrees with the maximal ideal of `A`, after taking its image in `K`. -/
theorem image_maximal_ideal : (coe : A → K) '' local_ring.maximal_ideal A = A.nonunits :=
begin
ext a,
simp only [set.mem_image, set_like.mem_coe, mem_nonunits_iff_exists_mem_maximal_ideal],
erw subtype.exists,
simp_rw [subtype.coe_mk, exists_and_distrib_right, exists_eq_right],
end
end nonunits
section principal_unit_group
/-- The principal unit group of a valuation subring, as a subgroup of `Kˣ`. -/
def principal_unit_group : subgroup Kˣ :=
{ carrier := { x | A.valuation (x - 1) < 1 },
mul_mem' := begin
intros a b ha hb,
refine lt_of_le_of_lt _ (max_lt hb ha),
rw [← one_mul (A.valuation (b - 1)), ← A.valuation.map_one_add_of_lt ha, add_sub_cancel'_right,
← valuation.map_mul, mul_sub_one, ← sub_add_sub_cancel],
exact A.valuation.map_add _ _,
end,
one_mem' := by simp,
inv_mem' := begin
dsimp,
intros a ha,
conv {to_lhs, rw [← mul_one (A.valuation _), ← A.valuation.map_one_add_of_lt ha]},
rwa [add_sub_cancel'_right, ← valuation.map_mul, sub_mul, units.inv_mul, ← neg_sub, one_mul,
valuation.map_neg],
end }
lemma principal_units_le_units : A.principal_unit_group ≤ A.unit_group :=
λ a h, by simpa only [add_sub_cancel'_right] using A.valuation.map_one_add_of_lt h
lemma mem_principal_unit_group_iff (x : Kˣ) :
x ∈ A.principal_unit_group ↔ A.valuation ((x : K) - 1) < 1 := iff.rfl
lemma principal_unit_group_le_principal_unit_group {A B : valuation_subring K} :
B.principal_unit_group ≤ A.principal_unit_group ↔ A ≤ B :=
begin
split,
{ intros h x hx,
by_cases h_1 : x = 0, { simp only [h_1, zero_mem] },
by_cases h_2 : x⁻¹ + 1 = 0,
{ rw [add_eq_zero_iff_eq_neg, inv_eq_iff_inv_eq, inv_neg, inv_one] at h_2,
simpa only [h_2] using B.neg_mem _ B.one_mem },
{ rw [← valuation_le_one_iff, ← not_lt, valuation.one_lt_val_iff _ h_1, ← add_sub_cancel x⁻¹,
← units.coe_mk0 h_2, ← mem_principal_unit_group_iff] at hx ⊢,
simpa only [hx] using @h (units.mk0 (x⁻¹ + 1) h_2) } },
{ intros h x hx,
by_contra h_1, from not_lt.2 (monotone_map_of_le _ _ h (not_lt.1 h_1)) hx }
end
lemma principal_unit_group_injective :
function.injective (principal_unit_group : valuation_subring K → subgroup _) :=
λ A B h, by { simpa [le_antisymm_iff, principal_unit_group_le_principal_unit_group] using h.symm }
lemma eq_iff_principal_unit_group {A B : valuation_subring K} :
A = B ↔ A.principal_unit_group = B.principal_unit_group :=
principal_unit_group_injective.eq_iff.symm
/-- The map on valuation subrings to their principal unit groups is an order embedding. -/
def principal_unit_group_order_embedding :
valuation_subring K ↪o (subgroup Kˣ)ᵒᵈ :=
{ to_fun := λ A, A.principal_unit_group,
inj' := principal_unit_group_injective,
map_rel_iff' := λ A B, principal_unit_group_le_principal_unit_group }
lemma coe_mem_principal_unit_group_iff {x : A.unit_group} :
(x : Kˣ) ∈ A.principal_unit_group ↔
A.unit_group_mul_equiv x ∈ (units.map (local_ring.residue A).to_monoid_hom).ker :=
begin
rw [monoid_hom.mem_ker, units.ext_iff],
dsimp,
let π := ideal.quotient.mk (local_ring.maximal_ideal A), change _ ↔ π _ = _,
rw [← π.map_one, ← sub_eq_zero, ← π.map_sub, ideal.quotient.eq_zero_iff_mem,
valuation_lt_one_iff],
simpa,
end
/-- The principal unit group agrees with the kernel of the canonical map from
the units of `A` to the units of the residue field of `A`. -/
def principal_unit_group_equiv :
A.principal_unit_group ≃* (units.map (local_ring.residue A).to_monoid_hom).ker :=
{ to_fun := λ x, ⟨A.unit_group_mul_equiv ⟨_, A.principal_units_le_units x.2⟩,
A.coe_mem_principal_unit_group_iff.1 x.2⟩,
inv_fun := λ x, ⟨A.unit_group_mul_equiv.symm x,
by { rw A.coe_mem_principal_unit_group_iff, simpa using set_like.coe_mem x }⟩,
left_inv := λ x, by simp,
right_inv := λ x, by simp,
map_mul' := λ x y, by refl, }
@[simp]
lemma principal_unit_group_equiv_apply (a : A.principal_unit_group) :
(principal_unit_group_equiv A a : K) = a := rfl
@[simp]
lemma principal_unit_group_symm_apply
(a : (units.map (local_ring.residue A).to_monoid_hom).ker) :
(A.principal_unit_group_equiv.symm a : K) = a := rfl
/-- The canonical map from the unit group of `A` to the units of the residue field of `A`. -/
def unit_group_to_residue_field_units :
A.unit_group →* (local_ring.residue_field A)ˣ :=
monoid_hom.comp (units.map $ (ideal.quotient.mk _).to_monoid_hom)
A.unit_group_mul_equiv.to_monoid_hom
@[simp]
lemma coe_unit_group_to_residue_field_units_apply (x : A.unit_group) :
(A.unit_group_to_residue_field_units x : (local_ring.residue_field A) ) =
(ideal.quotient.mk _ (A.unit_group_mul_equiv x : A)) := rfl
lemma ker_unit_group_to_residue_field_units :
A.unit_group_to_residue_field_units.ker = A.principal_unit_group.comap A.unit_group.subtype :=
by { ext, simpa only [subgroup.mem_comap, subgroup.coe_subtype, coe_mem_principal_unit_group_iff] }
lemma surjective_unit_group_to_residue_field_units :
function.surjective A.unit_group_to_residue_field_units :=
(local_ring.surjective_units_map_of_local_ring_hom _
ideal.quotient.mk_surjective local_ring.is_local_ring_hom_residue).comp (mul_equiv.surjective _)
/-- The quotient of the unit group of `A` by the principal unit group of `A` agrees with
the units of the residue field of `A`. -/
def units_mod_principal_units_equiv_residue_field_units :
(A.unit_group ⧸ (A.principal_unit_group.comap A.unit_group.subtype)) ≃*
(local_ring.residue_field A)ˣ :=
(quotient_group.quotient_mul_equiv_of_eq A.ker_unit_group_to_residue_field_units.symm).trans
(quotient_group.quotient_ker_equiv_of_surjective _ A.surjective_unit_group_to_residue_field_units)
@[simp]
lemma units_mod_principal_units_equiv_residue_field_units_comp_quotient_group_mk :
A.units_mod_principal_units_equiv_residue_field_units.to_monoid_hom.comp
(quotient_group.mk' _) = A.unit_group_to_residue_field_units := rfl
@[simp]
lemma units_mod_principal_units_equiv_residue_field_units_comp_quotient_group_mk_apply
(x : A.unit_group) :
A.units_mod_principal_units_equiv_residue_field_units.to_monoid_hom
(quotient_group.mk x) = A.unit_group_to_residue_field_units x := rfl
end principal_unit_group
/-! ### Pointwise actions
This transfers the action from `subring.pointwise_mul_action`, noting that it only applies when
the action is by a group. Notably this provides an instances when `G` is `K ≃+* K`.
These instances are in the `pointwise` locale.
The lemmas in this section are copied from `ring_theory/subring/pointwise.lean`; try to keep these
in sync.
-/
section pointwise_actions
open_locale pointwise
variables {G : Type*} [group G] [mul_semiring_action G K]
/-- The action on a valuation subring corresponding to applying the action to every element.
This is available as an instance in the `pointwise` locale. -/
def pointwise_has_smul : has_smul G (valuation_subring K) :=
{ smul := λ g S,
-- TODO: if we add `valuation_subring.map` at a later date, we should use it here
{ mem_or_inv_mem' := λ x, (mem_or_inv_mem S (g⁻¹ • x)).imp
(subring.mem_pointwise_smul_iff_inv_smul_mem.mpr)
(λ h, subring.mem_pointwise_smul_iff_inv_smul_mem.mpr $ by rwa smul_inv''),
.. g • S.to_subring } }
localized "attribute [instance] valuation_subring.pointwise_has_smul" in pointwise
open_locale pointwise
@[simp] lemma coe_pointwise_smul (g : G) (S : valuation_subring K) : ↑(g • S) = g • (S : set K) :=
rfl
@[simp] lemma pointwise_smul_to_subring (g : G) (S : valuation_subring K) :
(g • S).to_subring = g • S.to_subring := rfl
/-- The action on a valuation subring corresponding to applying the action to every element.
This is available as an instance in the `pointwise` locale.
This is a stronger version of `valuation_subring.pointwise_has_smul`. -/
def pointwise_mul_action : mul_action G (valuation_subring K) :=
to_subring_injective.mul_action to_subring pointwise_smul_to_subring
localized "attribute [instance] valuation_subring.pointwise_mul_action" in pointwise
open_locale pointwise
lemma smul_mem_pointwise_smul (g : G) (x : K) (S : valuation_subring K) : x ∈ S → g • x ∈ g • S :=
(set.smul_mem_smul_set : _ → _ ∈ g • (S : set K))
lemma mem_smul_pointwise_iff_exists (g : G) (x : K) (S : valuation_subring K) :
x ∈ g • S ↔ ∃ (s : K), s ∈ S ∧ g • s = x :=
(set.mem_smul_set : x ∈ g • (S : set K) ↔ _)
instance pointwise_central_scalar [mul_semiring_action Gᵐᵒᵖ K] [is_central_scalar G K] :
is_central_scalar G (valuation_subring K) :=
⟨λ g S, to_subring_injective $ by exact op_smul_eq_smul g S.to_subring⟩
@[simp] lemma smul_mem_pointwise_smul_iff {g : G} {S : valuation_subring K} {x : K} :
g • x ∈ g • S ↔ x ∈ S :=
set.smul_mem_smul_set_iff
lemma mem_pointwise_smul_iff_inv_smul_mem {g : G} {S : valuation_subring K} {x : K} :
x ∈ g • S ↔ g⁻¹ • x ∈ S :=
set.mem_smul_set_iff_inv_smul_mem
lemma mem_inv_pointwise_smul_iff {g : G} {S : valuation_subring K} {x : K} :
x ∈ g⁻¹ • S ↔ g • x ∈ S :=
set.mem_inv_smul_set_iff
@[simp] lemma pointwise_smul_le_pointwise_smul_iff {g : G} {S T : valuation_subring K} :
g • S ≤ g • T ↔ S ≤ T :=
set.set_smul_subset_set_smul_iff
lemma pointwise_smul_subset_iff {g : G} {S T : valuation_subring K} : g • S ≤ T ↔ S ≤ g⁻¹ • T :=
set.set_smul_subset_iff
lemma subset_pointwise_smul_iff {g : G} {S T : valuation_subring K} : S ≤ g • T ↔ g⁻¹ • S ≤ T :=
set.subset_set_smul_iff
end pointwise_actions
end valuation_subring
namespace valuation
variables {Γ : Type*} [linear_ordered_comm_group_with_zero Γ] (v : valuation K Γ) (x : Kˣ)
@[simp] lemma mem_unit_group_iff : x ∈ v.valuation_subring.unit_group ↔ v x = 1 :=
(valuation.is_equiv_iff_val_eq_one _ _).mp (valuation.is_equiv_valuation_valuation_subring _).symm
end valuation
|
bdb566bc75dc6dfed7e16fe75076577207a1c26e | d1a52c3f208fa42c41df8278c3d280f075eb020c | /tests/lean/run/lemma.lean | f2ce990c40a254a7b65f3e166931ae332d87c721 | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | cipher1024/lean4 | 6e1f98bb58e7a92b28f5364eb38a14c8d0aae393 | 69114d3b50806264ef35b57394391c3e738a9822 | refs/heads/master | 1,642,227,983,603 | 1,642,011,696,000 | 1,642,011,696,000 | 228,607,691 | 0 | 0 | Apache-2.0 | 1,576,584,269,000 | 1,576,584,268,000 | null | UTF-8 | Lean | false | false | 215 | lean | macro "lemma" n:declId sig:declSig val:declVal : command => `(theorem $n $sig $val)
lemma fooSimple (n : Nat) : Prop :=
if n = 0 then True else False
lemma fooPat : Nat → Prop
| 0 => True
| n+1 => False
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.