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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3d6d6e27029244a8d1ab1656bfd16fe0cafb2b54 | c213e436cb87414954d055137f2a847a9674d7d2 | /src/topology/algebra/module.lean | e6edbba9c463928e0d4c4a786207bfd7c755a238 | [
"Apache-2.0"
] | permissive | dsanjen/mathlib | 642d270c3d209cfdfb097c2ddc9dd36c102fae9f | a3844c85c606acca5922408217d55891b760fad6 | refs/heads/master | 1,606,199,308,451 | 1,576,274,676,000 | 1,576,274,676,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 13,441 | lean | /-
Copyright (c) 2019 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jan-David Salchow, Sébastien Gouëzel, Jean Lo
Theory of topological modules and continuous linear maps.
-/
import topology.algebra.ring linear_algebra.basic ring_theory.algebra
open topological_space
universes u v w u'
section prio
set_option default_priority 100 -- see Note [default priority]
/-- A topological semimodule, over a semiring which is also a topological space, is a
semimodule in which scalar multiplication is continuous. In applications, α will be a topological
semiring and β a topological additive semigroup, but this is not needed for the definition -/
class topological_semimodule (α : Type u) (β : Type v)
[semiring α] [topological_space α]
[topological_space β] [add_comm_monoid β]
[semimodule α β] : Prop :=
(continuous_smul : continuous (λp : α × β, p.1 • p.2))
end prio
section
variables {α : Type u} {β : Type v}
[semiring α] [topological_space α]
[topological_space β] [add_comm_monoid β]
[semimodule α β] [topological_semimodule α β]
lemma continuous_smul' : continuous (λp:α×β, p.1 • p.2) :=
topological_semimodule.continuous_smul α β
lemma continuous_smul {γ : Type*} [topological_space γ] {f : γ → α} {g : γ → β}
(hf : continuous f) (hg : continuous g) : continuous (λp, f p • g p) :=
continuous_smul'.comp (hf.prod_mk hg)
end
section prio
set_option default_priority 100 -- see Note [default priority]
/-- A topological module, over a ring which is also a topological space, is a module in which
scalar multiplication is continuous. In applications, α will be a topological ring and β a
topological additive group, but this is not needed for the definition -/
class topological_module (α : Type u) (β : Type v)
[ring α] [topological_space α]
[topological_space β] [add_comm_group β]
[module α β]
extends topological_semimodule α β : Prop
/-- A topological vector space is a topological module over a field. -/
class topological_vector_space (α : Type u) (β : Type v)
[discrete_field α] [topological_space α]
[topological_space β] [add_comm_group β] [vector_space α β]
extends topological_module α β
end prio
section
variables {α : Type*} {β : Type*}
[ring α] [topological_space α]
[topological_space β] [add_comm_group β]
[module α β] [topological_module α β]
/-- Scalar multiplication by a unit is a homeomorphism from a
topological module onto itself. -/
protected def homeomorph.smul_of_unit (a : units α) : β ≃ₜ β :=
{ to_fun := λ x, (a : α) • x,
inv_fun := λ x, ((a⁻¹ : units α) : α) • x,
right_inv := λ x, calc (a : α) • ((a⁻¹ : units α) : α) • x = x :
by rw [smul_smul, units.mul_inv, one_smul],
left_inv := λ x, calc ((a⁻¹ : units α) : α) • (a : α) • x = x :
by rw [smul_smul, units.inv_mul, one_smul],
continuous_to_fun := continuous_smul continuous_const continuous_id,
continuous_inv_fun := continuous_smul continuous_const continuous_id }
lemma is_open_map_smul_of_unit (a : units α) : is_open_map (λ (x : β), (a : α) • x) :=
(homeomorph.smul_of_unit a).is_open_map
lemma is_closed_map_smul_of_unit (a : units α) : is_closed_map (λ (x : β), (a : α) • x) :=
(homeomorph.smul_of_unit a).is_closed_map
end
section
variables {α : Type*} {β : Type*} {a : α}
[discrete_field α] [topological_space α]
[topological_space β] [add_comm_group β]
[vector_space α β] [topological_vector_space α β]
set_option class.instance_max_depth 36
/-- Scalar multiplication by a non-zero field element is a
homeomorphism from a topological vector space onto itself. -/
protected def homeomorph.smul_of_ne_zero (ha : a ≠ 0) : β ≃ₜ β :=
{.. homeomorph.smul_of_unit ((equiv.units_equiv_ne_zero _).inv_fun ⟨_, ha⟩)}
lemma is_open_map_smul_of_ne_zero (ha : a ≠ 0) : is_open_map (λ (x : β), a • x) :=
(homeomorph.smul_of_ne_zero ha).is_open_map
lemma is_closed_map_smul_of_ne_zero (ha : a ≠ 0) : is_closed_map (λ (x : β), a • x) :=
(homeomorph.smul_of_ne_zero ha).is_closed_map
end
/-- Continuous linear maps between modules. We only put the type classes that are necessary for the
definition, although in applications β and γ will be topological modules over the topological
ring α -/
structure continuous_linear_map
(α : Type*) [ring α]
(β : Type*) [topological_space β] [add_comm_group β]
(γ : Type*) [topological_space γ] [add_comm_group γ]
[module α β] [module α γ]
extends linear_map α β γ :=
(cont : continuous to_fun)
notation β ` →L[`:25 α `] ` γ := continuous_linear_map α β γ
namespace continuous_linear_map
section general_ring
/- Properties that hold for non-necessarily commutative rings. -/
variables
{α : Type*} [ring α]
{β : Type*} [topological_space β] [add_comm_group β]
{γ : Type*} [topological_space γ] [add_comm_group γ]
{δ : Type*} [topological_space δ] [add_comm_group δ]
[module α β] [module α γ] [module α δ]
/-- Coerce continuous linear maps to linear maps. -/
instance : has_coe (β →L[α] γ) (β →ₗ[α] γ) := ⟨to_linear_map⟩
protected lemma continuous (f : β →L[α] γ) : continuous f := f.2
/-- Coerce continuous linear maps to functions. -/
instance to_fun : has_coe_to_fun $ β →L[α] γ := ⟨_, λ f, f.to_fun⟩
@[ext] theorem ext {f g : β →L[α] γ} (h : ∀ x, f x = g x) : f = g :=
by cases f; cases g; congr' 1; ext x; apply h
theorem ext_iff {f g : β →L[α] γ} : f = g ↔ ∀ x, f x = g x :=
⟨λ h x, by rw h, by ext⟩
variables (c : α) (f g : β →L[α] γ) (h : γ →L[α] δ) (x y z : β)
-- make some straightforward lemmas available to `simp`.
@[simp] lemma map_zero : f (0 : β) = 0 := (to_linear_map _).map_zero
@[simp] lemma map_add : f (x + y) = f x + f y := (to_linear_map _).map_add _ _
@[simp] lemma map_sub : f (x - y) = f x - f y := (to_linear_map _).map_sub _ _
@[simp] lemma map_smul : f (c • x) = c • f x := (to_linear_map _).map_smul _ _
@[simp] lemma map_neg : f (-x) = - (f x) := (to_linear_map _).map_neg _
@[simp, squash_cast] lemma coe_coe : ((f : β →ₗ[α] γ) : (β → γ)) = (f : β → γ) := rfl
/-- The continuous map that is constantly zero. -/
def zero : β →L[α] γ :=
⟨0, by exact continuous_const⟩
instance: has_zero (β →L[α] γ) := ⟨zero⟩
@[simp] lemma zero_apply : (0 : β →L[α] γ) x = 0 := rfl
@[simp, elim_cast] lemma coe_zero : ((0 : β →L[α] γ) : β →ₗ[α] γ) = 0 := rfl
/- no simp attribute on the next line as simp does not always simplify 0 x to x
when 0 is the zero function, while it does for the zero continuous linear map,
and this is the most important property we care about. -/
@[elim_cast] lemma coe_zero' : ((0 : β →L[α] γ) : β → γ) = 0 := rfl
/-- the identity map as a continuous linear map. -/
def id : β →L[α] β :=
⟨linear_map.id, continuous_id⟩
instance : has_one (β →L[α] β) := ⟨id⟩
@[simp] lemma id_apply : (id : β →L[α] β) x = x := rfl
@[simp, elim_cast] lemma coe_id : ((id : β →L[α] β) : β →ₗ[α] β) = linear_map.id := rfl
@[simp, elim_cast] lemma coe_id' : ((id : β →L[α] β) : β → β) = _root_.id := rfl
@[simp] lemma one_apply : (1 : β →L[α] β) x = x := rfl
section add
variables [topological_add_group γ]
instance : has_add (β →L[α] γ) :=
⟨λ f g, ⟨f + g, f.2.add g.2⟩⟩
@[simp] lemma add_apply : (f + g) x = f x + g x := rfl
@[simp, move_cast] lemma coe_add : (((f + g) : β →L[α] γ) : β →ₗ[α] γ) = (f : β →ₗ[α] γ) + g := rfl
@[move_cast] lemma coe_add' : (((f + g) : β →L[α] γ) : β → γ) = (f : β → γ) + g := rfl
instance : has_neg (β →L[α] γ) := ⟨λ f, ⟨-f, f.2.neg⟩⟩
@[simp] lemma neg_apply : (-f) x = - (f x) := rfl
@[simp, move_cast] lemma coe_neg : (((-f) : β →L[α] γ) : β →ₗ[α] γ) = -(f : β →ₗ[α] γ) := rfl
@[move_cast] lemma coe_neg' : (((-f) : β →L[α] γ) : β → γ) = -(f : β → γ) := rfl
instance : add_comm_group (β →L[α] γ) :=
by refine {zero := 0, add := (+), neg := has_neg.neg, ..};
intros; ext; simp
@[simp] lemma sub_apply (x : β) : (f - g) x = f x - g x := rfl
@[simp, move_cast] lemma coe_sub : (((f - g) : β →L[α] γ) : β →ₗ[α] γ) = (f : β →ₗ[α] γ) - g := rfl
@[simp, move_cast] lemma coe_sub' : (((f - g) : β →L[α] γ) : β → γ) = (f : β → γ) - g := rfl
end add
/-- Composition of bounded linear maps. -/
def comp (g : γ →L[α] δ) (f : β →L[α] γ) : β →L[α] δ :=
⟨linear_map.comp g.to_linear_map f.to_linear_map, g.2.comp f.2⟩
@[simp, move_cast] lemma coe_comp : ((h.comp f) : (β →ₗ[α] δ)) = (h : γ →ₗ[α] δ).comp f := rfl
@[simp, move_cast] lemma coe_comp' : ((h.comp f) : (β → δ)) = (h : γ → δ) ∘ f := rfl
@[simp] theorem comp_id : f.comp id = f :=
ext $ λ x, rfl
@[simp] theorem id_comp : id.comp f = f :=
ext $ λ x, rfl
@[simp] theorem comp_zero : f.comp (0 : δ →L[α] β) = 0 :=
by { ext, simp }
@[simp] theorem zero_comp : (0 : γ →L[α] δ).comp f = 0 :=
by { ext, simp }
@[simp] lemma comp_add [topological_add_group γ] [topological_add_group δ]
(g : γ →L[α] δ) (f₁ f₂ : β →L[α] γ) :
g.comp (f₁ + f₂) = g.comp f₁ + g.comp f₂ :=
by { ext, simp }
@[simp] lemma add_comp [topological_add_group δ]
(g₁ g₂ : γ →L[α] δ) (f : β →L[α] γ) :
(g₁ + g₂).comp f = g₁.comp f + g₂.comp f :=
by { ext, simp }
instance : has_mul (β →L[α] β) := ⟨comp⟩
instance [topological_add_group β] : ring (β →L[α] β) :=
{ mul := (*),
one := 1,
mul_one := λ _, ext $ λ _, rfl,
one_mul := λ _, ext $ λ _, rfl,
mul_assoc := λ _ _ _, ext $ λ _, rfl,
left_distrib := λ _ _ _, ext $ λ _, map_add _ _ _,
right_distrib := λ _ _ _, ext $ λ _, linear_map.add_apply _ _ _,
..continuous_linear_map.add_comm_group }
/-- The cartesian product of two bounded linear maps, as a bounded linear map. -/
def prod (f₁ : β →L[α] γ) (f₂ : β →L[α] δ) : β →L[α] (γ × δ) :=
{ cont := f₁.2.prod_mk f₂.2,
..f₁.to_linear_map.prod f₂.to_linear_map }
end general_ring
section comm_ring
variables
{α : Type*} [comm_ring α] [topological_space α]
{β : Type*} [topological_space β] [add_comm_group β]
{γ : Type*} [topological_space γ] [add_comm_group γ]
{δ : Type*} [topological_space δ] [add_comm_group δ]
[module α β] [module α γ] [module α δ] [topological_module α δ]
instance : has_scalar α (β →L[α] δ) :=
⟨λ c f, ⟨c • f, continuous_smul continuous_const f.2⟩⟩
variables (c : α) (h : γ →L[α] δ) (f g : β →L[α] γ) (x y z : β)
@[simp] lemma smul_comp : (c • h).comp f = c • (h.comp f) := rfl
variable [topological_module α γ]
@[simp] lemma smul_apply : (c • f) x = c • (f x) := rfl
@[simp, move_cast] lemma coe_apply : (((c • f) : β →L[α] γ) : β →ₗ[α] γ) = c • (f : β →ₗ[α] γ) := rfl
@[move_cast] lemma coe_apply' : (((c • f) : β →L[α] γ) : β → γ) = c • (f : β → γ) := rfl
@[simp] lemma comp_smul : h.comp (c • f) = c • (h.comp f) := by { ext, simp }
/-- The linear map `λ x, c x • f`. Associates to a scalar-valued linear map and an element of
`γ` the `γ`-valued linear map obtained by multiplying the two (a.k.a. tensoring by `γ`) -/
def smul_right (c : β →L[α] α) (f : γ) : β →L[α] γ :=
{ cont := continuous_smul c.2 continuous_const,
..c.to_linear_map.smul_right f }
@[simp]
lemma smul_right_apply {c : β →L[α] α} {f : γ} {x : β} :
(smul_right c f : β → γ) x = (c : β → α) x • f :=
rfl
@[simp]
lemma smul_right_one_one (c : α →L[α] γ) : smul_right 1 ((c : α → γ) 1) = c :=
by ext; simp [-continuous_linear_map.map_smul, (continuous_linear_map.map_smul _ _ _).symm]
@[simp]
lemma smul_right_one_eq_iff {f f' : γ} :
smul_right (1 : α →L[α] α) f = smul_right 1 f' ↔ f = f' :=
⟨λ h, have (smul_right (1 : α →L[α] α) f : α → γ) 1 = (smul_right (1 : α →L[α] α) f' : α → γ) 1,
by rw h,
by simp at this; assumption,
by cc⟩
variable [topological_add_group γ]
instance : module α (β →L[α] γ) :=
{ smul_zero := λ _, ext $ λ _, smul_zero _,
zero_smul := λ _, ext $ λ _, zero_smul _ _,
one_smul := λ _, ext $ λ _, one_smul _ _,
mul_smul := λ _ _ _, ext $ λ _, mul_smul _ _ _,
add_smul := λ _ _ _, ext $ λ _, add_smul _ _ _,
smul_add := λ _ _ _, ext $ λ _, smul_add _ _ _ }
set_option class.instance_max_depth 55
instance : is_ring_hom (λ c : α, c • (1 : γ →L[α] γ)) :=
{ map_one := one_smul _ _,
map_add := λ _ _, ext $ λ _, add_smul _ _ _,
map_mul := λ _ _, ext $ λ _, mul_smul _ _ _ }
instance : algebra α (γ →L[α] γ) :=
{ to_fun := λ c, c • 1,
smul_def' := λ _ _, rfl,
commutes' := λ _ _, ext $ λ _, map_smul _ _ _ }
end comm_ring
section field
variables
{α : Type*} [discrete_field α] [topological_space α]
{β : Type*} [topological_space β] [add_comm_group β]
{γ : Type*} [topological_space γ] [add_comm_group γ] [topological_add_group γ]
[vector_space α β] [vector_space α γ] [topological_vector_space α γ]
instance : vector_space α (β →L[α] γ) := { ..continuous_linear_map.module }
end field
end continuous_linear_map
|
638c5a10cc63b8bc7edf2b5f35ab2fa9d3479b34 | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/number_theory/ADE_inequality.lean | 70c27658b9f50e5e6fd1d8dbbb9c8c3d0300c674 | [
"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 | 7,695 | lean | /-
Copyright (c) 2021 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin
-/
import data.multiset.sort
import data.pnat.basic
import data.rat.order
import tactic.norm_num
import tactic.field_simp
import tactic.interval_cases
/-!
# The inequality `p⁻¹ + q⁻¹ + r⁻¹ > 1`
In this file we classify solutions to the inequality
`(p⁻¹ + q⁻¹ + r⁻¹ : ℚ) > 1`, for positive natural numbers `p`, `q`, and `r`.
The solutions are exactly of the form.
* `A' q r := {1,q,r}`
* `D' r := {2,2,r}`
* `E6 := {2,3,3}`, or `E7 := {2,3,4}`, or `E8 := {2,3,5}`
This inequality shows up in Lie theory,
in the classification of Dynkin diagrams, root systems, and semisimple Lie algebras.
## Main declarations
* `pqr.A' q r`, the multiset `{1,q,r}`
* `pqr.D' r`, the multiset `{2,2,r}`
* `pqr.E6`, the multiset `{2,3,3}`
* `pqr.E7`, the multiset `{2,3,4}`
* `pqr.E8`, the multiset `{2,3,5}`
* `pqr.classification`, the classification of solutions to `p⁻¹ + q⁻¹ + r⁻¹ > 1`
-/
namespace ADE_inequality
open multiset
/-- `A' q r := {1,q,r}` is a `multiset ℕ+`
that is a solution to the inequality
`(p⁻¹ + q⁻¹ + r⁻¹ : ℚ) > 1`. -/
def A' (q r : ℕ+) : multiset ℕ+ := {1,q,r}
/-- `A r := {1,1,r}` is a `multiset ℕ+`
that is a solution to the inequality
`(p⁻¹ + q⁻¹ + r⁻¹ : ℚ) > 1`.
These solutions are related to the Dynkin diagrams $A_r$. -/
def A (r : ℕ+) : multiset ℕ+ := A' 1 r
/-- `D' r := {2,2,r}` is a `multiset ℕ+`
that is a solution to the inequality
`(p⁻¹ + q⁻¹ + r⁻¹ : ℚ) > 1`.
These solutions are related to the Dynkin diagrams $D_{r+2}$. -/
def D' (r : ℕ+) : multiset ℕ+ := {2,2,r}
/-- `E' r := {2,3,r}` is a `multiset ℕ+`.
For `r ∈ {3,4,5}` is a solution to the inequality
`(p⁻¹ + q⁻¹ + r⁻¹ : ℚ) > 1`.
These solutions are related to the Dynkin diagrams $E_{r+3}$. -/
def E' (r : ℕ+) : multiset ℕ+ := {2,3,r}
/-- `E6 := {2,3,3}` is a `multiset ℕ+`
that is a solution to the inequality
`(p⁻¹ + q⁻¹ + r⁻¹ : ℚ) > 1`.
This solution is related to the Dynkin diagrams $E_6$. -/
def E6 : multiset ℕ+ := E' 3
/-- `E7 := {2,3,4}` is a `multiset ℕ+`
that is a solution to the inequality
`(p⁻¹ + q⁻¹ + r⁻¹ : ℚ) > 1`.
This solution is related to the Dynkin diagrams $E_7$. -/
def E7 : multiset ℕ+ := E' 4
/-- `E8 := {2,3,5}` is a `multiset ℕ+`
that is a solution to the inequality
`(p⁻¹ + q⁻¹ + r⁻¹ : ℚ) > 1`.
This solution is related to the Dynkin diagrams $E_8$. -/
def E8 : multiset ℕ+ := E' 5
/-- `sum_inv pqr` for a `pqr : multiset ℕ+` is the sum of the inverses
of the elements of `pqr`, as rational number.
The intended argument is a multiset `{p,q,r}` of cardinality `3`. -/
def sum_inv (pqr : multiset ℕ+) : ℚ :=
multiset.sum $ pqr.map $ λ x, x⁻¹
lemma sum_inv_pqr (p q r : ℕ+) : sum_inv {p,q,r} = p⁻¹ + q⁻¹ + r⁻¹ :=
by simp only [sum_inv, map_congr, coe_coe, add_zero, insert_eq_cons, add_assoc,
singleton_eq_singleton, map_cons, sum_cons, map_zero, sum_zero]
/-- A multiset `pqr` of positive natural numbers is `admissible`
if it is equal to `A' q r`, or `D' r`, or one of `E6`, `E7`, or `E8`. -/
def admissible (pqr : multiset ℕ+) : Prop :=
(∃ q r, A' q r = pqr) ∨ (∃ r, D' r = pqr) ∨ (E' 3 = pqr ∨ E' 4 = pqr ∨ E' 5 = pqr)
lemma admissible_A' (q r : ℕ+) : admissible (A' q r) := or.inl ⟨q, r, rfl⟩
lemma admissible_D' (n : ℕ+) : admissible (D' n) := or.inr $ or.inl ⟨n, rfl⟩
lemma admissible_E'3 : admissible (E' 3) := or.inr $ or.inr $ or.inl rfl
lemma admissible_E'4 : admissible (E' 4) := or.inr $ or.inr $ or.inr $ or.inl rfl
lemma admissible_E'5 : admissible (E' 5) := or.inr $ or.inr $ or.inr $ or.inr rfl
lemma admissible_E6 : admissible (E6) := admissible_E'3
lemma admissible_E7 : admissible (E7) := admissible_E'4
lemma admissible_E8 : admissible (E8) := admissible_E'5
lemma admissible.one_lt_sum_inv {pqr : multiset ℕ+} :
admissible pqr → 1 < sum_inv pqr :=
begin
rw [admissible],
rintro (⟨p', q', H⟩|⟨n, H⟩|H|H|H),
{ rw [← H, A', sum_inv_pqr, add_assoc],
simp only [lt_add_iff_pos_right, pnat.one_coe, inv_one, nat.cast_one, coe_coe],
apply add_pos; simp only [pnat.pos, nat.cast_pos, inv_pos] },
{ rw [← H, D', sum_inv_pqr],
simp only [lt_add_iff_pos_right, pnat.one_coe, inv_one, nat.cast_one,
coe_coe, pnat.coe_bit0, nat.cast_bit0],
norm_num },
all_goals { rw [← H, E', sum_inv_pqr], norm_num }
end
lemma lt_three {p q r : ℕ+} (hpq : p ≤ q) (hqr : q ≤ r) (H : 1 < sum_inv {p, q, r}) :
p < 3 :=
begin
have h3 : (0:ℚ) < 3, by norm_num,
contrapose! H, rw sum_inv_pqr,
have h3q := H.trans hpq,
have h3r := h3q.trans hqr,
calc (p⁻¹ + q⁻¹ + r⁻¹ : ℚ) ≤ 3⁻¹ + 3⁻¹ + 3⁻¹ : add_le_add (add_le_add _ _) _
... = 1 : by norm_num,
all_goals { rw inv_le_inv _ h3; [assumption_mod_cast, norm_num] }
end
lemma lt_four {q r : ℕ+} (hqr : q ≤ r) (H : 1 < sum_inv {2, q, r}) :
q < 4 :=
begin
have h4 : (0:ℚ) < 4, by norm_num,
contrapose! H, rw sum_inv_pqr,
have h4r := H.trans hqr,
simp only [pnat.coe_bit0, nat.cast_bit0, pnat.one_coe, nat.cast_one, coe_coe],
calc (2⁻¹ + q⁻¹ + r⁻¹ : ℚ) ≤ 2⁻¹ + 4⁻¹ + 4⁻¹ : add_le_add (add_le_add le_rfl _) _
... = 1 : by norm_num,
all_goals { rw inv_le_inv _ h4; [assumption_mod_cast, norm_num] }
end
lemma lt_six {r : ℕ+} (H : 1 < sum_inv {2, 3, r}) :
r < 6 :=
begin
have h6 : (0:ℚ) < 6, by norm_num,
contrapose! H, rw sum_inv_pqr,
simp only [pnat.coe_bit0, nat.cast_bit0, pnat.one_coe, nat.cast_bit1, nat.cast_one,
pnat.coe_bit1, coe_coe],
calc (2⁻¹ + 3⁻¹ + r⁻¹ : ℚ) ≤ 2⁻¹ + 3⁻¹ + 6⁻¹ : add_le_add (add_le_add le_rfl le_rfl) _
... = 1 : by norm_num,
rw inv_le_inv _ h6; [assumption_mod_cast, norm_num]
end
lemma admissible_of_one_lt_sum_inv_aux' {p q r : ℕ+} (hpq : p ≤ q) (hqr : q ≤ r)
(H : 1 < sum_inv {p,q,r}) :
admissible {p,q,r} :=
begin
have hp3 : p < 3 := lt_three hpq hqr H,
interval_cases p,
{ exact admissible_A' q r },
have hq4 : q < 4 := lt_four hqr H,
interval_cases q,
{ exact admissible_D' r },
have hr6 : r < 6 := lt_six H,
interval_cases r,
{ exact admissible_E6 },
{ exact admissible_E7 },
{ exact admissible_E8 }
end
lemma admissible_of_one_lt_sum_inv_aux :
∀ {pqr : list ℕ+} (hs : pqr.sorted (≤)) (hl : pqr.length = 3) (H : 1 < sum_inv pqr),
admissible pqr
| [p,q,r] hs hl H :=
begin
obtain ⟨⟨hpq, -⟩, hqr⟩ : (p ≤ q ∧ p ≤ r) ∧ q ≤ r,
simpa using hs,
exact admissible_of_one_lt_sum_inv_aux' hpq hqr H,
end
lemma admissible_of_one_lt_sum_inv {p q r : ℕ+} (H : 1 < sum_inv {p,q,r}) :
admissible {p,q,r} :=
begin
simp only [admissible],
let S := sort ((≤) : ℕ+ → ℕ+ → Prop) {p,q,r},
have hS : S.sorted (≤) := sort_sorted _ _,
have hpqr : ({p,q,r} : multiset ℕ+) = S := (sort_eq has_le.le {p, q, r}).symm,
simp only [hpqr] at *,
apply admissible_of_one_lt_sum_inv_aux hS _ H,
simp only [singleton_eq_singleton, length_sort, insert_eq_cons, card_singleton,
card_cons, card_zero],
end
/-- A multiset `{p,q,r}` of positive natural numbers
is a solution to `(p⁻¹ + q⁻¹ + r⁻¹ : ℚ) > 1` if and only if
it is `admissible` which means it is one of:
* `A' q r := {1,q,r}`
* `D' r := {2,2,r}`
* `E6 := {2,3,3}`, or `E7 := {2,3,4}`, or `E8 := {2,3,5}`
-/
lemma classification (p q r : ℕ+) :
1 < sum_inv {p,q,r} ↔ admissible {p,q,r} :=
⟨admissible_of_one_lt_sum_inv, admissible.one_lt_sum_inv⟩
end ADE_inequality
|
e68dbca6ed3806a751b973df20badbc82e2c236e | 4e3bf8e2b29061457a887ac8889e88fa5aa0e34c | /lean/love07_metaprogramming_exercise_sheet.lean | 70bf1f431cb116f938dd8bc2018378a04868335d | [] | no_license | mukeshtiwari/logical_verification_2019 | 9f964c067a71f65eb8884743273fbeef99e6503d | 16f62717f55ed5b7b87e03ae0134791a9bef9b9a | refs/heads/master | 1,619,158,844,208 | 1,585,139,500,000 | 1,585,139,500,000 | 249,906,380 | 0 | 0 | null | 1,585,118,728,000 | 1,585,118,727,000 | null | UTF-8 | Lean | false | false | 6,560 | lean | /- LoVe Exercise 7: Metaprogramming -/
import .lovelib
namespace LoVe
open expr
open tactic
/- Question 1: A Term Exploder -/
/- In this exercise, we develop a string format for the `expr` metatype. By
default, there is no `has_repr` instance to print a nice string. For
example: -/
#eval (expr.app (expr.var 0) (expr.var 1) : expr) -- result: `[external]`
#eval (`(λx : ℕ, x + x) : expr) -- result: `[external]`
/- 1.1. Define a metafunction `expr.repr` that converts an `expr` into a
`string`. It is acceptable to leave out some fields from the `expr`
constructors, such as the level `l` of a sort, the binder information `bi` of
a λ or Π binder, and the arguments of the `macro` constructor.
**Hint**: Use `name.to_string` to convert a name to a string, and `repr` for
other types that belong to the `has_repr` type class. -/
-- enter your definition here
/- We register `expr.repr` in the `has_repr` type class, so that we can use
`repr` without qualification in the future, and so that it is available to
`#eval`. We need the `meta` keyword in front of the command we enter. -/
meta instance : has_repr expr := ⟨expr.repr⟩
/- 1.2. Test your setup. -/
#eval (expr.app (expr.var 0) (expr.var 1) : expr)
#eval (`(λx : ℕ, x + x) : expr)
/- 1.3. Compare your answer with `expr.to_raw_fmt`. -/
#check expr.to_raw_fmt
/- Question 2: `destruct_and` on Steroids -/
/- Recall from the lecture that `destruct_and` fails on the following easy
goal: -/
example {a b c d : Prop} (h : a ∧ (b ∧ c) ∧ d) :
b ∧ d :=
sorry
/- We will now address this by developing a new tactic called `destro_and`,
which applies both **des**truction and in**tro**duction rules for conjunction.
It will also go automatically through the hypotheses instead of taking an
argument. We will develop it in three steps. -/
/- 2.1. Develop a tactic `intro_ands` that replaces all goals of the form
`a ∧ b` with two new goals `a` and `b` systematically, until all top-level
conjunctions are gone.
For this, we can use tactics such as `repeat` (which repeatedly applies a tactic
on all goals until the tactic fails on each of the goal) and `applyc` (which can
be used to apply a rule, in connection with backtick quoting). -/
meta def intro_ands : tactic unit :=
sorry
example {a b c d : Prop} (h : a ∧ (b ∧ c) ∧ d) :
b ∧ d :=
begin
intro_ands,
/- The proof state should be as follows:
2 goals
a b c d : Prop,
h : a ∧ (b ∧ c) ∧ d
⊢ b
a b c d : Prop,
h : a ∧ (b ∧ c) ∧ d
⊢ d -/
repeat { sorry }
end
example {a b c d : Prop} (h : a ∧ (b ∧ c) ∧ d) :
b ∧ (a ∧ (c ∧ b)) :=
begin
intro_ands,
/- The proof state should be as follows:
4 goals
a b c d : Prop,
h : a ∧ (b ∧ c) ∧ d
⊢ b
a b c d : Prop,
h : a ∧ (b ∧ c) ∧ d
⊢ a
a b c d : Prop,
h : a ∧ (b ∧ c) ∧ d
⊢ c
a b c d : Prop,
h : a ∧ (b ∧ c) ∧ d
⊢ b -/
repeat { sorry }
end
/- 2.2. Develop a tactic `destruct_ands` that replaces hypotheses of the form
`h : a ∧ b` by two new hypotheses `h_left : a` and `h_right : b` systematically,
until all top-level conjunctions are gone.
Here is imperative-style pseudocode that you can follow:
1. Retrieve the list of hypotheses from the context. This is provided by the
metaconstant `local_context`.
2. Find the first hypothesis (= term) with a type (= proposition) of the form
`_ ∧ _`. Here, you can use the `list.mfirst` function, in conjunction with
pattern matching. You can use `infer_type` to query the type of a term.
3. Perform a case split on the first found hypothesis. This can be achieved
using the `cases` metafunction.
4. Go to step 1.
The above procedure might fail if there exists no hypotheses of the required
form. Make sure to handle this failure gracefully using `<|>`. -/
meta def destruct_ands : tactic unit :=
sorry
example {a b c d : Prop} (h : a ∧ (b ∧ c) ∧ d) :
b ∧ d :=
begin
destruct_ands,
/- The proof state should be as follows:
a b c d : Prop,
h_left : a,
h_right_right : d,
h_right_left_left : b,
h_right_left_right : c
⊢ b ∧ d -/
sorry
end
/- 2.3. Finally, combine the two tactics developed above and the `assumption`
tactic to implement the desired `destro_and` tactic. -/
meta def destro_and : tactic unit :=
sorry
example {a b c d : Prop} (h : a ∧ (b ∧ c) ∧ d) :
b ∧ d :=
by destro_and
example {a b c d : Prop} (h : a ∧ (b ∧ c) ∧ d) :
b ∧ (a ∧ (c ∧ b)) :=
by destro_and
/- Question 3 **optional**: A Theorem Finder -/
/- We will implement a function that allows us to find theorems by constants
appearing in their statements. So given a list of constant names, the function
will list all theorems in which all these constants appear.
You can use the following metaconstants:
* `declaration` contains all data (name, type, value) associated with a
declaration understood broadly (e.g., axiom, lemma, constant, etc.);
* `tactic.get_env` gives us access to the `environment`, a metatype thats lists
all `declaration`s (including all theorems);
* `environment.fold` allows us to walk through the environment and collect data;
* `expr.fold` allows us to walk through an expression and collect data. -/
/- 3.1 **optional**. Write a metafunction that checks whether an expression
contains a specific constant.
You can use `expr.fold` to walk through the expression, `||` and `ff` for
Booleans, and `expr.is_constant_of` to check whether an expression is a
constant. -/
meta def term_contains (e : expr) (nam : name) : bool :=
sorry
/- 3.2 **optional**. Write a metafunction that checks whether an expression
contains _all_ constants in a list.
You can use `list.band` (Boolean and). -/
meta def term_contains_all (nams : list name) (e : expr) : bool :=
sorry
/- 3.3 **optional**. Produce the list of all theorems that contain all constants
`nams` in their statement.
`environment.fold` allows you to walk over the list of declarations. With
`declaration.type`, you get the type of a theorem, and with
`declaration.to_name` you get the name. -/
meta def list_constants (nams : list name) (e : environment) : list name :=
sorry
/- Finally, we develop a tactic that uses the above metafunctions to log all
found theorems: -/
meta def find_constants (nams : list name) : tactic unit :=
do
env ← get_env,
list.mmap' trace (list_constants nams env)
/- We test the solution. -/
run_cmd find_constants [] -- lists all theorems
run_cmd find_constants [`list.map, `function.comp]
end LoVe
|
3099349152bc407f626afe2ab21821ee90b000fc | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /src/tactic/simpa.lean | fd1f1b1efc4a41c51675dccd5b3f1c4a54243406 | [
"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 | 2,410 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import tactic.doc_commands
open interactive
open interactive.types
namespace tactic
namespace interactive
open expr lean.parser
local postfix `?`:9001 := optional
/--
This is a "finishing" tactic modification of `simp`. It has two forms.
* `simpa [rules, ...] using e` will simplify the goal and the type of
`e` using `rules`, then try to close the goal using `e`.
Simplifying the type of `e` makes it more likely to match the goal
(which has also been simplified). This construction also tends to be
more robust under changes to the simp lemma set.
* `simpa [rules, ...]` will simplify the goal and the type of a
hypothesis `this` if present in the context, then try to close the goal using
the `assumption` tactic. -/
meta def simpa (use_iota_eqn : parse $ (tk "!")?) (trace_lemmas : parse $ (tk "?")?)
(no_dflt : parse only_flag) (hs : parse simp_arg_list) (attr_names : parse with_ident_list)
(tgt : parse (tk "using" *> texpr)?) (cfg : simp_config_ext := {}) : tactic unit :=
let simp_at lc (close_tac : tactic unit) := focus1 $
simp use_iota_eqn trace_lemmas no_dflt hs attr_names (loc.ns lc)
{fail_if_unchanged := ff, ..cfg} >>
(((close_tac <|> trivial) >> done) <|> fail "simpa failed") in
match tgt with
| none := get_local `this >> simp_at [some `this, none] assumption <|> simp_at [none] assumption
| some e := focus1 $ do
e ← i_to_expr e <|> do {
ty ← target,
-- for positional error messages, we don't care about the result
e ← i_to_expr_strict ``(%%e : %%ty),
pty ← pp ty, ptgt ← pp e,
-- Fail deliberately, to advise regarding `simp; exact` usage
fail ("simpa failed, 'using' expression type not directly " ++
"inferrable. Try:\n\nsimpa ... using\nshow " ++
to_fmt pty ++ ",\nfrom " ++ ptgt : format) },
match e with
| local_const _ lc _ _ := simp_at [some lc, none] (get_local lc >>= tactic.exact)
| e := do
t ← infer_type e,
assertv `this t e,
simp_at [some `this, none] (get_local `this >>= tactic.exact),
all_goals (try apply_instance)
end
end
add_tactic_doc
{ name := "simpa",
category := doc_category.tactic,
decl_names := [`tactic.interactive.simpa],
tags := ["simplification"] }
end interactive
end tactic
|
8f96ca52e96b3dae8bb8409aba7aa0ff648192f8 | ac60dab17014edd769c9618cc1569ce8c960a6a5 | /src/wireworld.lean | 2d6f000f357d80ded5f5dc3c14e38776680e5909 | [
"MIT"
] | permissive | frankSil/CAExtensions | 20e1f856b3ad775d5e8dc8877614dbcd58c77901 | f5c74fd9a806696c73497d9abd45b7315f45379f | refs/heads/master | 1,608,706,941,607 | 1,586,193,337,000 | 1,586,193,337,000 | 237,077,434 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 6,759 | lean | import cautomaton utils data.vector
open utils
namespace ww
section ww
inductive cellT | empty | ehead | etail | condu
open cellT
def cellT_str : cellT → string
| empty := " "
| ehead := "H"
| etail := "T"
| condu := "X"
instance cellT_to_str : has_to_string cellT := ⟨cellT_str⟩
instance cellT_repr : has_repr cellT := ⟨cellT_str⟩
instance cellT_deceq : decidable_eq cellT :=
λl r,
begin
cases l; cases r; try {exact is_true rfl}; apply is_false; trivial
end
attribute [reducible]
def ww := cautomaton cellT
def step : cellT → ℕ → cellT
| empty _ := empty
| ehead _ := etail
| etail _ := condu
| condu c := if c = 1 ∨ c = 2 then ehead else condu
def ww_step (cell : cellT) (neigh : list cellT) :=
step cell $ count_at_single neigh ehead
def mk_ww (g : vec_grid₀ cellT) : ww :=
⟨g, empty, cautomatons.moore,
sum.inr $ @bound_const (vec_grid₀ cellT) _, ww_step⟩
def wire_g :=
vec_grid₀.mk ⟨1, 5, dec_trivial,
⟨[etail, ehead, condu, condu, condu], rfl⟩⟩
⟨0, 1⟩
def wire : ww := mk_ww wire_g
def or_g_10 :=
vec_grid₀.mk ⟨5, 6, dec_trivial,
⟨[etail, ehead, empty, empty, empty, empty,
empty, empty, condu, empty, empty, empty,
empty, condu, condu, condu, condu, condu,
empty, empty, condu, empty, empty, empty,
condu, condu, empty, empty, empty, empty], rfl⟩⟩
⟨0, 1⟩
def or_10 : ww := mk_ww or_g_10
def or_g_01 :=
vec_grid₀.mk ⟨5, 6, dec_trivial,
⟨[condu, condu, empty, empty, empty, empty,
empty, empty, condu, empty, empty, empty,
empty, condu, condu, condu, condu, condu,
empty, empty, condu, empty, empty, empty,
etail, ehead, empty, empty, empty, empty], rfl⟩⟩
⟨0, 1⟩
def or_01 : ww := mk_ww or_g_01
open cardinals
section ww_or
def or_gate' :=
vec_grid₀.mk ⟨5, 6, dec_trivial,
⟨[condu, condu, empty, empty, empty, empty,
empty, empty, condu, empty, empty, empty,
empty, condu, condu, condu, condu, condu,
empty, empty, condu, empty, empty, empty,
etail, ehead, empty, empty, empty, empty], rfl⟩⟩
⟨-5, -5⟩
def or_gate : ww := mk_ww or_gate'
def write_input (i₁ : bool) (i₂ : bool) :=
let (b₁, b₂) := if i₁ then (etail, ehead) else (condu, condu) in
let (b₃, b₄) := if i₂ then (etail, ehead) else (condu, condu) in
mod_many
[(⟨-5, -10⟩, b₁), (⟨-4, -10⟩, b₂), (⟨-5, -6⟩, b₃), (⟨-4, -6⟩, b₄)]
or_gate
def sim_or (i₁ i₂ : bool) : bool :=
let sim := step_n (write_input i₁ i₂) 3 in
yield_at sim ⟨-8, -2⟩ = etail ∧ yield_at sim ⟨-8, -1⟩ = ehead
end ww_or
section ww_xor
inductive direction | N | W | E | S
open direction
structure inout :=
(p₁ : point)
(p₂ : point)
(dir : direction)
structure ww₁ :=
(aut : ww)
(ins : list inout)
(ous : list inout)
def str_of_ww₁ : ww₁ → string
| ⟨aut, _, _⟩ := to_string aut
instance ww₁_to_str : has_to_string ww₁ := ⟨str_of_ww₁⟩
instance ww₁_repr : has_repr ww₁ := ⟨str_of_ww₁⟩
def mk_ww₁ (g : vec_grid₀ cellT) (inputs outputs : list inout) : ww₁ :=
⟨mk_ww g, inputs, outputs⟩
def write (a : ww₁) (n : ℕ) (b : bool) : ww₁ :=
let input := list.nth a.ins n in
match input with
| none := a
| some ⟨p₁, p₂, dir⟩ :=
if b then
match dir with
| N :=
ww₁.mk (mod_many [(up p₁ p₂, ehead), (down p₁ p₂, etail)] a.aut)
a.ins a.ous
| S :=
ww₁.mk (mod_many [(down p₁ p₂, ehead), (up p₁ p₂, etail)] a.aut)
a.ins a.ous
| W :=
ww₁.mk (mod_many [(left p₁ p₂, ehead), (right p₁ p₂, etail)] a.aut)
a.ins a.ous
| E :=
ww₁.mk (mod_many [(right p₁ p₂, ehead), (left p₁ p₂, etail)] a.aut)
a.ins a.ous
end
else ww₁.mk (mod_many [(p₁, condu), (p₂, condu)] a.aut) a.ins a.ous
end
def read (a : ww₁) (n : ℕ) : bool :=
let output := list.nth a.ous n in
match output with
| none := ff
| some ⟨p₁, p₂, dir⟩ :=
match dir with
| N := yield_at a.aut (up p₁ p₂) = ehead ∧
yield_at a.aut (down p₁ p₂) = etail
| S := yield_at a.aut (up p₁ p₂) = etail ∧
yield_at a.aut (down p₁ p₂) = ehead
| W := yield_at a.aut (left p₁ p₂) = ehead ∧
yield_at a.aut (right p₁ p₂) = etail
| E := yield_at a.aut (left p₁ p₂) = etail ∧
yield_at a.aut (right p₁ p₂) = ehead
end
end
def xor_gate' :=
vec_grid₀.mk ⟨7, 7, dec_trivial,
⟨[condu, condu, empty, empty, empty, empty, empty,
empty, empty, condu, empty, empty, empty, empty,
empty, condu, condu, condu, condu, empty, empty,
empty, condu, empty, empty, condu, condu, condu,
empty, condu, condu, condu, condu, empty, empty,
empty, empty, condu, empty, empty, empty, empty,
condu, condu, empty, empty, empty, empty, empty], rfl⟩⟩
⟨0, 0⟩
def xor_gate_inputs : list inout := [⟨⟨0, 6⟩, ⟨1, 6⟩, E⟩, ⟨⟨0, 0⟩, ⟨1, 0⟩, E⟩]
def xor_gate_outputs : list inout := [⟨⟨5, 3⟩, ⟨6, 3⟩, E⟩]
def mk_xor (a : ww) : ww₁ := ⟨a, xor_gate_inputs, xor_gate_outputs⟩
def xor_gate_w : ww := mk_ww xor_gate'
def xor_gate : ww₁ := mk_xor xor_gate_w
def xor' (b₁ b₂ : bool) : bool :=
read (mk_xor (step_n (write (write xor_gate 0 b₂) 1 b₁).aut 5)) 0
theorem xor_iff_xor' {b₁ b₂} : bxor b₁ b₂ ↔ xor' b₁ b₂ :=
begin
cases b₁; cases b₂; split; intros h,
{
dsimp at h, contradiction
},
{
have : xor' ff ff = ff, from dec_trivial,
rw this at h,
contradiction
},
{
exact dec_trivial
},
{
dsimp, unfold_coes
},
{
exact dec_trivial
},
{
dsimp, unfold_coes
},
{
dsimp at h, contradiction
},
{
have : xor' tt tt = ff, from dec_trivial,
rw this at h,
contradiction
}
end
end ww_xor
end ww
end ww |
6d1357d5d3126acdc5f9182361dc8e5b936476d9 | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/category_theory/monoidal/Mod.lean | 1ac72705788c97178419b4ab7a22b43b8f43445f | [
"Apache-2.0"
] | permissive | jjgarzella/mathlib | 96a345378c4e0bf26cf604aed84f90329e4896a2 | 395d8716c3ad03747059d482090e2bb97db612c8 | refs/heads/master | 1,686,480,124,379 | 1,625,163,323,000 | 1,625,163,323,000 | 281,190,421 | 2 | 0 | Apache-2.0 | 1,595,268,170,000 | 1,595,268,169,000 | null | UTF-8 | Lean | false | false | 3,625 | 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 category_theory.monoidal.Mon_
/-!
# The category of module objects over a monoid object.
-/
universes v₁ v₂ u₁ u₂
open category_theory
open category_theory.monoidal_category
variables (C : Type u₁) [category.{v₁} C] [monoidal_category.{v₁} C]
variables {C}
/-- A module object for a monoid object, all internal to some monoidal category. -/
structure Mod (A : Mon_ C) :=
(X : C)
(act : A.X ⊗ X ⟶ X)
(one_act' : (A.one ⊗ 𝟙 X) ≫ act = (λ_ X).hom . obviously)
(assoc' : (A.mul ⊗ 𝟙 X) ≫ act = (α_ A.X A.X X).hom ≫ (𝟙 A.X ⊗ act) ≫ act . obviously)
restate_axiom Mod.one_act'
restate_axiom Mod.assoc'
attribute [simp, reassoc] Mod.one_act Mod.assoc
namespace Mod
variables {A : Mon_ C} (M : Mod A)
lemma assoc_flip : (𝟙 A.X ⊗ M.act) ≫ M.act = (α_ A.X A.X M.X).inv ≫ (A.mul ⊗ 𝟙 M.X) ≫ M.act :=
by simp
/-- A morphism of module objects. -/
@[ext]
structure hom (M N : Mod A) :=
(hom : M.X ⟶ N.X)
(act_hom' : M.act ≫ hom = (𝟙 A.X ⊗ hom) ≫ N.act . obviously)
restate_axiom hom.act_hom'
attribute [simp, reassoc] hom.act_hom
/-- The identity morphism on a module object. -/
@[simps]
def id (M : Mod A) : hom M M :=
{ hom := 𝟙 M.X, }
instance hom_inhabited (M : Mod A) : inhabited (hom M M) := ⟨id M⟩
/-- Composition of module object morphisms. -/
@[simps]
def comp {M N O : Mod A} (f : hom M N) (g : hom N O) : hom M O :=
{ hom := f.hom ≫ g.hom, }
instance : category (Mod A) :=
{ hom := λ M N, hom M N,
id := id,
comp := λ M N O f g, comp f g, }
@[simp] lemma id_hom' (M : Mod A) : (𝟙 M : hom M M).hom = 𝟙 M.X := rfl
@[simp] lemma comp_hom' {M N K : Mod A} (f : M ⟶ N) (g : N ⟶ K) :
(f ≫ g : hom M K).hom = f.hom ≫ g.hom := rfl
variables (A)
/-- A monoid object as a module over itself. -/
@[simps]
def regular : Mod A :=
{ X := A.X,
act := A.mul, }
instance : inhabited (Mod A) := ⟨regular A⟩
/-- The forgetful functor from module objects to the ambient category. -/
def forget : Mod A ⥤ C :=
{ obj := λ A, A.X,
map := λ A B f, f.hom, }
open category_theory.monoidal_category
/--
A morphism of monoid objects induces a "restriction" or "comap" functor
between the categories of module objects.
-/
@[simps]
def comap {A B : Mon_ C} (f : A ⟶ B) : Mod B ⥤ Mod A :=
{ obj := λ M,
{ X := M.X,
act := (f.hom ⊗ 𝟙 M.X) ≫ M.act,
one_act' :=
begin
slice_lhs 1 2 { rw [←comp_tensor_id], },
rw [f.one_hom, one_act],
end,
assoc' :=
begin
-- oh, for homotopy.io in a widget!
slice_rhs 2 3 { rw [id_tensor_comp_tensor_id, ←tensor_id_comp_id_tensor], },
rw id_tensor_comp,
slice_rhs 4 5 { rw Mod.assoc_flip, },
slice_rhs 3 4 { rw associator_inv_naturality, },
slice_rhs 2 3 { rw [←tensor_id, associator_inv_naturality], },
slice_rhs 1 3 { rw [iso.hom_inv_id_assoc], },
slice_rhs 1 2 { rw [←comp_tensor_id, tensor_id_comp_id_tensor], },
slice_rhs 1 2 { rw [←comp_tensor_id, ←f.mul_hom], },
rw [comp_tensor_id, category.assoc],
end, },
map := λ M N g,
{ hom := g.hom,
act_hom' :=
begin
dsimp,
slice_rhs 1 2 { rw [id_tensor_comp_tensor_id, ←tensor_id_comp_id_tensor], },
slice_rhs 2 3 { rw ←g.act_hom, },
rw category.assoc,
end }, }
-- Lots more could be said about `comap`, e.g. how it interacts with
-- identities, compositions, and equalities of monoid object morphisms.
end Mod
|
f41c569e9c585169041081a8744195157f70fd06 | 07c76fbd96ea1786cc6392fa834be62643cea420 | /hott/init/path.hlean | ba71d51d520e249534761aa405dfd5caf51b444d | [
"Apache-2.0"
] | permissive | fpvandoorn/lean2 | 5a430a153b570bf70dc8526d06f18fc000a60ad9 | 0889cf65b7b3cebfb8831b8731d89c2453dd1e9f | refs/heads/master | 1,592,036,508,364 | 1,545,093,958,000 | 1,545,093,958,000 | 75,436,854 | 0 | 0 | null | 1,480,718,780,000 | 1,480,718,780,000 | null | UTF-8 | Lean | false | false | 32,674 | hlean | /-
Copyright (c) 2014 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Jakob von Raumer, Floris van Doorn
Ported from Coq HoTT
-/
prelude
import .function .tactic
open function eq
/- Path equality -/
namespace eq
variables {A A' B B' C : Type} {P : A → Type} {a a' a'' x y z t : A} {b b' b'' : B}
--notation a = b := eq a b
notation x = y `:>`:50 A:49 := @eq A x y
definition idp [reducible] [constructor] {a : A} := refl a
definition idpath [reducible] [constructor] (a : A) := refl a
-- unbased path induction
definition rec_unbased [reducible] [unfold 6] {P : Π (a b : A), (a = b) → Type}
(H : Π (a : A), P a a idp) {a b : A} (p : a = b) : P a b p :=
eq.rec (H a) p
definition rec_on_unbased [reducible] [unfold 5] {P : Π (a b : A), (a = b) → Type}
{a b : A} (p : a = b) (H : Π (a : A), P a a idp) : P a b p :=
eq.rec (H a) p
/- Concatenation and inverse -/
definition concat [trans] [unfold 6] (p : x = y) (q : y = z) : x = z :=
by induction q; exact p
definition inverse [symm] [unfold 4] (p : x = y) : y = x :=
by induction p; reflexivity
infix ⬝ := concat
postfix ⁻¹ := inverse
--a second notation for the inverse, which is not overloaded
postfix [parsing_only] `⁻¹ᵖ`:std.prec.max_plus := inverse
/- The 1-dimensional groupoid structure -/
-- The identity path is a right unit.
definition con_idp [unfold_full] (p : x = y) : p ⬝ idp = p :=
idp
-- The identity path is a left unit.
definition idp_con [unfold 4] (p : x = y) : idp ⬝ p = p :=
by induction p; reflexivity
-- Concatenation is associative.
definition con.assoc' [unfold 8] (p : x = y) (q : y = z) (r : z = t) :
p ⬝ (q ⬝ r) = (p ⬝ q) ⬝ r :=
by induction r; reflexivity
definition con.assoc [unfold 8] (p : x = y) (q : y = z) (r : z = t) :
(p ⬝ q) ⬝ r = p ⬝ (q ⬝ r) :=
by induction r; reflexivity
definition con.assoc5 {a₁ a₂ a₃ a₄ a₅ a₆ : A}
(p₁ : a₁ = a₂) (p₂ : a₂ = a₃) (p₃ : a₃ = a₄) (p₄ : a₄ = a₅) (p₅ : a₅ = a₆) :
p₁ ⬝ (p₂ ⬝ p₃ ⬝ p₄) ⬝ p₅ = (p₁ ⬝ p₂) ⬝ p₃ ⬝ (p₄ ⬝ p₅) :=
by induction p₅; induction p₄; induction p₃; reflexivity
-- The right inverse law.
definition con.right_inv [unfold 4] (p : x = y) : p ⬝ p⁻¹ = idp :=
by induction p; reflexivity
-- The left inverse law.
definition con.left_inv [unfold 4] (p : x = y) : p⁻¹ ⬝ p = idp :=
by induction p; reflexivity
/- Several auxiliary theorems about canceling inverses across associativity. These are somewhat
redundant, following from earlier theorems. -/
definition inv_con_cancel_left (p : x = y) (q : y = z) : p⁻¹ ⬝ (p ⬝ q) = q :=
by induction q; induction p; reflexivity
definition con_inv_cancel_left (p : x = y) (q : x = z) : p ⬝ (p⁻¹ ⬝ q) = q :=
by induction q; induction p; reflexivity
definition con_inv_cancel_right (p : x = y) (q : y = z) : (p ⬝ q) ⬝ q⁻¹ = p :=
by induction q; reflexivity
definition inv_con_cancel_right (p : x = z) (q : y = z) : (p ⬝ q⁻¹) ⬝ q = p :=
by induction q; reflexivity
-- Inverse distributes over concatenation
definition con_inv (p : x = y) (q : y = z) : (p ⬝ q)⁻¹ = q⁻¹ ⬝ p⁻¹ :=
by induction q; induction p; reflexivity
definition inv_con_inv_left (p : y = x) (q : y = z) : (p⁻¹ ⬝ q)⁻¹ = q⁻¹ ⬝ p :=
by induction q; induction p; reflexivity
definition inv_con_inv_right (p : x = y) (q : z = y) : (p ⬝ q⁻¹)⁻¹ = q ⬝ p⁻¹ :=
by induction q; induction p; reflexivity
definition inv_con_inv_inv (p : y = x) (q : z = y) : (p⁻¹ ⬝ q⁻¹)⁻¹ = q ⬝ p :=
by induction q; induction p; reflexivity
-- Inverse is an involution.
definition inv_inv [unfold 4] (p : x = y) : p⁻¹⁻¹ = p :=
by induction p; reflexivity
-- auxiliary definition used by 'cases' tactic
definition elim_inv_inv [unfold 5] {A : Type} {a b : A} {C : a = b → Type}
(H₁ : a = b) (H₂ : C (H₁⁻¹⁻¹)) : C H₁ :=
eq.rec_on (inv_inv H₁) H₂
definition eq.rec_symm {A : Type} {a₀ : A} {P : Π⦃a₁⦄, a₁ = a₀ → Type}
(H : P idp) ⦃a₁ : A⦄ (p : a₁ = a₀) : P p :=
begin
cases p, exact H
end
/- Theorems for moving things around in equations -/
definition con_eq_of_eq_inv_con {p : x = z} {q : y = z} {r : y = x} :
p = r⁻¹ ⬝ q → r ⬝ p = q :=
begin
induction r, intro h, exact !idp_con ⬝ h ⬝ !idp_con
end
definition con_eq_of_eq_con_inv [unfold 5] {p : x = z} {q : y = z} {r : y = x} :
r = q ⬝ p⁻¹ → r ⬝ p = q :=
by induction p; exact id
definition inv_con_eq_of_eq_con {p : x = z} {q : y = z} {r : x = y} :
p = r ⬝ q → r⁻¹ ⬝ p = q :=
by induction r; intro h; exact !idp_con ⬝ h ⬝ !idp_con
definition con_inv_eq_of_eq_con [unfold 5] {p : z = x} {q : y = z} {r : y = x} :
r = q ⬝ p → r ⬝ p⁻¹ = q :=
by induction p; exact id
definition eq_con_of_inv_con_eq {p : x = z} {q : y = z} {r : y = x} :
r⁻¹ ⬝ q = p → q = r ⬝ p :=
by induction r; intro h; exact !idp_con⁻¹ ⬝ h ⬝ !idp_con⁻¹
definition eq_con_of_con_inv_eq [unfold 5] {p : x = z} {q : y = z} {r : y = x} :
q ⬝ p⁻¹ = r → q = r ⬝ p :=
by induction p; exact id
definition eq_inv_con_of_con_eq {p : x = z} {q : y = z} {r : x = y} :
r ⬝ q = p → q = r⁻¹ ⬝ p :=
by induction r; intro h; exact !idp_con⁻¹ ⬝ h ⬝ !idp_con⁻¹
definition eq_con_inv_of_con_eq [unfold 5] {p : z = x} {q : y = z} {r : y = x} :
q ⬝ p = r → q = r ⬝ p⁻¹ :=
by induction p; exact id
definition eq_of_con_inv_eq_idp [unfold 5] {p q : x = y} : p ⬝ q⁻¹ = idp → p = q :=
by induction q; exact id
definition eq_of_inv_con_eq_idp {p q : x = y} : q⁻¹ ⬝ p = idp → p = q :=
by induction q; intro h; exact !idp_con⁻¹ ⬝ h
definition eq_inv_of_con_eq_idp' [unfold 5] {p : x = y} {q : y = x} : p ⬝ q = idp → p = q⁻¹ :=
by induction q; exact id
definition eq_inv_of_con_eq_idp {p : x = y} {q : y = x} : q ⬝ p = idp → p = q⁻¹ :=
by induction q; intro h; exact !idp_con⁻¹ ⬝ h
definition eq_of_idp_eq_inv_con {p q : x = y} : idp = p⁻¹ ⬝ q → p = q :=
by induction p; intro h; exact h ⬝ !idp_con
definition eq_of_idp_eq_con_inv [unfold 4] {p q : x = y} : idp = q ⬝ p⁻¹ → p = q :=
by induction p; exact id
definition inv_eq_of_idp_eq_con [unfold 4] {p : x = y} {q : y = x} : idp = q ⬝ p → p⁻¹ = q :=
by induction p; exact id
definition inv_eq_of_idp_eq_con' {p : x = y} {q : y = x} : idp = p ⬝ q → p⁻¹ = q :=
by induction p; intro h; exact h ⬝ !idp_con
definition con_inv_eq_idp [unfold 6] {p q : x = y} (r : p = q) : p ⬝ q⁻¹ = idp :=
by cases r; apply con.right_inv
definition inv_con_eq_idp [unfold 6] {p q : x = y} (r : p = q) : q⁻¹ ⬝ p = idp :=
by cases r; apply con.left_inv
definition con_eq_idp {p : x = y} {q : y = x} (r : p = q⁻¹) : p ⬝ q = idp :=
by cases q; exact r
definition idp_eq_inv_con {p q : x = y} (r : p = q) : idp = p⁻¹ ⬝ q :=
by cases r; exact !con.left_inv⁻¹
definition idp_eq_con_inv {p q : x = y} (r : p = q) : idp = q ⬝ p⁻¹ :=
by cases r; exact !con.right_inv⁻¹
definition idp_eq_con {p : x = y} {q : y = x} (r : p⁻¹ = q) : idp = q ⬝ p :=
by cases p; exact r
definition eq_idp_of_con_right {p : x = x} {q : x = y} (r : p ⬝ q = q) : p = idp :=
by cases q; exact r
definition eq_idp_of_con_left {p : x = x} {q : y = x} (r : q ⬝ p = q) : p = idp :=
by cases q; exact (idp_con p)⁻¹ ⬝ r
definition idp_eq_of_con_right {p : x = x} {q : x = y} (r : q = p ⬝ q) : idp = p :=
by cases q; exact r
definition idp_eq_of_con_left {p : x = x} {q : y = x} (r : q = q ⬝ p) : idp = p :=
by cases q; exact r ⬝ idp_con p
/- Transport -/
definition transport [subst] [reducible] [unfold 5] (P : A → Type) {x y : A} (p : x = y)
(u : P x) : P y :=
by induction p; exact u
-- This idiom makes the operation right associative.
infixr ` ▸ ` := transport _
definition cast [reducible] [unfold 3] {A B : Type} (p : A = B) (a : A) : B :=
p ▸ a
definition cast_def [reducible] [unfold_full] {A B : Type} (p : A = B) (a : A)
: cast p a = p ▸ a :=
idp
definition tr_rev [reducible] [unfold 6] (P : A → Type) {x y : A} (p : x = y) (u : P y) : P x :=
p⁻¹ ▸ u
definition ap [unfold 6] ⦃A B : Type⦄ (f : A → B) {x y:A} (p : x = y) : f x = f y :=
by induction p; reflexivity
abbreviation ap01 [parsing_only] := ap
definition homotopy [reducible] (f g : Πx, P x) : Type :=
Πx : A, f x = g x
infix ~ := homotopy
protected definition homotopy.refl [refl] [reducible] [unfold_full] (f : Πx, P x) : f ~ f :=
λ x, idp
protected definition homotopy.rfl [reducible] [unfold_full] {f : Πx, P x} : f ~ f :=
homotopy.refl f
protected definition homotopy.symm [symm] [reducible] [unfold_full] {f g : Πx, P x} (H : f ~ g)
: g ~ f :=
λ x, (H x)⁻¹
protected definition homotopy.trans [trans] [reducible] [unfold_full] {f g h : Πx, P x}
(H1 : f ~ g) (H2 : g ~ h) : f ~ h :=
λ x, H1 x ⬝ H2 x
infix ` ⬝hty `:75 := homotopy.trans
postfix `⁻¹ʰᵗʸ`:(max+1) := homotopy.symm
definition hwhisker_left [unfold_full] (g : B → C) {f f' : A → B} (H : f ~ f') :
g ∘ f ~ g ∘ f' :=
λa, ap g (H a)
definition hwhisker_right [unfold_full] (f : A → B) {g g' : B → C} (H : g ~ g') :
g ∘ f ~ g' ∘ f :=
λa, H (f a)
definition compose_id (f : A → B) : f ∘ id ~ f :=
by reflexivity
definition id_compose (f : A → B) : id ∘ f ~ f :=
by reflexivity
definition compose2 {A B C : Type} {g g' : B → C} {f f' : A → B}
(p : g ~ g') (q : f ~ f') : g ∘ f ~ g' ∘ f' :=
hwhisker_right f p ⬝hty hwhisker_left g' q
definition hassoc {A B C D : Type} (h : C → D) (g : B → C) (f : A → B) : (h ∘ g) ∘ f ~ h ∘ (g ∘ f) :=
λa, idp
definition homotopy_of_eq [unfold 5] {f g : Πx, P x} (H : f = g) : f ~ g :=
λa, ap (λh, h a) H
definition apd10 [unfold 5] {f g : Πx, P x} (H : f = g) : f ~ g :=
λa, ap (λh, h a) H
--the next theorem is useful if you want to write "apply (apd10' a)"
definition apd10' [unfold 6] {f g : Πx, P x} (a : A) (H : f = g) : f a = g a :=
apd10 H a
--apd10 is a special case of ap
definition apd10_eq_ap_eval {f g : Πx, P x} (H : f = g) (a : A)
: apd10 H a = ap (λs : Πx, P x, s a) H :=
by reflexivity
definition ap10 [reducible] [unfold 5] {f g : A → B} (H : f = g) : f ~ g := apd10 H
definition ap11 {f g : A → B} (H : f = g) {x y : A} (p : x = y) : f x = g y :=
by induction H; exact ap f p
-- [apd] is defined in init.pathover using pathover instead of an equality with transport.
definition apdt [unfold 6] (f : Πa, P a) {x y : A} (p : x = y) : p ▸ f x = f y :=
by induction p; reflexivity
definition ap011 [unfold 9] (f : A → B → C) (Ha : a = a') (Hb : b = b') : f a b = f a' b' :=
by cases Ha; exact ap (f a) Hb
/- More theorems for moving things around in equations -/
definition tr_eq_of_eq_inv_tr {P : A → Type} {x y : A} {p : x = y} {u : P x} {v : P y} :
u = p⁻¹ ▸ v → p ▸ u = v :=
by induction p; exact id
definition inv_tr_eq_of_eq_tr {P : A → Type} {x y : A} {p : y = x} {u : P x} {v : P y} :
u = p ▸ v → p⁻¹ ▸ u = v :=
by induction p; exact id
definition eq_inv_tr_of_tr_eq {P : A → Type} {x y : A} {p : x = y} {u : P x} {v : P y} :
p ▸ u = v → u = p⁻¹ ▸ v :=
by induction p; exact id
definition eq_tr_of_inv_tr_eq {P : A → Type} {x y : A} {p : y = x} {u : P x} {v : P y} :
p⁻¹ ▸ u = v → u = p ▸ v :=
by induction p; exact id
/- Transporting along the diagonal of a type family -/
definition tr_diag_eq_tr_tr {A : Type} (P : A → A → Type) {x y : A} (p : x = y) (a : P x x) :
transport (λ x, P x x) p a = transport (λ x, P _ x) p (transport (λ x, P x _) p a) :=
by induction p; reflexivity
/- Functoriality of functions -/
-- Here we prove that functions behave like functors between groupoids, and that [ap] itself is
-- functorial.
-- Functions take identity paths to identity paths
definition ap_idp [unfold_full] (x : A) (f : A → B) : ap f idp = idp :> (f x = f x) := idp
-- Functions commute with concatenation.
definition ap_con [unfold 8] (f : A → B) {x y z : A} (p : x = y) (q : y = z) :
ap f (p ⬝ q) = ap f p ⬝ ap f q :=
by induction q; reflexivity
definition con_ap_con_eq_con_ap_con_ap (f : A → B) {w x y z : A} (r : f w = f x)
(p : x = y) (q : y = z) : r ⬝ ap f (p ⬝ q) = (r ⬝ ap f p) ⬝ ap f q :=
by induction q; induction p; reflexivity
definition ap_con_con_eq_ap_con_ap_con (f : A → B) {w x y z : A} (p : x = y) (q : y = z)
(r : f z = f w) : ap f (p ⬝ q) ⬝ r = ap f p ⬝ (ap f q ⬝ r) :=
by induction q; induction p; apply con.assoc
-- Functions commute with path inverses.
definition ap_inv' [unfold 6] (f : A → B) {x y : A} (p : x = y) : (ap f p)⁻¹ = ap f p⁻¹ :=
by induction p; reflexivity
definition ap_inv [unfold 6] (f : A → B) {x y : A} (p : x = y) : ap f p⁻¹ = (ap f p)⁻¹ :=
by induction p; reflexivity
-- [ap] itself is functorial in the first argument.
definition ap_id [unfold 4] (p : x = y) : ap id p = p :=
by induction p; reflexivity
definition ap_compose [unfold 8] (g : B → C) (f : A → B) {x y : A} (p : x = y) :
ap (g ∘ f) p = ap g (ap f p) :=
by induction p; reflexivity
-- Sometimes we don't have the actual function [compose].
definition ap_compose' [unfold 8] (g : B → C) (f : A → B) {x y : A} (p : x = y) :
ap g (ap f p) = ap (λa, g (f a)) p :=
by induction p; reflexivity
-- The action of constant maps.
definition ap_constant [unfold 5] (p : x = y) (z : B) : ap (λu, z) p = idp :=
by induction p; reflexivity
-- Naturality of [ap].
-- see also natural_square in cubical.square
definition ap_con_eq_con_ap {f g : A → B} (p : f ~ g) {x y : A} (q : x = y) :
ap f q ⬝ p y = p x ⬝ ap g q :=
by induction q; apply idp_con
-- Naturality of [ap] at identity.
definition ap_con_eq_con {f : A → A} (p : Πx, f x = x) {x y : A} (q : x = y) :
ap f q ⬝ p y = p x ⬝ q :=
by induction q; apply idp_con
definition con_ap_eq_con {f : A → A} (p : Πx, x = f x) {x y : A} (q : x = y) :
p x ⬝ ap f q = q ⬝ p y :=
by induction q; exact !idp_con⁻¹
-- Naturality of [ap] with constant function
definition ap_con_eq {f : A → B} {b : B} (p : Πx, f x = b) {x y : A} (q : x = y) :
ap f q ⬝ p y = p x :=
by induction q; apply idp_con
-- Naturality with other paths hanging around.
definition con_ap_con_con_eq_con_con_ap_con {f g : A → B} (p : f ~ g) {x y : A} (q : x = y)
{w z : B} (r : w = f x) (s : g y = z) :
(r ⬝ ap f q) ⬝ (p y ⬝ s) = (r ⬝ p x) ⬝ (ap g q ⬝ s) :=
by induction s; induction q; reflexivity
definition con_ap_con_eq_con_con_ap {f g : A → B} (p : f ~ g) {x y : A} (q : x = y)
{w : B} (r : w = f x) :
(r ⬝ ap f q) ⬝ p y = (r ⬝ p x) ⬝ ap g q :=
by induction q; reflexivity
definition ap_con_con_eq_con_ap_con {f g : A → B} (p : f ~ g) {x y : A} (q : x = y)
{z : B} (s : g y = z) :
ap f q ⬝ (p y ⬝ s) = p x ⬝ (ap g q ⬝ s) :=
begin
induction s,
induction q,
apply idp_con
end
definition con_ap_con_con_eq_con_con_con {f : A → A} (p : f ~ id) {x y : A} (q : x = y)
{w z : A} (r : w = f x) (s : y = z) :
(r ⬝ ap f q) ⬝ (p y ⬝ s) = (r ⬝ p x) ⬝ (q ⬝ s) :=
by induction s; induction q; reflexivity
definition con_con_ap_con_eq_con_con_con {g : A → A} (p : id ~ g) {x y : A} (q : x = y)
{w z : A} (r : w = x) (s : g y = z) :
(r ⬝ p x) ⬝ (ap g q ⬝ s) = (r ⬝ q) ⬝ (p y ⬝ s) :=
by induction s; induction q; reflexivity
definition con_ap_con_eq_con_con {f : A → A} (p : f ~ id) {x y : A} (q : x = y)
{w : A} (r : w = f x) :
(r ⬝ ap f q) ⬝ p y = (r ⬝ p x) ⬝ q :=
by induction q; reflexivity
definition ap_con_con_eq_con_con {f : A → A} (p : f ~ id) {x y : A} (q : x = y)
{z : A} (s : y = z) :
ap f q ⬝ (p y ⬝ s) = p x ⬝ (q ⬝ s) :=
by induction s; induction q; apply idp_con
definition con_con_ap_eq_con_con {g : A → A} (p : id ~ g) {x y : A} (q : x = y)
{w : A} (r : w = x) :
(r ⬝ p x) ⬝ ap g q = (r ⬝ q) ⬝ p y :=
begin cases q, exact idp end
definition con_ap_con_eq_con_con' {g : A → A} (p : id ~ g) {x y : A} (q : x = y)
{z : A} (s : g y = z) :
p x ⬝ (ap g q ⬝ s) = q ⬝ (p y ⬝ s) :=
by induction s; induction q; exact !idp_con⁻¹
/- Action of [apd10] and [ap10] on paths -/
-- Application of paths between functions preserves the groupoid structure
definition apd10_idp (f : Πx, P x) (x : A) : apd10 (refl f) x = idp := idp
definition apd10_con {f f' f'' : Πx, P x} (h : f = f') (h' : f' = f'') (x : A) :
apd10 (h ⬝ h') x = apd10 h x ⬝ apd10 h' x :=
by induction h; induction h'; reflexivity
definition apd10_inv {f g : Πx : A, P x} (h : f = g) (x : A) :
apd10 h⁻¹ x = (apd10 h x)⁻¹ :=
by induction h; reflexivity
definition ap10_idp {f : A → B} (x : A) : ap10 (refl f) x = idp := idp
definition ap10_con {f f' f'' : A → B} (h : f = f') (h' : f' = f'') (x : A) :
ap10 (h ⬝ h') x = ap10 h x ⬝ ap10 h' x := apd10_con h h' x
definition ap10_inv {f g : A → B} (h : f = g) (x : A) : ap10 h⁻¹ x = (ap10 h x)⁻¹ :=
apd10_inv h x
-- [ap10] also behaves nicely on paths produced by [ap]
definition ap_ap10 (f g : A → B) (h : B → C) (p : f = g) (a : A) :
ap h (ap10 p a) = ap10 (ap (λ f', h ∘ f') p) a:=
by induction p; reflexivity
/- some lemma's about ap011 -/
definition ap_eq_ap011_left (f : A → B → C) (Ha : a = a') (b : B) :
ap (λa, f a b) Ha = ap011 f Ha idp :=
by induction Ha; reflexivity
definition ap_eq_ap011_right (f : A → B → C) (a : A) (Hb : b = b') :
ap (f a) Hb = ap011 f idp Hb :=
by reflexivity
definition ap_ap011 {A B C D : Type} (g : C → D) (f : A → B → C) {a a' : A} {b b' : B}
(p : a = a') (q : b = b') : ap g (ap011 f p q) = ap011 (λa b, g (f a b)) p q :=
begin
induction p, exact (ap_compose g (f a) q)⁻¹
end
/- Transport and the groupoid structure of paths -/
definition idp_tr {P : A → Type} {x : A} (u : P x) : idp ▸ u = u := idp
definition con_tr [unfold 7] {P : A → Type} {x y z : A} (p : x = y) (q : y = z) (u : P x) :
p ⬝ q ▸ u = q ▸ p ▸ u :=
by induction q; reflexivity
definition tr_inv_tr {P : A → Type} {x y : A} (p : x = y) (z : P y) :
p ▸ p⁻¹ ▸ z = z :=
(con_tr p⁻¹ p z)⁻¹ ⬝ ap (λr, transport P r z) (con.left_inv p)
definition inv_tr_tr {P : A → Type} {x y : A} (p : x = y) (z : P x) :
p⁻¹ ▸ p ▸ z = z :=
(con_tr p p⁻¹ z)⁻¹ ⬝ ap (λr, transport P r z) (con.right_inv p)
definition cast_cast_inv {A : Type} {P : A → Type} {x y : A} (p : x = y) (z : P y) :
cast (ap P p) (cast (ap P p⁻¹) z) = z :=
by induction p; reflexivity
definition cast_inv_cast {A : Type} {P : A → Type} {x y : A} (p : x = y) (z : P x) :
cast (ap P p⁻¹) (cast (ap P p) z) = z :=
by induction p; reflexivity
definition fn_tr_eq_tr_fn {P Q : A → Type} {x y : A} (p : x = y) (f : Πx, P x → Q x) (z : P x) :
f y (p ▸ z) = p ▸ f x z :=
by induction p; reflexivity
definition fn_cast_eq_cast_fn {A : Type} {P Q : A → Type} {x y : A} (p : x = y)
(f : Πx, P x → Q x) (z : P x) : f y (cast (ap P p) z) = cast (ap Q p) (f x z) :=
by induction p; reflexivity
definition con_con_tr {P : A → Type}
{x y z w : A} (p : x = y) (q : y = z) (r : z = w) (u : P x) :
ap (λe, e ▸ u) (con.assoc' p q r) ⬝ (con_tr (p ⬝ q) r u) ⬝
ap (transport P r) (con_tr p q u)
= (con_tr p (q ⬝ r) u) ⬝ (con_tr q r (p ▸ u))
:> ((p ⬝ (q ⬝ r)) ▸ u = r ▸ q ▸ p ▸ u) :=
by induction r; induction q; induction p; reflexivity
-- Here is another coherence lemma for transport.
definition tr_inv_tr_lemma {P : A → Type} {x y : A} (p : x = y) (z : P x) :
tr_inv_tr p (transport P p z) = ap (transport P p) (inv_tr_tr p z) :=
by induction p; reflexivity
/- some properties for apdt -/
definition apdt_idp (x : A) (f : Πx, P x) : apdt f idp = idp :> (f x = f x) := idp
definition apdt_con (f : Πx, P x) {x y z : A} (p : x = y) (q : y = z)
: apdt f (p ⬝ q) = con_tr p q (f x) ⬝ ap (transport P q) (apdt f p) ⬝ apdt f q :=
by cases p; cases q; apply idp
definition apdt_inv (f : Πx, P x) {x y : A} (p : x = y)
: apdt f p⁻¹ = (eq_inv_tr_of_tr_eq (apdt f p))⁻¹ :=
by cases p; apply idp
-- Dependent transport in a doubly dependent type.
-- This is a special case of transporto in init.pathover
definition transportD [unfold 6] {P : A → Type} (Q : Πa, P a → Type)
{a a' : A} (p : a = a') (b : P a) (z : Q a b) : Q a' (p ▸ b) :=
by induction p; exact z
-- In Coq the variables P, Q and b are explicit, but in Lean we can probably have them implicit
-- using the following notation
notation p ` ▸D `:65 x:64 := transportD _ p _ x
-- transporting over 2 one-dimensional paths
-- This is a special case of transporto in init.pathover
definition transport11 {A B : Type} (P : A → B → Type) {a a' : A} {b b' : B}
(p : a = a') (q : b = b') (z : P a b) : P a' b' :=
transport (P a') q (p ▸ z)
definition transport11_con (P : A → B → Type) (p : a = a') (p' : a' = a'') (q : b = b')
(q' : b' = b'') (z : P a b) :
transport11 P (p ⬝ p') (q ⬝ q') z = transport11 P p' q' (transport11 P p q z) :=
begin induction p', induction q', reflexivity end
definition transport11_compose (P : A' → B' → Type) (f : A → A') (g : B → B')
(p : a = a') (q : b = b') (z : P (f a) (g b)) :
transport11 (λa b, P (f a) (g b)) p q z = transport11 P (ap f p) (ap g q) z :=
by induction p; induction q; reflexivity
definition transport11_ap (P : A' → B' → Type) (f : A → A') (g : B → B')
(p : a = a') (q : b = b') (z : P (f a) (g b)) :
transport11 P (ap f p) (ap g q) z =
transport11 (λ(a : A) (b : B), P (f a) (g b)) p q z :=
(transport11_compose P f g p q z)⁻¹
definition fn_transport11_eq_transport11_fn (P : A → B → Type)
(Q : A → B → Type) (p : a = a') (q : b = b')
(f : Πa b, P a b → Q a b) (z : P a b) :
f a' b' (transport11 P p q z) = transport11 Q p q (f a b z) :=
by induction p; induction q; reflexivity
-- Transporting along higher-dimensional paths
definition transport2 [unfold 7] (P : A → Type) {x y : A} {p q : x = y} (r : p = q) (z : P x) :
p ▸ z = q ▸ z :=
ap (λp', p' ▸ z) r
notation p ` ▸2 `:65 x:64 := transport2 _ p _ x
-- An alternative definition.
definition tr2_eq_ap10 (Q : A → Type) {x y : A} {p q : x = y} (r : p = q) (z : Q x) :
transport2 Q r z = ap10 (ap (transport Q) r) z :=
by induction r; reflexivity
definition tr2_con {P : A → Type} {x y : A} {p1 p2 p3 : x = y}
(r1 : p1 = p2) (r2 : p2 = p3) (z : P x) :
transport2 P (r1 ⬝ r2) z = transport2 P r1 z ⬝ transport2 P r2 z :=
by induction r1; induction r2; reflexivity
definition tr2_inv (Q : A → Type) {x y : A} {p q : x = y} (r : p = q) (z : Q x) :
transport2 Q r⁻¹ z = (transport2 Q r z)⁻¹ :=
by induction r; reflexivity
definition transportD2 [unfold 7] {B C : A → Type} (D : Π(a:A), B a → C a → Type)
{x1 x2 : A} (p : x1 = x2) (y : B x1) (z : C x1) (w : D x1 y z) : D x2 (p ▸ y) (p ▸ z) :=
by induction p; exact w
notation p ` ▸D2 `:65 x:64 := transportD2 _ p _ _ x
definition ap_tr_con_tr2 (P : A → Type) {x y : A} {p q : x = y} {z w : P x} (r : p = q)
(s : z = w) :
ap (transport P p) s ⬝ transport2 P r w = transport2 P r z ⬝ ap (transport P q) s :=
by induction r; exact !idp_con⁻¹
/- Transporting in particular fibrations -/
/-
From the Coq HoTT library:
One frequently needs lemmas showing that transport in a certain dependent type is equal to some
more explicitly defined operation, defined according to the structure of that dependent type.
For most dependent types, we prove these lemmas in the appropriate file in the types/
subdirectory. Here we consider only the most basic cases.
-/
-- Transporting in a constant fibration.
definition tr_constant (p : x = y) (z : B) : transport (λx, B) p z = z :=
by induction p; reflexivity
definition tr2_constant {p q : x = y} (r : p = q) (z : B) :
tr_constant p z = transport2 (λu, B) r z ⬝ tr_constant q z :=
by induction r; exact !idp_con⁻¹
-- Transporting in a pulled back fibration.
definition tr_compose (P : B → Type) (f : A → B) (p : x = y) (z : P (f x)) :
transport (P ∘ f) p z = transport P (ap f p) z :=
by induction p; reflexivity
definition tr_ap (P : B → Type) (f : A → B) (p : x = y) (z : P (f x)) :
transport P (ap f p) z = transport (P ∘ f) p z :=
(tr_compose P f p z)⁻¹
definition ap_precompose (f : A → B) (g g' : B → C) (p : g = g') :
ap (λh, h ∘ f) p = transport (λh : B → C, g ∘ f = h ∘ f) p idp :=
by induction p; reflexivity
definition apd10_ap_precompose (f : A → B) (g g' : B → C) (p : g = g') :
apd10 (ap (λh : B → C, h ∘ f) p) = λa, apd10 p (f a) :=
by induction p; reflexivity
definition apd10_ap_precompose_dependent {C : B → Type}
(f : A → B) {g g' : Πb : B, C b} (p : g = g')
: apd10 (ap (λ(h : (Πb : B, C b))(a : A), h (f a)) p) = λa, apd10 p (f a) :=
by induction p; reflexivity
definition apd10_ap_postcompose (f : B → C) (g g' : A → B) (p : g = g') :
apd10 (ap (λh : A → B, f ∘ h) p) = λa, ap f (apd10 p a) :=
by induction p; reflexivity
-- A special case of [tr_compose] which seems to come up a lot.
definition tr_eq_cast_ap {P : A → Type} {x y} (p : x = y) (u : P x) : p ▸ u = cast (ap P p) u :=
by induction p; reflexivity
definition tr_eq_cast_ap_fn {P : A → Type} {x y} (p : x = y) : transport P p = cast (ap P p) :=
by induction p; reflexivity
/- The behavior of [ap] and [apdt] -/
-- In a constant fibration, [apdt] reduces to [ap], modulo [transport_const].
definition apdt_eq_tr_constant_con_ap (f : A → B) (p : x = y) :
apdt f p = tr_constant p (f x) ⬝ ap f p :=
by induction p; reflexivity
/- The 2-dimensional groupoid structure -/
-- Horizontal composition of 2-dimensional paths.
definition concat2 [unfold 9 10] {p p' : x = y} {q q' : y = z} (h : p = p') (h' : q = q')
: p ⬝ q = p' ⬝ q' :=
ap011 concat h h'
-- 2-dimensional path inversion
definition inverse2 [unfold 6] {p q : x = y} (h : p = q) : p⁻¹ = q⁻¹ :=
ap inverse h
infixl ` ◾ `:80 := concat2
postfix [parsing_only] `⁻²`:(max+10) := inverse2 --this notation is abusive, should we use it?
/- Whiskering -/
definition whisker_left [unfold 8] (p : x = y) {q r : y = z} (h : q = r) : p ⬝ q = p ⬝ r :=
idp ◾ h
definition whisker_right [unfold 8] {p q : x = y} (r : y = z) (h : p = q) : p ⬝ r = q ⬝ r :=
h ◾ idp
-- Unwhiskering, a.k.a. cancelling
definition cancel_left {x y z : A} (p : x = y) {q r : y = z} : (p ⬝ q = p ⬝ r) → (q = r) :=
λs, !inv_con_cancel_left⁻¹ ⬝ whisker_left p⁻¹ s ⬝ !inv_con_cancel_left
definition cancel_right {x y z : A} {p q : x = y} (r : y = z) : (p ⬝ r = q ⬝ r) → (p = q) :=
λs, !con_inv_cancel_right⁻¹ ⬝ whisker_right r⁻¹ s ⬝ !con_inv_cancel_right
-- Whiskering and identity paths.
definition whisker_right_idp {p q : x = y} (h : p = q) :
whisker_right idp h = h :=
by induction h; induction p; reflexivity
definition whisker_right_idp_left [unfold_full] (p : x = y) (q : y = z) :
whisker_right q idp = idp :> (p ⬝ q = p ⬝ q) :=
idp
definition whisker_left_idp_right [unfold_full] (p : x = y) (q : y = z) :
whisker_left p idp = idp :> (p ⬝ q = p ⬝ q) :=
idp
definition whisker_left_idp {p q : x = y} (h : p = q) :
(idp_con p)⁻¹ ⬝ whisker_left idp h ⬝ idp_con q = h :=
by induction h; induction p; reflexivity
definition whisker_left_idp2 {A : Type} {a : A} (p : idp = idp :> a = a) :
whisker_left idp p = p :=
begin
refine _ ⬝ whisker_left_idp p,
exact !idp_con⁻¹
end
definition con2_idp [unfold_full] {p q : x = y} (h : p = q) :
h ◾ idp = whisker_right idp h :> (p ⬝ idp = q ⬝ idp) :=
idp
definition idp_con2 [unfold_full] {p q : x = y} (h : p = q) :
idp ◾ h = whisker_left idp h :> (idp ⬝ p = idp ⬝ q) :=
idp
definition inv2_con2 {p p' : x = y} (h : p = p')
: h⁻² ◾ h = con.left_inv p ⬝ (con.left_inv p')⁻¹ :=
by induction h; induction p; reflexivity
-- The interchange law for concatenation.
definition con2_con_con2 {p p' p'' : x = y} {q q' q'' : y = z}
(a : p = p') (b : p' = p'') (c : q = q') (d : q' = q'') :
a ◾ c ⬝ b ◾ d = (a ⬝ b) ◾ (c ⬝ d) :=
by induction d; induction c; induction b;induction a; reflexivity
definition con2_eq_rl {A : Type} {x y z : A} {p p' : x = y} {q q' : y = z}
(a : p = p') (b : q = q') : a ◾ b = whisker_right q a ⬝ whisker_left p' b :=
by induction b; induction a; reflexivity
definition con2_eq_lf {A : Type} {x y z : A} {p p' : x = y} {q q' : y = z}
(a : p = p') (b : q = q') : a ◾ b = whisker_left p b ⬝ whisker_right q' a :=
by induction b; induction a; reflexivity
definition whisker_right_con_whisker_left {x y z : A} {p p' : x = y} {q q' : y = z}
(a : p = p') (b : q = q') :
(whisker_right q a) ⬝ (whisker_left p' b) = (whisker_left p b) ⬝ (whisker_right q' a) :=
by induction b; induction a; reflexivity
-- Structure corresponding to the coherence equations of a bicategory.
-- The "pentagonator": the 3-cell witnessing the associativity pentagon.
definition pentagon {v w x y z : A} (p : v = w) (q : w = x) (r : x = y) (s : y = z) :
whisker_left p (con.assoc' q r s)
⬝ con.assoc' p (q ⬝ r) s
⬝ whisker_right s (con.assoc' p q r)
= con.assoc' p q (r ⬝ s) ⬝ con.assoc' (p ⬝ q) r s :=
by induction s;induction r;induction q;induction p;reflexivity
-- The 3-cell witnessing the left unit triangle.
definition triangulator (p : x = y) (q : y = z) :
con.assoc' p idp q ⬝ whisker_right q (con_idp p) = whisker_left p (idp_con q) :=
by induction q; induction p; reflexivity
definition eckmann_hilton (p q : idp = idp :> a = a) : p ⬝ q = q ⬝ p :=
begin
refine (whisker_right_idp p ◾ whisker_left_idp2 q)⁻¹ ⬝ _,
refine !whisker_right_con_whisker_left ⬝ _,
refine !whisker_left_idp2 ◾ !whisker_right_idp
end
definition con_eq_con2 (p q : idp = idp :> a = a) : p ⬝ q = p ◾ q :=
begin
refine (whisker_right_idp p ◾ whisker_left_idp2 q)⁻¹ ⬝ _,
exact !con2_eq_rl⁻¹
end
definition inv_eq_inv2 (p : idp = idp :> a = a) : p⁻¹ = p⁻² :=
begin
apply eq.cancel_right p,
refine !con.left_inv ⬝ _,
refine _ ⬝ !con_eq_con2⁻¹,
exact !inv2_con2⁻¹,
end
-- The action of functions on 2-dimensional paths
definition ap02 [unfold 8] [reducible] (f : A → B) {x y : A} {p q : x = y} (r : p = q)
: ap f p = ap f q :=
ap (ap f) r
definition ap02_con (f : A → B) {x y : A} {p p' p'' : x = y} (r : p = p') (r' : p' = p'') :
ap02 f (r ⬝ r') = ap02 f r ⬝ ap02 f r' :=
by induction r; induction r'; reflexivity
definition ap02_con2 (f : A → B) {x y z : A} {p p' : x = y} {q q' :y = z} (r : p = p')
(s : q = q') :
ap02 f (r ◾ s) = ap_con f p q
⬝ (ap02 f r ◾ ap02 f s)
⬝ (ap_con f p' q')⁻¹ :=
by induction r; induction s; induction q; induction p; reflexivity
definition apdt02 [unfold 8] {p q : x = y} (f : Π x, P x) (r : p = q) :
apdt f p = transport2 P r (f x) ⬝ apdt f q :=
by induction r; exact !idp_con⁻¹
end eq
/-
an auxillary namespace for concatenation and inversion for homotopies. We put this is a separate
namespace because ⁻¹ʰ is also used as the inverse of a homomorphism
-/
open eq
namespace homotopy
infix ` ⬝h `:75 := homotopy.trans
postfix `⁻¹ʰ`:(max+1) := homotopy.symm
end homotopy
|
6cbeb501ec5bae7e0d5da8369ffe0c8dfaa04f7a | 69d4931b605e11ca61881fc4f66db50a0a875e39 | /src/data/equiv/basic.lean | 7e5d634856317b7625dac0d94adb3812b2abcfb7 | [
"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 | 100,370 | lean | /-
Copyright (c) 2015 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura, Mario Carneiro
-/
import data.set.function
import data.sigma.basic
/-!
# Equivalence between types
In this file we define two types:
* `equiv α β` a.k.a. `α ≃ β`: a bijective map `α → β` bundled with its inverse map; we use this (and
not equality!) to express that various `Type`s or `Sort`s are equivalent.
* `equiv.perm α`: the group of permutations `α ≃ α`. More lemmas about `equiv.perm` can be found in
`group_theory/perm`.
Then we define
* canonical isomorphisms between various types: e.g.,
- `equiv.refl α` is the identity map interpreted as `α ≃ α`;
- `equiv.sum_equiv_sigma_bool` is the canonical equivalence between the sum of two types `α ⊕ β`
and the sigma-type `Σ b : bool, cond b α β`;
- `equiv.prod_sum_distrib : α × (β ⊕ γ) ≃ (α × β) ⊕ (α × γ)` shows that type product and type sum
satisfy the distributive law up to a canonical equivalence;
* operations on equivalences: e.g.,
- `equiv.symm e : β ≃ α` is the inverse of `e : α ≃ β`;
- `equiv.trans e₁ e₂ : α ≃ γ` is the composition of `e₁ : α ≃ β` and `e₂ : β ≃ γ` (note the order
of the arguments!);
- `equiv.prod_congr ea eb : α₁ × β₁ ≃ α₂ × β₂`: combine two equivalences `ea : α₁ ≃ α₂` and
`eb : β₁ ≃ β₂` using `prod.map`.
* definitions that transfer some instances along an equivalence. By convention, we transfer
instances from right to left.
- `equiv.inhabited` takes `e : α ≃ β` and `[inhabited β]` and returns `inhabited α`;
- `equiv.unique` takes `e : α ≃ β` and `[unique β]` and returns `unique α`;
- `equiv.decidable_eq` takes `e : α ≃ β` and `[decidable_eq β]` and returns `decidable_eq α`.
More definitions of this kind can be found in other files. E.g., `data/equiv/transfer_instance`
does it for many algebraic type classes like `group`, `module`, etc.
## Tags
equivalence, congruence, bijective map
-/
open function
universes u v w z
variables {α : Sort u} {β : Sort v} {γ : Sort w}
/-- `α ≃ β` is the type of functions from `α → β` with a two-sided inverse. -/
@[nolint has_inhabited_instance]
structure equiv (α : Sort*) (β : Sort*) :=
(to_fun : α → β)
(inv_fun : β → α)
(left_inv : left_inverse inv_fun to_fun)
(right_inv : right_inverse inv_fun to_fun)
infix ` ≃ `:25 := equiv
/-- Convert an involutive function `f` to an equivalence with `to_fun = inv_fun = f`. -/
def function.involutive.to_equiv (f : α → α) (h : involutive f) : α ≃ α :=
⟨f, f, h.left_inverse, h.right_inverse⟩
namespace equiv
/-- `perm α` is the type of bijections from `α` to itself. -/
@[reducible] def perm (α : Sort*) := equiv α α
instance : has_coe_to_fun (α ≃ β) :=
⟨_, to_fun⟩
@[simp] theorem coe_fn_mk (f : α → β) (g l r) : (equiv.mk f g l r : α → β) = f :=
rfl
/-- The map `coe_fn : (r ≃ s) → (r → s)` is injective. -/
theorem coe_fn_injective : function.injective (λ (e : α ≃ β) (x : α), e x)
| ⟨f₁, g₁, l₁, r₁⟩ ⟨f₂, g₂, l₂, r₂⟩ h :=
have f₁ = f₂, from h,
have g₁ = g₂, from l₁.eq_right_inverse (this.symm ▸ r₂),
by simp *
@[simp, norm_cast] protected lemma coe_inj {e₁ e₂ : α ≃ β} : ⇑e₁ = e₂ ↔ e₁ = e₂ :=
coe_fn_injective.eq_iff
@[ext] lemma ext {f g : equiv α β} (H : ∀ x, f x = g x) : f = g :=
coe_fn_injective (funext H)
protected lemma congr_arg {f : equiv α β} : Π {x x' : α}, x = x' → f x = f x'
| _ _ rfl := rfl
protected lemma congr_fun {f g : equiv α β} (h : f = g) (x : α) : f x = g x := h ▸ rfl
lemma ext_iff {f g : equiv α β} : f = g ↔ ∀ x, f x = g x :=
⟨λ h x, h ▸ rfl, ext⟩
@[ext] lemma perm.ext {σ τ : equiv.perm α} (H : ∀ x, σ x = τ x) : σ = τ :=
equiv.ext H
protected lemma perm.congr_arg {f : equiv.perm α} {x x' : α} : x = x' → f x = f x' :=
equiv.congr_arg
protected lemma perm.congr_fun {f g : equiv.perm α} (h : f = g) (x : α) : f x = g x :=
equiv.congr_fun h x
lemma perm.ext_iff {σ τ : equiv.perm α} : σ = τ ↔ ∀ x, σ x = τ x :=
ext_iff
/-- Any type is equivalent to itself. -/
@[refl] protected def refl (α : Sort*) : α ≃ α := ⟨id, id, λ x, rfl, λ x, rfl⟩
instance inhabited' : inhabited (α ≃ α) := ⟨equiv.refl α⟩
/-- Inverse of an equivalence `e : α ≃ β`. -/
@[symm] protected def symm (e : α ≃ β) : β ≃ α := ⟨e.inv_fun, e.to_fun, e.right_inv, e.left_inv⟩
/-- See Note [custom simps projection] -/
def simps.symm_apply (e : α ≃ β) : β → α := e.symm
initialize_simps_projections equiv (to_fun → apply, inv_fun → symm_apply)
-- Generate the `simps` projections for previously defined equivs.
attribute [simps] function.involutive.to_equiv
/-- Composition of equivalences `e₁ : α ≃ β` and `e₂ : β ≃ γ`. -/
@[trans] protected def trans (e₁ : α ≃ β) (e₂ : β ≃ γ) : α ≃ γ :=
⟨e₂ ∘ e₁, e₁.symm ∘ e₂.symm,
e₂.left_inv.comp e₁.left_inv, e₂.right_inv.comp e₁.right_inv⟩
@[simp]
lemma to_fun_as_coe (e : α ≃ β) : e.to_fun = e := rfl
@[simp]
lemma inv_fun_as_coe (e : α ≃ β) : e.inv_fun = e.symm := rfl
protected theorem injective (e : α ≃ β) : injective e :=
e.left_inv.injective
protected theorem surjective (e : α ≃ β) : surjective e :=
e.right_inv.surjective
protected theorem bijective (f : α ≃ β) : bijective f :=
⟨f.injective, f.surjective⟩
@[simp] lemma range_eq_univ {α : Type*} {β : Type*} (e : α ≃ β) : set.range e = set.univ :=
set.eq_univ_of_forall e.surjective
protected theorem subsingleton (e : α ≃ β) [subsingleton β] : subsingleton α :=
e.injective.subsingleton
protected theorem subsingleton.symm (e : α ≃ β) [subsingleton α] : subsingleton β :=
e.symm.injective.subsingleton
lemma subsingleton_congr (e : α ≃ β) : subsingleton α ↔ subsingleton β :=
⟨λ h, by exactI e.symm.subsingleton, λ h, by exactI e.subsingleton⟩
instance equiv_subsingleton_cod [subsingleton β] :
subsingleton (α ≃ β) :=
⟨λ f g, equiv.ext $ λ x, subsingleton.elim _ _⟩
instance equiv_subsingleton_dom [subsingleton α] :
subsingleton (α ≃ β) :=
⟨λ f g, equiv.ext $ λ x, @subsingleton.elim _ (equiv.subsingleton.symm f) _ _⟩
instance perm_subsingleton [subsingleton α] : subsingleton (perm α) :=
equiv.equiv_subsingleton_cod
lemma perm.subsingleton_eq_refl [subsingleton α] (e : perm α) :
e = equiv.refl α := subsingleton.elim _ _
/-- Transfer `decidable_eq` across an equivalence. -/
protected def decidable_eq (e : α ≃ β) [decidable_eq β] : decidable_eq α :=
e.injective.decidable_eq
lemma nonempty_iff_nonempty (e : α ≃ β) : nonempty α ↔ nonempty β :=
nonempty.congr e e.symm
/-- If `α ≃ β` and `β` is inhabited, then so is `α`. -/
protected def inhabited [inhabited β] (e : α ≃ β) : inhabited α :=
⟨e.symm (default _)⟩
/-- If `α ≃ β` and `β` is a singleton type, then so is `α`. -/
protected def unique [unique β] (e : α ≃ β) : unique α :=
e.symm.surjective.unique
/-- Equivalence between equal types. -/
protected def cast {α β : Sort*} (h : α = β) : α ≃ β :=
⟨cast h, cast h.symm, λ x, by { cases h, refl }, λ x, by { cases h, refl }⟩
@[simp] theorem coe_fn_symm_mk (f : α → β) (g l r) : ((equiv.mk f g l r).symm : β → α) = g :=
rfl
@[simp] theorem coe_refl : ⇑(equiv.refl α) = id := rfl
@[simp] theorem perm.coe_subsingleton {α : Type*} [subsingleton α] (e : perm α) : ⇑(e) = id :=
by rw [perm.subsingleton_eq_refl e, coe_refl]
theorem refl_apply (x : α) : equiv.refl α x = x := rfl
@[simp] theorem coe_trans (f : α ≃ β) (g : β ≃ γ) : ⇑(f.trans g) = g ∘ f := rfl
theorem trans_apply (f : α ≃ β) (g : β ≃ γ) (a : α) : (f.trans g) a = g (f a) := rfl
@[simp] theorem apply_symm_apply (e : α ≃ β) (x : β) : e (e.symm x) = x :=
e.right_inv x
@[simp] theorem symm_apply_apply (e : α ≃ β) (x : α) : e.symm (e x) = x :=
e.left_inv x
@[simp] theorem symm_comp_self (e : α ≃ β) : e.symm ∘ e = id := funext e.symm_apply_apply
@[simp] theorem self_comp_symm (e : α ≃ β) : e ∘ e.symm = id := funext e.apply_symm_apply
@[simp] lemma symm_trans_apply (f : α ≃ β) (g : β ≃ γ) (a : γ) :
(f.trans g).symm a = f.symm (g.symm a) := rfl
-- The `simp` attribute is needed to make this a `dsimp` lemma.
-- `simp` will always rewrite with `equiv.symm_symm` before this has a chance to fire.
@[simp, nolint simp_nf] theorem symm_symm_apply (f : α ≃ β) (b : α) : f.symm.symm b = f b := rfl
@[simp] theorem apply_eq_iff_eq (f : α ≃ β) {x y : α} : f x = f y ↔ x = y :=
f.injective.eq_iff
theorem apply_eq_iff_eq_symm_apply {α β : Sort*} (f : α ≃ β) {x : α} {y : β} :
f x = y ↔ x = f.symm y :=
begin
conv_lhs { rw ←apply_symm_apply f y, },
rw apply_eq_iff_eq,
end
@[simp] theorem cast_apply {α β} (h : α = β) (x : α) : equiv.cast h x = cast h x := rfl
@[simp] theorem cast_symm {α β} (h : α = β) : (equiv.cast h).symm = equiv.cast h.symm := rfl
@[simp] theorem cast_refl {α} (h : α = α := rfl) : equiv.cast h = equiv.refl α := rfl
@[simp] theorem cast_trans {α β γ} (h : α = β) (h2 : β = γ) :
(equiv.cast h).trans (equiv.cast h2) = equiv.cast (h.trans h2) :=
ext $ λ x, by { substs h h2, refl }
lemma cast_eq_iff_heq {α β} (h : α = β) {a : α} {b : β} : equiv.cast h a = b ↔ a == b :=
by { subst h, simp }
lemma symm_apply_eq {α β} (e : α ≃ β) {x y} : e.symm x = y ↔ x = e y :=
⟨λ H, by simp [H.symm], λ H, by simp [H]⟩
lemma eq_symm_apply {α β} (e : α ≃ β) {x y} : y = e.symm x ↔ e y = x :=
(eq_comm.trans e.symm_apply_eq).trans eq_comm
@[simp] theorem symm_symm (e : α ≃ β) : e.symm.symm = e := by { cases e, refl }
@[simp] theorem trans_refl (e : α ≃ β) : e.trans (equiv.refl β) = e := by { cases e, refl }
@[simp] theorem refl_symm : (equiv.refl α).symm = equiv.refl α := rfl
@[simp] theorem refl_trans (e : α ≃ β) : (equiv.refl α).trans e = e := by { cases e, refl }
@[simp] theorem symm_trans (e : α ≃ β) : e.symm.trans e = equiv.refl β := ext (by simp)
@[simp] theorem trans_symm (e : α ≃ β) : e.trans e.symm = equiv.refl α := ext (by simp)
lemma trans_assoc {δ} (ab : α ≃ β) (bc : β ≃ γ) (cd : γ ≃ δ) :
(ab.trans bc).trans cd = ab.trans (bc.trans cd) :=
equiv.ext $ assume a, rfl
theorem left_inverse_symm (f : equiv α β) : left_inverse f.symm f := f.left_inv
theorem right_inverse_symm (f : equiv α β) : function.right_inverse f.symm f := f.right_inv
@[simp] lemma injective_comp (e : α ≃ β) (f : β → γ) : injective (f ∘ e) ↔ injective f :=
injective.of_comp_iff' f e.bijective
@[simp] lemma comp_injective (f : α → β) (e : β ≃ γ) : injective (e ∘ f) ↔ injective f :=
e.injective.of_comp_iff f
@[simp] lemma surjective_comp (e : α ≃ β) (f : β → γ) : surjective (f ∘ e) ↔ surjective f :=
e.surjective.of_comp_iff f
@[simp] lemma comp_surjective (f : α → β) (e : β ≃ γ) : surjective (e ∘ f) ↔ surjective f :=
surjective.of_comp_iff' e.bijective f
@[simp] lemma bijective_comp (e : α ≃ β) (f : β → γ) : bijective (f ∘ e) ↔ bijective f :=
e.bijective.of_comp_iff f
@[simp] lemma comp_bijective (f : α → β) (e : β ≃ γ) : bijective (e ∘ f) ↔ bijective f :=
bijective.of_comp_iff' e.bijective f
/-- If `α` is equivalent to `β` and `γ` is equivalent to `δ`, then the type of equivalences `α ≃ γ`
is equivalent to the type of equivalences `β ≃ δ`. -/
def equiv_congr {δ} (ab : α ≃ β) (cd : γ ≃ δ) : (α ≃ γ) ≃ (β ≃ δ) :=
⟨ λac, (ab.symm.trans ac).trans cd, λbd, ab.trans $ bd.trans $ cd.symm,
assume ac, by { ext x, simp }, assume ac, by { ext x, simp } ⟩
@[simp] lemma equiv_congr_refl {α β} :
(equiv.refl α).equiv_congr (equiv.refl β) = equiv.refl (α ≃ β) := by { ext, refl }
@[simp] lemma equiv_congr_symm {δ} (ab : α ≃ β) (cd : γ ≃ δ) :
(ab.equiv_congr cd).symm = ab.symm.equiv_congr cd.symm := by { ext, refl }
@[simp] lemma equiv_congr_trans {δ ε ζ} (ab : α ≃ β) (de : δ ≃ ε) (bc : β ≃ γ) (ef : ε ≃ ζ) :
(ab.equiv_congr de).trans (bc.equiv_congr ef) = (ab.trans bc).equiv_congr (de.trans ef) :=
by { ext, refl }
@[simp] lemma equiv_congr_refl_left {α β γ} (bg : β ≃ γ) (e : α ≃ β) :
(equiv.refl α).equiv_congr bg e = e.trans bg := rfl
@[simp] lemma equiv_congr_refl_right {α β} (ab e : α ≃ β) :
ab.equiv_congr (equiv.refl β) e = ab.symm.trans e := rfl
@[simp] lemma equiv_congr_apply_apply {δ} (ab : α ≃ β) (cd : γ ≃ δ) (e : α ≃ γ) (x) :
ab.equiv_congr cd e x = cd (e (ab.symm x)) := rfl
section perm_congr
variables {α' β' : Type*} (e : α' ≃ β')
/-- If `α` is equivalent to `β`, then `perm α` is equivalent to `perm β`. -/
def perm_congr : perm α' ≃ perm β' :=
equiv_congr e e
lemma perm_congr_def (p : equiv.perm α') :
e.perm_congr p = (e.symm.trans p).trans e := rfl
@[simp] lemma perm_congr_refl :
e.perm_congr (equiv.refl _) = equiv.refl _ :=
by simp [perm_congr_def]
@[simp] lemma perm_congr_symm :
e.perm_congr.symm = e.symm.perm_congr := rfl
@[simp] lemma perm_congr_apply (p : equiv.perm α') (x) :
e.perm_congr p x = e (p (e.symm x)) := rfl
lemma perm_congr_symm_apply (p : equiv.perm β') (x) :
e.perm_congr.symm p x = e.symm (p (e x)) := rfl
lemma perm_congr_trans (p p' : equiv.perm α') :
(e.perm_congr p).trans (e.perm_congr p') = e.perm_congr (p.trans p') :=
by { ext, simp }
end perm_congr
protected lemma image_eq_preimage {α β} (e : α ≃ β) (s : set α) : e '' s = e.symm ⁻¹' s :=
set.ext $ assume x, set.mem_image_iff_of_inverse e.left_inv e.right_inv
protected lemma subset_image {α β} (e : α ≃ β) (s : set α) (t : set β) :
t ⊆ e '' s ↔ e.symm '' t ⊆ s :=
by rw [set.image_subset_iff, e.image_eq_preimage]
@[simp] lemma symm_image_image {α β} (e : α ≃ β) (s : set α) : e.symm '' (e '' s) = s :=
by { rw [← set.image_comp], simp }
lemma eq_image_iff_symm_image_eq {α β} (e : α ≃ β) (s : set α) (t : set β) :
t = e '' s ↔ e.symm '' t = s :=
begin
refine (injective.eq_iff' _ _).symm,
{ rw set.image_injective,
exact (equiv.symm e).injective },
{ exact equiv.symm_image_image _ _ }
end
@[simp] lemma image_symm_image {α β} (e : α ≃ β) (s : set β) : e '' (e.symm '' s) = s :=
e.symm.symm_image_image s
@[simp] lemma image_preimage {α β} (e : α ≃ β) (s : set β) : e '' (e ⁻¹' s) = s :=
e.surjective.image_preimage s
@[simp] lemma preimage_image {α β} (e : α ≃ β) (s : set α) : e ⁻¹' (e '' s) = s :=
set.preimage_image_eq s e.injective
protected lemma image_compl {α β} (f : equiv α β) (s : set α) :
f '' sᶜ = (f '' s)ᶜ :=
set.image_compl_eq f.bijective
@[simp] lemma symm_preimage_preimage {α β} (e : α ≃ β) (s : set β) :
e.symm ⁻¹' (e ⁻¹' s) = s :=
by ext; simp
@[simp] lemma preimage_symm_preimage {α β} (e : α ≃ β) (s : set α) :
e ⁻¹' (e.symm ⁻¹' s) = s :=
by ext; simp
@[simp] lemma preimage_subset {α β} (e : α ≃ β) (s t : set β) : e ⁻¹' s ⊆ e ⁻¹' t ↔ s ⊆ t :=
e.surjective.preimage_subset_preimage_iff
@[simp] lemma image_subset {α β} (e : α ≃ β) (s t : set α) : e '' s ⊆ e '' t ↔ s ⊆ t :=
set.image_subset_image_iff e.injective
@[simp] lemma image_eq_iff_eq {α β} (e : α ≃ β) (s t : set α) : e '' s = e '' t ↔ s = t :=
set.image_eq_image e.injective
lemma preimage_eq_iff_eq_image {α β} (e : α ≃ β) (s t) : e ⁻¹' s = t ↔ s = e '' t :=
set.preimage_eq_iff_eq_image e.bijective
lemma eq_preimage_iff_image_eq {α β} (e : α ≃ β) (s t) : s = e ⁻¹' t ↔ e '' s = t :=
set.eq_preimage_iff_image_eq e.bijective
/-- If `α` is an empty type, then it is equivalent to the `empty` type. -/
def equiv_empty (α : Sort u) [is_empty α] : α ≃ empty :=
⟨is_empty_elim, λ e, e.rec _, is_empty_elim, λ e, e.rec _⟩
/-- `α` is equivalent to an empty type iff `α` is empty. -/
def equiv_empty_equiv (α : Sort u) : (α ≃ empty) ≃ is_empty α :=
⟨λ e, function.is_empty e, @equiv_empty α, λ e, ext $ λ x, (e x).elim, λ p, rfl⟩
/-- `false` is equivalent to `empty`. -/
def false_equiv_empty : false ≃ empty :=
equiv_empty _
/-- If `α` is an empty type, then it is equivalent to the `pempty` type in any universe. -/
def {u' v'} equiv_pempty (α : Sort v') [is_empty α] : α ≃ pempty.{u'} :=
⟨is_empty_elim, λ e, e.rec _, is_empty_elim, λ e, e.rec _⟩
/-- `false` is equivalent to `pempty`. -/
def false_equiv_pempty : false ≃ pempty :=
equiv_pempty _
/-- `empty` is equivalent to `pempty`. -/
def empty_equiv_pempty : empty ≃ pempty :=
equiv_pempty _
/-- `pempty` types from any two universes are equivalent. -/
def pempty_equiv_pempty : pempty.{v} ≃ pempty.{w} :=
equiv_pempty _
/-- The `Sort` of proofs of a true proposition is equivalent to `punit`. -/
def prop_equiv_punit {p : Prop} (h : p) : p ≃ punit :=
⟨λ x, (), λ x, h, λ _, rfl, λ ⟨⟩, rfl⟩
/-- `true` is equivalent to `punit`. -/
def true_equiv_punit : true ≃ punit := prop_equiv_punit trivial
/-- `ulift α` is equivalent to `α`. -/
@[simps apply symm_apply {fully_applied := ff}]
protected def ulift {α : Type v} : ulift.{u} α ≃ α :=
⟨ulift.down, ulift.up, ulift.up_down, λ a, rfl⟩
/-- `plift α` is equivalent to `α`. -/
@[simps apply symm_apply {fully_applied := ff}]
protected def plift : plift α ≃ α :=
⟨plift.down, plift.up, plift.up_down, plift.down_up⟩
/-- equivalence of propositions is the same as iff -/
def of_iff {P Q : Prop} (h : P ↔ Q) : P ≃ Q :=
{ to_fun := h.mp,
inv_fun := h.mpr,
left_inv := λ x, rfl,
right_inv := λ y, rfl }
/-- If `α₁` is equivalent to `α₂` and `β₁` is equivalent to `β₂`, then the type of maps `α₁ → β₁`
is equivalent to the type of maps `α₂ → β₂`. -/
@[congr, simps apply] def arrow_congr {α₁ β₁ α₂ β₂ : Sort*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) :
(α₁ → β₁) ≃ (α₂ → β₂) :=
{ to_fun := λ f, e₂ ∘ f ∘ e₁.symm,
inv_fun := λ f, e₂.symm ∘ f ∘ e₁,
left_inv := λ f, funext $ λ x, by simp,
right_inv := λ f, funext $ λ x, by simp }
lemma arrow_congr_comp {α₁ β₁ γ₁ α₂ β₂ γ₂ : Sort*}
(ea : α₁ ≃ α₂) (eb : β₁ ≃ β₂) (ec : γ₁ ≃ γ₂) (f : α₁ → β₁) (g : β₁ → γ₁) :
arrow_congr ea ec (g ∘ f) = (arrow_congr eb ec g) ∘ (arrow_congr ea eb f) :=
by { ext, simp only [comp, arrow_congr_apply, eb.symm_apply_apply] }
@[simp] lemma arrow_congr_refl {α β : Sort*} :
arrow_congr (equiv.refl α) (equiv.refl β) = equiv.refl (α → β) := rfl
@[simp] lemma arrow_congr_trans {α₁ β₁ α₂ β₂ α₃ β₃ : Sort*}
(e₁ : α₁ ≃ α₂) (e₁' : β₁ ≃ β₂) (e₂ : α₂ ≃ α₃) (e₂' : β₂ ≃ β₃) :
arrow_congr (e₁.trans e₂) (e₁'.trans e₂') = (arrow_congr e₁ e₁').trans (arrow_congr e₂ e₂') :=
rfl
@[simp] lemma arrow_congr_symm {α₁ β₁ α₂ β₂ : Sort*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) :
(arrow_congr e₁ e₂).symm = arrow_congr e₁.symm e₂.symm :=
rfl
/--
A version of `equiv.arrow_congr` in `Type`, rather than `Sort`.
The `equiv_rw` tactic is not able to use the default `Sort` level `equiv.arrow_congr`,
because Lean's universe rules will not unify `?l_1` with `imax (1 ?m_1)`.
-/
@[congr, simps apply]
def arrow_congr' {α₁ β₁ α₂ β₂ : Type*} (hα : α₁ ≃ α₂) (hβ : β₁ ≃ β₂) : (α₁ → β₁) ≃ (α₂ → β₂) :=
equiv.arrow_congr hα hβ
@[simp] lemma arrow_congr'_refl {α β : Type*} :
arrow_congr' (equiv.refl α) (equiv.refl β) = equiv.refl (α → β) := rfl
@[simp] lemma arrow_congr'_trans {α₁ β₁ α₂ β₂ α₃ β₃ : Type*}
(e₁ : α₁ ≃ α₂) (e₁' : β₁ ≃ β₂) (e₂ : α₂ ≃ α₃) (e₂' : β₂ ≃ β₃) :
arrow_congr' (e₁.trans e₂) (e₁'.trans e₂') = (arrow_congr' e₁ e₁').trans (arrow_congr' e₂ e₂') :=
rfl
@[simp] lemma arrow_congr'_symm {α₁ β₁ α₂ β₂ : Type*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) :
(arrow_congr' e₁ e₂).symm = arrow_congr' e₁.symm e₂.symm :=
rfl
/-- Conjugate a map `f : α → α` by an equivalence `α ≃ β`. -/
@[simps apply]
def conj (e : α ≃ β) : (α → α) ≃ (β → β) := arrow_congr e e
@[simp] lemma conj_refl : conj (equiv.refl α) = equiv.refl (α → α) := rfl
@[simp] lemma conj_symm (e : α ≃ β) : e.conj.symm = e.symm.conj := rfl
@[simp] lemma conj_trans (e₁ : α ≃ β) (e₂ : β ≃ γ) :
(e₁.trans e₂).conj = e₁.conj.trans e₂.conj :=
rfl
-- This should not be a simp lemma as long as `(∘)` is reducible:
-- when `(∘)` is reducible, Lean can unify `f₁ ∘ f₂` with any `g` using
-- `f₁ := g` and `f₂ := λ x, x`. This causes nontermination.
lemma conj_comp (e : α ≃ β) (f₁ f₂ : α → α) :
e.conj (f₁ ∘ f₂) = (e.conj f₁) ∘ (e.conj f₂) :=
by apply arrow_congr_comp
section binary_op
variables {α₁ β₁ : Type*} (e : α₁ ≃ β₁) (f : α₁ → α₁ → α₁)
lemma semiconj_conj (f : α₁ → α₁) : semiconj e f (e.conj f) := λ x, by simp
lemma semiconj₂_conj : semiconj₂ e f (e.arrow_congr e.conj f) := λ x y, by simp
instance [is_associative α₁ f] :
is_associative β₁ (e.arrow_congr (e.arrow_congr e) f) :=
(e.semiconj₂_conj f).is_associative_right e.surjective
instance [is_idempotent α₁ f] :
is_idempotent β₁ (e.arrow_congr (e.arrow_congr e) f) :=
(e.semiconj₂_conj f).is_idempotent_right e.surjective
instance [is_left_cancel α₁ f] :
is_left_cancel β₁ (e.arrow_congr (e.arrow_congr e) f) :=
⟨e.surjective.forall₃.2 $ λ x y z, by simpa using @is_left_cancel.left_cancel _ f _ x y z⟩
instance [is_right_cancel α₁ f] :
is_right_cancel β₁ (e.arrow_congr (e.arrow_congr e) f) :=
⟨e.surjective.forall₃.2 $ λ x y z, by simpa using @is_right_cancel.right_cancel _ f _ x y z⟩
end binary_op
/-- `punit` sorts in any two universes are equivalent. -/
def punit_equiv_punit : punit.{v} ≃ punit.{w} :=
⟨λ _, punit.star, λ _, punit.star, λ u, by { cases u, refl }, λ u, by { cases u, reflexivity }⟩
section
/-- The sort of maps to `punit.{v}` is equivalent to `punit.{w}`. -/
def arrow_punit_equiv_punit (α : Sort*) : (α → punit.{v}) ≃ punit.{w} :=
⟨λ f, punit.star, λ u f, punit.star,
λ f, by { funext x, cases f x, refl }, λ u, by { cases u, reflexivity }⟩
/-- If `α` has a unique term, then the type of function `α → β` is equivalent to `β`. -/
@[simps] def fun_unique (α β) [unique α] : (α → β) ≃ β :=
{ to_fun := λ f, f (default α),
inv_fun := λ b a, b,
left_inv := λ f, funext $ λ a, congr_arg f $ subsingleton.elim _ _,
right_inv := λ b, rfl }
/-- The sort of maps from `punit` is equivalent to the codomain. -/
def punit_arrow_equiv (α : Sort*) : (punit.{u} → α) ≃ α :=
fun_unique _ _
/-- The sort of maps from `true` is equivalent to the codomain. -/
def true_arrow_equiv (α : Sort*) : (true → α) ≃ α :=
fun_unique _ _
/-- The sort of maps from a type that `is_empty` is equivalent to `punit`. -/
def arrow_punit_of_is_empty (α β : Sort*) [is_empty α] : (α → β) ≃ punit.{u} :=
⟨λ f, punit.star, λ u, is_empty_elim, λ f, funext is_empty_elim, λ u, by { cases u, refl }⟩
/-- The sort of maps from `empty` is equivalent to `punit`. -/
def empty_arrow_equiv_punit (α : Sort*) : (empty → α) ≃ punit.{u} :=
arrow_punit_of_is_empty _ _
/-- The sort of maps from `pempty` is equivalent to `punit`. -/
def pempty_arrow_equiv_punit (α : Sort*) : (pempty → α) ≃ punit.{u} :=
arrow_punit_of_is_empty _ _
/-- The sort of maps from `false` is equivalent to `punit`. -/
def false_arrow_equiv_punit (α : Sort*) : (false → α) ≃ punit.{u} :=
arrow_punit_of_is_empty _ _
end
/-- Product of two equivalences. If `α₁ ≃ α₂` and `β₁ ≃ β₂`, then `α₁ × β₁ ≃ α₂ × β₂`. -/
@[congr, simps apply]
def prod_congr {α₁ β₁ α₂ β₂ : Type*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) : α₁ × β₁ ≃ α₂ × β₂ :=
⟨prod.map e₁ e₂, prod.map e₁.symm e₂.symm, λ ⟨a, b⟩, by simp, λ ⟨a, b⟩, by simp⟩
@[simp] theorem prod_congr_symm {α₁ β₁ α₂ β₂ : Type*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) :
(prod_congr e₁ e₂).symm = prod_congr e₁.symm e₂.symm :=
rfl
/-- Type product is commutative up to an equivalence: `α × β ≃ β × α`. -/
@[simps apply] def prod_comm (α β : Type*) : α × β ≃ β × α :=
⟨prod.swap, prod.swap, λ⟨a, b⟩, rfl, λ⟨a, b⟩, rfl⟩
@[simp] lemma prod_comm_symm (α β) : (prod_comm α β).symm = prod_comm β α := rfl
/-- Type product is associative up to an equivalence. -/
@[simps] def prod_assoc (α β γ : Sort*) : (α × β) × γ ≃ α × (β × γ) :=
⟨λ p, (p.1.1, p.1.2, p.2), λp, ((p.1, p.2.1), p.2.2), λ ⟨⟨a, b⟩, c⟩, rfl, λ ⟨a, ⟨b, c⟩⟩, rfl⟩
lemma prod_assoc_preimage {α β γ} {s : set α} {t : set β} {u : set γ} :
equiv.prod_assoc α β γ ⁻¹' s.prod (t.prod u) = (s.prod t).prod u :=
by { ext, simp [and_assoc] }
/-- Functions on `α × β` are equivalent to functions `α → β → γ`. -/
@[simps {fully_applied := ff}] def curry (α β γ : Type*) :
(α × β → γ) ≃ (α → β → γ) :=
{ to_fun := curry,
inv_fun := uncurry,
left_inv := uncurry_curry,
right_inv := curry_uncurry }
section
/-- `punit` is a right identity for type product up to an equivalence. -/
@[simps] def prod_punit (α : Type*) : α × punit.{u+1} ≃ α :=
⟨λ p, p.1, λ a, (a, punit.star), λ ⟨_, punit.star⟩, rfl, λ a, rfl⟩
/-- `punit` is a left identity for type product up to an equivalence. -/
@[simps] def punit_prod (α : Type*) : punit.{u+1} × α ≃ α :=
calc punit × α ≃ α × punit : prod_comm _ _
... ≃ α : prod_punit _
/-- `empty` type is a right absorbing element for type product up to an equivalence. -/
def prod_empty (α : Type*) : α × empty ≃ empty :=
equiv_empty _
/-- `empty` type is a left absorbing element for type product up to an equivalence. -/
def empty_prod (α : Type*) : empty × α ≃ empty :=
equiv_empty _
/-- `pempty` type is a right absorbing element for type product up to an equivalence. -/
def prod_pempty (α : Type*) : α × pempty ≃ pempty :=
equiv_pempty _
/-- `pempty` type is a left absorbing element for type product up to an equivalence. -/
def pempty_prod (α : Type*) : pempty × α ≃ pempty :=
equiv_pempty _
end
section
open sum
/-- `psum` is equivalent to `sum`. -/
def psum_equiv_sum (α β : Type*) : psum α β ≃ α ⊕ β :=
⟨λ s, psum.cases_on s inl inr,
λ s, sum.cases_on s psum.inl psum.inr,
λ s, by cases s; refl,
λ s, by cases s; refl⟩
/-- If `α ≃ α'` and `β ≃ β'`, then `α ⊕ β ≃ α' ⊕ β'`. -/
@[simps apply]
def sum_congr {α₁ β₁ α₂ β₂ : Type*} (ea : α₁ ≃ α₂) (eb : β₁ ≃ β₂) : α₁ ⊕ β₁ ≃ α₂ ⊕ β₂ :=
⟨sum.map ea eb, sum.map ea.symm eb.symm, λ x, by simp, λ x, by simp⟩
@[simp] lemma sum_congr_trans {α₁ α₂ β₁ β₂ γ₁ γ₂ : Sort*}
(e : α₁ ≃ β₁) (f : α₂ ≃ β₂) (g : β₁ ≃ γ₁) (h : β₂ ≃ γ₂) :
(equiv.sum_congr e f).trans (equiv.sum_congr g h) = (equiv.sum_congr (e.trans g) (f.trans h)) :=
by { ext i, cases i; refl }
@[simp] lemma sum_congr_symm {α β γ δ : Sort*} (e : α ≃ β) (f : γ ≃ δ) :
(equiv.sum_congr e f).symm = (equiv.sum_congr (e.symm) (f.symm)) :=
rfl
@[simp] lemma sum_congr_refl {α β : Sort*} :
equiv.sum_congr (equiv.refl α) (equiv.refl β) = equiv.refl (α ⊕ β) :=
by { ext i, cases i; refl }
namespace perm
/-- Combine a permutation of `α` and of `β` into a permutation of `α ⊕ β`. -/
@[reducible]
def sum_congr {α β : Type*} (ea : equiv.perm α) (eb : equiv.perm β) : equiv.perm (α ⊕ β) :=
equiv.sum_congr ea eb
@[simp] lemma sum_congr_apply {α β : Type*} (ea : equiv.perm α) (eb : equiv.perm β) (x : α ⊕ β) :
sum_congr ea eb x = sum.map ⇑ea ⇑eb x := equiv.sum_congr_apply ea eb x
@[simp] lemma sum_congr_trans {α β : Sort*}
(e : equiv.perm α) (f : equiv.perm β) (g : equiv.perm α) (h : equiv.perm β) :
(sum_congr e f).trans (sum_congr g h) = sum_congr (e.trans g) (f.trans h) :=
equiv.sum_congr_trans e f g h
@[simp] lemma sum_congr_symm {α β : Sort*} (e : equiv.perm α) (f : equiv.perm β) :
(sum_congr e f).symm = sum_congr (e.symm) (f.symm) :=
equiv.sum_congr_symm e f
@[simp] lemma sum_congr_refl {α β : Sort*} :
sum_congr (equiv.refl α) (equiv.refl β) = equiv.refl (α ⊕ β) :=
equiv.sum_congr_refl
end perm
/-- `bool` is equivalent the sum of two `punit`s. -/
def bool_equiv_punit_sum_punit : bool ≃ punit.{u+1} ⊕ punit.{v+1} :=
⟨λ b, cond b (inr punit.star) (inl punit.star),
λ s, sum.rec_on s (λ_, ff) (λ_, tt),
λ b, by cases b; refl,
λ s, by rcases s with ⟨⟨⟩⟩ | ⟨⟨⟩⟩; refl⟩
/-- `Prop` is noncomputably equivalent to `bool`. -/
noncomputable def Prop_equiv_bool : Prop ≃ bool :=
⟨λ p, @to_bool p (classical.prop_decidable _),
λ b, b, λ p, by simp, λ b, by simp⟩
/-- Sum of types is commutative up to an equivalence. -/
@[simps apply]
def sum_comm (α β : Sort*) : α ⊕ β ≃ β ⊕ α :=
⟨sum.swap, sum.swap, sum.swap_swap, sum.swap_swap⟩
@[simp] lemma sum_comm_symm (α β) : (sum_comm α β).symm = sum_comm β α := rfl
/-- Sum of types is associative up to an equivalence. -/
def sum_assoc (α β γ : Sort*) : (α ⊕ β) ⊕ γ ≃ α ⊕ (β ⊕ γ) :=
⟨sum.elim (sum.elim sum.inl (sum.inr ∘ sum.inl)) (sum.inr ∘ sum.inr),
sum.elim (sum.inl ∘ sum.inl) $ sum.elim (sum.inl ∘ sum.inr) sum.inr,
by rintros (⟨_ | _⟩ | _); refl,
by rintros (_ | ⟨_ | _⟩); refl⟩
@[simp] theorem sum_assoc_apply_in1 {α β γ} (a) : sum_assoc α β γ (inl (inl a)) = inl a := rfl
@[simp] theorem sum_assoc_apply_in2 {α β γ} (b) : sum_assoc α β γ (inl (inr b)) = inr (inl b) := rfl
@[simp] theorem sum_assoc_apply_in3 {α β γ} (c) : sum_assoc α β γ (inr c) = inr (inr c) := rfl
/-- Sum with `empty` is equivalent to the original type. -/
@[simps symm_apply] def sum_empty (α β : Type*) [is_empty β] : α ⊕ β ≃ α :=
⟨sum.elim id is_empty_elim,
inl,
λ s, by { rcases s with _ | x, refl, exact is_empty_elim x },
λ a, rfl⟩
@[simp] lemma sum_empty_apply_inl {α β : Type*} [is_empty β] (a : α) :
sum_empty α β (sum.inl a) = a := rfl
/-- The sum of `empty` with any `Sort*` is equivalent to the right summand. -/
@[simps symm_apply] def empty_sum (α β : Type*) [is_empty α] : α ⊕ β ≃ β :=
(sum_comm _ _).trans $ sum_empty _ _
@[simp] lemma empty_sum_apply_inr {α β : Type*} [is_empty α] (b : β) :
empty_sum α β (sum.inr b) = b := rfl
/-- `option α` is equivalent to `α ⊕ punit` -/
def option_equiv_sum_punit (α : Type*) : option α ≃ α ⊕ punit.{u+1} :=
⟨λ o, match o with none := inr punit.star | some a := inl a end,
λ s, match s with inr _ := none | inl a := some a end,
λ o, by cases o; refl,
λ s, by rcases s with _ | ⟨⟨⟩⟩; refl⟩
@[simp] lemma option_equiv_sum_punit_none {α} :
option_equiv_sum_punit α none = sum.inr punit.star := rfl
@[simp] lemma option_equiv_sum_punit_some {α} (a) :
option_equiv_sum_punit α (some a) = sum.inl a := rfl
@[simp] lemma option_equiv_sum_punit_coe {α} (a : α) :
option_equiv_sum_punit α a = sum.inl a := rfl
@[simp] lemma option_equiv_sum_punit_symm_inl {α} (a) :
(option_equiv_sum_punit α).symm (sum.inl a) = a :=
rfl
@[simp] lemma option_equiv_sum_punit_symm_inr {α} (a) :
(option_equiv_sum_punit α).symm (sum.inr a) = none :=
rfl
/-- The set of `x : option α` such that `is_some x` is equivalent to `α`. -/
def option_is_some_equiv (α : Type*) : {x : option α // x.is_some} ≃ α :=
{ to_fun := λ o, option.get o.2,
inv_fun := λ x, ⟨some x, dec_trivial⟩,
left_inv := λ o, subtype.eq $ option.some_get _,
right_inv := λ x, option.get_some _ _ }
/-- `α ⊕ β` is equivalent to a `sigma`-type over `bool`. Note that this definition assumes `α` and
`β` to be types from the same universe, so it cannot by used directly to transfer theorems about
sigma types to theorems about sum types. In many cases one can use `ulift` to work around this
difficulty. -/
def sum_equiv_sigma_bool (α β : Type u) : α ⊕ β ≃ (Σ b: bool, cond b α β) :=
⟨λ s, s.elim (λ x, ⟨tt, x⟩) (λ x, ⟨ff, x⟩),
λ s, match s with ⟨tt, a⟩ := inl a | ⟨ff, b⟩ := inr b end,
λ s, by cases s; refl,
λ s, by rcases s with ⟨_|_, _⟩; refl⟩
/-- `sigma_preimage_equiv f` for `f : α → β` is the natural equivalence between
the type of all fibres of `f` and the total space `α`. -/
@[simps]
def sigma_preimage_equiv {α β : Type*} (f : α → β) :
(Σ y : β, {x // f x = y}) ≃ α :=
⟨λ x, ↑x.2, λ x, ⟨f x, x, rfl⟩, λ ⟨y, x, rfl⟩, rfl, λ x, rfl⟩
/-- A set `s` in `α × β` is equivalent to the sigma-type `Σ x, {y | (x, y) ∈ s}`. -/
def set_prod_equiv_sigma {α β : Type*} (s : set (α × β)) :
s ≃ Σ x : α, {y | (x, y) ∈ s} :=
{ to_fun := λ x, ⟨x.1.1, x.1.2, by simp⟩,
inv_fun := λ x, ⟨(x.1, x.2.1), x.2.2⟩,
left_inv := λ ⟨⟨x, y⟩, h⟩, rfl,
right_inv := λ ⟨x, y, h⟩, rfl }
end
section sum_compl
/-- For any predicate `p` on `α`,
the sum of the two subtypes `{a // p a}` and its complement `{a // ¬ p a}`
is naturally equivalent to `α`. -/
def sum_compl {α : Type*} (p : α → Prop) [decidable_pred p] :
{a // p a} ⊕ {a // ¬ p a} ≃ α :=
{ to_fun := sum.elim coe coe,
inv_fun := λ a, if h : p a then sum.inl ⟨a, h⟩ else sum.inr ⟨a, h⟩,
left_inv := by { rintros (⟨x,hx⟩|⟨x,hx⟩); dsimp; [rw dif_pos, rw dif_neg], },
right_inv := λ a, by { dsimp, split_ifs; refl } }
@[simp] lemma sum_compl_apply_inl {α : Type*} (p : α → Prop) [decidable_pred p]
(x : {a // p a}) :
sum_compl p (sum.inl x) = x := rfl
@[simp] lemma sum_compl_apply_inr {α : Type*} (p : α → Prop) [decidable_pred p]
(x : {a // ¬ p a}) :
sum_compl p (sum.inr x) = x := rfl
@[simp] lemma sum_compl_apply_symm_of_pos {α : Type*} (p : α → Prop) [decidable_pred p]
(a : α) (h : p a) :
(sum_compl p).symm a = sum.inl ⟨a, h⟩ := dif_pos h
@[simp] lemma sum_compl_apply_symm_of_neg {α : Type*} (p : α → Prop) [decidable_pred p]
(a : α) (h : ¬ p a) :
(sum_compl p).symm a = sum.inr ⟨a, h⟩ := dif_neg h
/-- Combines an `equiv` between two subtypes with an `equiv` between their complements to form a
permutation. -/
def subtype_congr {α : Type*} {p q : α → Prop} [decidable_pred p] [decidable_pred q]
(e : {x // p x} ≃ {x // q x}) (f : {x // ¬p x} ≃ {x // ¬q x}) : perm α :=
(sum_compl p).symm.trans ((sum_congr e f).trans
(sum_compl q))
open equiv
variables {ε : Type*} {p : ε → Prop} [decidable_pred p]
variables (ep ep' : perm {a // p a}) (en en' : perm {a // ¬ p a})
/-- Combining permutations on `ε` that permute only inside or outside the subtype
split induced by `p : ε → Prop` constructs a permutation on `ε`. -/
def perm.subtype_congr : equiv.perm ε :=
perm_congr (sum_compl p) (sum_congr ep en)
lemma perm.subtype_congr.apply (a : ε) :
ep.subtype_congr en a = if h : p a then ep ⟨a, h⟩ else en ⟨a, h⟩ :=
by { by_cases h : p a; simp [perm.subtype_congr, h] }
@[simp] lemma perm.subtype_congr.left_apply {a : ε} (h : p a) :
ep.subtype_congr en a = ep ⟨a, h⟩ :=
by simp [perm.subtype_congr.apply, h]
@[simp] lemma perm.subtype_congr.left_apply_subtype (a : {a // p a}) :
ep.subtype_congr en a = ep a :=
by { convert perm.subtype_congr.left_apply _ _ a.property, simp }
@[simp] lemma perm.subtype_congr.right_apply {a : ε} (h : ¬ p a) :
ep.subtype_congr en a = en ⟨a, h⟩ :=
by simp [perm.subtype_congr.apply, h]
@[simp] lemma perm.subtype_congr.right_apply_subtype (a : {a // ¬ p a}) :
ep.subtype_congr en a = en a :=
by { convert perm.subtype_congr.right_apply _ _ a.property, simp }
@[simp] lemma perm.subtype_congr.refl :
perm.subtype_congr (equiv.refl {a // p a}) (equiv.refl {a // ¬ p a}) = equiv.refl ε :=
by { ext x, by_cases h : p x; simp [h] }
@[simp] lemma perm.subtype_congr.symm :
(ep.subtype_congr en).symm = perm.subtype_congr ep.symm en.symm :=
begin
ext x,
by_cases h : p x,
{ have : p (ep.symm ⟨x, h⟩) := subtype.property _,
simp [perm.subtype_congr.apply, h, symm_apply_eq, this] },
{ have : ¬ p (en.symm ⟨x, h⟩) := subtype.property (en.symm _),
simp [perm.subtype_congr.apply, h, symm_apply_eq, this] }
end
@[simp] lemma perm.subtype_congr.trans :
(ep.subtype_congr en).trans (ep'.subtype_congr en') =
perm.subtype_congr (ep.trans ep') (en.trans en') :=
begin
ext x,
by_cases h : p x,
{ have : p (ep ⟨x, h⟩) := subtype.property _,
simp [perm.subtype_congr.apply, h, this] },
{ have : ¬ p (en ⟨x, h⟩) := subtype.property (en _),
simp [perm.subtype_congr.apply, h, symm_apply_eq, this] }
end
end sum_compl
section subtype_preimage
variables (p : α → Prop) [decidable_pred p] (x₀ : {a // p a} → β)
/-- For a fixed function `x₀ : {a // p a} → β` defined on a subtype of `α`,
the subtype of functions `x : α → β` that agree with `x₀` on the subtype `{a // p a}`
is naturally equivalent to the type of functions `{a // ¬ p a} → β`. -/
@[simps]
def subtype_preimage :
{x : α → β // x ∘ coe = x₀} ≃ ({a // ¬ p a} → β) :=
{ to_fun := λ (x : {x : α → β // x ∘ coe = x₀}) a, (x : α → β) a,
inv_fun := λ x, ⟨λ a, if h : p a then x₀ ⟨a, h⟩ else x ⟨a, h⟩,
funext $ λ ⟨a, h⟩, dif_pos h⟩,
left_inv := λ ⟨x, hx⟩, subtype.val_injective $ funext $ λ a,
(by { dsimp, split_ifs; [ rw ← hx, skip ]; refl }),
right_inv := λ x, funext $ λ ⟨a, h⟩,
show dite (p a) _ _ = _, by { dsimp, rw [dif_neg h] } }
lemma subtype_preimage_symm_apply_coe_pos (x : {a // ¬ p a} → β) (a : α) (h : p a) :
((subtype_preimage p x₀).symm x : α → β) a = x₀ ⟨a, h⟩ :=
dif_pos h
lemma subtype_preimage_symm_apply_coe_neg (x : {a // ¬ p a} → β) (a : α) (h : ¬ p a) :
((subtype_preimage p x₀).symm x : α → β) a = x ⟨a, h⟩ :=
dif_neg h
end subtype_preimage
section
/-- A family of equivalences `Π a, β₁ a ≃ β₂ a` generates an equivalence between `Π a, β₁ a` and
`Π a, β₂ a`. -/
def Pi_congr_right {α} {β₁ β₂ : α → Sort*} (F : Π a, β₁ a ≃ β₂ a) : (Π a, β₁ a) ≃ (Π a, β₂ a) :=
⟨λ H a, F a (H a), λ H a, (F a).symm (H a),
λ H, funext $ by simp, λ H, funext $ by simp⟩
/-- Dependent `curry` equivalence: the type of dependent functions on `Σ i, β i` is equivalent
to the type of dependent functions of two arguments (i.e., functions to the space of functions).
This is `sigma.curry` and `sigma.uncurry` together as an equiv. -/
def Pi_curry {α} {β : α → Sort*} (γ : Π a, β a → Sort*) :
(Π x : Σ i, β i, γ x.1 x.2) ≃ (Π a b, γ a b) :=
{ to_fun := sigma.curry,
inv_fun := sigma.uncurry,
left_inv := sigma.uncurry_curry,
right_inv := sigma.curry_uncurry }
end
section
/-- A `psigma`-type is equivalent to the corresponding `sigma`-type. -/
@[simps apply symm_apply] def psigma_equiv_sigma {α} (β : α → Sort*) : (Σ' i, β i) ≃ Σ i, β i :=
⟨λ a, ⟨a.1, a.2⟩, λ a, ⟨a.1, a.2⟩, λ ⟨a, b⟩, rfl, λ ⟨a, b⟩, rfl⟩
/-- A family of equivalences `Π a, β₁ a ≃ β₂ a` generates an equivalence between `Σ a, β₁ a` and
`Σ a, β₂ a`. -/
@[simps apply]
def sigma_congr_right {α} {β₁ β₂ : α → Sort*} (F : Π a, β₁ a ≃ β₂ a) : (Σ a, β₁ a) ≃ Σ a, β₂ a :=
⟨λ a, ⟨a.1, F a.1 a.2⟩, λ a, ⟨a.1, (F a.1).symm a.2⟩,
λ ⟨a, b⟩, congr_arg (sigma.mk a) $ symm_apply_apply (F a) b,
λ ⟨a, b⟩, congr_arg (sigma.mk a) $ apply_symm_apply (F a) b⟩
@[simp] lemma sigma_congr_right_trans {α} {β₁ β₂ β₃ : α → Sort*}
(F : Π a, β₁ a ≃ β₂ a) (G : Π a, β₂ a ≃ β₃ a) :
(sigma_congr_right F).trans (sigma_congr_right G) = sigma_congr_right (λ a, (F a).trans (G a)) :=
by { ext1 x, cases x, refl }
@[simp] lemma sigma_congr_right_symm {α} {β₁ β₂ : α → Sort*} (F : Π a, β₁ a ≃ β₂ a) :
(sigma_congr_right F).symm = sigma_congr_right (λ a, (F a).symm) :=
by { ext1 x, cases x, refl }
@[simp] lemma sigma_congr_right_refl {α} {β : α → Sort*} :
(sigma_congr_right (λ a, equiv.refl (β a))) = equiv.refl (Σ a, β a) :=
by { ext1 x, cases x, refl }
namespace perm
/-- A family of permutations `Π a, perm (β a)` generates a permuation `perm (Σ a, β₁ a)`. -/
@[reducible]
def sigma_congr_right {α} {β : α → Sort*} (F : Π a, perm (β a)) : perm (Σ a, β a) :=
equiv.sigma_congr_right F
@[simp] lemma sigma_congr_right_trans {α} {β : α → Sort*}
(F : Π a, perm (β a)) (G : Π a, perm (β a)) :
(sigma_congr_right F).trans (sigma_congr_right G) = sigma_congr_right (λ a, (F a).trans (G a)) :=
equiv.sigma_congr_right_trans F G
@[simp] lemma sigma_congr_right_symm {α} {β : α → Sort*} (F : Π a, perm (β a)) :
(sigma_congr_right F).symm = sigma_congr_right (λ a, (F a).symm) :=
equiv.sigma_congr_right_symm F
@[simp] lemma sigma_congr_right_refl {α} {β : α → Sort*} :
(sigma_congr_right (λ a, equiv.refl (β a))) = equiv.refl (Σ a, β a) :=
equiv.sigma_congr_right_refl
end perm
/-- An equivalence `f : α₁ ≃ α₂` generates an equivalence between `Σ a, β (f a)` and `Σ a, β a`. -/
@[simps apply]
def sigma_congr_left {α₁ α₂} {β : α₂ → Sort*} (e : α₁ ≃ α₂) : (Σ a:α₁, β (e a)) ≃ (Σ a:α₂, β a) :=
⟨λ a, ⟨e a.1, a.2⟩, λ a, ⟨e.symm a.1, @@eq.rec β a.2 (e.right_inv a.1).symm⟩,
λ ⟨a, b⟩, match e.symm (e a), e.left_inv a : ∀ a' (h : a' = a),
@sigma.mk _ (β ∘ e) _ (@@eq.rec β b (congr_arg e h.symm)) = ⟨a, b⟩ with
| _, rfl := rfl end,
λ ⟨a, b⟩, match e (e.symm a), _ : ∀ a' (h : a' = a),
sigma.mk a' (@@eq.rec β b h.symm) = ⟨a, b⟩ with
| _, rfl := rfl end⟩
/-- Transporting a sigma type through an equivalence of the base -/
def sigma_congr_left' {α₁ α₂} {β : α₁ → Sort*} (f : α₁ ≃ α₂) :
(Σ a:α₁, β a) ≃ (Σ a:α₂, β (f.symm a)) :=
(sigma_congr_left f.symm).symm
/-- Transporting a sigma type through an equivalence of the base and a family of equivalences
of matching fibers -/
def sigma_congr {α₁ α₂} {β₁ : α₁ → Sort*} {β₂ : α₂ → Sort*} (f : α₁ ≃ α₂)
(F : ∀ a, β₁ a ≃ β₂ (f a)) :
sigma β₁ ≃ sigma β₂ :=
(sigma_congr_right F).trans (sigma_congr_left f)
/-- `sigma` type with a constant fiber is equivalent to the product. -/
@[simps apply symm_apply] def sigma_equiv_prod (α β : Type*) : (Σ_:α, β) ≃ α × β :=
⟨λ a, ⟨a.1, a.2⟩, λ a, ⟨a.1, a.2⟩, λ ⟨a, b⟩, rfl, λ ⟨a, b⟩, rfl⟩
/-- If each fiber of a `sigma` type is equivalent to a fixed type, then the sigma type
is equivalent to the product. -/
def sigma_equiv_prod_of_equiv {α β} {β₁ : α → Sort*} (F : Π a, β₁ a ≃ β) : sigma β₁ ≃ α × β :=
(sigma_congr_right F).trans (sigma_equiv_prod α β)
end
section prod_congr
variables {α₁ β₁ β₂ : Type*} (e : α₁ → β₁ ≃ β₂)
/-- A family of equivalences `Π (a : α₁), β₁ ≃ β₂` generates an equivalence
between `β₁ × α₁` and `β₂ × α₁`. -/
def prod_congr_left : β₁ × α₁ ≃ β₂ × α₁ :=
{ to_fun := λ ab, ⟨e ab.2 ab.1, ab.2⟩,
inv_fun := λ ab, ⟨(e ab.2).symm ab.1, ab.2⟩,
left_inv := by { rintros ⟨a, b⟩, simp },
right_inv := by { rintros ⟨a, b⟩, simp } }
@[simp] lemma prod_congr_left_apply (b : β₁) (a : α₁) :
prod_congr_left e (b, a) = (e a b, a) := rfl
lemma prod_congr_refl_right (e : β₁ ≃ β₂) :
prod_congr e (equiv.refl α₁) = prod_congr_left (λ _, e) :=
by { ext ⟨a, b⟩ : 1, simp }
/-- A family of equivalences `Π (a : α₁), β₁ ≃ β₂` generates an equivalence
between `α₁ × β₁` and `α₁ × β₂`. -/
def prod_congr_right : α₁ × β₁ ≃ α₁ × β₂ :=
{ to_fun := λ ab, ⟨ab.1, e ab.1 ab.2⟩,
inv_fun := λ ab, ⟨ab.1, (e ab.1).symm ab.2⟩,
left_inv := by { rintros ⟨a, b⟩, simp },
right_inv := by { rintros ⟨a, b⟩, simp } }
@[simp] lemma prod_congr_right_apply (a : α₁) (b : β₁) :
prod_congr_right e (a, b) = (a, e a b) := rfl
lemma prod_congr_refl_left (e : β₁ ≃ β₂) :
prod_congr (equiv.refl α₁) e = prod_congr_right (λ _, e) :=
by { ext ⟨a, b⟩ : 1, simp }
@[simp] lemma prod_congr_left_trans_prod_comm :
(prod_congr_left e).trans (prod_comm _ _) = (prod_comm _ _).trans (prod_congr_right e) :=
by { ext ⟨a, b⟩ : 1, simp }
@[simp] lemma prod_congr_right_trans_prod_comm :
(prod_congr_right e).trans (prod_comm _ _) = (prod_comm _ _).trans (prod_congr_left e) :=
by { ext ⟨a, b⟩ : 1, simp }
lemma sigma_congr_right_sigma_equiv_prod :
(sigma_congr_right e).trans (sigma_equiv_prod α₁ β₂) =
(sigma_equiv_prod α₁ β₁).trans (prod_congr_right e) :=
by { ext ⟨a, b⟩ : 1, simp }
lemma sigma_equiv_prod_sigma_congr_right :
(sigma_equiv_prod α₁ β₁).symm.trans (sigma_congr_right e) =
(prod_congr_right e).trans (sigma_equiv_prod α₁ β₂).symm :=
by { ext ⟨a, b⟩ : 1, simp }
/-- A variation on `equiv.prod_congr` where the equivalence in the second component can depend
on the first component. A typical example is a shear mapping, explaining the name of this
declaration. -/
@[simps {fully_applied := ff}]
def prod_shear {α₁ β₁ α₂ β₂ : Type*} (e₁ : α₁ ≃ α₂) (e₂ : α₁ → β₁ ≃ β₂) : α₁ × β₁ ≃ α₂ × β₂ :=
{ to_fun := λ x : α₁ × β₁, (e₁ x.1, e₂ x.1 x.2),
inv_fun := λ y : α₂ × β₂, (e₁.symm y.1, (e₂ $ e₁.symm y.1).symm y.2),
left_inv := by { rintro ⟨x₁, y₁⟩, simp only [symm_apply_apply] },
right_inv := by { rintro ⟨x₁, y₁⟩, simp only [apply_symm_apply] } }
end prod_congr
namespace perm
variables {α₁ β₁ β₂ : Type*} [decidable_eq α₁] (a : α₁) (e : perm β₁)
/-- `prod_extend_right a e` extends `e : perm β` to `perm (α × β)` by sending `(a, b)` to
`(a, e b)` and keeping the other `(a', b)` fixed. -/
def prod_extend_right : perm (α₁ × β₁) :=
{ to_fun := λ ab, if ab.fst = a then (a, e ab.snd) else ab,
inv_fun := λ ab, if ab.fst = a then (a, e.symm ab.snd) else ab,
left_inv := by { rintros ⟨k', x⟩, simp only, split_ifs with h; simp [h] },
right_inv := by { rintros ⟨k', x⟩, simp only, split_ifs with h; simp [h] } }
@[simp] lemma prod_extend_right_apply_eq (b : β₁) :
prod_extend_right a e (a, b) = (a, e b) := if_pos rfl
lemma prod_extend_right_apply_ne {a a' : α₁} (h : a' ≠ a) (b : β₁) :
prod_extend_right a e (a', b) = (a', b) := if_neg h
lemma eq_of_prod_extend_right_ne {e : perm β₁} {a a' : α₁} {b : β₁}
(h : prod_extend_right a e (a', b) ≠ (a', b)) : a' = a :=
by { contrapose! h, exact prod_extend_right_apply_ne _ h _ }
@[simp] lemma fst_prod_extend_right (ab : α₁ × β₁) :
(prod_extend_right a e ab).fst = ab.fst :=
begin
rw [prod_extend_right, coe_fn_mk],
split_ifs with h,
{ rw h },
{ refl }
end
end perm
section
/-- The type of functions to a product `α × β` is equivalent to the type of pairs of functions
`γ → α` and `γ → β`. -/
def arrow_prod_equiv_prod_arrow (α β γ : Type*) : (γ → α × β) ≃ (γ → α) × (γ → β) :=
⟨λ f, (λ c, (f c).1, λ c, (f c).2),
λ p c, (p.1 c, p.2 c),
λ f, funext $ λ c, prod.mk.eta,
λ p, by { cases p, refl }⟩
open sum
/-- The type of functions on a sum type `α ⊕ β` is equivalent to the type of pairs of functions
on `α` and on `β`. -/
def sum_arrow_equiv_prod_arrow (α β γ : Type*) : ((α ⊕ β) → γ) ≃ (α → γ) × (β → γ) :=
⟨λ f, (f ∘ inl, f ∘ inr),
λ p, sum.elim p.1 p.2,
λ f, by { ext ⟨⟩; refl },
λ p, by { cases p, refl }⟩
/-- Type product is right distributive with respect to type sum up to an equivalence. -/
def sum_prod_distrib (α β γ : Sort*) : (α ⊕ β) × γ ≃ (α × γ) ⊕ (β × γ) :=
⟨λ p, match p with (inl a, c) := inl (a, c) | (inr b, c) := inr (b, c) end,
λ s, match s with inl q := (inl q.1, q.2) | inr q := (inr q.1, q.2) end,
λ p, by rcases p with ⟨_ | _, _⟩; refl,
λ s, by rcases s with ⟨_, _⟩ | ⟨_, _⟩; refl⟩
@[simp] theorem sum_prod_distrib_apply_left {α β γ} (a : α) (c : γ) :
sum_prod_distrib α β γ (sum.inl a, c) = sum.inl (a, c) := rfl
@[simp] theorem sum_prod_distrib_apply_right {α β γ} (b : β) (c : γ) :
sum_prod_distrib α β γ (sum.inr b, c) = sum.inr (b, c) := rfl
/-- Type product is left distributive with respect to type sum up to an equivalence. -/
def prod_sum_distrib (α β γ : Sort*) : α × (β ⊕ γ) ≃ (α × β) ⊕ (α × γ) :=
calc α × (β ⊕ γ) ≃ (β ⊕ γ) × α : prod_comm _ _
... ≃ (β × α) ⊕ (γ × α) : sum_prod_distrib _ _ _
... ≃ (α × β) ⊕ (α × γ) : sum_congr (prod_comm _ _) (prod_comm _ _)
@[simp] theorem prod_sum_distrib_apply_left {α β γ} (a : α) (b : β) :
prod_sum_distrib α β γ (a, sum.inl b) = sum.inl (a, b) := rfl
@[simp] theorem prod_sum_distrib_apply_right {α β γ} (a : α) (c : γ) :
prod_sum_distrib α β γ (a, sum.inr c) = sum.inr (a, c) := rfl
/-- The product of an indexed sum of types (formally, a `sigma`-type `Σ i, α i`) by a type `β` is
equivalent to the sum of products `Σ i, (α i × β)`. -/
def sigma_prod_distrib {ι : Type*} (α : ι → Type*) (β : Type*) :
((Σ i, α i) × β) ≃ (Σ i, (α i × β)) :=
⟨λ p, ⟨p.1.1, (p.1.2, p.2)⟩,
λ p, (⟨p.1, p.2.1⟩, p.2.2),
λ p, by { rcases p with ⟨⟨_, _⟩, _⟩, refl },
λ p, by { rcases p with ⟨_, ⟨_, _⟩⟩, refl }⟩
/-- The product `bool × α` is equivalent to `α ⊕ α`. -/
def bool_prod_equiv_sum (α : Type u) : bool × α ≃ α ⊕ α :=
calc bool × α ≃ (unit ⊕ unit) × α : prod_congr bool_equiv_punit_sum_punit (equiv.refl _)
... ≃ (unit × α) ⊕ (unit × α) : sum_prod_distrib _ _ _
... ≃ α ⊕ α : sum_congr (punit_prod _) (punit_prod _)
/-- The function type `bool → α` is equivalent to `α × α`. -/
def bool_to_equiv_prod (α : Type u) : (bool → α) ≃ α × α :=
calc (bool → α) ≃ ((unit ⊕ unit) → α) : (arrow_congr bool_equiv_punit_sum_punit (equiv.refl α))
... ≃ (unit → α) × (unit → α) : sum_arrow_equiv_prod_arrow _ _ _
... ≃ α × α : prod_congr (punit_arrow_equiv _) (punit_arrow_equiv _)
@[simp] lemma bool_to_equiv_prod_apply {α : Type u} (f : bool → α) :
bool_to_equiv_prod α f = (f ff, f tt) := rfl
@[simp] lemma bool_to_equiv_prod_symm_apply_ff {α : Type u} (p : α × α) :
(bool_to_equiv_prod α).symm p ff = p.1 := rfl
@[simp] lemma bool_to_equiv_prod_symm_apply_tt {α : Type u} (p : α × α) :
(bool_to_equiv_prod α).symm p tt = p.2 := rfl
end
section
open sum nat
/-- The set of natural numbers is equivalent to `ℕ ⊕ punit`. -/
def nat_equiv_nat_sum_punit : ℕ ≃ ℕ ⊕ punit.{u+1} :=
⟨λ n, match n with zero := inr punit.star | succ a := inl a end,
λ s, match s with inl n := succ n | inr punit.star := zero end,
λ n, begin cases n, repeat { refl } end,
λ s, begin cases s with a u, { refl }, {cases u, { refl }} end⟩
/-- `ℕ ⊕ punit` is equivalent to `ℕ`. -/
def nat_sum_punit_equiv_nat : ℕ ⊕ punit.{u+1} ≃ ℕ :=
nat_equiv_nat_sum_punit.symm
/-- The type of integer numbers is equivalent to `ℕ ⊕ ℕ`. -/
def int_equiv_nat_sum_nat : ℤ ≃ ℕ ⊕ ℕ :=
by refine ⟨_, _, _, _⟩; intro z; {cases z; [left, right]; assumption} <|> {cases z; refl}
end
/-- An equivalence between `α` and `β` generates an equivalence between `list α` and `list β`. -/
def list_equiv_of_equiv {α β : Type*} (e : α ≃ β) : list α ≃ list β :=
{ to_fun := list.map e,
inv_fun := list.map e.symm,
left_inv := λ l, by rw [list.map_map, e.symm_comp_self, list.map_id],
right_inv := λ l, by rw [list.map_map, e.self_comp_symm, list.map_id] }
/-- `fin n` is equivalent to `{m // m < n}`. -/
def fin_equiv_subtype (n : ℕ) : fin n ≃ {m // m < n} :=
⟨λ x, ⟨x.1, x.2⟩, λ x, ⟨x.1, x.2⟩, λ ⟨a, b⟩, rfl,λ ⟨a, b⟩, rfl⟩
/-- If `α` is equivalent to `β`, then `unique α` is equivalent to `unique β`. -/
def unique_congr (e : α ≃ β) : unique α ≃ unique β :=
{ to_fun := λ h, @equiv.unique _ _ h e.symm,
inv_fun := λ h, @equiv.unique _ _ h e,
left_inv := λ _, subsingleton.elim _ _,
right_inv := λ _, subsingleton.elim _ _ }
/-- If `α` is equivalent to `β`, then `is_empty α` is equivalent to `is_empty β`. -/
lemma is_empty_congr (e : α ≃ β) : is_empty α ↔ is_empty β :=
⟨λ h, @function.is_empty _ _ h e.symm, λ h, @function.is_empty _ _ h e⟩
section
open subtype
/-- If `α` is equivalent to `β` and the predicates `p : α → Prop` and `q : β → Prop` are equivalent
at corresponding points, then `{a // p a}` is equivalent to `{b // q b}`.
For the statement where `α = β`, that is, `e : perm α`, see `perm.subtype_perm`. -/
def subtype_equiv {p : α → Prop} {q : β → Prop}
(e : α ≃ β) (h : ∀ a, p a ↔ q (e a)) : {a : α // p a} ≃ {b : β // q b} :=
⟨λ x, ⟨e x, (h _).1 x.2⟩,
λ y, ⟨e.symm y, (h _).2 (by { simp, exact y.2 })⟩,
λ ⟨x, h⟩, subtype.ext_val $ by simp,
λ ⟨y, h⟩, subtype.ext_val $ by simp⟩
@[simp] lemma subtype_equiv_refl {p : α → Prop}
(h : ∀ a, p a ↔ p (equiv.refl _ a) := λ a, iff.rfl) :
(equiv.refl α).subtype_equiv h = equiv.refl {a : α // p a} :=
by { ext, refl }
@[simp] lemma subtype_equiv_symm {p : α → Prop} {q : β → Prop} (e : α ≃ β)
(h : ∀ (a : α), p a ↔ q (e a)) :
(e.subtype_equiv h).symm = e.symm.subtype_equiv (λ a, by {
convert (h $ e.symm a).symm,
exact (e.apply_symm_apply a).symm,
}) :=
rfl
@[simp] lemma subtype_equiv_trans {p : α → Prop} {q : β → Prop} {r : γ → Prop}
(e : α ≃ β) (f : β ≃ γ)
(h : ∀ (a : α), p a ↔ q (e a)) (h' : ∀ (b : β), q b ↔ r (f b)):
(e.subtype_equiv h).trans (f.subtype_equiv h') =
(e.trans f).subtype_equiv (λ a, (h a).trans (h' $ e a)) :=
rfl
@[simp] lemma subtype_equiv_apply {p : α → Prop} {q : β → Prop} (e : α ≃ β)
(h : ∀ (a : α), p a ↔ q (e a)) (x : {x // p x}) :
e.subtype_equiv h x = ⟨e x, (h _).1 x.2⟩ :=
rfl
/-- If two predicates `p` and `q` are pointwise equivalent, then `{x // p x}` is equivalent to
`{x // q x}`. -/
@[simps]
def subtype_equiv_right {p q : α → Prop} (e : ∀x, p x ↔ q x) : {x // p x} ≃ {x // q x} :=
subtype_equiv (equiv.refl _) e
/-- If `α ≃ β`, then for any predicate `p : β → Prop` the subtype `{a // p (e a)}` is equivalent
to the subtype `{b // p b}`. -/
def subtype_equiv_of_subtype {p : β → Prop} (e : α ≃ β) :
{a : α // p (e a)} ≃ {b : β // p b} :=
subtype_equiv e $ by simp
/-- If `α ≃ β`, then for any predicate `p : α → Prop` the subtype `{a // p a}` is equivalent
to the subtype `{b // p (e.symm b)}`. This version is used by `equiv_rw`. -/
def subtype_equiv_of_subtype' {p : α → Prop} (e : α ≃ β) :
{a : α // p a} ≃ {b : β // p (e.symm b)} :=
e.symm.subtype_equiv_of_subtype.symm
/-- If two predicates are equal, then the corresponding subtypes are equivalent. -/
def subtype_equiv_prop {α : Type*} {p q : α → Prop} (h : p = q) : subtype p ≃ subtype q :=
subtype_equiv (equiv.refl α) (assume a, h ▸ iff.rfl)
/-- The subtypes corresponding to equal sets are equivalent. -/
@[simps apply]
def set_congr {α : Type*} {s t : set α} (h : s = t) : s ≃ t :=
subtype_equiv_prop h
/-- A subtype of a subtype is equivalent to the subtype of elements satisfying both predicates. This
version allows the “inner” predicate to depend on `h : p a`. -/
def subtype_subtype_equiv_subtype_exists {α : Type u} (p : α → Prop) (q : subtype p → Prop) :
subtype q ≃ {a : α // ∃h:p a, q ⟨a, h⟩ } :=
⟨λ⟨⟨a, ha⟩, ha'⟩, ⟨a, ha, ha'⟩,
λ⟨a, ha⟩, ⟨⟨a, ha.cases_on $ assume h _, h⟩, by { cases ha, exact ha_h }⟩,
assume ⟨⟨a, ha⟩, h⟩, rfl, assume ⟨a, h₁, h₂⟩, rfl⟩
@[simp] lemma subtype_subtype_equiv_subtype_exists_apply {α : Type u} (p : α → Prop)
(q : subtype p → Prop) (a) : (subtype_subtype_equiv_subtype_exists p q a : α) = a :=
by { cases a, cases a_val, refl }
/-- A subtype of a subtype is equivalent to the subtype of elements satisfying both predicates. -/
def subtype_subtype_equiv_subtype_inter {α : Type u} (p q : α → Prop) :
{x : subtype p // q x.1} ≃ subtype (λ x, p x ∧ q x) :=
(subtype_subtype_equiv_subtype_exists p _).trans $
subtype_equiv_right $ λ x, exists_prop
@[simp] lemma subtype_subtype_equiv_subtype_inter_apply {α : Type u} (p q : α → Prop) (a) :
(subtype_subtype_equiv_subtype_inter p q a : α) = a :=
by { cases a, cases a_val, refl }
/-- If the outer subtype has more restrictive predicate than the inner one,
then we can drop the latter. -/
def subtype_subtype_equiv_subtype {α : Type u} {p q : α → Prop} (h : ∀ {x}, q x → p x) :
{x : subtype p // q x.1} ≃ subtype q :=
(subtype_subtype_equiv_subtype_inter p _).trans $
subtype_equiv_right $
assume x,
⟨and.right, λ h₁, ⟨h h₁, h₁⟩⟩
@[simp] lemma subtype_subtype_equiv_subtype_apply {α : Type u} {p q : α → Prop} (h : ∀ x, q x → p x)
(a : {x : subtype p // q x.1}) :
(subtype_subtype_equiv_subtype h a : α) = a :=
by { cases a, cases a_val, refl }
/-- If a proposition holds for all elements, then the subtype is
equivalent to the original type. -/
@[simps apply symm_apply]
def subtype_univ_equiv {α : Type u} {p : α → Prop} (h : ∀ x, p x) :
subtype p ≃ α :=
⟨λ x, x, λ x, ⟨x, h x⟩, λ x, subtype.eq rfl, λ x, rfl⟩
/-- A subtype of a sigma-type is a sigma-type over a subtype. -/
def subtype_sigma_equiv {α : Type u} (p : α → Type v) (q : α → Prop) :
{ y : sigma p // q y.1 } ≃ Σ(x : subtype q), p x.1 :=
⟨λ x, ⟨⟨x.1.1, x.2⟩, x.1.2⟩,
λ x, ⟨⟨x.1.1, x.2⟩, x.1.2⟩,
λ ⟨⟨x, h⟩, y⟩, rfl,
λ ⟨⟨x, y⟩, h⟩, rfl⟩
/-- A sigma type over a subtype is equivalent to the sigma set over the original type,
if the fiber is empty outside of the subset -/
def sigma_subtype_equiv_of_subset {α : Type u} (p : α → Type v) (q : α → Prop)
(h : ∀ x, p x → q x) :
(Σ x : subtype q, p x) ≃ Σ x : α, p x :=
(subtype_sigma_equiv p q).symm.trans $ subtype_univ_equiv $ λ x, h x.1 x.2
/-- If a predicate `p : β → Prop` is true on the range of a map `f : α → β`, then
`Σ y : {y // p y}, {x // f x = y}` is equivalent to `α`. -/
def sigma_subtype_preimage_equiv {α : Type u} {β : Type v} (f : α → β) (p : β → Prop)
(h : ∀ x, p (f x)) :
(Σ y : subtype p, {x : α // f x = y}) ≃ α :=
calc _ ≃ Σ y : β, {x : α // f x = y} : sigma_subtype_equiv_of_subset _ p (λ y ⟨x, h'⟩, h' ▸ h x)
... ≃ α : sigma_preimage_equiv f
/-- If for each `x` we have `p x ↔ q (f x)`, then `Σ y : {y // q y}, f ⁻¹' {y}` is equivalent
to `{x // p x}`. -/
def sigma_subtype_preimage_equiv_subtype {α : Type u} {β : Type v} (f : α → β)
{p : α → Prop} {q : β → Prop} (h : ∀ x, p x ↔ q (f x)) :
(Σ y : subtype q, {x : α // f x = y}) ≃ subtype p :=
calc (Σ y : subtype q, {x : α // f x = y}) ≃
Σ y : subtype q, {x : subtype p // subtype.mk (f x) ((h x).1 x.2) = y} :
begin
apply sigma_congr_right,
assume y,
symmetry,
refine (subtype_subtype_equiv_subtype_exists _ _).trans (subtype_equiv_right _),
assume x,
exact ⟨λ ⟨hp, h'⟩, congr_arg subtype.val h', λ h', ⟨(h x).2 (h'.symm ▸ y.2), subtype.eq h'⟩⟩
end
... ≃ subtype p : sigma_preimage_equiv (λ x : subtype p, (⟨f x, (h x).1 x.property⟩ : subtype q))
/-- The `pi`-type `Π i, π i` is equivalent to the type of sections `f : ι → Σ i, π i` of the
`sigma` type such that for all `i` we have `(f i).fst = i`. -/
def pi_equiv_subtype_sigma (ι : Type*) (π : ι → Type*) :
(Πi, π i) ≃ {f : ι → Σi, π i | ∀i, (f i).1 = i } :=
⟨ λf, ⟨λi, ⟨i, f i⟩, assume i, rfl⟩, λf i, begin rw ← f.2 i, exact (f.1 i).2 end,
assume f, funext $ assume i, rfl,
assume ⟨f, hf⟩, subtype.eq $ funext $ assume i, sigma.eq (hf i).symm $
eq_of_heq $ rec_heq_of_heq _ $ rec_heq_of_heq _ $ heq.refl _⟩
/-- The set of functions `f : Π a, β a` such that for all `a` we have `p a (f a)` is equivalent
to the set of functions `Π a, {b : β a // p a b}`. -/
def subtype_pi_equiv_pi {α : Sort u} {β : α → Sort v} {p : Πa, β a → Prop} :
{f : Πa, β a // ∀a, p a (f a) } ≃ Πa, { b : β a // p a b } :=
⟨λf a, ⟨f.1 a, f.2 a⟩, λf, ⟨λa, (f a).1, λa, (f a).2⟩,
by { rintro ⟨f, h⟩, refl },
by { rintro f, funext a, exact subtype.ext_val rfl }⟩
/-- A subtype of a product defined by componentwise conditions
is equivalent to a product of subtypes. -/
def subtype_prod_equiv_prod {α : Type u} {β : Type v} {p : α → Prop} {q : β → Prop} :
{c : α × β // p c.1 ∧ q c.2} ≃ ({a // p a} × {b // q b}) :=
⟨λ x, ⟨⟨x.1.1, x.2.1⟩, ⟨x.1.2, x.2.2⟩⟩,
λ x, ⟨⟨x.1.1, x.2.1⟩, ⟨x.1.2, x.2.2⟩⟩,
λ ⟨⟨_, _⟩, ⟨_, _⟩⟩, rfl,
λ ⟨⟨_, _⟩, ⟨_, _⟩⟩, rfl⟩
/-- A subtype of a `prod` is equivalent to a sigma type whose fibers are subtypes. -/
def subtype_prod_equiv_sigma_subtype {α β : Type*} (p : α → β → Prop) :
{x : α × β // p x.1 x.2} ≃ Σ a, {b : β // p a b} :=
{ to_fun := λ x, ⟨x.1.1, x.1.2, x.prop⟩,
inv_fun := λ x, ⟨⟨x.1, x.2⟩, x.2.prop⟩,
left_inv := λ x, by ext; refl,
right_inv := λ ⟨a, b, pab⟩, rfl }
end
section subtype_equiv_codomain
variables {X : Type*} {Y : Type*} [decidable_eq X] {x : X}
/-- The type of all functions `X → Y` with prescribed values for all `x' ≠ x`
is equivalent to the codomain `Y`. -/
def subtype_equiv_codomain (f : {x' // x' ≠ x} → Y) : {g : X → Y // g ∘ coe = f} ≃ Y :=
(subtype_preimage _ f).trans $
@fun_unique {x' // ¬ x' ≠ x} _ $
show unique {x' // ¬ x' ≠ x}, from @equiv.unique _ _
(show unique {x' // x' = x}, from
{ default := ⟨x, rfl⟩, uniq := λ ⟨x', h⟩, subtype.val_injective h })
(subtype_equiv_right $ λ a, not_not)
@[simp] lemma coe_subtype_equiv_codomain (f : {x' // x' ≠ x} → Y) :
(subtype_equiv_codomain f : {g : X → Y // g ∘ coe = f} → Y) = λ g, (g : X → Y) x := rfl
@[simp] lemma subtype_equiv_codomain_apply (f : {x' // x' ≠ x} → Y)
(g : {g : X → Y // g ∘ coe = f}) :
subtype_equiv_codomain f g = (g : X → Y) x := rfl
lemma coe_subtype_equiv_codomain_symm (f : {x' // x' ≠ x} → Y) :
((subtype_equiv_codomain f).symm : Y → {g : X → Y // g ∘ coe = f}) =
λ y, ⟨λ x', if h : x' ≠ x then f ⟨x', h⟩ else y,
by { funext x', dsimp, erw [dif_pos x'.2, subtype.coe_eta] }⟩ := rfl
@[simp] lemma subtype_equiv_codomain_symm_apply (f : {x' // x' ≠ x} → Y) (y : Y) (x' : X) :
((subtype_equiv_codomain f).symm y : X → Y) x' = if h : x' ≠ x then f ⟨x', h⟩ else y :=
rfl
@[simp] lemma subtype_equiv_codomain_symm_apply_eq (f : {x' // x' ≠ x} → Y) (y : Y) :
((subtype_equiv_codomain f).symm y : X → Y) x = y :=
dif_neg (not_not.mpr rfl)
lemma subtype_equiv_codomain_symm_apply_ne (f : {x' // x' ≠ x} → Y) (y : Y) (x' : X) (h : x' ≠ x) :
((subtype_equiv_codomain f).symm y : X → Y) x' = f ⟨x', h⟩ :=
dif_pos h
end subtype_equiv_codomain
/--
A set is equivalent to its image under an equivalence.
-/
-- We could construct this using `equiv.set.image e s e.injective`,
-- but this definition provides an explicit inverse.
@[simps]
def image {α β : Type*} (e : α ≃ β) (s : set α) : s ≃ e '' s :=
{ to_fun := λ x, ⟨e x.1, by simp⟩,
inv_fun := λ y, ⟨e.symm y.1, by { rcases y with ⟨-, ⟨a, ⟨m, rfl⟩⟩⟩, simpa using m, }⟩,
left_inv := λ x, by simp,
right_inv := λ y, by simp, }.
namespace set
open set
/-- `univ α` is equivalent to `α`. -/
@[simps apply symm_apply]
protected def univ (α) : @univ α ≃ α :=
⟨coe, λ a, ⟨a, trivial⟩, λ ⟨a, _⟩, rfl, λ a, rfl⟩
/-- An empty set is equivalent to the `empty` type. -/
protected def empty (α) : (∅ : set α) ≃ empty :=
equiv_empty _
/-- An empty set is equivalent to a `pempty` type. -/
protected def pempty (α) : (∅ : set α) ≃ pempty :=
equiv_pempty _
/-- If sets `s` and `t` are separated by a decidable predicate, then `s ∪ t` is equivalent to
`s ⊕ t`. -/
protected def union' {α} {s t : set α}
(p : α → Prop) [decidable_pred p]
(hs : ∀ x ∈ s, p x)
(ht : ∀ x ∈ t, ¬ p x) : (s ∪ t : set α) ≃ s ⊕ t :=
{ to_fun := λ x, if hp : p x
then sum.inl ⟨_, x.2.resolve_right (λ xt, ht _ xt hp)⟩
else sum.inr ⟨_, x.2.resolve_left (λ xs, hp (hs _ xs))⟩,
inv_fun := λ o, match o with
| (sum.inl x) := ⟨x, or.inl x.2⟩
| (sum.inr x) := ⟨x, or.inr x.2⟩
end,
left_inv := λ ⟨x, h'⟩, by by_cases p x; simp [union'._match_1, h]; congr,
right_inv := λ o, begin
rcases o with ⟨x, h⟩ | ⟨x, h⟩;
dsimp [union'._match_1];
[simp [hs _ h], simp [ht _ h]]
end }
/-- If sets `s` and `t` are disjoint, then `s ∪ t` is equivalent to `s ⊕ t`. -/
protected def union {α} {s t : set α} [decidable_pred (λ x, x ∈ s)] (H : s ∩ t ⊆ ∅) :
(s ∪ t : set α) ≃ s ⊕ t :=
set.union' (λ x, x ∈ s) (λ _, id) (λ x xt xs, H ⟨xs, xt⟩)
lemma union_apply_left {α} {s t : set α} [decidable_pred (λ x, x ∈ s)] (H : s ∩ t ⊆ ∅)
{a : (s ∪ t : set α)} (ha : ↑a ∈ s) : equiv.set.union H a = sum.inl ⟨a, ha⟩ :=
dif_pos ha
lemma union_apply_right {α} {s t : set α} [decidable_pred (λ x, x ∈ s)] (H : s ∩ t ⊆ ∅)
{a : (s ∪ t : set α)} (ha : ↑a ∈ t) : equiv.set.union H a = sum.inr ⟨a, ha⟩ :=
dif_neg $ λ h, H ⟨h, ha⟩
@[simp] lemma union_symm_apply_left {α} {s t : set α} [decidable_pred (λ x, x ∈ s)] (H : s ∩ t ⊆ ∅)
(a : s) : (equiv.set.union H).symm (sum.inl a) = ⟨a, subset_union_left _ _ a.2⟩ :=
rfl
@[simp] lemma union_symm_apply_right {α} {s t : set α} [decidable_pred (λ x, x ∈ s)] (H : s ∩ t ⊆ ∅)
(a : t) : (equiv.set.union H).symm (sum.inr a) = ⟨a, subset_union_right _ _ a.2⟩ :=
rfl
/-- A singleton set is equivalent to a `punit` type. -/
protected def singleton {α} (a : α) : ({a} : set α) ≃ punit.{u} :=
⟨λ _, punit.star, λ _, ⟨a, mem_singleton _⟩,
λ ⟨x, h⟩, by { simp at h, subst x },
λ ⟨⟩, rfl⟩
/-- Equal sets are equivalent. -/
@[simps apply symm_apply]
protected def of_eq {α : Type u} {s t : set α} (h : s = t) : s ≃ t :=
{ to_fun := λ x, ⟨x, h ▸ x.2⟩,
inv_fun := λ x, ⟨x, h.symm ▸ x.2⟩,
left_inv := λ _, subtype.eq rfl,
right_inv := λ _, subtype.eq rfl }
/-- If `a ∉ s`, then `insert a s` is equivalent to `s ⊕ punit`. -/
protected def insert {α} {s : set.{u} α} [decidable_pred s] {a : α} (H : a ∉ s) :
(insert a s : set α) ≃ s ⊕ punit.{u+1} :=
calc (insert a s : set α) ≃ ↥(s ∪ {a}) : equiv.set.of_eq (by simp)
... ≃ s ⊕ ({a} : set α) : equiv.set.union (by finish [set.subset_def])
... ≃ s ⊕ punit.{u+1} : sum_congr (equiv.refl _) (equiv.set.singleton _)
@[simp] lemma insert_symm_apply_inl {α} {s : set.{u} α} [decidable_pred s] {a : α} (H : a ∉ s)
(b : s) : (equiv.set.insert H).symm (sum.inl b) = ⟨b, or.inr b.2⟩ :=
rfl
@[simp] lemma insert_symm_apply_inr {α} {s : set.{u} α} [decidable_pred s] {a : α} (H : a ∉ s)
(b : punit.{u+1}) : (equiv.set.insert H).symm (sum.inr b) = ⟨a, or.inl rfl⟩ :=
rfl
@[simp] lemma insert_apply_left {α} {s : set.{u} α} [decidable_pred s] {a : α} (H : a ∉ s) :
equiv.set.insert H ⟨a, or.inl rfl⟩ = sum.inr punit.star :=
(equiv.set.insert H).apply_eq_iff_eq_symm_apply.2 rfl
@[simp] lemma insert_apply_right {α} {s : set.{u} α} [decidable_pred s] {a : α} (H : a ∉ s)
(b : s) : equiv.set.insert H ⟨b, or.inr b.2⟩ = sum.inl b :=
(equiv.set.insert H).apply_eq_iff_eq_symm_apply.2 rfl
/-- If `s : set α` is a set with decidable membership, then `s ⊕ sᶜ` is equivalent to `α`. -/
protected def sum_compl {α} (s : set α) [decidable_pred s] : s ⊕ (sᶜ : set α) ≃ α :=
calc s ⊕ (sᶜ : set α) ≃ ↥(s ∪ sᶜ) : (equiv.set.union (by simp [set.ext_iff])).symm
... ≃ @univ α : equiv.set.of_eq (by simp)
... ≃ α : equiv.set.univ _
@[simp] lemma sum_compl_apply_inl {α : Type u} (s : set α) [decidable_pred s] (x : s) :
equiv.set.sum_compl s (sum.inl x) = x := rfl
@[simp] lemma sum_compl_apply_inr {α : Type u} (s : set α) [decidable_pred s] (x : sᶜ) :
equiv.set.sum_compl s (sum.inr x) = x := rfl
lemma sum_compl_symm_apply_of_mem {α : Type u} {s : set α} [decidable_pred s] {x : α}
(hx : x ∈ s) : (equiv.set.sum_compl s).symm x = sum.inl ⟨x, hx⟩ :=
have ↑(⟨x, or.inl hx⟩ : (s ∪ sᶜ : set α)) ∈ s, from hx,
by { rw [equiv.set.sum_compl], simpa using set.union_apply_left _ this }
lemma sum_compl_symm_apply_of_not_mem {α : Type u} {s : set α} [decidable_pred s] {x : α}
(hx : x ∉ s) : (equiv.set.sum_compl s).symm x = sum.inr ⟨x, hx⟩ :=
have ↑(⟨x, or.inr hx⟩ : (s ∪ sᶜ : set α)) ∈ sᶜ, from hx,
by { rw [equiv.set.sum_compl], simpa using set.union_apply_right _ this }
@[simp] lemma sum_compl_symm_apply {α : Type*} {s : set α} [decidable_pred s] {x : s} :
(equiv.set.sum_compl s).symm x = sum.inl x :=
by cases x with x hx; exact set.sum_compl_symm_apply_of_mem hx
@[simp] lemma sum_compl_symm_apply_compl {α : Type*} {s : set α}
[decidable_pred s] {x : sᶜ} : (equiv.set.sum_compl s).symm x = sum.inr x :=
by cases x with x hx; exact set.sum_compl_symm_apply_of_not_mem hx
/-- `sum_diff_subset s t` is the natural equivalence between
`s ⊕ (t \ s)` and `t`, where `s` and `t` are two sets. -/
protected def sum_diff_subset {α} {s t : set α} (h : s ⊆ t) [decidable_pred s] :
s ⊕ (t \ s : set α) ≃ t :=
calc s ⊕ (t \ s : set α) ≃ (s ∪ (t \ s) : set α) :
(equiv.set.union (by simp [inter_diff_self])).symm
... ≃ t : equiv.set.of_eq (by { simp [union_diff_self, union_eq_self_of_subset_left h] })
@[simp] lemma sum_diff_subset_apply_inl
{α} {s t : set α} (h : s ⊆ t) [decidable_pred s] (x : s) :
equiv.set.sum_diff_subset h (sum.inl x) = inclusion h x := rfl
@[simp] lemma sum_diff_subset_apply_inr
{α} {s t : set α} (h : s ⊆ t) [decidable_pred s] (x : t \ s) :
equiv.set.sum_diff_subset h (sum.inr x) = inclusion (diff_subset t s) x := rfl
lemma sum_diff_subset_symm_apply_of_mem
{α} {s t : set α} (h : s ⊆ t) [decidable_pred s] {x : t} (hx : x.1 ∈ s) :
(equiv.set.sum_diff_subset h).symm x = sum.inl ⟨x, hx⟩ :=
begin
apply (equiv.set.sum_diff_subset h).injective,
simp only [apply_symm_apply, sum_diff_subset_apply_inl],
exact subtype.eq rfl,
end
lemma sum_diff_subset_symm_apply_of_not_mem
{α} {s t : set α} (h : s ⊆ t) [decidable_pred s] {x : t} (hx : x.1 ∉ s) :
(equiv.set.sum_diff_subset h).symm x = sum.inr ⟨x, ⟨x.2, hx⟩⟩ :=
begin
apply (equiv.set.sum_diff_subset h).injective,
simp only [apply_symm_apply, sum_diff_subset_apply_inr],
exact subtype.eq rfl,
end
/-- If `s` is a set with decidable membership, then the sum of `s ∪ t` and `s ∩ t` is equivalent
to `s ⊕ t`. -/
protected def union_sum_inter {α : Type u} (s t : set α) [decidable_pred s] :
(s ∪ t : set α) ⊕ (s ∩ t : set α) ≃ s ⊕ t :=
calc (s ∪ t : set α) ⊕ (s ∩ t : set α)
≃ (s ∪ t \ s : set α) ⊕ (s ∩ t : set α) : by rw [union_diff_self]
... ≃ (s ⊕ (t \ s : set α)) ⊕ (s ∩ t : set α) :
sum_congr (set.union $ subset_empty_iff.2 (inter_diff_self _ _)) (equiv.refl _)
... ≃ s ⊕ (t \ s : set α) ⊕ (s ∩ t : set α) : sum_assoc _ _ _
... ≃ s ⊕ (t \ s ∪ s ∩ t : set α) : sum_congr (equiv.refl _) begin
refine (set.union' (∉ s) _ _).symm,
exacts [λ x hx, hx.2, λ x hx, not_not_intro hx.1]
end
... ≃ s ⊕ t : by { rw (_ : t \ s ∪ s ∩ t = t), rw [union_comm, inter_comm, inter_union_diff] }
/-- Given an equivalence `e₀` between sets `s : set α` and `t : set β`, the set of equivalences
`e : α ≃ β` such that `e ↑x = ↑(e₀ x)` for each `x : s` is equivalent to the set of equivalences
between `sᶜ` and `tᶜ`. -/
protected def compl {α : Type u} {β : Type v} {s : set α} {t : set β} [decidable_pred s]
[decidable_pred t] (e₀ : s ≃ t) :
{e : α ≃ β // ∀ x : s, e x = e₀ x} ≃ ((sᶜ : set α) ≃ (tᶜ : set β)) :=
{ to_fun := λ e, subtype_equiv e
(λ a, not_congr $ iff.symm $ maps_to.mem_iff
(maps_to_iff_exists_map_subtype.2 ⟨e₀, e.2⟩)
(surj_on.maps_to_compl (surj_on_iff_exists_map_subtype.2
⟨t, e₀, subset.refl t, e₀.surjective, e.2⟩) e.1.injective)),
inv_fun := λ e₁,
subtype.mk
(calc α ≃ s ⊕ (sᶜ : set α) : (set.sum_compl s).symm
... ≃ t ⊕ (tᶜ : set β) : e₀.sum_congr e₁
... ≃ β : set.sum_compl t)
(λ x, by simp only [sum.map_inl, trans_apply, sum_congr_apply,
set.sum_compl_apply_inl, set.sum_compl_symm_apply]),
left_inv := λ e,
begin
ext x,
by_cases hx : x ∈ s,
{ simp only [set.sum_compl_symm_apply_of_mem hx, ←e.prop ⟨x, hx⟩,
sum.map_inl, sum_congr_apply, trans_apply,
subtype.coe_mk, set.sum_compl_apply_inl] },
{ simp only [set.sum_compl_symm_apply_of_not_mem hx, sum.map_inr,
subtype_equiv_apply, set.sum_compl_apply_inr, trans_apply,
sum_congr_apply, subtype.coe_mk] },
end,
right_inv := λ e, equiv.ext $ λ x, by simp only [sum.map_inr, subtype_equiv_apply,
set.sum_compl_apply_inr, function.comp_app, sum_congr_apply, equiv.coe_trans,
subtype.coe_eta, subtype.coe_mk, set.sum_compl_symm_apply_compl] }
/-- The set product of two sets is equivalent to the type product of their coercions to types. -/
protected def prod {α β} (s : set α) (t : set β) :
s.prod t ≃ s × t :=
@subtype_prod_equiv_prod α β s t
/-- If a function `f` is injective on a set `s`, then `s` is equivalent to `f '' s`. -/
protected noncomputable def image_of_inj_on {α β} (f : α → β) (s : set α) (H : inj_on f s) :
s ≃ (f '' s) :=
⟨λ p, ⟨f p, mem_image_of_mem f p.2⟩,
λ p, ⟨classical.some p.2, (classical.some_spec p.2).1⟩,
λ ⟨x, h⟩, subtype.eq (H (classical.some_spec (mem_image_of_mem f h)).1 h
(classical.some_spec (mem_image_of_mem f h)).2),
λ ⟨y, h⟩, subtype.eq (classical.some_spec h).2⟩
/-- If `f` is an injective function, then `s` is equivalent to `f '' s`. -/
@[simps apply]
protected noncomputable def image {α β} (f : α → β) (s : set α) (H : injective f) : s ≃ (f '' s) :=
equiv.set.image_of_inj_on f s (H.inj_on s)
lemma image_symm_preimage {α β} {f : α → β} (hf : injective f) (u s : set α) :
(λ x, (set.image f s hf).symm x : f '' s → α) ⁻¹' u = coe ⁻¹' (f '' u) :=
begin
ext ⟨b, a, has, rfl⟩,
have : ∀(h : ∃a', a' ∈ s ∧ a' = a), classical.some h = a := λ h, (classical.some_spec h).2,
simp [equiv.set.image, equiv.set.image_of_inj_on, hf.eq_iff, this],
end
/-- If `α` is equivalent to `β`, then `set α` is equivalent to `set β`. -/
@[simps]
protected def congr {α β : Type*} (e : α ≃ β) : set α ≃ set β :=
⟨λ s, e '' s, λ t, e.symm '' t, symm_image_image e, symm_image_image e.symm⟩
/-- The set `{x ∈ s | t x}` is equivalent to the set of `x : s` such that `t x`. -/
protected def sep {α : Type u} (s : set α) (t : α → Prop) :
({ x ∈ s | t x } : set α) ≃ { x : s | t x } :=
(equiv.subtype_subtype_equiv_subtype_inter s t).symm
/-- The set `𝒫 S := {x | x ⊆ S}` is equivalent to the type `set S`. -/
protected def powerset {α} (S : set α) : 𝒫 S ≃ set S :=
{ to_fun := λ x : 𝒫 S, coe ⁻¹' (x : set α),
inv_fun := λ x : set S, ⟨coe '' x, by rintro _ ⟨a : S, _, rfl⟩; exact a.2⟩,
left_inv := λ x, by ext y; exact ⟨λ ⟨⟨_, _⟩, h, rfl⟩, h, λ h, ⟨⟨_, x.2 h⟩, h, rfl⟩⟩,
right_inv := λ x, by ext; simp }
end set
/-- If `f : α → β` has a left-inverse when `α` is nonempty, then `α` is computably equivalent to the
range of `f`.
While awkward, the `nonempty α` hypothesis on `f_inv` and `hf` allows this to be used when `α` is
empty too. This hypothesis is absent on analogous definitions on stronger `equiv`s like
`linear_equiv.of_left_inverse` and `ring_equiv.of_left_inverse` as their typeclass assumptions
are already sufficient to ensure non-emptiness. -/
@[simps]
def of_left_inverse {α β : Sort*}
(f : α → β) (f_inv : nonempty α → β → α) (hf : Π h : nonempty α, left_inverse (f_inv h) f) :
α ≃ set.range f :=
{ to_fun := λ a, ⟨f a, a, rfl⟩,
inv_fun := λ b, f_inv (nonempty_of_exists b.2) b,
left_inv := λ a, hf ⟨a⟩ a,
right_inv := λ ⟨b, a, ha⟩, subtype.eq $ show f (f_inv ⟨a⟩ b) = b,
from eq.trans (congr_arg f $ by exact ha ▸ (hf _ a)) ha }
/-- If `f : α → β` has a left-inverse, then `α` is computably equivalent to the range of `f`.
Note that if `α` is empty, no such `f_inv` exists and so this definition can't be used, unlike
the stronger but less convenient `of_left_inverse`. -/
abbreviation of_left_inverse' {α β : Sort*}
(f : α → β) (f_inv : β → α) (hf : left_inverse f_inv f) :
α ≃ set.range f :=
of_left_inverse f (λ _, f_inv) (λ _, hf)
/-- If `f : α → β` is an injective function, then domain `α` is equivalent to the range of `f`. -/
@[simps apply]
noncomputable def of_injective {α β} (f : α → β) (hf : injective f) : α ≃ set.range f :=
equiv.of_left_inverse f
(λ h, by exactI function.inv_fun f) (λ h, by exactI function.left_inverse_inv_fun hf)
theorem apply_of_injective_symm {α β} (f : α → β) (hf : injective f) (b : set.range f) :
f ((of_injective f hf).symm b) = b :=
subtype.ext_iff.1 $ (of_injective f hf).apply_symm_apply b
@[simp] lemma self_comp_of_injective_symm {α β} (f : α → β) (hf : injective f) :
f ∘ ((of_injective f hf).symm) = coe :=
funext (λ x, apply_of_injective_symm f hf x)
lemma of_left_inverse_eq_of_injective {α β : Type*}
(f : α → β) (f_inv : nonempty α → β → α) (hf : Π h : nonempty α, left_inverse (f_inv h) f) :
of_left_inverse f f_inv hf = of_injective f
((em (nonempty α)).elim (λ h, (hf h).injective) (λ h _ _ _, by {
haveI : subsingleton α := subsingleton_of_not_nonempty h, simp })) :=
by { ext, simp }
lemma of_left_inverse'_eq_of_injective {α β : Type*}
(f : α → β) (f_inv : β → α) (hf : left_inverse f_inv f) :
of_left_inverse' f f_inv hf = of_injective f hf.injective :=
by { ext, simp }
/-- If `f` is a bijective function, then its domain is equivalent to its codomain. -/
@[simps apply]
noncomputable def of_bijective {α β} (f : α → β) (hf : bijective f) : α ≃ β :=
(of_injective f hf.1).trans $ (set_congr hf.2.range_eq).trans $ equiv.set.univ β
lemma of_bijective_apply_symm_apply {α β} (f : α → β) (hf : bijective f) (x : β) :
f ((of_bijective f hf).symm x) = x :=
(of_bijective f hf).apply_symm_apply x
@[simp] lemma of_bijective_symm_apply_apply {α β} (f : α → β) (hf : bijective f) (x : α) :
(of_bijective f hf).symm (f x) = x :=
(of_bijective f hf).symm_apply_apply x
section
variables {α' β' : Type*} (e : perm α') {p : β' → Prop} [decidable_pred p]
(f : α' ≃ subtype p)
/--
Extend the domain of `e : equiv.perm α` to one that is over `β` via `f : α → subtype p`,
where `p : β → Prop`, permuting only the `b : β` that satisfy `p b`.
This can be used to extend the domain across a function `f : α → β`,
keeping everything outside of `set.range f` fixed. For this use-case `equiv` given by `f` can
be constructed by `equiv.of_left_inverse'` or `equiv.of_left_inverse` when there is a known
inverse, or `equiv.of_injective` in the general case.`.
-/
def perm.extend_domain : perm β' :=
(perm_congr f e).subtype_congr (equiv.refl _)
@[simp] lemma perm.extend_domain_apply_image (a : α') :
e.extend_domain f (f a) = f (e a) :=
by simp [perm.extend_domain]
lemma perm.extend_domain_apply_subtype {b : β'} (h : p b) :
e.extend_domain f b = f (e (f.symm ⟨b, h⟩)) :=
by simp [perm.extend_domain, h]
lemma perm.extend_domain_apply_not_subtype {b : β'} (h : ¬ p b) :
e.extend_domain f b = b :=
by simp [perm.extend_domain, h]
@[simp] lemma perm.extend_domain_refl : perm.extend_domain (equiv.refl _) f = equiv.refl _ :=
by simp [perm.extend_domain]
@[simp] lemma perm.extend_domain_symm :
(e.extend_domain f).symm = perm.extend_domain e.symm f := rfl
lemma perm.extend_domain_trans (e e' : perm α') :
(e.extend_domain f).trans (e'.extend_domain f) = perm.extend_domain (e.trans e') f :=
by simp [perm.extend_domain, perm_congr_trans]
end
/-- Subtype of the quotient is equivalent to the quotient of the subtype. Let `α` be a setoid with
equivalence relation `~`. Let `p₂` be a predicate on the quotient type `α/~`, and `p₁` be the lift
of this predicate to `α`: `p₁ a ↔ p₂ ⟦a⟧`. Let `~₂` be the restriction of `~` to `{x // p₁ x}`.
Then `{x // p₂ x}` is equivalent to the quotient of `{x // p₁ x}` by `~₂`. -/
def subtype_quotient_equiv_quotient_subtype (p₁ : α → Prop) [s₁ : setoid α]
[s₂ : setoid (subtype p₁)] (p₂ : quotient s₁ → Prop) (hp₂ : ∀ a, p₁ a ↔ p₂ ⟦a⟧)
(h : ∀ x y : subtype p₁, @setoid.r _ s₂ x y ↔ (x : α) ≈ y) :
{x // p₂ x} ≃ quotient s₂ :=
{ to_fun := λ a, quotient.hrec_on a.1 (λ a h, ⟦⟨a, (hp₂ _).2 h⟩⟧)
(λ a b hab, hfunext (by rw quotient.sound hab)
(λ h₁ h₂ _, heq_of_eq (quotient.sound ((h _ _).2 hab)))) a.2,
inv_fun := λ a, quotient.lift_on a (λ a, (⟨⟦a.1⟧, (hp₂ _).1 a.2⟩ : {x // p₂ x}))
(λ a b hab, subtype.ext_val (quotient.sound ((h _ _).1 hab))),
left_inv := λ ⟨a, ha⟩, quotient.induction_on a (λ a ha, rfl) ha,
right_inv := λ a, quotient.induction_on a (λ ⟨a, ha⟩, rfl) }
section swap
variable [decidable_eq α]
/-- A helper function for `equiv.swap`. -/
def swap_core (a b r : α) : α :=
if r = a then b
else if r = b then a
else r
theorem swap_core_self (r a : α) : swap_core a a r = r :=
by { unfold swap_core, split_ifs; cc }
theorem swap_core_swap_core (r a b : α) : swap_core a b (swap_core a b r) = r :=
by { unfold swap_core, split_ifs; cc }
theorem swap_core_comm (r a b : α) : swap_core a b r = swap_core b a r :=
by { unfold swap_core, split_ifs; cc }
/-- `swap a b` is the permutation that swaps `a` and `b` and
leaves other values as is. -/
def swap (a b : α) : perm α :=
⟨swap_core a b, swap_core a b, λr, swap_core_swap_core r a b, λr, swap_core_swap_core r a b⟩
@[simp] theorem swap_self (a : α) : swap a a = equiv.refl _ :=
ext $ λ r, swap_core_self r a
theorem swap_comm (a b : α) : swap a b = swap b a :=
ext $ λ r, swap_core_comm r _ _
theorem swap_apply_def (a b x : α) : swap a b x = if x = a then b else if x = b then a else x :=
rfl
@[simp] theorem swap_apply_left (a b : α) : swap a b a = b :=
if_pos rfl
@[simp] theorem swap_apply_right (a b : α) : swap a b b = a :=
by { by_cases h : b = a; simp [swap_apply_def, h], }
theorem swap_apply_of_ne_of_ne {a b x : α} : x ≠ a → x ≠ b → swap a b x = x :=
by simp [swap_apply_def] {contextual := tt}
@[simp] theorem swap_swap (a b : α) : (swap a b).trans (swap a b) = equiv.refl _ :=
ext $ λ x, swap_core_swap_core _ _ _
@[simp] lemma symm_swap (a b : α) : (swap a b).symm = swap a b := rfl
@[simp] lemma swap_eq_refl_iff {x y : α} : swap x y = equiv.refl _ ↔ x = y :=
begin
refine ⟨λ h, (equiv.refl _).injective _, λ h, h ▸ (swap_self _)⟩,
rw [←h, swap_apply_left, h, refl_apply]
end
theorem swap_comp_apply {a b x : α} (π : perm α) :
π.trans (swap a b) x = if π x = a then b else if π x = b then a else π x :=
by { cases π, refl }
lemma swap_eq_update (i j : α) :
⇑(equiv.swap i j) = update (update id j i) i j :=
funext $ λ x, by rw [update_apply _ i j, update_apply _ j i, equiv.swap_apply_def, id.def]
lemma comp_swap_eq_update (i j : α) (f : α → β) :
f ∘ equiv.swap i j = update (update f j (f i)) i (f j) :=
by rw [swap_eq_update, comp_update, comp_update, comp.right_id]
@[simp] lemma symm_trans_swap_trans [decidable_eq β] (a b : α) (e : α ≃ β) :
(e.symm.trans (swap a b)).trans e = swap (e a) (e b) :=
equiv.ext (λ x, begin
have : ∀ a, e.symm x = a ↔ x = e a :=
λ a, by { rw @eq_comm _ (e.symm x), split; intros; simp * at * },
simp [swap_apply_def, this],
split_ifs; simp
end)
@[simp] lemma trans_swap_trans_symm [decidable_eq β] (a b : β)
(e : α ≃ β) : (e.trans (swap a b)).trans e.symm = swap (e.symm a) (e.symm b) :=
symm_trans_swap_trans a b e.symm
@[simp] lemma swap_apply_self (i j a : α) :
swap i j (swap i j a) = a :=
by rw [← equiv.trans_apply, equiv.swap_swap, equiv.refl_apply]
/-- A function is invariant to a swap if it is equal at both elements -/
lemma apply_swap_eq_self {v : α → β} {i j : α} (hv : v i = v j) (k : α) : v (swap i j k) = v k :=
begin
by_cases hi : k = i, { rw [hi, swap_apply_left, hv] },
by_cases hj : k = j, { rw [hj, swap_apply_right, hv] },
rw swap_apply_of_ne_of_ne hi hj,
end
lemma swap_apply_eq_iff {x y z w : α} :
swap x y z = w ↔ z = swap x y w :=
by rw [apply_eq_iff_eq_symm_apply, symm_swap]
namespace perm
@[simp] lemma sum_congr_swap_refl {α β : Sort*} [decidable_eq α] [decidable_eq β] (i j : α) :
equiv.perm.sum_congr (equiv.swap i j) (equiv.refl β) = equiv.swap (sum.inl i) (sum.inl j) :=
begin
ext x,
cases x,
{ simp [sum.map, swap_apply_def],
split_ifs; refl},
{ simp [sum.map, swap_apply_of_ne_of_ne] },
end
@[simp] lemma sum_congr_refl_swap {α β : Sort*} [decidable_eq α] [decidable_eq β] (i j : β) :
equiv.perm.sum_congr (equiv.refl α) (equiv.swap i j) = equiv.swap (sum.inr i) (sum.inr j) :=
begin
ext x,
cases x,
{ simp [sum.map, swap_apply_of_ne_of_ne] },
{ simp [sum.map, swap_apply_def],
split_ifs; refl},
end
end perm
/-- Augment an equivalence with a prescribed mapping `f a = b` -/
def set_value (f : α ≃ β) (a : α) (b : β) : α ≃ β :=
(swap a (f.symm b)).trans f
@[simp] theorem set_value_eq (f : α ≃ β) (a : α) (b : β) : set_value f a b a = b :=
by { dsimp [set_value], simp [swap_apply_left] }
end swap
end equiv
lemma function.injective.map_swap {α β : Type*} [decidable_eq α] [decidable_eq β]
{f : α → β} (hf : function.injective f) (x y z : α) :
f (equiv.swap x y z) = equiv.swap (f x) (f y) (f z) :=
begin
conv_rhs { rw equiv.swap_apply_def },
split_ifs with h₁ h₂,
{ rw [hf h₁, equiv.swap_apply_left] },
{ rw [hf h₂, equiv.swap_apply_right] },
{ rw [equiv.swap_apply_of_ne_of_ne (mt (congr_arg f) h₁) (mt (congr_arg f) h₂)] }
end
namespace equiv
protected lemma exists_unique_congr {p : α → Prop} {q : β → Prop} (f : α ≃ β)
(h : ∀{x}, p x ↔ q (f x)) : (∃! x, p x) ↔ ∃! y, q y :=
begin
split,
{ rintro ⟨a, ha₁, ha₂⟩,
exact ⟨f a, h.1 ha₁, λ b hb, f.symm_apply_eq.1 (ha₂ (f.symm b) (h.2 (by simpa using hb)))⟩ },
{ rintro ⟨b, hb₁, hb₂⟩,
exact ⟨f.symm b, h.2 (by simpa using hb₁), λ y hy, (eq_symm_apply f).2 (hb₂ _ (h.1 hy))⟩ }
end
protected lemma exists_unique_congr_left' {p : α → Prop} (f : α ≃ β) :
(∃! x, p x) ↔ (∃! y, p (f.symm y)) :=
equiv.exists_unique_congr f (λx, by simp)
protected lemma exists_unique_congr_left {p : β → Prop} (f : α ≃ β) :
(∃! x, p (f x)) ↔ (∃! y, p y) :=
(equiv.exists_unique_congr_left' f.symm).symm
protected lemma forall_congr {p : α → Prop} {q : β → Prop} (f : α ≃ β)
(h : ∀{x}, p x ↔ q (f x)) : (∀x, p x) ↔ (∀y, q y) :=
begin
split; intros h₂ x,
{ rw [←f.right_inv x], apply h.mp, apply h₂ },
apply h.mpr, apply h₂
end
protected lemma forall_congr' {p : α → Prop} {q : β → Prop} (f : α ≃ β)
(h : ∀{x}, p (f.symm x) ↔ q x) : (∀x, p x) ↔ (∀y, q y) :=
(equiv.forall_congr f.symm (λ x, h.symm)).symm
-- We next build some higher arity versions of `equiv.forall_congr`.
-- Although they appear to just be repeated applications of `equiv.forall_congr`,
-- unification of metavariables works better with these versions.
-- In particular, they are necessary in `equiv_rw`.
-- (Stopping at ternary functions seems reasonable: at least in 1-categorical mathematics,
-- it's rare to have axioms involving more than 3 elements at once.)
universes ua1 ua2 ub1 ub2 ug1 ug2
variables {α₁ : Sort ua1} {α₂ : Sort ua2}
{β₁ : Sort ub1} {β₂ : Sort ub2}
{γ₁ : Sort ug1} {γ₂ : Sort ug2}
protected lemma forall₂_congr {p : α₁ → β₁ → Prop} {q : α₂ → β₂ → Prop} (eα : α₁ ≃ α₂)
(eβ : β₁ ≃ β₂) (h : ∀{x y}, p x y ↔ q (eα x) (eβ y)) :
(∀x y, p x y) ↔ (∀x y, q x y) :=
begin
apply equiv.forall_congr,
intros,
apply equiv.forall_congr,
intros,
apply h,
end
protected lemma forall₂_congr' {p : α₁ → β₁ → Prop} {q : α₂ → β₂ → Prop} (eα : α₁ ≃ α₂)
(eβ : β₁ ≃ β₂) (h : ∀{x y}, p (eα.symm x) (eβ.symm y) ↔ q x y) :
(∀x y, p x y) ↔ (∀x y, q x y) :=
(equiv.forall₂_congr eα.symm eβ.symm (λ x y, h.symm)).symm
protected lemma forall₃_congr {p : α₁ → β₁ → γ₁ → Prop} {q : α₂ → β₂ → γ₂ → Prop}
(eα : α₁ ≃ α₂) (eβ : β₁ ≃ β₂) (eγ : γ₁ ≃ γ₂)
(h : ∀{x y z}, p x y z ↔ q (eα x) (eβ y) (eγ z)) : (∀x y z, p x y z) ↔ (∀x y z, q x y z) :=
begin
apply equiv.forall₂_congr,
intros,
apply equiv.forall_congr,
intros,
apply h,
end
protected lemma forall₃_congr' {p : α₁ → β₁ → γ₁ → Prop} {q : α₂ → β₂ → γ₂ → Prop}
(eα : α₁ ≃ α₂) (eβ : β₁ ≃ β₂) (eγ : γ₁ ≃ γ₂)
(h : ∀{x y z}, p (eα.symm x) (eβ.symm y) (eγ.symm z) ↔ q x y z) :
(∀x y z, p x y z) ↔ (∀x y z, q x y z) :=
(equiv.forall₃_congr eα.symm eβ.symm eγ.symm (λ x y z, h.symm)).symm
protected lemma forall_congr_left' {p : α → Prop} (f : α ≃ β) :
(∀x, p x) ↔ (∀y, p (f.symm y)) :=
equiv.forall_congr f (λx, by simp)
protected lemma forall_congr_left {p : β → Prop} (f : α ≃ β) :
(∀x, p (f x)) ↔ (∀y, p y) :=
(equiv.forall_congr_left' f.symm).symm
protected lemma exists_congr_left {α β} (f : α ≃ β) {p : α → Prop} :
(∃ a, p a) ↔ (∃ b, p (f.symm b)) :=
⟨λ ⟨a, h⟩, ⟨f a, by simpa using h⟩, λ ⟨b, h⟩, ⟨_, h⟩⟩
protected lemma set_forall_iff {α β} (e : α ≃ β) {p : set α → Prop} :
(∀ a, p a) ↔ (∀ a, p (e ⁻¹' a)) :=
by simpa [equiv.image_eq_preimage] using (equiv.set.congr e).forall_congr_left'
protected lemma preimage_sUnion {α β} (f : α ≃ β) {s : set (set β)} :
f ⁻¹' (⋃₀ s) = ⋃₀ (_root_.set.image f ⁻¹' s) :=
by { ext x, simp [(equiv.set.congr f).symm.exists_congr_left] }
section
variables (P : α → Sort w) (e : α ≃ β)
/--
Transport dependent functions through an equivalence of the base space.
-/
@[simps] def Pi_congr_left' : (Π a, P a) ≃ (Π b, P (e.symm b)) :=
{ to_fun := λ f x, f (e.symm x),
inv_fun := λ f x, begin rw [← e.symm_apply_apply x], exact f (e x) end,
left_inv := λ f, funext $ λ x, eq_of_heq ((eq_rec_heq _ _).trans
(by { dsimp, rw e.symm_apply_apply })),
right_inv := λ f, funext $ λ x, eq_of_heq ((eq_rec_heq _ _).trans
(by { rw e.apply_symm_apply })) }
end
section
variables (P : β → Sort w) (e : α ≃ β)
/--
Transporting dependent functions through an equivalence of the base,
expressed as a "simplification".
-/
def Pi_congr_left : (Π a, P (e a)) ≃ (Π b, P b) :=
(Pi_congr_left' P e.symm).symm
end
section
variables
{W : α → Sort w} {Z : β → Sort z} (h₁ : α ≃ β) (h₂ : Π a : α, (W a ≃ Z (h₁ a)))
/--
Transport dependent functions through
an equivalence of the base spaces and a family
of equivalences of the matching fibers.
-/
def Pi_congr : (Π a, W a) ≃ (Π b, Z b) :=
(equiv.Pi_congr_right h₂).trans (equiv.Pi_congr_left _ h₁)
end
section
variables
{W : α → Sort w} {Z : β → Sort z} (h₁ : α ≃ β) (h₂ : Π b : β, (W (h₁.symm b) ≃ Z b))
/--
Transport dependent functions through
an equivalence of the base spaces and a family
of equivalences of the matching fibres.
-/
def Pi_congr' : (Π a, W a) ≃ (Π b, Z b) :=
(Pi_congr h₁.symm (λ b, (h₂ b).symm)).symm
end
end equiv
lemma function.injective.swap_apply [decidable_eq α] [decidable_eq β] {f : α → β}
(hf : function.injective f) (x y z : α) :
equiv.swap (f x) (f y) (f z) = f (equiv.swap x y z) :=
begin
by_cases hx : z = x, by simp [hx],
by_cases hy : z = y, by simp [hy],
rw [equiv.swap_apply_of_ne_of_ne hx hy, equiv.swap_apply_of_ne_of_ne (hf.ne hx) (hf.ne hy)]
end
lemma function.injective.swap_comp [decidable_eq α] [decidable_eq β] {f : α → β}
(hf : function.injective f) (x y : α) :
equiv.swap (f x) (f y) ∘ f = f ∘ equiv.swap x y :=
funext $ λ z, hf.swap_apply _ _ _
instance {α} [subsingleton α] : subsingleton (ulift α) := equiv.ulift.subsingleton
instance {α} [subsingleton α] : subsingleton (plift α) := equiv.plift.subsingleton
instance {α} [unique α] : unique (ulift α) := equiv.ulift.unique
instance {α} [unique α] : unique (plift α) := equiv.plift.unique
instance {α} [decidable_eq α] : decidable_eq (ulift α) := equiv.ulift.decidable_eq
instance {α} [decidable_eq α] : decidable_eq (plift α) := equiv.plift.decidable_eq
/-- If both `α` and `β` are singletons, then `α ≃ β`. -/
def equiv_of_unique_of_unique [unique α] [unique β] : α ≃ β :=
{ to_fun := λ _, default β,
inv_fun := λ _, default α,
left_inv := λ _, subsingleton.elim _ _,
right_inv := λ _, subsingleton.elim _ _ }
/-- If `α` is a singleton, then it is equivalent to any `punit`. -/
def equiv_punit_of_unique [unique α] : α ≃ punit.{v} :=
equiv_of_unique_of_unique
/-- If `α` is a subsingleton, then it is equivalent to `α × α`. -/
def subsingleton_prod_self_equiv {α : Type*} [subsingleton α] : α × α ≃ α :=
{ to_fun := λ p, p.1,
inv_fun := λ a, (a, a),
left_inv := λ p, subsingleton.elim _ _,
right_inv := λ p, subsingleton.elim _ _, }
/-- To give an equivalence between two subsingleton types, it is sufficient to give any two
functions between them. -/
def equiv_of_subsingleton_of_subsingleton [subsingleton α] [subsingleton β]
(f : α → β) (g : β → α) : α ≃ β :=
{ to_fun := f,
inv_fun := g,
left_inv := λ _, subsingleton.elim _ _,
right_inv := λ _, subsingleton.elim _ _ }
/-- A nonempty subsingleton type is (noncomputably) equivalent to `punit`. -/
noncomputable
def equiv.punit_of_nonempty_of_subsingleton {α : Sort*} [h : nonempty α] [subsingleton α] :
α ≃ punit.{v} :=
equiv_of_subsingleton_of_subsingleton
(λ _, punit.star) (λ _, h.some)
/-- `unique (unique α)` is equivalent to `unique α`. -/
def unique_unique_equiv : unique (unique α) ≃ unique α :=
equiv_of_subsingleton_of_subsingleton (λ h, h.default)
(λ h, { default := h, uniq := λ _, subsingleton.elim _ _ })
namespace quot
/-- An equivalence `e : α ≃ β` generates an equivalence between quotient spaces,
if `ra a₁ a₂ ↔ rb (e a₁) (e a₂). -/
protected def congr {ra : α → α → Prop} {rb : β → β → Prop} (e : α ≃ β)
(eq : ∀a₁ a₂, ra a₁ a₂ ↔ rb (e a₁) (e a₂)) :
quot ra ≃ quot rb :=
{ to_fun := quot.map e (assume a₁ a₂, (eq a₁ a₂).1),
inv_fun := quot.map e.symm
(assume b₁ b₂ h,
(eq (e.symm b₁) (e.symm b₂)).2
((e.apply_symm_apply b₁).symm ▸ (e.apply_symm_apply b₂).symm ▸ h)),
left_inv := by { rintros ⟨a⟩, dunfold quot.map, simp only [equiv.symm_apply_apply] },
right_inv := by { rintros ⟨a⟩, dunfold quot.map, simp only [equiv.apply_symm_apply] } }
/-- Quotients are congruent on equivalences under equality of their relation.
An alternative is just to use rewriting with `eq`, but then computational proofs get stuck. -/
protected def congr_right {r r' : α → α → Prop} (eq : ∀a₁ a₂, r a₁ a₂ ↔ r' a₁ a₂) :
quot r ≃ quot r' :=
quot.congr (equiv.refl α) eq
/-- An equivalence `e : α ≃ β` generates an equivalence between the quotient space of `α`
by a relation `ra` and the quotient space of `β` by the image of this relation under `e`. -/
protected def congr_left {r : α → α → Prop} (e : α ≃ β) :
quot r ≃ quot (λ b b', r (e.symm b) (e.symm b')) :=
@quot.congr α β r (λ b b', r (e.symm b) (e.symm b')) e (λ a₁ a₂, by simp only [e.symm_apply_apply])
end quot
namespace quotient
/-- An equivalence `e : α ≃ β` generates an equivalence between quotient spaces,
if `ra a₁ a₂ ↔ rb (e a₁) (e a₂). -/
protected def congr {ra : setoid α} {rb : setoid β} (e : α ≃ β)
(eq : ∀a₁ a₂, @setoid.r α ra a₁ a₂ ↔ @setoid.r β rb (e a₁) (e a₂)) :
quotient ra ≃ quotient rb :=
quot.congr e eq
/-- Quotients are congruent on equivalences under equality of their relation.
An alternative is just to use rewriting with `eq`, but then computational proofs get stuck. -/
protected def congr_right {r r' : setoid α}
(eq : ∀a₁ a₂, @setoid.r α r a₁ a₂ ↔ @setoid.r α r' a₁ a₂) : quotient r ≃ quotient r' :=
quot.congr_right eq
end quotient
/-- If a function is a bijection between two sets `s` and `t`, then it induces an
equivalence between the the types `↥s` and ``↥t`. -/
noncomputable def set.bij_on.equiv {α : Type*} {β : Type*} {s : set α} {t : set β} (f : α → β)
(h : set.bij_on f s t) : s ≃ t :=
equiv.of_bijective _ h.bijective
namespace function
lemma update_comp_equiv {α β α' : Sort*} [decidable_eq α'] [decidable_eq α] (f : α → β) (g : α' ≃ α)
(a : α) (v : β) :
update f a v ∘ g = update (f ∘ g) (g.symm a) v :=
by rw [← update_comp_eq_of_injective _ g.injective, g.apply_symm_apply]
lemma update_apply_equiv_apply {α β α' : Sort*} [decidable_eq α'] [decidable_eq α]
(f : α → β) (g : α' ≃ α) (a : α) (v : β) (a' : α') :
update f a v (g a') = update (f ∘ g) (g.symm a) v a' :=
congr_fun (update_comp_equiv f g a v) a'
end function
/-- The composition of an updated function with an equiv on a subset can be expressed as an
updated function. -/
lemma dite_comp_equiv_update {α : Type*} {β : Sort*} {γ : Sort*} {s : set α} (e : β ≃ s)
(v : β → γ) (w : α → γ) (j : β) (x : γ) [decidable_eq β] [decidable_eq α]
[∀ j, decidable (j ∈ s)] :
(λ (i : α), if h : i ∈ s then (function.update v j x) (e.symm ⟨i, h⟩) else w i) =
function.update (λ (i : α), if h : i ∈ s then v (e.symm ⟨i, h⟩) else w i) (e j) x :=
begin
ext i,
by_cases h : i ∈ s,
{ rw [dif_pos h,
function.update_apply_equiv_apply, equiv.symm_symm, function.comp,
function.update_apply, function.update_apply,
dif_pos h],
have h_coe : (⟨i, h⟩ : s) = e j ↔ i = e j := subtype.ext_iff.trans (by rw subtype.coe_mk),
simp_rw h_coe,
congr, },
{ have : i ≠ e j,
by { contrapose! h, have : (e j : α) ∈ s := (e j).2, rwa ← h at this },
simp [h, this] }
end
|
7b3132a7f73a3e14c0f48df24a8fb65692e7ef6d | 5e3548e65f2c037cb94cd5524c90c623fbd6d46a | /src_icannos_totilas/applications_lineaires/cpge_applin_1_b.lean | 5424ff269158d295ffda245560fbdd8f224c490f | [] | no_license | ahayat16/lean_exos | d4f08c30adb601a06511a71b5ffb4d22d12ef77f | 682f2552d5b04a8c8eb9e4ab15f875a91b03845c | refs/heads/main | 1,693,101,073,585 | 1,636,479,336,000 | 1,636,479,336,000 | 415,000,441 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 292 | lean | import algebra.module.linear_map
import data.real.basic
def f (x y z : ℝ) : ℝ := x-z
theorem cpge_applin_1_b [module ℝ (prod ℝ (prod ℝ ℝ))] [E : set (prod ℝ ℝ)]:
∃ g : (linear_map ℝ (prod ℝ (prod ℝ ℝ)) ℝ),
∀ x y z : ℝ , (f x y z) = (g (x, y, z)) := sorry |
c9dd00a2468cde66be8f2b5fee1b36f3fe953b55 | 534c92d7322a8676cfd1583e26f5946134561b54 | /src/Exercises/01_Propositions/Q0104/S0004.lean | 815d208107ef34ed4b4ddbd3d67041a478488523 | [
"Apache-2.0"
] | permissive | kbuzzard/mathematics-in-lean | 53f387174f04d6077f434e27c407aee9425837f7 | 3fad7bb7e888dabef94921101af8671b78a4304a | refs/heads/master | 1,586,812,457,439 | 1,546,893,744,000 | 1,546,893,744,000 | 163,450,734 | 8 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 77 | lean | theorem P_implies_P (P : Prop) : P → P :=
begin
intro HP,
exact HP
end
|
6a9de4851d4156d6e0743b9d158f863ce1e38877 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/category_theory/limits/preserves/opposites.lean | 915b9945217fcb91f96f04198bcbc21ef643bc4e | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 12,112 | lean | /-
Copyright (c) 2022 Markus Himmel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Markus Himmel
-/
import category_theory.limits.opposites
import category_theory.limits.preserves.finite
/-!
# Limit preservation properties of `functor.op` and related constructions
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
We formulate conditions about `F` which imply that `F.op`, `F.unop`, `F.left_op` and `F.right_op`
preserve certain (co)limits.
## Future work
* Dually, it is possible to formulate conditions about `F.op` ec. for `F` to preserve certain
(co)limits.
-/
universes w w' v₁ v₂ u₁ u₂
noncomputable theory
open category_theory
namespace category_theory.limits
section
variables {C : Type u₁} [category.{v₁} C] {D : Type u₂} [category.{v₂} D]
variables {J : Type w} [category.{w'} J]
/-- If `F : C ⥤ D` preserves colimits of `K.left_op : Jᵒᵖ ⥤ C`, then `F.op : Cᵒᵖ ⥤ Dᵒᵖ` preserves
limits of `K : J ⥤ Cᵒᵖ`. -/
def preserves_limit_op (K : J ⥤ Cᵒᵖ) (F : C ⥤ D) [preserves_colimit K.left_op F] :
preserves_limit K F.op :=
{ preserves := λ c hc, is_limit_cone_right_op_of_cocone _
(is_colimit_of_preserves F (is_colimit_cocone_left_op_of_cone _ hc)) }
/-- If `F : C ⥤ Dᵒᵖ` preserves colimits of `K.left_op : Jᵒᵖ ⥤ C`, then `F.left_op : Cᵒᵖ ⥤ D`
preserves limits of `K : J ⥤ Cᵒᵖ`. -/
def preserves_limit_left_op (K : J ⥤ Cᵒᵖ) (F : C ⥤ Dᵒᵖ) [preserves_colimit K.left_op F] :
preserves_limit K F.left_op :=
{ preserves := λ c hc, is_limit_cone_unop_of_cocone _
(is_colimit_of_preserves F (is_colimit_cocone_left_op_of_cone _ hc)) }
/-- If `F : Cᵒᵖ ⥤ D` preserves colimits of `K.op : Jᵒᵖ ⥤ Cᵒᵖ`, then `F.right_op : C ⥤ Dᵒᵖ` preserves
limits of `K : J ⥤ C`. -/
def preserves_limit_right_op (K : J ⥤ C) (F : Cᵒᵖ ⥤ D) [preserves_colimit K.op F] :
preserves_limit K F.right_op :=
{ preserves := λ c hc, is_limit_cone_right_op_of_cocone _
(is_colimit_of_preserves F (is_colimit_cone_op _ hc)) }
/-- If `F : Cᵒᵖ ⥤ Dᵒᵖ` preserves colimits of `K.op : Jᵒᵖ ⥤ Cᵒᵖ`, then `F.unop : C ⥤ D` preserves
limits of `K : J ⥤ C`. -/
def preserves_limit_unop (K : J ⥤ C) (F : Cᵒᵖ ⥤ Dᵒᵖ) [preserves_colimit K.op F] :
preserves_limit K F.unop :=
{ preserves := λ c hc, is_limit_cone_unop_of_cocone _
(is_colimit_of_preserves F (is_colimit_cone_op _ hc)) }
/-- If `F : C ⥤ D` preserves limits of `K.left_op : Jᵒᵖ ⥤ C`, then `F.op : Cᵒᵖ ⥤ Dᵒᵖ` preserves
colimits of `K : J ⥤ Cᵒᵖ`. -/
def preserves_colimit_op (K : J ⥤ Cᵒᵖ) (F : C ⥤ D) [preserves_limit K.left_op F] :
preserves_colimit K F.op :=
{ preserves := λ c hc, is_colimit_cocone_right_op_of_cone _
(is_limit_of_preserves F (is_limit_cone_left_op_of_cocone _ hc)) }
/-- If `F : C ⥤ Dᵒᵖ` preserves limits of `K.left_op : Jᵒᵖ ⥤ C`, then `F.left_op : Cᵒᵖ ⥤ D` preserves
colimits of `K : J ⥤ Cᵒᵖ`. -/
def preserves_colimit_left_op (K : J ⥤ Cᵒᵖ) (F : C ⥤ Dᵒᵖ) [preserves_limit K.left_op F] :
preserves_colimit K F.left_op :=
{ preserves := λ c hc, is_colimit_cocone_unop_of_cone _
(is_limit_of_preserves F (is_limit_cone_left_op_of_cocone _ hc)) }
/-- If `F : Cᵒᵖ ⥤ D` preserves limits of `K.op : Jᵒᵖ ⥤ Cᵒᵖ`, then `F.right_op : C ⥤ Dᵒᵖ` preserves
colimits of `K : J ⥤ C`. -/
def preserves_colimit_right_op (K : J ⥤ C) (F : Cᵒᵖ ⥤ D) [preserves_limit K.op F] :
preserves_colimit K F.right_op :=
{ preserves := λ c hc, is_colimit_cocone_right_op_of_cone _
(is_limit_of_preserves F (is_limit_cocone_op _ hc)) }
/-- If `F : Cᵒᵖ ⥤ Dᵒᵖ` preserves limits of `K.op : Jᵒᵖ ⥤ Cᵒᵖ`, then `F.unop : C ⥤ D` preserves
colimits of `K : J ⥤ C`. -/
def preserves_colimit_unop (K : J ⥤ C) (F : Cᵒᵖ ⥤ Dᵒᵖ) [preserves_limit K.op F] :
preserves_colimit K F.unop :=
{ preserves := λ c hc, is_colimit_cocone_unop_of_cone _
(is_limit_of_preserves F (is_limit_cocone_op _ hc)) }
section
variables (J)
/-- If `F : C ⥤ D` preserves colimits of shape `Jᵒᵖ`, then `F.op : Cᵒᵖ ⥤ Dᵒᵖ` preserves limits of
shape `J`. -/
def preserves_limits_of_shape_op (F : C ⥤ D) [preserves_colimits_of_shape Jᵒᵖ F] :
preserves_limits_of_shape J F.op :=
{ preserves_limit := λ K, preserves_limit_op K F }
/-- If `F : C ⥤ Dᵒᵖ` preserves colimits of shape `Jᵒᵖ`, then `F.left_op : Cᵒᵖ ⥤ D` preserves limits
of shape `J`. -/
def preserves_limits_of_shape_left_op (F : C ⥤ Dᵒᵖ) [preserves_colimits_of_shape Jᵒᵖ F] :
preserves_limits_of_shape J F.left_op :=
{ preserves_limit := λ K, preserves_limit_left_op K F }
/-- If `F : Cᵒᵖ ⥤ D` preserves colimits of shape `Jᵒᵖ`, then `F.right_op : C ⥤ Dᵒᵖ` preserves limits
of shape `J`. -/
def preserves_limits_of_shape_right_op (F : Cᵒᵖ ⥤ D) [preserves_colimits_of_shape Jᵒᵖ F] :
preserves_limits_of_shape J F.right_op :=
{ preserves_limit := λ K, preserves_limit_right_op K F }
/-- If `F : Cᵒᵖ ⥤ Dᵒᵖ` preserves colimits of shape `Jᵒᵖ`, then `F.unop : C ⥤ D` preserves limits of
shape `J`. -/
def preserves_limits_of_shape_unop (F : Cᵒᵖ ⥤ Dᵒᵖ) [preserves_colimits_of_shape Jᵒᵖ F] :
preserves_limits_of_shape J F.unop :=
{ preserves_limit := λ K, preserves_limit_unop K F }
/-- If `F : C ⥤ D` preserves limits of shape `Jᵒᵖ`, then `F.op : Cᵒᵖ ⥤ Dᵒᵖ` preserves colimits of
shape `J`. -/
def preserves_colimits_of_shape_op (F : C ⥤ D) [preserves_limits_of_shape Jᵒᵖ F] :
preserves_colimits_of_shape J F.op :=
{ preserves_colimit := λ K, preserves_colimit_op K F }
/-- If `F : C ⥤ Dᵒᵖ` preserves limits of shape `Jᵒᵖ`, then `F.left_op : Cᵒᵖ ⥤ D` preserves colimits
of shape `J`. -/
def preserves_colimits_of_shape_left_op (F : C ⥤ Dᵒᵖ) [preserves_limits_of_shape Jᵒᵖ F] :
preserves_colimits_of_shape J F.left_op :=
{ preserves_colimit := λ K, preserves_colimit_left_op K F }
/-- If `F : Cᵒᵖ ⥤ D` preserves limits of shape `Jᵒᵖ`, then `F.right_op : C ⥤ Dᵒᵖ` preserves colimits
of shape `J`. -/
def preserves_colimits_of_shape_right_op (F : Cᵒᵖ ⥤ D) [preserves_limits_of_shape Jᵒᵖ F] :
preserves_colimits_of_shape J F.right_op :=
{ preserves_colimit := λ K, preserves_colimit_right_op K F }
/-- If `F : Cᵒᵖ ⥤ Dᵒᵖ` preserves limits of shape `Jᵒᵖ`, then `F.unop : C ⥤ D` preserves colimits
of shape `J`. -/
def preserves_colimits_of_shape_unop (F : Cᵒᵖ ⥤ Dᵒᵖ) [preserves_limits_of_shape Jᵒᵖ F] :
preserves_colimits_of_shape J F.unop :=
{ preserves_colimit := λ K, preserves_colimit_unop K F }
end
/-- If `F : C ⥤ D` preserves colimits, then `F.op : Cᵒᵖ ⥤ Dᵒᵖ` preserves limits. -/
def preserves_limits_op (F : C ⥤ D) [preserves_colimits F] : preserves_limits F.op :=
{ preserves_limits_of_shape := λ J _, by exactI preserves_limits_of_shape_op J F }
/-- If `F : C ⥤ Dᵒᵖ` preserves colimits, then `F.left_op : Cᵒᵖ ⥤ D` preserves limits. -/
def preserves_limits_left_op (F : C ⥤ Dᵒᵖ) [preserves_colimits F] : preserves_limits F.left_op :=
{ preserves_limits_of_shape := λ J _, by exactI preserves_limits_of_shape_left_op J F }
/-- If `F : Cᵒᵖ ⥤ D` preserves colimits, then `F.right_op : C ⥤ Dᵒᵖ` preserves limits. -/
def preserves_limits_right_op (F : Cᵒᵖ ⥤ D) [preserves_colimits F] : preserves_limits F.right_op :=
{ preserves_limits_of_shape := λ J _, by exactI preserves_limits_of_shape_right_op J F }
/-- If `F : Cᵒᵖ ⥤ Dᵒᵖ` preserves colimits, then `F.unop : C ⥤ D` preserves limits. -/
def preserves_limits_unop (F : Cᵒᵖ ⥤ Dᵒᵖ) [preserves_colimits F] : preserves_limits F.unop :=
{ preserves_limits_of_shape := λ J _, by exactI preserves_limits_of_shape_unop J F }
/-- If `F : C ⥤ D` preserves limits, then `F.op : Cᵒᵖ ⥤ Dᵒᵖ` preserves colimits. -/
def perserves_colimits_op (F : C ⥤ D) [preserves_limits F] : preserves_colimits F.op :=
{ preserves_colimits_of_shape := λ J _, by exactI preserves_colimits_of_shape_op J F }
/-- If `F : C ⥤ Dᵒᵖ` preserves limits, then `F.left_op : Cᵒᵖ ⥤ D` preserves colimits. -/
def preserves_colimits_left_op (F : C ⥤ Dᵒᵖ) [preserves_limits F] : preserves_colimits F.left_op :=
{ preserves_colimits_of_shape := λ J _, by exactI preserves_colimits_of_shape_left_op J F }
/-- If `F : Cᵒᵖ ⥤ D` preserves limits, then `F.right_op : C ⥤ Dᵒᵖ` preserves colimits. -/
def preserves_colimits_right_op (F : Cᵒᵖ ⥤ D) [preserves_limits F] :
preserves_colimits F.right_op :=
{ preserves_colimits_of_shape := λ J _, by exactI preserves_colimits_of_shape_right_op J F }
/-- If `F : Cᵒᵖ ⥤ Dᵒᵖ` preserves limits, then `F.unop : C ⥤ D` preserves colimits. -/
def preserves_colimits_unop (F : Cᵒᵖ ⥤ Dᵒᵖ) [preserves_limits F] : preserves_colimits F.unop :=
{ preserves_colimits_of_shape := λ J _, by exactI preserves_colimits_of_shape_unop J F }
end
section
-- Preservation of finite (colimits) is only defined when the morphisms of C and D live in the same
-- universe.
variables {C : Type u₁} [category.{v₁} C] {D : Type u₂} [category.{v₁} D]
/-- If `F : C ⥤ D` preserves finite colimits, then `F.op : Cᵒᵖ ⥤ Dᵒᵖ` preserves finite
limits. -/
def preserves_finite_limits_op (F : C ⥤ D) [preserves_finite_colimits F] :
preserves_finite_limits F.op :=
{ preserves_finite_limits := λ J _ _, by exactI preserves_limits_of_shape_op J F }
/-- If `F : C ⥤ Dᵒᵖ` preserves finite colimits, then `F.left_op : Cᵒᵖ ⥤ D` preserves finite
limits. -/
def preserves_finite_limits_left_op (F : C ⥤ Dᵒᵖ) [preserves_finite_colimits F] :
preserves_finite_limits F.left_op :=
{ preserves_finite_limits := λ J _ _, by exactI preserves_limits_of_shape_left_op J F }
/-- If `F : Cᵒᵖ ⥤ D` preserves finite colimits, then `F.right_op : C ⥤ Dᵒᵖ` preserves finite
limits. -/
def preserves_finite_limits_right_op (F : Cᵒᵖ ⥤ D) [preserves_finite_colimits F] :
preserves_finite_limits F.right_op :=
{ preserves_finite_limits := λ J _ _, by exactI preserves_limits_of_shape_right_op J F }
/-- If `F : Cᵒᵖ ⥤ Dᵒᵖ` preserves finite colimits, then `F.unop : C ⥤ D` preserves finite
limits. -/
def preserves_finite_limits_unop (F : Cᵒᵖ ⥤ Dᵒᵖ) [preserves_finite_colimits F] :
preserves_finite_limits F.unop :=
{ preserves_finite_limits := λ J _ _, by exactI preserves_limits_of_shape_unop J F }
/-- If `F : C ⥤ D` preserves finite limits, then `F.op : Cᵒᵖ ⥤ Dᵒᵖ` preserves finite
colimits. -/
def preserves_finite_colimits_op (F : C ⥤ D) [preserves_finite_limits F] :
preserves_finite_colimits F.op :=
{ preserves_finite_colimits := λ J _ _, by exactI preserves_colimits_of_shape_op J F }
/-- If `F : C ⥤ Dᵒᵖ` preserves finite limits, then `F.left_op : Cᵒᵖ ⥤ D` preserves finite
colimits. -/
def preserves_finite_colimits_left_op (F : C ⥤ Dᵒᵖ) [preserves_finite_limits F] :
preserves_finite_colimits F.left_op :=
{ preserves_finite_colimits := λ J _ _, by exactI preserves_colimits_of_shape_left_op J F }
/-- If `F : Cᵒᵖ ⥤ D` preserves finite limits, then `F.right_op : C ⥤ Dᵒᵖ` preserves finite
colimits. -/
def preserves_finite_colimits_right_op (F : Cᵒᵖ ⥤ D) [preserves_finite_limits F] :
preserves_finite_colimits F.right_op :=
{ preserves_finite_colimits := λ J _ _, by exactI preserves_colimits_of_shape_right_op J F }
/-- If `F : Cᵒᵖ ⥤ Dᵒᵖ` preserves finite limits, then `F.unop : C ⥤ D` preserves finite
colimits. -/
def preserves_finite_colimits_unop (F : Cᵒᵖ ⥤ Dᵒᵖ) [preserves_finite_limits F] :
preserves_finite_colimits F.unop :=
{ preserves_finite_colimits := λ J _ _, by exactI preserves_colimits_of_shape_unop J F }
end
end category_theory.limits
|
fc093b9efef48d4fe3707ded6bf39ee264f0224d | 32025d5c2d6e33ad3b6dd8a3c91e1e838066a7f7 | /tests/lean/run/parseCore.lean | 6c0461937934dbd4afe53a59b6a0de15ef4f0a91 | [
"Apache-2.0"
] | permissive | walterhu1015/lean4 | b2c71b688975177402758924eaa513475ed6ce72 | 2214d81e84646a905d0b20b032c89caf89c737ad | refs/heads/master | 1,671,342,096,906 | 1,599,695,985,000 | 1,599,695,985,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 325 | lean | import Lean.Parser
def test : IO Unit :=
if System.Platform.isWindows then
pure () -- TODO investigate why the following doesn't work on Windows
else do
env ← Lean.mkEmptyEnvironment;
_ ← Lean.Parser.parseFile env (System.mkFilePath ["..", "..", "..", "src", "Init", "Core.lean"]);
IO.println "done"
#eval test
|
eb718a7a3e5c957ce92a029fbbfa37b849282ddc | 57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d | /src/Lean/Message.lean | 96ffd51627a21769ab741f3340a6e08bd1d7965d | [
"Apache-2.0"
] | permissive | collares/lean4 | 861a9269c4592bce49b71059e232ff0bfe4594cc | 52a4f535d853a2c7c7eea5fee8a4fa04c682c1ee | refs/heads/master | 1,691,419,031,324 | 1,618,678,138,000 | 1,618,678,138,000 | 358,989,750 | 0 | 0 | Apache-2.0 | 1,618,696,333,000 | 1,618,696,333,000 | null | UTF-8 | Lean | false | false | 14,037 | lean | /-
Copyright (c) 2018 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Sebastian Ullrich, Leonardo de Moura
Message Type used by the Lean frontend
-/
import Lean.Data.Position
import Lean.Data.OpenDecl
import Lean.Syntax
import Lean.MetavarContext
import Lean.Environment
import Lean.Util.PPExt
namespace Lean
def mkErrorStringWithPos (fileName : String) (pos : Position) (msg : String) (endPos : Option Position := none) : String :=
let endPos := match endPos with
| some endPos => s!"-{endPos.line}:{endPos.column}"
| none => ""
s!"{fileName}:{pos.line}:{pos.column}{endPos}: {msg}"
inductive MessageSeverity where
| information | warning | error
deriving Inhabited, BEq
structure MessageDataContext where
env : Environment
mctx : MetavarContext
lctx : LocalContext
opts : Options
structure NamingContext where
currNamespace : Name
openDecls : List OpenDecl
/- Structure message data. We use it for reporting errors, trace messages, etc. -/
inductive MessageData where
| ofFormat : Format → MessageData
| ofSyntax : Syntax → MessageData
| ofExpr : Expr → MessageData
| ofLevel : Level → MessageData
| ofName : Name → MessageData
| ofGoal : MVarId → MessageData
/- `withContext ctx d` specifies the pretty printing context `(env, mctx, lctx, opts)` for the nested expressions in `d`. -/
| withContext : MessageDataContext → MessageData → MessageData
| withNamingContext : NamingContext → MessageData → MessageData
/- Lifted `Format.nest` -/
| nest : Nat → MessageData → MessageData
/- Lifted `Format.group` -/
| group : MessageData → MessageData
/- Lifted `Format.compose` -/
| compose : MessageData → MessageData → MessageData
/- Tagged sections. `Name` should be viewed as a "kind", and is used by `MessageData` inspector functions.
Example: an inspector that tries to find "definitional equality failures" may look for the tag "DefEqFailure". -/
| tagged : Name → MessageData → MessageData
| node : Array MessageData → MessageData
deriving Inhabited
namespace MessageData
/- Instantiate metavariables occurring in nexted `ofExpr` constructors.
It uses the surrounding `MetavarContext` at `withContext` constructors.
-/
partial def instantiateMVars (msg : MessageData) : MessageData :=
visit msg {}
where
visit (msg : MessageData) (mctx : MetavarContext) : MessageData :=
match msg with
| ofExpr e => ofExpr <| mctx.instantiateMVars e |>.1
| withContext ctx msg => withContext ctx <| visit msg ctx.mctx
| withNamingContext ctx msg => withNamingContext ctx <| visit msg mctx
| nest n msg => nest n <| visit msg mctx
| group msg => group <| visit msg mctx
| compose msg₁ msg₂ => compose (visit msg₁ mctx) <| visit msg₂ mctx
| tagged n msg => tagged n <| visit msg mctx
| node msgs => node <| msgs.map (visit . mctx)
| _ => msg
def nil : MessageData :=
ofFormat Format.nil
def isNil : MessageData → Bool
| ofFormat Format.nil => true
| _ => false
def isNest : MessageData → Bool
| nest _ _ => true
| _ => false
def mkPPContext (nCtx : NamingContext) (ctx : MessageDataContext) : PPContext := {
env := ctx.env, mctx := ctx.mctx, lctx := ctx.lctx, opts := ctx.opts,
currNamespace := nCtx.currNamespace, openDecls := nCtx.openDecls
}
partial def formatAux : NamingContext → Option MessageDataContext → MessageData → IO Format
| _, _, ofFormat fmt => pure fmt
| _, _, ofLevel u => pure $ fmt u
| _, _, ofName n => pure $ fmt n
| nCtx, some ctx, ofSyntax s => ppTerm (mkPPContext nCtx ctx) s -- HACK: might not be a term
| _, none, ofSyntax s => pure $ s.formatStx
| _, none, ofExpr e => pure $ format (toString e)
| nCtx, some ctx, ofExpr e => ppExpr (mkPPContext nCtx ctx) e
| _, none, ofGoal mvarId => pure $ "goal " ++ format (mkMVar mvarId)
| nCtx, some ctx, ofGoal mvarId => ppGoal (mkPPContext nCtx ctx) mvarId
| nCtx, _, withContext ctx d => formatAux nCtx ctx d
| _, ctx, withNamingContext nCtx d => formatAux nCtx ctx d
| nCtx, ctx, tagged cls d => do let d ← formatAux nCtx ctx d; pure $ Format.sbracket (format cls) ++ " " ++ d
| nCtx, ctx, nest n d => Format.nest n <$> formatAux nCtx ctx d
| nCtx, ctx, compose d₁ d₂ => do let d₁ ← formatAux nCtx ctx d₁; let d₂ ← formatAux nCtx ctx d₂; pure $ d₁ ++ d₂
| nCtx, ctx, group d => Format.group <$> formatAux nCtx ctx d
| nCtx, ctx, node ds => Format.nest 2 <$> ds.foldlM (fun r d => do let d ← formatAux nCtx ctx d; pure $ r ++ Format.line ++ d) Format.nil
protected def format (msgData : MessageData) : IO Format :=
formatAux { currNamespace := Name.anonymous, openDecls := [] } none msgData
protected def toString (msgData : MessageData) : IO String := do
let fmt ← msgData.format
pure $ toString fmt
instance : Append MessageData := ⟨compose⟩
instance : Coe String MessageData := ⟨ofFormat ∘ format⟩
instance : Coe Format MessageData := ⟨ofFormat⟩
instance : Coe Level MessageData := ⟨ofLevel⟩
instance : Coe Expr MessageData := ⟨ofExpr⟩
instance : Coe Name MessageData := ⟨ofName⟩
instance : Coe Syntax MessageData := ⟨ofSyntax⟩
instance : Coe (Option Expr) MessageData := ⟨fun o => match o with | none => "none" | some e => ofExpr e⟩
partial def arrayExpr.toMessageData (es : Array Expr) (i : Nat) (acc : MessageData) : MessageData :=
if h : i < es.size then
let e := es.get ⟨i, h⟩;
let acc := if i == 0 then acc ++ ofExpr e else acc ++ ", " ++ ofExpr e;
toMessageData es (i+1) acc
else
acc ++ "]"
instance : Coe (Array Expr) MessageData := ⟨fun es => arrayExpr.toMessageData es 0 "#["⟩
def bracket (l : String) (f : MessageData) (r : String) : MessageData := group (nest l.length $ l ++ f ++ r)
def paren (f : MessageData) : MessageData := bracket "(" f ")"
def sbracket (f : MessageData) : MessageData := bracket "[" f "]"
def joinSep : List MessageData → MessageData → MessageData
| [], sep => Format.nil
| [a], sep => a
| a::as, sep => a ++ sep ++ joinSep as sep
def ofList: List MessageData → MessageData
| [] => "[]"
| xs => sbracket $ joinSep xs (ofFormat "," ++ Format.line)
def ofArray (msgs : Array MessageData) : MessageData :=
ofList msgs.toList
instance : Coe (List MessageData) MessageData := ⟨ofList⟩
instance : Coe (List Expr) MessageData := ⟨fun es => ofList $ es.map ofExpr⟩
end MessageData
structure Message where
fileName : String
pos : Position
endPos : Option Position := none
severity : MessageSeverity := MessageSeverity.error
caption : String := ""
data : MessageData
deriving Inhabited
namespace Message
protected def toString (msg : Message) (includeEndPos := false) : IO String := do
let mut str ← msg.data.toString
let endPos := if includeEndPos then msg.endPos else none
unless msg.caption == "" do
str := msg.caption ++ ":\n" ++ str
match msg.severity with
| MessageSeverity.information => pure ()
| MessageSeverity.warning => str := mkErrorStringWithPos msg.fileName msg.pos (endPos := endPos) "warning: " ++ str
| MessageSeverity.error => str := mkErrorStringWithPos msg.fileName msg.pos (endPos := endPos) "error: " ++ str
if str.isEmpty || str.back != '\n' then
str := str ++ "\n"
return str
end Message
structure MessageLog where
msgs : Std.PersistentArray Message := {}
deriving Inhabited
namespace MessageLog
def empty : MessageLog := ⟨{}⟩
def isEmpty (log : MessageLog) : Bool :=
log.msgs.isEmpty
def add (msg : Message) (log : MessageLog) : MessageLog :=
⟨log.msgs.push msg⟩
protected def append (l₁ l₂ : MessageLog) : MessageLog :=
⟨l₁.msgs ++ l₂.msgs⟩
instance : Append MessageLog :=
⟨MessageLog.append⟩
def hasErrors (log : MessageLog) : Bool :=
log.msgs.any fun m => match m.severity with
| MessageSeverity.error => true
| _ => false
def errorsToWarnings (log : MessageLog) : MessageLog :=
{ msgs := log.msgs.map (fun m => match m.severity with | MessageSeverity.error => { m with severity := MessageSeverity.warning } | _ => m) }
def getInfoMessages (log : MessageLog) : MessageLog :=
{ msgs := log.msgs.filter fun m => match m.severity with | MessageSeverity.information => true | _ => false }
def forM {m : Type → Type} [Monad m] (log : MessageLog) (f : Message → m Unit) : m Unit :=
log.msgs.forM f
def toList (log : MessageLog) : List Message :=
(log.msgs.foldl (fun acc msg => msg :: acc) []).reverse
end MessageLog
def MessageData.nestD (msg : MessageData) : MessageData :=
MessageData.nest 2 msg
def indentD (msg : MessageData) : MessageData :=
MessageData.nestD (Format.line ++ msg)
def indentExpr (e : Expr) : MessageData :=
indentD e
class AddMessageContext (m : Type → Type) where
addMessageContext : MessageData → m MessageData
export AddMessageContext (addMessageContext)
instance (m n) [MonadLift m n] [AddMessageContext m] : AddMessageContext n where
addMessageContext := fun msg => liftM (addMessageContext msg : m _)
def addMessageContextPartial {m} [Monad m] [MonadEnv m] [MonadOptions m] (msgData : MessageData) : m MessageData := do
let env ← getEnv
let opts ← getOptions
pure $ MessageData.withContext { env := env, mctx := {}, lctx := {}, opts := opts } msgData
def addMessageContextFull {m} [Monad m] [MonadEnv m] [MonadMCtx m] [MonadLCtx m] [MonadOptions m] (msgData : MessageData) : m MessageData := do
let env ← getEnv
let mctx ← getMCtx
let lctx ← getLCtx
let opts ← getOptions
pure $ MessageData.withContext { env := env, mctx := mctx, lctx := lctx, opts := opts } msgData
class ToMessageData (α : Type) where
toMessageData : α → MessageData
export ToMessageData (toMessageData)
def stringToMessageData (str : String) : MessageData :=
let lines := str.split (· == '\n')
let lines := lines.map (MessageData.ofFormat ∘ fmt)
MessageData.joinSep lines (MessageData.ofFormat Format.line)
instance {α} [ToFormat α] : ToMessageData α := ⟨MessageData.ofFormat ∘ fmt⟩
instance : ToMessageData Expr := ⟨MessageData.ofExpr⟩
instance : ToMessageData Level := ⟨MessageData.ofLevel⟩
instance : ToMessageData Name := ⟨MessageData.ofName⟩
instance : ToMessageData String := ⟨stringToMessageData⟩
instance : ToMessageData Syntax := ⟨MessageData.ofSyntax⟩
instance : ToMessageData Format := ⟨MessageData.ofFormat⟩
instance : ToMessageData MessageData := ⟨id⟩
instance {α} [ToMessageData α] : ToMessageData (List α) := ⟨fun as => MessageData.ofList $ as.map toMessageData⟩
instance {α} [ToMessageData α] : ToMessageData (Array α) := ⟨fun as => toMessageData as.toList⟩
instance {α} [ToMessageData α] : ToMessageData (Option α) := ⟨fun | none => "none" | some e => "some (" ++ toMessageData e ++ ")"⟩
instance : ToMessageData (Option Expr) := ⟨fun | none => "<not-available>" | some e => toMessageData e⟩
syntax:max "m!" interpolatedStr(term) : term
macro_rules
| `(m! $interpStr) => do interpStr.expandInterpolatedStr (← `(MessageData)) (← `(toMessageData))
namespace KernelException
private def mkCtx (env : Environment) (lctx : LocalContext) (opts : Options) (msg : MessageData) : MessageData :=
MessageData.withContext { env := env, mctx := {}, lctx := lctx, opts := opts } msg
def toMessageData (e : KernelException) (opts : Options) : MessageData :=
match e with
| unknownConstant env constName => mkCtx env {} opts m!"(kernel) unknown constant '{constName}'"
| alreadyDeclared env constName => mkCtx env {} opts m!"(kernel) constant has already been declared '{constName}'"
| declTypeMismatch env decl givenType =>
let process (n : Name) (expectedType : Expr) : MessageData :=
m!"(kernel) declaration type mismatch, '{n}' has type{indentExpr givenType}\nbut it is expected to have type{indentExpr expectedType}";
match decl with
| Declaration.defnDecl { name := n, type := type, .. } => process n type
| Declaration.thmDecl { name := n, type := type, .. } => process n type
| _ => "(kernel) declaration type mismatch" -- TODO fix type checker, type mismatch for mutual decls does not have enough information
| declHasMVars env constName _ => mkCtx env {} opts m!"(kernel) declaration has metavariables '{constName}'"
| declHasFVars env constName _ => mkCtx env {} opts m!"(kernel) declaration has free variables '{constName}'"
| funExpected env lctx e => mkCtx env lctx opts m!"(kernel) function expected{indentExpr e}"
| typeExpected env lctx e => mkCtx env lctx opts m!"(kernel) type expected{indentExpr e}"
| letTypeMismatch env lctx n _ _ => mkCtx env lctx opts m!"(kernel) let-declaration type mismatch '{n}'"
| exprTypeMismatch env lctx e _ => mkCtx env lctx opts m!"(kernel) type mismatch at{indentExpr e}"
| appTypeMismatch env lctx e fnType argType =>
mkCtx env lctx opts m!"application type mismatch{indentExpr e}\nargument has type{indentExpr argType}\nbut function has type{indentExpr fnType}"
| invalidProj env lctx e => mkCtx env lctx opts m!"(kernel) invalid projection{indentExpr e}"
| other msg => m!"(kernel) {msg}"
end KernelException
end Lean
|
935224d05454bf3f53bcb7073d528dc4dd5ce1ca | 4727251e0cd73359b15b664c3170e5d754078599 | /archive/sensitivity.lean | b0dfa141ff98a3652eb0643693e31a9745386661 | [
"Apache-2.0"
] | permissive | Vierkantor/mathlib | 0ea59ac32a3a43c93c44d70f441c4ee810ccceca | 83bc3b9ce9b13910b57bda6b56222495ebd31c2f | refs/heads/master | 1,658,323,012,449 | 1,652,256,003,000 | 1,652,256,003,000 | 209,296,341 | 0 | 1 | Apache-2.0 | 1,568,807,655,000 | 1,568,807,655,000 | null | UTF-8 | Lean | false | false | 15,649 | lean | /-
Copyright (c) 2019 Reid Barton, Johan Commelin, Jesse Han, Chris Hughes, Robert Y. Lewis,
Patrick Massot. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Reid Barton, Johan Commelin, Jesse Han, Chris Hughes, Robert Y. Lewis, Patrick Massot
-/
import tactic.fin_cases
import tactic.apply_fun
import linear_algebra.finite_dimensional
import linear_algebra.dual
import analysis.normed_space.basic
import data.real.sqrt
/-!
# Huang's sensitivity theorem
A formalization of Hao Huang's sensitivity theorem: in the hypercube of
dimension n ≥ 1, if one colors more than half the vertices then at least one
vertex has at least √n colored neighbors.
A fun summer collaboration by
Reid Barton, Johan Commelin, Jesse Han, Chris Hughes, Robert Y. Lewis, and Patrick Massot,
based on Don Knuth's account of the story
(https://www.cs.stanford.edu/~knuth/papers/huang.pdf),
using the Lean theorem prover (https://leanprover.github.io/),
by Leonardo de Moura at Microsoft Research, and his collaborators
(https://leanprover.github.io/people/),
and using Lean's user maintained mathematics library
(https://github.com/leanprover-community/mathlib).
The project was developed at https://github.com/leanprover-community/lean-sensitivity and is now
archived at https://github.com/leanprover-community/mathlib/blob/master/archive/sensitivity.lean
-/
/-! The next two lines assert we do not want to give a constructive proof,
but rather use classical logic. -/
noncomputable theory
open_locale classical
/-! We also want to use the notation `∑` for sums. -/
open_locale big_operators
notation `√` := real.sqrt
open function bool linear_map fintype finite_dimensional dual_pair
/-!
### The hypercube
Notations:
- `ℕ` denotes natural numbers (including zero).
- `fin n` = {0, ⋯ , n - 1}.
- `bool` = {`tt`, `ff`}.
-/
/-- The hypercube in dimension `n`. -/
@[derive [inhabited, fintype]] def Q (n : ℕ) := fin n → bool
/-- The projection from `Q (n + 1)` to `Q n` forgetting the first value
(ie. the image of zero). -/
def π {n : ℕ} : Q (n + 1) → Q n := λ p, p ∘ fin.succ
namespace Q
/-! `n` will always denote a natural number. -/
variable (n : ℕ)
/-- `Q 0` has a unique element. -/
instance : unique (Q 0) :=
⟨⟨λ _, tt⟩, by { intro, ext x, fin_cases x }⟩
/-- `Q n` has 2^n elements. -/
lemma card : card (Q n) = 2^n :=
by simp [Q]
/-! Until the end of this namespace, `n` will be an implicit argument (still
a natural number). -/
variable {n}
lemma succ_n_eq (p q : Q (n+1)) : p = q ↔ (p 0 = q 0 ∧ π p = π q) :=
begin
split,
{ rintro rfl, exact ⟨rfl, rfl⟩, },
{ rintros ⟨h₀, h⟩,
ext x,
by_cases hx : x = 0,
{ rwa hx },
{ rw ← fin.succ_pred x hx,
convert congr_fun h (fin.pred x hx) } }
end
/-- The adjacency relation defining the graph structure on `Q n`:
`p.adjacent q` if there is an edge from `p` to `q` in `Q n`. -/
def adjacent {n : ℕ} (p : Q n) : set (Q n) := λ q, ∃! i, p i ≠ q i
/-- In `Q 0`, no two vertices are adjacent. -/
lemma not_adjacent_zero (p q : Q 0) : ¬ p.adjacent q :=
by rintros ⟨v, _⟩; apply fin_zero_elim v
/-- If `p` and `q` in `Q (n+1)` have different values at zero then they are adjacent
iff their projections to `Q n` are equal. -/
lemma adj_iff_proj_eq {p q : Q (n+1)} (h₀ : p 0 ≠ q 0) :
p.adjacent q ↔ π p = π q :=
begin
split,
{ rintros ⟨i, h_eq, h_uni⟩,
ext x, by_contradiction hx,
apply fin.succ_ne_zero x,
rw [h_uni _ hx, h_uni _ h₀] },
{ intro heq,
use [0, h₀],
intros y hy,
contrapose! hy,
rw ←fin.succ_pred _ hy,
apply congr_fun heq }
end
/-- If `p` and `q` in `Q (n+1)` have the same value at zero then they are adjacent
iff their projections to `Q n` are adjacent. -/
lemma adj_iff_proj_adj {p q : Q (n+1)} (h₀ : p 0 = q 0) :
p.adjacent q ↔ (π p).adjacent (π q) :=
begin
split,
{ rintros ⟨i, h_eq, h_uni⟩,
have h_i : i ≠ 0, from λ h_i, absurd h₀ (by rwa h_i at h_eq),
use [i.pred h_i,
show p (fin.succ (fin.pred i _)) ≠ q (fin.succ (fin.pred i _)),
by rwa fin.succ_pred],
intros y hy,
simp [eq.symm (h_uni _ hy)] },
{ rintros ⟨i, h_eq, h_uni⟩,
use [i.succ, h_eq],
intros y hy,
rw [←fin.pred_inj, fin.pred_succ],
{ apply h_uni,
change p (fin.pred _ _).succ ≠ q (fin.pred _ _).succ,
simp [hy] },
{ contrapose! hy,
rw [hy, h₀] },
{ apply fin.succ_ne_zero } }
end
@[symm] lemma adjacent.symm {p q : Q n} : p.adjacent q ↔ q.adjacent p :=
by simp only [adjacent, ne_comm]
end Q
/-! ### The vector space -/
/-- The free vector space on vertices of a hypercube, defined inductively. -/
def V : ℕ → Type
| 0 := ℝ
| (n+1) := V n × V n
namespace V
variables (n : ℕ)
/-! `V n` is a real vector space whose equality relation is computable. -/
instance : decidable_eq (V n) :=
by { induction n ; { dunfold V, resetI, apply_instance } }
instance : add_comm_group (V n) :=
by { induction n ; { dunfold V, resetI, apply_instance } }
instance : module ℝ (V n) :=
by { induction n ; { dunfold V, resetI, apply_instance } }
end V
/-- The basis of `V` indexed by the hypercube, defined inductively. -/
noncomputable def e : Π {n}, Q n → V n
| 0 := λ _, (1:ℝ)
| (n+1) := λ x, cond (x 0) (e (π x), 0) (0, e (π x))
@[simp] lemma e_zero_apply (x : Q 0) : e x = (1 : ℝ) := rfl
/-- The dual basis to `e`, defined inductively. -/
noncomputable def ε : Π {n : ℕ} (p : Q n), V n →ₗ[ℝ] ℝ
| 0 _ := linear_map.id
| (n+1) p := cond (p 0) ((ε $ π p).comp $ linear_map.fst _ _ _)
((ε $ π p).comp $ linear_map.snd _ _ _)
variable {n : ℕ}
lemma duality (p q : Q n) : ε p (e q) = if p = q then 1 else 0 :=
begin
induction n with n IH,
{ rw (show p = q, from subsingleton.elim p q),
dsimp [ε, e],
simp },
{ dsimp [ε, e],
cases hp : p 0 ; cases hq : q 0,
all_goals
{ repeat {rw cond_tt},
repeat {rw cond_ff},
simp only [linear_map.fst_apply, linear_map.snd_apply, linear_map.comp_apply, IH],
try { congr' 1, rw Q.succ_n_eq, finish },
try
{ erw (ε _).map_zero,
have : p ≠ q, { intro h, rw p.succ_n_eq q at h, finish },
simp [this] } } }
end
/-- Any vector in `V n` annihilated by all `ε p`'s is zero. -/
lemma epsilon_total {v : V n} (h : ∀ p : Q n, (ε p) v = 0) : v = 0 :=
begin
induction n with n ih,
{ dsimp [ε] at h, exact h (λ _, tt) },
{ cases v with v₁ v₂,
ext ; change _ = (0 : V n) ; simp only ; apply ih ; intro p ;
[ let q : Q (n+1) := λ i, if h : i = 0 then tt else p (i.pred h),
let q : Q (n+1) := λ i, if h : i = 0 then ff else p (i.pred h)],
all_goals
{ specialize h q,
rw [ε, show q 0 = tt, from rfl, cond_tt] at h <|>
rw [ε, show q 0 = ff, from rfl, cond_ff] at h,
rwa show p = π q, by { ext, simp [q, fin.succ_ne_zero, π] } } }
end
/-- `e` and `ε` are dual families of vectors. It implies that `e` is indeed a basis
and `ε` computes coefficients of decompositions of vectors on that basis. -/
def dual_pair_e_ε (n : ℕ) : dual_pair (@e n) (@ε n) :=
{ eval := duality,
total := @epsilon_total _ }
/-! We will now derive the dimension of `V`, first as a cardinal in `dim_V` and,
since this cardinal is finite, as a natural number in `finrank_V` -/
lemma dim_V : module.rank ℝ (V n) = 2^n :=
have module.rank ℝ (V n) = (2^n : ℕ),
by { rw [dim_eq_card_basis (dual_pair_e_ε _).basis, Q.card]; apply_instance },
by assumption_mod_cast
instance : finite_dimensional ℝ (V n) :=
finite_dimensional.of_fintype_basis (dual_pair_e_ε _).basis
lemma finrank_V : finrank ℝ (V n) = 2^n :=
have _ := @dim_V n,
by rw ←finrank_eq_dim at this; assumption_mod_cast
/-! ### The linear map -/
/-- The linear operator $f_n$ corresponding to Huang's matrix $A_n$,
defined inductively as a ℝ-linear map from `V n` to `V n`. -/
noncomputable def f : Π n, V n →ₗ[ℝ] V n
| 0 := 0
| (n+1) := linear_map.prod
(linear_map.coprod (f n) linear_map.id)
(linear_map.coprod linear_map.id (-f n))
/-! The preceding definition uses linear map constructions to automatically
get that `f` is linear, but its values are somewhat buried as a side-effect.
The next two lemmas unbury them. -/
@[simp] lemma f_zero : f 0 = 0 := rfl
lemma f_succ_apply (v : V (n+1)) :
f (n+1) v = (f n v.1 + v.2, v.1 - f n v.2) :=
begin
cases v,
rw f,
simp only [linear_map.id_apply, linear_map.prod_apply, pi.prod, prod.mk.inj_iff,
linear_map.neg_apply, sub_eq_add_neg, linear_map.coprod_apply],
exact ⟨rfl, rfl⟩
end
/-! In the next statement, the explicit conversion `(n : ℝ)` of `n` to a real number
is necessary since otherwise `n • v` refers to the multiplication defined
using only the addition of `V`. -/
lemma f_squared : ∀ v : V n, (f n) (f n v) = (n : ℝ) • v :=
begin
induction n with n IH; intro,
{ simpa only [nat.cast_zero, zero_smul] },
{ cases v, simp [f_succ_apply, IH, add_smul, add_assoc], abel }
end
/-! We now compute the matrix of `f` in the `e` basis (`p` is the line index,
`q` the column index). -/
lemma f_matrix :
∀ p q : Q n, |ε q (f n (e p))| = if q.adjacent p then 1 else 0 :=
begin
induction n with n IH,
{ intros p q,
dsimp [f],
simp [Q.not_adjacent_zero] },
{ intros p q,
have ite_nonneg : ite (π q = π p) (1 : ℝ) 0 ≥ 0,
{ split_ifs ; norm_num },
have f_map_zero := (show (V (n+0)) →ₗ[ℝ] (V n), from f n).map_zero,
dsimp [e, ε, f], cases hp : p 0 ; cases hq : q 0,
all_goals
{ repeat {rw cond_tt}, repeat {rw cond_ff},
simp [f_map_zero, hp, hq, IH, duality, abs_of_nonneg ite_nonneg, Q.adj_iff_proj_eq,
Q.adj_iff_proj_adj] } }
end
/-- The linear operator $g_m$ corresponding to Knuth's matrix $B_m$. -/
noncomputable def g (m : ℕ) : V m →ₗ[ℝ] V (m+1) :=
linear_map.prod (f m + √(m+1) • linear_map.id) linear_map.id
/-! In the following lemmas, `m` will denote a natural number. -/
variables {m : ℕ}
/-! Again we unpack what are the values of `g`. -/
lemma g_apply : ∀ v, g m v = (f m v + √(m+1) • v, v) :=
by delta g; simp
lemma g_injective : injective (g m) :=
begin
rw g,
intros x₁ x₂ h,
simp only [linear_map.prod_apply, linear_map.id_apply, prod.mk.inj_iff, pi.prod] at h,
exact h.right
end
lemma f_image_g (w : V (m + 1)) (hv : ∃ v, g m v = w) :
f (m + 1) w = √(m + 1) • w :=
begin
rcases hv with ⟨v, rfl⟩,
have : √(m+1) * √(m+1) = m+1 :=
real.mul_self_sqrt (by exact_mod_cast zero_le _),
simp [this, f_succ_apply, g_apply, f_squared, smul_add, add_smul, smul_smul],
abel
end
/-!
### The main proof
In this section, in order to enforce that `n` is positive, we write it as
`m + 1` for some natural number `m`. -/
/-! `dim X` will denote the dimension of a subspace `X` as a cardinal. -/
notation `dim` X:70 := module.rank ℝ ↥X
/-! `fdim X` will denote the (finite) dimension of a subspace `X` as a natural number. -/
notation `fdim` := finrank ℝ
/-! `Span S` will denote the ℝ-subspace spanned by `S`. -/
notation `Span` := submodule.span ℝ
/-! `Card X` will denote the cardinal of a subset of a finite type, as a
natural number. -/
notation `Card` X:70 := X.to_finset.card
/-! In the following, `⊓` and `⊔` will denote intersection and sums of ℝ-subspaces,
equipped with their subspace structures. The notations come from the general
theory of lattices, with inf and sup (also known as meet and join). -/
/-- If a subset `H` of `Q (m+1)` has cardinal at least `2^m + 1` then the
subspace of `V (m+1)` spanned by the corresponding basis vectors non-trivially
intersects the range of `g m`. -/
lemma exists_eigenvalue (H : set (Q (m + 1))) (hH : Card H ≥ 2^m + 1) :
∃ y ∈ Span (e '' H) ⊓ (g m).range, y ≠ (0 : _) :=
begin
let W := Span (e '' H),
let img := (g m).range,
suffices : 0 < dim (W ⊓ img),
{ simp only [exists_prop],
exact_mod_cast exists_mem_ne_zero_of_dim_pos this },
have dim_le : dim (W ⊔ img) ≤ 2^(m + 1),
{ convert ← dim_submodule_le (W ⊔ img),
apply dim_V },
have dim_add : dim (W ⊔ img) + dim (W ⊓ img) = dim W + 2^m,
{ convert ← dim_sup_add_dim_inf_eq W img,
rw ← dim_eq_of_injective (g m) g_injective,
apply dim_V },
have dimW : dim W = card H,
{ have li : linear_independent ℝ (H.restrict e),
{ convert (dual_pair_e_ε _).basis.linear_independent.comp _ subtype.val_injective,
rw (dual_pair_e_ε _).coe_basis },
have hdW := dim_span li,
rw set.range_restrict at hdW,
convert hdW,
rw [← (dual_pair_e_ε _).coe_basis, cardinal.mk_image_eq (dual_pair_e_ε _).basis.injective,
cardinal.mk_fintype] },
rw ← finrank_eq_dim ℝ at ⊢ dim_le dim_add dimW,
rw [← finrank_eq_dim ℝ, ← finrank_eq_dim ℝ] at dim_add,
norm_cast at ⊢ dim_le dim_add dimW,
rw pow_succ' at dim_le,
rw set.to_finset_card at hH,
linarith
end
/-- **Huang sensitivity theorem** also known as the **Huang degree theorem** -/
theorem huang_degree_theorem (H : set (Q (m + 1))) (hH : Card H ≥ 2^m + 1) :
∃ q, q ∈ H ∧ √(m + 1) ≤ Card (H ∩ q.adjacent) :=
begin
rcases exists_eigenvalue H hH with ⟨y, ⟨⟨y_mem_H, y_mem_g⟩, y_ne⟩⟩,
have coeffs_support : ((dual_pair_e_ε (m+1)).coeffs y).support ⊆ H.to_finset,
{ intros p p_in,
rw finsupp.mem_support_iff at p_in,
rw set.mem_to_finset,
exact (dual_pair_e_ε _).mem_of_mem_span y_mem_H p p_in },
obtain ⟨q, H_max⟩ : ∃ q : Q (m+1), ∀ q' : Q (m+1), |(ε q' : _) y| ≤ |ε q y|,
from fintype.exists_max _,
have H_q_pos : 0 < |ε q y|,
{ contrapose! y_ne,
exact epsilon_total (λ p, abs_nonpos_iff.mp (le_trans (H_max p) y_ne)) },
refine ⟨q, (dual_pair_e_ε _).mem_of_mem_span y_mem_H q (abs_pos.mp H_q_pos), _⟩,
let s := √(m+1),
suffices : s * |ε q y| ≤ ↑(_) * |ε q y|,
from (mul_le_mul_right H_q_pos).mp ‹_›,
let coeffs := (dual_pair_e_ε (m+1)).coeffs,
calc
s * |ε q y|
= |ε q (s • y)| :
by rw [map_smul, smul_eq_mul, abs_mul, abs_of_nonneg (real.sqrt_nonneg _)]
... = |ε q (f (m+1) y)| : by rw [← f_image_g y (by simpa using y_mem_g)]
... = |ε q (f (m+1) (lc _ (coeffs y)))| : by rw (dual_pair_e_ε _).lc_coeffs y
... = |(coeffs y).sum (λ (i : Q (m + 1)) (a : ℝ), a • ((ε q) ∘ (f (m + 1)) ∘
λ (i : Q (m + 1)), e i) i)| :
by erw [(f $ m + 1).map_finsupp_total, (ε q).map_finsupp_total, finsupp.total_apply]
... ≤ ∑ p in (coeffs y).support, |(coeffs y p) * (ε q $ f (m+1) $ e p)| :
norm_sum_le _ $ λ p, coeffs y p * _
... = ∑ p in (coeffs y).support, |coeffs y p| * ite (q.adjacent p) 1 0 :
by simp only [abs_mul, f_matrix]
... = ∑ p in (coeffs y).support.filter (Q.adjacent q), |coeffs y p| :
by simp [finset.sum_filter]
... ≤ ∑ p in (coeffs y).support.filter (Q.adjacent q), |coeffs y q| :
finset.sum_le_sum (λ p _, H_max p)
... = (((coeffs y).support.filter (Q.adjacent q)).card : ℝ) * |coeffs y q| :
by rw [finset.sum_const, nsmul_eq_mul]
... = (((coeffs y).support ∩ (Q.adjacent q).to_finset).card : ℝ) * |coeffs y q| :
by { congr' with x, simp, refl }
... ≤ (finset.card ((H ∩ Q.adjacent q).to_finset )) * |ε q y| :
begin
refine (mul_le_mul_right H_q_pos).2 _,
norm_cast,
apply finset.card_le_of_subset,
rw set.to_finset_inter,
convert finset.inter_subset_inter_right coeffs_support
end
end
|
88a76034575a3ab4d51c2ea3532265383b91f108 | 55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5 | /src/tactic/lint/simp.lean | ff19f6d4d16dc75dc54c64e1742bed320640d6a0 | [
"Apache-2.0"
] | permissive | dupuisf/mathlib | 62de4ec6544bf3b79086afd27b6529acfaf2c1bb | 8582b06b0a5d06c33ee07d0bdf7c646cae22cf36 | refs/heads/master | 1,669,494,854,016 | 1,595,692,409,000 | 1,595,692,409,000 | 272,046,630 | 0 | 0 | Apache-2.0 | 1,592,066,143,000 | 1,592,066,142,000 | null | UTF-8 | Lean | false | false | 9,342 | lean | /-
Copyright (c) 2020 Gabriel Ebner. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Gabriel Ebner
-/
import tactic.lint.basic
/-!
# Linter for simplification lemmas
This files defines several linters that prevent common mistakes when declaring simp lemmas:
* `simp_nf` checks that the left-hand side of a simp lemma is not simplified by a different lemma.
* `simp_var_head` checks that the head symbol of the left-hand side is not a variable.
* `simp_comm` checks that commutativity lemmas are not marked as simplification lemmas.
-/
open tactic expr
/-- `simp_lhs_rhs ty` returns the left-hand and right-hand side of a simp lemma with type `ty`. -/
private meta def simp_lhs_rhs : expr → tactic (expr × expr) | ty := do
ty ← whnf ty transparency.reducible,
-- We only detect a fixed set of simp relations here.
-- This is somewhat justified since for a custom simp relation R,
-- the simp lemma `R a b` is implicitly converted to `R a b ↔ true` as well.
match ty with
| `(¬ %%lhs) := pure (lhs, `(false))
| `(%%lhs = %%rhs) := pure (lhs, rhs)
| `(%%lhs ↔ %%rhs) := pure (lhs, rhs)
| (expr.pi n bi a b) := do
l ← mk_local' n bi a,
simp_lhs_rhs (b.instantiate_var l)
| ty := pure (ty, `(true))
end
/-- `simp_lhs ty` returns the left-hand side of a simp lemma with type `ty`. -/
private meta def simp_lhs (ty : expr): tactic expr :=
prod.fst <$> simp_lhs_rhs ty
/--
`simp_is_conditional_core ty` returns `none` if `ty` is a conditional simp
lemma, and `some lhs` otherwise.
-/
private meta def simp_is_conditional_core : expr → tactic (option expr) | ty := do
ty ← whnf ty transparency.semireducible,
match ty with
| `(¬ %%lhs) := pure lhs
| `(%%lhs = _) := pure lhs
| `(%%lhs ↔ _) := pure lhs
| (expr.pi n bi a b) := do
l ← mk_local' n bi a,
some lhs ← simp_is_conditional_core (b.instantiate_var l) | pure none,
if bi ≠ binder_info.inst_implicit ∧
¬ (lhs.abstract_local l.local_uniq_name).has_var then
pure none
else
pure lhs
| ty := pure ty
end
/--
`simp_is_conditional ty` returns true iff the simp lemma with type `ty` is conditional.
-/
private meta def simp_is_conditional (ty : expr) : tactic bool :=
option.is_none <$> simp_is_conditional_core ty
private meta def heuristic_simp_lemma_extraction (prf : expr) : tactic (list name) :=
prf.list_constant.to_list.mfilter is_simp_lemma
/-- Checks whether two expressions are equal for the simplifier. That is,
they are reducibly-definitional equal, and they have the same head symbol. -/
meta def is_simp_eq (a b : expr) : tactic bool :=
if a.get_app_fn.const_name ≠ b.get_app_fn.const_name then pure ff else
succeeds $ is_def_eq a b transparency.reducible
/-- Reports declarations that are simp lemmas whose left-hand side is not in simp-normal form. -/
meta def simp_nf_linter (timeout := 200000) (d : declaration) : tactic (option string) := do
tt ← is_simp_lemma d.to_name | pure none,
-- Sometimes, a definition is tagged @[simp] to add the equational lemmas to the simp set.
-- In this case, ignore the declaration if it is not a valid simp lemma by itself.
tt ← is_valid_simp_lemma_cnst d.to_name | pure none,
[] ← get_eqn_lemmas_for ff d.to_name | pure none,
try_for timeout $
retrieve $ do
g ← mk_meta_var d.type,
set_goals [g],
unfreezing intros,
(lhs, rhs) ← target >>= simp_lhs_rhs,
sls ← simp_lemmas.mk_default,
let sls' := sls.erase [d.to_name],
(lhs', prf1) ← decorate_error "simplify fails on left-hand side:" $
simplify sls [] lhs {fail_if_unchanged := ff},
prf1_lems ← heuristic_simp_lemma_extraction prf1,
if d.to_name ∈ prf1_lems then pure none else do
is_cond ← simp_is_conditional d.type,
(rhs', prf2) ← decorate_error "simplify fails on right-hand side:" $
simplify sls [] rhs {fail_if_unchanged := ff},
lhs'_eq_rhs' ← is_simp_eq lhs' rhs',
lhs_in_nf ← is_simp_eq lhs' lhs,
if lhs'_eq_rhs' then do
used_lemmas ← heuristic_simp_lemma_extraction (prf1 prf2),
pure $ pure $ "simp can prove this:\n"
++ " by simp only " ++ to_string used_lemmas ++ "\n"
++ "One of the lemmas above could be a duplicate.\n"
++ "If that's not the case try reordering lemmas or adding @[priority].\n"
else if ¬ lhs_in_nf then do
lhs ← pp lhs,
lhs' ← pp lhs',
pure $ format.to_string $
to_fmt "Left-hand side simplifies from"
++ lhs.group.indent 2 ++ format.line
++ "to" ++ lhs'.group.indent 2 ++ format.line
++ "using " ++ (to_fmt prf1_lems).group.indent 2 ++ format.line
++ "Try to change the left-hand side to the simplified term!\n"
else if ¬ is_cond ∧ lhs = lhs' then do
pure "Left-hand side does not simplify.\nYou need to debug this yourself using `set_option trace.simplify.rewrite true`"
else
pure none
/--
This note gives you some tips to debug any errors that the simp-normal form linter raises
The reason that a lemma was considered faulty is because its left-hand side is not in simp-normal form.
These lemmas are hence never used by the simplifier.
This linter gives you a list of other simp lemmas, look at them!
Here are some tips depending on the error raised by the linter:
1. 'the left-hand side reduces to XYZ':
you should probably use XYZ as the left-hand side.
2. 'simp can prove this':
This typically means that lemma is a duplicate, or is shadowed by another lemma:
2a. Always put more general lemmas after specific ones:
@[simp] lemma zero_add_zero : 0 + 0 = 0 := rfl
@[simp] lemma add_zero : x + 0 = x := rfl
And not the other way around! The simplifier always picks the last matching lemma.
2b. You can also use @[priority] instead of moving simp-lemmas around in the file.
Tip: the default priority is 1000.
Use `@[priority 1100]` instead of moving a lemma down,
and `@[priority 900]` instead of moving a lemma up.
2c. Conditional simp lemmas are tried last, if they are shadowed
just remove the simp attribute.
2d. If two lemmas are duplicates, the linter will complain about the first one.
Try to fix the second one instead!
(You can find it among the other simp lemmas the linter prints out!)
3. 'try_for tactic failed, timeout':
This typically means that there is a loop of simp lemmas.
Try to apply squeeze_simp to the right-hand side (removing this lemma from the simp set) to see
what lemmas might be causing the loop.
Another trick is to `set_option trace.simplify.rewrite true` and
then apply `try_for 10000 { simp }` to the right-hand side. You will
see a periodic sequence of lemma applications in the trace message.
-/
library_note "simp-normal form"
/-- A linter for simp lemmas whose lhs is not in simp-normal form, and which hence never fire. -/
@[linter] meta def linter.simp_nf : linter :=
{ test := simp_nf_linter,
auto_decls := tt,
no_errors_found := "All left-hand sides of simp lemmas are in simp-normal form",
errors_found := "SOME SIMP LEMMAS ARE NOT IN SIMP-NORMAL FORM.
see note [simp-normal form] for tips how to debug this.
https://leanprover-community.github.io/mathlib_docs/notes.html#simp-normal%20form
" }
private meta def simp_var_head (d : declaration) : tactic (option string) := do
tt ← is_simp_lemma d.to_name | pure none,
-- Sometimes, a definition is tagged @[simp] to add the equational lemmas to the simp set.
-- In this case, ignore the declaration if it is not a valid simp lemma by itself.
tt ← is_valid_simp_lemma_cnst d.to_name | pure none,
lhs ← simp_lhs d.type,
head_sym@(expr.local_const _ _ _ _) ← pure lhs.get_app_fn | pure none,
head_sym ← pp head_sym,
pure $ format.to_string $ "Left-hand side has variable as head symbol: " ++ head_sym
/--
A linter for simp lemmas whose lhs has a variable as head symbol,
and which hence never fire.
-/
@[linter] meta def linter.simp_var_head : linter :=
{ test := simp_var_head,
auto_decls := tt,
no_errors_found :=
"No left-hand sides of a simp lemma has a variable as head symbol",
errors_found := "LEFT-HAND SIDE HAS VARIABLE AS HEAD SYMBOL.\n" ++
"Some simp lemmas have a variable as head symbol of the left-hand side" }
private meta def simp_comm (d : declaration) : tactic (option string) := do
tt ← is_simp_lemma d.to_name | pure none,
-- Sometimes, a definition is tagged @[simp] to add the equational lemmas to the simp set.
-- In this case, ignore the declaration if it is not a valid simp lemma by itself.
tt ← is_valid_simp_lemma_cnst d.to_name | pure none,
(lhs, rhs) ← simp_lhs_rhs d.type,
if lhs.get_app_fn.const_name ≠ rhs.get_app_fn.const_name then pure none else do
(lhs', rhs') ← (prod.snd <$> mk_meta_pis d.type) >>= simp_lhs_rhs,
tt ← succeeds $ unify rhs lhs' transparency.reducible | pure none,
tt ← succeeds $ is_def_eq rhs lhs' transparency.reducible | pure none,
-- ensure that the second application makes progress:
ff ← succeeds $ unify lhs' rhs' transparency.reducible | pure none,
pure $ "should not be marked simp"
/-- A linter for commutativity lemmas that are marked simp. -/
@[linter] meta def linter.simp_comm : linter :=
{ test := simp_comm,
auto_decls := tt,
no_errors_found := "No commutativity lemma is marked simp",
errors_found := "COMMUTATIVITY LEMMA IS SIMP.\n" ++
"Some commutativity lemmas are simp lemmas" }
|
6be123a10fd0cf81cbaaca778260095494e5f173 | 9be442d9ec2fcf442516ed6e9e1660aa9071b7bd | /tests/lean/1102.lean | 260b8f35cab64016c082c4524cb9ff6aaa272549 | [
"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 | 860 | lean | class cls12 := (u12 : Unit)
class cls11 extends cls12 := (u11 : Unit)
class cls10 extends cls11 := (u10 : Unit)
class cls9 extends cls10 := (u9 : Unit)
class cls8 extends cls9 := (u8 : Unit)
class cls7 extends cls8 := (u7 : Unit)
class cls6 extends cls7 := (u6 : Unit)
class cls5 extends cls6 := (u5 : Unit)
class cls4 extends cls5 := (u4 : Unit)
class cls3 extends cls4 := (u3 : Unit)
class cls2 extends cls3 := (u2 : Unit)
class cls1 extends cls2 := (u1 : Unit)
class cls0 extends cls1 := (u0 : Unit)
class CommRing (n : Nat) extends cls0 := (ucr : Unit)
class Field (n) extends CommRing n := (uf : Unit)
class DVR (n) [CommRing n] := (udvr : Unit)
instance [c : CommRing n] : CommRing n.succ := { ucr := c.u12 }
instance [Field n] : DVR n.succ := ⟨()⟩
example [CommRing 0] : DVR 1 := by infer_instance -- should fail fast, instead hits maxHeartbeats
|
a3bd86a6bc460752194cd3c3308fb563a6fc16bd | 77c5b91fae1b966ddd1db969ba37b6f0e4901e88 | /src/linear_algebra/matrix/nonsingular_inverse.lean | ae99bc0223b634cbecef3b618a7e71623ed9fd07 | [
"Apache-2.0"
] | permissive | dexmagic/mathlib | ff48eefc56e2412429b31d4fddd41a976eb287ce | 7a5d15a955a92a90e1d398b2281916b9c41270b2 | refs/heads/master | 1,693,481,322,046 | 1,633,360,193,000 | 1,633,360,193,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 30,134 | lean | /-
Copyright (c) 2019 Tim Baanen. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Tim Baanen, Lu-Ming Zhang
-/
import algebra.associated
import algebra.regular.smul
import linear_algebra.matrix.polynomial
import tactic.linarith
import tactic.ring_exp
/-!
# Nonsingular inverses
In this file, we define an inverse for square matrices of invertible
determinant. For matrices that are not square or not of full rank, there is a
more general notion of pseudoinverses which we do not consider here.
The definition of inverse used in this file is the adjugate divided by the determinant.
The adjugate is calculated with Cramer's rule, which we introduce first.
The vectors returned by Cramer's rule are given by the linear map `cramer`,
which sends a matrix `A` and vector `b` to the vector consisting of the
determinant of replacing the `i`th column of `A` with `b` at index `i`
(written as `(A.update_column i b).det`).
Using Cramer's rule, we can compute for each matrix `A` the matrix `adjugate A`.
The entries of the adjugate are the determinants of each minor of `A`.
Instead of defining a minor to be `A` with row `i` and column `j` deleted, we
replace the `i`th row of `A` with the `j`th basis vector; this has the same
determinant as the minor but more importantly equals Cramer's rule applied
to `A` and the `j`th basis vector, simplifying the subsequent proofs.
We prove the adjugate behaves like `det A • A⁻¹`. Finally, we show that dividing
the adjugate by `det A` (if possible), giving a matrix `nonsing_inv A`, will
result in a multiplicative inverse to `A`.
## References
* https://en.wikipedia.org/wiki/Cramer's_rule#Finding_inverse_matrix
## Tags
matrix inverse, cramer, cramer's rule, adjugate
-/
namespace matrix
universes u v
variables {n : Type u} [decidable_eq n] [fintype n] {α : Type v} [comm_ring α]
open_locale matrix big_operators
open equiv equiv.perm finset
section cramer
/-!
### `cramer` section
Introduce the linear map `cramer` with values defined by `cramer_map`.
After defining `cramer_map` and showing it is linear,
we will restrict our proofs to using `cramer`.
-/
variables (A : matrix n n α) (b : n → α)
/--
`cramer_map A b i` is the determinant of the matrix `A` with column `i` replaced with `b`,
and thus `cramer_map A b` is the vector output by Cramer's rule on `A` and `b`.
If `A ⬝ x = b` has a unique solution in `x`, `cramer_map A` sends the vector `b` to `A.det • x`.
Otherwise, the outcome of `cramer_map` is well-defined but not necessarily useful.
-/
def cramer_map (i : n) : α := (A.update_column i b).det
lemma cramer_map_is_linear (i : n) : is_linear_map α (λ b, cramer_map A b i) :=
{ map_add := det_update_column_add _ _,
map_smul := det_update_column_smul _ _ }
lemma cramer_is_linear : is_linear_map α (cramer_map A) :=
begin
split; intros; ext i,
{ apply (cramer_map_is_linear A i).1 },
{ apply (cramer_map_is_linear A i).2 }
end
/--
`cramer A b i` is the determinant of the matrix `A` with column `i` replaced with `b`,
and thus `cramer A b` is the vector output by Cramer's rule on `A` and `b`.
If `A ⬝ x = b` has a unique solution in `x`, `cramer A` sends the vector `b` to `A.det • x`.
Otherwise, the outcome of `cramer` is well-defined but not necessarily useful.
-/
def cramer (A : matrix n n α) : (n → α) →ₗ[α] (n → α) :=
is_linear_map.mk' (cramer_map A) (cramer_is_linear A)
lemma cramer_apply (i : n) : cramer A b i = (A.update_column i b).det := rfl
lemma cramer_transpose_row_self (i : n) :
Aᵀ.cramer (A i) = pi.single i A.det :=
begin
ext j,
rw [cramer_apply, pi.single_apply],
split_ifs with h,
{ -- i = j: this entry should be `A.det`
subst h,
simp only [update_column_transpose, det_transpose, update_row, function.update_eq_self] },
{ -- i ≠ j: this entry should be 0
rw [update_column_transpose, det_transpose],
apply det_zero_of_row_eq h,
rw [update_row_self, update_row_ne (ne.symm h)] }
end
lemma cramer_row_self (i : n) (h : ∀ j, b j = A j i) :
A.cramer b = pi.single i A.det :=
begin
rw [← transpose_transpose A, det_transpose],
convert cramer_transpose_row_self Aᵀ i,
exact funext h
end
@[simp] lemma cramer_one : cramer (1 : matrix n n α) = 1 :=
begin
ext i j,
convert congr_fun (cramer_row_self (1 : matrix n n α) (pi.single i 1) i _) j,
{ simp },
{ intros j, rw [matrix.one_eq_pi_single, pi.single_comm] }
end
@[simp] lemma cramer_subsingleton_apply [subsingleton n] (A : matrix n n α) (b : n → α) (i : n) :
cramer A b i = b i :=
by rw [cramer_apply, det_eq_elem_of_subsingleton _ i, update_column_self]
lemma cramer_zero [nontrivial n] : cramer (0 : matrix n n α) = 0 :=
begin
ext i j,
obtain ⟨j', hj'⟩ : ∃ j', j' ≠ j := exists_ne j,
apply det_eq_zero_of_column_eq_zero j',
intro j'',
simp [update_column_ne hj'],
end
/-- Use linearity of `cramer` to take it out of a summation. -/
lemma sum_cramer {β} (s : finset β) (f : β → n → α) :
∑ x in s, cramer A (f x) = cramer A (∑ x in s, f x) :=
(linear_map.map_sum (cramer A)).symm
/-- Use linearity of `cramer` and vector evaluation to take `cramer A _ i` out of a summation. -/
lemma sum_cramer_apply {β} (s : finset β) (f : n → β → α) (i : n) :
∑ x in s, cramer A (λ j, f j x) i = cramer A (λ (j : n), ∑ x in s, f j x) i :=
calc ∑ x in s, cramer A (λ j, f j x) i
= (∑ x in s, cramer A (λ j, f j x)) i : (finset.sum_apply i s _).symm
... = cramer A (λ (j : n), ∑ x in s, f j x) i :
by { rw [sum_cramer, cramer_apply], congr' with j, apply finset.sum_apply }
end cramer
section adjugate
/-!
### `adjugate` section
Define the `adjugate` matrix and a few equations.
These will hold for any matrix over a commutative ring,
while the `inv` section is specifically for invertible matrices.
-/
/-- The adjugate matrix is the transpose of the cofactor matrix.
Typically, the cofactor matrix is defined by taking the determinant of minors,
i.e. the matrix with a row and column removed.
However, the proof of `mul_adjugate` becomes a lot easier if we define the
minor as replacing a column with a basis vector, since it allows us to use
facts about the `cramer` map.
-/
def adjugate (A : matrix n n α) : matrix n n α := λ i, cramer Aᵀ (λ j, if i = j then 1 else 0)
lemma adjugate_def (A : matrix n n α) :
adjugate A = λ i, cramer Aᵀ (λ j, if i = j then 1 else 0) := rfl
lemma adjugate_apply (A : matrix n n α) (i j : n) :
adjugate A i j = (A.update_row j (λ j, if i = j then 1 else 0)).det :=
by { rw adjugate_def, simp only, rw [cramer_apply, update_column_transpose, det_transpose], }
lemma adjugate_transpose (A : matrix n n α) : (adjugate A)ᵀ = adjugate (Aᵀ) :=
begin
ext i j,
rw [transpose_apply, adjugate_apply, adjugate_apply, update_row_transpose, det_transpose],
rw [det_apply', det_apply'],
apply finset.sum_congr rfl,
intros σ _,
congr' 1,
by_cases i = σ j,
{ -- Everything except `(i , j)` (= `(σ j , j)`) is given by A, and the rest is a single `1`.
congr; ext j',
have := (@equiv.injective _ _ σ j j' : σ j = σ j' → j = j'),
rw [update_row_apply, update_column_apply],
finish },
{ -- Otherwise, we need to show that there is a `0` somewhere in the product.
have : (∏ j' : n, update_column A j (λ (i' : n), ite (i = i') 1 0) (σ j') j') = 0,
{ apply prod_eq_zero (mem_univ j),
rw [update_column_self],
exact if_neg h },
rw this,
apply prod_eq_zero (mem_univ (σ⁻¹ i)),
erw [apply_symm_apply σ i, update_row_self],
apply if_neg,
intro h',
exact h ((symm_apply_eq σ).mp h'.symm) }
end
/-- Since the map `b ↦ cramer A b` is linear in `b`, it must be multiplication by some matrix. This
matrix is `A.adjugate`. -/
lemma cramer_eq_adjugate_mul_vec (A : matrix n n α) (b : n → α) :
cramer A b = A.adjugate.mul_vec b :=
begin
nth_rewrite 1 ← A.transpose_transpose,
rw [← adjugate_transpose, adjugate_def],
have : b = ∑ i, (b i) • (λ j, if i = j then 1 else 0), { ext i, simp, },
rw this, ext k,
simp [mul_vec, dot_product, mul_comm],
end
lemma mul_adjugate_apply (A : matrix n n α) (i j k) :
A i k * adjugate A k j = cramer Aᵀ (λ j, if k = j then A i k else 0) j :=
begin
erw [←smul_eq_mul, ←pi.smul_apply, ←linear_map.map_smul],
congr' with l,
rw [pi.smul_apply, smul_eq_mul, mul_boole],
end
lemma mul_adjugate (A : matrix n n α) : A ⬝ adjugate A = A.det • 1 :=
begin
ext i j,
rw [mul_apply, pi.smul_apply, pi.smul_apply, one_apply, smul_eq_mul, mul_boole],
simp [mul_adjugate_apply, sum_cramer_apply, cramer_transpose_row_self, pi.single_apply, eq_comm]
end
lemma adjugate_mul (A : matrix n n α) : adjugate A ⬝ A = A.det • 1 :=
calc adjugate A ⬝ A = (Aᵀ ⬝ (adjugate Aᵀ))ᵀ :
by rw [←adjugate_transpose, ←transpose_mul, transpose_transpose]
... = A.det • 1 : by rw [mul_adjugate (Aᵀ), det_transpose, transpose_smul, transpose_one]
/-- `det_adjugate_of_cancel` is an auxiliary lemma for computing `(adjugate A).det`,
used in `det_adjugate_eq_one` and `det_adjugate_of_is_unit`.
The formula for the determinant of the adjugate of an `n` by `n` matrix `A`
is in general `(adjugate A).det = A.det ^ (n - 1)`, but the proof differs in several cases.
This lemma `det_adjugate_of_cancel` covers the case that `det A` cancels
on the left of the equation `A.det * b = A.det ^ n`.
-/
lemma det_adjugate_of_cancel {A : matrix n n α}
(h : ∀ b, A.det * b = A.det ^ fintype.card n → b = A.det ^ (fintype.card n - 1)) :
(adjugate A).det = A.det ^ (fintype.card n - 1) :=
h (adjugate A).det (calc A.det * (adjugate A).det = (A ⬝ adjugate A).det : (det_mul _ _).symm
... = A.det ^ fintype.card n : by simp [mul_adjugate])
lemma adjugate_subsingleton [subsingleton n] (A : matrix n n α) : adjugate A = 1 :=
begin
ext i j,
simp [subsingleton.elim i j, adjugate_apply, det_eq_elem_of_subsingleton _ i]
end
lemma adjugate_eq_one_of_card_eq_one {A : matrix n n α} (h : fintype.card n = 1) : adjugate A = 1 :=
begin
haveI : subsingleton n := fintype.card_le_one_iff_subsingleton.mp h.le,
exact adjugate_subsingleton _
end
@[simp] lemma adjugate_zero (h : 1 < fintype.card n) : adjugate (0 : matrix n n α) = 0 :=
begin
ext i j,
obtain ⟨j', hj'⟩ : ∃ j', j' ≠ j := fintype.exists_ne_of_one_lt_card h j,
apply det_eq_zero_of_column_eq_zero j',
intro j'',
simp [update_column_ne hj'],
end
@[simp] lemma adjugate_one : adjugate (1 : matrix n n α) = 1 :=
by { ext, simp [adjugate_def, matrix.one_apply] }
lemma det_adjugate_eq_one {A : matrix n n α} (h : A.det = 1) : (adjugate A).det = 1 :=
calc (adjugate A).det
= A.det ^ (fintype.card n - 1) : det_adjugate_of_cancel (λ b hb, by simpa [h] using hb)
... = 1 : by rw [h, one_pow]
/-- `det_adjugate_of_is_unit` gives the formula for `(adjugate A).det` if `A.det` has an inverse.
The formula for the determinant of the adjugate of an `n` by `n` matrix `A`
is in general `(adjugate A).det = A.det ^ (n - 1)`, but the proof differs in several cases.
This lemma `det_adjugate_of_is_unit` covers the case that `det A` has an inverse.
-/
lemma det_adjugate_of_is_unit {A : matrix n n α} (h : is_unit A.det) :
(adjugate A).det = A.det ^ (fintype.card n - 1) :=
begin
rcases is_unit_iff_exists_inv'.mp h with ⟨a, ha⟩,
by_cases card_lt_zero : fintype.card n ≤ 0,
{ have h : fintype.card n = 0 := by linarith,
simp [det_eq_one_of_card_eq_zero h] },
have zero_lt_card : 0 < fintype.card n := by linarith,
have n_nonempty : nonempty n := fintype.card_pos_iff.mp zero_lt_card,
by_cases card_lt_one : fintype.card n ≤ 1,
{ have h : fintype.card n = 1 := by linarith,
simp [h, adjugate_eq_one_of_card_eq_one h] },
have one_lt_card : 1 < fintype.card n := by linarith,
have zero_lt_card_sub_one : 0 < fintype.card n - 1 :=
(nat.sub_lt_sub_right_iff (refl 1)).mpr one_lt_card,
apply det_adjugate_of_cancel,
intros b hb,
calc b = a * (det A ^ (fintype.card n - 1 + 1)) :
by rw [←one_mul b, ←ha, mul_assoc, hb, nat.sub_add_cancel zero_lt_card]
... = a * det A * det A ^ (fintype.card n - 1) : by ring_exp
... = det A ^ (fintype.card n - 1) : by rw [ha, one_mul]
end
end adjugate
section inv
/-!
### `inv` section
Defines the matrix `nonsing_inv A` and proves it is the inverse matrix
of a square matrix `A` as long as `det A` has a multiplicative inverse.
-/
variables (A : matrix n n α) (B : matrix n n α)
open_locale classical
lemma is_unit_det_transpose (h : is_unit A.det) : is_unit Aᵀ.det :=
by { rw det_transpose, exact h, }
/-- The inverse of a square matrix, when it is invertible (and zero otherwise).-/
noncomputable def nonsing_inv : matrix n n α :=
if h : is_unit A.det then h.unit⁻¹ • A.adjugate else 0
noncomputable instance : has_inv (matrix n n α) := ⟨matrix.nonsing_inv⟩
lemma inv_def (A : matrix n n α) : A⁻¹ = A.nonsing_inv := rfl
lemma nonsing_inv_apply_not_is_unit (h : ¬ is_unit A.det) :
A⁻¹ = 0 :=
by rw [inv_def, nonsing_inv, dif_neg h]
lemma nonsing_inv_apply (h : is_unit A.det) :
A⁻¹ = h.unit⁻¹ • A.adjugate :=
by rw [inv_def, nonsing_inv, dif_pos h]
lemma transpose_nonsing_inv (h : is_unit A.det) :
(A⁻¹)ᵀ = (Aᵀ)⁻¹ :=
begin
have h' := A.is_unit_det_transpose h,
have dets_eq : h.unit = h'.unit := units.ext (by rw [h.unit_spec, h'.unit_spec, det_transpose]),
rw [A.nonsing_inv_apply h, Aᵀ.nonsing_inv_apply h', dets_eq, A.adjugate_transpose.symm],
refl,
end
/-- The `nonsing_inv` of `A` is a right inverse. -/
@[simp] lemma mul_nonsing_inv (h : is_unit A.det) : A ⬝ A⁻¹ = 1 :=
by rw [A.nonsing_inv_apply h, units.smul_def, mul_smul, mul_adjugate, smul_smul,
units.inv_mul_of_eq h.unit_spec, one_smul]
/-- The `nonsing_inv` of `A` is a left inverse. -/
@[simp] lemma nonsing_inv_mul (h : is_unit A.det) : A⁻¹ ⬝ A = 1 :=
calc A⁻¹ ⬝ A = (Aᵀ ⬝ (Aᵀ)⁻¹)ᵀ : by { rw [transpose_mul,
Aᵀ.transpose_nonsing_inv (A.is_unit_det_transpose h),
transpose_transpose], }
... = 1ᵀ : by { rw Aᵀ.mul_nonsing_inv, exact A.is_unit_det_transpose h, }
... = 1 : transpose_one
lemma nonsing_inv_cancel_or_zero :
(A⁻¹ ⬝ A = 1 ∧ A ⬝ A⁻¹ = 1) ∨ A⁻¹ = 0 :=
begin
by_cases h : is_unit A.det,
{ exact or.inl ⟨nonsing_inv_mul _ h, mul_nonsing_inv _ h⟩ },
{ exact or.inr (nonsing_inv_apply_not_is_unit _ h) }
end
@[simp] lemma nonsing_inv_det (h : is_unit A.det) : A⁻¹.det * A.det = 1 :=
by rw [←det_mul, A.nonsing_inv_mul h, det_one]
lemma is_unit_nonsing_inv_det (h : is_unit A.det) : is_unit A⁻¹.det :=
is_unit_of_mul_eq_one _ _ (A.nonsing_inv_det h)
@[simp] lemma nonsing_inv_nonsing_inv (h : is_unit A.det) : (A⁻¹)⁻¹ = A :=
calc (A⁻¹)⁻¹ = 1 ⬝ (A⁻¹)⁻¹ : by rw matrix.one_mul
... = A ⬝ A⁻¹ ⬝ (A⁻¹)⁻¹ : by rw A.mul_nonsing_inv h
... = A : by { rw [matrix.mul_assoc,
(A⁻¹).mul_nonsing_inv (A.is_unit_nonsing_inv_det h),
matrix.mul_one], }
@[simp] lemma is_unit_nonsing_inv_det_iff {A : matrix n n α} :
is_unit A⁻¹.det ↔ is_unit A.det :=
begin
refine ⟨λ h, _, is_unit_nonsing_inv_det _⟩,
nontriviality α,
casesI is_empty_or_nonempty n,
{ simp },
contrapose! h,
rw [nonsing_inv_apply_not_is_unit _ h, det_zero],
{ simp },
{ apply_instance }
end
/-- If `A.det` has a constructive inverse, produce one for `A`. -/
def invertible_of_det_invertible [invertible A.det] : invertible A :=
{ inv_of := ⅟A.det • A.adjugate,
mul_inv_of_self :=
by rw [mul_smul_comm, matrix.mul_eq_mul, mul_adjugate, smul_smul, inv_of_mul_self, one_smul],
inv_of_mul_self :=
by rw [smul_mul_assoc, matrix.mul_eq_mul, adjugate_mul, smul_smul, inv_of_mul_self, one_smul] }
/-- `A.det` is invertible if `A` has a left inverse. -/
def det_invertible_of_left_inverse (h : B ⬝ A = 1) : invertible A.det :=
{ inv_of := B.det,
mul_inv_of_self := by rw [mul_comm, ← det_mul, h, det_one],
inv_of_mul_self := by rw [← det_mul, h, det_one] }
/-- `A.det` is invertible if `A` has a right inverse. -/
def det_invertible_of_right_inverse (h : A ⬝ B = 1) : invertible A.det :=
{ inv_of := B.det,
mul_inv_of_self := by rw [← det_mul, h, det_one],
inv_of_mul_self := by rw [mul_comm, ← det_mul, h, det_one] }
/-- If `A` has a constructive inverse, produce one for `A.det`. -/
def det_invertible_of_invertible [invertible A] : invertible A.det :=
det_invertible_of_left_inverse A (⅟A) (inv_of_mul_self _)
/-- Given a proof that `A.det` has a constructive inverse, lift `A` to `units (matrix n n α)`-/
def unit_of_det_invertible [invertible A.det] : units (matrix n n α) :=
@unit_of_invertible _ _ A (invertible_of_det_invertible A)
/-- A matrix whose determinant is a unit is itself a unit. This is a noncomputable version of
`matrix.units_of_det_invertible`, with the inverse defeq to `matrix.nonsing_inv`. -/
noncomputable def nonsing_inv_unit (h : is_unit A.det) : units (matrix n n α) :=
{ val := A,
inv := A⁻¹,
val_inv := by { rw matrix.mul_eq_mul, apply A.mul_nonsing_inv h, },
inv_val := by { rw matrix.mul_eq_mul, apply A.nonsing_inv_mul h, } }
lemma unit_of_det_invertible_eq_nonsing_inv_unit [invertible A.det] :
unit_of_det_invertible A = nonsing_inv_unit A (is_unit_of_invertible _) :=
by { ext, refl }
/-- When lowered to a prop, `matrix.det_invertible_of_invertible` and
`matrix.invertible_of_det_invertible` form an `iff`. -/
lemma is_unit_iff_is_unit_det : is_unit A ↔ is_unit A.det :=
begin
split; rintros ⟨x, hx⟩; refine @is_unit_of_invertible _ _ _ (id _),
{ haveI : invertible A := hx.rec x.invertible,
apply det_invertible_of_invertible, },
{ haveI : invertible A.det := hx.rec x.invertible,
apply invertible_of_det_invertible, },
end
/- `is_unit_of_invertible A`
converts the "stronger" condition `invertible A` to proposition `is_unit A`. -/
/-- `matrix.is_unit_det_of_invertible` converts `invertible A` to `is_unit A.det`. -/
lemma is_unit_det_of_invertible [invertible A] : is_unit A.det :=
@is_unit_of_invertible _ _ _(det_invertible_of_invertible A)
@[simp]
lemma inv_eq_nonsing_inv_of_invertible [invertible A] : ⅟ A = A⁻¹ :=
begin
suffices : is_unit A,
{ rw [←this.mul_left_inj, inv_of_mul_self, matrix.mul_eq_mul, nonsing_inv_mul],
rwa ←is_unit_iff_is_unit_det },
exact is_unit_of_invertible _
end
variables {A} {B}
/- `is_unit.invertible` lifts the proposition `is_unit A` to a constructive inverse of `A`. -/
/-- "Lift" the proposition `is_unit A.det` to a constructive inverse of `A`. -/
noncomputable def invertible_of_is_unit_det (h : is_unit A.det) : invertible A :=
⟨A⁻¹, nonsing_inv_mul A h, mul_nonsing_inv A h⟩
lemma is_unit_det_of_left_inverse (h : B ⬝ A = 1) : is_unit A.det :=
@is_unit_of_invertible _ _ _ (det_invertible_of_left_inverse _ _ h)
lemma is_unit_det_of_right_inverse (h : A ⬝ B = 1) : is_unit A.det :=
@is_unit_of_invertible _ _ _ (det_invertible_of_right_inverse _ _ h)
lemma det_ne_zero_of_left_inverse [nontrivial α] (h : B ⬝ A = 1) : A.det ≠ 0 :=
is_unit.ne_zero (matrix.is_unit_det_of_left_inverse h)
lemma det_ne_zero_of_right_inverse [nontrivial α] (h : A ⬝ B = 1) : A.det ≠ 0 :=
is_unit.ne_zero (matrix.is_unit_det_of_right_inverse h)
lemma nonsing_inv_left_right (h : A ⬝ B = 1) : B ⬝ A = 1 :=
begin
have h' : is_unit B.det := is_unit_det_of_left_inverse h,
calc B ⬝ A = (B ⬝ A) ⬝ (B ⬝ B⁻¹) : by simp only [h', matrix.mul_one, mul_nonsing_inv]
... = B ⬝ ((A ⬝ B) ⬝ B⁻¹) : by simp only [matrix.mul_assoc]
... = B ⬝ B⁻¹ : by simp only [h, matrix.one_mul]
... = 1 : mul_nonsing_inv B h',
end
lemma nonsing_inv_right_left (h : B ⬝ A = 1) : A ⬝ B = 1 :=
nonsing_inv_left_right h
/-- If matrix A is left invertible, then its inverse equals its left inverse. -/
lemma inv_eq_left_inv (h : B ⬝ A = 1) : A⁻¹ = B :=
begin
have h1 := (is_unit_det_of_left_inverse h),
have h2 := matrix.invertible_of_is_unit_det h1,
have := @inv_of_eq_left_inv (matrix n n α) (infer_instance) A B h2 h,
simp* at *,
end
/-- If matrix A is right invertible, then its inverse equals its right inverse. -/
lemma inv_eq_right_inv (h : A ⬝ B = 1) : A⁻¹ = B :=
begin
have h1 := (is_unit_det_of_right_inverse h),
have h2 := matrix.invertible_of_is_unit_det h1,
have := @inv_of_eq_right_inv (matrix n n α) (infer_instance) A B h2 h,
simp* at *,
end
/-- We can construct an instance of invertible A if A has a left inverse. -/
def invertible_of_left_inverse (h: B ⬝ A = 1) : invertible A :=
⟨B, h, nonsing_inv_right_left h⟩
/-- We can construct an instance of invertible A if A has a right inverse. -/
def invertible_of_right_inverse (h: A ⬝ B = 1) : invertible A :=
⟨B, nonsing_inv_left_right h, h⟩
section inv_eq_inv
variables {C : matrix n n α}
/-- The left inverse of matrix A is unique when existing. -/
lemma left_inv_eq_left_inv (h: B ⬝ A = 1) (g: C ⬝ A = 1) : B = C :=
by rw [←(inv_eq_left_inv h), ←(inv_eq_left_inv g)]
/-- The right inverse of matrix A is unique when existing. -/
lemma right_inv_eq_right_inv (h: A ⬝ B = 1) (g: A ⬝ C = 1) : B = C :=
by rw [←(inv_eq_right_inv h), ←(inv_eq_right_inv g)]
/-- The right inverse of matrix A equals the left inverse of A when they exist. -/
lemma right_inv_eq_left_inv (h: A ⬝ B = 1) (g: C ⬝ A = 1) : B = C :=
by rw [←(inv_eq_right_inv h), ←(inv_eq_left_inv g)]
lemma inv_inj (h : A⁻¹ = B⁻¹) (h' : is_unit A.det) : A = B :=
begin
refine left_inv_eq_left_inv (mul_nonsing_inv _ h') _,
rw h,
refine mul_nonsing_inv _ _,
rwa [←is_unit_nonsing_inv_det_iff, ←h, is_unit_nonsing_inv_det_iff]
end
end inv_eq_inv
variable (A)
@[simp] lemma mul_inv_of_invertible [invertible A] : A ⬝ A⁻¹ = 1 :=
mul_nonsing_inv A (is_unit_det_of_invertible A)
@[simp] lemma inv_mul_of_invertible [invertible A] : A⁻¹ ⬝ A = 1 :=
nonsing_inv_mul A (is_unit_det_of_invertible A)
@[simp] lemma inv_zero : (0 : matrix n n α)⁻¹ = 0 :=
begin
casesI (subsingleton_or_nontrivial α) with ht ht,
{ simp },
cases (fintype.card n).zero_le.eq_or_lt with hc hc,
{ rw [eq_comm, fintype.card_eq_zero_iff] at hc,
haveI := hc,
ext i,
exact (is_empty.false i).elim },
{ have hn : nonempty n := fintype.card_pos_iff.mp hc,
refine nonsing_inv_apply_not_is_unit _ _,
simp [hn] },
end
@[simp] lemma inv_one : (1 : matrix n n α)⁻¹ = 1 :=
inv_eq_left_inv (by simp)
lemma inv_smul (k : α) [invertible k] (h : is_unit A.det) : (k • A)⁻¹ = ⅟k • A⁻¹ :=
inv_eq_left_inv (by simp [h, smul_smul])
lemma inv_smul' (k : units α) (h : is_unit A.det) : (k • A)⁻¹ = k⁻¹ • A⁻¹ :=
inv_eq_left_inv (by simp [h, smul_smul])
lemma inv_adjugate (A : matrix n n α) (h : is_unit A.det) :
(adjugate A)⁻¹ = h.unit⁻¹ • A :=
begin
refine inv_eq_left_inv _,
rw [smul_mul, mul_adjugate, units.smul_def, smul_smul, h.coe_inv_mul, one_smul]
end
@[simp] lemma inv_inv_inv (A : matrix n n α) : A⁻¹⁻¹⁻¹ = A⁻¹ :=
begin
by_cases h : is_unit A.det,
{ rw [nonsing_inv_nonsing_inv _ h] },
{ simp [nonsing_inv_apply_not_is_unit _ h] }
end
lemma mul_inv_rev (A B : matrix n n α) : (A ⬝ B)⁻¹ = B⁻¹ ⬝ A⁻¹ :=
begin
by_cases h : is_unit (A ⬝ B).det,
{ refine inv_eq_left_inv _,
rw det_mul at h,
rw [←matrix.mul_assoc, matrix.mul_assoc _ _ A,
nonsing_inv_mul _ (is_unit_of_mul_is_unit_left h),
matrix.mul_one, nonsing_inv_mul _ (is_unit_of_mul_is_unit_right h)] },
{ rw nonsing_inv_apply_not_is_unit _ h,
rw det_mul at h,
have : ¬ is_unit A.det ∨ ¬ is_unit B.det,
{ contrapose! h,
exact h.left.mul h.right },
cases this with h' h';
simp [nonsing_inv_apply_not_is_unit _ h'] }
end
lemma ring_hom.map_adjugate {R S : Type*} [comm_ring R] [comm_ring S] (f : R →+* S)
(M : matrix n n R) : f.map_matrix M.adjugate = matrix.adjugate (f.map_matrix M) :=
begin
ext i k,
have : (λ (j : n), ite (i = j) (1 : S) 0) = f ∘ (λ (j : n), ite (i = j) 1 0),
{ ext,
simp [apply_ite f] },
rw [adjugate_apply, ring_hom.map_matrix_apply, map_apply, ring_hom.map_matrix_apply,
this, ←map_update_row, ←ring_hom.map_matrix_apply, ←ring_hom.map_det, ←adjugate_apply]
end
lemma is_regular_of_is_left_regular_det {A : matrix n n α} (hA : is_left_regular A.det) :
is_regular A :=
begin
split,
{ intros B C h,
refine hA.matrix _,
rw [←matrix.one_mul B, ←matrix.one_mul C, ←matrix.smul_mul, ←matrix.smul_mul, ←adjugate_mul,
matrix.mul_assoc, matrix.mul_assoc, ←mul_eq_mul A, h, mul_eq_mul] },
{ intros B C h,
simp only [mul_eq_mul] at h,
refine hA.matrix _,
rw [←matrix.mul_one B, ←matrix.mul_one C, ←matrix.mul_smul, ←matrix.mul_smul, ←mul_adjugate,
←matrix.mul_assoc, ←matrix.mul_assoc, h] }
end
lemma adjugate_mul_distrib_aux (A B : matrix n n α)
(hA : is_left_regular A.det)
(hB : is_left_regular B.det) :
adjugate (A ⬝ B) = adjugate B ⬝ adjugate A :=
begin
have hAB : is_left_regular (A ⬝ B).det,
{ rw [det_mul],
exact hA.mul hB },
refine (is_regular_of_is_left_regular_det hAB).left _,
rw [mul_eq_mul, mul_adjugate, mul_eq_mul, matrix.mul_assoc, ←matrix.mul_assoc B, mul_adjugate,
smul_mul, matrix.one_mul, mul_smul, mul_adjugate, smul_smul, mul_comm, ←det_mul]
end
/--
Proof follows from "The trace Cayley-Hamilton theorem" by Darij Grinberg, Section 5.3
-/
lemma adjugate_mul_distrib (A B : matrix n n α) : adjugate (A ⬝ B) = adjugate B ⬝ adjugate A :=
begin
casesI subsingleton_or_nontrivial α,
{ simp },
let g : matrix n n α → matrix n n (polynomial α) :=
λ M, M.map polynomial.C + (polynomial.X : polynomial α) • 1,
let f' : matrix n n (polynomial α) →+* matrix n n α := (polynomial.eval_ring_hom 0).map_matrix,
have f'_inv : ∀ M, f' (g M) = M,
{ intro,
ext,
simp [f', g], },
have f'_adj : ∀ (M : matrix n n α), f' (adjugate (g M)) = adjugate M,
{ intro,
rw [ring_hom.map_adjugate, f'_inv] },
have f'_g_mul : ∀ (M N : matrix n n α), f' (g M ⬝ g N) = M ⬝ N,
{ intros,
rw [←mul_eq_mul, ring_hom.map_mul, f'_inv, f'_inv, mul_eq_mul] },
have hu : ∀ (M : matrix n n α), is_regular (g M).det,
{ intros M,
refine polynomial.monic.is_regular _,
simp only [g, polynomial.monic.def, ←polynomial.leading_coeff_det_X_one_add_C M, add_comm] },
rw [←f'_adj, ←f'_adj, ←f'_adj, ←mul_eq_mul (f' (adjugate (g B))), ←f'.map_mul, mul_eq_mul,
←adjugate_mul_distrib_aux _ _ (hu A).left (hu B).left, ring_hom.map_adjugate,
ring_hom.map_adjugate, f'_inv, f'_g_mul]
end
@[simp] lemma adjugate_pow (A : matrix n n α) (k : ℕ) :
adjugate (A ^ k) = (adjugate A) ^ k :=
begin
induction k with k IH,
{ simp },
{ rw [pow_succ', mul_eq_mul, adjugate_mul_distrib, IH, ←mul_eq_mul, pow_succ] }
end
end inv
/-- One form of Cramer's rule -/
@[simp] lemma det_smul_inv_mul_vec_eq_cramer (A : matrix n n α) (b : n → α) (h : is_unit A.det) :
A.det • A⁻¹.mul_vec b = cramer A b :=
begin
rw [cramer_eq_adjugate_mul_vec, A.nonsing_inv_apply h, ← smul_mul_vec_assoc, units.smul_def,
smul_smul, h.mul_coe_inv, one_smul]
end
/-- A stronger form of **Cramer's rule** that allows us to solve some instances of `A ⬝ x = b` even
if the determinant is not a unit. A sufficient (but still not necessary) condition is that `A.det`
divides `b`. -/
@[simp] lemma mul_vec_cramer (A : matrix n n α) (b : n → α) :
A.mul_vec (cramer A b) = A.det • b :=
by rw [cramer_eq_adjugate_mul_vec, mul_vec_mul_vec, mul_adjugate, smul_mul_vec_assoc, one_mul_vec]
section nondegenerate
variables {m R A : Type*} [fintype m] [comm_ring R] [integral_domain A]
/-- A matrix `M` is nondegenerate if for all `v ≠ 0`, there is a `w ≠ 0` with `w ⬝ M ⬝ v ≠ 0`. -/
def nondegenerate (M : matrix m m R) :=
∀ v, (∀ w, matrix.dot_product v (mul_vec M w) = 0) → v = 0
/-- If `M` is nondegenerate and `w ⬝ M ⬝ v = 0` for all `w`, then `v = 0`. -/
lemma nondegenerate.eq_zero_of_ortho {M : matrix m m R} (hM : nondegenerate M)
{v : m → R} (hv : ∀ w, matrix.dot_product v (mul_vec M w) = 0) : v = 0 :=
hM v hv
/-- If `M` is nondegenerate and `v ≠ 0`, then there is some `w` such that `w ⬝ M ⬝ v ≠ 0`. -/
lemma nondegenerate.exists_not_ortho_of_ne_zero {M : matrix m m R} (hM : nondegenerate M)
{v : m → R} (hv : v ≠ 0) : ∃ w, matrix.dot_product v (mul_vec M w) ≠ 0 :=
not_forall.mp (mt hM.eq_zero_of_ortho hv)
/-- If `M` has a nonzero determinant, then `M` as a bilinear form on `n → A` is nondegenerate.
See also `bilin_form.nondegenerate_of_det_ne_zero'` and `bilin_form.nondegenerate_of_det_ne_zero`.
-/
theorem nondegenerate_of_det_ne_zero {M : matrix n n A} (hM : M.det ≠ 0) :
nondegenerate M :=
begin
intros v hv,
ext i,
specialize hv (M.cramer (pi.single i 1)),
refine (mul_eq_zero.mp _).resolve_right hM,
convert hv,
simp only [mul_vec_cramer M (pi.single i 1), dot_product, pi.smul_apply, smul_eq_mul],
rw [finset.sum_eq_single i, pi.single_eq_same, mul_one],
{ intros j _ hj, simp [hj] },
{ intros, have := finset.mem_univ i, contradiction }
end
theorem eq_zero_of_vec_mul_eq_zero {M : matrix n n A} (hM : M.det ≠ 0) {v : n → A}
(hv : M.vec_mul v = 0) : v = 0 :=
(nondegenerate_of_det_ne_zero hM).eq_zero_of_ortho
(λ w, by rw [dot_product_mul_vec, hv, zero_dot_product])
theorem eq_zero_of_mul_vec_eq_zero {M : matrix n n A} (hM : M.det ≠ 0) {v : n → A}
(hv : M.mul_vec v = 0) :
v = 0 :=
eq_zero_of_vec_mul_eq_zero (by rwa det_transpose) ((vec_mul_transpose M v).trans hv)
end nondegenerate
end matrix
|
d5614dc9511fe7ec98ed3e11163789d282a71caa | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/group_theory/subsemigroup/membership.lean | 8a67a43ff7ea38ce9b7d302b3958fd6dabe79ea4 | [
"Apache-2.0"
] | permissive | jcommelin/mathlib | d8456447c36c176e14d96d9e76f39841f69d2d9b | ee8279351a2e434c2852345c51b728d22af5a156 | refs/heads/master | 1,664,782,136,488 | 1,663,638,983,000 | 1,663,638,983,000 | 132,563,656 | 0 | 0 | Apache-2.0 | 1,663,599,929,000 | 1,525,760,539,000 | Lean | UTF-8 | Lean | false | false | 4,885 | lean | /-
Copyright (c) 2022 Jireh Loreaux. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jireh Loreaux
-/
import group_theory.subsemigroup.operations
/-!
# Subsemigroups: membership criteria
In this file we prove various facts about membership in a subsemigroup.
The intent is to mimic `group_theory/submonoid/membership`, but currently this file is mostly a
stub and only provides rudimentary support.
* `mem_supr_of_directed`, `coe_supr_of_directed`, `mem_Sup_of_directed_on`,
`coe_Sup_of_directed_on`: the supremum of a directed collection of subsemigroup is their union.
## TODO
* Define the `free_semigroup` generated by a set. This might require some rather substantial
additions to low-level API. For example, developing the subtype of nonempty lists, then defining
a product on nonempty lists, powers where the exponent is a positive natural, et cetera.
Another option would be to define the `free_semigroup` as the subsemigroup (pushed to be a
semigroup) of the `free_monoid` consisting of non-identity elements.
## Tags
subsemigroup
-/
variables {ι : Sort*} {M A B : Type*}
section non_assoc
variables [has_mul M]
open set
namespace subsemigroup
-- TODO: this section can be generalized to `[mul_mem_class B M] [complete_lattice B]`
-- such that `complete_lattice.le` coincides with `set_like.le`
@[to_additive]
lemma mem_supr_of_directed {S : ι → subsemigroup M} (hS : directed (≤) S) {x : M} :
x ∈ (⨆ i, S i) ↔ ∃ i, x ∈ S i :=
begin
refine ⟨_, λ ⟨i, hi⟩, (set_like.le_def.1 $ le_supr S i) hi⟩,
suffices : x ∈ closure (⋃ i, (S i : set M)) → ∃ i, x ∈ S i,
by simpa only [closure_Union, closure_eq (S _)] using this,
refine (λ hx, closure_induction hx (λ y hy, mem_Union.mp hy) _),
{ rintros x y ⟨i, hi⟩ ⟨j, hj⟩,
rcases hS i j with ⟨k, hki, hkj⟩,
exact ⟨k, (S k).mul_mem (hki hi) (hkj hj)⟩ }
end
@[to_additive]
lemma coe_supr_of_directed {S : ι → subsemigroup M} (hS : directed (≤) S) :
((⨆ i, S i : subsemigroup M) : set M) = ⋃ i, ↑(S i) :=
set.ext $ λ x, by simp [mem_supr_of_directed hS]
@[to_additive]
lemma mem_Sup_of_directed_on {S : set (subsemigroup M)}
(hS : directed_on (≤) S) {x : M} :
x ∈ Sup S ↔ ∃ s ∈ S, x ∈ s :=
by simp only [Sup_eq_supr', mem_supr_of_directed hS.directed_coe, set_coe.exists, subtype.coe_mk]
@[to_additive]
lemma coe_Sup_of_directed_on {S : set (subsemigroup M)}
(hS : directed_on (≤) S) :
(↑(Sup S) : set M) = ⋃ s ∈ S, ↑s :=
set.ext $ λ x, by simp [mem_Sup_of_directed_on hS]
@[to_additive]
lemma mem_sup_left {S T : subsemigroup M} : ∀ {x : M}, x ∈ S → x ∈ S ⊔ T :=
show S ≤ S ⊔ T, from le_sup_left
@[to_additive]
lemma mem_sup_right {S T : subsemigroup M} : ∀ {x : M}, x ∈ T → x ∈ S ⊔ T :=
show T ≤ S ⊔ T, from le_sup_right
@[to_additive]
lemma mul_mem_sup {S T : subsemigroup M} {x y : M} (hx : x ∈ S) (hy : y ∈ T) : x * y ∈ S ⊔ T :=
mul_mem (mem_sup_left hx) (mem_sup_right hy)
@[to_additive]
lemma mem_supr_of_mem {S : ι → subsemigroup M} (i : ι) :
∀ {x : M}, x ∈ S i → x ∈ supr S :=
show S i ≤ supr S, from le_supr _ _
@[to_additive]
lemma mem_Sup_of_mem {S : set (subsemigroup M)} {s : subsemigroup M}
(hs : s ∈ S) : ∀ {x : M}, x ∈ s → x ∈ Sup S :=
show s ≤ Sup S, from le_Sup hs
/-- An induction principle for elements of `⨆ i, S i`.
If `C` holds all elements of `S i` for all `i`, and is preserved under multiplication,
then it holds for all elements of the supremum of `S`. -/
@[elab_as_eliminator, to_additive /-" An induction principle for elements of `⨆ i, S i`.
If `C` holds all elements of `S i` for all `i`, and is preserved under addition,
then it holds for all elements of the supremum of `S`. "-/]
lemma supr_induction (S : ι → subsemigroup M) {C : M → Prop} {x : M} (hx : x ∈ ⨆ i, S i)
(hp : ∀ i (x ∈ S i), C x)
(hmul : ∀ x y, C x → C y → C (x * y)) : C x :=
begin
rw supr_eq_closure at hx,
refine closure_induction hx (λ x hx, _) hmul,
obtain ⟨i, hi⟩ := set.mem_Union.mp hx,
exact hp _ _ hi,
end
/-- A dependent version of `subsemigroup.supr_induction`. -/
@[elab_as_eliminator, to_additive /-"A dependent version of `add_subsemigroup.supr_induction`. "-/]
lemma supr_induction' (S : ι → subsemigroup M) {C : Π x, (x ∈ ⨆ i, S i) → Prop}
(hp : ∀ i (x ∈ S i), C x (mem_supr_of_mem i ‹_›))
(hmul : ∀ x y hx hy, C x hx → C y hy → C (x * y) (mul_mem ‹_› ‹_›))
{x : M} (hx : x ∈ ⨆ i, S i) : C x hx :=
begin
refine exists.elim _ (λ (hx : x ∈ ⨆ i, S i) (hc : C x hx), hc),
refine supr_induction S hx (λ i x hx, _) (λ x y, _),
{ exact ⟨_, hp _ _ hx⟩ },
{ rintro ⟨_, Cx⟩ ⟨_, Cy⟩,
exact ⟨_, hmul _ _ _ _ Cx Cy⟩ },
end
end subsemigroup
end non_assoc
|
0d521b65836ec4c74704749cf0d87cc48a99d492 | 2c096fdfecf64e46ea7bc6ce5521f142b5926864 | /tests/lean/run/1852.lean | 868f079fdb4ef5eb97889270f50f10c91d7aafe8 | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | Kha/lean4 | 1005785d2c8797ae266a303968848e5f6ce2fe87 | b99e11346948023cd6c29d248cd8f3e3fb3474cf | refs/heads/master | 1,693,355,498,027 | 1,669,080,461,000 | 1,669,113,138,000 | 184,748,176 | 0 | 0 | Apache-2.0 | 1,665,995,520,000 | 1,556,884,930,000 | Lean | UTF-8 | Lean | false | false | 95 | lean | class foo (F : Type) where
foo : F
class foobar (F : outParam Type) [foo F] where
bar : F
|
5592ac89983457757d6557d190edf777097d2cdd | d0f9af2b0ace5ce352570d61b09019c8ef4a3b96 | /exam_2/predicate_logic/rules_of_reasoning.lean | 2e79a009bb31de3691269bf4b0b584a5dcc9663f | [] | no_license | jngo13/Discrete-Mathematics | 8671540ef2da7c75915d32332dd20c02f001474e | bf674a866e61f60e6e6d128df85fa73819091787 | refs/heads/master | 1,675,615,657,924 | 1,609,142,011,000 | 1,609,142,011,000 | 267,190,341 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 3,473 | lean |
axiom P : Prop
axiom Q : Prop
axiom R : Prop
-->> def true_intro : pExp := pTrue
#check true -- a type
#check true.intro -- a constructor (value)
#print true
-- true is a proposition
-- in Lean represented as a type
-- intro is defined to be a proof of it (a value)
-- because there is proof, we judge the proposition to be true
-- a proof is necessary and sufficient *evidence* of truth
-- *** FALSE ***
-- false
#check false
#print false
-- there is no proof of the proposition false
-- this is by definition of false as a type with no values
-- so we judge the proposition, false, to be false (untrue)
-->> def false_elim := pFalse >> P
#check @false.elim
-- def true_imp := pTrue >> P
-- oops, this is not a valid law
def true_imp : ∀ (P : Prop), true → P :=
λ P t, _
-- *** AND ***
#check and
#print and
-->> def and_intro := P >> Q >> P ∧ Q
#check @and.intro -- constructor
-->> def and_elim_left := P ∧ Q >> P
#check @and.elim_left
#print and.elim_left
-->> def and_elim_right := P ∧ Q >> Q
#check @and.elim_right
#print and.elim_right
-- *** OR ***
-->> def or_intro_left := P >> P ∨ Q
#check @or.intro_left
-->> def or_intro_right := Q >> P ∨ Q
#check @or.intro_right
-->> def or_elim := P ∨ Q >> (P >> R) >> (Q >> R) >> R
#check @or.elim
-- *** IFF ***
#check iff
#print iff
-- def iff_intro := (P >> Q) >> (Q >> P) >> (P ↔ Q)
#check @iff.intro
-- def iff_elim_left := (P ↔ Q) >> (P >> Q)
#check @iff.elim_left
#check @iff.mp
-- def iff_elim_right := (P ↔ Q) >> (Q >> P)
#check @iff.elim_right
#check @iff.mpr
-- *** ARROW ***
-- introduction rule:
-- if you show that given any (p : P) you can derive
-- a value (q : Q), then you've proven P → Q. To prove
-- P → Q, define any function of this type. The totality
-- of functions in Lean is essential here: to the "any".
-- def arrow_elim := (P >> Q) >> P >> Q
-- if you're given a function of type P → Q and
-- any value of type P, you can derive one of type Q
axiom p : P
axiom pf : P → Q
#check (pf p)
-- *** RESOLUTION ***
--def resolution := (P ∨ Q) >> (¬ Q ∨ R) >> (P ∨ R)
--def unit_resolution := (P ∨ Q) >> ¬ Q >> P
-- The resolution rules are used in some automated
-- theorem provers. We won't study them in this class
-- That said, they are clearly valid reasoning rules.
-- *** NEGATION
-- def neg_intro := (P >> pFalse) >> (¬ P)
#print not
-- def neg_elim := (¬¬P) >> P -- "proof by contradiction"
#check classical.em
-- *** THEOREMS ***
-- def syllogism := (P >> Q) >> (Q >> R) >> (P >> R)
def syllogism : ∀ {P Q R : Prop}, (P → Q) → (Q → R) → (P → R) :=
λ (P Q R : Prop) (pq : P → Q) (qr : Q → R),
qr ∘ pq
--def modus_tollens := (P >> Q) >> (¬ Q >> ¬ P)
theorem modus_tollens : ∀ {P Q : Prop}, (P → Q) → ¬ Q → ¬ P :=
λ P Q pq nq, syllogism pq nq
-- *** AXIOMS ***
-- def excluded_middle := P ∨ (¬ P)
#check classical.em
-- *** NON-THEOREMS (FALSEHOODS) ***
--def affirm_consequence := (P >> Q) >> (Q >> P)
theorem affirm_consequence : ∀ {P Q : Prop}, (P → Q) → Q → P :=
λ P Q pq q, _ -- sTuCK!
--def affirm_disjunct := (P ∨ Q) >> (P >> ¬ Q)
theorem affirm_disjunct : ∀ {P Q : Prop }, (P ∨ Q) → P → ¬ Q :=
λ (P Q : Prop) (pq : P ∨ Q) (p : P), _ -- sTuCK!
--def deny_antecedent := (P >> Q) >> (¬ P >> ¬ Q)
theorem deny_antecedent : ∀ {P Q : Prop }, (P → Q) → (¬P → ¬Q) :=
λ P Q pq np, _ |
2e86f3a427f94932eceb47415bc0f65e5515d8f2 | 957a80ea22c5abb4f4670b250d55534d9db99108 | /tests/lean/run/app_builder_tac1.lean | 9e54fbc0d19e1915019deeb25a131ebb84d0e9a4 | [
"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 | 544 | lean | open tactic list nat name
set_option trace.app_builder true
set_option pp.all true
meta definition mk_ite (c a b : expr) : tactic expr :=
mk_mapp `ite [some c, none, none, some a, some b]
example (a b : nat) : nat :=
by do a ← get_local `a,
b ← get_local `b,
mk_app `has_add.add [a, b] >>= trace,
mk_app `has_mul.mul [a, b] >>= trace,
mk_app `has_sub.sub [a, b] >>= trace,
c ← mk_app `eq [a, b],
trace c,
mk_ite c a b >>= trace,
mk_ite c b a >>= trace,
assumption,
return ()
|
70dee6904636f0e2ee3efc2ce1defba4bee15c44 | dd0f5513e11c52db157d2fcc8456d9401a6cd9da | /12_Axioms.org.2.lean | 7943d4d6a490ac382f8fcb5c90659e83fd4038d7 | [] | 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 | 346 | lean | import standard
namespace hide
axiom propext {a b : Prop} : (a ↔ b) → a = b
-- BEGIN
section
open eq.ops
variables a b c d e : Prop
variable P : Prop → Prop
example (H : a ↔ b) : (c ∧ a ∧ d → e) ↔ (c ∧ b ∧ d → e) :=
propext H ▸ !iff.refl
example (H : a ↔ b) (H1 : P a) : P b :=
propext H ▸ H1
end
-- END
end hide
|
be74106544376fa59923c44f466a91c84ad0389f | 9be442d9ec2fcf442516ed6e9e1660aa9071b7bd | /tests/lean/run/dotNameIssue.lean | df334dcacf15a5cff2a759b94da3b7a1372fb4ad | [
"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 | 167 | lean | example : x ≠ y → x ∉ [y] :=
fun hne hin =>
match hin with
| .head _ _ => hne rfl
example : x ≠ y → x ∉ [y] :=
fun hne (.head _ _) => hne rfl
|
4674e6be612f4e4827386d492f630a7c02f10d7e | 947b78d97130d56365ae2ec264df196ce769371a | /tests/lean/run/meta6.lean | bf3ddd841a6dac8ced083e483a67476fa8c9f66e | [
"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 | 2,525 | lean | import Lean.Meta
new_frontend
open Lean
open Lean.Meta
def print (msg : MessageData) : MetaM Unit :=
trace! `Meta.debug msg
def checkM (x : MetaM Bool) : MetaM Unit :=
unlessM x $ throwError "check failed"
def nat := mkConst `Nat
def boolE := mkConst `Bool
def succ := mkConst `Nat.succ
def zero := mkConst `Nat.zero
def add := mkConst `Nat.add
def io := mkConst `IO
def type := mkSort levelOne
def mkArrow (d b : Expr) : Expr := mkForall `_ BinderInfo.default d b
def tst1 : MetaM Unit := do
print "----- tst1 -----";
let m1 ← mkFreshExprMVar (mkArrow nat nat);
let lhs := mkApp m1 zero;
let rhs := zero;
checkM $ fullApproxDefEq $ isDefEq lhs rhs;
pure ()
set_option pp.all true
#eval tst1
set_option trace.Meta.debug true
def tst2 : MetaM Unit := do
print "----- tst2 -----";
let ps ← getParamNames `Or.elim; print (toString ps);
let ps ← getParamNames `Iff.elim; print (toString ps);
let ps ← getParamNames `checkM; print (toString ps);
pure ()
#eval tst2
axiom t1 : [Unit] = []
axiom t2 : 0 > 5
def tst3 : MetaM Unit := do
let env ← getEnv;
let t2 ← getConstInfo `t2;
let c ← mkNoConfusion t2.type (mkConst `t1);
print c;
check c;
let cType ← inferType c;
print cType;
let lt ← mkLt (mkNatLit 10000000) (mkNatLit 20000000000);
let ltPrf ← mkDecideProof lt;
check ltPrf;
let t ← inferType ltPrf;
print t;
pure ()
#eval tst3
inductive Vec.{u} (α : Type u) : Nat → Type u
| nil : Vec α 0
| cons {n : Nat} : α → Vec α n → Vec α (n+1)
def tst4 : MetaM Unit :=
withLocalDeclD `x nat fun x =>
withLocalDeclD `y nat fun y => do
let vType ← mkAppM `Vec #[nat, x];
withLocalDeclD `v vType fun v => do
let m ← mkFreshExprSyntheticOpaqueMVar vType;
let subgoals ← caseValues m.mvarId! x.fvarId! #[mkNatLit 2, mkNatLit 3, mkNatLit 5];
subgoals.forM fun s => do {
print (MessageData.ofGoal s.mvarId);
assumption s.mvarId
};
let t ← instantiateMVars m;
print t;
check t;
pure ()
#eval tst4
def tst5 : MetaM Unit := do
let arrayNat ← mkAppM `Array #[nat];
withLocalDeclD `a arrayNat fun a => do
withLocalDeclD `b arrayNat fun b => do
let motiveType := _root_.mkArrow arrayNat (mkSort levelZero);
withLocalDeclD `motive motiveType fun motive => do
let mvarType := mkApp motive a;
let mvar ← mkFreshExprSyntheticOpaqueMVar mvarType;
let subgoals ← caseArraySizes mvar.mvarId! a.fvarId! #[1, 0, 4, 5];
subgoals.forM fun s => do {
print (MessageData.ofGoal s.mvarId);
pure ()
};
pure ()
set_option trace.Meta.synthInstance false
#eval tst5
|
588c610418d0b71e17c1668a57eeb695887593c3 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/run/subexpr.lean | 4b6848f3a9e14bccda17741defdc2fc0f76da8cc | [
"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 | 623 | lean | import Lean
open Lean.SubExpr
def ps := [#[], #[0], #[1], #[0,1], #[1,0] , #[0,0], #[1,2,3]]
theorem Pos.roundtrip :
true = ps.all fun x => x == (Pos.toArray <| Pos.ofArray <| x)
:= by native_decide
theorem Pos.append_roundtrip :
true = (List.all
(ps.bind fun p => ps.map fun q => (p,q))
(fun (x,y) => (x ++ y) == (Pos.toArray <| (Pos.append (Pos.ofArray x) (Pos.ofArray y))))
) := by native_decide
theorem Pos.stringRoundtrip :
true = ps.all (fun p =>
let x := Pos.ofArray p
some x == (Except.toOption $ Pos.fromString? $ Pos.toString $ x)
) := by native_decide
#eval Pos.toString Nat.zero
|
0a05e6be9660864ad0d8d51da85626b077496c6c | fe84e287c662151bb313504482b218a503b972f3 | /src/algebra/linmap.lean | ddb363c4e7299709d2ad6d9ff8a37f10e816d142 | [] | no_license | NeilStrickland/lean_lib | 91e163f514b829c42fe75636407138b5c75cba83 | 6a9563de93748ace509d9db4302db6cd77d8f92c | refs/heads/master | 1,653,408,198,261 | 1,652,996,419,000 | 1,652,996,419,000 | 181,006,067 | 4 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 726 | lean | /- Experiments with coercion of linear maps to maps -/
import data.rat.basic linear_algebra.basic
section zog
parameters {V : Type} [add_comm_group V] [module ℚ V]
def f : V →ₗ[ℚ] V :=
{ to_fun := λ (v : V), v,
map_add' := λ (v w : V), rfl,
map_smul' := λ (c : ℚ) (v : V), rfl }
#check linear_map.map_add'
#check linear_map.map_add
#check f
def f1 : V → V := (f : V →ₗ[ℚ] V)
#check f1
def f2 (v : V) : V := (f : V →ₗ[ℚ] V) v
#check f2
def f3 (v : V) : V := (f : V → V) v
#check f3
def f4 (v : V) : V := v
def g : V →ₗ[ℚ] V :=
{ to_fun := λ (v : V), v,
map_add' := λ (v w : V), rfl,
map_smul' := λ (c : ℚ) (v : V), rfl }
def gg (v : V) : V := g v
end zog
|
f88c9ce560e9f02ba3870795e84e53fe1998b2c0 | 624f6f2ae8b3b1adc5f8f67a365c51d5126be45a | /tests/lean/run/structInst.lean | be33fdd452bb170a6e412738b35650176214f006 | [
"Apache-2.0"
] | permissive | mhuisi/lean4 | 28d35a4febc2e251c7f05492e13f3b05d6f9b7af | dda44bc47f3e5d024508060dac2bcb59fd12e4c0 | refs/heads/master | 1,621,225,489,283 | 1,585,142,689,000 | 1,585,142,689,000 | 250,590,438 | 0 | 2 | Apache-2.0 | 1,602,443,220,000 | 1,585,327,814,000 | C | UTF-8 | Lean | false | false | 1,025 | lean | namespace Ex1
structure A :=
(x : Nat)
structure B extends A :=
(y : Nat := x + 2) (x := y + 1)
structure C extends B :=
(z : Nat) (x := z + 10)
end Ex1
namespace Ex2
structure A :=
(x : Nat) (y : Nat)
structure B extends A :=
(z : Nat := x + 1) (y := z + x)
end Ex2
namespace Ex3
structure A :=
(x : Nat)
structure B extends A :=
(y : Nat := x + 2) (x := y + 1)
structure C extends B :=
(z : Nat := 2*y) (x := z + 2) (y := z + 3)
end Ex3
namespace Ex4
structure A :=
(x : Nat)
structure B extends A :=
(y : Nat := x + 1) (x := y + 1)
structure C extends B :=
(z : Nat := 2*y) (x := z + 3)
end Ex4
new_frontend
namespace Ex1
#check { B . y := 1 }
#check { C . z := 1 }
end Ex1
namespace Ex2
#check { B . x := 1 }
end Ex2
namespace Ex3
#check { C . x := 1 }
#check { C . y := 1 }
#check { C . z := 1 }
end Ex3
namespace Ex4
#check { C . x := 1 } -- works
#check { C . y := 1 } -- works
#check { C . z := 1 } -- works
#check { C . z := 1, x := 2 } -- works
#check { B . y := 1 } -- works
end Ex4
|
1eaf7178a4028aa89570100691c5a6a1e68b8ed1 | 9b9a16fa2cb737daee6b2785474678b6fa91d6d4 | /src/data/zmod/quadratic_reciprocity.lean | d95ada6ad26caa231db30723c88f294727868248 | [
"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 | 32,128 | lean | /-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes
-/
import field_theory.finite data.zmod.basic algebra.pi_instances
open function finset nat finite_field zmodp
namespace zmodp
variables {p q : ℕ} (hp : nat.prime p) (hq : nat.prime q)
@[simp] lemma card_units_zmodp : fintype.card (units (zmodp p hp)) = p - 1 :=
by rw [card_units, card_zmodp]
theorem fermat_little {p : ℕ} (hp : nat.prime p) {a : zmodp p hp} (ha : a ≠ 0) : a ^ (p - 1) = 1 :=
by rw [← units.mk0_val ha, ← @units.coe_one (zmodp p hp), ← units.coe_pow, ← units.ext_iff,
← card_units_zmodp hp, pow_card_eq_one]
lemma euler_criterion_units {x : units (zmodp p hp)} :
(∃ y : units (zmodp p hp), y ^ 2 = x) ↔ x ^ (p / 2) = 1 :=
hp.eq_two_or_odd.elim
(λ h, by subst h; revert x; exact dec_trivial)
(λ hp1, let ⟨g, hg⟩ := is_cyclic.exists_generator (units (zmodp p hp)) in
let ⟨n, hn⟩ := show x ∈ powers g, from (powers_eq_gpowers g).symm ▸ hg x in
⟨λ ⟨y, hy⟩, by rw [← hy, ← pow_mul, two_mul_odd_div_two hp1,
← card_units_zmodp hp, pow_card_eq_one],
λ hx, have 2 * (p / 2) ∣ n * (p / 2),
by rw [two_mul_odd_div_two hp1, ← card_units_zmodp hp, ← order_of_eq_card_of_forall_mem_gpowers hg];
exact order_of_dvd_of_pow_eq_one (by rwa [pow_mul, hn]),
let ⟨m, hm⟩ := dvd_of_mul_dvd_mul_right (nat.div_pos hp.ge_two dec_trivial) this in
⟨g ^ m, by rwa [← pow_mul, mul_comm, ← hm]⟩⟩)
lemma euler_criterion {a : zmodp p hp} (ha : a ≠ 0) :
(∃ y : zmodp p hp, y ^ 2 = a) ↔ a ^ (p / 2) = 1 :=
⟨λ ⟨y, hy⟩,
have hy0 : y ≠ 0, from λ h, by simp [h, _root_.zero_pow (succ_pos 1)] at hy; cc,
by simpa using (units.ext_iff.1 $ (euler_criterion_units hp).1 ⟨units.mk0 _ hy0, show _ = units.mk0 _ ha,
by rw [units.ext_iff]; simpa⟩),
λ h, let ⟨y, hy⟩ := (euler_criterion_units hp).2 (show units.mk0 _ ha ^ (p / 2) = 1, by simpa [units.ext_iff]) in
⟨y, by simpa [units.ext_iff] using hy⟩⟩
lemma pow_div_two_eq_neg_one_or_one {a : zmodp p hp} (ha : a ≠ 0) : a ^ (p / 2) = 1 ∨ a ^ (p / 2) = -1 :=
hp.eq_two_or_odd.elim
(λ h, by revert a ha; subst h; exact dec_trivial)
(λ hp1, by rw [← mul_self_eq_one_iff, ← _root_.pow_add, ← two_mul, two_mul_odd_div_two hp1];
exact fermat_little hp ha)
@[simp] lemma wilsons_lemma {p : ℕ} (hp : nat.prime p) : (fact (p - 1) : zmodp p hp) = -1 :=
begin
rw [← finset.prod_range_id_eq_fact, ← @units.coe_one (zmodp p hp), ← units.coe_neg,
← @prod_univ_units_id_eq_neg_one (zmodp p hp),
← prod_hom (coe : units (zmodp p hp) → zmodp p hp),
← prod_hom (coe : ℕ → zmodp p hp)],
exact eq.symm (prod_bij
(λ a _, (a : zmodp p hp).1) (λ a ha, mem_erase.2
⟨λ h, units.coe_ne_zero a $ fin.eq_of_veq h,
by rw [mem_range, ← succ_sub hp.pos, succ_sub_one]; exact a.1.2⟩)
(λ a _, by simp) (λ _ _ _ _, units.ext_iff.2 ∘ fin.eq_of_veq)
(λ b hb,
have b ≠ 0 ∧ b < p, by rwa [mem_erase, mem_range, ← succ_sub hp.pos, succ_sub_one] at hb,
⟨units.mk0 _ (show (b : zmodp p hp) ≠ 0, from fin.ne_of_vne $
by rw [zmod.val_cast_nat, ← @nat.cast_zero (zmodp p hp), zmod.val_cast_nat];
simp [mod_eq_of_lt this.2, this.1]), mem_univ _,
by simp [val_cast_of_lt hp this.2]⟩))
end
@[simp] lemma prod_range_prime_erase_zero {p : ℕ} (hp : nat.prime p) :
((range p).erase 0).prod (λ x, (x : zmodp p hp)) = -1 :=
by conv in (range p) { rw [← succ_sub_one p, succ_sub hp.pos] };
rw [prod_hom (coe : ℕ → zmodp p hp),
finset.prod_range_id_eq_fact, wilsons_lemma]
end zmodp
namespace quadratic_reciprocity_aux
variables {p q : ℕ} (hp : nat.prime p) (hq : nat.prime q) (hp1 : p % 2 = 1) (hq1 : q % 2 = 1)
(hpq : p ≠ q)
include hp hq hp1 hq1 hpq
lemma filter_range_p_mul_q_div_two_eq :
(range ((p * q) / 2).succ).filter (coprime p) =
(range (q / 2)).bind (λ x, (erase (range p) 0).image (+ p * x))
∪ (erase (range (succ (p / 2))) 0).image (+ q / 2 * p) :=
finset.ext.2 $ λ x,
⟨λ h, have hxp0 : x % p ≠ 0, by rw [ne.def, ← dvd_iff_mod_eq_zero, ← hp.coprime_iff_not_dvd];
exact (mem_filter.1 h).2,
mem_union.2 $ or_iff_not_imp_right.2 (λ h₁, mem_bind.2
⟨x / p, mem_range.2 $ nat.div_lt_of_lt_mul (by_contradiction
(λ h₂,
let ⟨c, hc⟩ := le_iff_exists_add.1 (le_of_not_gt h₂) in
have hcp : c ≤ p / 2, from @nat.le_of_add_le_add_left (p * (q / 2)) _ _
(by rw [← hc, ← odd_mul_odd_div_two hp1 hq1]; exact le_of_lt_succ (mem_range.1 (mem_filter.1 h).1)),
h₁ $ mem_image.2 ⟨c, mem_erase.2 ⟨λ h, hxp0 $ by simp [h, hc],
mem_range.2 $ lt_succ_of_le $ hcp⟩, by rw hc; simp [mul_comm]⟩)),
mem_image.2 ⟨x % p, mem_erase.2 $
by rw [ne.def, ← dvd_iff_mod_eq_zero, ← hp.coprime_iff_not_dvd, mem_range];
exact ⟨(mem_filter.1 h).2, mod_lt _ hp.pos⟩, nat.mod_add_div _ _⟩⟩),
λ h, mem_filter.2 $
(mem_union.1 h).elim
(λ h, let ⟨m, hm₁, hm₂⟩ := mem_bind.1 h in
let ⟨k, hk₁, hk₂⟩ := mem_image.1 hm₂ in
⟨mem_range.2 $ hk₂ ▸ (mul_lt_mul_left (show 0 < 2, from dec_trivial)).1 begin
rw [mul_succ, two_mul_odd_div_two (nat.odd_mul_odd hp1 hq1), mul_add],
clear _let_match _let_match,
exact calc 2 * k + 2 * (p * m) < 2 * p + 2 * (p * m) :
add_lt_add_right ((mul_lt_mul_left dec_trivial).2 (by simp at hk₁; tauto)) _
... = 2 * (p * (m + 1)) : by simp [mul_add, mul_assoc, mul_comm, mul_left_comm]
... ≤ 2 * (p * (q / 2)) : (mul_le_mul_left (show 0 < 2, from dec_trivial)).2
((mul_le_mul_left hp.pos).2 $ succ_le_of_lt $ mem_range.1 hm₁)
... ≤ _ : by rw [mul_left_comm, two_mul_odd_div_two hq1, nat.mul_sub_left_distrib,
← nat.sub_add_comm (mul_pos hp.pos hq.pos), add_succ, succ_eq_add_one, nat.add_sub_cancel];
exact le_trans (nat.sub_le_self _ _) (nat.le_add_right _ _),
end,
by rw [nat.prime.coprime_iff_not_dvd hp, ← hk₂, ← nat.dvd_add_iff_left (dvd_mul_right _ _),
dvd_iff_mod_eq_zero, mod_eq_of_lt]; clear _let_match _let_match; simp at hk₁; tauto⟩)
(λ h, let ⟨m, hm₁, hm₂⟩ := mem_image.1 h in ⟨mem_range.2 $ hm₂ ▸ begin
refine (mul_lt_mul_left (show 0 < 2, from dec_trivial)).1 _,
rw [mul_succ, two_mul_odd_div_two (nat.odd_mul_odd hp1 hq1), mul_add, ← mul_assoc 2, two_mul_odd_div_two hq1],
exact calc 2 * m + (q - 1) * p ≤ 2 * (p / 2) + (q - 1) * p :
add_le_add_right ((mul_le_mul_left dec_trivial).2 (le_of_lt_succ (mem_range.1 (by simp * at *)))) _
... < _ : begin rw [two_mul_odd_div_two hp1, nat.mul_sub_right_distrib, one_mul],
rw [← nat.sub_add_comm hp.pos, nat.add_sub_cancel' (le_mul_of_ge_one_left' (nat.zero_le _) hq.pos), mul_comm],
exact lt_add_of_pos_right _ dec_trivial
end,
end,
by rw [hp.coprime_iff_not_dvd, dvd_iff_mod_eq_zero, ← hm₂, nat.add_mul_mod_self_right, mod_eq_of_lt
(lt_of_lt_of_le _ (nat.div_lt_self hp.pos (show 1 < 2, from dec_trivial)))];
simp at hm₁; clear _let_match; tauto⟩)⟩
lemma prod_filter_range_p_mul_q_div_two_eq :
(range (q / 2)).prod (λ n, ((range p).erase 0).prod (+ p * n)) *
((range (p / 2).succ).erase 0).prod (+ (q / 2) * p) =
((range ((p * q) / 2).succ).filter (coprime p)).prod (λ x, x) :=
calc (range (q / 2)).prod (λ n, ((range p).erase 0).prod (+ p * n)) *
((range (p / 2).succ).erase 0).prod (+ (q / 2) * p)
= (range (q / 2)).prod (λ n, (((range p).erase 0).image (+ p * n)).prod (λ x, x)) *
(((range (p / 2).succ).erase 0).image (+ (q / 2) * p)).prod (λ x, x) :
by simp only [prod_image (λ _ _ _ _ h, add_right_cancel h)]; refl
... = ((range (q / 2)).bind (λ x, (erase (range p) 0).image (+ p * x))
∪ (erase (range (succ (p / 2))) 0).image (+ q / 2 * p)).prod (λ x, x) :
have h₁ : finset.bind (range (q / 2)) (λ x, ((range p).erase 0).image (+ p * x)) ∩
image (+ q / 2 * p) (erase (range (succ (p / 2))) 0) = ∅ :=
eq_empty_iff_forall_not_mem.2 $ λ x, begin
suffices : ∀ a, a ≠ 0 → a ≤ p / 2 → a + q / 2 * p = x → ∀ b, b < q / 2 →
∀ c, c ≠ 0 → c < p → ¬c + p * b = x,
{ simpa [lt_succ_iff] },
assume a ha0 hap ha b hbq c hc0 hcp hc,
rw mul_comm at ha,
rw [← ((nat.div_mod_unique hp.pos).2 ⟨hc, hcp⟩).1,
← ((nat.div_mod_unique hp.pos).2 ⟨ha, lt_of_le_of_lt hap
(nat.div_lt_self hp.pos dec_trivial)⟩).1] at hbq,
exact lt_irrefl _ hbq
end,
have h₂ : ∀ x, x ∈ range (q / 2) → ∀ y, y ∈ range (q / 2) → x ≠ y →
(erase (range p) 0).image (+ p * x) ∩ image (+ p * y) (erase (range p) 0) = ∅ :=
λ x hx y hy hxy, begin
suffices : ∀ z a, a ≠ 0 → a < p → a + p * x = z → ∀ b, b ≠ 0 → b < p → b + p * y ≠ z,
{ simpa [finset.ext] },
assume z a ha0 hap ha b hb0 hbp hb,
have : (a + p * x) / p = (b + p * y) / p,
{ rw [ha, hb] },
rw [nat.add_mul_div_left _ _ hp.pos, nat.add_mul_div_left _ _ hp.pos,
(nat.div_eq_zero_iff hp.pos).2 hap, (nat.div_eq_zero_iff hp.pos).2 hbp] at this,
simpa [hxy]
end,
by rw [prod_union h₁, prod_bind h₂]
... = (((range ((p * q) / 2).succ)).filter (coprime p)).prod (λ x, x) :
prod_congr (filter_range_p_mul_q_div_two_eq hp hq hp1 hq1 hpq).symm (λ _ _, rfl)
lemma prod_filter_range_p_mul_q_div_two_mod_p_eq :
((((range ((p * q) / 2).succ).filter (coprime p)).prod (λ x, x) : ℕ) : zmodp p hp)
= (-1) ^ (q / 2) * ((range (p / 2).succ).erase 0).prod (λ x, x) :=
begin
rw [← prod_filter_range_p_mul_q_div_two_eq hp hq hp1 hq1 hpq, nat.cast_mul,
← prod_hom (coe : ℕ → zmodp p hp),
← prod_hom (coe : ℕ → zmodp p hp)],
conv in ((finset.prod (erase (range p) 0) _ : ℕ) : zmodp p hp)
{ rw ← prod_hom (coe : ℕ → zmodp p hp) },
simp
end
lemma prod_filter_range_p_mul_q_not_coprime_eq :
(((((range ((p * q) / 2).succ).filter (coprime p)).filter
(λ x, ¬ coprime q x)).prod (λ x, x) : ℕ) : zmodp p hp) =
q ^ (p / 2) * ((range (p / 2).succ).erase 0).prod (λ x, x) :=
have hcard : ((range (p / 2).succ).erase 0).card = p / 2 :=
by rw [card_erase_of_mem (mem_range.2 (succ_pos _)), card_range, pred_succ],
begin
conv in ((q : zmodp p hp) ^ (p / 2)) { rw ← hcard },
rw [← prod_const, ← prod_mul_distrib, ← prod_hom (coe : ℕ → zmodp p hp)],
exact eq.symm (prod_bij (λ a _, a * q)
(λ a ha,
have ha' : a ≤ p / 2 ∧ a > 0,
by simp [nat.pos_iff_ne_zero, lt_succ_iff] at *; tauto,
mem_filter.2 ⟨mem_filter.2 ⟨mem_range.2 $ lt_succ_of_le $
(calc a * q ≤ q * (p / 2) :
by rw mul_comm; exact mul_le_mul_left _ ha'.1
... ≤ _ : by rw [mul_comm p, odd_mul_odd_div_two hq1 hp1];
exact nat.le_add_right _ _),
by rw [hp.coprime_iff_not_dvd, hp.dvd_mul, not_or_distrib];
refine ⟨λ hpa, not_le_of_gt (show p / 2 < p, from nat.div_lt_self hp.pos dec_trivial)
(le_trans (le_of_dvd ha'.2 hpa) ha'.1), by rwa [← hp.coprime_iff_not_dvd, coprime_primes hp hq]⟩⟩,
by simp [hq.coprime_iff_not_dvd]⟩)
(by simp [mul_comm])
(by simp [nat.mul_right_inj hq.pos])
(λ b hb, have hb' : (b ≤ p * q / 2 ∧ coprime p b) ∧ q ∣ b,
by simpa [hq.coprime_iff_not_dvd, lt_succ_iff] using hb,
have hb0 : b > 0, from nat.pos_of_ne_zero (λ hb0, by simpa [hb0, hp.coprime_iff_not_dvd] using hb'),
⟨b / q, mem_erase.2 ⟨nat.pos_iff_ne_zero.1 (nat.div_pos (le_of_dvd hb0 hb'.2) hq.pos),
mem_range.2 $ lt_succ_of_le $
by rw [mul_comm, odd_mul_odd_div_two hq1 hp1] at hb';
have := @nat.div_le_div_right _ _ hb'.1.1 q;
rwa [add_comm, nat.add_mul_div_left _ _ hq.pos,
((nat.div_eq_zero_iff hq.pos).2 (nat.div_lt_self hq.pos (lt_succ_self _))), zero_add] at this⟩,
by rw nat.div_mul_cancel hb'.2⟩))
end
lemma prod_range_p_mul_q_filter_coprime_mod_p (hq : nat.prime q) (hp1 : p % 2 = 1) (hq1 : q % 2 = 1) (hpq : p ≠ q) :
((((range ((p * q) / 2).succ).filter (coprime (p * q))).prod (λ x, x) : ℕ) : zmodp p hp) =
(-1) ^ (q / 2) * q ^ (p / 2) :=
have hq0 : (q : zmodp p hp) ≠ 0, by rwa [← nat.cast_zero, ne.def, zmodp.eq_iff_modeq_nat, nat.modeq.modeq_zero_iff,
← hp.coprime_iff_not_dvd, coprime_primes hp hq],
(domain.mul_right_inj
(show (q ^ (p / 2) * ((range (p / 2).succ).erase 0).prod (λ x, x) : zmodp p hp) ≠ 0,
from mul_ne_zero
(pow_ne_zero _ hq0)
(suffices h : ∀ (x : ℕ), ¬x = 0 → x ≤ p / 2 → ¬(x : zmodp p hp) = 0,
by simpa [prod_eq_zero_iff, lt_succ_iff],
assume x hx0 hxp,
by rwa [← @nat.cast_zero (zmodp p hp), zmodp.eq_iff_modeq_nat, nat.modeq,
zero_mod, mod_eq_of_lt (lt_of_le_of_lt hxp (nat.div_lt_self hp.pos (lt_succ_self _)))]))).1 $
have h₁ : (range (succ (p * q / 2))).filter (coprime (p * q)) ∩
filter (λ x, ¬coprime q x) (filter (coprime p) (range (succ (p * q / 2)))) = ∅,
by have := @coprime.coprime_mul_left p q; simp [finset.ext, *] at * {contextual := tt},
calc ((((range ((p * q) / 2).succ).filter (coprime (p * q))).prod (λ x, x) : ℕ) : zmodp p hp)
* (q ^ (p / 2) * ((range (p / 2).succ).erase 0).prod (λ x, x) : zmodp p hp)
= (((range (succ (p * q / 2))).filter (coprime (p * q)) ∪
filter (λ x, ¬coprime q x) (filter (coprime p) (range (succ (p * q / 2))))).prod (λ x, x) : ℕ) :
by rw [← prod_filter_range_p_mul_q_not_coprime_eq hp hq hp1 hq1 hpq, ← nat.cast_mul, ← prod_union h₁]
... = (((range ((p * q) / 2).succ).filter (coprime p)).prod (λ x, x) : ℕ) :
congr_arg coe (prod_congr (by simp [finset.ext, coprime_mul_iff_left]; tauto) (λ _ _, rfl))
... = _ : by rw [prod_filter_range_p_mul_q_div_two_mod_p_eq hp hq hp1 hq1 hpq];
cases zmodp.pow_div_two_eq_neg_one_or_one hp hq0; simp [h, _root_.pow_succ]
lemma card_range_p_mul_q_filter_not_coprime :
card (filter (λ x, ¬coprime p x) (range (succ (p * q / 2)))) = (q / 2).succ :=
calc card (filter (λ x, ¬coprime p x) (range (succ (p * q / 2))))
= card ((range (q / 2).succ).image (* p)) :
congr_arg card $ finset.ext.2 $ λ x, begin
rw [mem_filter, mem_range, hp.coprime_iff_not_dvd, not_not, mem_image],
exact ⟨λ ⟨h, ⟨m, hm⟩⟩, ⟨m, mem_range.2 (lt_of_mul_lt_mul_left
(by rw ← hm; exact lt_of_lt_of_le h (by rw [succ_le_iff, mul_succ,
odd_mul_odd_div_two hp1 hq1];
exact add_lt_add_left (div_lt_self hp.pos (lt_succ_self 1)) _))
(nat.zero_le p)), hm.symm ▸ mul_comm m p⟩,
λ ⟨m, hm₁, hm₂⟩, ⟨lt_succ_of_le (by rw [← hm₂, odd_mul_odd_div_two hp1 hq1];
exact le_trans (by rw mul_comm; exact mul_le_mul_left _
(le_of_lt_succ (mem_range.1 hm₁))) (le_add_right _ _)),
by simp [hm₂.symm]⟩⟩
end
... = _ : by rw [card_image_of_injective _ (λ _ _ h, (nat.mul_right_inj hp.pos).1 h), card_range]
lemma prod_filter_range_p_mul_q_div_two_eq_prod_product :
((range ((p * q) / 2).succ).filter (coprime (p * q))).prod
(λ x, if (x : zmodp q hq).1 ≤ q / 2 then ((x : zmodp p hp), (x : zmodp q hq))
else -((x : zmodp p hp), (x : zmodp q hq))) =
(((range p).erase 0).product ((range (q / 2).succ).erase 0)).prod
(λ x, ((x.1 : zmodp p hp), (x.2 : zmodp q hq))) :=
have hpqpnat : (((⟨p * q, mul_pos hp.pos hq.pos⟩ : ℕ+) : ℕ) : ℤ) = (p * q : ℤ), by simp,
have hpqpnat' : ((⟨p * q, mul_pos hp.pos hq.pos⟩ : ℕ+) : ℕ) = p * q, by simp,
have hpq1 : ((⟨p * q, mul_pos hp.pos hq.pos⟩ : ℕ+) : ℕ) % 2 = 1,
from nat.odd_mul_odd hp1 hq1,
have hpq1' : p * q > 1, from one_lt_mul hp.pos hq.gt_one,
have hhq0 : ∀ a : ℕ, coprime q a → a ≠ 0,
from λ a, imp_not_comm.1 $ by simp [hq.coprime_iff_not_dvd] {contextual := tt},
have hpq0 : 0 < p * q / 2, from nat.div_pos (succ_le_of_lt $ one_lt_mul hp.pos hq.gt_one) dec_trivial,
have hinj : ∀ a₁ a₂ : ℕ,
a₁ ∈ (range (p * q / 2).succ).filter (coprime (p * q)) →
a₂ ∈ (range (p * q / 2).succ).filter (coprime (p * q)) →
(if (a₁ : zmodp q hq).1 ≤ q / 2 then ((a₁ : zmodp p hp).1, (a₁ : zmodp q hq).1)
else ((-a₁ : zmodp p hp).1, (-a₁ : zmodp q hq).1)) =
(if (a₂ : zmodp q hq).1 ≤ q / 2 then ((a₂ : zmodp p hp).1, (a₂ : zmodp q hq).1)
else ((-a₂ : zmodp p hp).1, (-a₂ : zmodp q hq).1)) → a₁ = a₂,
from λ a b ha hb h,
have ha' : a ≤ (p * q) / 2 ∧ coprime (p * q) a,
by simpa [lt_succ_iff] using ha,
have hapq' : a < ((⟨p * q, mul_pos hp.pos hq.pos⟩ : ℕ+) : ℕ) :=
lt_of_le_of_lt ha'.1 (div_lt_self (mul_pos hp.pos hq.pos) dec_trivial),
have hb' : b ≤ (p * q) / 2 ∧ coprime (p * q) b,
by simpa [lt_succ_iff, coprime_mul_iff_left] using hb,
have hbpq' : b < ((⟨p * q, mul_pos hp.pos hq.pos⟩ : ℕ+) : ℕ) :=
lt_of_le_of_lt hb'.1 (div_lt_self (mul_pos hp.pos hq.pos) dec_trivial),
have val_inj : ∀ {p : ℕ} (hp : nat.prime p) (x y : zmodp p hp), x.val = y.val ↔ x = y,
from λ _ _ _ _, ⟨fin.eq_of_veq, fin.veq_of_eq⟩,
have hbpq0 : (b : zmod (⟨p * q, mul_pos hp.pos hq.pos⟩)) ≠ 0,
by rw [ne.def, zmod.eq_zero_iff_dvd_nat];
exact λ h, not_coprime_of_dvd_of_dvd hpq1' (dvd_refl (p * q)) h hb'.2,
have habneg : ¬((a : zmodp p hp) = -b ∧ (a : zmodp q hq) = -b),
begin
rw [← int.cast_coe_nat a, ← int.cast_coe_nat b, ← int.cast_coe_nat a, ← int.cast_coe_nat b,
← int.cast_neg, ← int.cast_neg, zmodp.eq_iff_modeq_int, zmodp.eq_iff_modeq_int,
@int.modeq.modeq_and_modeq_iff_modeq_mul _ _ p q ((coprime_primes hp hq).2 hpq), ← hpqpnat,
← zmod.eq_iff_modeq_int, int.cast_coe_nat, int.cast_neg, int.cast_coe_nat],
assume h,
rw [← hpqpnat', ← zmod.val_cast_of_lt hbpq', zmod.le_div_two_iff_lt_neg hpq1 hbpq0,
← h, zmod.val_cast_of_lt hapq', ← not_le] at hb',
exact hb'.1 ha'.1,
end,
have habneg' : ¬((-a : zmodp p hp) = b ∧ (-a : zmodp q hq) = b),
by rwa [← neg_inj', neg_neg, ← @neg_inj' _ _ (-a : zmodp q hq), neg_neg],
suffices (a : zmodp p hp) = b ∧ (a : zmodp q hq) = b,
by rw [← mod_eq_of_lt hapq', ← mod_eq_of_lt hbpq'];
rwa [zmodp.eq_iff_modeq_nat, zmodp.eq_iff_modeq_nat,
nat.modeq.modeq_and_modeq_iff_modeq_mul ((coprime_primes hp hq).2 hpq)] at this,
by split_ifs at h; simp * at *,
have hmem : ∀ a : ℕ,
a ∈ (range (p * q / 2).succ).filter (coprime (p * q)) →
(if (a : zmodp q hq).1 ≤ q / 2 then ((a : zmodp p hp).1, (a : zmodp q hq).1)
else ((-a : zmodp p hp).1, (-a : zmodp q hq).1)) ∈
((range p).erase 0).product ((range (succ (q / 2))).erase 0),
from λ x, have hxp : ∀ {p : ℕ} (hp : nat.prime p), (x : zmodp p hp).val = 0 ↔ p ∣ x,
from λ p hp, by rw [zmodp.val_cast_nat, nat.dvd_iff_mod_eq_zero],
have hxpneg : ∀ {p : ℕ} (hp : nat.prime p), (-x : zmodp p hp).val = 0 ↔ p ∣ x,
from λ p hp, by rw [← int.cast_coe_nat x, ← int.cast_neg, ← int.coe_nat_inj',
zmodp.coe_val_cast_int, int.coe_nat_zero, ← int.dvd_iff_mod_eq_zero, dvd_neg, int.coe_nat_dvd],
have hxplt : (x : zmodp p hp).val < p := (x : zmodp p hp).2,
have hxpltneg : (-x : zmodp p hp).val < p := (-x : zmodp p hp).2,
have hneglt : ¬(x : zmodp q hq).val ≤ q / 2 → (x : zmodp q hq) ≠ 0 → (-x : zmodp q hq).val ≤ q / 2,
from λ hx₁ hx0, by rwa [zmodp.le_div_two_iff_lt_neg hq hq1 hx0, not_lt] at hx₁,
by split_ifs;
simp [zmodp.eq_zero_iff_dvd_nat hq, (x : zmodp p hp).2, coprime_mul_iff_left,
lt_succ_iff, h, *, hp.coprime_iff_not_dvd,
hq.coprime_iff_not_dvd, (x : zmodp p hp).2, (-x : zmodp p hp).2] {contextual := tt},
prod_bij (λ x _, if (x : zmodp q hq).1 ≤ (q / 2) then ((x : zmodp p hp).val, (x : zmodp q hq).val)
else ((-x : zmodp p hp).val, (-x : zmodp q hq).val))
hmem
(λ a ha, by split_ifs; simp [*, prod.ext_iff] at *)
hinj
(surj_on_of_inj_on_of_card_le _ hmem hinj
(@nat.le_of_add_le_add_right (q / 2 + (p / 2).succ) _ _
(calc card (finset.product (erase (range p) 0) (erase (range (succ (q / 2))) 0)) + (q / 2 + (p / 2).succ)
= (p * q) / 2 + 1 :
by rw [card_product, card_erase_of_mem (mem_range.2 hp.pos), card_erase_of_mem (mem_range.2 (succ_pos _)),
card_range, card_range, pred_succ, ← add_assoc, ← succ_mul, succ_pred_eq_of_pos hp.pos,
odd_mul_odd_div_two hp1 hq1, add_succ]
... = card (range (p * q / 2).succ) : by rw card_range
... = card ((range (p * q / 2).succ).filter (coprime (p * q)) ∪
((range (p * q / 2).succ).filter (λ x, ¬coprime p x)).erase 0 ∪
(range (p * q / 2).succ).filter (λ x, ¬coprime q x)) :
congr_arg card (by simp [finset.ext, coprime_mul_iff_left]; tauto)
... ≤ card ((range (p * q / 2).succ).filter (coprime (p * q))) +
card (((range (p * q / 2).succ).filter (λ x, ¬coprime p x)).erase 0) +
card ((range (p * q / 2).succ).filter (λ x, ¬coprime q x)) :
le_trans (card_union_le _ _) (add_le_add_right (card_union_le _ _) _)
... = _ : by rw [card_erase_of_mem, card_range_p_mul_q_filter_not_coprime hp hq hp1 hq1 hpq,
mul_comm p q, card_range_p_mul_q_filter_not_coprime hq hp hq1 hp1 hpq.symm, pred_succ,
add_assoc];
simp [range_succ, hp.coprime_iff_not_dvd, hpq0])))
lemma prod_range_div_two_erase_zero :
((range (p / 2).succ).erase 0).prod (λ x, (x : zmodp p hp)) ^ 2 * (-1) ^ (p / 2) = -1 :=
have hcard : card (erase (range (succ (p / 2))) 0) = p / 2,
by rw [card_erase_of_mem (mem_range.2 (succ_pos _)), card_range, pred_succ],
have hp2 : p / 2 < p, from div_lt_self hp.pos dec_trivial,
have h₁ : (range (p / 2).succ).erase 0 = ((range p).erase 0).filter (λ x, (x : zmodp p hp).val ≤ p / 2) :=
finset.ext.2 (λ a,
⟨λ h, mem_filter.2 $ by rw [mem_erase, mem_range, lt_succ_iff] at h;
exact ⟨mem_erase.2 ⟨h.1, mem_range.2 (lt_of_le_of_lt h.2 hp2)⟩,
by rw zmodp.val_cast_of_lt hp (lt_of_le_of_lt h.2 hp2); exact h.2⟩,
λ h, mem_erase.2 ⟨by simp at h; tauto,
by rw [mem_filter, mem_erase, mem_range] at h;
rw [mem_range, lt_succ_iff, ← zmodp.val_cast_of_lt hp h.1.2]; exact h.2⟩⟩),
have hmem : ∀ x ∈ (range (p / 2).succ).erase 0, x ≠ 0 ∧ x ≤ p / 2,
from λ x hx, by simpa [lt_succ_iff] using hx,
have hmemv : ∀ x ∈ (range (p / 2).succ).erase 0, (x : zmodp p hp).val = x,
from λ x hx, zmodp.val_cast_of_lt hp (lt_of_le_of_lt (hmem x hx).2 hp2),
have hmem0 : ∀ x ∈ (range (p / 2).succ).erase 0, (x : zmodp p hp) ≠ 0,
from λ x hx, fin.ne_of_vne $ by simp [hmemv x hx, (hmem x hx).1],
have hmem0' : ∀ x ∈ (range (p / 2).succ).erase 0, (-x : zmodp p hp) ≠ 0,
from λ x hx, neg_ne_zero.2 (hmem0 x hx),
have h₂ : ((range (p / 2).succ).erase 0).prod (λ x : ℕ, (x : zmodp p hp) * -1) =
(((range p).erase 0).filter (λ x : ℕ, ¬(x : zmodp p hp).val ≤ p / 2)).prod (λ x, (x : zmodp p hp)) :=
prod_bij (λ a _, (-a : zmodp p hp).1)
(λ a ha, mem_filter.2 ⟨mem_erase.2 ⟨fin.vne_of_ne (hmem0' a ha), mem_range.2 (-a : zmodp p hp).2⟩,
by simp [zmodp.le_div_two_iff_lt_neg hp hp1 (hmem0' a ha), hmemv a ha, (hmem a ha).2]; tauto⟩)
(by simp)
(λ a₁ a₂ ha₁ ha₂ h,
by rw [← hmemv a₁ ha₁, ← hmemv a₂ ha₂]; exact fin.veq_of_eq (by rw neg_inj (fin.eq_of_veq h)))
(λ b hb,
have hb' : (b ≠ 0 ∧ b < p) ∧ (¬(b : zmodp p hp).1 ≤ p / 2), by simpa using hb,
have hbv : (b : zmodp p hp).1 = b, from zmodp.val_cast_of_lt hp hb'.1.2,
have hb0 : (b : zmodp p hp) ≠ 0, from fin.ne_of_vne $ by simp [hbv, hb'.1.1],
⟨(-b : zmodp p hp).1, mem_erase.2 ⟨fin.vne_of_ne (neg_ne_zero.2 hb0 : _),
mem_range.2 $ lt_succ_of_le $ by rw [← not_lt, ← zmodp.le_div_two_iff_lt_neg hp hp1 hb0]; exact hb'.2⟩,
by simp [hbv]⟩),
calc ((((range (p / 2).succ).erase 0).prod (λ x, (x : zmodp p hp)) ^ 2)) * (-1) ^ (p / 2) =
((range (p / 2).succ).erase 0).prod (λ x, (x : zmodp p hp)) *
((range (p / 2).succ).erase 0).prod (λ x, (x : zmodp p hp) * -1) :
by rw prod_mul_distrib; simp [_root_.pow_two, hcard, mul_assoc]
... = (((range p).erase 0).filter (λ x : ℕ, (x : zmodp p hp).val ≤ p / 2)).prod (λ x, (x : zmodp p hp)) *
(((range p).erase 0).filter (λ x : ℕ, ¬(x : zmodp p hp).val ≤ p / 2)).prod (λ x, (x : zmodp p hp)) :
by rw [h₂, h₁]
... = ((range p).erase 0).prod (λ x, (x : zmodp p hp)) :
begin
rw ← prod_union,
{ exact finset.prod_congr (by simp [finset.ext, -not_lt, -not_le]; tauto) (λ _ _, rfl) },
{ simp [finset.ext, -not_lt, - not_le]; tauto }
end
... = -1 : by simp
lemma range_p_product_range_q_div_two_prod :
(((range p).erase 0).product ((range (q / 2).succ).erase 0)).prod
(λ x, ((x.1 : zmodp p hp), (x.2 : zmodp q hq))) =
((-1) ^ (q / 2), (-1) ^ (p / 2) * (-1) ^ (p / 2 * (q / 2))) :=
have hcard : card (erase (range (succ (q / 2))) 0) = q / 2,
by rw [card_erase_of_mem (mem_range.2 (succ_pos _)), card_range, pred_succ],
have finset.prod (erase (range (succ (q / 2))) 0) (λ x : ℕ, (x : zmodp q hq)) ^ 2 = -((-1 : zmodp q hq) ^ (q / 2)),
from (domain.mul_right_inj (show (-1 : zmodp q hq) ^ (q / 2) ≠ 0, from pow_ne_zero _ (neg_ne_zero.2 zero_ne_one.symm))).1 $
by rw [prod_range_div_two_erase_zero hq hp hq1 hp1 hpq.symm, ← neg_mul_eq_neg_mul, ← _root_.pow_add, ← two_mul,
pow_mul, _root_.pow_two]; simp,
have finset.prod (erase (range (succ (q / 2))) 0) (λ x, (x : zmodp q hq)) ^ card (erase (range p) 0) =
(- 1) ^ (p / 2) * ((-1) ^ (p / 2 * (q / 2))),
by rw [card_erase_of_mem (mem_range.2 hp.pos), card_range, pred_eq_sub_one,
← two_mul_odd_div_two hp1, pow_mul, this, mul_comm (p / 2), pow_mul, ← _root_.mul_pow]; simp,
by simp [prod_product, (prod_mk_prod _ _ _).symm, prod_pow, prod_nat_pow, prod_const, *,
zmodp.prod_range_prime_erase_zero hp]
lemma prod_range_p_mul_q_div_two_ite_eq :
((range ((p * q) / 2).succ).filter (coprime (p * q))).prod
(λ x, if (x : zmodp q hq).1 ≤ (q / 2) then ((x : zmodp p hp), (x : zmodp q hq))
else -((x : zmodp p hp), (x : zmodp q hq))) =
((range ((p * q) / 2).succ).filter (coprime (p * q))).prod (λ x, if (x : zmodp q hq).1 ≤ q / 2 then 1 else -1) *
((-1) ^ (q / 2) * q ^ (p / 2), (-1) ^ (p / 2) * p ^ (q / 2)) :=
calc ((range ((p * q) / 2).succ).filter (coprime (p * q))).prod
(λ x, if (x : zmodp q hq).1 ≤ (q / 2) then ((x : zmodp p hp), (x : zmodp q hq))
else -((x : zmodp p hp), (x : zmodp q hq))) =
((range ((p * q) / 2).succ).filter (coprime (p * q))).prod
(λ x, (if (x : zmodp q hq).1 ≤ (q / 2) then 1 else -1) * ((x : zmodp p hp), (x : zmodp q hq))) :
prod_congr rfl (λ _ _, by split_ifs; simp)
... = _ : by rw [prod_mul_distrib, ← prod_mk_prod,
prod_hom (coe : ℕ → zmodp p hp),
prod_range_p_mul_q_filter_coprime_mod_p hp hq hp1 hq1 hpq,
prod_hom (coe : ℕ → zmodp q hq),
mul_comm p q, prod_range_p_mul_q_filter_coprime_mod_p hq hp hq1 hp1 hpq.symm]
end quadratic_reciprocity_aux
open quadratic_reciprocity_aux
variables {p q : ℕ} (hp : nat.prime p) (hq : nat.prime q)
namespace zmodp
def legendre_sym (a p : ℕ) (hp : nat.prime p) : ℤ :=
if (a : zmodp p hp) = 0 then 0 else if ∃ b : zmodp p hp, b ^ 2 = a then 1 else -1
lemma legendre_sym_eq_pow (a p : ℕ) (hp : nat.prime p) : (legendre_sym a p hp : zmodp p hp) = (a ^ (p / 2)) :=
if ha : (a : zmodp p hp) = 0 then by simp [*, legendre_sym, _root_.zero_pow (nat.div_pos hp.ge_two (succ_pos 1))]
else
(nat.prime.eq_two_or_odd hp).elim
(λ hp2, begin subst hp2,
suffices : ∀ a : zmodp 2 nat.prime_two,
(((ite (a = 0) 0 (ite (∃ (b : zmodp 2 hp), b ^ 2 = a) 1 (-1))) : ℤ) : zmodp 2 nat.prime_two) = a ^ (2 / 2),
{ exact this a },
exact dec_trivial,
end)
(λ hp1, have _ := euler_criterion hp ha,
have (-1 : zmodp p hp) ≠ 1, from (ne_neg_self hp hp1 zero_ne_one.symm).symm,
by cases zmodp.pow_div_two_eq_neg_one_or_one hp ha; simp [legendre_sym, *] at *)
lemma legendre_sym_eq_one_or_neg_one (a : ℕ) (hp : nat.prime p) (ha : (a : zmodp p hp) ≠ 0) :
legendre_sym a p hp = -1 ∨ legendre_sym a p hp = 1 :=
by unfold legendre_sym; split_ifs; simp * at *
theorem quadratic_reciprocity (hp : nat.prime p) (hq : nat.prime q) (hp1 : p % 2 = 1) (hq1 : q % 2 = 1) (hpq : p ≠ q) :
legendre_sym p q hq * legendre_sym q p hp = (-1) ^ ((p / 2) * (q / 2)) :=
have hneg_one_or_one : ((range (p * q / 2).succ).filter (coprime (p * q))).prod
(λ (x : ℕ), if (x : zmodp q hq).val ≤ q / 2 then (1 : zmodp p hp × zmodp q hq) else -1) = 1 ∨
((range (p * q / 2).succ).filter (coprime (p * q))).prod
(λ (x : ℕ), if (x : zmodp q hq).val ≤ q / 2 then (1 : zmodp p hp × zmodp q hq) else -1) = -1 :=
finset.induction_on ((range (p * q / 2).succ).filter (coprime (p * q))) (or.inl rfl)
(λ a s h, by simp [prod_insert h]; split_ifs; finish),
have h : (((-1) ^ (q / 2), (-1) ^ (p / 2) * (-1) ^ (p / 2 * (q / 2))) : zmodp p hp × zmodp q hq) =
((-1) ^ (q / 2) * q ^ (p / 2), (-1) ^ (p / 2) * p ^ (q / 2)) ∨
(((-1) ^ (q / 2), (-1) ^ (p / 2) * (-1) ^ (p / 2 * (q / 2))) : zmodp p hp × zmodp q hq) =
- ((-1) ^ (q / 2) * q ^ (p / 2), (-1) ^ (p / 2) * p ^ (q / 2)) :=
begin
have := prod_filter_range_p_mul_q_div_two_eq_prod_product hp hq hp1 hq1 hpq,
rw [prod_range_p_mul_q_div_two_ite_eq hp hq hp1 hq1 hpq,
range_p_product_range_q_div_two_prod hp hq hp1 hq1 hpq] at this,
cases hneg_one_or_one with h h; simp * at *
end,
begin
have := ne_neg_self hp hp1 one_ne_zero,
have := ne_neg_self hq hq1 one_ne_zero,
generalize hnp : (-1 : ℤ) ^ (p / 2) = np,
have hnpp : (-1 : zmodp q hq) ^ (p / 2) = np, by simp [hnp.symm],
generalize hnq : (-1 : ℤ) ^ (q / 2) = nq,
have hnqp : (-1 : zmodp p hp) ^ (q / 2) = nq, by simp [hnq.symm],
have hnqq : (-1 : zmodp q hq) ^ (q / 2) = nq, by simp [hnq.symm],
cases legendre_sym_eq_one_or_neg_one q hp (zmodp.prime_ne_zero hp hq hpq);
cases legendre_sym_eq_one_or_neg_one p hq (zmodp.prime_ne_zero hq hp hpq.symm);
cases @neg_one_pow_eq_or ℤ _ (p / 2);
cases @neg_one_pow_eq_or ℤ _ (q / 2);
simp [*, pow_mul, (legendre_sym_eq_pow p q hq).symm, (legendre_sym_eq_pow q p hp).symm, prod.ext_iff] at *;
cc
end
lemma is_square_iff_is_square_of_mod_four_eq_one (hp1 : p % 4 = 1) (hq1 : q % 2 = 1) :
(∃ a : zmodp p hp, a ^ 2 = q) ↔ ∃ b : zmodp q hq, b ^ 2 = p :=
if hpq : p = q then by subst hpq else
have h1 : ((p / 2) * (q / 2)) % 2 = 0,
from (dvd_iff_mod_eq_zero _ _).1
(dvd_mul_of_dvd_left ((dvd_iff_mod_eq_zero _ _).2 $
by rw [← mod_mul_right_div_self, show 2 * 2 = 4, from rfl, hp1]; refl) _),
begin
have := quadratic_reciprocity hp hq (odd_of_mod_four_eq_one hp1) hq1 hpq,
rw [neg_one_pow_eq_pow_mod_two, h1, legendre_sym, legendre_sym,
if_neg (zmodp.prime_ne_zero hp hq hpq),
if_neg (zmodp.prime_ne_zero hq hp (ne.symm hpq))] at this,
split_ifs at this; simp *; contradiction
end
lemma is_square_iff_is_not_square_of_mod_four_eq_three (hp3 : p % 4 = 3) (hq3 : q % 4 = 3)
(hpq : p ≠ q) : (∃ a : zmodp p hp, a ^ 2 = q) ↔ ¬∃ b : zmodp q hq, b ^ 2 = p :=
have h1 : ((p / 2) * (q / 2)) % 2 = 1,
from nat.odd_mul_odd
(by rw [← mod_mul_right_div_self, show 2 * 2 = 4, from rfl, hp3]; refl)
(by rw [← mod_mul_right_div_self, show 2 * 2 = 4, from rfl, hq3]; refl),
begin
have := quadratic_reciprocity hp hq (odd_of_mod_four_eq_three hp3)
(odd_of_mod_four_eq_three hq3) hpq,
rw [neg_one_pow_eq_pow_mod_two, h1, legendre_sym, legendre_sym,
if_neg (zmodp.prime_ne_zero hp hq hpq),
if_neg (zmodp.prime_ne_zero hq hp hpq.symm)] at this,
split_ifs at this; simp *; contradiction
end
end zmodp |
d6c79baa95ca938618cc7d2a1ee0aeb98e3ad555 | acc85b4be2c618b11fc7cb3005521ae6858a8d07 | /analysis/topology/infinite_sum.lean | f94f574ecf0b2d82f00baff6d51d72a2eccc81a0 | [
"Apache-2.0"
] | permissive | linpingchuan/mathlib | d49990b236574df2a45d9919ba43c923f693d341 | 5ad8020f67eb13896a41cc7691d072c9331b1f76 | refs/heads/master | 1,626,019,377,808 | 1,508,048,784,000 | 1,508,048,784,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 20,205 | 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
Infinite sum over a topological monoid
This sum is known as unconditionally convergent, as it sums to the same value under all possible
permutations. For Euclidean spaces (finite dimensional Banach spaces) this is equivalent to absolute
convergence.
-/
import logic.function algebra.big_operators data.set data.finset
analysis.metric_space analysis.topology.topological_structures
noncomputable theory
open set lattice finset filter function classical
local attribute [instance] decidable_inhabited prop_decidable
variables {α : Type*} {β : Type*} {γ : Type*}
section is_sum
variables [add_comm_monoid α] [topological_space α] [topological_add_monoid α]
/-- Infinite sum on a topological monoid
The `at_top` filter on `finset α` is the limit of all finite sets towards the entire type. So we sum
up bigger and bigger sets. This sum operation is still invariant under reordering, and a absolute
sum operator.
This is based on Mario Carneiro's infinite sum in Metamath.
-/
def is_sum (f : β → α) (a : α) : Prop := tendsto (λs:finset β, s.sum f) at_top (nhds a)
def has_sum (f : β → α) : Prop := ∃a, is_sum f a
def tsum (f : β → α) := if h : has_sum f then classical.some h else 0
notation `∑` binders `, ` r:(scoped f, tsum f) := r
variables {f g : β → α} {a b : α} {s : finset β}
lemma is_sum_tsum (ha : has_sum f) : is_sum f (∑b, f b) :=
by simp [ha, tsum]; exact some_spec ha
lemma has_sum_spec (ha : is_sum f a) : has_sum f := ⟨a, ha⟩
lemma is_sum_zero : is_sum (λb, 0 : β → α) 0 :=
by simp [is_sum, tendsto_const_nhds]
lemma has_sum_zero : has_sum (λb, 0 : β → α) := has_sum_spec is_sum_zero
lemma is_sum_add (hf : is_sum f a) (hg : is_sum g b) : is_sum (λb, f b + g b) (a + b) :=
by simp [is_sum, sum_add_distrib]; exact tendsto_add hf hg
lemma has_sum_add (hf : has_sum f) (hg : has_sum g) : has_sum (λb, f b + g b) :=
has_sum_spec $ is_sum_add (is_sum_tsum hf)(is_sum_tsum hg)
lemma is_sum_sum {f : γ → β → α} {a : γ → α} {s : finset γ} :
(∀i∈s, is_sum (f i) (a i)) → is_sum (λb, s.sum $ λi, f i b) (s.sum a) :=
s.induction_on (by simp [is_sum_zero]) (by simp [is_sum_add] {contextual := tt})
lemma has_sum_sum {f : γ → β → α} {s : finset γ} (hf : ∀i∈s, has_sum (f i)) :
has_sum (λb, s.sum $ λi, f i b) :=
has_sum_spec $ is_sum_sum $ assume i hi, is_sum_tsum $ hf i hi
lemma is_sum_sum_of_ne_finset_zero (hf : ∀b∉s, f b = 0) : is_sum f (s.sum f) :=
tendsto_infi' s $ tendsto_cong tendsto_const_nhds $
assume t (ht : s ⊆ t), show s.sum f = t.sum f, from sum_subset ht $ assume x _, hf _
lemma has_sum_sum_of_ne_finset_zero (hf : ∀b∉s, f b = 0) : has_sum f :=
has_sum_spec $ is_sum_sum_of_ne_finset_zero hf
lemma is_sum_of_iso {j : γ → β} {i : β → γ}
(hf : is_sum f a) (h₁ : ∀x, i (j x) = x) (h₂ : ∀x, j (i x) = x) : is_sum (f ∘ j) a :=
have ∀x y, j x = j y → x = y,
from assume x y h,
have i (j x) = i (j y), by rw [h],
by rwa [h₁, h₁] at this,
have (λs:finset γ, s.sum (f ∘ j)) = (λs:finset β, s.sum f) ∘ (λs:finset γ, s.image j),
from funext $ assume s, (sum_image $ assume x _ y _, this x y).symm,
show tendsto (λs:finset γ, s.sum (f ∘ j)) at_top (nhds a),
by rw [this]; apply tendsto_compose (tendsto_finset_image_at_top_at_top h₂) hf
lemma is_sum_iff_is_sum_of_iso {j : γ → β} (i : β → γ)
(h₁ : ∀x, i (j x) = x) (h₂ : ∀x, j (i x) = x) :
is_sum (f ∘ j) a ↔ is_sum f a :=
iff.intro
(assume hfj,
have is_sum ((f ∘ j) ∘ i) a, from is_sum_of_iso hfj h₂ h₁,
by simp [(∘), h₂] at this; assumption)
(assume hf, is_sum_of_iso hf h₁ h₂)
lemma is_sum_hom (g : α → γ) [add_comm_monoid γ] [topological_space γ] [topological_add_monoid γ]
(h₁ : g 0 = 0) (h₂ : ∀x y, g (x + y) = g x + g y) (h₃ : continuous g) (hf : is_sum f a) :
is_sum (g ∘ f) (g a) :=
have (λs:finset β, s.sum (g ∘ f)) = g ∘ (λs:finset β, s.sum f),
from funext $ assume s, sum_hom g h₁ h₂,
show tendsto (λs:finset β, s.sum (g ∘ f)) at_top (nhds (g a)),
by rw [this]; exact tendsto_compose hf (continuous_iff_tendsto.mp h₃ a)
lemma tendsto_sum_nat_of_is_sum {f : ℕ → α} (h : is_sum f a) :
tendsto (λn:ℕ, (range n).sum f) at_top (nhds a) :=
suffices map (λ (n : ℕ), sum (range n) f) at_top ≤ map (λ (s : finset ℕ), sum s f) at_top,
from le_trans this h,
assume s (hs : {t : finset ℕ | t.sum f ∈ s} ∈ at_top.sets),
let ⟨t, ht⟩ := mem_at_top_iff.mp hs, ⟨n, hn⟩ := @exists_nat_subset_range t in
mem_at_top_iff.mpr ⟨n, assume n' hn', ht _ $ subset.trans hn $ range_subset.mpr hn'⟩
lemma is_sum_sigma [regular_space α] {γ : β → Type*} {f : (Σ b:β, γ b) → α} {g : β → α} {a : α}
(hf : ∀b, is_sum (λc, f ⟨b, c⟩) (g b)) (ha : is_sum f a) : is_sum g a :=
assume s' hs',
let
⟨s, hs, hss', hsc⟩ := nhds_is_closed hs',
⟨u, hu⟩ := mem_at_top_iff.mp $ ha $ hs,
fsts := u.image sigma.fst,
snds := λb, u.bind (λp, (if h : p.1 = b then {cast (congr_arg γ h) p.2} else ∅ : finset (γ b)))
in
have u_subset : u ⊆ fsts.sigma snds,
from subset_iff.mpr $ assume ⟨b, c⟩ hu,
have hb : b ∈ fsts, from mem_image_iff.mpr ⟨_, hu, rfl⟩,
have hc : c ∈ snds b, from mem_bind_iff.mpr ⟨_, hu, by simp; refl⟩,
by simp [mem_sigma_iff, hb, hc] ,
mem_at_top_iff.mpr $ exists.intro fsts $ assume bs (hbs : fsts ⊆ bs),
have h : ∀cs:(Πb, b ∈ bs → finset (γ b)),
(⋂b (hb : b ∈ bs), (λp:Πb, finset (γ b), p b) ⁻¹' {cs' | cs b hb ⊆ cs' }) ∩
(λp, bs.sum (λb, (p b).sum (λc, f ⟨b, c⟩))) ⁻¹' s ≠ ∅,
from assume cs,
let cs' := λb, (if h : b ∈ bs then cs b h else ∅) ∪ snds b in
have sum_eq : bs.sum (λb, (cs' b).sum (λc, f ⟨b, c⟩)) = (bs.sigma cs').sum f,
from sum_sigma.symm,
have (bs.sigma cs').sum f ∈ s,
from hu _ $ subset.trans u_subset $ sigma_mono hbs $
assume b, @finset.subset_union_right (γ b) _ _ _,
ne_empty_iff_exists_mem.mpr $ exists.intro cs' $
by simp [sum_eq, this]; { intros b hb, simp [cs', hb, finset.subset_union_right] },
have tendsto (λp:(Πb:β, finset (γ b)), bs.sum (λb, (p b).sum (λc, f ⟨b, c⟩)))
(⨅b (h : b ∈ bs), at_top.vmap (λp, p b)) (nhds (bs.sum g)),
from tendsto_sum $
assume c hc, tendsto_infi' c $ tendsto_infi' hc $ tendsto_compose tendsto_vmap (hf c),
have bs.sum g ∈ s,
from mem_closure_of_tendsto this hsc $ forall_sets_neq_empty_iff_neq_bot.mp $
by simp [mem_inf_sets, exists_imp_distrib, and_imp, forall_and_distrib,
filter.mem_infi_sets_finset, mem_vmap, skolem, mem_at_top_iff];
from
assume s₁ s₂ s₃ hs₁ hs₃ p hs₂ p' hp cs hp',
have (⋂b (h : b ∈ bs), (λp:(Πb, finset (γ b)), p b) ⁻¹' {cs' | cs b h ⊆ cs' }) ≤ (⨅b∈bs, p b),
from infi_le_infi $ assume b, infi_le_infi $ assume hb,
le_trans (preimage_mono $ hp' b hb) (hp b hb),
neq_bot_of_le_neq_bot (h _) (le_trans (inter_subset_inter (le_trans this hs₂) hs₃) hs₁),
hss' this
lemma has_sum_sigma [regular_space α] {γ : β → Type*} {f : (Σb:β, γ b) → α}
(hf : ∀b, has_sum (λc, f ⟨b, c⟩)) (ha : has_sum f) : has_sum (λb, ∑c, f ⟨b, c⟩):=
has_sum_spec $ is_sum_sigma (assume b, is_sum_tsum $ hf b) (is_sum_tsum ha)
end is_sum
section is_sum_iff_is_sum_of_iso_ne_zero
variables [add_comm_monoid α] [topological_space α] [topological_add_monoid α]
variables {f : β → α} {g : γ → α} {a : α}
lemma is_sum_of_is_sum
(h_eq : ∀u:finset γ, ∃v:finset β, ∀v', v ⊆ v' → ∃u', u ⊆ u' ∧ u'.sum g = v'.sum f)
(hf : is_sum g a) : is_sum f a :=
suffices at_top.map (λs:finset β, s.sum f) ≤ at_top.map (λs:finset γ, s.sum g),
from le_trans this hf,
by rw [map_at_top_eq, map_at_top_eq];
from (le_infi $ assume b, let ⟨v, hv⟩ := h_eq b in infi_le_of_le v $
by simp [image_subset_iff]; exact hv)
lemma is_sum_iff_is_sum
(h₁ : ∀u:finset γ, ∃v:finset β, ∀v', v ⊆ v' → ∃u', u ⊆ u' ∧ u'.sum g = v'.sum f)
(h₂ : ∀v:finset β, ∃u:finset γ, ∀u', u ⊆ u' → ∃v', v ⊆ v' ∧ v'.sum f = u'.sum g) :
is_sum f a ↔ is_sum g a :=
⟨is_sum_of_is_sum h₂, is_sum_of_is_sum h₁⟩
variables
(i : Π{{c}}, g c ≠ 0 → β) (hi : ∀{{c}} (h : g c ≠ 0), f (i h) ≠ 0)
(j : Π{{b}}, f b ≠ 0 → γ) (hj : ∀{{b}} (h : f b ≠ 0), g (j h) ≠ 0)
(hji : ∀{{c}} (h : g c ≠ 0), j (hi h) = c)
(hij : ∀{{b}} (h : f b ≠ 0), i (hj h) = b)
(hgj : ∀{{b}} (h : f b ≠ 0), g (j h) = f b)
include hi hj hji hij hgj
lemma is_sum_of_is_sum_ne_zero : is_sum g a → is_sum f a :=
have j_inj : ∀x y (hx : f x ≠ 0) (hy : f y ≠ 0), (j hx = j hy ↔ x = y),
from assume x y hx hy,
⟨assume h,
have i (hj hx) = i (hj hy), by simp [h],
by rwa [hij, hij] at this; assumption,
by simp {contextual := tt}⟩,
let ii : finset γ → finset β := λu, u.bind $ λc, if h : g c = 0 then ∅ else {i h} in
let jj : finset β → finset γ := λv, v.bind $ λb, if h : f b = 0 then ∅ else {j h} in
is_sum_of_is_sum $ assume u, exists.intro (ii u) $
assume v hv, exists.intro (u ∪ jj v) $ and.intro subset_union_left $
have ∀c:γ, c ∈ u ∪ jj v → c ∉ jj v → g c = 0,
from assume c hc hnc, classical.by_contradiction $ assume h : g c ≠ 0,
have c ∈ u,
from (mem_or_mem_of_mem_union hc).resolve_right hnc,
have i h ∈ v,
from mem_of_subset_of_mem hv $ by simp [mem_bind_iff]; existsi c; simp [h, this],
have j (hi h) ∈ jj v,
by simp [mem_bind_iff]; existsi i h; simp [h, hi, this],
by rw [hji h] at this; exact hnc this,
calc (u ∪ jj v).sum g = (jj v).sum g : (sum_subset subset_union_right this).symm
... = v.sum _ : sum_bind $ by intros x hx y hy hxy; by_cases f x = 0; by_cases f y = 0; simp [*]
... = v.sum f : sum_congr $ by intros x hx; by_cases f x = 0; simp [*]
lemma is_sum_iff_is_sum_of_ne_zero : is_sum f a ↔ is_sum g a :=
iff.intro
(is_sum_of_is_sum_ne_zero j hj i hi hij hji $ assume b hb, by rw [←hgj (hi _), hji])
(is_sum_of_is_sum_ne_zero i hi j hj hji hij hgj)
lemma has_sum_iff_has_sum_ne_zero : has_sum g ↔ has_sum f :=
exists_congr $
assume a, is_sum_iff_is_sum_of_ne_zero j hj i hi hij hji $
assume b hb, by rw [←hgj (hi _), hji]
end is_sum_iff_is_sum_of_iso_ne_zero
section tsum
variables [add_comm_monoid α] [topological_space α] [topological_add_monoid α] [t2_space α]
variables {f g : β → α} {a a₁ a₂ : α}
lemma is_sum_unique : is_sum f a₁ → is_sum f a₂ → a₁ = a₂ := tendsto_nhds_unique at_top_ne_bot
lemma tsum_eq_is_sum (ha : is_sum f a) : (∑b, f b) = a := is_sum_unique (is_sum_tsum ⟨a, ha⟩) ha
@[simp] lemma tsum_zero : (∑b:β, 0:α) = 0 := tsum_eq_is_sum is_sum_zero
lemma tsum_add (hf : has_sum f) (hg : has_sum g) : (∑b, f b + g b) = (∑b, f b) + (∑b, g b) :=
tsum_eq_is_sum $ is_sum_add (is_sum_tsum hf) (is_sum_tsum hg)
lemma tsum_sum {f : γ → β → α} {s : finset γ} (hf : ∀i∈s, has_sum (f i)) :
(∑b, s.sum (λi, f i b)) = s.sum (λi, ∑b, f i b) :=
tsum_eq_is_sum $ is_sum_sum $ assume i hi, is_sum_tsum $ hf i hi
lemma tsum_eq_sum {f : β → α} {s : finset β} (hf : ∀b∉s, f b = 0) :
(∑b, f b) = s.sum f :=
tsum_eq_is_sum $ is_sum_sum_of_ne_finset_zero hf
lemma tsum_eq_single {f : β → α} (b : β) (hf : ∀b' ≠ b, f b' = 0) :
(∑b, f b) = f b :=
calc (∑b, f b) = ({b} : finset β).sum f : tsum_eq_sum $ by simp [hf] {contextual := tt}
... = f b : by simp
lemma tsum_sigma [regular_space α] {γ : β → Type*} {f : (Σb:β, γ b) → α}
(h₁ : ∀b, has_sum (λc, f ⟨b, c⟩)) (h₂ : has_sum f) : (∑p, f p) = (∑b c, f ⟨b, c⟩):=
(tsum_eq_is_sum $ is_sum_sigma (assume b, is_sum_tsum $ h₁ b) $ is_sum_tsum h₂).symm
lemma tsum_eq_tsum_of_is_sum_iff_is_sum {f : β → α} {g : γ → α}
(h : ∀{a}, is_sum f a ↔ is_sum g a) : (∑b, f b) = (∑c, g c) :=
by_cases
(assume : ∃a, is_sum f a,
let ⟨a, hfa⟩ := this in
have hga : is_sum g a, from h.mp hfa,
by rw [tsum_eq_is_sum hfa, tsum_eq_is_sum hga])
(assume hf : ¬ has_sum f,
have hg : ¬ has_sum g, from assume ⟨a, hga⟩, hf ⟨a, h.mpr hga⟩,
by simp [tsum, hf, hg])
lemma tsum_eq_tsum_of_ne_zero {f : β → α} {g : γ → α}
(i : Π{{c}}, g c ≠ 0 → β) (hi : ∀{{c}} (h : g c ≠ 0), f (i h) ≠ 0)
(j : Π{{b}}, f b ≠ 0 → γ) (hj : ∀{{b}} (h : f b ≠ 0), g (j h) ≠ 0)
(hji : ∀{{c}} (h : g c ≠ 0), j (hi h) = c)
(hij : ∀{{b}} (h : f b ≠ 0), i (hj h) = b)
(hgj : ∀{{b}} (h : f b ≠ 0), g (j h) = f b) :
(∑i, f i) = (∑j, g j) :=
tsum_eq_tsum_of_is_sum_iff_is_sum $ assume a, is_sum_iff_is_sum_of_ne_zero i hi j hj hji hij hgj
lemma tsum_eq_tsum_of_ne_zero_bij {f : β → α} {g : γ → α}
(i : Π{{c}}, g c ≠ 0 → β)
(h₁ : ∀{{c₁ c₂}} (h₁ : g c₁ ≠ 0) (h₂ : g c₂ ≠ 0), i h₁ = i h₂ → c₁ = c₂)
(h₂ : ∀{{b}}, f b ≠ 0 → ∃c (h : g c ≠ 0), i h = b)
(h₃ : ∀{{c}} (h : g c ≠ 0), f (i h) = g c) :
(∑i, f i) = (∑j, g j) :=
have hi : ∀{{c}} (h : g c ≠ 0), f (i h) ≠ 0,
from assume c h, by simp [h₃, h],
let j : Π{{b}}, f b ≠ 0 → γ := λb h, some $ h₂ h in
have hj : ∀{{b}} (h : f b ≠ 0), ∃(h : g (j h) ≠ 0), i h = b,
from assume b h, some_spec $ h₂ h,
have hj₁ : ∀{{b}} (h : f b ≠ 0), g (j h) ≠ 0,
from assume b h, let ⟨h₁, _⟩ := hj h in h₁,
have hj₂ : ∀{{b}} (h : f b ≠ 0), i (hj₁ h) = b,
from assume b h, let ⟨h₁, h₂⟩ := hj h in h₂,
tsum_eq_tsum_of_ne_zero i hi j hj₁
(assume c h, h₁ (hj₁ _) h $ hj₂ _) hj₂ (assume b h, by rw [←h₃ (hj₁ _), hj₂])
lemma tsum_eq_tsum_of_iso (j : γ → β) (i : β → γ)
(h₁ : ∀x, i (j x) = x) (h₂ : ∀x, j (i x) = x) :
(∑c, f (j c)) = (∑b, f b) :=
tsum_eq_tsum_of_is_sum_iff_is_sum $ assume a, is_sum_iff_is_sum_of_iso i h₁ h₂
end tsum
section topological_group
variables [add_comm_group α] [topological_space α] [topological_add_group α]
variables {f g : β → α} {a a₁ a₂ : α}
lemma is_sum_neg : is_sum f a → is_sum (λb, - f b) (- a) :=
is_sum_hom has_neg.neg (by simp) (by simp) continuous_neg'
lemma has_sum_neg (hf : has_sum f) : has_sum (λb, - f b) :=
has_sum_spec $ is_sum_neg $ is_sum_tsum $ hf
lemma is_sum_sub (hf : is_sum f a₁) (hg : is_sum g a₂) : is_sum (λb, f b - g b) (a₁ - a₂) :=
by simp; exact is_sum_add hf (is_sum_neg hg)
lemma has_sum_sub (hf : has_sum f) (hg : has_sum g) : has_sum (λb, f b - g b) :=
has_sum_spec $ is_sum_sub (is_sum_tsum hf) (is_sum_tsum hg)
section tsum
variables [t2_space α]
lemma tsum_neg (hf : has_sum f) : (∑b, - f b) = - (∑b, f b) :=
tsum_eq_is_sum $ is_sum_neg $ is_sum_tsum $ hf
lemma tsum_sub (hf : has_sum f) (hg : has_sum g) : (∑b, f b - g b) = (∑b, f b) - (∑b, g b) :=
tsum_eq_is_sum $ is_sum_sub (is_sum_tsum hf) (is_sum_tsum hg)
end tsum
end topological_group
section topological_semiring
variables [semiring α] [topological_space α] [topological_semiring α]
variables {f g : β → α} {a a₁ a₂ : α}
lemma is_sum_mul_left : is_sum f a₁ → is_sum (λb, a₂ * f b) (a₂ * a₁) :=
is_sum_hom _ (by simp) (by simp [mul_add]) (continuous_mul continuous_const continuous_id)
lemma is_sum_mul_right (hf : is_sum f a₁) : is_sum (λb, f b * a₂) (a₁ * a₂) :=
@is_sum_hom _ _ _ _ _ _ f a₁ (λa, a * a₂) _ _ _
(by simp) (by simp [add_mul]) (continuous_mul continuous_id continuous_const) hf
lemma has_sum_mul_left (hf : has_sum f) : has_sum (λb, a * f b) :=
has_sum_spec $ is_sum_mul_left $ is_sum_tsum hf
lemma has_sum_mul_right (hf : has_sum f) : has_sum (λb, f b * a) :=
has_sum_spec $ is_sum_mul_right $ is_sum_tsum hf
section tsum
variables [t2_space α]
lemma tsum_mul_left (hf : has_sum f) : (∑b, a * f b) = a * (∑b, f b) :=
tsum_eq_is_sum $ is_sum_mul_left $ is_sum_tsum hf
lemma tsum_mul_right (hf : has_sum f) : (∑b, f b * a) = (∑b, f b) * a :=
tsum_eq_is_sum $ is_sum_mul_right $ is_sum_tsum hf
end tsum
end topological_semiring
section order_topology
variables [ordered_comm_monoid α] [topological_space α] [ordered_topology α] [topological_add_monoid α]
variables {f g : β → α} {a a₁ a₂ : α}
lemma is_sum_le (h : ∀b, f b ≤ g b) (hf : is_sum f a₁) (hg : is_sum g a₂) : a₁ ≤ a₂ :=
le_of_tendsto at_top_ne_bot hf hg $ univ_mem_sets' $ assume s, sum_le_sum' $ assume b _, h b
lemma tsum_le_tsum (h : ∀b, f b ≤ g b) (hf : has_sum f) (hg : has_sum g) : (∑b, f b) ≤ (∑b, g b) :=
is_sum_le h (is_sum_tsum hf) (is_sum_tsum hg)
end order_topology
section uniform_group
variables [add_comm_group α] [uniform_space α] [complete_space α] [uniform_add_group α]
variables {f g : β → α} {a a₁ a₂ : α}
/- TODO: generalize to monoid with a uniform continuous subtraction operator: `(a + b) - b = a` -/
lemma has_sum_of_has_sum_of_sub {f' : β → α} (hf : has_sum f) (h : ∀b, f' b = 0 ∨ f' b = f b) :
has_sum f' :=
let ⟨a, hf⟩ := hf in
suffices cauchy (at_top.map (λs:finset β, s.sum f')),
from complete_space.complete this,
⟨map_ne_bot at_top_ne_bot,
assume s' hs',
have ∃t∈(@uniformity α _).sets, ∀{a₁ a₂ a₃ a₄}, (a₁, a₂) ∈ t → (a₃, a₄) ∈ t → (a₁ - a₃, a₂ - a₄) ∈ s',
begin
have h : {p:(α×α)×(α×α)| (p.1.1 - p.1.2, p.2.1 - p.2.2) ∈ s'} ∈ (@uniformity (α × α) _).sets,
from uniform_continuous_sub' hs',
rw [uniformity_prod_eq_prod, mem_map, mem_prod_same_iff] at h,
cases h with t ht, cases ht with ht h,
exact ⟨t, ht, assume a₁ a₂ a₃ a₄ h₁ h₂, @h ((a₁, a₂), (a₃, a₄)) ⟨h₁, h₂⟩⟩
end,
let ⟨s, hs, hss'⟩ := this in
have cauchy (at_top.map (λs:finset β, s.sum f)),
from cauchy_downwards cauchy_nhds (map_ne_bot at_top_ne_bot) hf,
have ∃t, ∀u₁ u₂:finset β, t ⊆ u₁ → t ⊆ u₂ → (u₁.sum f, u₂.sum f) ∈ s,
by simp [cauchy_iff, mem_at_top_iff] at this;
from let ⟨t, ht, u, hu⟩ := this s hs in
⟨u, assume u₁ u₂ h₁ h₂, ht $ prod_mk_mem_set_prod_eq.mpr ⟨hu _ h₁, hu _ h₂⟩⟩,
let ⟨t, ht⟩ := this in
let d := (t.filter (λb, f' b = 0)).sum f in
have eq : ∀{u}, t ⊆ u → (t ∪ u.filter (λb, f' b ≠ 0)).sum f - d = u.sum f',
from assume u hu,
have t ∪ u.filter (λb, f' b ≠ 0) = t.filter (λb, f' b = 0) ∪ u.filter (λb, f' b ≠ 0),
from ext $ assume b, by by_cases f' b = 0;
simp [h, subset_iff.mp hu, iff_def, or_imp_distrib] {contextual := tt},
calc (t ∪ u.filter (λb, f' b ≠ 0)).sum f - d =
(t.filter (λb, f' b = 0) ∪ u.filter (λb, f' b ≠ 0)).sum f - d : by rw [this]
... = (d + (u.filter (λb, f' b ≠ 0)).sum f) - d :
by rw [sum_union]; exact (ext $ assume b, by simp)
... = (u.filter (λb, f' b ≠ 0)).sum f :
by simp
... = (u.filter (λb, f' b ≠ 0)).sum f' :
sum_congr $ assume b, by have h := h b; cases h with h h; simp [*]
... = u.sum f' :
by apply sum_subset; by simp [subset_iff, not_not] {contextual := tt},
have ∀{u₁ u₂}, t ⊆ u₁ → t ⊆ u₂ → (u₁.sum f', u₂.sum f') ∈ s',
from assume u₁ u₂ h₁ h₂,
have ((t ∪ u₁.filter (λb, f' b ≠ 0)).sum f, (t ∪ u₂.filter (λb, f' b ≠ 0)).sum f) ∈ s,
from ht _ _ subset_union_left subset_union_left,
have ((t ∪ u₁.filter (λb, f' b ≠ 0)).sum f - d, (t ∪ u₂.filter (λb, f' b ≠ 0)).sum f - d) ∈ s',
from hss' this $ refl_mem_uniformity hs,
by rwa [eq h₁, eq h₂] at this,
mem_prod_same_iff.mpr ⟨(λu:finset β, u.sum f') '' {u | t ⊆ u},
image_mem_map $ mem_at_top t,
assume ⟨a₁, a₂⟩ ⟨⟨t₁, h₁, eq₁⟩, ⟨t₂, h₂, eq₂⟩⟩, by simp at eq₁ eq₂; rw [←eq₁, ←eq₂]; exact this h₁ h₂⟩⟩
end uniform_group
|
1b36bd10713d19263e0e9262a9a5e6360ae489f7 | 947b78d97130d56365ae2ec264df196ce769371a | /tests/lean/run/match1.lean | e61b2b9a309ea78635344763b9b5360bf850d081 | [
"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 | 3,263 | lean | new_frontend
def f (xs : List Nat) : List Bool :=
xs.map fun
| 0 => true
| _ => false
#eval f [1, 2, 0, 2]
theorem ex1 : f [1, 0, 2] = [false, true, false] :=
rfl
#check f
def g (xs : List Nat) : List Bool :=
xs.map $ by {
intro
| 0 => exact true
| _ => exact false
}
theorem ex2 : g [1, 0, 2] = [false, true, false] :=
rfl
theorem ex3 {p q r : Prop} : p ∨ q → r → (q ∧ r) ∨ (p ∧ r) :=
by intro
| Or.inl hp, h => { apply Or.inr; apply And.intro; assumption; assumption }
| Or.inr hq, h => { apply Or.inl; exact ⟨hq, h⟩ }
inductive C
| mk₁ : Nat → C
| mk₂ : Nat → Nat → C
def C.x : C → Nat
| C.mk₁ x => x
| C.mk₂ x _ => x
def head : {α : Type} → List α → Option α
| _, a::as => some a
| _, _ => none
theorem ex4 : head [1, 2] = some 1 :=
rfl
def head2 : {α : Type} → List α → Option α :=
@fun
| _, a::as => some a
| _, _ => none
theorem ex5 : head2 [1, 2] = some 1 :=
rfl
def head3 {α : Type} (xs : List α) : Option α :=
let rec aux : {α : Type} → List α → Option α
| _, a::as => some a
| _, _ => none;
aux xs
theorem ex6 : head3 [1, 2] = some 1 :=
rfl
inductive Vec.{u} (α : Type u) : Nat → Type u
| nil : Vec α 0
| cons {n} (head : α) (tail : Vec α n) : Vec α (n+1)
def Vec.mapHead1 {α β δ} : {n : Nat} → Vec α n → Vec β n → (α → β → δ) → Option δ
| _, nil, nil, f => none
| _, cons a as, cons b bs, f => some (f a b)
def Vec.mapHead2 {α β δ} : {n : Nat} → Vec α n → Vec β n → (α → β → δ) → Option δ
| _, nil, nil, f => none
| _, @cons _ n a as, cons b bs, f => some (f a b)
def Vec.mapHead3 {α β δ} : {n : Nat} → Vec α n → Vec β n → (α → β → δ) → Option δ
| _, nil, nil, f => none
| _, cons (tail := as) (head := a), cons b bs, f => some (f a b)
inductive Foo
| mk₁ (x y z w : Nat)
| mk₂ (x y z w : Nat)
def Foo.z : Foo → Nat
| mk₁ (z := z) .. => z
| mk₂ (z := z) .. => z
#eval (Foo.mk₁ 10 20 30 40).z
theorem ex7 : (Foo.mk₁ 10 20 30 40).z = 30 :=
rfl
def Foo.addY? : Foo × Foo → Option Nat
| (mk₁ (y := y₁) .., mk₁ (y := y₂) ..) => some (y₁ + y₂)
| _ => none
#eval Foo.addY? (Foo.mk₁ 1 2 3 4, Foo.mk₁ 10 20 30 40)
theorem ex8 : Foo.addY? (Foo.mk₁ 1 2 3 4, Foo.mk₁ 10 20 30 40) = some 22 :=
rfl
instance {α} : Inhabited (Sigma fun m => Vec α m) :=
⟨⟨0, Vec.nil⟩⟩
partial def filter {α} (p : α → Bool) : {n : Nat} → Vec α n → Sigma fun m => Vec α m
| _, Vec.nil => ⟨0, Vec.nil⟩
| _, Vec.cons x xs => match p x, filter p xs with
| true, ⟨_, ys⟩ => ⟨_, Vec.cons x ys⟩
| false, ys => ys
inductive Bla
| ofNat (x : Nat)
| ofBool (x : Bool)
def Bla.optional? : Bla → Option Nat
| ofNat x => some x
| ofBool _ => none
def Bla.isNat? (b : Bla) : Option { x : Nat // optional? b = some x } :=
match b.optional? with
| some y => some ⟨y, rfl⟩
| none => none
def foo (b : Bla) : Option Nat := b.optional?
theorem fooEq (b : Bla) : foo b = b.optional? :=
rfl
def Bla.isNat2? (b : Bla) : Option { x : Nat // optional? b = some x } :=
match h:foo b with
| some y => some ⟨y, Eq.trans (fooEq b).symm h⟩
| none => none
|
4a88afca2476180e72b0ddded9a3ce55ba08caa0 | c777c32c8e484e195053731103c5e52af26a25d1 | /src/order/initial_seg.lean | 2d3ef20adcc9de56b7ea7ee09664821ab2c0a4f7 | [
"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 | 19,669 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Floris van Doorn
-/
import order.rel_iso.set
import order.well_founded
/-!
# Initial and principal segments
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file defines initial and principal segments.
## Main definitions
* `initial_seg r s`: type of order embeddings of `r` into `s` for which the range is an initial
segment (i.e., if `b` belongs to the range, then any `b' < b` also belongs to the range).
It is denoted by `r ≼i s`.
* `principal_seg r s`: Type of order embeddings of `r` into `s` for which the range is a principal
segment, i.e., an interval of the form `(-∞, top)` for some element `top`. It is denoted by
`r ≺i s`.
## Notations
These notations belong to the `initial_seg` locale.
* `r ≼i s`: the type of initial segment embeddings of `r` into `s`.
* `r ≺i s`: the type of principal segment embeddings of `r` into `s`.
-/
/-!
### Initial segments
Order embeddings whose range is an initial segment of `s` (i.e., if `b` belongs to the range, then
any `b' < b` also belongs to the range). The type of these embeddings from `r` to `s` is called
`initial_seg r s`, and denoted by `r ≼i s`.
-/
variables {α : Type*} {β : Type*} {γ : Type*}
{r : α → α → Prop} {s : β → β → Prop} {t : γ → γ → Prop}
open function
/-- If `r` is a relation on `α` and `s` in a relation on `β`, then `f : r ≼i s` is an order
embedding whose range is an initial segment. That is, whenever `b < f a` in `β` then `b` is in the
range of `f`. -/
structure initial_seg {α β : Type*} (r : α → α → Prop) (s : β → β → Prop) extends r ↪r s :=
(init' : ∀ a b, s b (to_rel_embedding a) → ∃ a', to_rel_embedding a' = b)
localized "infix (name := initial_seg) ` ≼i `:25 := initial_seg" in initial_seg
namespace initial_seg
instance : has_coe (r ≼i s) (r ↪r s) := ⟨initial_seg.to_rel_embedding⟩
instance : embedding_like (r ≼i s) α β :=
{ coe := λ f, f.to_fun,
coe_injective' :=
begin
rintro ⟨f, hf⟩ ⟨g, hg⟩ h,
congr' with x,
exact congr_fun h x
end,
injective' := λ f, f.inj' }
@[ext] lemma ext {f g : r ≼i s} (h : ∀ x, f x = g x) : f = g := fun_like.ext f g h
@[simp] theorem coe_fn_mk (f : r ↪r s) (o) :
(@initial_seg.mk _ _ r s f o : α → β) = f := rfl
@[simp] theorem coe_fn_to_rel_embedding (f : r ≼i s) : (f.to_rel_embedding : α → β) = f := rfl
@[simp] theorem coe_coe_fn (f : r ≼i s) : ((f : r ↪r s) : α → β) = f := rfl
theorem init (f : r ≼i s) {a : α} {b : β} : s b (f a) → ∃ a', f a' = b :=
f.init' _ _
theorem map_rel_iff (f : r ≼i s) {a b : α} : s (f a) (f b) ↔ r a b := f.1.map_rel_iff
theorem init_iff (f : r ≼i s) {a : α} {b : β} : s b (f a) ↔ ∃ a', f a' = b ∧ r a' a :=
⟨λ h, let ⟨a', e⟩ := f.init h in ⟨a', e, f.map_rel_iff.1 (e.symm ▸ h)⟩,
λ ⟨a', e, h⟩, e ▸ f.map_rel_iff.2 h⟩
/-- An order isomorphism is an initial segment -/
def of_iso (f : r ≃r s) : r ≼i s :=
⟨f, λ a b h, ⟨f.symm b, rel_iso.apply_symm_apply f _⟩⟩
/-- The identity function shows that `≼i` is reflexive -/
@[refl] protected def refl (r : α → α → Prop) : r ≼i r :=
⟨rel_embedding.refl _, λ a b h, ⟨_, rfl⟩⟩
instance (r : α → α → Prop) : inhabited (r ≼i r) := ⟨initial_seg.refl r⟩
/-- Composition of functions shows that `≼i` is transitive -/
@[trans] protected def trans (f : r ≼i s) (g : s ≼i t) : r ≼i t :=
⟨f.1.trans g.1, λ a c h, begin
simp at h ⊢,
rcases g.2 _ _ h with ⟨b, rfl⟩, have h := g.map_rel_iff.1 h,
rcases f.2 _ _ h with ⟨a', rfl⟩, exact ⟨a', rfl⟩
end⟩
@[simp] theorem refl_apply (x : α) : initial_seg.refl r x = x := rfl
@[simp] theorem trans_apply (f : r ≼i s) (g : s ≼i t) (a : α) : (f.trans g) a = g (f a) := rfl
instance subsingleton_of_trichotomous_of_irrefl [is_trichotomous β s] [is_irrefl β s]
[is_well_founded α r] : subsingleton (r ≼i s) :=
⟨λ f g, begin
ext a,
apply is_well_founded.induction r a (λ b IH, _),
refine extensional_of_trichotomous_of_irrefl s (λ x, _),
rw [f.init_iff, g.init_iff],
exact exists_congr (λ x, and_congr_left $ λ hx, IH _ hx ▸ iff.rfl)
end⟩
instance [is_well_order β s] : subsingleton (r ≼i s) :=
⟨λ a, by { letI := a.is_well_founded, apply subsingleton.elim }⟩
protected theorem eq [is_well_order β s] (f g : r ≼i s) (a) : f a = g a :=
by rw subsingleton.elim f g
theorem antisymm.aux [is_well_order α r] (f : r ≼i s) (g : s ≼i r) : left_inverse g f :=
initial_seg.eq (f.trans g) (initial_seg.refl _)
/-- If we have order embeddings between `α` and `β` whose images are initial segments, and `β`
is a well-order then `α` and `β` are order-isomorphic. -/
def antisymm [is_well_order β s] (f : r ≼i s) (g : s ≼i r) : r ≃r s :=
by haveI := f.to_rel_embedding.is_well_order; exact
⟨⟨f, g, antisymm.aux f g, antisymm.aux g f⟩, λ _ _, f.map_rel_iff'⟩
@[simp] theorem antisymm_to_fun [is_well_order β s]
(f : r ≼i s) (g : s ≼i r) : (antisymm f g : α → β) = f := rfl
@[simp] theorem antisymm_symm [is_well_order α r] [is_well_order β s]
(f : r ≼i s) (g : s ≼i r) : (antisymm f g).symm = antisymm g f :=
rel_iso.coe_fn_injective rfl
theorem eq_or_principal [is_well_order β s] (f : r ≼i s) :
surjective f ∨ ∃ b, ∀ x, s x b ↔ ∃ y, f y = x :=
or_iff_not_imp_right.2 $ λ h b,
acc.rec_on (is_well_founded.wf.apply b : acc s b) $ λ x H IH,
not_forall_not.1 $ λ hn,
h ⟨x, λ y, ⟨(IH _), λ ⟨a, e⟩, by rw ← e; exact
(trichotomous _ _).resolve_right
(not_or (hn a) (λ hl, not_exists.2 hn (f.init hl)))⟩⟩
/-- Restrict the codomain of an initial segment -/
def cod_restrict (p : set β) (f : r ≼i s) (H : ∀ a, f a ∈ p) : r ≼i subrel s p :=
⟨rel_embedding.cod_restrict p f H, λ a ⟨b, m⟩ (h : s b (f a)),
let ⟨a', e⟩ := f.init h in ⟨a', by clear _let_match; subst e; refl⟩⟩
@[simp] theorem cod_restrict_apply (p) (f : r ≼i s) (H a) : cod_restrict p f H a = ⟨f a, H a⟩ := rfl
/-- Initial segment from an empty type. -/
def of_is_empty (r : α → α → Prop) (s : β → β → Prop) [is_empty α] : r ≼i s :=
⟨rel_embedding.of_is_empty r s, is_empty_elim⟩
/-- Initial segment embedding of an order `r` into the disjoint union of `r` and `s`. -/
def le_add (r : α → α → Prop) (s : β → β → Prop) : r ≼i sum.lex r s :=
⟨⟨⟨sum.inl, λ _ _, sum.inl.inj⟩, λ a b, sum.lex_inl_inl⟩,
λ a b, by cases b; [exact λ _, ⟨_, rfl⟩, exact false.elim ∘ sum.lex_inr_inl]⟩
@[simp] theorem le_add_apply (r : α → α → Prop) (s : β → β → Prop)
(a) : le_add r s a = sum.inl a := rfl
protected theorem acc (f : r ≼i s) (a : α) : acc r a ↔ acc s (f a) :=
⟨begin
refine λ h, acc.rec_on h (λ a _ ha, acc.intro _ (λ b hb, _)),
obtain ⟨a', rfl⟩ := f.init hb,
exact ha _ (f.map_rel_iff.mp hb),
end, f.to_rel_embedding.acc a⟩
end initial_seg
/-!
### Principal segments
Order embeddings whose range is a principal segment of `s` (i.e., an interval of the form
`(-∞, top)` for some element `top` of `β`). The type of these embeddings from `r` to `s` is called
`principal_seg r s`, and denoted by `r ≺i s`. Principal segments are in particular initial
segments.
-/
/-- If `r` is a relation on `α` and `s` in a relation on `β`, then `f : r ≺i s` is an order
embedding whose range is an open interval `(-∞, top)` for some element `top` of `β`. Such order
embeddings are called principal segments -/
@[nolint has_nonempty_instance]
structure principal_seg {α β : Type*} (r : α → α → Prop) (s : β → β → Prop) extends r ↪r s :=
(top : β)
(down' : ∀ b, s b top ↔ ∃ a, to_rel_embedding a = b)
localized "infix (name := principal_seg) ` ≺i `:25 := principal_seg" in initial_seg
namespace principal_seg
instance : has_coe (r ≺i s) (r ↪r s) := ⟨principal_seg.to_rel_embedding⟩
instance : has_coe_to_fun (r ≺i s) (λ _, α → β) := ⟨λ f, f⟩
@[simp] theorem coe_fn_mk (f : r ↪r s) (t o) :
(@principal_seg.mk _ _ r s f t o : α → β) = f := rfl
@[simp] theorem coe_fn_to_rel_embedding (f : r ≺i s) : (f.to_rel_embedding : α → β) = f := rfl
@[simp] theorem coe_coe_fn (f : r ≺i s) : ((f : r ↪r s) : α → β) = f := rfl
theorem down (f : r ≺i s) : ∀ {b : β}, s b f.top ↔ ∃ a, f a = b := f.down'
theorem lt_top (f : r ≺i s) (a : α) : s (f a) f.top := f.down.2 ⟨_, rfl⟩
theorem init [is_trans β s] (f : r ≺i s) {a : α} {b : β} (h : s b (f a)) : ∃ a', f a' = b :=
f.down.1 $ trans h $ f.lt_top _
/-- A principal segment is in particular an initial segment. -/
instance has_coe_initial_seg [is_trans β s] : has_coe (r ≺i s) (r ≼i s) :=
⟨λ f, ⟨f.to_rel_embedding, λ a b, f.init⟩⟩
theorem coe_coe_fn' [is_trans β s] (f : r ≺i s) : ((f : r ≼i s) : α → β) = f := rfl
theorem init_iff [is_trans β s] (f : r ≺i s) {a : α} {b : β} :
s b (f a) ↔ ∃ a', f a' = b ∧ r a' a :=
@initial_seg.init_iff α β r s f a b
theorem irrefl {r : α → α → Prop} [is_well_order α r] (f : r ≺i r) : false :=
begin
have := f.lt_top f.top,
rw [show f f.top = f.top, from
initial_seg.eq ↑f (initial_seg.refl r) f.top] at this,
exact irrefl _ this
end
instance (r : α → α → Prop) [is_well_order α r] : is_empty (r ≺i r) := ⟨λ f, f.irrefl⟩
/-- Composition of a principal segment with an initial segment, as a principal segment -/
def lt_le (f : r ≺i s) (g : s ≼i t) : r ≺i t :=
⟨@rel_embedding.trans _ _ _ r s t f g, g f.top, λ a,
by simp only [g.init_iff, f.down', exists_and_distrib_left.symm,
exists_swap, rel_embedding.trans_apply, exists_eq_right']; refl⟩
@[simp] theorem lt_le_apply (f : r ≺i s) (g : s ≼i t) (a : α) : (f.lt_le g) a = g (f a) :=
rel_embedding.trans_apply _ _ _
@[simp] theorem lt_le_top (f : r ≺i s) (g : s ≼i t) : (f.lt_le g).top = g f.top := rfl
/-- Composition of two principal segments as a principal segment -/
@[trans] protected def trans [is_trans γ t] (f : r ≺i s) (g : s ≺i t) : r ≺i t :=
lt_le f g
@[simp] theorem trans_apply [is_trans γ t] (f : r ≺i s) (g : s ≺i t) (a : α) :
(f.trans g) a = g (f a) :=
lt_le_apply _ _ _
@[simp] theorem trans_top [is_trans γ t] (f : r ≺i s) (g : s ≺i t) :
(f.trans g).top = g f.top := rfl
/-- Composition of an order isomorphism with a principal segment, as a principal segment -/
def equiv_lt (f : r ≃r s) (g : s ≺i t) : r ≺i t :=
⟨@rel_embedding.trans _ _ _ r s t f g, g.top, λ c,
suffices (∃ (a : β), g a = c) ↔ ∃ (a : α), g (f a) = c, by simpa [g.down],
⟨λ ⟨b, h⟩, ⟨f.symm b, by simp only [h, rel_iso.apply_symm_apply, rel_iso.coe_coe_fn]⟩,
λ ⟨a, h⟩, ⟨f a, h⟩⟩⟩
/-- Composition of a principal segment with an order isomorphism, as a principal segment -/
def lt_equiv {r : α → α → Prop} {s : β → β → Prop} {t : γ → γ → Prop}
(f : principal_seg r s) (g : s ≃r t) : principal_seg r t :=
⟨@rel_embedding.trans _ _ _ r s t f g, g f.top,
begin
intro x,
rw [← g.apply_symm_apply x, g.map_rel_iff, f.down', exists_congr],
intro y, exact ⟨congr_arg g, λ h, g.to_equiv.bijective.1 h⟩
end⟩
@[simp] theorem equiv_lt_apply (f : r ≃r s) (g : s ≺i t) (a : α) : (equiv_lt f g) a = g (f a) :=
rel_embedding.trans_apply _ _ _
@[simp] theorem equiv_lt_top (f : r ≃r s) (g : s ≺i t) : (equiv_lt f g).top = g.top := rfl
/-- Given a well order `s`, there is a most one principal segment embedding of `r` into `s`. -/
instance [is_well_order β s] : subsingleton (r ≺i s) :=
⟨λ f g, begin
have ef : (f : α → β) = g,
{ show ((f : r ≼i s) : α → β) = g,
rw @subsingleton.elim _ _ (f : r ≼i s) g, refl },
have et : f.top = g.top,
{ refine extensional_of_trichotomous_of_irrefl s (λ x, _),
simp only [f.down, g.down, ef, coe_fn_to_rel_embedding] },
cases f, cases g,
have := rel_embedding.coe_fn_injective ef; congr'
end⟩
theorem top_eq [is_well_order γ t]
(e : r ≃r s) (f : r ≺i t) (g : s ≺i t) : f.top = g.top :=
by rw subsingleton.elim f (principal_seg.equiv_lt e g); refl
lemma top_lt_top {r : α → α → Prop} {s : β → β → Prop} {t : γ → γ → Prop}
[is_well_order γ t]
(f : principal_seg r s) (g : principal_seg s t) (h : principal_seg r t) : t h.top g.top :=
by { rw [subsingleton.elim h (f.trans g)], apply principal_seg.lt_top }
/-- Any element of a well order yields a principal segment -/
def of_element {α : Type*} (r : α → α → Prop) (a : α) : subrel r {b | r b a} ≺i r :=
⟨subrel.rel_embedding _ _, a, λ b,
⟨λ h, ⟨⟨_, h⟩, rfl⟩, λ ⟨⟨_, h⟩, rfl⟩, h⟩⟩
@[simp] theorem of_element_apply {α : Type*} (r : α → α → Prop) (a : α) (b) :
of_element r a b = b.1 := rfl
@[simp] theorem of_element_top {α : Type*} (r : α → α → Prop) (a : α) :
(of_element r a).top = a := rfl
/-- Restrict the codomain of a principal segment -/
def cod_restrict (p : set β) (f : r ≺i s)
(H : ∀ a, f a ∈ p) (H₂ : f.top ∈ p) : r ≺i subrel s p :=
⟨rel_embedding.cod_restrict p f H, ⟨f.top, H₂⟩, λ ⟨b, h⟩,
f.down.trans $ exists_congr $ λ a,
show (⟨f a, H a⟩ : p).1 = _ ↔ _, from ⟨subtype.eq, congr_arg _⟩⟩
@[simp]
theorem cod_restrict_apply (p) (f : r ≺i s) (H H₂ a) : cod_restrict p f H H₂ a = ⟨f a, H a⟩ := rfl
@[simp]
theorem cod_restrict_top (p) (f : r ≺i s) (H H₂) : (cod_restrict p f H H₂).top = ⟨f.top, H₂⟩ := rfl
/-- Principal segment from an empty type into a type with a minimal element. -/
def of_is_empty (r : α → α → Prop) [is_empty α] {b : β} (H : ∀ b', ¬ s b' b) : r ≺i s :=
{ top := b,
down' := by simp [H],
..rel_embedding.of_is_empty r s }
@[simp] theorem of_is_empty_top (r : α → α → Prop) [is_empty α] {b : β} (H : ∀ b', ¬ s b' b) :
(of_is_empty r H).top = b := rfl
/-- Principal segment from the empty relation on `pempty` to the empty relation on `punit`. -/
@[reducible] def pempty_to_punit : @empty_relation pempty ≺i @empty_relation punit :=
@of_is_empty _ _ empty_relation _ _ punit.star $ λ x, not_false
protected theorem acc [is_trans β s] (f : r ≺i s) (a : α) : acc r a ↔ acc s (f a) :=
(f : r ≼i s).acc a
end principal_seg
/--
A relation is well-founded iff every principal segment of it is well-founded.
In this lemma we use `subrel` to indicate its principal segments because it's usually more
convenient to use.
-/
theorem well_founded_iff_well_founded_subrel {β : Type*} {s : β → β → Prop} [is_trans β s] :
well_founded s ↔ (∀ b, well_founded (subrel s {b' | s b' b})) :=
begin
refine ⟨λ wf b, ⟨λ b', ((principal_seg.of_element _ b).acc b').mpr (wf.apply b')⟩,
λ wf, ⟨λ b, acc.intro _ (λ b' hb', _)⟩⟩,
let f := principal_seg.of_element s b,
obtain ⟨b', rfl⟩ := f.down.mp ((principal_seg.of_element_top s b).symm ▸ hb' : s b' f.top),
exact (f.acc b').mp ((wf b).apply b'),
end
theorem {u} well_founded_iff_principal_seg {β : Type u} {s : β → β → Prop} [is_trans β s] :
well_founded s ↔ (∀ (α : Type u) (r : α → α → Prop) (f : r ≺i s), well_founded r) :=
⟨λ wf α r f, rel_hom_class.well_founded f.to_rel_embedding wf,
λ h, well_founded_iff_well_founded_subrel.mpr (λ b, h _ _ (principal_seg.of_element s b))⟩
/-! ### Properties of initial and principal segments -/
/-- To an initial segment taking values in a well order, one can associate either a principal
segment (if the range is not everything, hence one can take as top the minimum of the complement
of the range) or an order isomorphism (if the range is everything). -/
noncomputable def initial_seg.lt_or_eq [is_well_order β s] (f : r ≼i s) : (r ≺i s) ⊕ (r ≃r s) :=
begin
by_cases h : surjective f,
{ exact sum.inr (rel_iso.of_surjective f h) },
{ have h' : _, from (initial_seg.eq_or_principal f).resolve_left h,
exact sum.inl ⟨f, classical.some h', classical.some_spec h'⟩ }
end
theorem initial_seg.lt_or_eq_apply_left [is_well_order β s]
(f : r ≼i s) (g : r ≺i s) (a : α) : g a = f a :=
@initial_seg.eq α β r s _ g f a
theorem initial_seg.lt_or_eq_apply_right [is_well_order β s]
(f : r ≼i s) (g : r ≃r s) (a : α) : g a = f a :=
initial_seg.eq (initial_seg.of_iso g) f a
/-- Composition of an initial segment taking values in a well order and a principal segment. -/
noncomputable def initial_seg.le_lt [is_well_order β s] [is_trans γ t] (f : r ≼i s) (g : s ≺i t) :
r ≺i t :=
match f.lt_or_eq with
| sum.inl f' := f'.trans g
| sum.inr f' := principal_seg.equiv_lt f' g
end
@[simp] theorem initial_seg.le_lt_apply [is_well_order β s] [is_trans γ t]
(f : r ≼i s) (g : s ≺i t) (a : α) : (f.le_lt g) a = g (f a) :=
begin
delta initial_seg.le_lt, cases h : f.lt_or_eq with f' f',
{ simp only [principal_seg.trans_apply, f.lt_or_eq_apply_left] },
{ simp only [principal_seg.equiv_lt_apply, f.lt_or_eq_apply_right] }
end
namespace rel_embedding
/-- Given an order embedding into a well order, collapse the order embedding by filling the
gaps, to obtain an initial segment. Here, we construct the collapsed order embedding pointwise,
but the proof of the fact that it is an initial segment will be given in `collapse`. -/
noncomputable def collapse_F [is_well_order β s] (f : r ↪r s) : Π a, {b // ¬ s (f a) b} :=
(rel_embedding.well_founded f $ is_well_founded.wf).fix $ λ a IH, begin
let S := {b | ∀ a h, s (IH a h).1 b},
have : f a ∈ S, from λ a' h, ((trichotomous _ _)
.resolve_left $ λ h', (IH a' h).2 $ trans (f.map_rel_iff.2 h) h')
.resolve_left $ λ h', (IH a' h).2 $ h' ▸ f.map_rel_iff.2 h,
exact ⟨is_well_founded.wf.min S ⟨_, this⟩,
is_well_founded.wf.not_lt_min _ _ this⟩
end
theorem collapse_F.lt [is_well_order β s] (f : r ↪r s) {a : α}
: ∀ {a'}, r a' a → s (collapse_F f a').1 (collapse_F f a).1 :=
show (collapse_F f a).1 ∈ {b | ∀ a' (h : r a' a), s (collapse_F f a').1 b}, begin
unfold collapse_F, rw well_founded.fix_eq,
apply well_founded.min_mem _ _
end
theorem collapse_F.not_lt [is_well_order β s] (f : r ↪r s) (a : α)
{b} (h : ∀ a' (h : r a' a), s (collapse_F f a').1 b) : ¬ s b (collapse_F f a).1 :=
begin
unfold collapse_F, rw well_founded.fix_eq,
exact well_founded.not_lt_min _ _ _
(show b ∈ {b | ∀ a' (h : r a' a), s (collapse_F f a').1 b}, from h)
end
/-- Construct an initial segment from an order embedding into a well order, by collapsing it
to fill the gaps. -/
noncomputable def collapse [is_well_order β s] (f : r ↪r s) : r ≼i s :=
by haveI := rel_embedding.is_well_order f; exact
⟨rel_embedding.of_monotone
(λ a, (collapse_F f a).1) (λ a b, collapse_F.lt f),
λ a b, acc.rec_on (is_well_founded.wf.apply b : acc s b) (λ b H IH a h, begin
let S := {a | ¬ s (collapse_F f a).1 b},
have : S.nonempty := ⟨_, asymm h⟩,
existsi (is_well_founded.wf : well_founded r).min S this,
refine ((@trichotomous _ s _ _ _).resolve_left _).resolve_right _,
{ exact (is_well_founded.wf : well_founded r).min_mem S this },
{ refine collapse_F.not_lt f _ (λ a' h', _),
by_contradiction hn,
exact is_well_founded.wf.not_lt_min S this hn h' }
end) a⟩
theorem collapse_apply [is_well_order β s] (f : r ↪r s)
(a) : collapse f a = (collapse_F f a).1 := rfl
end rel_embedding
|
213dfc58259ee92658a26866abb1f9d9dbc7d359 | 2c819623a83d8c53b7282622429e344389ce4030 | /proofs/thm1.lean | c4807f00c8b1b63578ebb54921f8c2b87567400a | [] | no_license | uw-unsat/jitsynth | 6bc97dd1ede9da42c0b9313a4766095345493adc | 69529e18d4a8d4dace884bfde91aa26b549523fa | refs/heads/master | 1,653,802,737,129 | 1,588,361,732,000 | 1,588,361,732,000 | 260,513,113 | 14 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 21,563 | lean | import tactic
import tactic.find
import tactic.core
import .lib
import .util.nat
import .util.list
namespace jitsynth
-- If starting PC is too big,
-- Result of run is the starting state
lemma run_big_pc :
∀ m : arm,
∀ p : list cinstr,
∀ σ : state,
∀ T : cinstr → state → state,
∀ φ : ℕ,
p.length ≤ σ.pc →
(run p σ T φ) = σ
| m p σ T 0 :=
by intro h; unfold run
| m p σ T (nat.succ φ) :=
begin
intro h,
unfold run,
rewrite nth_big_i; try {exact h},
unfold run._match_1
end
-- Simplify the length of a compiled program
lemma compile_len :
∀ sp : list cinstr,
∀ C : cinstr → list cinstr,
(∀ si : cinstr, (C si).length = pc_mult) →
(compile C sp).length = pc_mult * sp.length
| [] C h := by unfold compile;simp
| (sph :: spt) C h :=
begin
unfold compile,
simp,
rewrite h,
rewrite nat.left_distrib,
simp,
rewrite compile_len,
exact h
end
-- Can reduce/increase the amount of fuel
-- if the smaller fuel value is enough
-- to complete the run
lemma enough_fuel :
∀ m : arm,
∀ p : list cinstr,
∀ σ : state,
∀ f big_f : ℕ,
p.length - σ.pc ≤ f →
f ≤ big_f →
run p σ m.T f = run p σ m.T big_f
| m p σ 0 big_f f_bound big_f_bound :=
begin
-- nat.le_of_sub_eq_zero
have f_bound' := nat.eq_zero_of_le_zero f_bound,
have pc_bound := nat.le_of_sub_eq_zero f_bound',
repeat {rewrite run_big_pc},
repeat {assumption}
end
| m p σ (f+1) big_f f_bound big_f_bound :=
begin
cases nat.lt_or_ge σ.pc p.length,
-- σ.pc < p.length
have e_p_nth := e_nth cinstr p σ.pc empty_cinstr h,
cases e_p_nth with p_pc some_p_pc,
unfold run,
rewrite ← some_p_pc,
unfold run._match_1,
rewrite (enough_fuel m p (m.T p_pc σ) f (big_f - 1)),
have one_le_big_f : 1 ≤ big_f,
apply one_le_of_add_le,
rewrite nat.add_comm,
apply big_f_bound,
have big_f_decomp := sub_succ big_f one_le_big_f,
have rewrite_right :
run p σ m.T big_f = run p σ m.T (big_f - 1 + 1),
rewrite big_f_decomp,
rewrite rewrite_right,
unfold run,
rewrite ← some_p_pc,
unfold run._match_1,
-- p.len - newpc ≤ f
apply sub_le_of_sub_le_succ_of_lt,
apply no_back_jumps,
assumption,
-- f ≤ big_f - 1
apply succ_le_le_sub,
assumption,
-- σ.pc ≥ p.length
repeat {rewrite run_big_pc},
repeat {assumption}
end
-- Progress "run" by one step
lemma head_run_somepc :
∀ m : arm,
∀ p : list cinstr,
∀ pi : cinstr,
∀ σ : state,
∀ f : ℕ,
some pi = p.nth σ.pc →
1 ≤ f →
run p σ m.T f =
run p (m.T pi σ) m.T (f - 1)
| m p pi σ 0 pc0 f_bound := by cases f_bound
| m p pi σ (f+1) pc0 f_bound :=
begin
simp,
unfold run,
rewrite ← pc0,
unfold run._match_1
end
-- Can run the head of a program and reduce fuel
-- when enough fuel exists
lemma head_run :
∀ m : arm,
∀ hp : cinstr,
∀ tp : list cinstr,
∀ σ : state,
∀ f : ℕ,
1 + tp.length ≤ f →
run (hp::tp) σ m.T f =
run (hp::tp) (run [hp] σ m.T 1) m.T (f - 1)
| m hp tp σ 0 f_bound :=
begin
exfalso,
apply nat.not_succ_le_zero,
rewrite ← nat.add_one,
rewrite nat.add_comm,
assumption
end
| m hp tp σ 1 f_bound :=
begin
simp at *,
unfold run,
have tp_nil := list.eq_nil_of_length_eq_zero f_bound,
rewrite tp_nil
end
| m hp tp σ (f+1) f_bound :=
begin
simp,
cases nat.lt_or_ge 0 σ.pc with pc_bound pc_bound,
-- σ.pc > 0
have inner_simp : run [hp] σ m.T 1 = σ,
apply run_big_pc; assumption; simp,
rewrite inner_simp,
rewrite ← enough_fuel,
-- 1 + tp.length - σ.pc ≤ f
simp,
apply sub_le_of_sub_le_succ_of_lt,
assumption,
simp; assumption,
--
apply nat.le_succ,
-- σ.pc = 0
have pc_zero : σ.pc = 0,
apply nat.eq_zero_of_le_zero; assumption,
unfold run,
rewrite pc_zero,
simp,
unfold run._match_1
end
-- If a program length is bound by fuel and starting PC,
-- then it's also bound by the resulting PC
lemma run_length_bound_pc_helper :
∀ m : arm,
∀ p : list cinstr,
∀ σ : state,
∀ f : ℕ,
p.length ≤ f + σ.pc →
p.length ≤ (run p σ m.T f).pc
| m p σ 0 bound :=
begin
unfold run,
simp at bound,
apply bound
end
| m p σ (f+1) bound :=
begin
cases nat.lt_or_ge σ.pc p.length,
have e_pi_nth := e_nth cinstr p σ.pc empty_cinstr h,
cases e_pi_nth with pi pi_nth,
unfold run,
rewrite ← pi_nth,
unfold run._match_1,
apply run_length_bound_pc_helper,
apply nat.le_trans,
apply bound,
rewrite nat.add_assoc,
apply nat.add_le_add_left,
apply nat.le_of_lt_succ,
rewrite ← nat.add_one,
rewrite nat.add_comm,
apply nat.add_lt_add_right,
apply no_back_jumps,
---
rewrite run_big_pc,
repeat {assumption}
end
-- If a program length is bound by fuel,
-- then it's also bound by the resulting PC
lemma run_length_bound_pc :
∀ m : arm,
∀ p : list cinstr,
∀ σ : state,
∀ f : ℕ,
p.length ≤ f →
p.length ≤ (run p σ m.T f).pc
| m p σ f bound :=
begin
rewrite ← enough_fuel m p σ p.length f,
apply run_length_bound_pc_helper,
apply nat.le_add_right,
apply sub_le,
assumption
end
-- Can run the first part of a program with enough fuel,
-- proven with induction over the difference between
-- the length of this smaller program and the starting PC
lemma head_prog_run_subpc_pciter :
∀ m : arm,
∀ hp tp : list cinstr,
∀ σ : state,
∀ k f : ℕ,
hp.length - σ.pc = k →
hp.length + tp.length ≤ f + σ.pc →
run (hp++tp) σ m.T f =
run (hp++tp) (run hp σ m.T (hp.length - σ.pc)) m.T (f - (hp.length - σ.pc))
| m [] tp σ pc f k_def f_bound := by simp; unfold run
| m (hh::hp) tp σ 0 f k_def f_bound :=
begin
have pc_ineq := nat.le_of_sub_eq_zero k_def,
have rw_inner : (run (hh::hp) σ m.T ((hh::hp).length - σ.pc)) = σ,
apply run_big_pc m,
apply pc_ineq,
rewrite rw_inner,
rewrite k_def,
simp
end
| m hp tp σ k 0 k_def f_bound :=
begin
simp at *,
unfold run,
rewrite run_big_pc m,
apply nat.le_trans,
apply nat.le_add_right,
exact tp.length,
assumption
end
| m (hh::hp) tp σ (k+1) (f+1) k_def f_bound :=
begin
-- Try to increase the fuel on the left and right side
-- So that I can use the head_run on the left
have rw_inner :
run (hh::hp) σ m.T ((hh::hp).length - σ.pc) =
run (hh::hp) σ m.T (hh::hp).length,
rewrite enough_fuel,
reflexivity,
apply sub_le,
rewrite rw_inner,
have pc_ineq : σ.pc < (hh::hp).length,
apply lt_sub_succ_n; assumption,
have e_p_nth := e_nth cinstr (hh::hp) σ.pc empty_cinstr pc_ineq,
cases e_p_nth with p p_nth,
have nth_hptp : (hh::hp++tp).nth σ.pc = some p,
apply nth_sub,
rewrite p_nth,
----
unfold run,
rewrite nth_hptp,
unfold run._match_1,
----
-- do head_run_somepc on the inner one
have rw_inner2 :
run (hh::hp) σ m.T (hh::hp).length =
run (hh::hp) (m.T p σ) m.T ((hh::hp).length - 1),
rewrite head_run_somepc,
assumption,
simp; apply nat.le_add_right,
rewrite rw_inner2,
have eval_ge_1 : 1 ≤ (m.T p σ).pc,
apply nat.le_of_lt_succ,
rewrite ← nat.add_one,
simp,
apply nat.lt_of_le_of_lt,
apply nat.zero_le,
apply no_back_jumps,
----
rewrite head_prog_run_subpc_pciter,
---
have rw_inner2 :
run (hh::hp) (m.T p σ) m.T ((hh::hp).length - (m.T p σ).pc) =
run (hh::hp) (m.T p σ) m.T ((hh::hp).length - 1),
apply enough_fuel,
reflexivity,
apply nat.sub_le_sub_left,
apply eval_ge_1,
rewrite rw_inner2,
have my_inner_pc_bound :
(hh::hp).length ≤ (run (hh::hp) (m.T p σ) m.T ((hh::hp).length - 1)).pc,
apply run_length_bound_pc_helper,
simp,
rewrite nat.add_comm,
apply nat.add_le_add_left,
apply eval_ge_1,
-- Need to prove both of these inequalities
---- First
have trans_lemma1 :
(hh::hp++tp).length - (run (hh::hp) (m.T p σ) m.T ((hh::hp).length - 1)).pc ≤
(hh::hp++tp).length - (hh::hp).length,
apply nat.sub_le_sub_left,
apply my_inner_pc_bound,
have trans_lemma2 :
tp.length ≤ f - (hp.length - σ.pc),
simp at f_bound,
rewrite nat.add_comm at f_bound,
rewrite ← nat.add_assoc at f_bound,
have f_bound' := nat.le_of_add_le_add_right f_bound,
rewrite nat.add_comm at f_bound',
have f_bound'' := nat.sub_le_sub_right f_bound' σ.pc,
rewrite nat.add_sub_assoc at f_bound'',
rewrite nat.add_sub_cancel at f_bound'',
have f_bound''' := nat.sub_le_sub_right f_bound'' (hp.length - σ.pc),
rewrite nat.add_sub_cancel at f_bound''',
assumption,
---
apply nat.le_of_lt_succ,
simp at pc_ineq,
rewrite nat.add_comm at pc_ineq,
rewrite nat.add_one at pc_ineq,
assumption,
have len_add_rw : 1 + (hp.length + tp.length) = tp.length + (1 + hp.length),
simp,
have enough_fuel_ineq1 :
(hh::hp++tp).length - (run (hh::hp) (m.T p σ) m.T ((hh::hp).length - 1)).pc ≤
(f - ((hh::hp).length - (m.T p σ).pc)),
apply nat.le_trans trans_lemma1,
simp,
rewrite len_add_rw,
rewrite nat.add_sub_cancel,
apply nat.le_trans trans_lemma2,
apply nat.sub_le_sub_left,
apply nat.le_of_lt_succ,
rewrite ← nat.one_add,
rewrite ← nat.add_sub_assoc,
apply smaller_sub,
apply no_back_jumps,
simp at pc_ineq,
assumption,
apply nat.le_of_lt_succ,
simp at pc_ineq,
rewrite one_add,
assumption,
-------
---- Second
have enough_fuel_ineq2 :
(hh::hp++tp).length - (run (hh::hp) (m.T p σ) m.T ((hh::hp).length - 1)).pc ≤
(f + 1 - ((hh::hp).length - σ.pc)),
-- NOTE: This should be strictly easier than the last one,
-- Since this was basically a sub-proof
-- (can basically get + 1 and hh to cancel, going smaller)
apply nat.le_trans trans_lemma1,
simp,
rewrite len_add_rw,
rewrite nat.add_sub_cancel,
apply nat.le_trans trans_lemma2,
have rw_asa : 1 + hp.length - σ.pc = (hp.length - σ.pc) + 1,
simp,
apply nat.add_sub_assoc,
apply nat.le_of_lt_succ,
simp at pc_ineq,
rewrite one_add,
assumption,
rewrite rw_asa,
rewrite nat.add_sub_add_right,
--------
cases nat.lt_or_ge
(f - ((hh::hp).length - (m.T p σ).pc))
(f + 1 - ((hh::hp).length - σ.pc)),
-- case 1
apply enough_fuel,
apply enough_fuel_ineq1,
apply nat.le_of_lt; assumption,
-- case 2
apply symm,
apply enough_fuel,
apply enough_fuel_ineq2,
assumption,
------
reflexivity,
---
apply nat.le_trans,
assumption,
rewrite nat.add_assoc,
apply nat.add_le_add_left,
apply nat.le_of_lt_succ,
rewrite ← nat.add_one,
rewrite nat.add_comm,
apply nat.add_lt_add_right,
apply no_back_jumps
---
end
-- Can run the first part of a program with enough fuel
lemma head_prog_run_subpc :
∀ m : arm,
∀ hp : list cinstr,
∀ tp : list cinstr,
∀ σ : state,
∀ f : ℕ,
hp.length + tp.length ≤ f + σ.pc →
run (hp++tp) σ m.T f =
run (hp++tp) (run hp σ m.T (hp.length - σ.pc)) m.T (f - (hp.length - σ.pc))
| m hp tp σ f f_bound :=
begin
apply head_prog_run_subpc_pciter,
reflexivity,
assumption
end
---
-- For a non-empty source program,
-- can decompose the compiled program
-- into a compiled first sequence,
-- a compiled single source instruction,
-- and some tailing program
lemma decompose_compile :
∀ C : cinstr → list cinstr,
∀ sp : list cinstr,
∀ p : cinstr,
∀ pc : ℕ,
sp.nth pc = some p →
∃ t : list cinstr,
(compile C sp) = (compile C (sublist sp pc)) ++ (C p) ++ t
| C [] p pc smp := by cases smp
| C (a::sp) p pc smp :=
begin
cases nat.lt_or_ge pc 1,
apply exists.intro,
unfold compile,
-- pc < 1
have pc0 := only_zero_lt_one pc h,
rewrite pc0,
unfold sublist,
unfold compile,
simp,
have pa : p = a,
rewrite pc0 at smp,
simp at smp,
rewrite smp,
rewrite pa,
-- pc ≥ 1
have pcm1 : pc = (pc - 1) + 1,
rewrite sub_succ,
apply h,
rewrite pcm1,
unfold sublist,
unfold compile,
have smp_sub1 : sp.nth (pc-1) = some p,
rewrite pcm1 at smp,
unfold list.nth at smp,
assumption,
have ih := decompose_compile C sp p (pc-1) smp_sub1,
cases ih with comp_tail rw_comp,
rewrite rw_comp,
simp,
existsi comp_tail,
reflexivity
end
-- Given necessary assumptions,
-- for any starting target state and fuel,
-- there exists a new target state and smaller fuel value
-- such that a "run" with the starting state and fuel
-- is equivalent to a run with this new state
-- and reduced fuel.
-- In addition, this new target state is congruent to
-- the source state one step after the starting source state,
-- and the reduced fuel is reduced by pc_mult at most.
lemma sm_to_e_cong_tstate :
∀ s t : arm,
∀ C : cinstr → list cinstr,
(sound_minic s t C) →
(∀ si : cinstr, (C si).length = pc_mult) →
∀ sp : list cinstr,
∀ p : cinstr,
∀ σs σt : state,
∀ t_k : ℕ,
(cong σs σt) →
σs.pc < sp.length →
some p = sp.nth σs.pc →
pc_mult * (sp.length - σs.pc) ≤ t_k →
∃ σt' t_k',
(cong (s.T p σs) σt') ∧
t_k' ≤ t_k ∧
t_k - t_k' ≤ pc_mult ∧
(run (compile C sp) σt (t.T) t_k) =
(run (compile C sp) σt' (t.T) t_k')
| s t C lsm csize sp p σs σt t_k cst pc_bound some_p tk_bound :=
begin
unfold sound_minic at lsm,
existsi (run ((compile C (sublist sp σs.pc)) ++ C p) σt (t.T) pc_mult),
-- Previously tried, but not as nice
-- existsi t_k - (used_fuel ((compile C (sublist sp σs.pc)) ++ C p) σt (t.T) pc_mult),
existsi t_k - pc_mult,
apply and.intro,
apply lsm,
apply cst,
-----
unfold cong at cst,
cases cst with rcst cst,
cases cst with mcst pcst,
unfold pc_cong at pcst,
rewrite compile_len,
rewrite sublist_length,
exact pcst,
----
apply le_of_lt; apply pc_bound,
apply csize,
reflexivity,
apply and.intro,
-- t_k - used_fuel ≤ t_k
apply sub_le,
apply and.intro,
rewrite nat.sub_sub_self,
have sp_diff_ge_1 := diff_ge_1 σs.pc sp.length pc_bound,
rewrite ← nat.mul_one pc_mult,
have first_trans : pc_mult * 1 ≤ pc_mult * (sp.length - σs.pc),
cases nat.lt_or_ge 0 pc_mult,
-- 0 < pc_mult
rewrite mul_le_mul_left,
apply sp_diff_ge_1,
assumption,
-- pc_mult = 0
simp at h,
rewrite h,
simp,
apply nat.le_trans,
assumption,
assumption,
-- head_prog_run
-- decompose compile C sp
have decomp :=
decompose_compile
C sp p σs.pc
(eq.symm some_p),
cases decomp with t_prog rw_comp,
rewrite rw_comp,
have pc_mult_rw :
pc_mult = ((compile C (sublist sp σs.pc)) ++ C p).length - σt.pc,
simp,
rewrite csize,
rewrite compile_len,
rewrite sublist_length,
unfold cong at cst,
cases cst with rcst cst,
cases cst with mcst pcst,
unfold pc_cong at pcst,
rewrite ← pcst; simp,
apply nat.le_of_lt,
exact pc_bound,
exact csize,
have tk_pc_diff_rw :
t_k - pc_mult = t_k - (((compile C (sublist sp σs.pc)) ++ C p).length - σt.pc),
rewrite pc_mult_rw,
rewrite tk_pc_diff_rw,
rewrite pc_mult_rw,
apply head_prog_run_subpc t ((compile C (sublist sp σs.pc)) ++ C p) t_prog σt t_k,
simp,
rewrite nat.add_comm,
have rw_left := nat.add_comm (C p).length (compile C (sublist sp σs.pc)).length,
rewrite rw_left,
rewrite append_length,
rewrite append_length,
rewrite ← rw_comp,
rewrite compile_len,
unfold cong at cst,
cases cst with reg_cst cst,
cases cst with mem_cst pc_cst,
unfold pc_cong at pc_cst,
rewrite ← pc_cst,
rewrite ← nat.add_le_add_iff_le_right (pc_mult * σs.pc) at tk_bound,
rewrite ← nat.left_distrib at tk_bound,
rewrite nat.sub_add_cancel at tk_bound,
assumption,
apply nat.le_of_lt,
repeat {assumption}
end
-- Prove the main theorem with fewer restrictions
-- to allow for a stronger inductive hypothesis
theorem sound_run_jit :
∀ s t : arm, ∀ sp : list cinstr,
∀ C : cinstr → list cinstr,
∀ σs σt : state,
∀ k t_k : ℕ,
sp.length - σs.pc ≤ k →
pc_mult * k ≤ t_k →
(∀ si : cinstr, (C si).length = pc_mult) →
(sound_minic s t C) →
(cong σs σt) →
(cong (run sp σs s.T k)
(run (compile C sp) σt t.T t_k))
| s t sp C σs σt nat.zero t_k :=
begin
intros kl0 tkg Cilen_eq_pcmul sml cst,
have k0 : 0 = sp.length - σs.pc,
symmetry,
apply nat.eq_zero_of_le_zero; apply kl0,
have len_leq_pc := eq.symm k0,
rewrite nat.sub_eq_zero_iff_le at len_leq_pc,
have tpc_pcmul_x_spc : σt.pc = pc_mult * σs.pc,
unfold cong at cst; unfold pc_cong at cst,
apply eq.symm,
exact cst.right.right,
have t_len_leq_pc : (list.length (compile C sp)) ≤ σt.pc,
rewrite tpc_pcmul_x_spc,
rewrite compile_len,
apply nat.mul_le_mul_left,
repeat {assumption},
rewrite run_big_pc,
rewrite run_big_pc,
repeat {assumption}
end
| s t sp C σs σt (nat.succ k) t_k :=
begin
intros kn tkg cilen sml cst,
have pc_lt_or_ge := nat.lt_or_ge σs.pc sp.length,
apply or.elim pc_lt_or_ge; intro pc_ineq,
-- case: σs.pc < list.length sp ----------------------
have e_sp_nth : ∃ p, some p = list.nth sp σs.pc,
apply e_nth,
exact empty_cinstr,
assumption,
cases e_sp_nth with p sp_nth,
have rewrite_left :
(run sp σs (s.T) (nat.succ k)) =
(run sp (s.T p σs) (s.T) k),
unfold run,
rewrite ← sp_nth,
unfold run._match_1,
rewrite rewrite_left,
have e_cong_tstate :
∃ σt' t_k',
(cong (s.T p σs) σt') ∧
pc_mult * k ≤ t_k' ∧
(run (compile C sp) σt (t.T) t_k) =
(run (compile C sp) σt' (t.T) t_k'),
have t_k_bound : pc_mult * (sp.length - σs.pc) ≤ t_k,
apply mul_le_inside,
assumption,
assumption,
have e_cong_sub :=
(sm_to_e_cong_tstate
s t C sml cilen
sp p σs σt t_k
cst pc_ineq sp_nth t_k_bound),
cases e_cong_sub with σt' e_cong_sub,
cases e_cong_sub with t_k' e_cong_sub,
cases e_cong_sub with cst' e_cong_sub,
cases e_cong_sub with tk'_le_tk e_cong_sub,
cases e_cong_sub with diff_bound e_cong_rewrite,
existsi σt'; existsi t_k',
apply and.intro, assumption,
apply and.intro,
-- pc_mult * k ≤ t_k'
rewrite nat.mul_succ at tkg,
have tkg' := nat.sub_le_sub_right tkg pc_mult,
simp at tkg',
apply nat.le_trans,
apply tkg',
-- rewrite nat.add_le_to_le_sub at diff_bound,
have diff_bound' := nat.add_le_add_right diff_bound t_k',
rewrite nat.sub_add_cancel at diff_bound',
have diff_bound'' := nat.sub_le_sub_right diff_bound' pc_mult,
simp at diff_bound'',
assumption,
assumption,
assumption,
--
cases e_cong_tstate with σt' e_cong_tstate,
cases e_cong_tstate with t_k' e_cong_tstate,
cases e_cong_tstate with cong_state e_cong_tstate,
cases e_cong_tstate with t_k'_bound rewrite_right,
rewrite rewrite_right,
apply sound_run_jit,
-- goal: list.length sp - (s.T p σs).pc ≤ k
have nbj := no_back_jumps s p σs,
have ineq1 : list.length sp - (s.T p σs).pc ≤ list.length sp - σs.pc,
apply nat.sub_le_sub_left,
apply nat.le_of_lt nbj,
have ineq2 : list.length sp - (s.T p σs).pc < list.length sp - σs.pc,
apply sub_lt_sub,
apply no_back_jumps,
exact pc_ineq,
apply nat.le_of_lt_succ,
apply nat.lt_of_lt_of_le,
exact ineq2,
repeat {assumption},
-- case: σs.pc < list.length sp ----------------------
repeat {rewrite run_big_pc; try {assumption}},
unfold cong at cst,
cases cst with rcst cst; cases cst with mcst pcst,
unfold pc_cong at pcst,
rewrite ← pcst,
rewrite compile_len,
apply nat.mul_le_mul_left,
repeat {assumption}
end
-- Main theorem
-- States that for any pair of machines,
-- any source program, any compiler,
-- and any starting state pair,
-- given compiled programs are "pc_mult" long,
-- given the starting fuel is the program length,
-- given the individual compilers are sound,
-- given the starting states are congruent,
-- then the result of executing the source program
-- is congruent to the result of executing the
-- compiled source program
theorem jit_soundness :
∀ s t : arm, ∀ sp : list cinstr,
∀ C : cinstr → list cinstr,
∀ σs σt : state,
(∀ si : cinstr, (C si).length = pc_mult) →
(∀ p : list cinstr, s.Φ p = p.length) →
(∀ p : list cinstr, t.Φ p = p.length) →
(sound_minic s t C) →
(cong σs σt) →
(cong (𝔸 s sp σs) (𝔸 t (compile C sp) σt))
| s t sp C σs σt clen sfuel_bound tfuel_bound sml cst :=
begin
unfold 𝔸,
rewrite sfuel_bound,
rewrite tfuel_bound,
apply sound_run_jit,
apply sub_le,
rewrite compile_len,
repeat {assumption}
end
end jitsynth |
aef1164064d7895da9cc521b48aeb5be03e62491 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/category_theory/subobject/limits.lean | 08e559e0c2913697d0a964de43d3c7827612dfc2 | [
"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 | 17,697 | lean | /-
Copyright (c) 2020 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Bhavik Mehta, Scott Morrison
-/
import category_theory.subobject.lattice
/-!
# Specific subobjects
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
We define `equalizer_subobject`, `kernel_subobject` and `image_subobject`, which are the subobjects
represented by the equalizer, kernel and image of (a pair of) morphism(s) and provide conditions
for `P.factors f`, where `P` is one of these special subobjects.
TODO: Add conditions for when `P` is a pullback subobject.
TODO: an iff characterisation of `(image_subobject f).factors h`
-/
universes v u
noncomputable theory
open category_theory category_theory.category category_theory.limits category_theory.subobject
opposite
variables {C : Type u} [category.{v} C] {X Y Z : C}
namespace category_theory
namespace limits
section equalizer
variables (f g : X ⟶ Y) [has_equalizer f g]
/-- The equalizer of morphisms `f g : X ⟶ Y` as a `subobject X`. -/
abbreviation equalizer_subobject : subobject X :=
subobject.mk (equalizer.ι f g)
/-- The underlying object of `equalizer_subobject f g` is (up to isomorphism!)
the same as the chosen object `equalizer f g`. -/
def equalizer_subobject_iso : (equalizer_subobject f g : C) ≅ equalizer f g :=
subobject.underlying_iso (equalizer.ι f g)
@[simp, reassoc]
lemma equalizer_subobject_arrow :
(equalizer_subobject_iso f g).hom ≫ equalizer.ι f g = (equalizer_subobject f g).arrow :=
by simp [equalizer_subobject_iso]
@[simp, reassoc]
lemma equalizer_subobject_arrow' :
(equalizer_subobject_iso f g).inv ≫ (equalizer_subobject f g).arrow = equalizer.ι f g :=
by simp [equalizer_subobject_iso]
@[reassoc]
lemma equalizer_subobject_arrow_comp :
(equalizer_subobject f g).arrow ≫ f = (equalizer_subobject f g).arrow ≫ g :=
by rw [←equalizer_subobject_arrow, category.assoc, category.assoc, equalizer.condition]
lemma equalizer_subobject_factors {W : C} (h : W ⟶ X) (w : h ≫ f = h ≫ g) :
(equalizer_subobject f g).factors h :=
⟨equalizer.lift h w, by simp⟩
lemma equalizer_subobject_factors_iff {W : C} (h : W ⟶ X) :
(equalizer_subobject f g).factors h ↔ h ≫ f = h ≫ g :=
⟨λ w, by rw [←subobject.factor_thru_arrow _ _ w, category.assoc,
equalizer_subobject_arrow_comp, category.assoc],
equalizer_subobject_factors f g h⟩
end equalizer
section kernel
variables [has_zero_morphisms C] (f : X ⟶ Y) [has_kernel f]
/-- The kernel of a morphism `f : X ⟶ Y` as a `subobject X`. -/
abbreviation kernel_subobject : subobject X :=
subobject.mk (kernel.ι f)
/-- The underlying object of `kernel_subobject f` is (up to isomorphism!)
the same as the chosen object `kernel f`. -/
def kernel_subobject_iso :
(kernel_subobject f : C) ≅ kernel f :=
subobject.underlying_iso (kernel.ι f)
@[simp, reassoc, elementwise]
lemma kernel_subobject_arrow :
(kernel_subobject_iso f).hom ≫ kernel.ι f = (kernel_subobject f).arrow :=
by simp [kernel_subobject_iso]
@[simp, reassoc, elementwise]
lemma kernel_subobject_arrow' :
(kernel_subobject_iso f).inv ≫ (kernel_subobject f).arrow = kernel.ι f :=
by simp [kernel_subobject_iso]
@[simp, reassoc, elementwise]
lemma kernel_subobject_arrow_comp :
(kernel_subobject f).arrow ≫ f = 0 :=
by { rw [←kernel_subobject_arrow], simp only [category.assoc, kernel.condition, comp_zero], }
lemma kernel_subobject_factors {W : C} (h : W ⟶ X) (w : h ≫ f = 0) :
(kernel_subobject f).factors h :=
⟨kernel.lift _ h w, by simp⟩
lemma kernel_subobject_factors_iff {W : C} (h : W ⟶ X) :
(kernel_subobject f).factors h ↔ h ≫ f = 0 :=
⟨λ w, by rw [←subobject.factor_thru_arrow _ _ w, category.assoc,
kernel_subobject_arrow_comp, comp_zero],
kernel_subobject_factors f h⟩
/-- A factorisation of `h : W ⟶ X` through `kernel_subobject f`, assuming `h ≫ f = 0`. -/
def factor_thru_kernel_subobject {W : C} (h : W ⟶ X) (w : h ≫ f = 0) :
W ⟶ kernel_subobject f :=
(kernel_subobject f).factor_thru h (kernel_subobject_factors f h w)
@[simp] lemma factor_thru_kernel_subobject_comp_arrow {W : C} (h : W ⟶ X) (w : h ≫ f = 0) :
factor_thru_kernel_subobject f h w ≫ (kernel_subobject f).arrow = h :=
by { dsimp [factor_thru_kernel_subobject], simp, }
@[simp] lemma factor_thru_kernel_subobject_comp_kernel_subobject_iso {W : C} (h : W ⟶ X)
(w : h ≫ f = 0) :
factor_thru_kernel_subobject f h w ≫ (kernel_subobject_iso f).hom = kernel.lift f h w :=
(cancel_mono (kernel.ι f)).1 $ by simp
section
variables {f} {X' Y' : C} {f' : X' ⟶ Y'} [has_kernel f']
/-- A commuting square induces a morphism between the kernel subobjects. -/
def kernel_subobject_map (sq : arrow.mk f ⟶ arrow.mk f') :
(kernel_subobject f : C) ⟶ (kernel_subobject f' : C) :=
subobject.factor_thru _
((kernel_subobject f).arrow ≫ sq.left)
(kernel_subobject_factors _ _ (by simp [sq.w]))
@[simp, reassoc, elementwise]
lemma kernel_subobject_map_arrow (sq : arrow.mk f ⟶ arrow.mk f') :
kernel_subobject_map sq ≫ (kernel_subobject f').arrow =
(kernel_subobject f).arrow ≫ sq.left :=
by simp [kernel_subobject_map]
@[simp] lemma kernel_subobject_map_id : kernel_subobject_map (𝟙 (arrow.mk f)) = 𝟙 _ :=
by { ext, simp, dsimp, simp, } -- See library note [dsimp, simp].
@[simp] lemma kernel_subobject_map_comp {X'' Y'' : C} {f'' : X'' ⟶ Y''} [has_kernel f'']
(sq : arrow.mk f ⟶ arrow.mk f') (sq' : arrow.mk f' ⟶ arrow.mk f'') :
kernel_subobject_map (sq ≫ sq') = kernel_subobject_map sq ≫ kernel_subobject_map sq' :=
by { ext, simp, }
@[reassoc] lemma kernel_map_comp_kernel_subobject_iso_inv (sq : arrow.mk f ⟶ arrow.mk f') :
kernel.map f f' sq.1 sq.2 sq.3.symm ≫ (kernel_subobject_iso _).inv =
(kernel_subobject_iso _).inv ≫ kernel_subobject_map sq :=
by ext; simp
@[reassoc] lemma kernel_subobject_iso_comp_kernel_map
(sq : arrow.mk f ⟶ arrow.mk f') :
(kernel_subobject_iso _).hom ≫ kernel.map f f' sq.1 sq.2 sq.3.symm =
kernel_subobject_map sq ≫ (kernel_subobject_iso _).hom :=
by simp [←iso.comp_inv_eq, kernel_map_comp_kernel_subobject_iso_inv]
end
@[simp]
lemma kernel_subobject_zero {A B : C} : kernel_subobject (0 : A ⟶ B) = ⊤ :=
(is_iso_iff_mk_eq_top _).mp (by apply_instance)
instance is_iso_kernel_subobject_zero_arrow : is_iso (kernel_subobject (0 : X ⟶ Y)).arrow :=
(is_iso_arrow_iff_eq_top _).mpr kernel_subobject_zero
lemma le_kernel_subobject (A : subobject X) (h : A.arrow ≫ f = 0) : A ≤ kernel_subobject f :=
subobject.le_mk_of_comm (kernel.lift f A.arrow h) (by simp)
/--
The isomorphism between the kernel of `f ≫ g` and the kernel of `g`,
when `f` is an isomorphism.
-/
def kernel_subobject_iso_comp
{X' : C} (f : X' ⟶ X) [is_iso f] (g : X ⟶ Y) [has_kernel g] :
(kernel_subobject (f ≫ g) : C) ≅ (kernel_subobject g : C) :=
(kernel_subobject_iso _) ≪≫ (kernel_is_iso_comp f g) ≪≫ (kernel_subobject_iso _).symm
@[simp]
lemma kernel_subobject_iso_comp_hom_arrow
{X' : C} (f : X' ⟶ X) [is_iso f] (g : X ⟶ Y) [has_kernel g] :
(kernel_subobject_iso_comp f g).hom ≫ (kernel_subobject g).arrow =
(kernel_subobject (f ≫ g)).arrow ≫ f :=
by { simp [kernel_subobject_iso_comp], }
@[simp]
lemma kernel_subobject_iso_comp_inv_arrow
{X' : C} (f : X' ⟶ X) [is_iso f] (g : X ⟶ Y) [has_kernel g] :
(kernel_subobject_iso_comp f g).inv ≫ (kernel_subobject (f ≫ g)).arrow =
(kernel_subobject g).arrow ≫ inv f :=
by { simp [kernel_subobject_iso_comp], }
/-- The kernel of `f` is always a smaller subobject than the kernel of `f ≫ h`. -/
lemma kernel_subobject_comp_le
(f : X ⟶ Y) [has_kernel f] {Z : C} (h : Y ⟶ Z) [has_kernel (f ≫ h)]:
kernel_subobject f ≤ kernel_subobject (f ≫ h) :=
le_kernel_subobject _ _ (by simp)
/-- Postcomposing by an monomorphism does not change the kernel subobject. -/
@[simp]
lemma kernel_subobject_comp_mono
(f : X ⟶ Y) [has_kernel f] {Z : C} (h : Y ⟶ Z) [mono h] :
kernel_subobject (f ≫ h) = kernel_subobject f :=
le_antisymm
(le_kernel_subobject _ _ ((cancel_mono h).mp (by simp)))
(kernel_subobject_comp_le f h)
instance kernel_subobject_comp_mono_is_iso
(f : X ⟶ Y) [has_kernel f] {Z : C} (h : Y ⟶ Z) [mono h] :
is_iso (subobject.of_le _ _ (kernel_subobject_comp_le f h)) :=
begin
rw of_le_mk_le_mk_of_comm (kernel_comp_mono f h).inv,
{ apply_instance, },
{ simp, },
end
/-- Taking cokernels is an order-reversing map from the subobjects of `X` to the quotient objects
of `X`. -/
@[simps]
def cokernel_order_hom [has_cokernels C] (X : C) : subobject X →o (subobject (op X))ᵒᵈ :=
{ to_fun := subobject.lift (λ A f hf, subobject.mk (cokernel.π f).op)
begin
rintros A B f g hf hg i rfl,
refine subobject.mk_eq_mk_of_comm _ _ (iso.op _) (quiver.hom.unop_inj _),
{ exact (is_colimit.cocone_point_unique_up_to_iso (colimit.is_colimit _)
(is_cokernel_epi_comp (colimit.is_colimit _) i.hom rfl)).symm },
{ simp only [iso.comp_inv_eq, iso.op_hom, iso.symm_hom, unop_comp, quiver.hom.unop_op,
colimit.comp_cocone_point_unique_up_to_iso_hom, cofork.of_π_ι_app, coequalizer.cofork_π] }
end,
monotone' := subobject.ind₂ _ $
begin
introsI A B f g hf hg h,
dsimp only [subobject.lift_mk],
refine subobject.mk_le_mk_of_comm (cokernel.desc f (cokernel.π g) _).op _,
{ rw [← subobject.of_mk_le_mk_comp h, category.assoc, cokernel.condition, comp_zero] },
{ exact quiver.hom.unop_inj (cokernel.π_desc _ _ _) }
end }
/-- Taking kernels is an order-reversing map from the quotient objects of `X` to the subobjects of
`X`. -/
@[simps]
def kernel_order_hom [has_kernels C] (X : C) : (subobject (op X))ᵒᵈ →o subobject X :=
{ to_fun := subobject.lift (λ A f hf, subobject.mk (kernel.ι f.unop))
begin
rintros A B f g hf hg i rfl,
refine subobject.mk_eq_mk_of_comm _ _ _ _,
{ exact is_limit.cone_point_unique_up_to_iso (limit.is_limit _)
(is_kernel_comp_mono (limit.is_limit (parallel_pair g.unop 0)) i.unop.hom rfl) },
{ dsimp,
simp only [←iso.eq_inv_comp, limit.cone_point_unique_up_to_iso_inv_comp, fork.of_ι_π_app] }
end,
monotone' := subobject.ind₂ _ $
begin
introsI A B f g hf hg h,
dsimp only [subobject.lift_mk],
refine subobject.mk_le_mk_of_comm (kernel.lift g.unop (kernel.ι f.unop) _) _,
{ rw [← subobject.of_mk_le_mk_comp h, unop_comp, kernel.condition_assoc, zero_comp] },
{ exact quiver.hom.op_inj (by simp) }
end }
end kernel
section image
variables (f : X ⟶ Y) [has_image f]
/-- The image of a morphism `f g : X ⟶ Y` as a `subobject Y`. -/
abbreviation image_subobject : subobject Y :=
subobject.mk (image.ι f)
/-- The underlying object of `image_subobject f` is (up to isomorphism!)
the same as the chosen object `image f`. -/
def image_subobject_iso :
(image_subobject f : C) ≅ image f :=
subobject.underlying_iso (image.ι f)
@[simp, reassoc]
lemma image_subobject_arrow :
(image_subobject_iso f).hom ≫ image.ι f = (image_subobject f).arrow :=
by simp [image_subobject_iso]
@[simp, reassoc]
lemma image_subobject_arrow' :
(image_subobject_iso f).inv ≫ (image_subobject f).arrow = image.ι f :=
by simp [image_subobject_iso]
/-- A factorisation of `f : X ⟶ Y` through `image_subobject f`. -/
def factor_thru_image_subobject : X ⟶ image_subobject f :=
factor_thru_image f ≫ (image_subobject_iso f).inv
instance [has_equalizers C] : epi (factor_thru_image_subobject f) :=
by { dsimp [factor_thru_image_subobject], apply epi_comp, }
@[simp, reassoc, elementwise]
lemma image_subobject_arrow_comp :
factor_thru_image_subobject f ≫ (image_subobject f).arrow = f :=
by simp [factor_thru_image_subobject, image_subobject_arrow]
lemma image_subobject_arrow_comp_eq_zero
[has_zero_morphisms C] {X Y Z : C} {f : X ⟶ Y} {g : Y ⟶ Z} [has_image f]
[epi (factor_thru_image_subobject f)] (h : f ≫ g = 0) : (image_subobject f).arrow ≫ g = 0 :=
zero_of_epi_comp (factor_thru_image_subobject f) $ by simp [h]
lemma image_subobject_factors_comp_self {W : C} (k : W ⟶ X) :
(image_subobject f).factors (k ≫ f) :=
⟨k ≫ factor_thru_image f, by simp⟩
@[simp]
lemma factor_thru_image_subobject_comp_self {W : C} (k : W ⟶ X) (h) :
(image_subobject f).factor_thru (k ≫ f) h = k ≫ factor_thru_image_subobject f :=
by { ext, simp, }
@[simp]
lemma factor_thru_image_subobject_comp_self_assoc {W W' : C} (k : W ⟶ W') (k' : W' ⟶ X) (h) :
(image_subobject f).factor_thru (k ≫ k' ≫ f) h = k ≫ k' ≫ factor_thru_image_subobject f :=
by { ext, simp, }
/-- The image of `h ≫ f` is always a smaller subobject than the image of `f`. -/
lemma image_subobject_comp_le
{X' : C} (h : X' ⟶ X) (f : X ⟶ Y) [has_image f] [has_image (h ≫ f)] :
image_subobject (h ≫ f) ≤ image_subobject f :=
subobject.mk_le_mk_of_comm (image.pre_comp h f) (by simp)
section
open_locale zero_object
variables [has_zero_morphisms C] [has_zero_object C]
@[simp]
lemma image_subobject_zero_arrow :
(image_subobject (0 : X ⟶ Y)).arrow = 0 :=
by { rw ←image_subobject_arrow, simp, }
@[simp]
lemma image_subobject_zero {A B : C} :
image_subobject (0 : A ⟶ B) = ⊥ :=
subobject.eq_of_comm
(image_subobject_iso _ ≪≫ image_zero ≪≫ subobject.bot_coe_iso_zero.symm) (by simp)
end
section
variables [has_equalizers C]
local attribute [instance] epi_comp
/--
The morphism `image_subobject (h ≫ f) ⟶ image_subobject f`
is an epimorphism when `h` is an epimorphism.
In general this does not imply that `image_subobject (h ≫ f) = image_subobject f`,
although it will when the ambient category is abelian.
-/
instance image_subobject_comp_le_epi_of_epi
{X' : C} (h : X' ⟶ X) [epi h] (f : X ⟶ Y) [has_image f] [has_image (h ≫ f)] :
epi (subobject.of_le _ _ (image_subobject_comp_le h f)) :=
begin
rw of_le_mk_le_mk_of_comm (image.pre_comp h f),
{ apply_instance, },
{ simp, },
end
end
section
variables [has_equalizers C]
/-- Postcomposing by an isomorphism gives an isomorphism between image subobjects. -/
def image_subobject_comp_iso
(f : X ⟶ Y) [has_image f] {Y' : C} (h : Y ⟶ Y') [is_iso h] :
(image_subobject (f ≫ h) : C) ≅ (image_subobject f : C) :=
(image_subobject_iso _) ≪≫ (image.comp_iso _ _).symm ≪≫ (image_subobject_iso _).symm
@[simp, reassoc]
lemma image_subobject_comp_iso_hom_arrow
(f : X ⟶ Y) [has_image f] {Y' : C} (h : Y ⟶ Y') [is_iso h] :
(image_subobject_comp_iso f h).hom ≫ (image_subobject f).arrow =
(image_subobject (f ≫ h)).arrow ≫ inv h :=
by simp [image_subobject_comp_iso]
@[simp, reassoc]
lemma image_subobject_comp_iso_inv_arrow
(f : X ⟶ Y) [has_image f] {Y' : C} (h : Y ⟶ Y') [is_iso h] :
(image_subobject_comp_iso f h).inv ≫ (image_subobject (f ≫ h)).arrow =
(image_subobject f).arrow ≫ h :=
by simp [image_subobject_comp_iso]
end
lemma image_subobject_mono (f : X ⟶ Y) [mono f] : image_subobject f = mk f :=
eq_of_comm (image_subobject_iso f ≪≫ image_mono_iso_source f ≪≫ (underlying_iso f).symm) (by simp)
/-- Precomposing by an isomorphism does not change the image subobject. -/
lemma image_subobject_iso_comp [has_equalizers C]
{X' : C} (h : X' ⟶ X) [is_iso h] (f : X ⟶ Y) [has_image f] :
image_subobject (h ≫ f) = image_subobject f :=
le_antisymm
(image_subobject_comp_le h f)
(subobject.mk_le_mk_of_comm (inv (image.pre_comp h f)) (by simp))
lemma image_subobject_le {A B : C} {X : subobject B} (f : A ⟶ B) [has_image f]
(h : A ⟶ X) (w : h ≫ X.arrow = f) :
image_subobject f ≤ X :=
subobject.le_of_comm
((image_subobject_iso f).hom ≫ image.lift { I := (X : C), e := h, m := X.arrow, })
(by simp)
lemma image_subobject_le_mk {A B : C} {X : C} (g : X ⟶ B) [mono g] (f : A ⟶ B) [has_image f]
(h : A ⟶ X) (w : h ≫ g = f) :
image_subobject f ≤ subobject.mk g :=
image_subobject_le f (h ≫ (subobject.underlying_iso g).inv) (by simp [w])
/-- Given a commutative square between morphisms `f` and `g`,
we have a morphism in the category from `image_subobject f` to `image_subobject g`. -/
def image_subobject_map {W X Y Z : C} {f : W ⟶ X} [has_image f] {g : Y ⟶ Z} [has_image g]
(sq : arrow.mk f ⟶ arrow.mk g) [has_image_map sq] :
(image_subobject f : C) ⟶ (image_subobject g : C) :=
(image_subobject_iso f).hom ≫ image.map sq ≫ (image_subobject_iso g).inv
@[simp, reassoc]
lemma image_subobject_map_arrow {W X Y Z : C} {f : W ⟶ X} [has_image f] {g : Y ⟶ Z} [has_image g]
(sq : arrow.mk f ⟶ arrow.mk g) [has_image_map sq] :
image_subobject_map sq ≫ (image_subobject g).arrow = (image_subobject f).arrow ≫ sq.right :=
begin
simp only [image_subobject_map, category.assoc, image_subobject_arrow'],
erw [image.map_ι, ←category.assoc, image_subobject_arrow],
end
lemma image_map_comp_image_subobject_iso_inv
{W X Y Z : C} {f : W ⟶ X} [has_image f] {g : Y ⟶ Z} [has_image g]
(sq : arrow.mk f ⟶ arrow.mk g) [has_image_map sq] :
image.map sq ≫ (image_subobject_iso _).inv =
(image_subobject_iso _).inv ≫ image_subobject_map sq :=
by ext; simp
lemma image_subobject_iso_comp_image_map
{W X Y Z : C} {f : W ⟶ X} [has_image f] {g : Y ⟶ Z} [has_image g]
(sq : arrow.mk f ⟶ arrow.mk g) [has_image_map sq] :
(image_subobject_iso _).hom ≫ image.map sq =
image_subobject_map sq ≫ (image_subobject_iso _).hom :=
by rw [←iso.comp_inv_eq, category.assoc, ←(image_subobject_iso (arrow.mk f).hom).eq_inv_comp,
←image_map_comp_image_subobject_iso_inv]; refl
end image
end limits
end category_theory
|
d871226c654236c71bf546fa39e5f473902a6ce1 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/logic/relation_auto.lean | 680dcf3cc34325f0923edc88b3d5b2e93584d416 | [] | 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 | 13,812 | 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
Transitive reflexive as well as reflexive closure of relations.
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.tactic.basic
import Mathlib.PostPort
universes u_1 u_2 u_3 u_4
namespace Mathlib
namespace relation
/--
The composition of two relations, yielding a new relation. The result
relates a term of `α` and a term of `γ` if there is an intermediate
term of `β` related to both.
-/
def comp {α : Type u_1} {β : Type u_2} {γ : Type u_3} (r : α → β → Prop) (p : β → γ → Prop) (a : α)
(c : γ) :=
∃ (b : β), r a b ∧ p b c
theorem comp_eq {α : Type u_1} {β : Type u_2} {r : α → β → Prop} : comp r Eq = r := sorry
theorem eq_comp {α : Type u_1} {β : Type u_2} {r : α → β → Prop} : comp Eq r = r := sorry
theorem iff_comp {α : Type u_1} {r : Prop → α → Prop} : comp Iff r = r := sorry
theorem comp_iff {α : Type u_1} {r : α → Prop → Prop} : comp r Iff = r := sorry
theorem comp_assoc {α : Type u_1} {β : Type u_2} {γ : Type u_3} {δ : Type u_4} {r : α → β → Prop}
{p : β → γ → Prop} {q : γ → δ → Prop} : comp (comp r p) q = comp r (comp p q) :=
sorry
theorem flip_comp {α : Type u_1} {β : Type u_2} {γ : Type u_3} {r : α → β → Prop}
{p : β → γ → Prop} : flip (comp r p) = comp (flip p) (flip r) :=
sorry
/--
The map of a relation `r` through a pair of functions pushes the
relation to the codomains of the functions. The resulting relation is
defined by having pairs of terms related if they have preimages
related by `r`.
-/
protected def map {α : Type u_1} {β : Type u_2} {γ : Type u_3} {δ : Type u_4} (r : α → β → Prop)
(f : α → γ) (g : β → δ) : γ → δ → Prop :=
fun (c : γ) (d : δ) => ∃ (a : α), ∃ (b : β), r a b ∧ f a = c ∧ g b = d
/-- `refl_trans_gen r`: reflexive transitive closure of `r` -/
inductive refl_trans_gen {α : Type u_1} (r : α → α → Prop) (a : α) : α → Prop where
| refl : refl_trans_gen r a a
| tail : ∀ {b c : α}, refl_trans_gen r a b → r b c → refl_trans_gen r a c
/-- `refl_gen r`: reflexive closure of `r` -/
inductive refl_gen {α : Type u_1} (r : α → α → Prop) (a : α) : α → Prop where
| refl : refl_gen r a a
| single : ∀ {b : α}, r a b → refl_gen r a b
/-- `trans_gen r`: transitive closure of `r` -/
inductive trans_gen {α : Type u_1} (r : α → α → Prop) (a : α) : α → Prop where
| single : ∀ {b : α}, r a b → trans_gen r a b
| tail : ∀ {b c : α}, trans_gen r a b → r b c → trans_gen r a c
theorem refl_gen.to_refl_trans_gen {α : Type u_1} {r : α → α → Prop} {a : α} {b : α} :
refl_gen r a b → refl_trans_gen r a b :=
sorry
namespace refl_trans_gen
theorem trans {α : Type u_1} {r : α → α → Prop} {a : α} {b : α} {c : α} (hab : refl_trans_gen r a b)
(hbc : refl_trans_gen r b c) : refl_trans_gen r a c :=
sorry
theorem single {α : Type u_1} {r : α → α → Prop} {a : α} {b : α} (hab : r a b) :
refl_trans_gen r a b :=
tail refl hab
theorem head {α : Type u_1} {r : α → α → Prop} {a : α} {b : α} {c : α} (hab : r a b)
(hbc : refl_trans_gen r b c) : refl_trans_gen r a c :=
sorry
theorem symmetric {α : Type u_1} {r : α → α → Prop} (h : symmetric r) :
symmetric (refl_trans_gen r) :=
sorry
theorem cases_tail {α : Type u_1} {r : α → α → Prop} {a : α} {b : α} :
refl_trans_gen r a b → b = a ∨ ∃ (c : α), refl_trans_gen r a c ∧ r c b :=
iff.mp (cases_tail_iff r a b)
theorem head_induction_on {α : Type u_1} {r : α → α → Prop} {b : α}
{P : (a : α) → refl_trans_gen r a b → Prop} {a : α} (h : refl_trans_gen r a b) (refl : P b refl)
(head : ∀ {a c : α} (h' : r a c) (h : refl_trans_gen r c b), P c h → P a (head h' h)) : P a h :=
sorry
theorem trans_induction_on {α : Type u_1} {r : α → α → Prop}
{P : {a b : α} → refl_trans_gen r a b → Prop} {a : α} {b : α} (h : refl_trans_gen r a b)
(ih₁ : α → P refl) (ih₂ : ∀ {a b : α} (h : r a b), P (single h))
(ih₃ :
∀ {a b c : α} (h₁ : refl_trans_gen r a b) (h₂ : refl_trans_gen r b c),
P h₁ → P h₂ → P (trans h₁ h₂)) :
P h :=
sorry
theorem cases_head {α : Type u_1} {r : α → α → Prop} {a : α} {b : α} (h : refl_trans_gen r a b) :
a = b ∨ ∃ (c : α), r a c ∧ refl_trans_gen r c b :=
sorry
theorem cases_head_iff {α : Type u_1} {r : α → α → Prop} {a : α} {b : α} :
refl_trans_gen r a b ↔ a = b ∨ ∃ (c : α), r a c ∧ refl_trans_gen r c b :=
sorry
theorem total_of_right_unique {α : Type u_1} {r : α → α → Prop} {a : α} {b : α} {c : α}
(U : relator.right_unique r) (ab : refl_trans_gen r a b) (ac : refl_trans_gen r a c) :
refl_trans_gen r b c ∨ refl_trans_gen r c b :=
sorry
end refl_trans_gen
namespace trans_gen
theorem to_refl {α : Type u_1} {r : α → α → Prop} {a : α} {b : α} (h : trans_gen r a b) :
refl_trans_gen r a b :=
trans_gen.drec (fun {b : α} (h : r a b) => refl_trans_gen.single h)
(fun {b c : α} (h_ᾰ : trans_gen r a b) (bc : r b c) (ab : refl_trans_gen r a b) =>
refl_trans_gen.tail ab bc)
h
theorem trans_left {α : Type u_1} {r : α → α → Prop} {a : α} {b : α} {c : α} (hab : trans_gen r a b)
(hbc : refl_trans_gen r b c) : trans_gen r a c :=
sorry
theorem trans {α : Type u_1} {r : α → α → Prop} {a : α} {b : α} {c : α} (hab : trans_gen r a b)
(hbc : trans_gen r b c) : trans_gen r a c :=
trans_left hab (to_refl hbc)
theorem head' {α : Type u_1} {r : α → α → Prop} {a : α} {b : α} {c : α} (hab : r a b)
(hbc : refl_trans_gen r b c) : trans_gen r a c :=
trans_left (single hab) hbc
theorem tail' {α : Type u_1} {r : α → α → Prop} {a : α} {b : α} {c : α} (hab : refl_trans_gen r a b)
(hbc : r b c) : trans_gen r a c :=
sorry
theorem trans_right {α : Type u_1} {r : α → α → Prop} {a : α} {b : α} {c : α}
(hab : refl_trans_gen r a b) (hbc : trans_gen r b c) : trans_gen r a c :=
sorry
theorem head {α : Type u_1} {r : α → α → Prop} {a : α} {b : α} {c : α} (hab : r a b)
(hbc : trans_gen r b c) : trans_gen r a c :=
head' hab (to_refl hbc)
theorem tail'_iff {α : Type u_1} {r : α → α → Prop} {a : α} {c : α} :
trans_gen r a c ↔ ∃ (b : α), refl_trans_gen r a b ∧ r b c :=
sorry
theorem head'_iff {α : Type u_1} {r : α → α → Prop} {a : α} {c : α} :
trans_gen r a c ↔ ∃ (b : α), r a b ∧ refl_trans_gen r b c :=
sorry
theorem trans_gen_eq_self {α : Type u_1} {r : α → α → Prop} (trans : transitive r) :
trans_gen r = r :=
sorry
theorem transitive_trans_gen {α : Type u_1} {r : α → α → Prop} : transitive (trans_gen r) :=
fun (a b c : α) => trans
theorem trans_gen_idem {α : Type u_1} {r : α → α → Prop} : trans_gen (trans_gen r) = trans_gen r :=
trans_gen_eq_self transitive_trans_gen
theorem trans_gen_lift {α : Type u_1} {β : Type u_2} {r : α → α → Prop} {p : β → β → Prop} {a : α}
{b : α} (f : α → β) (h : ∀ (a b : α), r a b → p (f a) (f b)) (hab : trans_gen r a b) :
trans_gen p (f a) (f b) :=
sorry
theorem trans_gen_lift' {α : Type u_1} {β : Type u_2} {r : α → α → Prop} {p : β → β → Prop} {a : α}
{b : α} (f : α → β) (h : ∀ (a b : α), r a b → trans_gen p (f a) (f b)) (hab : trans_gen r a b) :
trans_gen p (f a) (f b) :=
eq.mpr (id (Eq.refl (trans_gen p (f a) (f b))))
(eq.mp (congr_fun (congr_fun trans_gen_idem (f a)) (f b)) (trans_gen_lift f h hab))
theorem trans_gen_closed {α : Type u_1} {r : α → α → Prop} {a : α} {b : α} {p : α → α → Prop} :
(∀ (a b : α), r a b → trans_gen p a b) → trans_gen r a b → trans_gen p a b :=
trans_gen_lift' id
end trans_gen
theorem refl_trans_gen_iff_eq {α : Type u_1} {r : α → α → Prop} {a : α} {b : α}
(h : ∀ (b : α), ¬r a b) : refl_trans_gen r a b ↔ b = a :=
sorry
theorem refl_trans_gen_iff_eq_or_trans_gen {α : Type u_1} {r : α → α → Prop} {a : α} {b : α} :
refl_trans_gen r a b ↔ b = a ∨ trans_gen r a b :=
sorry
theorem refl_trans_gen_lift {α : Type u_1} {β : Type u_2} {r : α → α → Prop} {p : β → β → Prop}
{a : α} {b : α} (f : α → β) (h : ∀ (a b : α), r a b → p (f a) (f b))
(hab : refl_trans_gen r a b) : refl_trans_gen p (f a) (f b) :=
refl_trans_gen.trans_induction_on hab (fun (a : α) => refl_trans_gen.refl)
(fun (a b : α) => refl_trans_gen.single ∘ h a b)
fun (a b c : α) (_x : refl_trans_gen r a b) (_x : refl_trans_gen r b c) => refl_trans_gen.trans
theorem refl_trans_gen_mono {α : Type u_1} {r : α → α → Prop} {a : α} {b : α} {p : α → α → Prop} :
(∀ (a b : α), r a b → p a b) → refl_trans_gen r a b → refl_trans_gen p a b :=
refl_trans_gen_lift id
theorem refl_trans_gen_eq_self {α : Type u_1} {r : α → α → Prop} (refl : reflexive r)
(trans : transitive r) : refl_trans_gen r = r :=
sorry
theorem reflexive_refl_trans_gen {α : Type u_1} {r : α → α → Prop} : reflexive (refl_trans_gen r) :=
fun (a : α) => refl_trans_gen.refl
theorem transitive_refl_trans_gen {α : Type u_1} {r : α → α → Prop} :
transitive (refl_trans_gen r) :=
fun (a b c : α) => refl_trans_gen.trans
theorem refl_trans_gen_idem {α : Type u_1} {r : α → α → Prop} :
refl_trans_gen (refl_trans_gen r) = refl_trans_gen r :=
refl_trans_gen_eq_self reflexive_refl_trans_gen transitive_refl_trans_gen
theorem refl_trans_gen_lift' {α : Type u_1} {β : Type u_2} {r : α → α → Prop} {p : β → β → Prop}
{a : α} {b : α} (f : α → β) (h : ∀ (a b : α), r a b → refl_trans_gen p (f a) (f b))
(hab : refl_trans_gen r a b) : refl_trans_gen p (f a) (f b) :=
eq.mpr (id (Eq.refl (refl_trans_gen p (f a) (f b))))
(eq.mp (congr_fun (congr_fun refl_trans_gen_idem (f a)) (f b)) (refl_trans_gen_lift f h hab))
theorem refl_trans_gen_closed {α : Type u_1} {r : α → α → Prop} {a : α} {b : α} {p : α → α → Prop} :
(∀ (a b : α), r a b → refl_trans_gen p a b) → refl_trans_gen r a b → refl_trans_gen p a b :=
refl_trans_gen_lift' id
/--
The join of a relation on a single type is a new relation for which
pairs of terms are related if there is a third term they are both
related to. For example, if `r` is a relation representing rewrites
in a term rewriting system, then *confluence* is the property that if
`a` rewrites to both `b` and `c`, then `join r` relates `b` and `c`
(see `relation.church_rosser`).
-/
def join {α : Type u_1} (r : α → α → Prop) : α → α → Prop :=
fun (a b : α) => ∃ (c : α), r a c ∧ r b c
theorem church_rosser {α : Type u_1} {r : α → α → Prop} {a : α} {b : α} {c : α}
(h : ∀ (a b c : α), r a b → r a c → ∃ (d : α), refl_gen r b d ∧ refl_trans_gen r c d)
(hab : refl_trans_gen r a b) (hac : refl_trans_gen r a c) : join (refl_trans_gen r) b c :=
sorry
theorem join_of_single {α : Type u_1} {r : α → α → Prop} {a : α} {b : α} (h : reflexive r)
(hab : r a b) : join r a b :=
Exists.intro b { left := hab, right := h b }
theorem symmetric_join {α : Type u_1} {r : α → α → Prop} : symmetric (join r) := sorry
theorem reflexive_join {α : Type u_1} {r : α → α → Prop} (h : reflexive r) : reflexive (join r) :=
fun (a : α) => Exists.intro a { left := h a, right := h a }
theorem transitive_join {α : Type u_1} {r : α → α → Prop} (ht : transitive r)
(h : ∀ (a b c : α), r a b → r a c → join r b c) : transitive (join r) :=
sorry
theorem equivalence_join {α : Type u_1} {r : α → α → Prop} (hr : reflexive r) (ht : transitive r)
(h : ∀ (a b c : α), r a b → r a c → join r b c) : equivalence (join r) :=
{ left := reflexive_join hr, right := { left := symmetric_join, right := transitive_join ht h } }
theorem equivalence_join_refl_trans_gen {α : Type u_1} {r : α → α → Prop}
(h : ∀ (a b c : α), r a b → r a c → ∃ (d : α), refl_gen r b d ∧ refl_trans_gen r c d) :
equivalence (join (refl_trans_gen r)) :=
equivalence_join reflexive_refl_trans_gen transitive_refl_trans_gen
fun (a b c : α) => church_rosser h
theorem join_of_equivalence {α : Type u_1} {r : α → α → Prop} {a : α} {b : α} {r' : α → α → Prop}
(hr : equivalence r) (h : ∀ (a b : α), r' a b → r a b) : join r' a b → r a b :=
sorry
theorem refl_trans_gen_of_transitive_reflexive {α : Type u_1} {r : α → α → Prop} {a : α} {b : α}
{r' : α → α → Prop} (hr : reflexive r) (ht : transitive r) (h : ∀ (a b : α), r' a b → r a b)
(h' : refl_trans_gen r' a b) : r a b :=
refl_trans_gen.drec (hr a)
(fun {b c : α} (hab : refl_trans_gen r' a b) (hbc : r' b c) (ih : r a b) => ht ih (h b c hbc))
h'
theorem refl_trans_gen_of_equivalence {α : Type u_1} {r : α → α → Prop} {a : α} {b : α}
{r' : α → α → Prop} (hr : equivalence r) :
(∀ (a b : α), r' a b → r a b) → refl_trans_gen r' a b → r a b :=
refl_trans_gen_of_transitive_reflexive (and.left hr) (and.right (and.right hr))
theorem eqv_gen_iff_of_equivalence {α : Type u_1} {r : α → α → Prop} {a : α} {b : α}
(h : equivalence r) : eqv_gen r a b ↔ r a b :=
sorry
theorem eqv_gen_mono {α : Type u_1} {a : α} {b : α} {r : α → α → Prop} {p : α → α → Prop}
(hrp : ∀ (a b : α), r a b → p a b) (h : eqv_gen r a b) : eqv_gen p a b :=
sorry
end Mathlib |
3936b583343c9ea42346782d36547b748d847480 | a7eef317ddec01b9fc6cfbb876fe7ac00f205ac7 | /src/group_theory/subgroup.lean | 73ba1a31b2a54d3508a2b844b455c918f0f7814a | [
"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 | 38,774 | lean | /-
Copyright (c) 2020 Kexing Ying. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kexing Ying
-/
import group_theory.submonoid
/-!
# Subgroups
This file defines multiplicative and additive subgroups as an extension of submonoids, in a bundled
form (unbundled subgroups are in `deprecated/subgroups.lean`).
We prove subgroups of a group form a complete lattice, and results about images and preimages of
subgroups under group homomorphisms. The bundled subgroups use bundled monoid homomorphisms.
There are also theorems about the subgroups generated by an element or a subset of a group,
defined both inductively and as the infimum of the set of subgroups containing a given
element/subset.
Special thanks goes to Amelia Livingston and Yury Kudryashov for their help and inspiration.
## Main definitions
Notation used here:
- `G N` are groups
- `A` is an add_group
- `H K` are subgroups of `G` or add_subgroups of `A`
- `x` is an element of type `G` or type `A`
- `f g : N →* G` are group homomorphisms
- `s k` are sets of elements of type `G`
Definitions in the file:
* `subgroup G` : the type of subgroups of a group `G`
* `add_subgroup A` : the type of subgroups of an additive group `A`
* `complete_lattice (subgroup G)` : the subgroups of `G` form a complete lattice
* `closure k` : the minimal subgroup that includes the set `k`
* `subtype` : the natural group homomorphism from a subgroup of group `G` to `G`
* `gi` : `closure` forms a Galois insertion with the coercion to set
* `comap H f` : the preimage of a subgroup `H` along the group homomorphism `f` is also a subgroup
* `map f H` : the image of a subgroup `H` along the group homomorphism `f` is also a subgroup
* `prod H K` : the product of subgroups `H`, `K` of groups `G`, `N` respectively, `H × K` is a
subgroup of `G × N`
* `monoid_hom.range f` : the range of the group homomorphism `f` is a subgroup
* `monoid_hom.ker f` : the kernel of a group homomorphism `f` is the subgroup of elements `x : G` such that
`f x = 1`
* `monoid_hom.eq_locus f g` : given group homomorphisms `f`, `g`, the elements of `G` such that `f x = g x`
form a subgroup of `G`
## Implementation notes
Subgroup inclusion is denoted `≤` rather than `⊆`, although `∈` is defined as
membership of a subgroup's underlying set.
## Tags
subgroup, subgroups
-/
open_locale big_operators
variables {G : Type*} [group G]
variables {A : Type*} [add_group A]
set_option old_structure_cmd true
/-- A subgroup of a group `G` is a subset containing 1, closed under multiplication
and closed under multiplicative inverse. -/
structure subgroup (G : Type*) [group G] extends submonoid G :=
(inv_mem' {x} : x ∈ carrier → x⁻¹ ∈ carrier)
/-- An additive subgroup of an additive group `G` is a subset containing 0, closed
under addition and additive inverse. -/
structure add_subgroup (G : Type*) [add_group G] extends add_submonoid G:=
(neg_mem' {x} : x ∈ carrier → -x ∈ carrier)
attribute [to_additive add_subgroup] subgroup
attribute [to_additive add_subgroup.to_add_submonoid] subgroup.to_submonoid
/-- Reinterpret a `subgroup` as a `submonoid`. -/
add_decl_doc subgroup.to_submonoid
/-- Reinterpret an `add_subgroup` as an `add_submonoid`. -/
add_decl_doc add_subgroup.to_add_submonoid
/-- Map from subgroups of group `G` to `add_subgroup`s of `additive G`. -/
def subgroup.to_add_subgroup {G : Type*} [group G] (H : subgroup G) :
add_subgroup (additive G) :=
{ neg_mem' := H.inv_mem',
.. submonoid.to_add_submonoid H.to_submonoid}
/-- Map from `add_subgroup`s of `additive G` to subgroups of `G`. -/
def subgroup.of_add_subgroup {G : Type*} [group G] (H : add_subgroup (additive G)) :
subgroup G :=
{ inv_mem' := H.neg_mem',
.. submonoid.of_add_submonoid H.to_add_submonoid}
/-- Map from `add_subgroup`s of `add_group G` to subgroups of `multiplicative G`. -/
def add_subgroup.to_subgroup {G : Type*} [add_group G] (H : add_subgroup G) :
subgroup (multiplicative G) :=
{ inv_mem' := H.neg_mem',
.. add_submonoid.to_submonoid H.to_add_submonoid}
/-- Map from subgroups of `multiplicative G` to `add_subgroup`s of `add_group G`. -/
def add_subgroup.of_subgroup {G : Type*} [add_group G] (H : subgroup (multiplicative G)) :
add_subgroup G :=
{ neg_mem' := H.inv_mem',
.. add_submonoid.of_submonoid H.to_submonoid }
/-- Subgroups of group `G` are isomorphic to additive subgroups of `additive G`. -/
def subgroup.add_subgroup_equiv (G : Type*) [group G] :
subgroup G ≃ add_subgroup (additive G) :=
{ to_fun := subgroup.to_add_subgroup,
inv_fun := subgroup.of_add_subgroup,
left_inv := λ x, by cases x; refl,
right_inv := λ x, by cases x; refl }
namespace subgroup
@[to_additive]
instance : has_coe (subgroup G) (set G) := { coe := subgroup.carrier }
@[simp, to_additive]
lemma coe_to_submonoid (K : subgroup G) : (K.to_submonoid : set G) = K := rfl
@[to_additive]
instance : has_mem G (subgroup G) := ⟨λ m K, m ∈ (K : set G)⟩
@[to_additive]
instance : has_coe_to_sort (subgroup G) := ⟨_, λ G, (G : Type*)⟩
@[simp, norm_cast, to_additive]
lemma mem_coe {K : subgroup G} {g : G} : g ∈ (K : set G) ↔ g ∈ K := iff.rfl
@[simp, norm_cast, to_additive]
lemma coe_coe (K : subgroup G) : ↥(K : set G) = K := rfl
attribute [norm_cast] add_subgroup.mem_coe
attribute [norm_cast] add_subgroup.coe_coe
end subgroup
@[to_additive]
protected lemma subgroup.exists {K : subgroup G} {p : K → Prop} :
(∃ x : K, p x) ↔ ∃ x ∈ K, p ⟨x, ‹x ∈ K›⟩ :=
set_coe.exists
@[to_additive]
protected lemma subgroup.forall {K : subgroup G} {p : K → Prop} :
(∀ x : K, p x) ↔ ∀ x ∈ K, p ⟨x, ‹x ∈ K›⟩ :=
set_coe.forall
namespace subgroup
variables (H K : subgroup G)
/-- Copy of a subgroup with a new `carrier` equal to the old one. Useful to fix definitional
equalities.-/
@[to_additive "Copy of an additive subgroup with a new `carrier` equal to the old one.
Useful to fix definitional equalities"]
protected def copy (K : subgroup G) (s : set G) (hs : s = K) : subgroup G :=
{ carrier := s,
one_mem' := hs.symm ▸ K.one_mem',
mul_mem' := hs.symm ▸ K.mul_mem',
inv_mem' := hs.symm ▸ K.inv_mem' }
/- Two subgroups are equal if the underlying set are the same. -/
@[to_additive "Two `add_group`s are equal if the underlying subsets are equal."]
theorem ext' {H K : subgroup G} (h : (H : set G) = K) : H = K :=
by { cases H, cases K, congr, exact h }
/- Two subgroups are equal if and only if the underlying subsets are equal. -/
@[to_additive "Two `add_subgroup`s are equal if and only if the underlying subsets are equal."]
protected theorem ext'_iff {H K : subgroup G} :
H = K ↔ (H : set G) = K := ⟨λ h, h ▸ rfl, ext'⟩
/-- Two subgroups are equal if they have the same elements. -/
@[ext, to_additive "Two `add_subgroup`s are equal if they have the same elements."]
theorem ext {H K : subgroup G}
(h : ∀ x, x ∈ H ↔ x ∈ K) : H = K := ext' $ set.ext h
attribute [ext] add_subgroup.ext
/-- A subgroup contains the group's 1. -/
@[to_additive "An `add_subgroup` contains the group's 0."]
theorem one_mem : (1 : G) ∈ H := H.one_mem'
/-- A subgroup is closed under multiplication. -/
@[to_additive "An `add_subgroup` is closed under addition."]
theorem mul_mem {x y : G} : x ∈ H → y ∈ H → x * y ∈ H := λ hx hy, H.mul_mem' hx hy
/-- A subgroup is closed under inverse. -/
@[to_additive "An `add_subgroup` is closed under inverse."]
theorem inv_mem {x : G} : x ∈ H → x⁻¹ ∈ H := λ hx, H.inv_mem' hx
@[simp, to_additive] theorem inv_mem_iff {x : G} : x⁻¹ ∈ H ↔ x ∈ H :=
⟨λ h, inv_inv x ▸ H.inv_mem h, H.inv_mem⟩
@[to_additive]
lemma mul_mem_cancel_right {x y : G} (h : x ∈ H) : y * x ∈ H ↔ y ∈ H :=
⟨λ hba, by simpa using H.mul_mem hba (H.inv_mem h), λ hb, H.mul_mem hb h⟩
@[to_additive]
lemma mul_mem_cancel_left {x y : G} (h : x ∈ H) : x * y ∈ H ↔ y ∈ H :=
⟨λ hab, by simpa using H.mul_mem (H.inv_mem h) hab, H.mul_mem h⟩
/-- Product of a list of elements in a subgroup is in the subgroup. -/
@[to_additive "Sum of a list of elements in an `add_subgroup` is in the `add_subgroup`."]
lemma list_prod_mem {l : list G} : (∀ x ∈ l, x ∈ K) → l.prod ∈ K :=
K.to_submonoid.list_prod_mem
/-- Product of a multiset of elements in a subgroup of a `comm_group` is in the subgroup. -/
@[to_additive "Sum of a multiset of elements in an `add_subgroup` of an `add_comm_group`
is in the `add_subgroup`."]
lemma multiset_prod_mem {G} [comm_group G] (K : subgroup G) (g : multiset G) :
(∀ a ∈ g, a ∈ K) → g.prod ∈ K := K.to_submonoid.multiset_prod_mem g
/-- Product of elements of a subgroup of a `comm_group` indexed by a `finset` is in the
subgroup. -/
@[to_additive "Sum of elements in an `add_subgroup` of an `add_comm_group` indexed by a `finset`
is in the `add_subgroup`."]
lemma prod_mem {G : Type*} [comm_group G] (K : subgroup G)
{ι : Type*} {t : finset ι} {f : ι → G} (h : ∀ c ∈ t, f c ∈ K) :
∏ c in t, f c ∈ K :=
K.to_submonoid.prod_mem h
lemma pow_mem {x : G} (hx : x ∈ K) : ∀ n : ℕ, x ^ n ∈ K := K.to_submonoid.pow_mem hx
lemma gpow_mem {x : G} (hx : x ∈ K) : ∀ n : ℤ, x ^ n ∈ K
| (int.of_nat n) := pow_mem _ hx n
| -[1+ n] := K.inv_mem $ K.pow_mem hx n.succ
/-- Construct a subgroup from a nonempty set that is closed under division. -/
@[to_additive "Construct a subgroup from a nonempty set that is closed under subtraction"]
def of_div (s : set G) (hsn : s.nonempty) (hs : ∀ x y ∈ s, x * y⁻¹ ∈ s) : subgroup G :=
have one_mem : (1 : G) ∈ s, from let ⟨x, hx⟩ := hsn in by simpa using hs x x hx hx,
have inv_mem : ∀ x, x ∈ s → x⁻¹ ∈ s, from λ x hx, by simpa using hs 1 x one_mem hx,
{ carrier := s,
one_mem' := one_mem,
inv_mem' := inv_mem,
mul_mem' := λ x y hx hy, by simpa using hs x y⁻¹ hx (inv_mem y hy) }
/-- A subgroup of a group inherits a multiplication. -/
@[to_additive "An `add_subgroup` of an `add_group` inherits an addition."]
instance has_mul : has_mul H := H.to_submonoid.has_mul
/-- A subgroup of a group inherits a 1. -/
@[to_additive "An `add_subgroup` of an `add_group` inherits a zero."]
instance has_one : has_one H := H.to_submonoid.has_one
/-- A subgroup of a group inherits an inverse. -/
@[to_additive "A `add_subgroup` of a `add_group` inherits an inverse."]
instance has_inv : has_inv H := ⟨λ a, ⟨a⁻¹, H.inv_mem a.2⟩⟩
@[simp, norm_cast, to_additive] lemma coe_mul (x y : H) : (↑(x * y) : G) = ↑x * ↑y := rfl
@[simp, norm_cast, to_additive] lemma coe_one : ((1 : H) : G) = 1 := rfl
@[simp, norm_cast, to_additive] lemma coe_inv (x : H) : ↑(x⁻¹ : H) = (x⁻¹ : G) := rfl
@[simp, norm_cast, to_additive] lemma coe_mk (x : G) (hx : x ∈ H) : ((⟨x, hx⟩ : H) : G) = x := rfl
attribute [norm_cast] add_subgroup.coe_add add_subgroup.coe_zero
add_subgroup.coe_neg add_subgroup.coe_mk
/-- A subgroup of a group inherits a group structure. -/
@[to_additive to_add_group "An `add_subgroup` of an `add_group` inherits an `add_group` structure."]
instance to_group {G : Type*} [group G] (H : subgroup G) : group H :=
{ inv := has_inv.inv,
mul_left_inv := λ x, subtype.eq $ mul_left_inv x,
.. H.to_submonoid.to_monoid }
/-- A subgroup of a `comm_group` is a `comm_group`. -/
@[to_additive to_add_comm_group "An `add_subgroup` of an `add_comm_group` is an `add_comm_group`."]
instance to_comm_group {G : Type*} [comm_group G] (H : subgroup G) : comm_group H :=
{ mul_comm := λ _ _, subtype.eq $ mul_comm _ _, .. H.to_group}
/-- The natural group hom from a subgroup of group `G` to `G`. -/
@[to_additive "The natural group hom from an `add_subgroup` of `add_group` `G` to `G`."]
def subtype : H →* G := ⟨coe, rfl, λ _ _, rfl⟩
@[simp, to_additive] theorem coe_subtype : ⇑H.subtype = coe := rfl
@[simp, norm_cast] lemma coe_pow (x : H) (n : ℕ) : ((x ^ n : H) : G) = x ^ n :=
coe_subtype H ▸ monoid_hom.map_pow _ _ _
@[simp, norm_cast] lemma coe_gpow (x : H) (n : ℤ) : ((x ^ n : H) : G) = x ^ n :=
coe_subtype H ▸ monoid_hom.map_gpow _ _ _
@[to_additive]
instance : has_le (subgroup G) := ⟨λ H K, ∀ ⦃x⦄, x ∈ H → x ∈ K⟩
@[to_additive]
lemma le_def {H K : subgroup G} : H ≤ K ↔ ∀ ⦃x : G⦄, x ∈ H → x ∈ K := iff.rfl
@[simp, to_additive]
lemma coe_subset_coe {H K : subgroup G} : (H : set G) ⊆ K ↔ H ≤ K := iff.rfl
@[to_additive]
instance : partial_order (subgroup G) :=
{ le := (≤),
.. partial_order.lift (coe : subgroup G → set G) (λ a b, ext') }
/-- The subgroup `G` of the group `G`. -/
@[to_additive "The `add_subgroup G` of the `add_group G`."]
instance : has_top (subgroup G) :=
⟨{ inv_mem' := λ _ _, set.mem_univ _ , .. (⊤ : submonoid G) }⟩
/-- The trivial subgroup `{1}` of an group `G`. -/
@[to_additive "The trivial `add_subgroup` `{0}` of an `add_group` `G`."]
instance : has_bot (subgroup G) :=
⟨{ inv_mem' := λ _, by simp *, .. (⊥ : submonoid G) }⟩
@[to_additive]
instance : inhabited (subgroup G) := ⟨⊥⟩
@[simp, to_additive] lemma mem_bot {x : G} : x ∈ (⊥ : subgroup G) ↔ x = 1 := set.mem_singleton_iff
@[simp, to_additive] lemma mem_top (x : G) : x ∈ (⊤ : subgroup G) := set.mem_univ x
@[simp, to_additive] lemma coe_top : ((⊤ : subgroup G) : set G) = set.univ := rfl
@[simp, to_additive] lemma coe_bot : ((⊥ : subgroup G) : set G) = {1} := rfl
/-- The inf of two subgroups is their intersection. -/
@[to_additive "The inf of two `add_subgroups`s is their intersection."]
instance : has_inf (subgroup G) :=
⟨λ H₁ H₂,
{ inv_mem' := λ _ ⟨hx, hx'⟩, ⟨H₁.inv_mem hx, H₂.inv_mem hx'⟩,
.. H₁.to_submonoid ⊓ H₂.to_submonoid }⟩
@[simp, to_additive]
lemma coe_inf (p p' : subgroup G) : ((p ⊓ p' : subgroup G) : set G) = p ∩ p' := rfl
@[simp, to_additive]
lemma mem_inf {p p' : subgroup G} {x : G} : x ∈ p ⊓ p' ↔ x ∈ p ∧ x ∈ p' := iff.rfl
@[to_additive]
instance : has_Inf (subgroup G) :=
⟨λ s,
{ inv_mem' := λ x hx, set.mem_bInter $ λ i h, i.inv_mem (by apply set.mem_bInter_iff.1 hx i h),
.. (⨅ S ∈ s, subgroup.to_submonoid S).copy (⋂ S ∈ s, ↑S) (by simp) }⟩
@[simp, to_additive]
lemma coe_Inf (H : set (subgroup G)) : ((Inf H : subgroup G) : set G) = ⋂ s ∈ H, ↑s := rfl
attribute [norm_cast] coe_Inf add_subgroup.coe_Inf
@[simp, to_additive]
lemma mem_Inf {S : set (subgroup G)} {x : G} : x ∈ Inf S ↔ ∀ p ∈ S, x ∈ p := set.mem_bInter_iff
/-- Subgroups of a group form a complete lattice. -/
@[to_additive "The `add_subgroup`s of an `add_group` form a complete lattice."]
instance : complete_lattice (subgroup G) :=
{ bot := (⊥),
bot_le := λ S x hx, (mem_bot.1 hx).symm ▸ S.one_mem,
top := (⊤),
le_top := λ S x hx, mem_top x,
inf := (⊓),
le_inf := λ a b c ha hb x hx, ⟨ha hx, hb hx⟩,
inf_le_left := λ a b x, and.left,
inf_le_right := λ a b x, and.right,
.. complete_lattice_of_Inf (subgroup G) $ λ s, is_glb.of_image
(λ H K, show (H : set G) ≤ K ↔ H ≤ K, from coe_subset_coe) is_glb_binfi }
/-- The `subgroup` generated by a set. -/
@[to_additive "The `add_subgroup` generated by a set"]
def closure (k : set G) : subgroup G := Inf {K | k ⊆ K}
variable {k : set G}
@[to_additive]
lemma mem_closure {x : G} : x ∈ closure k ↔ ∀ K : subgroup G, k ⊆ K → x ∈ K :=
mem_Inf
/-- The subgroup generated by a set includes the set. -/
@[simp, to_additive "The `add_subgroup` generated by a set includes the set."]
lemma subset_closure : k ⊆ closure k := λ x hx, mem_closure.2 $ λ K hK, hK hx
open set
/-- A subgroup `K` includes `closure k` if and only if it includes `k`. -/
@[simp, to_additive "An additive subgroup `K` includes `closure k` if and only if it includes `k`"]
lemma closure_le : closure k ≤ K ↔ k ⊆ K :=
⟨subset.trans subset_closure, λ h, Inf_le h⟩
@[to_additive]
lemma closure_eq_of_le (h₁ : k ⊆ K) (h₂ : K ≤ closure k) : closure k = K :=
le_antisymm ((closure_le $ K).2 h₁) h₂
/-- An induction principle for closure membership. If `p` holds for `1` and all elements of `k`, and
is preserved under multiplication and inverse, then `p` holds for all elements of the closure
of `k`. -/
@[to_additive "An induction principle for additive closure membership. If `p` holds for `0` and all
elements of `k`, and is preserved under addition and isvers, then `p` holds for all elements
of the additive closure of `k`."]
lemma closure_induction {p : G → Prop} {x} (h : x ∈ closure k)
(Hk : ∀ x ∈ k, p x) (H1 : p 1)
(Hmul : ∀ x y, p x → p y → p (x * y))
(Hinv : ∀ x, p x → p x⁻¹) : p x :=
(@closure_le _ _ ⟨p, H1, Hmul, Hinv⟩ _).2 Hk h
attribute [elab_as_eliminator] subgroup.closure_induction add_subgroup.closure_induction
variable (G)
/-- `closure` forms a Galois insertion with the coercion to set. -/
@[to_additive "`closure` forms a Galois insertion with the coercion to set."]
protected def gi : galois_insertion (@closure G _) coe :=
{ choice := λ s _, closure s,
gc := λ s t, @closure_le _ _ t s,
le_l_u := λ s, subset_closure,
choice_eq := λ s h, rfl }
variable {G}
/-- Subgroup closure of a set is monotone in its argument: if `h ⊆ k`,
then `closure h ≤ closure k`. -/
@[to_additive "Additive subgroup closure of a set is monotone in its argument: if `h ⊆ k`,
then `closure h ≤ closure k`"]
lemma closure_mono ⦃h k : set G⦄ (h' : h ⊆ k) : closure h ≤ closure k :=
(subgroup.gi G).gc.monotone_l h'
/-- Closure of a subgroup `K` equals `K`. -/
@[simp, to_additive "Additive closure of an additive subgroup `K` equals `K`"]
lemma closure_eq : closure (K : set G) = K := (subgroup.gi G).l_u_eq K
@[simp, to_additive] lemma closure_empty : closure (∅ : set G) = ⊥ :=
(subgroup.gi G).gc.l_bot
@[simp, to_additive] lemma closure_univ : closure (univ : set G) = ⊤ :=
@coe_top G _ ▸ closure_eq ⊤
@[to_additive]
lemma closure_union (s t : set G) : closure (s ∪ t) = closure s ⊔ closure t :=
(subgroup.gi G).gc.l_sup
@[to_additive]
lemma closure_Union {ι} (s : ι → set G) : closure (⋃ i, s i) = ⨆ i, closure (s i) :=
(subgroup.gi G).gc.l_supr
/-- The subgroup generated by an element of a group equals the set of integer number powers of
the element. -/
lemma mem_closure_singleton {x y : G} : y ∈ closure ({x} : set G) ↔ ∃ n : ℤ, x ^ n = y :=
begin
refine ⟨λ hy, closure_induction hy _ _ _ _,
λ ⟨n, hn⟩, hn ▸ gpow_mem _ (subset_closure $ mem_singleton x) n⟩,
{ intros y hy,
rw [eq_of_mem_singleton hy],
exact ⟨1, gpow_one x⟩ },
{ exact ⟨0, rfl⟩ },
{ rintros _ _ ⟨n, rfl⟩ ⟨m, rfl⟩,
exact ⟨n + m, gpow_add x n m⟩ },
rintros _ ⟨n, rfl⟩,
exact ⟨-n, gpow_neg x n⟩
end
@[to_additive]
lemma mem_supr_of_directed {ι} [hι : nonempty ι] {K : ι → subgroup G} (hK : directed (≤) K)
{x : G} :
x ∈ (supr K : subgroup G) ↔ ∃ i, x ∈ K i :=
begin
refine ⟨_, λ ⟨i, hi⟩, (le_def.1 $ le_supr K i) hi⟩,
suffices : x ∈ closure (⋃ i, (K i : set G)) → ∃ i, x ∈ K i,
by simpa only [closure_Union, closure_eq (K _)] using this,
refine (λ hx, closure_induction hx (λ _, mem_Union.1) _ _ _),
{ exact hι.elim (λ i, ⟨i, (K i).one_mem⟩) },
{ rintros x y ⟨i, hi⟩ ⟨j, hj⟩,
rcases hK i j with ⟨k, hki, hkj⟩,
exact ⟨k, (K k).mul_mem (hki hi) (hkj hj)⟩ },
rintros _ ⟨i, hi⟩, exact ⟨i, inv_mem (K i) hi⟩
end
@[to_additive]
lemma mem_Sup_of_directed_on {K : set (subgroup G)} (Kne : K.nonempty)
(hK : directed_on (≤) K) {x : G} :
x ∈ Sup K ↔ ∃ s ∈ K, x ∈ s :=
begin
haveI : nonempty K := Kne.to_subtype,
rw [Sup_eq_supr, supr_subtype', mem_supr_of_directed, subtype.exists],
exact (directed_on_iff_directed _).1 hK
end
variables {N : Type*} [group N] {P : Type*} [group P]
/-- The preimage of a subgroup along a monoid homomorphism is a subgroup. -/
@[to_additive "The preimage of an `add_subgroup` along an `add_monoid` homomorphism
is an `add_subgroup`."]
def comap {N : Type*} [group N] (f : G →* N)
(H : subgroup N) : subgroup G :=
{ carrier := (f ⁻¹' H),
inv_mem' := λ a ha,
show f a⁻¹ ∈ H, by rw f.map_inv; exact H.inv_mem ha,
.. H.to_submonoid.comap f }
@[simp, to_additive]
lemma coe_comap (K : subgroup N) (f : G →* N) : (K.comap f : set G) = f ⁻¹' K := rfl
@[simp, to_additive]
lemma mem_comap {K : subgroup N} {f : G →* N} {x : G} : x ∈ K.comap f ↔ f x ∈ K := iff.rfl
@[to_additive]
lemma comap_comap (K : subgroup P) (g : N →* P) (f : G →* N) :
(K.comap g).comap f = K.comap (g.comp f) :=
rfl
/-- The image of a subgroup along a monoid homomorphism is a subgroup. -/
@[to_additive "The image of an `add_subgroup` along an `add_monoid` homomorphism
is an `add_subgroup`."]
def map (f : G →* N) (H : subgroup G) : subgroup N :=
{ carrier := (f '' H),
inv_mem' := by { rintros _ ⟨x, hx, rfl⟩, exact ⟨x⁻¹, H.inv_mem hx, f.map_inv x⟩ },
.. H.to_submonoid.map f }
@[simp, to_additive]
lemma coe_map (f : G →* N) (K : subgroup G) :
(K.map f : set N) = f '' K := rfl
@[simp, to_additive]
lemma mem_map {f : G →* N} {K : subgroup G} {y : N} :
y ∈ K.map f ↔ ∃ x ∈ K, f x = y :=
mem_image_iff_bex
@[to_additive]
lemma map_map (g : N →* P) (f : G →* N) : (K.map f).map g = K.map (g.comp f) :=
ext' $ image_image _ _ _
@[to_additive]
lemma map_le_iff_le_comap {f : G →* N} {K : subgroup G} {H : subgroup N} :
K.map f ≤ H ↔ K ≤ H.comap f :=
image_subset_iff
@[to_additive]
lemma gc_map_comap (f : G →* N) : galois_connection (map f) (comap f) :=
λ _ _, map_le_iff_le_comap
@[to_additive]
lemma map_sup (H K : subgroup G) (f : G →* N) : (H ⊔ K).map f = H.map f ⊔ K.map f :=
(gc_map_comap f).l_sup
@[to_additive]
lemma map_supr {ι : Sort*} (f : G →* N) (s : ι → subgroup G) :
(supr s).map f = ⨆ i, (s i).map f :=
(gc_map_comap f).l_supr
@[to_additive]
lemma comap_inf (H K : subgroup N) (f : G →* N) : (H ⊓ K).comap f = H.comap f ⊓ K.comap f :=
(gc_map_comap f).u_inf
@[to_additive]
lemma comap_infi {ι : Sort*} (f : G →* N) (s : ι → subgroup N) :
(infi s).comap f = ⨅ i, (s i).comap f :=
(gc_map_comap f).u_infi
@[simp, to_additive] lemma map_bot (f : G →* N) : (⊥ : subgroup G).map f = ⊥ :=
(gc_map_comap f).l_bot
@[simp, to_additive] lemma comap_top (f : G →* N) : (⊤ : subgroup N).comap f = ⊤ :=
(gc_map_comap f).u_top
/-- Given `subgroup`s `H`, `K` of groups `G`, `N` respectively, `H × K` as a subgroup of `G × N`. -/
@[to_additive prod "Given `add_subgroup`s `H`, `K` of `add_group`s `A`, `B` respectively, `H × K`
as an `add_subgroup` of `A × B`."]
def prod (H : subgroup G) (K : subgroup N) : subgroup (G × N) :=
{ inv_mem' := λ _ hx, ⟨H.inv_mem' hx.1, K.inv_mem' hx.2⟩,
.. submonoid.prod H.to_submonoid K.to_submonoid}
@[to_additive coe_prod]
lemma coe_prod (H : subgroup G) (K : subgroup N) :
(H.prod K : set (G × N)) = (H : set G).prod (K : set N) := rfl
@[to_additive mem_prod]
lemma mem_prod {H : subgroup G} {K : subgroup N} {p : G × N} :
p ∈ H.prod K ↔ p.1 ∈ H ∧ p.2 ∈ K := iff.rfl
@[to_additive prod_mono]
lemma prod_mono : ((≤) ⇒ (≤) ⇒ (≤)) (@prod G _ N _) (@prod G _ N _) :=
λ s s' hs t t' ht, set.prod_mono hs ht
@[to_additive prod_mono_right]
lemma prod_mono_right (K : subgroup G) : monotone (λ t : subgroup N, K.prod t) :=
prod_mono (le_refl K)
@[to_additive prod_mono_left]
lemma prod_mono_left (H : subgroup N) : monotone (λ K : subgroup G, K.prod H) :=
λ s₁ s₂ hs, prod_mono hs (le_refl H)
@[to_additive prod_top]
lemma prod_top (K : subgroup G) :
K.prod (⊤ : subgroup N) = K.comap (monoid_hom.fst G N) :=
ext $ λ x, by simp [mem_prod, monoid_hom.coe_fst]
@[to_additive top_prod]
lemma top_prod (H : subgroup N) :
(⊤ : subgroup G).prod H = H.comap (monoid_hom.snd G N) :=
ext $ λ x, by simp [mem_prod, monoid_hom.coe_snd]
@[simp, to_additive top_prod_top]
lemma top_prod_top : (⊤ : subgroup G).prod (⊤ : subgroup N) = ⊤ :=
(top_prod _).trans $ comap_top _
@[to_additive] lemma bot_prod_bot : (⊥ : subgroup G).prod (⊥ : subgroup N) = ⊥ :=
ext' $ by simp [coe_prod, prod.one_eq_mk]
/-- Product of subgroups is isomorphic to their product as groups. -/
@[to_additive prod_equiv "Product of additive subgroups is isomorphic to their product
as additive groups"]
def prod_equiv (H : subgroup G) (K : subgroup N) : H.prod K ≃* H × K :=
{ map_mul' := λ x y, rfl, .. equiv.set.prod ↑H ↑K }
/-- A subgroup is normal if whenever `n ∈ H`, then `g * n * g⁻¹ ∈ H` for every `g : G` -/
structure normal : Prop :=
(conj_mem : ∀ n, n ∈ H → ∀ g : G, g * n * g⁻¹ ∈ H)
attribute [class] normal
end subgroup
namespace add_subgroup
/-- An add_subgroup is normal if whenever `n ∈ H`, then `g + n - g ∈ H` for every `g : G` -/
structure normal (H : add_subgroup A) : Prop :=
(conj_mem [] : ∀ n, n ∈ H → ∀ g : A, g + n - g ∈ H)
attribute [to_additive add_subgroup.normal] subgroup.normal
attribute [class] normal
end add_subgroup
namespace subgroup
variables {H K : subgroup G}
@[instance, priority 100, to_additive]
lemma normal_of_comm {G : Type*} [comm_group G] (H : subgroup G) : H.normal :=
⟨by simp [mul_comm, mul_left_comm]⟩
namespace normal
variable nH : H.normal
@[to_additive] lemma mem_comm {a b : G} (h : a * b ∈ H) : b * a ∈ H :=
have a⁻¹ * (a * b) * a⁻¹⁻¹ ∈ H, from nH.conj_mem (a * b) h a⁻¹, by simpa
@[to_additive] lemma mem_comm_iff {a b : G} : a * b ∈ H ↔ b * a ∈ H :=
⟨nH.mem_comm, nH.mem_comm⟩
end normal
@[instance, priority 100, to_additive]
lemma bot_normal : normal (⊥ : subgroup G) := ⟨by simp⟩
variable (G)
/-- The center of a group `G` is the set of elements that commute with everything in `G` -/
@[to_additive "The center of a group `G` is the set of elements that commute with everything in `G`"]
def center : subgroup G :=
{ carrier := {z | ∀ g, g * z = z * g},
one_mem' := by simp,
mul_mem' := λ a b (ha : ∀ g, g * a = a * g) (hb : ∀ g, g * b = b * g) g,
by assoc_rw [ha, hb g],
inv_mem' := λ a (ha : ∀ g, g * a = a * g) g,
by rw [← inv_inj', mul_inv_rev, inv_inv, ← ha, mul_inv_rev, inv_inv] }
variable {G}
@[to_additive] lemma mem_center_iff {z : G} : z ∈ center G ↔ ∀ g, g * z = z * g := iff.rfl
@[instance, priority 100, to_additive]
lemma center_normal : (center G).normal :=
⟨begin
assume n hn g h,
assoc_rw [hn (h * g), hn g],
simp
end⟩
variables {G} (H)
/-- The `normalizer` of `H` is the smallest subgroup of `G` inside which `H` is normal. -/
@[to_additive "The `normalizer` of `H` is the smallest subgroup of `G` inside which `H` is normal."]
def normalizer : subgroup G :=
{ carrier := {g : G | ∀ n, n ∈ H ↔ g * n * g⁻¹ ∈ H},
one_mem' := by simp,
mul_mem' := λ a b (ha : ∀ n, n ∈ H ↔ a * n * a⁻¹ ∈ H) (hb : ∀ n, n ∈ H ↔ b * n * b⁻¹ ∈ H) n,
by { rw [hb, ha], simp [mul_assoc] },
inv_mem' := λ a (ha : ∀ n, n ∈ H ↔ a * n * a⁻¹ ∈ H) n,
by { rw [ha (a⁻¹ * n * a⁻¹⁻¹)], simp [mul_assoc] } }
variable {H}
@[to_additive] lemma mem_normalizer_iff {g : G} :
g ∈ normalizer H ↔ ∀ n, n ∈ H ↔ g * n * g⁻¹ ∈ H := iff.rfl
@[to_additive] lemma le_normalizer : H ≤ normalizer H :=
λ x xH n, by rw [H.mul_mem_cancel_right (H.inv_mem xH), H.mul_mem_cancel_left xH]
@[instance, priority 100, to_additive]
lemma normal_in_normalizer : (H.comap H.normalizer.subtype).normal :=
⟨λ x xH g, by simpa using (g.2 x).1 xH⟩
open_locale classical
@[to_additive] lemma le_normalizer_of_normal (hK : (H.comap K.subtype).normal) (HK : H ≤ K) : K ≤ H.normalizer :=
λ x hx y, ⟨λ yH, hK.conj_mem ⟨y, HK yH⟩ yH ⟨x, hx⟩,
λ yH, by simpa [mem_comap, mul_assoc] using
hK.conj_mem ⟨x * y * x⁻¹, HK yH⟩ yH ⟨x⁻¹, K.inv_mem hx⟩⟩
end subgroup
namespace group
variables {s : set G}
/-- Given an element `a`, `conjugates a` is the set of conjugates. -/
def conjugates (a : G) : set G := {b | is_conj a b}
lemma mem_conjugates_self {a : G} : a ∈ conjugates a := is_conj_refl _
/-- Given a set `s`, `conjugates_of_set s` is the set of all conjugates of
the elements of `s`. -/
def conjugates_of_set (s : set G) : set G := ⋃ a ∈ s, conjugates a
lemma mem_conjugates_of_set_iff {x : G} : x ∈ conjugates_of_set s ↔ ∃ a ∈ s, is_conj a x :=
set.mem_bUnion_iff
theorem subset_conjugates_of_set : s ⊆ conjugates_of_set s :=
λ (x : G) (h : x ∈ s), mem_conjugates_of_set_iff.2 ⟨x, h, is_conj_refl _⟩
theorem conjugates_of_set_mono {s t : set G} (h : s ⊆ t) :
conjugates_of_set s ⊆ conjugates_of_set t :=
set.bUnion_subset_bUnion_left h
lemma conjugates_subset_normal {N : subgroup G} (tn : N.normal) {a : G} (h : a ∈ N) :
conjugates a ⊆ N :=
by { rintros a ⟨c, rfl⟩, exact tn.conj_mem a h c }
theorem conjugates_of_set_subset {s : set G} {N : subgroup G} (hN : N.normal) (h : s ⊆ N) :
conjugates_of_set s ⊆ N :=
set.bUnion_subset (λ x H, conjugates_subset_normal hN (h H))
/-- The set of conjugates of `s` is closed under conjugation. -/
lemma conj_mem_conjugates_of_set {x c : G} :
x ∈ conjugates_of_set s → (c * x * c⁻¹ ∈ conjugates_of_set s) :=
λ H,
begin
rcases (mem_conjugates_of_set_iff.1 H) with ⟨a,h₁,h₂⟩,
exact mem_conjugates_of_set_iff.2 ⟨a, h₁, is_conj_trans h₂ ⟨c,rfl⟩⟩,
end
end group
namespace subgroup
open group
variable {s : set G}
/-- The normal closure of a set `s` is the subgroup closure of all the conjugates of
elements of `s`. It is the smallest normal subgroup containing `s`. -/
def normal_closure (s : set G) : subgroup G := closure (conjugates_of_set s)
theorem conjugates_of_set_subset_normal_closure : conjugates_of_set s ⊆ normal_closure s :=
subset_closure
theorem subset_normal_closure : s ⊆ normal_closure s :=
set.subset.trans subset_conjugates_of_set conjugates_of_set_subset_normal_closure
/-- The normal closure of `s` is a normal subgroup. -/
@[instance] lemma normal_closure_normal : (normal_closure s).normal :=
⟨λ n h g,
begin
refine subgroup.closure_induction h (λ x hx, _) _ (λ x y ihx ihy, _) (λ x ihx, _),
{ exact (conjugates_of_set_subset_normal_closure (conj_mem_conjugates_of_set hx)) },
{ simpa using (normal_closure s).one_mem },
{ rw ← conj_mul,
exact mul_mem _ ihx ihy },
{ rw ← conj_inv,
exact inv_mem _ ihx }
end⟩
/-- The normal closure of `s` is the smallest normal subgroup containing `s`. -/
theorem normal_closure_le_normal {N : subgroup G} (hN : N.normal)
(h : s ⊆ N) : normal_closure s ≤ N :=
begin
assume a w,
refine closure_induction w (λ x hx, _) _ (λ x y ihx ihy, _) (λ x ihx, _),
{ exact (conjugates_of_set_subset hN h hx) },
{ exact subgroup.one_mem _ },
{ exact subgroup.mul_mem _ ihx ihy },
{ exact subgroup.inv_mem _ ihx }
end
lemma normal_closure_subset_iff {N : subgroup G} (hN : N.normal) : s ⊆ N ↔ normal_closure s ≤ N :=
⟨normal_closure_le_normal hN, set.subset.trans (subset_normal_closure)⟩
theorem normal_closure_mono {s t : set G} (h : s ⊆ t) : normal_closure s ≤ normal_closure t :=
normal_closure_le_normal normal_closure_normal (set.subset.trans h subset_normal_closure)
theorem normal_closure_eq_infi : normal_closure s =
⨅ (N : subgroup G) (h : normal N) (hs : s ⊆ N), N :=
le_antisymm
(le_infi (λ N, le_infi (λ hN, le_infi (normal_closure_le_normal hN))))
(infi_le_of_le (normal_closure s) (infi_le_of_le (by apply_instance)
(infi_le_of_le subset_normal_closure (le_refl _))))
end subgroup
namespace add_subgroup
open set
lemma gsmul_mem (H : add_subgroup A) {x : A} (hx : x ∈ H) :
∀ n : ℤ, gsmul n x ∈ H
| (int.of_nat n) := add_submonoid.nsmul_mem H.to_add_submonoid hx n
| -[1+ n] := H.neg_mem' $ H.add_mem hx $ add_submonoid.nsmul_mem H.to_add_submonoid hx n
lemma sub_mem (H : add_subgroup A) {x y : A} (hx : x ∈ H) (hy : y ∈ H) : x - y ∈ H :=
H.add_mem hx (H.neg_mem hy)
/-- The `add_subgroup` generated by an element of an `add_group` equals the set of
natural number multiples of the element. -/
lemma mem_closure_singleton {x y : A} :
y ∈ closure ({x} : set A) ↔ ∃ n : ℤ, gsmul n x = y :=
begin
refine ⟨λ hy, closure_induction hy _ _ _ _,
λ ⟨n, hn⟩, hn ▸ gsmul_mem _ (subset_closure $ mem_singleton x) n⟩,
{ intros y hy,
rw [eq_of_mem_singleton hy],
exact ⟨1, one_gsmul x⟩ },
{ exact ⟨0, rfl⟩ },
{ rintros _ _ ⟨n, rfl⟩ ⟨m, rfl⟩,
exact ⟨n + m, add_gsmul x n m⟩ },
{ rintros _ ⟨n, rfl⟩,
refine ⟨-n, neg_gsmul x n⟩ }
end
variable (H : add_subgroup A)
@[simp] lemma coe_smul (x : H) (n : ℕ) : ((nsmul n x : H) : A) = nsmul n x :=
coe_subtype H ▸ add_monoid_hom.map_nsmul _ _ _
@[simp] lemma coe_gsmul (x : H) (n : ℤ) : ((n •ℤ x : H) : A) = n •ℤ x :=
coe_subtype H ▸ add_monoid_hom.map_gsmul _ _ _
attribute [to_additive add_subgroup.coe_smul] subgroup.coe_pow
attribute [to_additive add_subgroup.coe_gsmul] subgroup.coe_gpow
end add_subgroup
namespace monoid_hom
variables {N : Type*} {P : Type*} [group N] [group P] (K : subgroup G)
open subgroup
/-- The range of a monoid homomorphism from a group is a subgroup. -/
@[to_additive "The range of an `add_monoid_hom` from an `add_group` is an `add_subgroup`."]
def range (f : G →* N) : subgroup N :=
subgroup.copy ((⊤ : subgroup G).map f) (set.range f) (by simp [set.ext_iff])
@[simp, to_additive] lemma coe_range (f : G →* N) :
(f.range : set N) = set.range f := rfl
@[simp, to_additive] lemma mem_range {f : G →* N} {y : N} :
y ∈ f.range ↔ ∃ x, f x = y :=
iff.rfl
@[to_additive] lemma range_eq_map (f : G →* N) : f.range = (⊤ : subgroup G).map f :=
by ext; simp
@[to_additive]
lemma map_range (g : N →* P) (f : G →* N) : f.range.map g = (g.comp f).range :=
by rw [range_eq_map, range_eq_map]; exact (⊤ : subgroup G).map_map g f
@[to_additive]
lemma range_top_iff_surjective {N} [group N] {f : G →* N} :
f.range = (⊤ : subgroup N) ↔ function.surjective f :=
subgroup.ext'_iff.trans $ iff.trans (by rw [coe_range, coe_top]) set.range_iff_surjective
/-- The range of a surjective monoid homomorphism is the whole of the codomain. -/
@[to_additive "The range of a surjective `add_monoid` homomorphism is the whole of the codomain."]
lemma range_top_of_surjective {N} [group N] (f : G →* N) (hf : function.surjective f) :
f.range = (⊤ : subgroup N) :=
range_top_iff_surjective.2 hf
/-- The multiplicative kernel of a monoid homomorphism is the subgroup of elements `x : G` such that
`f x = 1` -/
@[to_additive "The additive kernel of an `add_monoid` homomorphism is the `add_subgroup` of elements
such that `f x = 0`"]
def ker (f : G →* N) := (⊥ : subgroup N).comap f
@[to_additive]
lemma mem_ker {f : G →* N} {x : G} : x ∈ f.ker ↔ f x = 1 := subgroup.mem_bot
@[to_additive]
lemma comap_ker (g : N →* P) (f : G →* N) : g.ker.comap f = (g.comp f).ker := rfl
/-- The subgroup of elements `x : G` such that `f x = g x` -/
@[to_additive "The additive subgroup of elements `x : G` such that `f x = g x`"]
def eq_locus (f g : G →* N) : subgroup G :=
{ inv_mem' := λ x (hx : f x = g x), show f x⁻¹ = g x⁻¹, by rw [f.map_inv, g.map_inv, hx],
.. eq_mlocus f g}
/-- If two monoid homomorphisms are equal on a set, then they are equal on its subgroup closure. -/
@[to_additive]
lemma eq_on_closure {f g : G →* N} {s : set G} (h : set.eq_on f g s) :
set.eq_on f g (closure s) :=
show closure s ≤ f.eq_locus g, from (closure_le _).2 h
@[to_additive]
lemma eq_of_eq_on_top {f g : G →* N} (h : set.eq_on f g (⊤ : subgroup G)) :
f = g :=
ext $ λ x, h trivial
@[to_additive]
lemma eq_of_eq_on_dense {s : set G} (hs : closure s = ⊤) {f g : G →* N} (h : s.eq_on f g) :
f = g :=
eq_of_eq_on_top $ hs ▸ eq_on_closure h
@[to_additive]
lemma gclosure_preimage_le (f : G →* N) (s : set N) :
closure (f ⁻¹' s) ≤ (closure s).comap f :=
(closure_le _).2 $ λ x hx, by rw [mem_coe, mem_comap]; exact subset_closure hx
/-- The image under a monoid homomorphism of the subgroup generated by a set equals the subgroup
generated by the image of the set. -/
@[to_additive "The image under an `add_monoid` hom of the `add_subgroup` generated by a set equals
the `add_subgroup` generated by the image of the set."]
lemma map_closure (f : G →* N) (s : set G) :
(closure s).map f = closure (f '' s) :=
le_antisymm
(map_le_iff_le_comap.2 $ le_trans (closure_mono $ set.subset_preimage_image f s)
(gclosure_preimage_le _ _))
((closure_le _).2 $ set.image_subset _ subset_closure)
end monoid_hom
variables {N : Type*} [group N]
@[to_additive]
lemma subgroup.normal.comap {H : subgroup N} (hH : H.normal) (f : G →* N) :
(H.comap f).normal :=
⟨λ _, by simp [subgroup.mem_comap, hH.conj_mem] {contextual := tt}⟩
@[instance, priority 100, to_additive] lemma subgroup.normal_comap {H : subgroup N}
[nH : H.normal] (f : G →* N) : (H.comap f).normal := nH.comap _
@[instance, priority 100, to_additive]
lemma monoid_hom.normal_ker (f : G →* N) : f.ker.normal :=
by rw [monoid_hom.ker]; apply_instance
namespace subgroup
/-- The subgroup generated by an element. -/
def gpowers (g : G) : subgroup G :=
subgroup.copy (gpowers_hom G g).range (set.range ((^) g : ℤ → G)) rfl
@[simp] lemma mem_gpowers (g : G) : g ∈ gpowers g := ⟨1, gpow_one _⟩
lemma gpowers_eq_closure (g : G) : gpowers g = closure {g} :=
by { ext, exact mem_closure_singleton.symm }
end subgroup
namespace add_subgroup
/-- The subgroup generated by an element. -/
def gmultiples (a : A) : add_subgroup A :=
add_subgroup.copy (gmultiples_hom A a).range (set.range ((•ℤ a) : ℤ → A)) rfl
@[simp] lemma mem_gmultiples (a : A) : a ∈ gmultiples a := ⟨1, one_gsmul _⟩
lemma gmultiples_eq_closure (a : A) : gmultiples a = closure {a} :=
by { ext, exact mem_closure_singleton.symm }
attribute [to_additive add_subgroup.gmultiples] subgroup.gpowers
attribute [to_additive add_subgroup.mem_gmultiples] subgroup.mem_gpowers
attribute [to_additive add_subgroup.gmultiples_eq_closure] subgroup.gpowers_eq_closure
end add_subgroup
namespace mul_equiv
variables {H K : subgroup G}
/-- Makes the identity isomorphism from a proof two subgroups of a multiplicative
group are equal. -/
@[to_additive add_subgroup_congr "Makes the identity additive isomorphism from a proof
two subgroups of an additive group are equal."]
def subgroup_congr (h : H = K) : H ≃* K :=
{ map_mul' := λ _ _, rfl, ..equiv.set_congr $ subgroup.ext'_iff.1 h }
end mul_equiv
|
9787a161773f3db382273e487258a2df5786f864 | 7a0854479980a89e813e3c93d127f09a8e2c3a7e | /src/group/level01_extended.lean | 51693b836e13cdf4de8fdd4a8298b447c341850c | [] | no_license | cfbolz/group-theory-game | 020e382df58bf9a510dce38304f27400e4ef0b80 | b5282ce72a2a22e9ba1b48cee432ff3d77496040 | refs/heads/master | 1,668,643,052,237 | 1,594,820,769,000 | 1,594,820,769,000 | 279,899,736 | 0 | 0 | null | 1,594,825,474,000 | 1,594,825,473,000 | null | UTF-8 | Lean | false | false | 4,982 | lean | import group.theorems -- definition of a group and a comm_group
/-
class group (G : Type) extends has_group_notation G :=
(mul_assoc : ∀ (a b c : G), a * b * c = a * (b * c))
(one_mul : ∀ (a : G), 1 * a = a)
(mul_left_inv : ∀ (a : G), a⁻¹ * a = 1)
and `comm_group G` has the extra axiom
`mul_comm : ∀ (x y : G), x * y = y * x`
You access these axioms with `group.mul_assoc`, `group.one_mul` etc.
-/
-- This entire project takes place in the mygroup namespace
namespace mygroup
/- Our goal is to prove the following theorems (in the order
listed) :
`mul_left_cancel : ∀ (a b c : G), a * b = a * c → b = c`
`mul_eq_of_eq_inv_mul {a x y : G} : x = a⁻¹ * y → a * x = y`
`mul_one (a : G) : a * 1 = a`
`mul_right_inv (a : G) : a * a⁻¹ = 1`
`eq_mul_inv_of_mul_eq {a b c : G} (h : a * c = b) : a = b * c⁻¹`
`mul_left_eq_self {a b : G} : a * b = b ↔ a = 1`
`eq_inv_of_mul_eq_one {a b : G} (h : a * b = 1) : a = b⁻¹`
`inv_inv (a : G) : a ⁻¹ ⁻¹ = a`
`inv_eq_of_mul_eq_one {a b : G} (h : a * b = 1) : a⁻¹ = b`
and possibly more to come if we run into stuff we need.
We start with only `mul_assoc`, `one_mul` and `mul_left_inv`.
mul_assoc : ∀ (a b c : G), a * b * c = a * (b * c)
one_mul : ∀ (a : G), 1 * a = a
mul_left_inv : ∀ (a : G), a⁻¹ * a = 1
-/
namespace group
variables {G : Type} [group G]
-- Commented out lemmas are alternative solutions to the ones found in group.theorem while the non-commented out one are new!
/-
lemma mul_left_cancel (a x y : G) (Habac : a * x = a * y) : x = y :=
calc x = 1 * x : by rw one_mul
... = (a⁻¹ * a) * x : by rw mul_left_inv
... = a⁻¹ * (a * x) : by rw mul_assoc
... = a⁻¹ * (a * y) : by rw Habac
... = (a⁻¹ * a) * y : by rw mul_assoc
... = 1 * y : by rw mul_left_inv
... = y : by rw one_mul
@[simp] lemma mul_eq_of_eq_inv_mul {a x y : G} (h : x = a⁻¹ * y) : a * x = y :=
begin
apply mul_left_cancel a⁻¹,
rw [←mul_assoc, mul_left_inv, one_mul, h]
end
@[simp] theorem mul_one (a : G) : a * 1 = a :=
begin
apply mul_left_cancel a⁻¹,
rw [←mul_assoc, mul_left_inv, one_mul]
end
@[simp] theorem mul_right_inv (a : G) : a * a⁻¹ = 1 :=
begin
apply mul_left_cancel a⁻¹,
rw [←mul_assoc, mul_left_inv, mul_one, one_mul]
end
-/
lemma eq_mul_inv_of_mul_eq_right {a b c : G} (h : a * c = b) : a = b * c⁻¹ :=
begin
rw [←h, mul_assoc, mul_right_inv c, mul_one]
end
lemma eq_mul_inv_of_mul_eq_left {a b c : G} (h : a * c = b) : c = a⁻¹ * b :=
begin
rw [←h, ←mul_assoc, mul_left_inv a, one_mul]
end
/-
@[simp] lemma mul_left_eq_self {a b : G} : a * b = b ↔ a = 1 :=
begin
split,
intro h,
from calc a = b * b⁻¹ : by apply eq_mul_inv_of_mul_eq_right h
... = 1 : by rw mul_right_inv,
intro h,
rw [h, one_mul]
end
-/
@[simp] lemma mul_right_eq_self {a b : G} : a * b = a ↔ b = 1 :=
begin
split,
intro h,
from calc b = a⁻¹ * a : by apply eq_mul_inv_of_mul_eq_left h
... = 1 : by rw mul_left_inv,
intro h,
rw [h, mul_one]
end
/-
lemma eq_inv_of_mul_eq_one {a b : G} (h : a * b = 1) : a = b⁻¹ :=
begin
rw [←one_mul b⁻¹, ←h, mul_assoc, mul_right_inv b, mul_one]
end
@[simp] lemma inv_inv (a : G) : a ⁻¹ ⁻¹ = a :=
begin
apply mul_left_cancel a⁻¹,
rw [mul_left_inv, mul_right_inv]
end
@[simp] lemma inv_eq_of_mul_eq_one {a b : G} (h : a * b = 1) : a⁻¹ = b :=
begin
apply mul_left_cancel a,
rw [h, mul_right_inv]
end
-/
lemma unique_id {e : G} (h : ∀ x : G, e * x = x) : e = 1 :=
calc e = e * 1 : by rw mul_one
... = 1 : by rw h 1
lemma unique_inv {a b : G} (h : a * b = 1) : b = a⁻¹ :=
begin
apply mul_left_cancel a,
rw [h, mul_right_inv]
end
lemma mul_right_cancel (a x y : G) (Habac : x * a = y * a) : x = y :=
calc x = x * 1 : by rw mul_one
... = x * (a * a⁻¹) : by rw mul_right_inv
... = x * a * a⁻¹ : by rw mul_assoc
... = y * a * a⁻¹ : by rw Habac
... = y * (a * a⁻¹) : by rw mul_assoc
... = y * 1 : by rw mul_right_inv
... = y : by rw mul_one
@[simp] lemma mul_left_cancel_iff (a x y : G) : a * x = a * y ↔ x = y :=
begin
split,
from mul_left_cancel a x y,
intro hxy,
rwa hxy
end
@[simp] lemma mul_right_cancel_iff (a x y : G) : x * a = y * a ↔ x = y :=
begin
split,
from mul_right_cancel a x y,
intro hxy,
rwa hxy
end
@[simp] lemma inv_mul_inv_inv (a b : G) : (a * b)⁻¹ = b⁻¹ * a⁻¹ :=
begin
apply mul_right_cancel (a * b),
rw [mul_left_inv,
←mul_left_cancel_iff b,
mul_assoc, ←mul_assoc,
mul_right_inv,
one_mul, mul_one,
←mul_assoc, mul_left_inv, one_mul]
end
example (y z : G) (h : ∀ x : G, x * x = 1) : y * z = z * y :=
begin
replace h : ∀ x : G, x = x⁻¹ :=
by {intro x, apply mul_left_cancel x, rw [h x, mul_right_inv]},
suffices : z * y = z⁻¹ * y⁻¹,
rw [this, h (y * z)], apply inv_mul_inv_inv,
conv {to_lhs, rw [h z, h y]}
end
end group
end mygroup |
530b4dcf7380232e39a93b233e62d1f2a67cda3e | 947fa6c38e48771ae886239b4edce6db6e18d0fb | /src/data/fin/basic.lean | 69ba83256b4af0e94dc8fede1a6f0de98a869b1a | [
"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 | 65,007 | lean | /-
Copyright (c) 2017 Robert Y. Lewis. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Robert Y. Lewis, Keeley Hoek
-/
import tactic.apply_fun
import data.nat.cast
import order.rel_iso
import tactic.localized
/-!
# The finite type with `n` elements
`fin n` is the type whose elements are natural numbers smaller than `n`.
This file expands on the development in the core library.
## Main definitions
### Induction principles
* `fin_zero_elim` : Elimination principle for the empty set `fin 0`, generalizes `fin.elim0`.
* `fin.succ_rec` : Define `C n i` by induction on `i : fin n` interpreted
as `(0 : fin (n - i)).succ.succ…`. This function has two arguments: `H0 n` defines
`0`-th element `C (n+1) 0` of an `(n+1)`-tuple, and `Hs n i` defines `(i+1)`-st element
of `(n+1)`-tuple based on `n`, `i`, and `i`-th element of `n`-tuple.
* `fin.succ_rec_on` : same as `fin.succ_rec` but `i : fin n` is the first argument;
* `fin.induction` : Define `C i` by induction on `i : fin (n + 1)`, separating into the
`nat`-like base cases of `C 0` and `C (i.succ)`.
* `fin.induction_on` : same as `fin.induction` but with `i : fin (n + 1)` as the first argument.
* `fin.cases` : define `f : Π i : fin n.succ, C i` by separately handling the cases `i = 0` and
`i = fin.succ j`, `j : fin n`, defined using `fin.induction`.
* `fin.reverse_induction`: reverse induction on `i : fin (n + 1)`; given `C (fin.last n)` and
`∀ i : fin n, C (fin.succ i) → C (fin.cast_succ i)`, constructs all values `C i` by going down;
* `fin.last_cases`: define `f : Π i, fin (n + 1), C i` by separately handling the cases
`i = fin.last n` and `i = fin.cast_succ j`, a special case of `fin.reverse_induction`;
* `fin.add_cases`: define a function on `fin (m + n)` by separately handling the cases
`fin.cast_add n i` and `fin.nat_add m i`;
* `fin.succ_above_cases`: given `i : fin (n + 1)`, define a function on `fin (n + 1)` by separately
handling the cases `j = i` and `j = fin.succ_above i k`, same as `fin.insert_nth` but marked
as eliminator and works for `Sort*`.
### Order embeddings and an order isomorphism
* `fin.coe_embedding` : coercion to natural numbers as an `order_embedding`;
* `fin.succ_embedding` : `fin.succ` as an `order_embedding`;
* `fin.cast_le h` : embed `fin n` into `fin m`, `h : n ≤ m`;
* `fin.cast eq` : order isomorphism between `fin n` and fin m` provided that `n = m`,
see also `equiv.fin_congr`;
* `fin.cast_add m` : embed `fin n` into `fin (n+m)`;
* `fin.cast_succ` : embed `fin n` into `fin (n+1)`;
* `fin.succ_above p` : embed `fin n` into `fin (n + 1)` with a hole around `p`;
* `fin.add_nat m i` : add `m` on `i` on the right, generalizes `fin.succ`;
* `fin.nat_add n i` adds `n` on `i` on the left;
### Other casts
* `fin.of_nat'`: given a positive number `n` (deduced from `[fact (0 < n)]`), `fin.of_nat' i` is
`i % n` interpreted as an element of `fin n`;
* `fin.cast_lt i h` : embed `i` into a `fin` where `h` proves it belongs into;
* `fin.pred_above (p : fin n) i` : embed `i : fin (n+1)` into `fin n` by subtracting one if `p < i`;
* `fin.cast_pred` : embed `fin (n + 2)` into `fin (n + 1)` by mapping `fin.last (n + 1)` to
`fin.last n`;
* `fin.sub_nat i h` : subtract `m` from `i ≥ m`, generalizes `fin.pred`;
* `fin.clamp n m` : `min n m` as an element of `fin (m + 1)`;
* `fin.div_nat i` : divides `i : fin (m * n)` by `n`;
* `fin.mod_nat i` : takes the mod of `i : fin (m * n)` by `n`;
### Misc definitions
* `fin.last n` : The greatest value of `fin (n+1)`.
-/
universes u v
open fin nat function
/-- Elimination principle for the empty set `fin 0`, dependent version. -/
def fin_zero_elim {α : fin 0 → Sort u} (x : fin 0) : α x := x.elim0
lemma fact.succ.pos {n} : fact (0 < succ n) := ⟨zero_lt_succ _⟩
lemma fact.bit0.pos {n} [h : fact (0 < n)] : fact (0 < bit0 n) :=
⟨nat.zero_lt_bit0 $ ne_of_gt h.1⟩
lemma fact.bit1.pos {n} : fact (0 < bit1 n) :=
⟨nat.zero_lt_bit1 _⟩
lemma fact.pow.pos {p n : ℕ} [h : fact $ 0 < p] : fact (0 < p ^ n) :=
⟨pow_pos h.1 _⟩
localized "attribute [instance] fact.succ.pos" in fin_fact
localized "attribute [instance] fact.bit0.pos" in fin_fact
localized "attribute [instance] fact.bit1.pos" in fin_fact
localized "attribute [instance] fact.pow.pos" in fin_fact
namespace fin
/-- A non-dependent variant of `elim0`. -/
def elim0' {α : Sort*} (x : fin 0) : α := x.elim0
variables {n m : ℕ} {a b : fin n}
instance fin_to_nat (n : ℕ) : has_coe (fin n) nat := ⟨subtype.val⟩
lemma pos_iff_nonempty {n : ℕ} : 0 < n ↔ nonempty (fin n) :=
⟨λ h, ⟨⟨0, h⟩⟩, λ ⟨i⟩, lt_of_le_of_lt (nat.zero_le _) i.2⟩
section coe
/-!
### coercions and constructions
-/
@[simp] protected lemma eta (a : fin n) (h : (a : ℕ) < n) : (⟨(a : ℕ), h⟩ : fin n) = a :=
by cases a; refl
@[ext]
lemma ext {a b : fin n} (h : (a : ℕ) = b) : a = b := eq_of_veq h
lemma ext_iff (a b : fin n) : a = b ↔ (a : ℕ) = b :=
iff.intro (congr_arg _) fin.eq_of_veq
lemma coe_injective {n : ℕ} : injective (coe : fin n → ℕ) := subtype.coe_injective
lemma eq_iff_veq (a b : fin n) : a = b ↔ a.1 = b.1 :=
⟨veq_of_eq, eq_of_veq⟩
lemma ne_iff_vne (a b : fin n) : a ≠ b ↔ a.1 ≠ b.1 :=
⟨vne_of_ne, ne_of_vne⟩
@[simp] lemma mk_eq_subtype_mk (a : ℕ) (h : a < n) : mk a h = ⟨a, h⟩ := rfl
protected lemma mk.inj_iff {n a b : ℕ} {ha : a < n} {hb : b < n} :
(⟨a, ha⟩ : fin n) = ⟨b, hb⟩ ↔ a = b :=
subtype.mk_eq_mk
lemma mk_val {m n : ℕ} (h : m < n) : (⟨m, h⟩ : fin n).val = m := rfl
lemma eq_mk_iff_coe_eq {k : ℕ} {hk : k < n} : a = ⟨k, hk⟩ ↔ (a : ℕ) = k :=
fin.eq_iff_veq a ⟨k, hk⟩
@[simp, norm_cast] lemma coe_mk {m n : ℕ} (h : m < n) : ((⟨m, h⟩ : fin n) : ℕ) = m := rfl
lemma mk_coe (i : fin n) : (⟨i, i.property⟩ : fin n) = i :=
fin.eta _ _
lemma coe_eq_val (a : fin n) : (a : ℕ) = a.val := rfl
@[simp] lemma val_eq_coe (a : fin n) : a.val = a := rfl
/-- Assume `k = l`. If two functions defined on `fin k` and `fin l` are equal on each element,
then they coincide (in the heq sense). -/
protected lemma heq_fun_iff {α : Sort*} {k l : ℕ} (h : k = l) {f : fin k → α} {g : fin l → α} :
f == g ↔ (∀ (i : fin k), f i = g ⟨(i : ℕ), h ▸ i.2⟩) :=
by { induction h, simp [heq_iff_eq, function.funext_iff] }
protected lemma heq_ext_iff {k l : ℕ} (h : k = l) {i : fin k} {j : fin l} :
i == j ↔ (i : ℕ) = (j : ℕ) :=
by { induction h, simp [ext_iff] }
lemma exists_iff {p : fin n → Prop} : (∃ i, p i) ↔ ∃ i h, p ⟨i, h⟩ :=
⟨λ h, exists.elim h (λ ⟨i, hi⟩ hpi, ⟨i, hi, hpi⟩),
λ h, exists.elim h (λ i hi, ⟨⟨i, hi.fst⟩, hi.snd⟩)⟩
lemma forall_iff {p : fin n → Prop} : (∀ i, p i) ↔ ∀ i h, p ⟨i, h⟩ :=
⟨λ h i hi, h ⟨i, hi⟩, λ h ⟨i, hi⟩, h i hi⟩
end coe
section order
/-!
### order
-/
lemma is_lt (i : fin n) : (i : ℕ) < n := i.2
lemma is_le (i : fin (n + 1)) : (i : ℕ) ≤ n := le_of_lt_succ i.is_lt
lemma lt_iff_coe_lt_coe : a < b ↔ (a : ℕ) < b := iff.rfl
lemma le_iff_coe_le_coe : a ≤ b ↔ (a : ℕ) ≤ b := iff.rfl
lemma mk_lt_of_lt_coe {a : ℕ} (h : a < b) : (⟨a, h.trans b.is_lt⟩ : fin n) < b := h
lemma mk_le_of_le_coe {a : ℕ} (h : a ≤ b) : (⟨a, h.trans_lt b.is_lt⟩ : fin n) ≤ b := h
/-- `a < b` as natural numbers if and only if `a < b` in `fin n`. -/
@[norm_cast, simp] lemma coe_fin_lt {n : ℕ} {a b : fin n} : (a : ℕ) < (b : ℕ) ↔ a < b :=
iff.rfl
/-- `a ≤ b` as natural numbers if and only if `a ≤ b` in `fin n`. -/
@[norm_cast, simp] lemma coe_fin_le {n : ℕ} {a b : fin n} : (a : ℕ) ≤ (b : ℕ) ↔ a ≤ b :=
iff.rfl
instance {n : ℕ} : linear_order (fin n) := subtype.linear_order _
instance {n : ℕ} : partial_order (fin n) := subtype.partial_order _
lemma coe_strict_mono : strict_mono (coe : fin n → ℕ) := λ _ _, id
/-- The inclusion map `fin n → ℕ` is a relation embedding. -/
def coe_embedding (n) : (fin n) ↪o ℕ :=
⟨⟨coe, @fin.eq_of_veq _⟩, λ a b, iff.rfl⟩
/-- The ordering on `fin n` is a well order. -/
instance fin.lt.is_well_order (n) : is_well_order (fin n) (<) :=
(coe_embedding n).is_well_order
/-- Use the ordering on `fin n` for checking recursive definitions.
For example, the following definition is not accepted by the termination checker,
unless we declare the `has_well_founded` instance:
```lean
def factorial {n : ℕ} : fin n → ℕ
| ⟨0, _⟩ := 1
| ⟨i + 1, hi⟩ := (i + 1) * factorial ⟨i, i.lt_succ_self.trans hi⟩
```
-/
instance {n : ℕ} : has_well_founded (fin n) :=
⟨_, measure_wf coe⟩
@[simp] lemma coe_zero {n : ℕ} : ((0 : fin (n+1)) : ℕ) = 0 := rfl
attribute [simp] val_zero
@[simp] lemma val_zero' (n) : (0 : fin (n+1)).val = 0 := rfl
@[simp] lemma mk_zero : (⟨0, nat.succ_pos'⟩ : fin (n + 1)) = (0 : fin _) := rfl
@[simp] lemma zero_le (a : fin (n + 1)) : 0 ≤ a := zero_le a.1
lemma zero_lt_one : (0 : fin (n + 2)) < 1 := nat.zero_lt_one
@[simp] lemma not_lt_zero (a : fin n.succ) : ¬a < 0.
lemma pos_iff_ne_zero (a : fin (n+1)) : 0 < a ↔ a ≠ 0 :=
by rw [← coe_fin_lt, coe_zero, pos_iff_ne_zero, ne.def, ne.def, ext_iff, coe_zero]
lemma eq_zero_or_eq_succ {n : ℕ} (i : fin (n+1)) : i = 0 ∨ ∃ j : fin n, i = j.succ :=
begin
rcases i with ⟨_|j, h⟩,
{ left, refl, },
{ right, exact ⟨⟨j, nat.lt_of_succ_lt_succ h⟩, rfl⟩, }
end
/-- The greatest value of `fin (n+1)` -/
def last (n : ℕ) : fin (n+1) := ⟨_, n.lt_succ_self⟩
@[simp, norm_cast] lemma coe_last (n : ℕ) : (last n : ℕ) = n := rfl
lemma last_val (n : ℕ) : (last n).val = n := rfl
theorem le_last (i : fin (n+1)) : i ≤ last n :=
le_of_lt_succ i.is_lt
instance : bounded_order (fin (n + 1)) :=
{ top := last n,
le_top := le_last,
bot := 0,
bot_le := zero_le }
instance : lattice (fin (n + 1)) := linear_order.to_lattice
lemma last_pos : (0 : fin (n + 2)) < last (n + 1) :=
by simp [lt_iff_coe_lt_coe]
lemma eq_last_of_not_lt {i : fin (n+1)} (h : ¬ (i : ℕ) < n) : i = last n :=
le_antisymm (le_last i) (not_lt.1 h)
lemma top_eq_last (n : ℕ) : ⊤ = fin.last n := rfl
lemma bot_eq_zero (n : ℕ) : ⊥ = (0 : fin (n + 1)) := rfl
section
variables {α : Type*} [preorder α]
open set
/-- If `e` is an `order_iso` between `fin n` and `fin m`, then `n = m` and `e` is the identity
map. In this lemma we state that for each `i : fin n` we have `(e i : ℕ) = (i : ℕ)`. -/
@[simp] lemma coe_order_iso_apply (e : fin n ≃o fin m) (i : fin n) : (e i : ℕ) = i :=
begin
rcases i with ⟨i, hi⟩,
rw [subtype.coe_mk],
induction i using nat.strong_induction_on with i h,
refine le_antisymm (forall_lt_iff_le.1 $ λ j hj, _) (forall_lt_iff_le.1 $ λ j hj, _),
{ have := e.symm.lt_iff_lt.2 (mk_lt_of_lt_coe hj),
rw e.symm_apply_apply at this,
convert this,
simpa using h _ this (e.symm _).is_lt },
{ rwa [← h j hj (hj.trans hi), ← lt_iff_coe_lt_coe, e.lt_iff_lt] }
end
instance order_iso_subsingleton : subsingleton (fin n ≃o α) :=
⟨λ e e', by { ext i,
rw [← e.symm.apply_eq_iff_eq, e.symm_apply_apply, ← e'.trans_apply, ext_iff,
coe_order_iso_apply] }⟩
instance order_iso_subsingleton' : subsingleton (α ≃o fin n) :=
order_iso.symm_injective.subsingleton
instance order_iso_unique : unique (fin n ≃o fin n) := unique.mk' _
/-- Two strictly monotone functions from `fin n` are equal provided that their ranges
are equal. -/
lemma strict_mono_unique {f g : fin n → α} (hf : strict_mono f) (hg : strict_mono g)
(h : range f = range g) : f = g :=
have (hf.order_iso f).trans (order_iso.set_congr _ _ h) = hg.order_iso g,
from subsingleton.elim _ _,
congr_arg (function.comp (coe : range g → α)) (funext $ rel_iso.ext_iff.1 this)
/-- Two order embeddings of `fin n` are equal provided that their ranges are equal. -/
lemma order_embedding_eq {f g : fin n ↪o α} (h : range f = range g) : f = g :=
rel_embedding.ext $ funext_iff.1 $ strict_mono_unique f.strict_mono g.strict_mono h
end
end order
section add
/-!
### addition, numerals, and coercion from nat
-/
/-- Given a positive `n`, `fin.of_nat' i` is `i % n` as an element of `fin n`. -/
def of_nat' [h : fact (0 < n)] (i : ℕ) : fin n := ⟨i%n, mod_lt _ h.1⟩
lemma one_val {n : ℕ} : (1 : fin (n+1)).val = 1 % (n+1) := rfl
lemma coe_one' {n : ℕ} : ((1 : fin (n+1)) : ℕ) = 1 % (n+1) := rfl
@[simp] lemma val_one {n : ℕ} : (1 : fin (n+2)).val = 1 := rfl
@[simp] lemma coe_one {n : ℕ} : ((1 : fin (n+2)) : ℕ) = 1 := rfl
@[simp] lemma mk_one : (⟨1, nat.succ_lt_succ (nat.succ_pos n)⟩ : fin (n + 2)) = (1 : fin _) := rfl
instance {n : ℕ} : nontrivial (fin (n + 2)) := ⟨⟨0, 1, dec_trivial⟩⟩
lemma nontrivial_iff_two_le : nontrivial (fin n) ↔ 2 ≤ n :=
by rcases n with _|_|n; simp [fin.nontrivial, not_nontrivial, nat.succ_le_iff]
lemma subsingleton_iff_le_one : subsingleton (fin n) ↔ n ≤ 1 :=
by rcases n with _|_|n; simp [is_empty.subsingleton, unique.subsingleton, not_subsingleton]
section monoid
@[simp] protected lemma add_zero (k : fin (n + 1)) : k + 0 = k :=
by simp [eq_iff_veq, add_def, mod_eq_of_lt (is_lt k)]
@[simp] protected lemma zero_add (k : fin (n + 1)) : (0 : fin (n + 1)) + k = k :=
by simp [eq_iff_veq, add_def, mod_eq_of_lt (is_lt k)]
instance add_comm_monoid (n : ℕ) : add_comm_monoid (fin (n + 1)) :=
{ add := (+),
add_assoc := by simp [eq_iff_veq, add_def, add_assoc],
zero := 0,
zero_add := fin.zero_add,
add_zero := fin.add_zero,
add_comm := by simp [eq_iff_veq, add_def, add_comm] }
instance : add_monoid_with_one (fin (n + 1)) :=
{ one := 1,
nat_cast := fin.of_nat,
nat_cast_zero := rfl,
nat_cast_succ := λ i, eq_of_veq (add_mod _ _ _),
.. fin.add_comm_monoid n }
end monoid
lemma val_add {n : ℕ} : ∀ a b : fin n, (a + b).val = (a.val + b.val) % n
| ⟨_, _⟩ ⟨_, _⟩ := rfl
lemma coe_add {n : ℕ} : ∀ a b : fin n, ((a + b : fin n) : ℕ) = (a + b) % n
| ⟨_, _⟩ ⟨_, _⟩ := rfl
lemma coe_add_eq_ite {n : ℕ} (a b : fin n) :
(↑(a + b) : ℕ) = if n ≤ a + b then a + b - n else a + b :=
by rw [fin.coe_add, nat.add_mod_eq_ite,
nat.mod_eq_of_lt (show ↑a < n, from a.2), nat.mod_eq_of_lt (show ↑b < n, from b.2)]
lemma coe_bit0 {n : ℕ} (k : fin n) : ((bit0 k : fin n) : ℕ) = bit0 (k : ℕ) % n :=
by { cases k, refl }
lemma coe_bit1 {n : ℕ} (k : fin (n + 1)) :
((bit1 k : fin (n + 1)) : ℕ) = bit1 (k : ℕ) % (n + 1) :=
begin
cases n, { cases k with k h, cases k, {show _ % _ = _, simp}, cases h with _ h, cases h },
simp [bit1, fin.coe_bit0, fin.coe_add, fin.coe_one],
end
lemma coe_add_one_of_lt {n : ℕ} {i : fin n.succ} (h : i < last _) :
(↑(i + 1) : ℕ) = i + 1 :=
begin
-- First show that `((1 : fin n.succ) : ℕ) = 1`, because `n.succ` is at least 2.
cases n,
{ cases h },
-- Then just unfold the definitions.
rw [fin.coe_add, fin.coe_one, nat.mod_eq_of_lt (nat.succ_lt_succ _)],
exact h
end
@[simp] lemma last_add_one : ∀ n, last n + 1 = 0
| 0 := subsingleton.elim _ _
| (n + 1) := by { ext, rw [coe_add, coe_zero, coe_last, coe_one, nat.mod_self] }
lemma coe_add_one {n : ℕ} (i : fin (n + 1)) :
((i + 1 : fin (n + 1)) : ℕ) = if i = last _ then 0 else i + 1 :=
begin
rcases (le_last i).eq_or_lt with rfl|h,
{ simp },
{ simpa [h.ne] using coe_add_one_of_lt h }
end
section bit
@[simp] lemma mk_bit0 {m n : ℕ} (h : bit0 m < n) :
(⟨bit0 m, h⟩ : fin n) = (bit0 ⟨m, (nat.le_add_right m m).trans_lt h⟩ : fin _) :=
eq_of_veq (nat.mod_eq_of_lt h).symm
@[simp] lemma mk_bit1 {m n : ℕ} (h : bit1 m < n + 1) :
(⟨bit1 m, h⟩ : fin (n + 1)) = (bit1 ⟨m, (nat.le_add_right m m).trans_lt
((m + m).lt_succ_self.trans h)⟩ : fin _) :=
begin
ext,
simp only [bit1, bit0] at h,
simp only [bit1, bit0, coe_add, coe_one', coe_mk, ←nat.add_mod, nat.mod_eq_of_lt h],
end
end bit
@[simp] lemma val_two {n : ℕ} : (2 : fin (n+3)).val = 2 := rfl
@[simp] lemma coe_two {n : ℕ} : ((2 : fin (n+3)) : ℕ) = 2 := rfl
section of_nat_coe
@[simp]
lemma of_nat_eq_coe (n : ℕ) (a : ℕ) : (of_nat a : fin (n+1)) = a :=
rfl
/-- Converting an in-range number to `fin (n + 1)` produces a result
whose value is the original number. -/
lemma coe_val_of_lt {n : ℕ} {a : ℕ} (h : a < n + 1) :
((a : fin (n + 1)).val) = a :=
begin
rw ←of_nat_eq_coe,
exact nat.mod_eq_of_lt h
end
/-- Converting the value of a `fin (n + 1)` to `fin (n + 1)` results
in the same value. -/
lemma coe_val_eq_self {n : ℕ} (a : fin (n + 1)) : (a.val : fin (n + 1)) = a :=
begin
rw fin.eq_iff_veq,
exact coe_val_of_lt a.property
end
/-- Coercing an in-range number to `fin (n + 1)`, and converting back
to `ℕ`, results in that number. -/
lemma coe_coe_of_lt {n : ℕ} {a : ℕ} (h : a < n + 1) :
((a : fin (n + 1)) : ℕ) = a :=
coe_val_of_lt h
/-- Converting a `fin (n + 1)` to `ℕ` and back results in the same
value. -/
@[simp] lemma coe_coe_eq_self {n : ℕ} (a : fin (n + 1)) : ((a : ℕ) : fin (n + 1)) = a :=
coe_val_eq_self a
lemma coe_nat_eq_last (n) : (n : fin (n + 1)) = fin.last n :=
by { rw [←fin.of_nat_eq_coe, fin.of_nat, fin.last], simp only [nat.mod_eq_of_lt n.lt_succ_self] }
lemma le_coe_last (i : fin (n + 1)) : i ≤ n :=
by { rw fin.coe_nat_eq_last, exact fin.le_last i }
end of_nat_coe
lemma add_one_pos (i : fin (n + 1)) (h : i < fin.last n) : (0 : fin (n + 1)) < i + 1 :=
begin
cases n,
{ exact absurd h (nat.not_lt_zero _) },
{ rw [lt_iff_coe_lt_coe, coe_last, ←add_lt_add_iff_right 1] at h,
rw [lt_iff_coe_lt_coe, coe_add, coe_zero, coe_one, nat.mod_eq_of_lt h],
exact nat.zero_lt_succ _ }
end
lemma one_pos : (0 : fin (n + 2)) < 1 := succ_pos 0
lemma zero_ne_one : (0 : fin (n + 2)) ≠ 1 := ne_of_lt one_pos
@[simp] lemma zero_eq_one_iff : (0 : fin (n + 1)) = 1 ↔ n = 0 :=
begin
split,
{ cases n; intro h,
{ refl },
{ have := zero_ne_one, contradiction } },
{ rintro rfl, refl }
end
@[simp] lemma one_eq_zero_iff : (1 : fin (n + 1)) = 0 ↔ n = 0 :=
by rw [eq_comm, zero_eq_one_iff]
end add
section succ
/-!
### succ and casts into larger fin types
-/
@[simp] lemma coe_succ (j : fin n) : (j.succ : ℕ) = j + 1 :=
by cases j; simp [fin.succ]
@[simp]
lemma succ_pos (a : fin n) : (0 : fin (n + 1)) < a.succ := by simp [lt_iff_coe_lt_coe]
/-- `fin.succ` as an `order_embedding` -/
def succ_embedding (n : ℕ) : fin n ↪o fin (n + 1) :=
order_embedding.of_strict_mono fin.succ $ λ ⟨i, hi⟩ ⟨j, hj⟩ h, succ_lt_succ h
@[simp] lemma coe_succ_embedding : ⇑(succ_embedding n) = fin.succ := rfl
@[simp] lemma succ_le_succ_iff : a.succ ≤ b.succ ↔ a ≤ b :=
(succ_embedding n).le_iff_le
@[simp] lemma succ_lt_succ_iff : a.succ < b.succ ↔ a < b :=
(succ_embedding n).lt_iff_lt
lemma succ_injective (n : ℕ) : injective (@fin.succ n) :=
(succ_embedding n).injective
@[simp] lemma succ_inj {a b : fin n} : a.succ = b.succ ↔ a = b :=
(succ_injective n).eq_iff
lemma succ_ne_zero {n} : ∀ k : fin n, fin.succ k ≠ 0
| ⟨k, hk⟩ heq := nat.succ_ne_zero k $ (ext_iff _ _).1 heq
@[simp] lemma succ_zero_eq_one : fin.succ (0 : fin (n + 1)) = 1 := rfl
@[simp] lemma succ_one_eq_two : fin.succ (1 : fin (n + 2)) = 2 := rfl
@[simp] lemma succ_mk (n i : ℕ) (h : i < n) : fin.succ ⟨i, h⟩ = ⟨i + 1, nat.succ_lt_succ h⟩ :=
rfl
lemma mk_succ_pos (i : ℕ) (h : i < n) : (0 : fin (n + 1)) < ⟨i.succ, add_lt_add_right h 1⟩ :=
by { rw [lt_iff_coe_lt_coe, coe_zero], exact nat.succ_pos i }
lemma one_lt_succ_succ (a : fin n) : (1 : fin (n + 2)) < a.succ.succ :=
begin
cases n,
{ exact fin_zero_elim a },
{ rw [←succ_zero_eq_one, succ_lt_succ_iff], exact succ_pos a }
end
lemma succ_succ_ne_one (a : fin n) : fin.succ (fin.succ a) ≠ 1 := ne_of_gt (one_lt_succ_succ a)
/-- `cast_lt i h` embeds `i` into a `fin` where `h` proves it belongs into. -/
def cast_lt (i : fin m) (h : i.1 < n) : fin n := ⟨i.1, h⟩
@[simp] lemma coe_cast_lt (i : fin m) (h : i.1 < n) : (cast_lt i h : ℕ) = i := rfl
@[simp] lemma cast_lt_mk (i n m : ℕ) (hn : i < n) (hm : i < m) : cast_lt ⟨i, hn⟩ hm = ⟨i, hm⟩ := rfl
/-- `cast_le h i` embeds `i` into a larger `fin` type. -/
def cast_le (h : n ≤ m) : fin n ↪o fin m :=
order_embedding.of_strict_mono (λ a, cast_lt a (lt_of_lt_of_le a.2 h)) $ λ a b h, h
@[simp] lemma coe_cast_le (h : n ≤ m) (i : fin n) : (cast_le h i : ℕ) = i := rfl
@[simp] lemma cast_le_mk (i n m : ℕ) (hn : i < n) (h : n ≤ m) :
cast_le h ⟨i, hn⟩ = ⟨i, lt_of_lt_of_le hn h⟩ := rfl
@[simp] lemma cast_le_zero {n m : ℕ} (h : n.succ ≤ m.succ) :
cast_le h 0 = 0 :=
by simp [eq_iff_veq]
@[simp] lemma range_cast_le {n k : ℕ} (h : n ≤ k) :
set.range (cast_le h) = {i | (i : ℕ) < n} :=
set.ext (λ x, ⟨λ ⟨y, hy⟩, hy ▸ y.2, λ hx, ⟨⟨x, hx⟩, fin.ext rfl⟩⟩)
@[simp] lemma coe_of_injective_cast_le_symm {n k : ℕ} (h : n ≤ k) (i : fin k) (hi) :
((equiv.of_injective _ (cast_le h).injective).symm ⟨i, hi⟩ : ℕ) = i :=
begin
rw ← coe_cast_le,
exact congr_arg coe (equiv.apply_of_injective_symm _ _)
end
@[simp] lemma cast_le_succ {m n : ℕ} (h : (m + 1) ≤ (n + 1)) (i : fin m) :
cast_le h i.succ = (cast_le (nat.succ_le_succ_iff.mp h) i).succ :=
by simp [fin.eq_iff_veq]
@[simp] lemma cast_le_cast_le {k m n} (km : k ≤ m) (mn : m ≤ n) (i : fin k) :
fin.cast_le mn (fin.cast_le km i) = fin.cast_le (km.trans mn) i :=
fin.ext (by simp only [coe_cast_le])
@[simp] lemma cast_le_comp_cast_le {k m n} (km : k ≤ m) (mn : m ≤ n) :
fin.cast_le mn ∘ fin.cast_le km = fin.cast_le (km.trans mn) :=
funext (cast_le_cast_le km mn)
/-- `cast eq i` embeds `i` into a equal `fin` type, see also `equiv.fin_congr`. -/
def cast (eq : n = m) : fin n ≃o fin m :=
{ to_equiv := ⟨cast_le eq.le, cast_le eq.symm.le, λ a, eq_of_veq rfl, λ a, eq_of_veq rfl⟩,
map_rel_iff' := λ a b, iff.rfl }
@[simp] lemma symm_cast (h : n = m) : (cast h).symm = cast h.symm := rfl
/-- While `fin.coe_order_iso_apply` is a more general case of this, we mark this `simp` anyway
as it is eligible for `dsimp`. -/
@[simp]
lemma coe_cast (h : n = m) (i : fin n) : (cast h i : ℕ) = i := rfl
@[simp] lemma cast_zero {n' : ℕ} {h : n + 1 = n' + 1} :
cast h (0 : fin (n + 1)) = 0 :=
ext rfl
@[simp] lemma cast_last {n' : ℕ} {h : n + 1 = n' + 1} :
cast h (last n) = last n' :=
ext (by rw [coe_cast, coe_last, coe_last, nat.succ_injective h])
@[simp] lemma cast_mk (h : n = m) (i : ℕ) (hn : i < n) :
cast h ⟨i, hn⟩ = ⟨i, lt_of_lt_of_le hn h.le⟩ := rfl
@[simp] lemma cast_trans {k : ℕ} (h : n = m) (h' : m = k) {i : fin n} :
cast h' (cast h i) = cast (eq.trans h h') i := rfl
@[simp] lemma cast_refl (h : n = n := rfl) : cast h = order_iso.refl (fin n) :=
by { ext, refl }
lemma cast_le_of_eq {m n : ℕ} (h : m = n) {h' : m ≤ n} :
(cast_le h' : fin m → fin n) = fin.cast h :=
funext (λ _, rfl)
/-- While in many cases `fin.cast` is better than `equiv.cast`/`cast`, sometimes we want to apply
a generic theorem about `cast`. -/
lemma cast_to_equiv (h : n = m) : (cast h).to_equiv = equiv.cast (h ▸ rfl) :=
by { subst h, simp }
/-- While in many cases `fin.cast` is better than `equiv.cast`/`cast`, sometimes we want to apply
a generic theorem about `cast`. -/
lemma cast_eq_cast (h : n = m) : (cast h : fin n → fin m) = _root_.cast (h ▸ rfl) :=
by { subst h, ext, simp }
/-- `cast_add m i` embeds `i : fin n` in `fin (n+m)`. See also `fin.nat_add` and `fin.add_nat`. -/
def cast_add (m) : fin n ↪o fin (n + m) := cast_le $ nat.le_add_right n m
@[simp] lemma coe_cast_add (m : ℕ) (i : fin n) : (cast_add m i : ℕ) = i := rfl
@[simp] lemma cast_add_zero : (cast_add 0 : fin n → fin (n + 0)) = cast rfl := rfl
lemma cast_add_lt {m : ℕ} (n : ℕ) (i : fin m) : (cast_add n i : ℕ) < m := i.2
@[simp] lemma cast_add_mk (m : ℕ) (i : ℕ) (h : i < n) :
cast_add m ⟨i, h⟩ = ⟨i, lt_add_right i n m h⟩ := rfl
@[simp] lemma cast_add_cast_lt (m : ℕ) (i : fin (n + m)) (hi : i.val < n) :
cast_add m (cast_lt i hi) = i :=
ext rfl
@[simp] lemma cast_lt_cast_add (m : ℕ) (i : fin n) :
cast_lt (cast_add m i) (cast_add_lt m i) = i :=
ext rfl
/-- For rewriting in the reverse direction, see `fin.cast_cast_add_left`. -/
lemma cast_add_cast {n n' : ℕ} (m : ℕ) (i : fin n') (h : n' = n) :
cast_add m (fin.cast h i) = fin.cast (congr_arg _ h) (cast_add m i) :=
ext rfl
lemma cast_cast_add_left {n n' m : ℕ} (i : fin n') (h : n' + m = n + m) :
cast h (cast_add m i) = cast_add m (cast (add_right_cancel h) i) :=
ext rfl
@[simp] lemma cast_cast_add_right {n m m' : ℕ} (i : fin n) (h : n + m' = n + m) :
cast h (cast_add m' i) = cast_add m i :=
ext rfl
/-- The cast of the successor is the succesor of the cast. See `fin.succ_cast_eq` for rewriting in
the reverse direction. -/
@[simp] lemma cast_succ_eq {n' : ℕ} (i : fin n) (h : n.succ = n'.succ) :
cast h i.succ = (cast (nat.succ.inj h) i).succ :=
ext $ by simp
lemma succ_cast_eq {n' : ℕ} (i : fin n) (h : n = n') : (cast h i).succ = cast (by rw h) i.succ :=
ext $ by simp
/-- `cast_succ i` embeds `i : fin n` in `fin (n+1)`. -/
def cast_succ : fin n ↪o fin (n + 1) := cast_add 1
@[simp] lemma coe_cast_succ (i : fin n) : (i.cast_succ : ℕ) = i := rfl
@[simp] lemma cast_succ_mk (n i : ℕ) (h : i < n) : cast_succ ⟨i, h⟩ = ⟨i, nat.lt.step h⟩ := rfl
@[simp] lemma cast_cast_succ {n' : ℕ} {h : n + 1 = n' + 1} {i : fin n} :
cast h (cast_succ i) = cast_succ (cast (nat.succ_injective h) i) :=
by { ext, simp only [coe_cast, coe_cast_succ] }
lemma cast_succ_lt_succ (i : fin n) : i.cast_succ < i.succ :=
lt_iff_coe_lt_coe.2 $ by simp only [coe_cast_succ, coe_succ, nat.lt_succ_self]
lemma le_cast_succ_iff {i : fin (n + 1)} {j : fin n} : i ≤ j.cast_succ ↔ i < j.succ :=
by simpa [lt_iff_coe_lt_coe, le_iff_coe_le_coe] using nat.succ_le_succ_iff.symm
lemma cast_succ_lt_iff_succ_le {n : ℕ} {i : fin n} {j : fin (n+1)} :
i.cast_succ < j ↔ i.succ ≤ j :=
by simpa only [fin.lt_iff_coe_lt_coe, fin.le_iff_coe_le_coe, fin.coe_succ, fin.coe_cast_succ]
using nat.lt_iff_add_one_le
@[simp] lemma succ_last (n : ℕ) : (last n).succ = last (n.succ) := rfl
@[simp] lemma succ_eq_last_succ {n : ℕ} (i : fin n.succ) :
i.succ = last (n + 1) ↔ i = last n :=
by rw [← succ_last, (succ_injective _).eq_iff]
@[simp] lemma cast_succ_cast_lt (i : fin (n + 1)) (h : (i : ℕ) < n) : cast_succ (cast_lt i h) = i :=
fin.eq_of_veq rfl
@[simp] lemma cast_lt_cast_succ {n : ℕ} (a : fin n) (h : (a : ℕ) < n) :
cast_lt (cast_succ a) h = a :=
by cases a; refl
@[simp] lemma cast_succ_lt_cast_succ_iff : a.cast_succ < b.cast_succ ↔ a < b :=
(@cast_succ n).lt_iff_lt
lemma cast_succ_injective (n : ℕ) : injective (@fin.cast_succ n) :=
(cast_succ : fin n ↪o _).injective
lemma cast_succ_inj {a b : fin n} : a.cast_succ = b.cast_succ ↔ a = b :=
(cast_succ_injective n).eq_iff
lemma cast_succ_lt_last (a : fin n) : cast_succ a < last n := lt_iff_coe_lt_coe.mpr a.is_lt
@[simp] lemma cast_succ_zero : cast_succ (0 : fin (n + 1)) = 0 := rfl
@[simp] lemma cast_succ_one {n : ℕ} : fin.cast_succ (1 : fin (n + 2)) = 1 := rfl
/-- `cast_succ i` is positive when `i` is positive -/
lemma cast_succ_pos {i : fin (n + 1)} (h : 0 < i) : 0 < cast_succ i :=
by simpa [lt_iff_coe_lt_coe] using h
@[simp] lemma cast_succ_eq_zero_iff (a : fin (n + 1)) : a.cast_succ = 0 ↔ a = 0 :=
subtype.ext_iff.trans $ (subtype.ext_iff.trans $ by exact iff.rfl).symm
lemma cast_succ_ne_zero_iff (a : fin (n + 1)) : a.cast_succ ≠ 0 ↔ a ≠ 0 :=
not_iff_not.mpr $ cast_succ_eq_zero_iff a
lemma cast_succ_fin_succ (n : ℕ) (j : fin n) :
cast_succ (fin.succ j) = fin.succ (cast_succ j) :=
by simp [fin.ext_iff]
@[norm_cast, simp] lemma coe_eq_cast_succ : (a : fin (n + 1)) = a.cast_succ :=
begin
ext,
exact coe_val_of_lt (nat.lt.step a.is_lt),
end
@[simp] lemma coe_succ_eq_succ : a.cast_succ + 1 = a.succ :=
begin
cases n,
{ exact fin_zero_elim a },
{ simp [a.is_lt, eq_iff_veq, add_def, nat.mod_eq_of_lt] }
end
lemma lt_succ : a.cast_succ < a.succ :=
by { rw [cast_succ, lt_iff_coe_lt_coe, coe_cast_add, coe_succ], exact lt_add_one a.val }
@[simp] lemma range_cast_succ {n : ℕ} :
set.range (cast_succ : fin n → fin n.succ) = {i | (i : ℕ) < n} :=
range_cast_le _
@[simp] lemma coe_of_injective_cast_succ_symm {n : ℕ} (i : fin n.succ) (hi) :
((equiv.of_injective cast_succ (cast_succ_injective _)).symm ⟨i, hi⟩ : ℕ) = i :=
begin
rw ← coe_cast_succ,
exact congr_arg coe (equiv.apply_of_injective_symm _ _)
end
lemma succ_cast_succ {n : ℕ} (i : fin n) :
i.cast_succ.succ = i.succ.cast_succ :=
fin.ext (by simp)
/-- `add_nat m i` adds `m` to `i`, generalizes `fin.succ`. -/
def add_nat (m) : fin n ↪o fin (n + m) :=
order_embedding.of_strict_mono (λ i, ⟨(i : ℕ) + m, add_lt_add_right i.2 _⟩) $
λ i j h, lt_iff_coe_lt_coe.2 $ add_lt_add_right h _
@[simp] lemma coe_add_nat (m : ℕ) (i : fin n) : (add_nat m i : ℕ) = i + m := rfl
@[simp] lemma add_nat_one {i : fin n} : add_nat 1 i = i.succ :=
by { ext, rw [coe_add_nat, coe_succ] }
lemma le_coe_add_nat (m : ℕ) (i : fin n) : m ≤ add_nat m i := nat.le_add_left _ _
@[simp] lemma add_nat_mk (n i : ℕ) (hi : i < m) :
add_nat n ⟨i, hi⟩ = ⟨i + n, add_lt_add_right hi n⟩ := rfl
@[simp] lemma cast_add_nat_zero {n n' : ℕ} (i : fin n) (h : n + 0 = n') :
cast h (add_nat 0 i) = cast ((add_zero _).symm.trans h) i :=
ext $ add_zero _
/-- For rewriting in the reverse direction, see `fin.cast_add_nat_left`. -/
lemma add_nat_cast {n n' m : ℕ} (i : fin n') (h : n' = n) :
add_nat m (cast h i) = cast (congr_arg _ h) (add_nat m i) :=
ext rfl
lemma cast_add_nat_left {n n' m : ℕ} (i : fin n') (h : n' + m = n + m) :
cast h (add_nat m i) = add_nat m (cast (add_right_cancel h) i) :=
ext rfl
@[simp] lemma cast_add_nat_right {n m m' : ℕ} (i : fin n) (h : n + m' = n + m) :
cast h (add_nat m' i) = add_nat m i :=
ext $ (congr_arg ((+) (i : ℕ)) (add_left_cancel h) : _)
/-- `nat_add n i` adds `n` to `i` "on the left". -/
def nat_add (n) {m} : fin m ↪o fin (n + m) :=
order_embedding.of_strict_mono (λ i, ⟨n + (i : ℕ), add_lt_add_left i.2 _⟩) $
λ i j h, lt_iff_coe_lt_coe.2 $ add_lt_add_left h _
@[simp] lemma coe_nat_add (n : ℕ) {m : ℕ} (i : fin m) : (nat_add n i : ℕ) = n + i := rfl
@[simp] lemma nat_add_mk (n i : ℕ) (hi : i < m) :
nat_add n ⟨i, hi⟩ = ⟨n + i, add_lt_add_left hi n⟩ := rfl
lemma le_coe_nat_add (m : ℕ) (i : fin n) : m ≤ nat_add m i := nat.le_add_right _ _
lemma nat_add_zero {n : ℕ} : fin.nat_add 0 = (fin.cast (zero_add n).symm).to_rel_embedding :=
by { ext, apply zero_add }
/-- For rewriting in the reverse direction, see `fin.cast_nat_add_right`. -/
lemma nat_add_cast {n n' : ℕ} (m : ℕ) (i : fin n') (h : n' = n) :
nat_add m (cast h i) = cast (congr_arg _ h) (nat_add m i) :=
ext rfl
lemma cast_nat_add_right {n n' m : ℕ} (i : fin n') (h : m + n' = m + n) :
cast h (nat_add m i) = nat_add m (cast (add_left_cancel h) i) :=
ext rfl
@[simp] lemma cast_nat_add_left {n m m' : ℕ} (i : fin n) (h : m' + n = m + n) :
cast h (nat_add m' i) = nat_add m i :=
ext $ (congr_arg (+ (i : ℕ)) (add_right_cancel h) : _)
@[simp] lemma cast_nat_add_zero {n n' : ℕ} (i : fin n) (h : 0 + n = n') :
cast h (nat_add 0 i) = cast ((zero_add _).symm.trans h) i :=
ext $ zero_add _
@[simp] lemma cast_nat_add (n : ℕ) {m : ℕ} (i : fin m) :
cast (add_comm _ _) (nat_add n i) = add_nat n i :=
ext $ add_comm _ _
@[simp] lemma cast_add_nat {n : ℕ} (m : ℕ) (i : fin n) :
cast (add_comm _ _) (add_nat m i) = nat_add m i :=
ext $ add_comm _ _
@[simp] lemma nat_add_last {m n : ℕ} : nat_add n (last m) = last (n + m) := rfl
lemma nat_add_cast_succ {m n : ℕ} {i : fin m} :
nat_add n (cast_succ i) = cast_succ (nat_add n i) := rfl
end succ
section pred
/-!
### pred
-/
@[simp] lemma coe_pred (j : fin (n+1)) (h : j ≠ 0) : (j.pred h : ℕ) = j - 1 :=
by { cases j, refl }
@[simp] lemma succ_pred : ∀(i : fin (n+1)) (h : i ≠ 0), (i.pred h).succ = i
| ⟨0, h⟩ hi := by contradiction
| ⟨n + 1, h⟩ hi := rfl
@[simp] lemma pred_succ (i : fin n) {h : i.succ ≠ 0} : i.succ.pred h = i :=
by { cases i, refl }
@[simp] lemma pred_mk_succ (i : ℕ) (h : i < n + 1) :
fin.pred ⟨i + 1, add_lt_add_right h 1⟩ (ne_of_vne (ne_of_gt (mk_succ_pos i h))) = ⟨i, h⟩ :=
by simp only [ext_iff, coe_pred, coe_mk, add_tsub_cancel_right]
-- This is not a simp lemma by default, because `pred_mk_succ` is nicer when it applies.
lemma pred_mk {n : ℕ} (i : ℕ) (h : i < n + 1) (w) :
fin.pred ⟨i, h⟩ w =
⟨i - 1, by rwa tsub_lt_iff_right (nat.succ_le_of_lt $ nat.pos_of_ne_zero (fin.vne_of_ne w))⟩ :=
rfl
@[simp] lemma pred_le_pred_iff {n : ℕ} {a b : fin n.succ} {ha : a ≠ 0} {hb : b ≠ 0} :
a.pred ha ≤ b.pred hb ↔ a ≤ b :=
by rw [←succ_le_succ_iff, succ_pred, succ_pred]
@[simp] lemma pred_lt_pred_iff {n : ℕ} {a b : fin n.succ} {ha : a ≠ 0} {hb : b ≠ 0} :
a.pred ha < b.pred hb ↔ a < b :=
by rw [←succ_lt_succ_iff, succ_pred, succ_pred]
@[simp] lemma pred_inj :
∀ {a b : fin (n + 1)} {ha : a ≠ 0} {hb : b ≠ 0}, a.pred ha = b.pred hb ↔ a = b
| ⟨0, _⟩ b ha hb := by contradiction
| ⟨i+1, _⟩ ⟨0, _⟩ ha hb := by contradiction
| ⟨i+1, hi⟩ ⟨j+1, hj⟩ ha hb := by simp [fin.eq_iff_veq]
@[simp] lemma pred_one {n : ℕ} : fin.pred (1 : fin (n + 2)) (ne.symm (ne_of_lt one_pos)) = 0 := rfl
lemma pred_add_one (i : fin (n + 2)) (h : (i : ℕ) < n + 1) :
pred (i + 1) (ne_of_gt (add_one_pos _ (lt_iff_coe_lt_coe.mpr h))) = cast_lt i h :=
begin
rw [ext_iff, coe_pred, coe_cast_lt, coe_add, coe_one, mod_eq_of_lt, add_tsub_cancel_right],
exact add_lt_add_right h 1,
end
/-- `sub_nat i h` subtracts `m` from `i`, generalizes `fin.pred`. -/
def sub_nat (m) (i : fin (n + m)) (h : m ≤ (i : ℕ)) : fin n :=
⟨(i : ℕ) - m, by { rw [tsub_lt_iff_right h], exact i.is_lt }⟩
@[simp] lemma coe_sub_nat (i : fin (n + m)) (h : m ≤ i) : (i.sub_nat m h : ℕ) = i - m :=
rfl
@[simp] lemma sub_nat_mk {i : ℕ} (h₁ : i < n + m) (h₂ : m ≤ i) :
sub_nat m ⟨i, h₁⟩ h₂ = ⟨i - m, (tsub_lt_iff_right h₂).2 h₁⟩ :=
rfl
@[simp] lemma pred_cast_succ_succ (i : fin n) :
pred (cast_succ i.succ) (ne_of_gt (cast_succ_pos i.succ_pos)) = i.cast_succ :=
by simp [eq_iff_veq]
@[simp] lemma add_nat_sub_nat {i : fin (n + m)} (h : m ≤ i) :
add_nat m (sub_nat m i h) = i :=
ext $ tsub_add_cancel_of_le h
@[simp] lemma sub_nat_add_nat (i : fin n) (m : ℕ) (h : m ≤ add_nat m i := le_coe_add_nat m i) :
sub_nat m (add_nat m i) h = i :=
ext $ add_tsub_cancel_right i m
@[simp] lemma nat_add_sub_nat_cast {i : fin (n + m)} (h : n ≤ i) :
nat_add n (sub_nat n (cast (add_comm _ _) i) h) = i :=
by simp [← cast_add_nat]
end pred
section div_mod
/-- Compute `i / n`, where `n` is a `nat` and inferred the type of `i`. -/
def div_nat (i : fin (m * n)) : fin m :=
⟨i / n, nat.div_lt_of_lt_mul $ mul_comm m n ▸ i.prop⟩
@[simp] lemma coe_div_nat (i : fin (m * n)) : (i.div_nat : ℕ) = i / n := rfl
/-- Compute `i % n`, where `n` is a `nat` and inferred the type of `i`. -/
def mod_nat (i : fin (m * n)) : fin n :=
⟨i % n, nat.mod_lt _ $ pos_of_mul_pos_right ((nat.zero_le i).trans_lt i.is_lt) m.zero_le⟩
@[simp] lemma coe_mod_nat (i : fin (m * n)) : (i.mod_nat : ℕ) = i % n := rfl
end div_mod
section rec
/-!
### recursion and induction principles
-/
/-- Define `C n i` by induction on `i : fin n` interpreted as `(0 : fin (n - i)).succ.succ…`.
This function has two arguments: `H0 n` defines `0`-th element `C (n+1) 0` of an `(n+1)`-tuple,
and `Hs n i` defines `(i+1)`-st element of `(n+1)`-tuple based on `n`, `i`, and `i`-th element
of `n`-tuple. -/
@[elab_as_eliminator] def succ_rec
{C : Π n, fin n → Sort*}
(H0 : Π n, C (succ n) 0)
(Hs : Π n i, C n i → C (succ n) i.succ) : Π {n : ℕ} (i : fin n), C n i
| 0 i := i.elim0
| (succ n) ⟨0, _⟩ := H0 _
| (succ n) ⟨succ i, h⟩ := Hs _ _ (succ_rec ⟨i, lt_of_succ_lt_succ h⟩)
/-- Define `C n i` by induction on `i : fin n` interpreted as `(0 : fin (n - i)).succ.succ…`.
This function has two arguments: `H0 n` defines `0`-th element `C (n+1) 0` of an `(n+1)`-tuple,
and `Hs n i` defines `(i+1)`-st element of `(n+1)`-tuple based on `n`, `i`, and `i`-th element
of `n`-tuple.
A version of `fin.succ_rec` taking `i : fin n` as the first argument. -/
@[elab_as_eliminator] def succ_rec_on {n : ℕ} (i : fin n)
{C : Π n, fin n → Sort*}
(H0 : Π n, C (succ n) 0)
(Hs : Π n i, C n i → C (succ n) i.succ) : C n i :=
i.succ_rec H0 Hs
@[simp] theorem succ_rec_on_zero {C : ∀ n, fin n → Sort*} {H0 Hs} (n) :
@fin.succ_rec_on (succ n) 0 C H0 Hs = H0 n :=
rfl
@[simp] theorem succ_rec_on_succ {C : ∀ n, fin n → Sort*} {H0 Hs} {n} (i : fin n) :
@fin.succ_rec_on (succ n) i.succ C H0 Hs = Hs n i (fin.succ_rec_on i H0 Hs) :=
by cases i; refl
/--
Define `C i` by induction on `i : fin (n + 1)` via induction on the underlying `nat` value.
This function has two arguments: `h0` handles the base case on `C 0`,
and `hs` defines the inductive step using `C i.cast_succ`.
-/
@[elab_as_eliminator] def induction
{C : fin (n + 1) → Sort*}
(h0 : C 0)
(hs : ∀ i : fin n, C i.cast_succ → C i.succ) :
Π (i : fin (n + 1)), C i :=
begin
rintro ⟨i, hi⟩,
induction i with i IH,
{ rwa [fin.mk_zero] },
{ refine hs ⟨i, lt_of_succ_lt_succ hi⟩ _,
exact IH (lt_of_succ_lt hi) }
end
@[simp] lemma induction_zero {C : fin (n + 1) → Sort*} (h0 : C 0)
(hs : ∀ i : fin n, C i.cast_succ → C i.succ) :
(induction h0 hs : _) 0 = h0 := rfl
@[simp] lemma induction_succ {C : fin (n + 1) → Sort*} (h0 : C 0)
(hs : ∀ i : fin n, C i.cast_succ → C i.succ) (i : fin n) :
(induction h0 hs : _) i.succ = hs i (induction h0 hs i.cast_succ) := by cases i; refl
/--
Define `C i` by induction on `i : fin (n + 1)` via induction on the underlying `nat` value.
This function has two arguments: `h0` handles the base case on `C 0`,
and `hs` defines the inductive step using `C i.cast_succ`.
A version of `fin.induction` taking `i : fin (n + 1)` as the first argument.
-/
@[elab_as_eliminator] def induction_on (i : fin (n + 1))
{C : fin (n + 1) → Sort*}
(h0 : C 0)
(hs : ∀ i : fin n, C i.cast_succ → C i.succ) : C i :=
induction h0 hs i
/-- Define `f : Π i : fin n.succ, C i` by separately handling the cases `i = 0` and
`i = j.succ`, `j : fin n`. -/
@[elab_as_eliminator] def cases
{C : fin (succ n) → Sort*} (H0 : C 0) (Hs : Π i : fin n, C (i.succ)) :
Π (i : fin (succ n)), C i :=
induction H0 (λ i _, Hs i)
@[simp] theorem cases_zero {n} {C : fin (succ n) → Sort*} {H0 Hs} : @fin.cases n C H0 Hs 0 = H0 :=
rfl
@[simp] theorem cases_succ {n} {C : fin (succ n) → Sort*} {H0 Hs} (i : fin n) :
@fin.cases n C H0 Hs i.succ = Hs i :=
by cases i; refl
@[simp] theorem cases_succ' {n} {C : fin (succ n) → Sort*} {H0 Hs} {i : ℕ} (h : i + 1 < n + 1) :
@fin.cases n C H0 Hs ⟨i.succ, h⟩ = Hs ⟨i, lt_of_succ_lt_succ h⟩ :=
by cases i; refl
lemma forall_fin_succ {P : fin (n+1) → Prop} :
(∀ i, P i) ↔ P 0 ∧ (∀ i:fin n, P i.succ) :=
⟨λ H, ⟨H 0, λ i, H _⟩, λ ⟨H0, H1⟩ i, fin.cases H0 H1 i⟩
lemma exists_fin_succ {P : fin (n+1) → Prop} :
(∃ i, P i) ↔ P 0 ∨ (∃i:fin n, P i.succ) :=
⟨λ ⟨i, h⟩, fin.cases or.inl (λ i hi, or.inr ⟨i, hi⟩) i h,
λ h, or.elim h (λ h, ⟨0, h⟩) $ λ⟨i, hi⟩, ⟨i.succ, hi⟩⟩
lemma forall_fin_one {p : fin 1 → Prop} : (∀ i, p i) ↔ p 0 := @unique.forall_iff (fin 1) _ p
lemma exists_fin_one {p : fin 1 → Prop} : (∃ i, p i) ↔ p 0 := @unique.exists_iff (fin 1) _ p
lemma forall_fin_two {p : fin 2 → Prop} : (∀ i, p i) ↔ p 0 ∧ p 1 :=
forall_fin_succ.trans $ and_congr_right $ λ _, forall_fin_one
lemma exists_fin_two {p : fin 2 → Prop} : (∃ i, p i) ↔ p 0 ∨ p 1 :=
exists_fin_succ.trans $ or_congr_right' exists_fin_one
lemma fin_two_eq_of_eq_zero_iff {a b : fin 2} (h : a = 0 ↔ b = 0) : a = b :=
by { revert a b, simp [forall_fin_two] }
/--
Define `C i` by reverse induction on `i : fin (n + 1)` via induction on the underlying `nat` value.
This function has two arguments: `hlast` handles the base case on `C (fin.last n)`,
and `hs` defines the inductive step using `C i.succ`, inducting downwards.
-/
@[elab_as_eliminator]
def reverse_induction {n : ℕ}
{C : fin (n + 1) → Sort*}
(hlast : C (fin.last n))
(hs : ∀ i : fin n, C i.succ → C i.cast_succ) :
Π (i : fin (n + 1)), C i
| i :=
if hi : i = fin.last n
then _root_.cast (by rw hi) hlast
else
let j : fin n := ⟨i, lt_of_le_of_ne (nat.le_of_lt_succ i.2) (λ h, hi (fin.ext h))⟩ in
have wf : n + 1 - j.succ < n + 1 - i, begin
cases i,
rw [tsub_lt_tsub_iff_left_of_le];
simp [*, nat.succ_le_iff],
end,
have hi : i = fin.cast_succ j, from fin.ext rfl,
_root_.cast (by rw hi) (hs _ (reverse_induction j.succ))
using_well_founded { rel_tac := λ _ _, `[exact ⟨_, measure_wf (λ i : fin (n+1), n + 1 - i)⟩],
dec_tac := `[assumption] }
@[simp] lemma reverse_induction_last {n : ℕ}
{C : fin (n + 1) → Sort*}
(h0 : C (fin.last n))
(hs : ∀ i : fin n, C i.succ → C i.cast_succ) :
(reverse_induction h0 hs (fin.last n) : C (fin.last n)) = h0 :=
by rw [reverse_induction]; simp
@[simp] lemma reverse_induction_cast_succ {n : ℕ}
{C : fin (n + 1) → Sort*}
(h0 : C (fin.last n))
(hs : ∀ i : fin n, C i.succ → C i.cast_succ) (i : fin n):
(reverse_induction h0 hs i.cast_succ : C i.cast_succ) =
hs i (reverse_induction h0 hs i.succ) :=
begin
rw [reverse_induction, dif_neg (ne_of_lt (fin.cast_succ_lt_last i))],
cases i,
refl
end
/-- Define `f : Π i : fin n.succ, C i` by separately handling the cases `i = fin.last n` and
`i = j.cast_succ`, `j : fin n`. -/
@[elab_as_eliminator, elab_strategy]
def last_cases {n : ℕ} {C : fin (n + 1) → Sort*}
(hlast : C (fin.last n)) (hcast : (Π (i : fin n), C i.cast_succ)) (i : fin (n + 1)) : C i :=
reverse_induction hlast (λ i _, hcast i) i
@[simp] lemma last_cases_last {n : ℕ} {C : fin (n + 1) → Sort*}
(hlast : C (fin.last n)) (hcast : (Π (i : fin n), C i.cast_succ)) :
(fin.last_cases hlast hcast (fin.last n): C (fin.last n)) = hlast :=
reverse_induction_last _ _
@[simp] lemma last_cases_cast_succ {n : ℕ} {C : fin (n + 1) → Sort*}
(hlast : C (fin.last n)) (hcast : (Π (i : fin n), C i.cast_succ)) (i : fin n) :
(fin.last_cases hlast hcast (fin.cast_succ i): C (fin.cast_succ i)) = hcast i :=
reverse_induction_cast_succ _ _ _
/-- Define `f : Π i : fin (m + n), C i` by separately handling the cases `i = cast_add n i`,
`j : fin m` and `i = nat_add m j`, `j : fin n`. -/
@[elab_as_eliminator, elab_strategy]
def add_cases {m n : ℕ} {C : fin (m + n) → Sort u}
(hleft : Π i, C (cast_add n i))
(hright : Π i, C (nat_add m i)) (i : fin (m + n)) : C i :=
if hi : (i : ℕ) < m then eq.rec_on (cast_add_cast_lt n i hi) (hleft (cast_lt i hi))
else eq.rec_on (nat_add_sub_nat_cast (le_of_not_lt hi)) (hright _)
@[simp] lemma add_cases_left {m n : ℕ} {C : fin (m + n) → Sort*}
(hleft : Π i, C (cast_add n i)) (hright : Π i, C (nat_add m i)) (i : fin m) :
add_cases hleft hright (fin.cast_add n i) = hleft i :=
begin
cases i with i hi,
rw [add_cases, dif_pos (cast_add_lt _ _)],
refl
end
@[simp] lemma add_cases_right {m n : ℕ} {C : fin (m + n) → Sort*}
(hleft : Π i, C (cast_add n i)) (hright : Π i, C (nat_add m i)) (i : fin n) :
add_cases hleft hright (nat_add m i) = hright i :=
begin
have : ¬ (nat_add m i : ℕ) < m, from (le_coe_nat_add _ _).not_lt,
rw [add_cases, dif_neg this],
refine eq_of_heq ((eq_rec_heq _ _).trans _), congr' 1,
simp
end
end rec
lemma lift_fun_iff_succ {α : Type*} (r : α → α → Prop) [is_trans α r] {f : fin (n + 1) → α} :
((<) ⇒ r) f f ↔ ∀ i : fin n, r (f i.cast_succ) (f i.succ) :=
begin
split,
{ intros H i,
exact H i.cast_succ_lt_succ },
{ refine λ H i, fin.induction _ _,
{ exact λ h, (h.not_le (zero_le i)).elim },
{ intros j ihj hij,
rw [← le_cast_succ_iff] at hij,
rcases hij.eq_or_lt with rfl|hlt,
exacts [H j, trans (ihj hlt) (H j)] } }
end
/-- A function `f` on `fin (n + 1)` is strictly monotone if and only if `f i < f (i + 1)`
for all `i`. -/
lemma strict_mono_iff_lt_succ {α : Type*} [preorder α] {f : fin (n + 1) → α} :
strict_mono f ↔ ∀ i : fin n, f i.cast_succ < f i.succ :=
lift_fun_iff_succ (<)
/-- A function `f` on `fin (n + 1)` is monotone if and only if `f i ≤ f (i + 1)` for all `i`. -/
lemma monotone_iff_le_succ {α : Type*} [preorder α] {f : fin (n + 1) → α} :
monotone f ↔ ∀ i : fin n, f i.cast_succ ≤ f i.succ :=
monotone_iff_forall_lt.trans $ lift_fun_iff_succ (≤)
/-- A function `f` on `fin (n + 1)` is strictly antitone if and only if `f (i + 1) < f i`
for all `i`. -/
lemma strict_anti_iff_succ_lt {α : Type*} [preorder α] {f : fin (n + 1) → α} :
strict_anti f ↔ ∀ i : fin n, f i.succ < f i.cast_succ :=
lift_fun_iff_succ (>)
/-- A function `f` on `fin (n + 1)` is antitone if and only if `f (i + 1) ≤ f i` for all `i`. -/
lemma antitone_iff_succ_le {α : Type*} [preorder α] {f : fin (n + 1) → α} :
antitone f ↔ ∀ i : fin n, f i.succ ≤ f i.cast_succ :=
antitone_iff_forall_lt.trans $ lift_fun_iff_succ (≥)
section add_group
open nat int
/-- Negation on `fin n` -/
instance (n : ℕ) : has_neg (fin n) :=
⟨λ a, ⟨(n - a) % n, nat.mod_lt _ (lt_of_le_of_lt (nat.zero_le _) a.2)⟩⟩
/-- Abelian group structure on `fin (n+1)`. -/
instance (n : ℕ) : add_comm_group (fin (n+1)) :=
{ add_left_neg := λ ⟨a, ha⟩, fin.ext $ trans (nat.mod_add_mod _ _ _) $
by { rw [fin.coe_mk, fin.coe_zero, tsub_add_cancel_of_le, nat.mod_self], exact le_of_lt ha },
sub_eq_add_neg := λ ⟨a, ha⟩ ⟨b, hb⟩, fin.ext $
show (a + (n + 1 - b)) % (n + 1) = (a + (n + 1 - b) % (n + 1)) % (n + 1), by simp,
sub := fin.sub,
..fin.add_comm_monoid n,
..fin.has_neg n.succ }
protected lemma coe_neg (a : fin n) : ((-a : fin n) : ℕ) = (n - a) % n := rfl
protected lemma coe_sub (a b : fin n) : ((a - b : fin n) : ℕ) = (a + (n - b)) % n :=
by cases a; cases b; refl
@[simp] lemma coe_fin_one (a : fin 1) : ↑a = 0 :=
by rw [subsingleton.elim a 0, fin.coe_zero]
@[simp] lemma coe_neg_one : ↑(-1 : fin (n + 1)) = n :=
begin
cases n,
{ simp },
rw [fin.coe_neg, fin.coe_one, nat.succ_sub_one, nat.mod_eq_of_lt],
constructor
end
lemma coe_sub_one {n} (a : fin (n + 1)) : ↑(a - 1) = if a = 0 then n else a - 1 :=
begin
cases n,
{ simp },
split_ifs,
{ simp [h] },
rw [sub_eq_add_neg, coe_add_eq_ite, coe_neg_one, if_pos, add_comm, add_tsub_add_eq_tsub_left],
rw [add_comm ↑a, add_le_add_iff_left, nat.one_le_iff_ne_zero],
rwa subtype.ext_iff at h
end
lemma coe_sub_iff_le {n : ℕ} {a b : fin n} :
(↑(a - b) : ℕ) = a - b ↔ b ≤ a :=
begin
cases n, {exact fin_zero_elim a},
rw [le_iff_coe_le_coe, fin.coe_sub, ←add_tsub_assoc_of_le b.is_lt.le],
cases le_or_lt (b : ℕ) a with h h,
{ simp [←tsub_add_eq_add_tsub h, h, nat.mod_eq_of_lt ((nat.sub_le _ _).trans_lt a.is_lt)] },
{ rw [nat.mod_eq_of_lt, tsub_eq_zero_of_le h.le, tsub_eq_zero_iff_le, ←not_iff_not],
{ simpa [b.is_lt.trans_le (le_add_self)] using h },
{ rwa [tsub_lt_iff_left (b.is_lt.le.trans (le_add_self)), add_lt_add_iff_right] } }
end
lemma coe_sub_iff_lt {n : ℕ} {a b : fin n} :
(↑(a - b) : ℕ) = n + a - b ↔ a < b :=
begin
cases n, {exact fin_zero_elim a},
rw [lt_iff_coe_lt_coe, fin.coe_sub, add_comm],
cases le_or_lt (b : ℕ) a with h h,
{ simpa [add_tsub_assoc_of_le h, ←not_le, h]
using ((nat.mod_lt _ (nat.succ_pos _)).trans_le le_self_add).ne },
{ simp [←tsub_tsub_assoc b.is_lt.le h.le, ←tsub_add_eq_add_tsub b.is_lt.le,
nat.mod_eq_of_lt (tsub_lt_self (nat.succ_pos _) (tsub_pos_of_lt h)), h] }
end
/-- By sending `x` to `last n - x`, `fin n` is order-equivalent to its `order_dual`. -/
def _root_.order_iso.fin_equiv : ∀ {n}, (fin n)ᵒᵈ ≃o fin n
| 0 := ⟨⟨elim0, elim0, elim0, elim0⟩, elim0⟩
| (n+1) := order_iso.symm $
{ to_fun := λ x, order_dual.to_dual (last n - x),
inv_fun := λ x, last n - x.of_dual,
left_inv := sub_sub_cancel _,
right_inv := sub_sub_cancel _,
map_rel_iff' := λ a b,
begin
simp only [equiv.coe_fn_mk, order_dual.to_dual_le_to_dual],
rw [le_iff_coe_le_coe, coe_sub_iff_le.mpr (le_last b), coe_sub_iff_le.mpr (le_last _),
tsub_le_tsub_iff_left, le_iff_coe_le_coe],
exact le_last _,
end }
lemma _root_.order_iso.fin_equiv_apply (a) : order_iso.fin_equiv a = last n - a.of_dual := rfl
lemma _root_.order_iso.fin_equiv_symm_apply (a) :
order_iso.fin_equiv.symm a = order_dual.to_dual (last n - a) := rfl
end add_group
section succ_above
lemma succ_above_aux (p : fin (n + 1)) :
strict_mono (λ i : fin n, if i.cast_succ < p then i.cast_succ else i.succ) :=
(cast_succ : fin n ↪o _).strict_mono.ite (succ_embedding n).strict_mono
(λ i j hij hj, lt_trans ((cast_succ : fin n ↪o _).lt_iff_lt.2 hij) hj)
(λ i, (cast_succ_lt_succ i).le)
/-- `succ_above p i` embeds `fin n` into `fin (n + 1)` with a hole around `p`. -/
def succ_above (p : fin (n + 1)) : fin n ↪o fin (n + 1) :=
order_embedding.of_strict_mono _ p.succ_above_aux
/-- Embedding `i : fin n` into `fin (n + 1)` with a hole around `p : fin (n + 1)`
embeds `i` by `cast_succ` when the resulting `i.cast_succ < p`. -/
lemma succ_above_below (p : fin (n + 1)) (i : fin n) (h : i.cast_succ < p) :
p.succ_above i = i.cast_succ :=
by { rw [succ_above], exact if_pos h }
@[simp] lemma succ_above_ne_zero_zero {a : fin (n + 2)} (ha : a ≠ 0) : a.succ_above 0 = 0 :=
begin
rw fin.succ_above_below,
{ refl },
{ exact bot_lt_iff_ne_bot.mpr ha }
end
lemma succ_above_eq_zero_iff {a : fin (n + 2)} {b : fin (n + 1)} (ha : a ≠ 0) :
a.succ_above b = 0 ↔ b = 0 :=
by simp only [←succ_above_ne_zero_zero ha, order_embedding.eq_iff_eq]
lemma succ_above_ne_zero {a : fin (n + 2)} {b : fin (n + 1)} (ha : a ≠ 0) (hb : b ≠ 0) :
a.succ_above b ≠ 0 :=
mt (succ_above_eq_zero_iff ha).mp hb
/-- Embedding `fin n` into `fin (n + 1)` with a hole around zero embeds by `succ`. -/
@[simp] lemma succ_above_zero : ⇑(succ_above (0 : fin (n + 1))) = fin.succ := rfl
/-- Embedding `fin n` into `fin (n + 1)` with a hole around `last n` embeds by `cast_succ`. -/
@[simp] lemma succ_above_last : succ_above (fin.last n) = cast_succ :=
by { ext, simp only [succ_above_below, cast_succ_lt_last] }
lemma succ_above_last_apply (i : fin n) : succ_above (fin.last n) i = i.cast_succ :=
by rw succ_above_last
/-- Embedding `i : fin n` into `fin (n + 1)` with a hole around `p : fin (n + 1)`
embeds `i` by `succ` when the resulting `p < i.succ`. -/
lemma succ_above_above (p : fin (n + 1)) (i : fin n) (h : p ≤ i.cast_succ) :
p.succ_above i = i.succ :=
by simp [succ_above, h.not_lt]
/-- Embedding `i : fin n` into `fin (n + 1)` is always about some hole `p`. -/
lemma succ_above_lt_ge (p : fin (n + 1)) (i : fin n) : i.cast_succ < p ∨ p ≤ i.cast_succ :=
lt_or_ge (cast_succ i) p
/-- Embedding `i : fin n` into `fin (n + 1)` is always about some hole `p`. -/
lemma succ_above_lt_gt (p : fin (n + 1)) (i : fin n) : i.cast_succ < p ∨ p < i.succ :=
or.cases_on (succ_above_lt_ge p i)
(λ h, or.inl h) (λ h, or.inr (lt_of_le_of_lt h (cast_succ_lt_succ i)))
/-- Embedding `i : fin n` into `fin (n + 1)` using a pivot `p` that is greater
results in a value that is less than `p`. -/
@[simp] lemma succ_above_lt_iff (p : fin (n + 1)) (i : fin n) :
p.succ_above i < p ↔ i.cast_succ < p :=
begin
refine iff.intro _ _,
{ intro h,
cases succ_above_lt_ge p i with H H,
{ exact H },
{ rw succ_above_above _ _ H at h,
exact lt_trans (cast_succ_lt_succ i) h } },
{ intro h,
rw succ_above_below _ _ h,
exact h }
end
/-- Embedding `i : fin n` into `fin (n + 1)` using a pivot `p` that is lesser
results in a value that is greater than `p`. -/
lemma lt_succ_above_iff (p : fin (n + 1)) (i : fin n) : p < p.succ_above i ↔ p ≤ i.cast_succ :=
begin
refine iff.intro _ _,
{ intro h,
cases succ_above_lt_ge p i with H H,
{ rw succ_above_below _ _ H at h,
exact le_of_lt h },
{ exact H } },
{ intro h,
rw succ_above_above _ _ h,
exact lt_of_le_of_lt h (cast_succ_lt_succ i) },
end
/-- Embedding `i : fin n` into `fin (n + 1)` with a hole around `p : fin (n + 1)`
never results in `p` itself -/
theorem succ_above_ne (p : fin (n + 1)) (i : fin n) : p.succ_above i ≠ p :=
begin
intro eq,
by_cases H : i.cast_succ < p,
{ simpa [lt_irrefl, ←succ_above_below _ _ H, eq] using H },
{ simpa [←succ_above_above _ _ (le_of_not_lt H), eq] using cast_succ_lt_succ i }
end
/-- Embedding a positive `fin n` results in a positive fin (n + 1)` -/
lemma succ_above_pos (p : fin (n + 2)) (i : fin (n + 1)) (h : 0 < i) : 0 < p.succ_above i :=
begin
by_cases H : i.cast_succ < p,
{ simpa [succ_above_below _ _ H] using cast_succ_pos h },
{ simp [succ_above_above _ _ (le_of_not_lt H)] },
end
@[simp] lemma succ_above_cast_lt {x y : fin (n + 1)} (h : x < y)
(hx : x.1 < n := lt_of_lt_of_le h y.le_last) :
y.succ_above (x.cast_lt hx) = x :=
by { rw [succ_above_below, cast_succ_cast_lt], exact h }
@[simp] lemma succ_above_pred {x y : fin (n + 1)} (h : x < y)
(hy : y ≠ 0 := (x.zero_le.trans_lt h).ne') :
x.succ_above (y.pred hy) = y :=
by { rw [succ_above_above, succ_pred], simpa [le_iff_coe_le_coe] using nat.le_pred_of_lt h }
lemma cast_lt_succ_above {x : fin n} {y : fin (n + 1)} (h : cast_succ x < y)
(h' : (y.succ_above x).1 < n := lt_of_lt_of_le ((succ_above_lt_iff _ _).2 h) (le_last y)) :
(y.succ_above x).cast_lt h' = x :=
by simp only [succ_above_below _ _ h, cast_lt_cast_succ]
lemma pred_succ_above {x : fin n} {y : fin (n + 1)} (h : y ≤ cast_succ x)
(h' : y.succ_above x ≠ 0 := (y.zero_le.trans_lt $ (lt_succ_above_iff _ _).2 h).ne') :
(y.succ_above x).pred h' = x :=
by simp only [succ_above_above _ _ h, pred_succ]
lemma exists_succ_above_eq {x y : fin (n + 1)} (h : x ≠ y) : ∃ z, y.succ_above z = x :=
begin
cases h.lt_or_lt with hlt hlt,
exacts [⟨_, succ_above_cast_lt hlt⟩, ⟨_, succ_above_pred hlt⟩],
end
@[simp] lemma exists_succ_above_eq_iff {x y : fin (n + 1)} : (∃ z, x.succ_above z = y) ↔ y ≠ x :=
begin
refine ⟨_, exists_succ_above_eq⟩,
rintro ⟨y, rfl⟩,
exact succ_above_ne _ _
end
/-- The range of `p.succ_above` is everything except `p`. -/
@[simp] lemma range_succ_above (p : fin (n + 1)) : set.range (p.succ_above) = {p}ᶜ :=
set.ext $ λ _, exists_succ_above_eq_iff
/-- Given a fixed pivot `x : fin (n + 1)`, `x.succ_above` is injective -/
lemma succ_above_right_injective {x : fin (n + 1)} : injective (succ_above x) :=
(succ_above x).injective
/-- Given a fixed pivot `x : fin (n + 1)`, `x.succ_above` is injective -/
lemma succ_above_right_inj {x : fin (n + 1)} :
x.succ_above a = x.succ_above b ↔ a = b :=
succ_above_right_injective.eq_iff
/-- `succ_above` is injective at the pivot -/
lemma succ_above_left_injective : injective (@succ_above n) :=
λ _ _ h, by simpa [range_succ_above] using congr_arg (λ f : fin n ↪o fin (n + 1), (set.range f)ᶜ) h
/-- `succ_above` is injective at the pivot -/
@[simp] lemma succ_above_left_inj {x y : fin (n + 1)} :
x.succ_above = y.succ_above ↔ x = y :=
succ_above_left_injective.eq_iff
@[simp] lemma zero_succ_above {n : ℕ} (i : fin n) :
(0 : fin (n + 1)).succ_above i = i.succ :=
rfl
@[simp] lemma succ_succ_above_zero {n : ℕ} (i : fin (n + 1)) :
(i.succ).succ_above 0 = 0 :=
succ_above_below _ _ (succ_pos _)
@[simp] lemma succ_succ_above_succ {n : ℕ} (i : fin (n + 1)) (j : fin n) :
(i.succ).succ_above j.succ = (i.succ_above j).succ :=
(lt_or_ge j.cast_succ i).elim
(λ h, have h' : j.succ.cast_succ < i.succ, by simpa [lt_iff_coe_lt_coe] using h,
by { ext, simp [succ_above_below _ _ h, succ_above_below _ _ h'] })
(λ h, have h' : i.succ ≤ j.succ.cast_succ, by simpa [le_iff_coe_le_coe] using h,
by { ext, simp [succ_above_above _ _ h, succ_above_above _ _ h'] })
@[simp] lemma one_succ_above_zero {n : ℕ} :
(1 : fin (n + 2)).succ_above 0 = 0 :=
succ_succ_above_zero 0
/-- By moving `succ` to the outside of this expression, we create opportunities for further
simplification using `succ_above_zero` or `succ_succ_above_zero`. -/
@[simp] lemma succ_succ_above_one {n : ℕ} (i : fin (n + 2)) :
(i.succ).succ_above 1 = (i.succ_above 0).succ :=
succ_succ_above_succ i 0
@[simp] lemma one_succ_above_succ {n : ℕ} (j : fin n) :
(1 : fin (n + 2)).succ_above j.succ = j.succ.succ :=
succ_succ_above_succ 0 j
@[simp] lemma one_succ_above_one {n : ℕ} :
(1 : fin (n + 3)).succ_above 1 = 2 :=
succ_succ_above_succ 0 0
end succ_above
section pred_above
/-- `pred_above p i` embeds `i : fin (n+1)` into `fin n` by subtracting one if `p < i`. -/
def pred_above (p : fin n) (i : fin (n+1)) : fin n :=
if h : p.cast_succ < i then
i.pred (ne_of_lt (lt_of_le_of_lt (zero_le p.cast_succ) h)).symm
else
i.cast_lt (lt_of_le_of_lt (le_of_not_lt h) p.2)
lemma pred_above_right_monotone (p : fin n) : monotone p.pred_above :=
λ a b H,
begin
dsimp [pred_above],
split_ifs with ha hb hb,
all_goals { simp only [le_iff_coe_le_coe, coe_pred], },
{ exact pred_le_pred H, },
{ calc _ ≤ _ : nat.pred_le _
... ≤ _ : H, },
{ simp at ha, exact le_pred_of_lt (lt_of_le_of_lt ha hb), },
{ exact H, },
end
lemma pred_above_left_monotone (i : fin (n + 1)) : monotone (λ p, pred_above p i) :=
λ a b H,
begin
dsimp [pred_above],
split_ifs with ha hb hb,
all_goals { simp only [le_iff_coe_le_coe, coe_pred] },
{ exact pred_le _, },
{ have : b < a := cast_succ_lt_cast_succ_iff.mpr (hb.trans_le (le_of_not_gt ha)),
exact absurd H this.not_le }
end
/-- `cast_pred` embeds `i : fin (n + 2)` into `fin (n + 1)`
by lowering just `last (n + 1)` to `last n`. -/
def cast_pred (i : fin (n + 2)) : fin (n + 1) :=
pred_above (last n) i
@[simp] lemma cast_pred_zero : cast_pred (0 : fin (n + 2)) = 0 := rfl
@[simp] lemma cast_pred_one : cast_pred (1 : fin (n + 2)) = 1 :=
by { cases n, apply subsingleton.elim, refl }
@[simp] theorem pred_above_zero {i : fin (n + 2)} (hi : i ≠ 0) :
pred_above 0 i = i.pred hi :=
begin
dsimp [pred_above],
rw dif_pos,
exact (pos_iff_ne_zero _).mpr hi,
end
@[simp] lemma cast_pred_last : cast_pred (last (n + 1)) = last n :=
by simp [eq_iff_veq, cast_pred, pred_above, cast_succ_lt_last]
@[simp] lemma cast_pred_mk (n i : ℕ) (h : i < n + 1) :
cast_pred ⟨i, lt_succ_of_lt h⟩ = ⟨i, h⟩ :=
begin
have : ¬cast_succ (last n) < ⟨i, lt_succ_of_lt h⟩,
{ simpa [lt_iff_coe_lt_coe] using le_of_lt_succ h },
simp [cast_pred, pred_above, this]
end
lemma pred_above_below (p : fin (n + 1)) (i : fin (n + 2)) (h : i ≤ p.cast_succ) :
p.pred_above i = i.cast_pred :=
begin
have : i ≤ (last n).cast_succ := h.trans p.le_last,
simp [pred_above, cast_pred, h.not_lt, this.not_lt]
end
@[simp] lemma pred_above_last : pred_above (fin.last n) = cast_pred := rfl
lemma pred_above_last_apply (i : fin n) : pred_above (fin.last n) i = i.cast_pred :=
by rw pred_above_last
lemma pred_above_above (p : fin n) (i : fin (n + 1)) (h : p.cast_succ < i) :
p.pred_above i = i.pred (p.cast_succ.zero_le.trans_lt h).ne.symm :=
by simp [pred_above, h]
lemma cast_pred_monotone : monotone (@cast_pred n) :=
pred_above_right_monotone (last _)
/-- Sending `fin (n+1)` to `fin n` by subtracting one from anything above `p`
then back to `fin (n+1)` with a gap around `p` is the identity away from `p`. -/
@[simp] lemma succ_above_pred_above {p : fin n} {i : fin (n + 1)} (h : i ≠ p.cast_succ) :
p.cast_succ.succ_above (p.pred_above i) = i :=
begin
dsimp [pred_above, succ_above],
rcases p with ⟨p, _⟩,
rcases i with ⟨i, _⟩,
cases lt_or_le i p with H H,
{ rw dif_neg, rw if_pos, refl, exact H, simp, apply le_of_lt H, },
{ rw dif_pos, rw if_neg,
swap 3, -- For some reason `simp` doesn't fire fully unless we discharge the third goal.
{ exact lt_of_le_of_ne H (ne.symm h), },
{ simp, },
{ simp only [subtype.mk_eq_mk, ne.def, fin.cast_succ_mk] at h,
simp only [pred, subtype.mk_lt_mk, not_lt],
exact nat.le_pred_of_lt (nat.lt_of_le_and_ne H (ne.symm h)), }, },
end
/-- Sending `fin n` into `fin (n + 1)` with a gap at `p`
then back to `fin n` by subtracting one from anything above `p` is the identity. -/
@[simp] lemma pred_above_succ_above (p : fin n) (i : fin n) :
p.pred_above (p.cast_succ.succ_above i) = i :=
begin
dsimp [pred_above, succ_above],
rcases p with ⟨p, _⟩,
rcases i with ⟨i, _⟩,
split_ifs,
{ rw dif_neg,
{ refl },
{ simp_rw [if_pos h],
simp only [subtype.mk_lt_mk, not_lt],
exact le_of_lt h, }, },
{ rw dif_pos,
{ refl, },
{ simp_rw [if_neg h],
exact lt_succ_iff.mpr (not_lt.mp h), }, },
end
lemma cast_succ_pred_eq_pred_cast_succ {a : fin (n + 1)} (ha : a ≠ 0)
(ha' := a.cast_succ_ne_zero_iff.mpr ha) : (a.pred ha).cast_succ = a.cast_succ.pred ha' :=
by { cases a, refl }
/-- `pred` commutes with `succ_above`. -/
lemma pred_succ_above_pred {a : fin (n + 2)} {b : fin (n + 1)} (ha : a ≠ 0) (hb : b ≠ 0)
(hk := succ_above_ne_zero ha hb) :
(a.pred ha).succ_above (b.pred hb) = (a.succ_above b).pred hk :=
begin
obtain hbelow | habove := lt_or_le b.cast_succ a, -- `rwa` uses them
{ rw fin.succ_above_below,
{ rwa [cast_succ_pred_eq_pred_cast_succ , fin.pred_inj, fin.succ_above_below] },
{ rwa [cast_succ_pred_eq_pred_cast_succ , pred_lt_pred_iff] } },
{ rw fin.succ_above_above,
have : (b.pred hb).succ = b.succ.pred (fin.succ_ne_zero _), by rw [succ_pred, pred_succ],
{ rwa [this, fin.pred_inj, fin.succ_above_above] },
{ rwa [cast_succ_pred_eq_pred_cast_succ , fin.pred_le_pred_iff] } }
end
@[simp] theorem cast_pred_cast_succ (i : fin (n + 1)) :
cast_pred i.cast_succ = i :=
by simp [cast_pred, pred_above, le_last]
lemma cast_succ_cast_pred {i : fin (n + 2)} (h : i < last _) : cast_succ i.cast_pred = i :=
begin
rw [cast_pred, pred_above, dif_neg],
{ simp [fin.eq_iff_veq] },
{ exact h.not_le }
end
lemma coe_cast_pred_le_self (i : fin (n + 2)) : (i.cast_pred : ℕ) ≤ i :=
begin
rcases i.le_last.eq_or_lt with rfl|h,
{ simp },
{ rw [cast_pred, pred_above, dif_neg],
{ simp },
{ simpa [lt_iff_coe_lt_coe, le_iff_coe_le_coe, lt_succ_iff] using h } }
end
lemma coe_cast_pred_lt_iff {i : fin (n + 2)} : (i.cast_pred : ℕ) < i ↔ i = fin.last _ :=
begin
rcases i.le_last.eq_or_lt with rfl|H,
{ simp },
{ simp only [ne_of_lt H],
rw ←cast_succ_cast_pred H,
simp }
end
lemma lt_last_iff_coe_cast_pred {i : fin (n + 2)} : i < fin.last _ ↔ (i.cast_pred : ℕ) = i :=
begin
rcases i.le_last.eq_or_lt with rfl|H,
{ simp },
{ simp only [H],
rw ←cast_succ_cast_pred H,
simp }
end
end pred_above
/-- `min n m` as an element of `fin (m + 1)` -/
def clamp (n m : ℕ) : fin (m + 1) := of_nat $ min n m
@[simp] lemma coe_clamp (n m : ℕ) : (clamp n m : ℕ) = min n m :=
nat.mod_eq_of_lt $ nat.lt_succ_iff.mpr $ min_le_right _ _
@[simp]
lemma coe_of_nat_eq_mod (m n : ℕ) :
((n : fin (succ m)) : ℕ) = n % succ m :=
by rw [← of_nat_eq_coe]; refl
@[simp] lemma coe_of_nat_eq_mod' (m n : ℕ) [I : fact (0 < m)] :
(@fin.of_nat' _ I n : ℕ) = n % m :=
rfl
section mul
/-!
### mul
-/
lemma val_mul {n : ℕ} : ∀ a b : fin n, (a * b).val = (a.val * b.val) % n
| ⟨_, _⟩ ⟨_, _⟩ := rfl
lemma coe_mul {n : ℕ} : ∀ a b : fin n, ((a * b : fin n) : ℕ) = (a * b) % n
| ⟨_, _⟩ ⟨_, _⟩ := rfl
@[simp] protected lemma mul_one (k : fin (n + 1)) : k * 1 = k :=
by { cases n, simp, simp [eq_iff_veq, mul_def, mod_eq_of_lt (is_lt k)] }
@[simp] protected lemma one_mul (k : fin (n + 1)) : (1 : fin (n + 1)) * k = k :=
by { cases n, simp, simp [eq_iff_veq, mul_def, mod_eq_of_lt (is_lt k)] }
@[simp] protected lemma mul_zero (k : fin (n + 1)) : k * 0 = 0 :=
by simp [eq_iff_veq, mul_def]
@[simp] protected lemma zero_mul (k : fin (n + 1)) : (0 : fin (n + 1)) * k = 0 :=
by simp [eq_iff_veq, mul_def]
end mul
section
-- Note that here we are disabling the "safety" of reflected, to allow us to reuse `nat.mk_numeral`.
-- The usual way to provide the required `reflected` instance would be via rewriting to prove that
-- the expression we use here is equivalent.
local attribute [semireducible] reflected
meta instance reflect : Π n, has_reflect (fin n)
| 0 := fin_zero_elim
| (n + 1) := nat.mk_numeral `(fin n.succ)
`(by apply_instance : has_zero (fin n.succ))
`(by apply_instance : has_one (fin n.succ))
`(by apply_instance : has_add (fin n.succ)) ∘ subtype.val
end
end fin
|
d78450c230c5de31ed1862a3d2cd818624376aac | 3f7026ea8bef0825ca0339a275c03b911baef64d | /src/ring_theory/power_series.lean | 2f74c5bd1cb0911cb655164ce380eb0b2a363d1b | [
"Apache-2.0"
] | permissive | rspencer01/mathlib | b1e3afa5c121362ef0881012cc116513ab09f18c | c7d36292c6b9234dc40143c16288932ae38fdc12 | refs/heads/master | 1,595,010,346,708 | 1,567,511,503,000 | 1,567,511,503,000 | 206,071,681 | 0 | 0 | Apache-2.0 | 1,567,513,643,000 | 1,567,513,643,000 | null | UTF-8 | Lean | false | false | 38,628 | lean | /-
Copyright (c) 2019 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin, Kenny Lau
-/
import data.finsupp order.complete_lattice algebra.ordered_group data.mv_polynomial
import algebra.order_functions
import ring_theory.ideal_operations
/-!
# Formal power series
This file defines (multivariate) formal power series
and develops the basic properties of these objects.
A formal power series is to a polynomial like an infinite sum is to a finite sum.
We provide the natural inclusion from polynomials to formal power series.
`trunc n φ` truncates a formal power series to the polynomial
that has the same coefficients as φ, for all m ≤ n, and 0 otherwise.
If the constant coefficient of a formal power series is invertible,
then this formal power series is invertible.
Formal power series over a local ring form a local ring.
## Implementation notes
In this file we define multivariate formal power series with coefficients in `α` as
mv_power_series σ α := (σ →₀ ℕ) → α
Unfortunately there is not yet enough API to show that they are the completion
of the ring of multivariate polynomials. However, we provide most of the infrastructure
that is needed to do this. Once I-adic completion (topological or algebraic) is available
it should not be hard to fill in the details.
Formal power series in one variable are defined as
power_series α := mv_power_series unit α
This allows us to port a lot of proofs and properties
from the multivariate case to the single variable case.
However, it means that formal power series are indexed by (unit →₀ ℕ),
which is of course canonically isomorphic to ℕ.
We then build some glue to treat formal power series as if they are indexed by ℕ.
Occasionally this leads to proofs that are uglier than expected.
-/
/-- Multivariate formal power series, where `σ` is the index set of the variables
and `α` is the coefficient ring.-/
def mv_power_series (σ : Type*) (α : Type*) := (σ →₀ ℕ) → α
namespace mv_power_series
open finsupp
variables {σ : Type*} {α : Type*} [decidable_eq σ]
/-- The `n`th coefficient of a multivariate formal power series.-/
def coeff (n : σ →₀ ℕ) (φ : mv_power_series σ α) := φ n
/-- Two multivariate formal power series are equal if all their coefficients are equal.-/
@[extensionality] lemma ext {φ ψ : mv_power_series σ α} (h : ∀ n, coeff n φ = coeff n ψ) :
φ = ψ :=
funext h
/-- Two multivariate formal power series are equal
if and only if all their coefficients are equal.-/
lemma ext_iff {φ ψ : mv_power_series σ α} :
φ = ψ ↔ (∀ n, coeff n φ = coeff n ψ) :=
⟨λ h n, congr_arg (coeff n) h, ext⟩
section semiring
variables [semiring α]
/-- The `n`th monimial with coefficient `a` as multivariate formal power series.-/
def monomial (n : σ →₀ ℕ) (a : α) : mv_power_series σ α :=
λ m, if m = n then a else 0
lemma coeff_monomial (m n : σ →₀ ℕ) (a : α) :
coeff m (monomial n a) = if m = n then a else 0 := rfl
@[simp] lemma coeff_monomial' (n : σ →₀ ℕ) (a : α) :
coeff n (monomial n a) = a := if_pos rfl
/-- The constant multivariate formal power series.-/
def C (a : α) : mv_power_series σ α := monomial 0 a
lemma coeff_C (n : σ →₀ ℕ) (a : α) :
coeff n (C a : mv_power_series σ α) = if n = 0 then a else 0 := rfl
@[simp] lemma coeff_C_zero (a : α) : coeff 0 (C a : mv_power_series σ α) = a :=
coeff_monomial' 0 a
@[simp] lemma monomial_zero (a : α) : (monomial 0 a : mv_power_series σ α) = C a := rfl
/-- The variables of the multivariate formal power series ring.-/
def X (s : σ) : mv_power_series σ α := monomial (single s 1) 1
lemma coeff_X (n : σ →₀ ℕ) (s : σ) :
coeff n (X s : mv_power_series σ α) = if n = (single s 1) then 1 else 0 := rfl
lemma coeff_X' (s t : σ) :
coeff (single t 1) (X s : mv_power_series σ α) = if t = s then 1 else 0 :=
by { simp only [coeff_X, single_right_inj one_ne_zero], split_ifs; refl }
@[simp] lemma coeff_X'' (s : σ) :
coeff (single s 1) (X s : mv_power_series σ α) = 1 :=
by rw [coeff_X', if_pos rfl]
section ring_structure
variables (σ) (α) (n : σ →₀ ℕ) (φ ψ : mv_power_series σ α)
protected def zero : mv_power_series σ α := λ n, 0
instance : has_zero (mv_power_series σ α) := ⟨mv_power_series.zero σ α⟩
@[simp] lemma coeff_zero : coeff n (0 : mv_power_series σ α) = 0 := rfl
@[simp] lemma C_zero : (C 0 : mv_power_series σ α) = 0 :=
ext $ λ n, if h : n = 0 then by simp [h] else by rw [coeff_C, if_neg h, coeff_zero]
protected def one : mv_power_series σ α := C 1
instance : has_one (mv_power_series σ α) := ⟨mv_power_series.one σ α⟩
@[simp] lemma coeff_one :
coeff n (1 : mv_power_series σ α) = if n = 0 then 1 else 0 := rfl
@[simp] lemma coeff_one_zero : coeff 0 (1 : mv_power_series σ α) = 1 :=
coeff_C_zero 1
@[simp] lemma C_one : (C 1 : mv_power_series σ α) = 1 := rfl
protected def add (φ ψ : mv_power_series σ α) : mv_power_series σ α :=
λ n, coeff n φ + coeff n ψ
instance : has_add (mv_power_series σ α) := ⟨mv_power_series.add σ α⟩
variables {σ α}
@[simp] lemma coeff_add : coeff n (φ + ψ) = coeff n φ + coeff n ψ := rfl
protected lemma zero_add : (0 : mv_power_series σ α) + φ = φ := ext $ λ n, zero_add _
protected lemma add_zero : φ + 0 = φ := ext $ λ n, add_zero _
protected lemma add_comm : φ + ψ = ψ + φ := ext $ λ n, add_comm _ _
protected lemma add_assoc (φ₁ φ₂ φ₃ : mv_power_series σ α) :
(φ₁ + φ₂) + φ₃ = φ₁ + (φ₂ + φ₃) := ext $ λ n, add_assoc _ _ _
@[simp] lemma monomial_add (n : σ →₀ ℕ) (a b : α) :
(monomial n (a + b) : mv_power_series σ α) = monomial n a + monomial n b :=
ext $ λ m, if h : m = n then by simp [h] else by simp [coeff_monomial, if_neg h]
@[simp] lemma C_add (a b : α) : (C (a + b) : mv_power_series σ α) = C a + C b :=
monomial_add 0 a b
variables (σ α)
protected def mul (φ ψ : mv_power_series σ α) : mv_power_series σ α :=
λ n, (finsupp.antidiagonal n).support.sum (λ p, coeff p.1 φ * coeff p.2 ψ)
instance : has_mul (mv_power_series σ α) := ⟨mv_power_series.mul σ α⟩
variables {σ α}
lemma coeff_mul :
coeff n (φ * ψ) = (finsupp.antidiagonal n).support.sum (λ p, coeff p.1 φ * coeff p.2 ψ) := rfl
@[simp] lemma C_mul (a b : α) : (C (a * b) : mv_power_series σ α) = C a * C b :=
ext $ λ n,
begin
rw [coeff_C, coeff_mul],
split_ifs,
{ subst n, erw [antidiagonal_zero, finset.sum_singleton, coeff_C_zero, coeff_C_zero] },
{ rw finset.sum_eq_zero,
rintros ⟨i,j⟩ hij,
rw mem_antidiagonal_support at hij, rw [coeff_C, coeff_C],
split_ifs; simp * at * }
end
protected lemma zero_mul : (0 : mv_power_series σ α) * φ = 0 :=
ext $ λ n, by simp [coeff_mul]
protected lemma mul_zero : φ * 0 = 0 :=
ext $ λ n, by simp [coeff_mul]
protected lemma one_mul : (1 : mv_power_series σ α) * φ = φ :=
ext $ λ n,
begin
rw [coeff_mul, finset.sum_eq_single ((0 : σ →₀ ℕ), n)],
{ rw [coeff_one_zero, one_mul] },
{ rintros ⟨i,j⟩ hij h,
suffices : i ≠ 0,
{ rw [coeff_one, if_neg this, zero_mul] },
rw [mem_antidiagonal_support] at hij,
rw [ne.def, prod.mk.inj_iff, not_and] at h,
intro H, apply h H, rw [← hij, H, zero_add] },
{ intro H, exfalso, apply H,
rw [mem_antidiagonal_support, zero_add] }
end
protected lemma mul_one : φ * 1 = φ :=
ext $ λ n,
begin
rw [coeff_mul, finset.sum_eq_single (n, (0 : σ →₀ ℕ))],
{ rw [coeff_one_zero, mul_one] },
{ rintros ⟨i,j⟩ hij h,
suffices : j ≠ 0,
{ rw [coeff_one, if_neg this, mul_zero] },
rw [mem_antidiagonal_support] at hij,
rw [ne.def, prod.mk.inj_iff, not_and] at h,
intro H, apply h _ H, rw [← hij, H, add_zero] },
{ intro H, exfalso, apply H,
rw [mem_antidiagonal_support, add_zero] }
end
protected lemma mul_add (φ₁ φ₂ φ₃ : mv_power_series σ α) :
φ₁ * (φ₂ + φ₃) = φ₁ * φ₂ + φ₁ * φ₃ :=
ext $ λ n, by simp only [coeff_mul, coeff_add, mul_add, finset.sum_add_distrib]
protected lemma add_mul (φ₁ φ₂ φ₃ : mv_power_series σ α) :
(φ₁ + φ₂) * φ₃ = φ₁ * φ₃ + φ₂ * φ₃ :=
ext $ λ n, by simp only [coeff_mul, coeff_add, add_mul, finset.sum_add_distrib]
protected lemma mul_assoc (φ₁ φ₂ φ₃ : mv_power_series σ α) :
(φ₁ * φ₂) * φ₃ = φ₁ * (φ₂ * φ₃) :=
ext $ λ n,
begin
simp only [coeff_mul],
have := @finset.sum_sigma ((σ →₀ ℕ) × (σ →₀ ℕ)) α _ _ (antidiagonal n).support
(λ p, (antidiagonal (p.1)).support) (λ x, coeff x.2.1 φ₁ * coeff x.2.2 φ₂ * coeff x.1.2 φ₃),
convert this.symm using 1; clear this,
{ apply finset.sum_congr rfl,
intros p hp, exact finset.sum_mul },
have := @finset.sum_sigma ((σ →₀ ℕ) × (σ →₀ ℕ)) α _ _ (antidiagonal n).support
(λ p, (antidiagonal (p.2)).support) (λ x, coeff x.1.1 φ₁ * (coeff x.2.1 φ₂ * coeff x.2.2 φ₃)),
convert this.symm using 1; clear this,
{ apply finset.sum_congr rfl, intros p hp, rw finset.mul_sum },
apply finset.sum_bij,
swap 5,
{ rintros ⟨⟨i,j⟩, ⟨k,l⟩⟩ H, exact ⟨(k, l+j), (l, j)⟩ },
{ rintros ⟨⟨i,j⟩, ⟨k,l⟩⟩ H,
simp only [finset.mem_sigma, mem_antidiagonal_support] at H ⊢, finish },
{ rintros ⟨⟨i,j⟩, ⟨k,l⟩⟩ H, rw mul_assoc },
{ rintros ⟨⟨a,b⟩, ⟨c,d⟩⟩ ⟨⟨i,j⟩, ⟨k,l⟩⟩ H₁ H₂,
simp only [finset.mem_sigma, mem_antidiagonal_support,
and_imp, prod.mk.inj_iff, add_comm, heq_iff_eq] at H₁ H₂ ⊢,
finish },
{ rintros ⟨⟨i,j⟩, ⟨k,l⟩⟩ H, refine ⟨⟨(i+k, l), (i, k)⟩, _, _⟩;
{ simp only [finset.mem_sigma, mem_antidiagonal_support] at H ⊢, finish } }
end
instance : semiring (mv_power_series σ α) :=
{ mul_one := mv_power_series.mul_one,
one_mul := mv_power_series.one_mul,
add_assoc := mv_power_series.add_assoc,
zero_add := mv_power_series.zero_add,
add_zero := mv_power_series.add_zero,
add_comm := mv_power_series.add_comm,
mul_assoc := mv_power_series.mul_assoc,
mul_zero := mv_power_series.mul_zero,
zero_mul := mv_power_series.zero_mul,
left_distrib := mv_power_series.mul_add,
right_distrib := mv_power_series.add_mul,
.. mv_power_series.has_zero σ α,
.. mv_power_series.has_one σ α,
.. mv_power_series.has_add σ α,
.. mv_power_series.has_mul σ α }
end ring_structure
instance C.is_semiring_hom : is_semiring_hom (C : α → mv_power_series σ α) :=
{ map_zero := C_zero _ _,
map_one := C_one _ _,
map_add := C_add,
map_mul := C_mul }
instance coeff.is_add_monoid_hom (n : σ →₀ ℕ) :
is_add_monoid_hom (coeff n : mv_power_series σ α → α) :=
{ map_zero := coeff_zero _ _ _,
map_add := coeff_add n }
instance coeff_zero.is_semiring_hom :
is_semiring_hom (coeff 0 : mv_power_series σ α → α) :=
{ map_one := coeff_one_zero _ _,
map_mul := λ φ ψ, by simp [coeff_mul, support_single_ne_zero],
.. coeff.is_add_monoid_hom 0 }
/-- If a multivariate formal power series is invertible,
then so is its constant coefficient.-/
lemma is_unit_coeff_zero (φ : mv_power_series σ α) (h : is_unit φ) :
is_unit (coeff 0 φ) :=
h.map' (coeff 0)
instance : semimodule α (mv_power_series σ α) :=
{ smul := λ a φ, C a * φ,
one_smul := λ φ, one_mul _,
mul_smul := λ a b φ, by simp only [C_mul, mul_assoc],
smul_add := λ a φ ψ, mul_add _ _ _,
smul_zero := λ a, mul_zero _,
add_smul := λ a b φ, by simp only [C_add, add_mul],
zero_smul := λ φ, by simp only [zero_mul, C_zero] }
section map
variables {β : Type*} {γ : Type*} [semiring β] [semiring γ]
variables (f : α → β) (g : β → γ)
/-- The map between multivariate formal power series induced by a map on the coefficients.-/
def map : mv_power_series σ α → mv_power_series σ β :=
λ φ n, f $ coeff n φ
@[simp] lemma map_id : (map (id : α → α) :
mv_power_series σ α → mv_power_series σ α) = id := rfl
lemma map_comp : (map (g ∘ f) :
mv_power_series σ α → mv_power_series σ γ) = map g ∘ map f := rfl
@[simp] lemma coeff_map (n) (φ : mv_power_series σ α) :
coeff n (map f φ) = f (coeff n φ) := rfl
variables [is_semiring_hom f] [is_semiring_hom g]
@[simp] lemma map_zero : map f (0 : mv_power_series σ α) = 0 :=
ext $ λ n, is_semiring_hom.map_zero f
@[simp] lemma map_one : map f (1 : mv_power_series σ α) = 1 :=
ext $ λ n, if h : n = 0
then by rw [coeff_map, h, coeff_one_zero, is_semiring_hom.map_one f, coeff_one_zero]
else by rw [coeff_map, coeff_one, if_neg h, is_semiring_hom.map_zero f, coeff_one, if_neg h]
@[simp] lemma map_add (φ ψ : mv_power_series σ α) : map f (φ + ψ) = map f φ + map f ψ :=
ext $ λ n, by rw [coeff_map, coeff_add, is_semiring_hom.map_add f, coeff_add, coeff_map, coeff_map]
@[simp] lemma map_mul (φ ψ : mv_power_series σ α) : map f (φ * ψ) = map f φ * map f ψ :=
ext $ λ n,
begin
rw [coeff_map, coeff_mul, ← finset.sum_hom f, coeff_mul, finset.sum_congr rfl],
rintros ⟨i,j⟩ hij, rw [is_semiring_hom.map_mul f, coeff_map, coeff_map]
end
instance map.is_semiring_hom :
is_semiring_hom (map f : mv_power_series σ α → mv_power_series σ β) :=
{ map_zero := map_zero f,
map_one := map_one f,
map_add := map_add f,
map_mul := map_mul f }
end map
end semiring
section comm_semiring
variables [comm_semiring α]
variables (φ ψ : mv_power_series σ α)
protected lemma mul_comm : φ * ψ = ψ * φ :=
ext $ λ n, finset.sum_bij (λ p hp, p.swap)
(λ p hp, swap_mem_antidiagonal_support hp)
(λ p hp, mul_comm _ _)
(λ p q hp hq H, by simpa using congr_arg prod.swap H)
(λ p hp, ⟨p.swap, swap_mem_antidiagonal_support hp, p.swap_swap.symm⟩)
instance : comm_semiring (mv_power_series σ α) :=
{ mul_comm := mv_power_series.mul_comm,
.. mv_power_series.semiring }
section trunc
variables [decidable_eq α] (n : σ →₀ ℕ)
/-- The `n`th truncation of a multivariate formal power series to a multivariate polynomial -/
def trunc (φ : mv_power_series σ α) : mv_polynomial σ α :=
{ support := (n.antidiagonal.support.image prod.fst).filter (λ m, coeff m φ ≠ 0),
to_fun := λ m, if m ≤ n then coeff m φ else 0,
mem_support_to_fun := λ m,
begin
suffices : m ∈ finset.image prod.fst ((antidiagonal n).support) ↔ m ≤ n,
{ rw [finset.mem_filter, this], split,
{ intro h, rw [if_pos h.1], exact h.2 },
{ intro h, split_ifs at h with H H,
{ exact ⟨H, h⟩ },
{ exfalso, exact h rfl } } },
rw finset.mem_image, split,
{ rintros ⟨⟨i,j⟩, h, rfl⟩ s,
rw finsupp.mem_antidiagonal_support at h,
rw ← h, exact nat.le_add_right _ _ },
{ intro h, refine ⟨(m, n-m), _, rfl⟩,
rw finsupp.mem_antidiagonal_support, ext s, exact nat.add_sub_of_le (h s) }
end }
lemma coeff_trunc (m) (φ : mv_power_series σ α) :
mv_polynomial.coeff m (trunc n φ) =
if m ≤ n then coeff m φ else 0 := rfl
@[simp] lemma trunc_zero : trunc n (0 : mv_power_series σ α) = 0 :=
mv_polynomial.ext _ _ $ λ m,
begin
rw [coeff_trunc, coeff_zero, mv_polynomial.coeff_zero],
split_ifs; refl
end
@[simp] lemma trunc_one : trunc n (1 : mv_power_series σ α) = 1 :=
mv_polynomial.ext _ _ $ λ m,
begin
rw [coeff_trunc, coeff_one],
split_ifs with H H' H',
{ subst m, exact rfl },
{ symmetry, exact if_neg (ne.elim (ne.symm H')) },
{ symmetry, refine if_neg _,
intro H', apply H, subst m, intro s, exact nat.zero_le _ }
end
@[simp] lemma trunc_C (a : α) : trunc n (C a) = mv_polynomial.C a :=
mv_polynomial.ext _ _ $ λ m,
begin
rw [coeff_trunc, coeff_C, mv_polynomial.coeff_C],
split_ifs with H; refl <|> try {simp * at *},
exfalso, apply H, subst m, intro s, exact nat.zero_le _
end
@[simp] lemma trunc_add (φ ψ : mv_power_series σ α) :
trunc n (φ + ψ) = trunc n φ + trunc n ψ :=
mv_polynomial.ext _ _ $ λ m,
begin
simp only [coeff_trunc, coeff_add, mv_polynomial.coeff_add],
split_ifs with H, {refl}, {rw [zero_add]}
end
end trunc
end comm_semiring
section ring
variables [ring α]
protected def neg (φ : mv_power_series σ α) :
mv_power_series σ α := λ n, - coeff n φ
instance : has_neg (mv_power_series σ α) := ⟨mv_power_series.neg⟩
@[simp] lemma coeff_neg (φ : mv_power_series σ α) (n) : coeff n (- φ) = - coeff n φ := rfl
protected lemma add_left_neg (φ : mv_power_series σ α) : (-φ) + φ = 0 :=
ext $ λ n, by rw [coeff_add, coeff_zero, coeff_neg, add_left_neg]
instance : ring (mv_power_series σ α) :=
{ add_left_neg := mv_power_series.add_left_neg,
.. mv_power_series.has_neg, .. mv_power_series.semiring }
instance C.is_ring_hom : is_ring_hom (C : α → mv_power_series σ α) :=
{ map_one := C_one _ _,
map_add := C_add,
map_mul := C_mul }
instance coeff.is_add_group_hom (n : σ →₀ ℕ) :
is_add_group_hom (coeff n : mv_power_series σ α → α) :=
{ map_add := coeff_add n }
instance map.is_ring_hom {β : Type*} [comm_ring β] (f : α → β) [is_ring_hom f] :
is_ring_hom (map f : mv_power_series σ α → mv_power_series σ β) :=
{ .. map.is_semiring_hom f }
instance : module α (mv_power_series σ α) :=
{ ..mv_power_series.semimodule }
/-
The inverse of a multivariate formal power series is defined by
well-founded recursion on the coeffients of the inverse.
-/
/-- Auxiliary definition that unifies
the totalised inverse formal power series `(_)⁻¹` and
the inverse formal power series that depends on
an inverse of the constant coefficient `inv_of_unit`.-/
protected def inv.aux (a : α) (φ : mv_power_series σ α) : mv_power_series σ α
| n := if n = 0 then a else
- a * n.antidiagonal.support.sum (λ (x : (σ →₀ ℕ) × (σ →₀ ℕ)),
if h : x.2 < n then coeff x.1 φ * inv.aux x.2 else 0)
using_well_founded
{ rel_tac := λ _ _, `[exact ⟨_, finsupp.lt_wf σ⟩],
dec_tac := tactic.assumption }
lemma coeff_inv_aux (n : σ →₀ ℕ) (a : α) (φ : mv_power_series σ α) :
coeff n (inv.aux a φ) = if n = 0 then a else
- a * n.antidiagonal.support.sum (λ (x : (σ →₀ ℕ) × (σ →₀ ℕ)),
if x.2 < n then coeff x.1 φ * coeff x.2 (inv.aux a φ) else 0) :=
by rw [coeff, inv.aux]; refl
/-- A multivariate formal power series is invertible if the constant coefficient is invertible.-/
def inv_of_unit (φ : mv_power_series σ α) (u : units α) : mv_power_series σ α :=
inv.aux (↑u⁻¹) φ
lemma coeff_inv_of_unit (n : σ →₀ ℕ) (φ : mv_power_series σ α) (u : units α) :
coeff n (inv_of_unit φ u) = if n = 0 then ↑u⁻¹ else
- ↑u⁻¹ * n.antidiagonal.support.sum (λ (x : (σ →₀ ℕ) × (σ →₀ ℕ)),
if x.2 < n then coeff x.1 φ * coeff x.2 (inv_of_unit φ u) else 0) :=
coeff_inv_aux n (↑u⁻¹) φ
@[simp] lemma coeff_zero_inv_of_unit (φ : mv_power_series σ α) (u : units α) :
coeff (0 : σ →₀ ℕ) (inv_of_unit φ u) = ↑u⁻¹ :=
by rw [coeff_inv_of_unit, if_pos rfl]
lemma mul_inv_of_unit (φ : mv_power_series σ α) (u : units α) (h : coeff 0 φ = u) :
φ * inv_of_unit φ u = 1 :=
ext $ λ n,
if H : n = 0 then
by erw [H, coeff_mul, coeff_one_zero, finsupp.antidiagonal_zero,
finset.sum_singleton, coeff_zero_inv_of_unit, h, units.mul_inv]
else
begin
have : ((0 : σ →₀ ℕ), n) ∈ n.antidiagonal.support,
{ rw [finsupp.mem_antidiagonal_support, zero_add] },
rw [coeff_one, if_neg H, coeff_mul,
← finset.insert_erase this, finset.sum_insert (finset.not_mem_erase _ _),
h, coeff_inv_of_unit, if_neg H,
neg_mul_eq_neg_mul_symm, mul_neg_eq_neg_mul_symm, units.mul_inv_cancel_left,
← finset.insert_erase this, finset.sum_insert (finset.not_mem_erase _ _),
finset.insert_erase this, if_neg (not_lt_of_ge $ le_refl _), zero_add, add_comm,
← sub_eq_add_neg, sub_eq_zero, finset.sum_congr rfl],
rintros ⟨i,j⟩ hij, rw [finset.mem_erase, finsupp.mem_antidiagonal_support] at hij,
cases hij with h₁ h₂,
subst n, rw if_pos,
suffices : (0 : _) + j < i + j, {simpa},
apply add_lt_add_right,
split,
{ intro s, exact nat.zero_le _ },
{ intro H, apply h₁,
suffices : i = 0, {simp [this]},
ext1 s, exact nat.eq_zero_of_le_zero (H s) }
end
end ring
section comm_ring
variables [comm_ring α]
instance : comm_ring (mv_power_series σ α) :=
{ .. mv_power_series.comm_semiring, .. mv_power_series.ring }
instance : algebra α (mv_power_series σ α) :=
{ to_fun := C,
commutes' := λ _ _, mul_comm _ _,
smul_def' := λ c p, rfl,
.. mv_power_series.module }
/-- Multivariate formal power series over a local ring form a local ring.-/
def is_local_ring (h : is_local_ring α) : is_local_ring (mv_power_series σ α) :=
begin
split,
{ intro H, apply ‹is_local_ring α›.1, simpa using congr_arg (coeff 0) H },
{ intro φ, have := ‹is_local_ring α›.2 (coeff 0 φ),
cases this with h h; [left, right]; cases h with u h;
{ exact is_unit_of_mul_one _ _ (mul_inv_of_unit _ _ h) } }
end
-- TODO(jmc): once adic topology lands, show that this is complete
end comm_ring
section local_ring
variables {β : Type*} (f : α → β)
variables [local_ring α] [local_ring β] [is_local_ring_hom f]
instance : local_ring (mv_power_series σ α) :=
local_of_is_local_ring $ is_local_ring ⟨zero_ne_one, local_ring.is_local⟩
instance map.is_local_ring_hom :
is_local_ring_hom (map f : mv_power_series σ α → mv_power_series σ β) :=
{ map_nonunit :=
begin
rintros φ ⟨ψ, h⟩,
replace h := congr_arg (coeff 0) h,
rw coeff_map at h,
have : is_unit (coeff 0 ↑ψ) := @is_unit_coeff_zero σ β _ _ (↑ψ) (is_unit_unit ψ),
rw ← h at this,
rcases is_unit_of_map_unit f _ this with ⟨c, hc⟩,
exact is_unit_of_mul_one φ (inv_of_unit φ c) (mul_inv_of_unit φ c hc)
end,
.. map.is_ring_hom f }
end local_ring
section discrete_field
variables [discrete_field α]
protected def inv (φ : mv_power_series σ α) : mv_power_series σ α :=
inv.aux (coeff 0 φ)⁻¹ φ
instance : has_inv (mv_power_series σ α) := ⟨mv_power_series.inv⟩
lemma coeff_inv (n) (φ : mv_power_series σ α) :
coeff n (φ⁻¹) = if n = 0 then (coeff 0 φ)⁻¹ else
- (coeff 0 φ)⁻¹ * n.antidiagonal.support.sum (λ (x : (σ →₀ ℕ) × (σ →₀ ℕ)),
if x.2 < n then coeff x.1 φ * coeff x.2 (φ⁻¹) else 0) :=
coeff_inv_aux n _ φ
@[simp] lemma coeff_zero_inv (φ : mv_power_series σ α) :
coeff 0 (φ⁻¹) = (coeff 0 φ)⁻¹ :=
by rw [coeff_inv, if_pos rfl]
lemma inv_eq_zero {φ : mv_power_series σ α} :
φ⁻¹ = 0 ↔ coeff 0 φ = 0 :=
⟨λ h, by simpa using congr_arg (coeff 0) h,
λ h, ext $ λ n, by { rw coeff_inv, split_ifs;
simp only [h, mv_power_series.coeff_zero, zero_mul, inv_zero, neg_zero] }⟩
@[simp] lemma inv_of_unit_eq (φ : mv_power_series σ α) (h : coeff 0 φ ≠ 0) :
inv_of_unit φ (units.mk0 _ h) = φ⁻¹ := rfl
@[simp] lemma inv_of_unit_eq' (φ : mv_power_series σ α) (u : units α) (h : coeff 0 φ = u) :
inv_of_unit φ u = φ⁻¹ :=
begin
rw ← inv_of_unit_eq φ (h.symm ▸ u.ne_zero),
congr' 1, rw [units.ext_iff], exact h.symm,
end
@[simp] protected lemma mul_inv (φ : mv_power_series σ α) (h : coeff 0 φ ≠ 0) :
φ * φ⁻¹ = 1 :=
by rw [← inv_of_unit_eq φ h, mul_inv_of_unit φ (units.mk0 _ h) rfl]
@[simp] protected lemma inv_mul (φ : mv_power_series σ α) (h : coeff 0 φ ≠ 0) :
φ⁻¹ * φ = 1 :=
by rw [mul_comm, φ.mul_inv h]
end discrete_field
end mv_power_series
namespace mv_polynomial
open finsupp
variables {σ : Type*} {α : Type*} [decidable_eq σ] [decidable_eq α] [comm_semiring α]
/-- The natural inclusion from multivariate polynomials into multivariate formal power series.-/
def to_mv_power_series (φ : mv_polynomial σ α) : mv_power_series σ α :=
λ n, coeff n φ
@[simp] lemma to_mv_power_series_coeff (φ : mv_polynomial σ α) (n) :
mv_power_series.coeff n (φ.to_mv_power_series) = coeff n φ := rfl
namespace to_mv_power_series
instance :
is_semiring_hom (to_mv_power_series : mv_polynomial σ α → mv_power_series σ α) :=
{ map_zero := mv_power_series.ext $ λ n, by simp,
map_one := mv_power_series.ext $ λ n,
begin
rw [to_mv_power_series_coeff, mv_power_series.coeff_one],
split_ifs; rw ← C_1; simp [-C_1, h],
{ rw ← ne_from_not_eq at h, simp [h.symm] }
end,
map_add := λ φ ψ, mv_power_series.ext $ λ n, by simp,
map_mul := λ φ ψ, mv_power_series.ext $ λ n,
by simp only [to_mv_power_series_coeff, mv_power_series.coeff_mul, coeff_mul] }
end to_mv_power_series
end mv_polynomial
/-- Formal power series over the coefficient ring `α`.-/
def power_series (α : Type*) := mv_power_series unit α
namespace power_series
open finsupp (single)
variable {α : Type*}
/-- The `n`th coefficient of a formal power series.-/
def coeff (n : ℕ) : power_series α → α := mv_power_series.coeff (single () n)
/-- Two formal power series are equal if all their coefficients are equal.-/
@[extensionality] lemma ext {φ ψ : power_series α} (h : ∀ n, coeff n φ = coeff n ψ) :
φ = ψ :=
mv_power_series.ext $ λ n,
have this : n = single () (n ()), from (finsupp.unique_single n),
by convert h (n ())
/-- Two formal power series are equal if all their coefficients are equal.-/
lemma ext_iff {φ ψ : power_series α} : φ = ψ ↔ (∀ n, coeff n φ = coeff n ψ) :=
⟨λ h n, congr_arg (coeff n) h, ext⟩
/-- Constructor for formal power series.-/
def mk (f : ℕ → α) : power_series α := λ s, f (s ())
@[simp] lemma coeff_mk (n : ℕ) (f : ℕ → α) : coeff n (mk f) = f n := rfl
section comm_semiring
variable [comm_semiring α]
instance : comm_semiring (power_series α) := by delta power_series; apply_instance
/-- The `n`th monimial with coefficient `a` as formal power series.-/
def monomial (n : ℕ) : α → power_series α := mv_power_series.monomial (single () n)
/-- The constant formal power series.-/
def C : α → power_series α := mv_power_series.C
/-- The variable of the formal power series ring.-/
def X : power_series α := mv_power_series.X ()
lemma coeff_monomial (m n : ℕ) (a : α) :
coeff m (monomial n a) = if m = n then a else 0 :=
calc coeff m (monomial n a) = _ : mv_power_series.coeff_monomial _ _ _
... = if m = n then a else 0 :
by { simp only [finsupp.unique_single_eq_iff], split_ifs; refl }
lemma monomial_eq_mk (n : ℕ) (a : α) :
monomial n a = mk (λ m, if m = n then a else 0) :=
ext $ λ m, coeff_monomial _ _ _
@[simp] lemma coeff_monomial' (n : ℕ) (a : α) :
coeff n (monomial n a) = a := if_pos rfl
lemma coeff_C (n : ℕ) (a : α) :
coeff n (C a : power_series α) = if n = 0 then a else 0 :=
calc coeff n (C a) = _ : mv_power_series.coeff_C _ _
... = if n = 0 then a else 0 :
by { simp only [finsupp.single_eq_zero], split_ifs; refl }
@[simp] lemma coeff_C_zero (a : α) : coeff 0 (C a) = a :=
coeff_monomial' 0 a
@[simp] lemma monomial_zero (a : α) : (monomial 0 a : power_series α) = C a := rfl
lemma coeff_X (n : ℕ) :
coeff n (X : power_series α) = if n = 1 then 1 else 0 :=
calc coeff n (X : power_series α) = _ : mv_power_series.coeff_X _ _
... = if n = 1 then 1 else 0 :
by { simp only [finsupp.unique_single_eq_iff], split_ifs; refl }
@[simp] lemma coeff_X' : coeff 1 (X : power_series α) = 1 :=
by rw [coeff_X, if_pos rfl]
@[simp] lemma coeff_zero (n : ℕ) : coeff n (0 : power_series α) = 0 := rfl
@[simp] lemma C_zero : (C 0 : power_series α) = 0 := mv_power_series.C_zero _ _
@[simp] lemma coeff_one (n : ℕ) :
coeff n (1 : power_series α) = if n = 0 then 1 else 0 :=
calc coeff n (1 : power_series α) = _ : mv_power_series.coeff_one _ _ _
... = if n = 0 then 1 else 0 :
by { simp only [finsupp.single_eq_zero], split_ifs; refl }
@[simp] lemma coeff_one_zero : coeff 0 (1 : power_series α) = 1 :=
coeff_C_zero 1
@[simp] lemma C_one : (C 1 : power_series α) = 1 := rfl
@[simp] lemma coeff_add (n : ℕ) (φ ψ : power_series α) :
coeff n (φ + ψ) = coeff n φ + coeff n ψ := rfl
@[simp] lemma monomial_add (n : ℕ) (a b : α) :
(monomial n (a + b) : power_series α) = monomial n a + monomial n b :=
mv_power_series.monomial_add _ _ _
@[simp] lemma C_add (a b : α) : (C (a + b) : power_series α) = C a + C b :=
monomial_add 0 a b
lemma coeff_mul (n : ℕ) (φ ψ : power_series α) :
coeff n (φ * ψ) = (finset.nat.antidiagonal n).sum (λ p, coeff p.1 φ * coeff p.2 ψ) :=
begin
symmetry,
apply finset.sum_bij (λ (p : ℕ × ℕ) h, (single () p.1, single () p.2)),
{ rintros ⟨i,j⟩ hij, rw finset.nat.mem_antidiagonal at hij,
rw [finsupp.mem_antidiagonal_support, ← finsupp.single_add, hij] },
{ rintros ⟨i,j⟩ hij, refl },
{ rintros ⟨i,j⟩ ⟨k,l⟩ hij hkl,
simpa only [prod.mk.inj_iff, finsupp.unique_single_eq_iff] using id },
{ rintros ⟨f,g⟩ hfg,
refine ⟨(f (), g ()), _, _⟩,
{ rw finsupp.mem_antidiagonal_support at hfg,
rw [finset.nat.mem_antidiagonal, ← finsupp.add_apply, hfg, finsupp.single_eq_same] },
{ rw prod.mk.inj_iff, dsimp,
exact ⟨finsupp.unique_single f, finsupp.unique_single g⟩ } }
end
@[simp] lemma C_mul (a b : α) : (C (a * b) : power_series α) = C a * C b :=
mv_power_series.C_mul _ _
instance C.is_semiring_hom : is_semiring_hom (C : α → power_series α) :=
mv_power_series.C.is_semiring_hom
instance coeff.is_add_monoid_hom (n : ℕ) :
is_add_monoid_hom (coeff n : power_series α → α) :=
{ map_zero := coeff_zero n,
map_add := coeff_add n }
instance : semimodule α (power_series α) :=
mv_power_series.semimodule
section map
variables {β : Type*} {γ : Type*} [comm_semiring β] [comm_semiring γ]
variables (f : α → β) (g : β → γ)
/-- The map between formal power series induced by a map on the coefficients.-/
def map : power_series α → power_series β :=
mv_power_series.map f
@[simp] lemma map_id : (map (id : α → α) :
power_series α → power_series α) = id := rfl
lemma map_comp : (map (g ∘ f) :
power_series α → power_series γ) = map g ∘ map f := rfl
@[simp] lemma coeff_map (n : ℕ) (φ : power_series α) :
coeff n (map f φ) = f (coeff n φ) := rfl
variables [is_semiring_hom f] [is_semiring_hom g]
@[simp] lemma map_zero : map f (0 : power_series α) = 0 :=
mv_power_series.map_zero f
@[simp] lemma map_one : map f (1 : power_series α) = 1 :=
mv_power_series.map_one f
@[simp] lemma map_add (φ ψ : power_series α) : map f (φ + ψ) = map f φ + map f ψ :=
mv_power_series.map_add f φ ψ
@[simp] lemma map_mul (φ ψ : power_series α) : map f (φ * ψ) = map f φ * map f ψ :=
mv_power_series.map_mul f φ ψ
instance map.is_semiring_hom :
is_semiring_hom (map f : power_series α → power_series β) :=
mv_power_series.map.is_semiring_hom f
end map
section trunc
variables [decidable_eq α] (n : ℕ)
/-- The `n`th truncation of a formal power series to a polynomial -/
def trunc (φ : power_series α) : polynomial α :=
{ support := ((finset.nat.antidiagonal n).image prod.fst).filter (λ m, coeff m φ ≠ 0),
to_fun := λ m, if m ≤ n then coeff m φ else 0,
mem_support_to_fun := λ m,
begin
suffices : m ∈ ((finset.nat.antidiagonal n).image prod.fst) ↔ m ≤ n,
{ rw [finset.mem_filter, this], split,
{ intro h, rw [if_pos h.1], exact h.2 },
{ intro h, split_ifs at h with H H,
{ exact ⟨H, h⟩ },
{ exfalso, exact h rfl } } },
rw finset.mem_image, split,
{ rintros ⟨⟨i,j⟩, h, rfl⟩,
rw finset.nat.mem_antidiagonal at h,
rw ← h, exact nat.le_add_right _ _ },
{ intro h, refine ⟨(m, n-m), _, rfl⟩,
rw finset.nat.mem_antidiagonal, exact nat.add_sub_of_le h }
end }
lemma coeff_trunc (m) (φ : power_series α) :
polynomial.coeff (trunc n φ) m = if m ≤ n then coeff m φ else 0 := rfl
@[simp] lemma trunc_zero : trunc n (0 : power_series α) = 0 :=
polynomial.ext.2 $ λ m,
begin
rw [coeff_trunc, coeff_zero, polynomial.coeff_zero],
split_ifs; refl
end
@[simp] lemma trunc_one : trunc n (1 : power_series α) = 1 :=
polynomial.ext.2 $ λ m,
begin
rw [coeff_trunc, coeff_one],
split_ifs with H H' H',
{ subst m, exact rfl },
{ symmetry, exact if_neg (ne.elim (ne.symm H')) },
{ symmetry, refine if_neg _,
intro H', apply H, subst m, exact nat.zero_le _ }
end
@[simp] lemma trunc_C (a : α) : trunc n (C a) = polynomial.C a :=
polynomial.ext.2 $ λ m,
begin
rw [coeff_trunc, coeff_C, polynomial.coeff_C],
split_ifs with H; refl <|> try {simp * at *}
end
@[simp] lemma trunc_add (φ ψ : power_series α) :
trunc n (φ + ψ) = trunc n φ + trunc n ψ :=
polynomial.ext.2 $ λ m,
begin
simp only [coeff_trunc, coeff_add, polynomial.coeff_add],
split_ifs with H, {refl}, {rw [zero_add]}
end
end trunc
end comm_semiring
section comm_ring
variables [comm_ring α]
instance : comm_ring (power_series α) := by delta power_series; apply_instance
instance C.is_ring_hom : is_ring_hom (C : α → power_series α) :=
mv_power_series.C.is_ring_hom
instance map.is_ring_hom {β : Type*} [comm_ring β] (f : α → β) [is_ring_hom f] :
is_ring_hom (map f : power_series α → power_series β) :=
{ .. map.is_semiring_hom f }
instance : module α (power_series α) :=
mv_power_series.module
instance : algebra α (power_series α) :=
mv_power_series.algebra
protected def inv.aux : α → power_series α → power_series α :=
mv_power_series.inv.aux
lemma coeff_inv_aux (n : ℕ) (a : α) (φ : power_series α) :
coeff n (inv.aux a φ) = if n = 0 then a else
- a * (finset.nat.antidiagonal n).sum (λ (x : ℕ × ℕ),
if x.2 < n then coeff x.1 φ * coeff x.2 (inv.aux a φ) else 0) :=
begin
rw [coeff, inv.aux, mv_power_series.coeff_inv_aux],
simp only [finsupp.single_eq_zero],
split_ifs, {refl},
congr' 1,
symmetry,
apply finset.sum_bij (λ (p : ℕ × ℕ) h, (single () p.1, single () p.2)),
{ rintros ⟨i,j⟩ hij, rw finset.nat.mem_antidiagonal at hij,
rw [finsupp.mem_antidiagonal_support, ← finsupp.single_add, hij] },
{ rintros ⟨i,j⟩ hij,
by_cases H : j < n,
{ rw [if_pos H, if_pos], {refl},
split,
{ rintro ⟨⟩, simpa [finsupp.single_eq_same] using le_of_lt H },
{ intro hh, rw lt_iff_not_ge at H, apply H,
simpa [finsupp.single_eq_same] using hh () } },
{ rw [if_neg H, if_neg], rintro ⟨h₁, h₂⟩, apply h₂, rintro ⟨⟩,
simpa [finsupp.single_eq_same] using not_lt.1 H } },
{ rintros ⟨i,j⟩ ⟨k,l⟩ hij hkl,
simpa only [prod.mk.inj_iff, finsupp.unique_single_eq_iff] using id },
{ rintros ⟨f,g⟩ hfg,
refine ⟨(f (), g ()), _, _⟩,
{ rw finsupp.mem_antidiagonal_support at hfg,
rw [finset.nat.mem_antidiagonal, ← finsupp.add_apply, hfg, finsupp.single_eq_same] },
{ rw prod.mk.inj_iff, dsimp,
exact ⟨finsupp.unique_single f, finsupp.unique_single g⟩ } }
end
/-- A formal power series is invertible if the constant coefficient is invertible.-/
def inv_of_unit (φ : power_series α) (u : units α) : power_series α :=
mv_power_series.inv_of_unit φ u
lemma coeff_inv_of_unit (n : ℕ) (φ : power_series α) (u : units α) :
coeff n (inv_of_unit φ u) = if n = 0 then ↑u⁻¹ else
- ↑u⁻¹ * (finset.nat.antidiagonal n).sum (λ (x : ℕ × ℕ),
if x.2 < n then coeff x.1 φ * coeff x.2 (inv_of_unit φ u) else 0) :=
coeff_inv_aux n ↑u⁻¹ φ
@[simp] lemma coeff_zero_inv_of_unit (φ : power_series α) (u : units α) :
coeff (0 : ℕ) (inv_of_unit φ u) = ↑u⁻¹ :=
by rw [coeff_inv_of_unit, if_pos rfl]
lemma mul_inv_of_unit (φ : power_series α) (u : units α) (h : coeff 0 φ = u) :
φ * inv_of_unit φ u = 1 :=
mv_power_series.mul_inv_of_unit φ u h
end comm_ring
section local_ring
variables [comm_ring α]
lemma is_local_ring (h : is_local_ring α) :
is_local_ring (power_series α) :=
mv_power_series.is_local_ring h
end local_ring
section local_ring
variables {β : Type*} (f : α → β)
variables [local_ring α] [local_ring β] [is_local_ring_hom f]
instance : local_ring (power_series α) :=
mv_power_series.local_ring
instance map.is_local_ring_hom :
is_local_ring_hom (map f : power_series α → power_series β) :=
mv_power_series.map.is_local_ring_hom f
end local_ring
section discrete_field
variables [discrete_field α]
protected def inv : power_series α → power_series α :=
mv_power_series.inv
instance : has_inv (power_series α) := ⟨power_series.inv⟩
lemma coeff_inv (n) (φ : power_series α) :
coeff n (φ⁻¹) = if n = 0 then (coeff 0 φ)⁻¹ else
- (coeff 0 φ)⁻¹ * (finset.nat.antidiagonal n).sum (λ (x : ℕ × ℕ),
if x.2 < n then coeff x.1 φ * coeff x.2 (φ⁻¹) else 0) :=
coeff_inv_aux n _ φ
@[simp] lemma coeff_zero_inv (φ : power_series α) :
coeff 0 (φ⁻¹) = (coeff 0 φ)⁻¹ :=
mv_power_series.coeff_zero_inv φ
lemma inv_eq_zero {φ : power_series α} :
φ⁻¹ = 0 ↔ coeff 0 φ = 0 :=
mv_power_series.inv_eq_zero
@[simp] lemma inv_of_unit_eq (φ : power_series α) (h : coeff 0 φ ≠ 0) :
inv_of_unit φ (units.mk0 _ h) = φ⁻¹ := rfl
@[simp] lemma inv_of_unit_eq' (φ : power_series α) (u : units α) (h : coeff 0 φ = u) :
inv_of_unit φ u = φ⁻¹ :=
mv_power_series.inv_of_unit_eq' φ u h
@[simp] protected lemma mul_inv (φ : power_series α) (h : coeff 0 φ ≠ 0) :
φ * φ⁻¹ = 1 :=
mv_power_series.mul_inv φ h
@[simp] protected lemma inv_mul (φ : power_series α) (h : coeff 0 φ ≠ 0) :
φ⁻¹ * φ = 1 :=
mv_power_series.inv_mul φ h
end discrete_field
end power_series
namespace polynomial
open finsupp
variables {σ : Type*} {α : Type*} [decidable_eq σ] [decidable_eq α] [comm_semiring α]
/-- The natural inclusion from polynomials into formal power series.-/
def to_power_series (φ : polynomial α) : power_series α :=
power_series.mk $ λ n, coeff φ n
@[simp] lemma to_power_series_coeff (φ : polynomial α) (n) :
power_series.coeff n (φ.to_power_series) = coeff φ n := rfl
namespace to_power_series
instance : is_semiring_hom (to_power_series : polynomial α → power_series α) :=
{ map_zero := power_series.ext $ λ n, by simp,
map_one := power_series.ext $ λ n,
begin
rw [to_power_series_coeff, polynomial.coeff_one, power_series.coeff_one],
split_ifs; refl <|> simp * at *
end,
map_add := λ φ ψ, power_series.ext $ λ n, by simp,
map_mul := λ φ ψ, power_series.ext $ λ n,
by simp only [to_power_series_coeff, power_series.coeff_mul, coeff_mul] }
end to_power_series
end polynomial
|
1d5a10b5da576d3cd727d3095c77eefc4c51521a | aa5a655c05e5359a70646b7154e7cac59f0b4132 | /stage0/src/Lean/Meta/Basic.lean | 23828299e46b9e3f487cbbbe60407c5df8a988c8 | [
"Apache-2.0"
] | permissive | lambdaxymox/lean4 | ae943c960a42247e06eff25c35338268d07454cb | 278d47c77270664ef29715faab467feac8a0f446 | refs/heads/master | 1,677,891,867,340 | 1,612,500,005,000 | 1,612,500,005,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 44,153 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Data.LOption
import Lean.Environment
import Lean.Class
import Lean.ReducibilityAttrs
import Lean.Util.Trace
import Lean.Util.RecDepth
import Lean.Util.PPExt
import Lean.Util.OccursCheck
import Lean.Compiler.InlineAttrs
import Lean.Meta.TransparencyMode
import Lean.Meta.DiscrTreeTypes
import Lean.Eval
import Lean.CoreM
/-
This module provides four (mutually dependent) goodies that are needed for building the elaborator and tactic frameworks.
1- Weak head normal form computation with support for metavariables and transparency modes.
2- Definitionally equality checking with support for metavariables (aka unification modulo definitional equality).
3- Type inference.
4- Type class resolution.
They are packed into the MetaM monad.
-/
namespace Lean.Meta
builtin_initialize isDefEqStuckExceptionId : InternalExceptionId ← registerInternalExceptionId `isDefEqStuck
structure Config where
foApprox : Bool := false
ctxApprox : Bool := false
quasiPatternApprox : Bool := false
/- When `constApprox` is set to true,
we solve `?m t =?= c` using
`?m := fun _ => c`
when `?m t` is not a higher-order pattern and `c` is not an application as -/
constApprox : Bool := false
/-
When the following flag is set,
`isDefEq` throws the exeption `Exeption.isDefEqStuck`
whenever it encounters a constraint `?m ... =?= t` where
`?m` is read only.
This feature is useful for type class resolution where
we may want to notify the caller that the TC problem may be solveable
later after it assigns `?m`. -/
isDefEqStuckEx : Bool := false
transparency : TransparencyMode := TransparencyMode.default
/- If zetaNonDep == false, then non dependent let-decls are not zeta expanded. -/
zetaNonDep : Bool := true
/- When `trackZeta == true`, we store zetaFVarIds all free variables that have been zeta-expanded. -/
trackZeta : Bool := false
unificationHints : Bool := true
structure ParamInfo where
implicit : Bool := false
instImplicit : Bool := false
hasFwdDeps : Bool := false
backDeps : Array Nat := #[]
deriving Inhabited
def ParamInfo.isExplicit (p : ParamInfo) : Bool :=
!p.implicit && !p.instImplicit
structure FunInfo where
paramInfo : Array ParamInfo := #[]
resultDeps : Array Nat := #[]
structure InfoCacheKey where
transparency : TransparencyMode
expr : Expr
nargs? : Option Nat
deriving Inhabited, BEq
namespace InfoCacheKey
instance : Hashable InfoCacheKey :=
⟨fun ⟨transparency, expr, nargs⟩ => mixHash (hash transparency) $ mixHash (hash expr) (hash nargs)⟩
end InfoCacheKey
open Std (PersistentArray PersistentHashMap)
abbrev SynthInstanceCache := PersistentHashMap Expr (Option Expr)
structure Cache where
inferType : PersistentExprStructMap Expr := {}
funInfo : PersistentHashMap InfoCacheKey FunInfo := {}
synthInstance : SynthInstanceCache := {}
whnfDefault : PersistentExprStructMap Expr := {} -- cache for closed terms and `TransparencyMode.default`
whnfAll : PersistentExprStructMap Expr := {} -- cache for closed terms and `TransparencyMode.all`
deriving Inhabited
structure PostponedEntry where
lhs : Level
rhs : Level
structure State where
mctx : MetavarContext := {}
cache : Cache := {}
/- When `trackZeta == true`, then any let-decl free variable that is zeta expansion performed by `MetaM` is stored in `zetaFVarIds`. -/
zetaFVarIds : NameSet := {}
postponed : PersistentArray PostponedEntry := {}
deriving Inhabited
structure Context where
config : Config := {}
lctx : LocalContext := {}
localInstances : LocalInstances := #[]
abbrev MetaM := ReaderT Context $ StateRefT State CoreM
instance : Inhabited (MetaM α) where
default := fun _ _ => arbitrary
instance : MonadLCtx MetaM where
getLCtx := return (← read).lctx
instance : MonadMCtx MetaM where
getMCtx := return (← get).mctx
modifyMCtx f := modify fun s => { s with mctx := f s.mctx }
instance : AddMessageContext MetaM where
addMessageContext := addMessageContextFull
@[inline] def MetaM.run (x : MetaM α) (ctx : Context := {}) (s : State := {}) : CoreM (α × State) :=
x ctx |>.run s
@[inline] def MetaM.run' (x : MetaM α) (ctx : Context := {}) (s : State := {}) : CoreM α :=
Prod.fst <$> x.run ctx s
@[inline] def MetaM.toIO (x : MetaM α) (ctxCore : Core.Context) (sCore : Core.State) (ctx : Context := {}) (s : State := {}) : IO (α × Core.State × State) := do
let ((a, s), sCore) ← (x.run ctx s).toIO ctxCore sCore
pure (a, sCore, s)
instance [MetaEval α] : MetaEval (MetaM α) :=
⟨fun env opts x _ => MetaEval.eval env opts x.run' true⟩
protected def throwIsDefEqStuck {α} : MetaM α :=
throw $ Exception.internal isDefEqStuckExceptionId
builtin_initialize
registerTraceClass `Meta
registerTraceClass `Meta.debug
@[inline] def liftMetaM [MonadLiftT MetaM m] (x : MetaM α) : m α :=
liftM x
@[inline] def mapMetaM [MonadControlT MetaM m] [Monad m] (f : forall {α}, MetaM α → MetaM α) {α} (x : m α) : m α :=
controlAt MetaM fun runInBase => f $ runInBase x
@[inline] def map1MetaM [MonadControlT MetaM m] [Monad m] (f : forall {α}, (β → MetaM α) → MetaM α) {α} (k : β → m α) : m α :=
controlAt MetaM fun runInBase => f fun b => runInBase $ k b
@[inline] def map2MetaM [MonadControlT MetaM m] [Monad m] (f : forall {α}, (β → γ → MetaM α) → MetaM α) {α} (k : β → γ → m α) : m α :=
controlAt MetaM fun runInBase => f fun b c => runInBase $ k b c
section Methods
variable {n : Type → Type} [MonadControlT MetaM n] [Monad n]
def getLocalInstances : MetaM LocalInstances :=
return (← read).localInstances
def getConfig : MetaM Config :=
return (← read).config
def setMCtx (mctx : MetavarContext) : MetaM Unit :=
modify fun s => { s with mctx := mctx }
def resetZetaFVarIds : MetaM Unit :=
modify fun s => { s with zetaFVarIds := {} }
def getZetaFVarIds : MetaM NameSet :=
return (← get).zetaFVarIds
def getPostponed : MetaM (PersistentArray PostponedEntry) :=
return (← get).postponed
def setPostponed (postponed : PersistentArray PostponedEntry) : MetaM Unit :=
modify fun s => { s with postponed := postponed }
@[inline] def modifyPostponed (f : PersistentArray PostponedEntry → PersistentArray PostponedEntry) : MetaM Unit :=
modify fun s => { s with postponed := f s.postponed }
builtin_initialize whnfRef : IO.Ref (Expr → MetaM Expr) ← IO.mkRef fun _ => throwError "whnf implementation was not set"
builtin_initialize inferTypeRef : IO.Ref (Expr → MetaM Expr) ← IO.mkRef fun _ => throwError "inferType implementation was not set"
builtin_initialize isExprDefEqAuxRef : IO.Ref (Expr → Expr → MetaM Bool) ← IO.mkRef fun _ _ => throwError "isDefEq implementation was not set"
builtin_initialize synthPendingRef : IO.Ref (MVarId → MetaM Bool) ← IO.mkRef fun _ => pure false
def whnf (e : Expr) : MetaM Expr :=
withIncRecDepth do (← whnfRef.get) e
def whnfForall (e : Expr) : MetaM Expr := do
let e' ← whnf e
if e'.isForall then pure e' else pure e
def inferType (e : Expr) : MetaM Expr :=
withIncRecDepth do (← inferTypeRef.get) e
protected def isExprDefEqAux (t s : Expr) : MetaM Bool :=
withIncRecDepth do (← isExprDefEqAuxRef.get) t s
protected def synthPending (mvarId : MVarId) : MetaM Bool :=
withIncRecDepth do (← synthPendingRef.get) mvarId
-- withIncRecDepth for a monad `n` such that `[MonadControlT MetaM n]`
protected def withIncRecDepth {α} (x : n α) : n α :=
mapMetaM (withIncRecDepth (m := MetaM)) x
private def mkFreshExprMVarAtCore
(mvarId : MVarId) (lctx : LocalContext) (localInsts : LocalInstances) (type : Expr) (kind : MetavarKind) (userName : Name) (numScopeArgs : Nat) : MetaM Expr := do
modifyMCtx fun mctx => mctx.addExprMVarDecl mvarId userName lctx localInsts type kind numScopeArgs;
pure $ mkMVar mvarId
def mkFreshExprMVarAt
(lctx : LocalContext) (localInsts : LocalInstances) (type : Expr)
(kind : MetavarKind := MetavarKind.natural) (userName : Name := Name.anonymous) (numScopeArgs : Nat := 0)
: MetaM Expr := do
let mvarId ← mkFreshId
mkFreshExprMVarAtCore mvarId lctx localInsts type kind userName numScopeArgs
def mkFreshLevelMVar : MetaM Level := do
let mvarId ← mkFreshId
modifyMCtx fun mctx => mctx.addLevelMVarDecl mvarId;
return mkLevelMVar mvarId
private def mkFreshExprMVarCore (type : Expr) (kind : MetavarKind) (userName : Name) : MetaM Expr := do
let lctx ← getLCtx
let localInsts ← getLocalInstances
mkFreshExprMVarAt lctx localInsts type kind userName
private def mkFreshExprMVarImpl (type? : Option Expr) (kind : MetavarKind) (userName : Name) : MetaM Expr :=
match type? with
| some type => mkFreshExprMVarCore type kind userName
| none => do
let u ← mkFreshLevelMVar
let type ← mkFreshExprMVarCore (mkSort u) MetavarKind.natural Name.anonymous
mkFreshExprMVarCore type kind userName
def mkFreshExprMVar (type? : Option Expr) (kind := MetavarKind.natural) (userName := Name.anonymous) : MetaM Expr :=
mkFreshExprMVarImpl type? kind userName
def mkFreshTypeMVar (kind := MetavarKind.natural) (userName := Name.anonymous) : MetaM Expr := do
let u ← mkFreshLevelMVar
mkFreshExprMVar (mkSort u) kind userName
/- Low-level version of `MkFreshExprMVar` which allows users to create/reserve a `mvarId` using `mkFreshId`, and then later create
the metavar using this method. -/
private def mkFreshExprMVarWithIdCore (mvarId : MVarId) (type : Expr)
(kind : MetavarKind := MetavarKind.natural) (userName : Name := Name.anonymous) (numScopeArgs : Nat := 0)
: MetaM Expr := do
let lctx ← getLCtx
let localInsts ← getLocalInstances
mkFreshExprMVarAtCore mvarId lctx localInsts type kind userName numScopeArgs
def mkFreshExprMVarWithId (mvarId : MVarId) (type? : Option Expr := none) (kind : MetavarKind := MetavarKind.natural) (userName := Name.anonymous) : MetaM Expr :=
match type? with
| some type => mkFreshExprMVarWithIdCore mvarId type kind userName
| none => do
let u ← mkFreshLevelMVar
let type ← mkFreshExprMVar (mkSort u)
mkFreshExprMVarWithIdCore mvarId type kind userName
def getTransparency : MetaM TransparencyMode :=
return (← getConfig).transparency
def shouldReduceAll : MetaM Bool :=
return (← getTransparency) == TransparencyMode.all
def shouldReduceReducibleOnly : MetaM Bool :=
return (← getTransparency) == TransparencyMode.reducible
def getMVarDecl (mvarId : MVarId) : MetaM MetavarDecl := do
let mctx ← getMCtx
match mctx.findDecl? mvarId with
| some d => pure d
| none => throwError! "unknown metavariable '{mkMVar mvarId}'"
def setMVarKind (mvarId : MVarId) (kind : MetavarKind) : MetaM Unit :=
modifyMCtx fun mctx => mctx.setMVarKind mvarId kind
/- Update the type of the given metavariable. This function assumes the new type is
definitionally equal to the current one -/
def setMVarType (mvarId : MVarId) (type : Expr) : MetaM Unit := do
modifyMCtx fun mctx => mctx.setMVarType mvarId type
def isReadOnlyExprMVar (mvarId : MVarId) : MetaM Bool := do
let mvarDecl ← getMVarDecl mvarId
let mctx ← getMCtx
return mvarDecl.depth != mctx.depth
def isReadOnlyOrSyntheticOpaqueExprMVar (mvarId : MVarId) : MetaM Bool := do
let mvarDecl ← getMVarDecl mvarId
match mvarDecl.kind with
| MetavarKind.syntheticOpaque => pure true
| _ =>
let mctx ← getMCtx
return mvarDecl.depth != mctx.depth
def isReadOnlyLevelMVar (mvarId : MVarId) : MetaM Bool := do
let mctx ← getMCtx
match mctx.findLevelDepth? mvarId with
| some depth => return depth != mctx.depth
| _ => throwError! "unknown universe metavariable '{mkLevelMVar mvarId}'"
def renameMVar (mvarId : MVarId) (newUserName : Name) : MetaM Unit :=
modifyMCtx fun mctx => mctx.renameMVar mvarId newUserName
def isExprMVarAssigned (mvarId : MVarId) : MetaM Bool :=
return (← getMCtx).isExprAssigned mvarId
def getExprMVarAssignment? (mvarId : MVarId) : MetaM (Option Expr) :=
return (← getMCtx).getExprAssignment? mvarId
/-- Return true if `e` contains `mvarId` directly or indirectly -/
def occursCheck (mvarId : MVarId) (e : Expr) : MetaM Bool :=
return (← getMCtx).occursCheck mvarId e
def assignExprMVar (mvarId : MVarId) (val : Expr) : MetaM Unit :=
modifyMCtx fun mctx => mctx.assignExpr mvarId val
def isDelayedAssigned (mvarId : MVarId) : MetaM Bool :=
return (← getMCtx).isDelayedAssigned mvarId
def getDelayedAssignment? (mvarId : MVarId) : MetaM (Option DelayedMetavarAssignment) :=
return (← getMCtx).getDelayedAssignment? mvarId
def hasAssignableMVar (e : Expr) : MetaM Bool :=
return (← getMCtx).hasAssignableMVar e
def throwUnknownFVar {α} (fvarId : FVarId) : MetaM α :=
throwError! "unknown free variable '{mkFVar fvarId}'"
def findLocalDecl? (fvarId : FVarId) : MetaM (Option LocalDecl) :=
return (← getLCtx).find? fvarId
def getLocalDecl (fvarId : FVarId) : MetaM LocalDecl := do
match (← getLCtx).find? fvarId with
| some d => pure d
| none => throwUnknownFVar fvarId
def getFVarLocalDecl (fvar : Expr) : MetaM LocalDecl :=
getLocalDecl fvar.fvarId!
def getLocalDeclFromUserName (userName : Name) : MetaM LocalDecl := do
match (← getLCtx).findFromUserName? userName with
| some d => pure d
| none => throwError! "unknown local declaration '{userName}'"
def instantiateLevelMVars (u : Level) : MetaM Level :=
MetavarContext.instantiateLevelMVars u
def instantiateMVars (e : Expr) : MetaM Expr :=
(MetavarContext.instantiateExprMVars e).run
def instantiateLocalDeclMVars (localDecl : LocalDecl) : MetaM LocalDecl := do
match localDecl with
| LocalDecl.cdecl idx id n type bi =>
let type ← instantiateMVars type
return LocalDecl.cdecl idx id n type bi
| LocalDecl.ldecl idx id n type val nonDep =>
let type ← instantiateMVars type
let val ← instantiateMVars val
return LocalDecl.ldecl idx id n type val nonDep
@[inline] def liftMkBindingM {α} (x : MetavarContext.MkBindingM α) : MetaM α := do
match x (← getLCtx) { mctx := (← getMCtx), ngen := (← getNGen) } with
| EStateM.Result.ok e newS => do
setNGen newS.ngen;
setMCtx newS.mctx;
pure e
| EStateM.Result.error (MetavarContext.MkBinding.Exception.revertFailure mctx lctx toRevert decl) newS => do
setMCtx newS.mctx;
setNGen newS.ngen;
throwError "failed to create binder due to failure when reverting variable dependencies"
def mkForallFVars (xs : Array Expr) (e : Expr) : MetaM Expr :=
if xs.isEmpty then pure e else liftMkBindingM <| MetavarContext.mkForall xs e
def mkLambdaFVars (xs : Array Expr) (e : Expr) : MetaM Expr :=
if xs.isEmpty then pure e else liftMkBindingM <| MetavarContext.mkLambda xs e
def mkLetFVars (xs : Array Expr) (e : Expr) : MetaM Expr :=
mkLambdaFVars xs e
def mkArrow (d b : Expr) : MetaM Expr := do
let n ← mkFreshUserName `x
return Lean.mkForall n BinderInfo.default d b
def mkForallUsedOnly (xs : Array Expr) (e : Expr) : MetaM (Expr × Nat) := do
if xs.isEmpty then pure (e, 0) else liftMkBindingM <| MetavarContext.mkForallUsedOnly xs e
def elimMVarDeps (xs : Array Expr) (e : Expr) (preserveOrder : Bool := false) : MetaM Expr :=
if xs.isEmpty then pure e else liftMkBindingM <| MetavarContext.elimMVarDeps xs e preserveOrder
@[inline] def withConfig {α} (f : Config → Config) : n α → n α :=
mapMetaM <| withReader (fun ctx => { ctx with config := f ctx.config })
@[inline] def withTrackingZeta {α} (x : n α) : n α :=
withConfig (fun cfg => { cfg with trackZeta := true }) x
@[inline] def withTransparency {α} (mode : TransparencyMode) : n α → n α :=
mapMetaM <| withConfig (fun config => { config with transparency := mode })
@[inline] def withDefault {α} (x : n α) : n α :=
withTransparency TransparencyMode.default x
@[inline] def withReducible {α} (x : n α) : n α :=
withTransparency TransparencyMode.reducible x
@[inline] def withReducibleAndInstances {α} (x : n α) : n α :=
withTransparency TransparencyMode.instances x
@[inline] def withAtLeastTransparency {α} (mode : TransparencyMode) (x : n α) : n α :=
withConfig
(fun config =>
let oldMode := config.transparency
let mode := if oldMode.lt mode then mode else oldMode
{ config with transparency := mode })
x
/-- Save cache, execute `x`, restore cache -/
@[inline] private def savingCacheImpl {α} (x : MetaM α) : MetaM α := do
let s ← get
let savedCache := s.cache
try x finally modify fun s => { s with cache := savedCache }
@[inline] def savingCache {α} : n α → n α :=
mapMetaM savingCacheImpl
def getTheoremInfo (info : ConstantInfo) : MetaM (Option ConstantInfo) := do
if (← shouldReduceAll) then
return some info
else
return none
private def getDefInfoTemp (info : ConstantInfo) : MetaM (Option ConstantInfo) := do
match (← getTransparency) with
| TransparencyMode.all => return some info
| TransparencyMode.default => return some info
| _ =>
if (← isReducible info.name) then
return some info
else
return none
/- Remark: we later define `getConst?` at `GetConst.lean` after we define `Instances.lean`.
This method is only used to implement `isClassQuickConst?`.
It is very similar to `getConst?`, but it returns none when `TransparencyMode.instances` and
`constName` is an instance. This difference should be irrelevant for `isClassQuickConst?`. -/
private def getConstTemp? (constName : Name) : MetaM (Option ConstantInfo) := do
let env ← getEnv
match env.find? constName with
| some (info@(ConstantInfo.thmInfo _)) => getTheoremInfo info
| some (info@(ConstantInfo.defnInfo _)) => getDefInfoTemp info
| some info => pure (some info)
| none => throwUnknownConstant constName
private def isClassQuickConst? (constName : Name) : MetaM (LOption Name) := do
let env ← getEnv
if isClass env constName then
pure (LOption.some constName)
else
match (← getConstTemp? constName) with
| some _ => pure LOption.undef
| none => pure LOption.none
private partial def isClassQuick? : Expr → MetaM (LOption Name)
| Expr.bvar .. => pure LOption.none
| Expr.lit .. => pure LOption.none
| Expr.fvar .. => pure LOption.none
| Expr.sort .. => pure LOption.none
| Expr.lam .. => pure LOption.none
| Expr.letE .. => pure LOption.undef
| Expr.proj .. => pure LOption.undef
| Expr.forallE _ _ b _ => isClassQuick? b
| Expr.mdata _ e _ => isClassQuick? e
| Expr.const n _ _ => isClassQuickConst? n
| Expr.mvar mvarId _ => do
match (← getExprMVarAssignment? mvarId) with
| some val => isClassQuick? val
| none => pure LOption.none
| Expr.app f _ _ =>
match f.getAppFn with
| Expr.const n .. => isClassQuickConst? n
| Expr.lam .. => pure LOption.undef
| _ => pure LOption.none
def saveAndResetSynthInstanceCache : MetaM SynthInstanceCache := do
let s ← get
let savedSythInstance := s.cache.synthInstance
modify fun s => { s with cache := { s.cache with synthInstance := {} } }
pure savedSythInstance
def restoreSynthInstanceCache (cache : SynthInstanceCache) : MetaM Unit :=
modify fun s => { s with cache := { s.cache with synthInstance := cache } }
@[inline] private def resettingSynthInstanceCacheImpl {α} (x : MetaM α) : MetaM α := do
let savedSythInstance ← saveAndResetSynthInstanceCache
try x finally restoreSynthInstanceCache savedSythInstance
/-- Reset `synthInstance` cache, execute `x`, and restore cache -/
@[inline] def resettingSynthInstanceCache {α} : n α → n α :=
mapMetaM resettingSynthInstanceCacheImpl
@[inline] def resettingSynthInstanceCacheWhen {α} (b : Bool) (x : n α) : n α :=
if b then resettingSynthInstanceCache x else x
private def withNewLocalInstanceImp {α} (className : Name) (fvar : Expr) (k : MetaM α) : MetaM α := do
let localDecl ← getFVarLocalDecl fvar
/- Recall that we use `auxDecl` binderInfo when compiling recursive declarations. -/
match localDecl.binderInfo with
| BinderInfo.auxDecl => k
| _ =>
resettingSynthInstanceCache $
withReader
(fun ctx => { ctx with localInstances := ctx.localInstances.push { className := className, fvar := fvar } })
k
/-- Add entry `{ className := className, fvar := fvar }` to localInstances,
and then execute continuation `k`.
It resets the type class cache using `resettingSynthInstanceCache`. -/
def withNewLocalInstance {α} (className : Name) (fvar : Expr) : n α → n α :=
mapMetaM $ withNewLocalInstanceImp className fvar
private def fvarsSizeLtMaxFVars (fvars : Array Expr) (maxFVars? : Option Nat) : Bool :=
match maxFVars? with
| some maxFVars => fvars.size < maxFVars
| none => true
mutual
/--
`withNewLocalInstances isClassExpensive fvars j k` updates the vector or local instances
using free variables `fvars[j] ... fvars.back`, and execute `k`.
- `isClassExpensive` is defined later.
- The type class chache is reset whenever a new local instance is found.
- `isClassExpensive` uses `whnf` which depends (indirectly) on the set of local instances.
Thus, each new local instance requires a new `resettingSynthInstanceCache`. -/
private partial def withNewLocalInstancesImp {α}
(fvars : Array Expr) (i : Nat) (k : MetaM α) : MetaM α := do
if h : i < fvars.size then
let fvar := fvars.get ⟨i, h⟩
let decl ← getFVarLocalDecl fvar
match (← isClassQuick? decl.type) with
| LOption.none => withNewLocalInstancesImp fvars (i+1) k
| LOption.undef =>
match (← isClassExpensive? decl.type) with
| none => withNewLocalInstancesImp fvars (i+1) k
| some c => withNewLocalInstance c fvar $ withNewLocalInstancesImp fvars (i+1) k
| LOption.some c => withNewLocalInstance c fvar $ withNewLocalInstancesImp fvars (i+1) k
else
k
/--
`forallTelescopeAuxAux lctx fvars j type`
Remarks:
- `lctx` is the `MetaM` local context extended with declarations for `fvars`.
- `type` is the type we are computing the telescope for. It contains only
dangling bound variables in the range `[j, fvars.size)`
- if `reducing? == true` and `type` is not `forallE`, we use `whnf`.
- when `type` is not a `forallE` nor it can't be reduced to one, we
excute the continuation `k`.
Here is an example that demonstrates the `reducing?`.
Suppose we have
```
abbrev StateM s a := s -> Prod a s
```
Now, assume we are trying to build the telescope for
```
forall (x : Nat), StateM Int Bool
```
if `reducing == true`, the function executes `k #[(x : Nat) (s : Int)] Bool`.
if `reducing == false`, the function executes `k #[(x : Nat)] (StateM Int Bool)`
if `maxFVars?` is `some max`, then we interrupt the telescope construction
when `fvars.size == max`
-/
private partial def forallTelescopeReducingAuxAux {α}
(reducing : Bool) (maxFVars? : Option Nat)
(type : Expr)
(k : Array Expr → Expr → MetaM α) : MetaM α := do
let rec process (lctx : LocalContext) (fvars : Array Expr) (j : Nat) (type : Expr) : MetaM α := do
match type with
| Expr.forallE n d b c =>
if fvarsSizeLtMaxFVars fvars maxFVars? then
let d := d.instantiateRevRange j fvars.size fvars
let fvarId ← mkFreshId
let lctx := lctx.mkLocalDecl fvarId n d c.binderInfo
let fvar := mkFVar fvarId
let fvars := fvars.push fvar
process lctx fvars j b
else
let type := type.instantiateRevRange j fvars.size fvars;
withReader (fun ctx => { ctx with lctx := lctx }) do
withNewLocalInstancesImp fvars j do
k fvars type
| _ =>
let type := type.instantiateRevRange j fvars.size fvars;
withReader (fun ctx => { ctx with lctx := lctx }) do
withNewLocalInstancesImp fvars j do
if reducing && fvarsSizeLtMaxFVars fvars maxFVars? then
let newType ← whnf type
if newType.isForall then
process lctx fvars fvars.size newType
else
k fvars type
else
k fvars type
process (← getLCtx) #[] 0 type
private partial def forallTelescopeReducingAux {α} (type : Expr) (maxFVars? : Option Nat) (k : Array Expr → Expr → MetaM α) : MetaM α := do
match maxFVars? with
| some 0 => k #[] type
| _ => do
let newType ← whnf type
if newType.isForall then
forallTelescopeReducingAuxAux true maxFVars? newType k
else
k #[] type
private partial def isClassExpensive? : Expr → MetaM (Option Name)
| type => withReducible <| -- when testing whether a type is a type class, we only unfold reducible constants.
forallTelescopeReducingAux type none fun xs type => do
let env ← getEnv
match type.getAppFn with
| Expr.const c _ _ => do
if isClass env c then
return some c
else
-- make sure abbreviations are unfolded
match (← whnf type).getAppFn with
| Expr.const c _ _ => return if isClass env c then some c else none
| _ => return none
| _ => return none
private partial def isClassImp? (type : Expr) : MetaM (Option Name) := do
match (← isClassQuick? type) with
| LOption.none => pure none
| LOption.some c => pure (some c)
| LOption.undef => isClassExpensive? type
end
def isClass? (type : Expr) : MetaM (Option Name) :=
try isClassImp? type catch _ => pure none
private def withNewLocalInstancesImpAux {α} (fvars : Array Expr) (j : Nat) : n α → n α :=
mapMetaM $ withNewLocalInstancesImp fvars j
partial def withNewLocalInstances {α} (fvars : Array Expr) (j : Nat) : n α → n α :=
mapMetaM $ withNewLocalInstancesImpAux fvars j
@[inline] private def forallTelescopeImp {α} (type : Expr) (k : Array Expr → Expr → MetaM α) : MetaM α := do
forallTelescopeReducingAuxAux (reducing := false) (maxFVars? := none) type k
/--
Given `type` of the form `forall xs, A`, execute `k xs A`.
This combinator will declare local declarations, create free variables for them,
execute `k` with updated local context, and make sure the cache is restored after executing `k`. -/
def forallTelescope {α} (type : Expr) (k : Array Expr → Expr → n α) : n α :=
map2MetaM (fun k => forallTelescopeImp type k) k
private def forallTelescopeReducingImp {α} (type : Expr) (k : Array Expr → Expr → MetaM α) : MetaM α :=
forallTelescopeReducingAux type (maxFVars? := none) k
/--
Similar to `forallTelescope`, but given `type` of the form `forall xs, A`,
it reduces `A` and continues bulding the telescope if it is a `forall`. -/
def forallTelescopeReducing {α} (type : Expr) (k : Array Expr → Expr → n α) : n α :=
map2MetaM (fun k => forallTelescopeReducingImp type k) k
private def forallBoundedTelescopeImp {α} (type : Expr) (maxFVars? : Option Nat) (k : Array Expr → Expr → MetaM α) : MetaM α :=
forallTelescopeReducingAux type maxFVars? k
/--
Similar to `forallTelescopeReducing`, stops constructing the telescope when
it reaches size `maxFVars`. -/
def forallBoundedTelescope {α} (type : Expr) (maxFVars? : Option Nat) (k : Array Expr → Expr → n α) : n α :=
map2MetaM (fun k => forallBoundedTelescopeImp type maxFVars? k) k
/-- Similar to `forallTelescopeAuxAux` but for lambda and let expressions. -/
private partial def lambdaTelescopeAux {α}
(k : Array Expr → Expr → MetaM α)
: Bool → LocalContext → Array Expr → Nat → Expr → MetaM α
| consumeLet, lctx, fvars, j, Expr.lam n d b c => do
let d := d.instantiateRevRange j fvars.size fvars
let fvarId ← mkFreshId
let lctx := lctx.mkLocalDecl fvarId n d c.binderInfo
let fvar := mkFVar fvarId
lambdaTelescopeAux k consumeLet lctx (fvars.push fvar) j b
| true, lctx, fvars, j, Expr.letE n t v b _ => do
let t := t.instantiateRevRange j fvars.size fvars
let v := v.instantiateRevRange j fvars.size fvars
let fvarId ← mkFreshId
let lctx := lctx.mkLetDecl fvarId n t v
let fvar := mkFVar fvarId
lambdaTelescopeAux k true lctx (fvars.push fvar) j b
| _, lctx, fvars, j, e =>
let e := e.instantiateRevRange j fvars.size fvars;
withReader (fun ctx => { ctx with lctx := lctx }) do
withNewLocalInstancesImp fvars j do
k fvars e
private partial def lambdaTelescopeImp {α} (e : Expr) (consumeLet : Bool) (k : Array Expr → Expr → MetaM α) : MetaM α := do
let rec process (consumeLet : Bool) (lctx : LocalContext) (fvars : Array Expr) (j : Nat) (e : Expr) : MetaM α := do
match consumeLet, e with
| _, Expr.lam n d b c =>
let d := d.instantiateRevRange j fvars.size fvars
let fvarId ← mkFreshId
let lctx := lctx.mkLocalDecl fvarId n d c.binderInfo
let fvar := mkFVar fvarId
process consumeLet lctx (fvars.push fvar) j b
| true, Expr.letE n t v b _ => do
let t := t.instantiateRevRange j fvars.size fvars
let v := v.instantiateRevRange j fvars.size fvars
let fvarId ← mkFreshId
let lctx := lctx.mkLetDecl fvarId n t v
let fvar := mkFVar fvarId
process true lctx (fvars.push fvar) j b
| _, e =>
let e := e.instantiateRevRange j fvars.size fvars
withReader (fun ctx => { ctx with lctx := lctx }) do
withNewLocalInstancesImp fvars j do
k fvars e
process consumeLet (← getLCtx) #[] 0 e
/-- Similar to `forallTelescope` but for lambda and let expressions. -/
def lambdaLetTelescope {α} (type : Expr) (k : Array Expr → Expr → n α) : n α :=
map2MetaM (fun k => lambdaTelescopeImp type true k) k
/-- Similar to `forallTelescope` but for lambda expressions. -/
def lambdaTelescope {α} (type : Expr) (k : Array Expr → Expr → n α) : n α :=
map2MetaM (fun k => lambdaTelescopeImp type false k) k
/-- Return the parameter names for the givel global declaration. -/
def getParamNames (declName : Name) : MetaM (Array Name) := do
let cinfo ← getConstInfo declName
forallTelescopeReducing cinfo.type fun xs _ => do
xs.mapM fun x => do
let localDecl ← getLocalDecl x.fvarId!
pure localDecl.userName
-- `kind` specifies the metavariable kind for metavariables not corresponding to instance implicit `[ ... ]` arguments.
private partial def forallMetaTelescopeReducingAux
(e : Expr) (reducing : Bool) (maxMVars? : Option Nat) (kind : MetavarKind) : MetaM (Array Expr × Array BinderInfo × Expr) :=
let rec process (mvars : Array Expr) (bis : Array BinderInfo) (j : Nat) (type : Expr) : MetaM (Array Expr × Array BinderInfo × Expr) := do
match type with
| Expr.forallE n d b c =>
let cont : Unit → MetaM (Array Expr × Array BinderInfo × Expr) := fun _ => do
let d := d.instantiateRevRange j mvars.size mvars
let k := if c.binderInfo.isInstImplicit then MetavarKind.synthetic else kind
let mvar ← mkFreshExprMVar d k n
let mvars := mvars.push mvar
let bis := bis.push c.binderInfo
process mvars bis j b
match maxMVars? with
| none => cont ()
| some maxMVars =>
if mvars.size < maxMVars then
cont ()
else
let type := type.instantiateRevRange j mvars.size mvars;
pure (mvars, bis, type)
| _ =>
let type := type.instantiateRevRange j mvars.size mvars;
if reducing then do
let newType ← whnf type;
if newType.isForall then
process mvars bis mvars.size newType
else
pure (mvars, bis, type)
else
pure (mvars, bis, type)
process #[] #[] 0 e
/-- Similar to `forallTelescope`, but creates metavariables instead of free variables. -/
def forallMetaTelescope (e : Expr) (kind := MetavarKind.natural) : MetaM (Array Expr × Array BinderInfo × Expr) :=
forallMetaTelescopeReducingAux e (reducing := false) (maxMVars? := none) kind
/-- Similar to `forallTelescopeReducing`, but creates metavariables instead of free variables. -/
def forallMetaTelescopeReducing (e : Expr) (maxMVars? : Option Nat := none) (kind := MetavarKind.natural) : MetaM (Array Expr × Array BinderInfo × Expr) :=
forallMetaTelescopeReducingAux e (reducing := true) maxMVars? kind
/-- Similar to `forallMetaTelescopeReducingAux` but for lambda expressions. -/
partial def lambdaMetaTelescope (e : Expr) (maxMVars? : Option Nat := none) : MetaM (Array Expr × Array BinderInfo × Expr) :=
let rec process (mvars : Array Expr) (bis : Array BinderInfo) (j : Nat) (type : Expr) : MetaM (Array Expr × Array BinderInfo × Expr) := do
let finalize : Unit → MetaM (Array Expr × Array BinderInfo × Expr) := fun _ => do
let type := type.instantiateRevRange j mvars.size mvars
pure (mvars, bis, type)
let cont : Unit → MetaM (Array Expr × Array BinderInfo × Expr) := fun _ => do
match type with
| Expr.lam n d b c =>
let d := d.instantiateRevRange j mvars.size mvars
let mvar ← mkFreshExprMVar d
let mvars := mvars.push mvar
let bis := bis.push c.binderInfo
process mvars bis j b
| _ => finalize ()
match maxMVars? with
| none => cont ()
| some maxMVars =>
if mvars.size < maxMVars then
cont ()
else
finalize ()
process #[] #[] 0 e
private def withNewFVar {α} (fvar fvarType : Expr) (k : Expr → MetaM α) : MetaM α := do
match (← isClass? fvarType) with
| none => k fvar
| some c => withNewLocalInstance c fvar $ k fvar
private def withLocalDeclImp {α} (n : Name) (bi : BinderInfo) (type : Expr) (k : Expr → MetaM α) : MetaM α := do
let fvarId ← mkFreshId
let ctx ← read
let lctx := ctx.lctx.mkLocalDecl fvarId n type bi
let fvar := mkFVar fvarId
withReader (fun ctx => { ctx with lctx := lctx }) do
withNewFVar fvar type k
def withLocalDecl {α} (name : Name) (bi : BinderInfo) (type : Expr) (k : Expr → n α) : n α :=
map1MetaM (fun k => withLocalDeclImp name bi type k) k
def withLocalDeclD {α} (name : Name) (type : Expr) (k : Expr → n α) : n α :=
withLocalDecl name BinderInfo.default type k
private def withLetDeclImp {α} (n : Name) (type : Expr) (val : Expr) (k : Expr → MetaM α) : MetaM α := do
let fvarId ← mkFreshId
let ctx ← read
let lctx := ctx.lctx.mkLetDecl fvarId n type val
let fvar := mkFVar fvarId
withReader (fun ctx => { ctx with lctx := lctx }) do
withNewFVar fvar type k
def withLetDecl {α} (name : Name) (type : Expr) (val : Expr) (k : Expr → n α) : n α :=
map1MetaM (fun k => withLetDeclImp name type val k) k
private def withExistingLocalDeclsImp {α} (decls : List LocalDecl) (k : MetaM α) : MetaM α := do
let ctx ← read
let numLocalInstances := ctx.localInstances.size
let lctx := decls.foldl (fun (lctx : LocalContext) decl => lctx.addDecl decl) ctx.lctx
withReader (fun ctx => { ctx with lctx := lctx }) do
let newLocalInsts ← decls.foldlM
(fun (newlocalInsts : Array LocalInstance) (decl : LocalDecl) => (do {
match (← isClass? decl.type) with
| none => pure newlocalInsts
| some c => pure $ newlocalInsts.push { className := c, fvar := decl.toExpr } } : MetaM _))
ctx.localInstances;
if newLocalInsts.size == numLocalInstances then
k
else
resettingSynthInstanceCache $ withReader (fun ctx => { ctx with localInstances := newLocalInsts }) k
def withExistingLocalDecls {α} (decls : List LocalDecl) : n α → n α :=
mapMetaM $ withExistingLocalDeclsImp decls
private def withNewMCtxDepthImp {α} (x : MetaM α) : MetaM α := do
let s ← get
let savedMCtx := s.mctx
modifyMCtx fun mctx => mctx.incDepth
try x finally setMCtx savedMCtx
/--
Save cache and `MetavarContext`, bump the `MetavarContext` depth, execute `x`,
and restore saved data. -/
def withNewMCtxDepth {α} : n α → n α :=
mapMetaM withNewMCtxDepthImp
private def withLocalContextImp {α} (lctx : LocalContext) (localInsts : LocalInstances) (x : MetaM α) : MetaM α := do
let localInstsCurr ← getLocalInstances
withReader (fun ctx => { ctx with lctx := lctx, localInstances := localInsts }) do
if localInsts == localInstsCurr then
x
else
resettingSynthInstanceCache x
def withLCtx {α} (lctx : LocalContext) (localInsts : LocalInstances) : n α → n α :=
mapMetaM $ withLocalContextImp lctx localInsts
private def withMVarContextImp {α} (mvarId : MVarId) (x : MetaM α) : MetaM α := do
let mvarDecl ← getMVarDecl mvarId
withLocalContextImp mvarDecl.lctx mvarDecl.localInstances x
/--
Execute `x` using the given metavariable `LocalContext` and `LocalInstances`.
The type class resolution cache is flushed when executing `x` if its `LocalInstances` are
different from the current ones. -/
def withMVarContext {α} (mvarId : MVarId) : n α → n α :=
mapMetaM $ withMVarContextImp mvarId
private def withMCtxImp {α} (mctx : MetavarContext) (x : MetaM α) : MetaM α := do
let mctx' ← getMCtx
setMCtx mctx
try x finally setMCtx mctx'
def withMCtx {α} (mctx : MetavarContext) : n α → n α :=
mapMetaM $ withMCtxImp mctx
@[inline] private def approxDefEqImp {α} (x : MetaM α) : MetaM α :=
withConfig (fun config => { config with foApprox := true, ctxApprox := true, quasiPatternApprox := true}) x
/-- Execute `x` using approximate unification: `foApprox`, `ctxApprox` and `quasiPatternApprox`. -/
@[inline] def approxDefEq {α} : n α → n α :=
mapMetaM approxDefEqImp
@[inline] private def fullApproxDefEqImp {α} (x : MetaM α) : MetaM α :=
withConfig (fun config => { config with foApprox := true, ctxApprox := true, quasiPatternApprox := true, constApprox := true }) x
/--
Similar to `approxDefEq`, but uses all available approximations.
We don't use `constApprox` by default at `approxDefEq` because it often produces undesirable solution for monadic code.
For example, suppose we have `pure (x > 0)` which has type `?m Prop`. We also have the goal `[Pure ?m]`.
Now, assume the expected type is `IO Bool`. Then, the unification constraint `?m Prop =?= IO Bool` could be solved
as `?m := fun _ => IO Bool` using `constApprox`, but this spurious solution would generate a failure when we try to
solve `[Pure (fun _ => IO Bool)]` -/
@[inline] def fullApproxDefEq {α} : n α → n α :=
mapMetaM fullApproxDefEqImp
def normalizeLevel (u : Level) : MetaM Level := do
let u ← instantiateLevelMVars u
pure u.normalize
def assignLevelMVar (mvarId : MVarId) (u : Level) : MetaM Unit := do
modifyMCtx fun mctx => mctx.assignLevel mvarId u
def whnfR (e : Expr) : MetaM Expr :=
withTransparency TransparencyMode.reducible <| whnf e
def whnfD (e : Expr) : MetaM Expr :=
withTransparency TransparencyMode.default <| whnf e
def whnfI (e : Expr) : MetaM Expr :=
withTransparency TransparencyMode.instances <| whnf e
def setInlineAttribute (declName : Name) (kind := Compiler.InlineAttributeKind.inline): MetaM Unit := do
let env ← getEnv
match Compiler.setInlineAttribute env declName kind with
| Except.ok env => setEnv env
| Except.error msg => throwError msg
private partial def instantiateForallAux (ps : Array Expr) (i : Nat) (e : Expr) : MetaM Expr := do
if h : i < ps.size then
let p := ps.get ⟨i, h⟩
let e ← whnf e
match e with
| Expr.forallE _ _ b _ => instantiateForallAux ps (i+1) (b.instantiate1 p)
| _ => throwError "invalid instantiateForall, too many parameters"
else
pure e
/- Given `e` of the form `forall (a_1 : A_1) ... (a_n : A_n), B[a_1, ..., a_n]` and `p_1 : A_1, ... p_n : A_n`, return `B[p_1, ..., p_n]`. -/
def instantiateForall (e : Expr) (ps : Array Expr) : MetaM Expr :=
instantiateForallAux ps 0 e
private partial def instantiateLambdaAux (ps : Array Expr) (i : Nat) (e : Expr) : MetaM Expr := do
if h : i < ps.size then
let p := ps.get ⟨i, h⟩
let e ← whnf e
match e with
| Expr.lam _ _ b _ => instantiateLambdaAux ps (i+1) (b.instantiate1 p)
| _ => throwError "invalid instantiateLambda, too many parameters"
else
pure e
/- Given `e` of the form `fun (a_1 : A_1) ... (a_n : A_n) => t[a_1, ..., a_n]` and `p_1 : A_1, ... p_n : A_n`, return `t[p_1, ..., p_n]`.
It uses `whnf` to reduce `e` if it is not a lambda -/
def instantiateLambda (e : Expr) (ps : Array Expr) : MetaM Expr :=
instantiateLambdaAux ps 0 e
/-- Return true iff `e` depends on the free variable `fvarId` -/
def dependsOn (e : Expr) (fvarId : FVarId) : MetaM Bool :=
return (← getMCtx).exprDependsOn e fvarId
def ppExpr (e : Expr) : MetaM Format := do
let env ← getEnv
let mctx ← getMCtx
let lctx ← getLCtx
let opts ← getOptions
let ctxCore ← readThe Core.Context
Lean.ppExpr { env := env, mctx := mctx, lctx := lctx, opts := opts, currNamespace := ctxCore.currNamespace, openDecls := ctxCore.openDecls } e
@[inline] protected def orelse {α} (x y : MetaM α) : MetaM α := do
let env ← getEnv
let mctx ← getMCtx
try x catch _ => setEnv env; setMCtx mctx; y
instance {α} : OrElse (MetaM α) := ⟨Meta.orelse⟩
@[inline] private def orelseMergeErrorsImp {α} (x y : MetaM α)
(mergeRef : Syntax → Syntax → Syntax := fun r₁ r₂ => r₁)
(mergeMsg : MessageData → MessageData → MessageData := fun m₁ m₂ => m₁ ++ Format.line ++ m₂) : MetaM α := do
let env ← getEnv
let mctx ← getMCtx
try
x
catch ex =>
setEnv env
setMCtx mctx
match ex with
| Exception.error ref₁ m₁ =>
try
y
catch
| Exception.error ref₂ m₂ => throw $ Exception.error (mergeRef ref₁ ref₂) (mergeMsg m₁ m₂)
| ex => throw ex
| ex => throw ex
/--
Similar to `orelse`, but merge errors. Note that internal errors are not caught.
The default `mergeRef` uses the `ref` (position information) for the first message.
The default `mergeMsg` combines error messages using `Format.line ++ Format.line` as a separator. -/
@[inline] def orelseMergeErrors {α m} [MonadControlT MetaM m] [Monad m] (x y : m α)
(mergeRef : Syntax → Syntax → Syntax := fun r₁ r₂ => r₁)
(mergeMsg : MessageData → MessageData → MessageData := fun m₁ m₂ => m₁ ++ Format.line ++ Format.line ++ m₂) : m α := do
controlAt MetaM fun runInBase => orelseMergeErrorsImp (runInBase x) (runInBase y) mergeRef mergeMsg
/-- Execute `x`, and apply `f` to the produced error message -/
def mapErrorImp {α} (x : MetaM α) (f : MessageData → MessageData) : MetaM α := do
try
x
catch
| Exception.error ref msg => throw $ Exception.error ref $ f msg
| ex => throw ex
@[inline] def mapError {α m} [MonadControlT MetaM m] [Monad m] (x : m α) (f : MessageData → MessageData) : m α :=
controlAt MetaM fun runInBase => mapErrorImp (runInBase x) f
/-- `commitWhenSome? x` executes `x` and keep modifications when it returns `some a`. -/
@[specialize] def commitWhenSome? {α} (x? : MetaM (Option α)) : MetaM (Option α) := do
let env ← getEnv
let mctx ← getMCtx
try
match (← x?) with
| some a => pure (some a)
| none =>
setEnv env
setMCtx mctx
pure none
catch ex =>
setEnv env
setMCtx mctx
throw ex
end Methods
end Meta
export Meta (MetaM)
end Lean
|
25a0da9f52488cc7523052cf0a6322241cb52510 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/data/multiset/range.lean | b9959669106ca02037669fab16229ea906e4c800 | [
"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,835 | lean | /-
Copyright (c) 2015 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import data.multiset.basic
import data.list.range
/-! # `multiset.range n` gives `{0, 1, ..., n-1}` as a multiset.
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.-/
open list nat
namespace multiset
/- range -/
/-- `range n` is the multiset lifted from the list `range n`,
that is, the set `{0, 1, ..., n-1}`. -/
def range (n : ℕ) : multiset ℕ := range n
theorem coe_range (n : ℕ) : ↑(list.range n) = range n := rfl
@[simp] theorem range_zero : range 0 = 0 := rfl
@[simp] theorem range_succ (n : ℕ) : range (succ n) = n ::ₘ range n :=
by rw [range, range_succ, ← coe_add, add_comm]; refl
@[simp] theorem card_range (n : ℕ) : card (range n) = n := length_range _
theorem range_subset {m n : ℕ} : range m ⊆ range n ↔ m ≤ n := range_subset
@[simp] theorem mem_range {m n : ℕ} : m ∈ range n ↔ m < n := mem_range
@[simp] theorem not_mem_range_self {n : ℕ} : n ∉ range n := not_mem_range_self
theorem self_mem_range_succ (n : ℕ) : n ∈ range (n + 1) := list.self_mem_range_succ n
lemma range_add (a b : ℕ) : range (a + b) = range a + (range b).map (λ x, a + x) :=
congr_arg coe (list.range_add _ _)
lemma range_disjoint_map_add (a : ℕ) (m : multiset ℕ) :
(range a).disjoint (m.map (λ x, a + x)) :=
begin
intros x hxa hxb,
rw [range, mem_coe, list.mem_range] at hxa,
obtain ⟨c, _, rfl⟩ := mem_map.1 hxb,
exact (self_le_add_right _ _).not_lt hxa,
end
lemma range_add_eq_union (a b : ℕ) : range (a + b) = range a ∪ (range b).map (λ x, a + x) :=
by { rw [range_add, add_eq_union_iff_disjoint], apply range_disjoint_map_add }
end multiset
|
7769f8b52f529526ce89fab74c3fb8b857e5fe4f | 32317185abf7e7c963f4c67c190aec61af6b3628 | /hott/types/int/basic.hlean | c004028b672eafd3fc677e1fed62faf723f037c7 | [
"Apache-2.0"
] | permissive | Andrew-Zipperer-unorganized/lean | 198a2317f21198cd8d26e7085e484b86277f17f7 | dcb35008e1474a0abebe632b1dced120e5f8c009 | refs/heads/master | 1,622,526,520,945 | 1,453,576,559,000 | 1,454,612,842,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 25,905 | hlean | /-
Copyright (c) 2014 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Floris van Doorn, Jeremy Avigad
The integers, with addition, multiplication, and subtraction. The representation of the integers is
chosen to compute efficiently.
To faciliate proving things about these operations, we show that the integers are a quotient of
ℕ × ℕ with the usual equivalence relation, ≡, and functions
abstr : ℕ × ℕ → ℤ
repr : ℤ → ℕ × ℕ
satisfying:
abstr_repr (a : ℤ) : abstr (repr a) = a
repr_abstr (p : ℕ × ℕ) : repr (abstr p) ≡ p
abstr_eq (p q : ℕ × ℕ) : p ≡ q → abstr p = abstr q
For example, to "lift" statements about add to statements about padd, we need to prove the
following:
repr_add (a b : ℤ) : repr (a + b) = padd (repr a) (repr b)
padd_congr (p p' q q' : ℕ × ℕ) (H1 : p ≡ p') (H2 : q ≡ q') : padd p q ≡ p' q'
-/
import types.nat.sub algebra.relation types.prod
open prod relation nat
open decidable binary
open algebra eq lift
/- the type of integers -/
inductive int : Type :=
| of_nat : nat → int
| neg_succ_of_nat : nat → int
notation `ℤ` := int
definition int.of_num [coercion] [reducible] [constructor] (n : num) : ℤ :=
int.of_nat (nat.of_num n)
namespace int
attribute int.of_nat [coercion]
notation `-[1+ ` n `]` := int.neg_succ_of_nat n -- for pretty-printing output
protected definition prio : num := num.pred nat.prio
definition int_has_zero [reducible] [instance] [priority int.prio] : has_zero int :=
has_zero.mk (of_nat 0)
definition int_has_one [reducible] [instance] [priority int.prio] : has_one int :=
has_one.mk (of_nat 1)
theorem of_nat_zero : of_nat (0:nat) = (0:int) :=
rfl
theorem of_nat_one : of_nat (1:nat) = (1:int) :=
rfl
/- definitions of basic functions -/
definition neg_of_nat : ℕ → ℤ
| 0 := 0
| (succ m) := -[1+ m]
definition sub_nat_nat (m n : ℕ) : ℤ :=
match (n - m : nat) with
| 0 := of_nat (m - n) -- m ≥ n
| (succ k) := -[1+ k] -- m < n, and n - m = succ k
end
protected definition neg (a : ℤ) : ℤ :=
int.cases_on a neg_of_nat succ
protected definition add : ℤ → ℤ → ℤ
| (of_nat m) (of_nat n) := _root_.add m n
| (of_nat m) -[1+ n] := sub_nat_nat m (succ n)
| -[1+ m] (of_nat n) := sub_nat_nat n (succ m)
| -[1+ m] -[1+ n] := neg_of_nat (succ m + succ n)
protected definition mul : ℤ → ℤ → ℤ
| (of_nat m) (of_nat n) := m * n
| (of_nat m) -[1+ n] := neg_of_nat (m * succ n)
| -[1+ m] (of_nat n) := neg_of_nat (succ m * n)
| -[1+ m] -[1+ n] := succ m * succ n
/- notation -/
definition int_has_add [reducible] [instance] [priority int.prio] : has_add int := has_add.mk int.add
definition int_has_neg [reducible] [instance] [priority int.prio] : has_neg int := has_neg.mk int.neg
definition int_has_mul [reducible] [instance] [priority int.prio] : has_mul int := has_mul.mk int.mul
lemma mul_of_nat_of_nat (m n : nat) : of_nat m * of_nat n = of_nat (m * n) :=
rfl
lemma mul_of_nat_neg_succ_of_nat (m n : nat) : of_nat m * -[1+ n] = neg_of_nat (m * succ n) :=
rfl
lemma mul_neg_succ_of_nat_of_nat (m n : nat) : -[1+ m] * of_nat n = neg_of_nat (succ m * n) :=
rfl
lemma mul_neg_succ_of_nat_neg_succ_of_nat (m n : nat) : -[1+ m] * -[1+ n] = succ m * succ n :=
rfl
/- some basic functions and properties -/
theorem of_nat.inj {m n : ℕ} (H : of_nat m = of_nat n) : m = n :=
down (int.no_confusion H imp.id)
theorem eq_of_of_nat_eq_of_nat {m n : ℕ} (H : of_nat m = of_nat n) : m = n :=
of_nat.inj H
theorem of_nat_eq_of_nat_iff (m n : ℕ) : of_nat m = of_nat n ↔ m = n :=
iff.intro of_nat.inj !ap
theorem neg_succ_of_nat.inj {m n : ℕ} (H : neg_succ_of_nat m = neg_succ_of_nat n) : m = n :=
down (int.no_confusion H imp.id)
theorem neg_succ_of_nat_eq (n : ℕ) : -[1+ n] = -(n + 1) := rfl
private definition has_decidable_eq₂ : Π (a b : ℤ), decidable (a = b)
| (of_nat m) (of_nat n) := decidable_of_decidable_of_iff
(nat.has_decidable_eq m n) (iff.symm (of_nat_eq_of_nat_iff m n))
| (of_nat m) -[1+ n] := inr (by contradiction)
| -[1+ m] (of_nat n) := inr (by contradiction)
| -[1+ m] -[1+ n] := if H : m = n then
inl (ap neg_succ_of_nat H) else inr (not.mto neg_succ_of_nat.inj H)
definition has_decidable_eq [instance] [priority int.prio] : decidable_eq ℤ := has_decidable_eq₂
theorem of_nat_add (n m : nat) : of_nat (n + m) = of_nat n + of_nat m := rfl
theorem of_nat_succ (n : ℕ) : of_nat (succ n) = of_nat n + 1 := rfl
theorem of_nat_mul (n m : ℕ) : of_nat (n * m) = of_nat n * of_nat m := rfl
theorem sub_nat_nat_of_ge {m n : ℕ} (H : m ≥ n) : sub_nat_nat m n = of_nat (m - n) :=
show sub_nat_nat m n = nat.cases_on 0 (m -[nat] n) _, from (sub_eq_zero_of_le H) ▸ rfl
section
local attribute sub_nat_nat [reducible]
theorem sub_nat_nat_of_lt {m n : ℕ} (H : m < n) : sub_nat_nat m n = -[1+ pred (n - m)] :=
have H1 : n - m = succ (pred (n - m)), from inverse (succ_pred_of_pos (nat.sub_pos_of_lt H)),
show sub_nat_nat m n = nat.cases_on (succ (nat.pred (n - m))) (m -[nat] n) _, from H1 ▸ rfl
end
definition nat_abs (a : ℤ) : ℕ := int.cases_on a id succ
theorem nat_abs_of_nat (n : ℕ) : nat_abs n = n := rfl
theorem eq_zero_of_nat_abs_eq_zero : Π {a : ℤ}, nat_abs a = 0 → a = 0
| (of_nat m) H := ap of_nat H
| -[1+ m'] H := absurd H !succ_ne_zero
theorem nat_abs_zero : nat_abs (0:int) = (0:nat) :=
rfl
theorem nat_abs_one : nat_abs (1:int) = (1:nat) :=
rfl
/- int is a quotient of ordered pairs of natural numbers -/
protected definition equiv (p q : ℕ × ℕ) : Type₀ := pr1 p + pr2 q = pr2 p + pr1 q
local infix ≡ := int.equiv
protected theorem equiv.refl [refl] {p : ℕ × ℕ} : p ≡ p := !add.comm
protected theorem equiv.symm [symm] {p q : ℕ × ℕ} (H : p ≡ q) : q ≡ p :=
calc
pr1 q + pr2 p = pr2 p + pr1 q : by rewrite add.comm
... = pr1 p + pr2 q : H⁻¹
... = pr2 q + pr1 p : by rewrite add.comm
protected theorem equiv.trans [trans] {p q r : ℕ × ℕ} (H1 : p ≡ q) (H2 : q ≡ r) : p ≡ r :=
add.right_cancel (calc
pr1 p + pr2 r + pr2 q = pr1 p + pr2 q + pr2 r : by rewrite add.right_comm
... = pr2 p + pr1 q + pr2 r : {H1}
... = pr2 p + (pr1 q + pr2 r) : by rewrite add.assoc
... = pr2 p + (pr2 q + pr1 r) : {H2}
... = pr2 p + pr2 q + pr1 r : by rewrite add.assoc
... = pr2 p + pr1 r + pr2 q : by rewrite add.right_comm)
protected theorem equiv_equiv : is_equivalence int.equiv :=
is_equivalence.mk @equiv.refl @equiv.symm @equiv.trans
protected theorem equiv_cases {p q : ℕ × ℕ} (H : p ≡ q) :
(pr1 p ≥ pr2 p × pr1 q ≥ pr2 q) ⊎ (pr1 p < pr2 p × pr1 q < pr2 q) :=
sum.elim (@le_sum_gt _ _ (pr2 p) (pr1 p))
(suppose pr1 p ≥ pr2 p,
have pr2 p + pr1 q ≥ pr2 p + pr2 q, from H ▸ add_le_add_right this (pr2 q),
sum.inl (pair `pr1 p ≥ pr2 p` (le_of_add_le_add_left this)))
(suppose H₁ : pr1 p < pr2 p,
have pr2 p + pr1 q < pr2 p + pr2 q, from H ▸ add_lt_add_right H₁ (pr2 q),
sum.inr (pair H₁ (lt_of_add_lt_add_left this)))
protected theorem equiv_of_eq {p q : ℕ × ℕ} (H : p = q) : p ≡ q := H ▸ equiv.refl
/- the representation and abstraction functions -/
definition abstr (a : ℕ × ℕ) : ℤ := sub_nat_nat (pr1 a) (pr2 a)
theorem abstr_of_ge {p : ℕ × ℕ} (H : pr1 p ≥ pr2 p) : abstr p = of_nat (pr1 p - pr2 p) :=
sub_nat_nat_of_ge H
theorem abstr_of_lt {p : ℕ × ℕ} (H : pr1 p < pr2 p) :
abstr p = -[1+ pred (pr2 p - pr1 p)] :=
sub_nat_nat_of_lt H
definition repr : ℤ → ℕ × ℕ
| (of_nat m) := (m, 0)
| -[1+ m] := (0, succ m)
theorem abstr_repr : Π (a : ℤ), abstr (repr a) = a
| (of_nat m) := (sub_nat_nat_of_ge (zero_le m))
| -[1+ m] := rfl
theorem repr_sub_nat_nat (m n : ℕ) : repr (sub_nat_nat m n) ≡ (m, n) :=
nat.lt_ge_by_cases
(take H : m < n,
have H1 : repr (sub_nat_nat m n) = (0, n - m), by
rewrite [sub_nat_nat_of_lt H, -(succ_pred_of_pos (nat.sub_pos_of_lt H))],
H1⁻¹ ▸ (!zero_add ⬝ (nat.sub_add_cancel (le_of_lt H))⁻¹))
(take H : m ≥ n,
have H1 : repr (sub_nat_nat m n) = (m - n, 0), from sub_nat_nat_of_ge H ▸ rfl,
H1⁻¹ ▸ ((nat.sub_add_cancel H) ⬝ !zero_add⁻¹))
theorem repr_abstr (p : ℕ × ℕ) : repr (abstr p) ≡ p :=
!prod.eta ▸ !repr_sub_nat_nat
theorem abstr_eq {p q : ℕ × ℕ} (Hequiv : p ≡ q) : abstr p = abstr q :=
sum.elim (int.equiv_cases Hequiv)
(prod.rec (assume (Hp : pr1 p ≥ pr2 p) (Hq : pr1 q ≥ pr2 q),
have H : pr1 p - pr2 p = pr1 q - pr2 q, from
calc pr1 p - pr2 p
= pr1 p + pr2 q - pr2 q - pr2 p : by rewrite nat.add_sub_cancel
... = pr2 p + pr1 q - pr2 q - pr2 p : Hequiv
... = pr2 p + (pr1 q - pr2 q) - pr2 p : nat.add_sub_assoc Hq
... = pr1 q - pr2 q + pr2 p - pr2 p : by rewrite add.comm
... = pr1 q - pr2 q : by rewrite nat.add_sub_cancel,
abstr_of_ge Hp ⬝ (H ▸ rfl) ⬝ (abstr_of_ge Hq)⁻¹))
(prod.rec (assume (Hp : pr1 p < pr2 p) (Hq : pr1 q < pr2 q),
have H : pr2 p - pr1 p = pr2 q - pr1 q, from
calc pr2 p - pr1 p
= pr2 p + pr1 q - pr1 q - pr1 p : by rewrite nat.add_sub_cancel
... = pr1 p + pr2 q - pr1 q - pr1 p : Hequiv
... = pr1 p + (pr2 q - pr1 q) - pr1 p : nat.add_sub_assoc (le_of_lt Hq)
... = pr2 q - pr1 q + pr1 p - pr1 p : by rewrite add.comm
... = pr2 q - pr1 q : by rewrite nat.add_sub_cancel,
abstr_of_lt Hp ⬝ (H ▸ rfl) ⬝ (abstr_of_lt Hq)⁻¹))
theorem equiv_iff (p q : ℕ × ℕ) : (p ≡ q) ↔ (abstr p = abstr q) :=
iff.intro abstr_eq (assume H, equiv.trans (H ▸ equiv.symm (repr_abstr p)) (repr_abstr q))
theorem equiv_iff3 (p q : ℕ × ℕ) : (p ≡ q) ↔ ((p ≡ p) × (q ≡ q) × (abstr p = abstr q)) :=
iff.trans !equiv_iff (iff.symm
(iff.trans (prod_iff_right !equiv.refl) (prod_iff_right !equiv.refl)))
theorem eq_abstr_of_equiv_repr {a : ℤ} {p : ℕ × ℕ} (Hequiv : repr a ≡ p) : a = abstr p :=
!abstr_repr⁻¹ ⬝ abstr_eq Hequiv
theorem eq_of_repr_equiv_repr {a b : ℤ} (H : repr a ≡ repr b) : a = b :=
eq_abstr_of_equiv_repr H ⬝ !abstr_repr
section
local attribute abstr [reducible]
local attribute dist [reducible]
theorem nat_abs_abstr : Π (p : ℕ × ℕ), nat_abs (abstr p) = dist (pr1 p) (pr2 p)
| (m, n) := nat.lt_ge_by_cases
(assume H : m < n,
calc
nat_abs (abstr (m, n)) = nat_abs (-[1+ pred (n - m)]) : int.abstr_of_lt H
... = n - m : succ_pred_of_pos (nat.sub_pos_of_lt H)
... = dist m n : dist_eq_sub_of_le (le_of_lt H))
(assume H : m ≥ n, (abstr_of_ge H)⁻¹ ▸ (dist_eq_sub_of_ge H)⁻¹)
end
theorem cases_of_nat_succ (a : ℤ) : (Σn : ℕ, a = of_nat n) ⊎ (Σn : ℕ, a = - (of_nat (succ n))) :=
int.cases_on a (take m, sum.inl (sigma.mk _ rfl)) (take m, sum.inr (sigma.mk _ rfl))
theorem cases_of_nat (a : ℤ) : (Σn : ℕ, a = of_nat n) ⊎ (Σn : ℕ, a = - of_nat n) :=
sum.imp_right (sigma.rec (take n, (sigma.mk _))) !cases_of_nat_succ
theorem by_cases_of_nat {P : ℤ → Type} (a : ℤ)
(H1 : Πn : ℕ, P (of_nat n)) (H2 : Πn : ℕ, P (- of_nat n)) :
P a :=
sum.elim (cases_of_nat a)
(assume H, obtain (n : ℕ) (H3 : a = n), from H, H3⁻¹ ▸ H1 n)
(assume H, obtain (n : ℕ) (H3 : a = -n), from H, H3⁻¹ ▸ H2 n)
theorem by_cases_of_nat_succ {P : ℤ → Type} (a : ℤ)
(H1 : Πn : ℕ, P (of_nat n)) (H2 : Πn : ℕ, P (- of_nat (succ n))) :
P a :=
sum.elim (cases_of_nat_succ a)
(assume H, obtain (n : ℕ) (H3 : a = n), from H, H3⁻¹ ▸ H1 n)
(assume H, obtain (n : ℕ) (H3 : a = -(succ n)), from H, H3⁻¹ ▸ H2 n)
/-
int is a ring
-/
/- addition -/
definition padd (p q : ℕ × ℕ) : ℕ × ℕ := (pr1 p + pr1 q, pr2 p + pr2 q)
theorem repr_add : Π (a b : ℤ), repr (add a b) ≡ padd (repr a) (repr b)
| (of_nat m) (of_nat n) := !equiv.refl
| (of_nat m) -[1+ n] :=
begin
change repr (sub_nat_nat m (succ n)) ≡ (m + 0, 0 + succ n),
rewrite [zero_add, add_zero],
apply repr_sub_nat_nat
end
| -[1+ m] (of_nat n) :=
begin
change repr (-[1+ m] + n) ≡ (0 + n, succ m + 0),
rewrite [zero_add, add_zero],
apply repr_sub_nat_nat
end
| -[1+ m] -[1+ n] := !repr_sub_nat_nat
theorem padd_congr {p p' q q' : ℕ × ℕ} (Ha : p ≡ p') (Hb : q ≡ q') : padd p q ≡ padd p' q' :=
calc pr1 p + pr1 q + (pr2 p' + pr2 q')
= pr1 p + pr2 p' + (pr1 q + pr2 q') : add.comm4
... = pr2 p + pr1 p' + (pr1 q + pr2 q') : {Ha}
... = pr2 p + pr1 p' + (pr2 q + pr1 q') : {Hb}
... = pr2 p + pr2 q + (pr1 p' + pr1 q') : add.comm4
theorem padd_comm (p q : ℕ × ℕ) : padd p q = padd q p :=
calc (pr1 p + pr1 q, pr2 p + pr2 q)
= (pr1 q + pr1 p, pr2 p + pr2 q) : by rewrite add.comm
... = (pr1 q + pr1 p, pr2 q + pr2 p) : by rewrite (add.comm (pr2 p) (pr2 q))
theorem padd_assoc (p q r : ℕ × ℕ) : padd (padd p q) r = padd p (padd q r) :=
calc (pr1 p + pr1 q + pr1 r, pr2 p + pr2 q + pr2 r)
= (pr1 p + (pr1 q + pr1 r), pr2 p + pr2 q + pr2 r) : by rewrite add.assoc
... = (pr1 p + (pr1 q + pr1 r), pr2 p + (pr2 q + pr2 r)) : by rewrite add.assoc
protected theorem add_comm (a b : ℤ) : a + b = b + a :=
eq_of_repr_equiv_repr (equiv.trans !repr_add
(equiv.symm (!padd_comm ▸ !repr_add)))
protected theorem add_assoc (a b c : ℤ) : a + b + c = a + (b + c) :=
eq_of_repr_equiv_repr (calc
repr (a + b + c)
≡ padd (repr (a + b)) (repr c) : repr_add
... ≡ padd (padd (repr a) (repr b)) (repr c) : padd_congr !repr_add !equiv.refl
... = padd (repr a) (padd (repr b) (repr c)) : !padd_assoc
... ≡ padd (repr a) (repr (b + c)) : padd_congr !equiv.refl !repr_add
... ≡ repr (a + (b + c)) : repr_add)
protected theorem add_zero : Π (a : ℤ), a + 0 = a := int.rec (λm, rfl) (λm, rfl)
protected theorem zero_add (a : ℤ) : 0 + a = a := !int.add_comm ▸ !int.add_zero
/- negation -/
definition pneg (p : ℕ × ℕ) : ℕ × ℕ := (pr2 p, pr1 p)
-- note: this is =, not just ≡
theorem repr_neg : Π (a : ℤ), repr (- a) = pneg (repr a)
| 0 := rfl
| (succ m) := rfl
| -[1+ m] := rfl
theorem pneg_congr {p p' : ℕ × ℕ} (H : p ≡ p') : pneg p ≡ pneg p' := inverse H
theorem pneg_pneg (p : ℕ × ℕ) : pneg (pneg p) = p := !prod.eta
theorem nat_abs_neg (a : ℤ) : nat_abs (-a) = nat_abs a :=
calc
nat_abs (-a) = nat_abs (abstr (repr (-a))) : abstr_repr
... = nat_abs (abstr (pneg (repr a))) : repr_neg
... = dist (pr1 (pneg (repr a))) (pr2 (pneg (repr a))) : nat_abs_abstr
... = dist (pr2 (pneg (repr a))) (pr1 (pneg (repr a))) : dist.comm
... = nat_abs (abstr (repr a)) : nat_abs_abstr
... = nat_abs a : abstr_repr
theorem padd_pneg (p : ℕ × ℕ) : padd p (pneg p) ≡ (0, 0) :=
show pr1 p + pr2 p + 0 = pr2 p + pr1 p + 0, from !nat.add_comm ▸ rfl
theorem padd_padd_pneg (p q : ℕ × ℕ) : padd (padd p q) (pneg q) ≡ p :=
calc pr1 p + pr1 q + pr2 q + pr2 p
= pr1 p + (pr1 q + pr2 q) + pr2 p : add.assoc
... = pr1 p + (pr1 q + pr2 q + pr2 p) : add.assoc
... = pr1 p + (pr2 q + pr1 q + pr2 p) : add.comm
... = pr1 p + (pr2 q + pr2 p + pr1 q) : add.right_comm
... = pr1 p + (pr2 p + pr2 q + pr1 q) : add.comm
... = pr2 p + pr2 q + pr1 q + pr1 p : add.comm
protected theorem add_left_inv (a : ℤ) : -a + a = 0 :=
have H : repr (-a + a) ≡ repr 0, from
calc
repr (-a + a) ≡ padd (repr (neg a)) (repr a) : repr_add
... = padd (pneg (repr a)) (repr a) : repr_neg
... ≡ repr 0 : padd_pneg,
eq_of_repr_equiv_repr H
/- nat abs -/
definition pabs (p : ℕ × ℕ) : ℕ := dist (pr1 p) (pr2 p)
theorem pabs_congr {p q : ℕ × ℕ} (H : p ≡ q) : pabs p = pabs q :=
calc
pabs p = nat_abs (abstr p) : nat_abs_abstr
... = nat_abs (abstr q) : abstr_eq H
... = pabs q : nat_abs_abstr
theorem nat_abs_eq_pabs_repr (a : ℤ) : nat_abs a = pabs (repr a) :=
calc
nat_abs a = nat_abs (abstr (repr a)) : abstr_repr
... = pabs (repr a) : nat_abs_abstr
theorem nat_abs_add_le (a b : ℤ) : nat_abs (a + b) ≤ nat_abs a + nat_abs b :=
calc
nat_abs (a + b) = pabs (repr (a + b)) : nat_abs_eq_pabs_repr
... = pabs (padd (repr a) (repr b)) : pabs_congr !repr_add
... ≤ pabs (repr a) + pabs (repr b) : dist_add_add_le_add_dist_dist
... = pabs (repr a) + nat_abs b : nat_abs_eq_pabs_repr
... = nat_abs a + nat_abs b : nat_abs_eq_pabs_repr
theorem nat_abs_neg_of_nat (n : nat) : nat_abs (neg_of_nat n) = n :=
begin cases n, reflexivity, reflexivity end
section
local attribute nat_abs [reducible]
theorem nat_abs_mul : Π (a b : ℤ), nat_abs (a * b) = (nat_abs a) * (nat_abs b)
| (of_nat m) (of_nat n) := rfl
| (of_nat m) -[1+ n] := by rewrite [mul_of_nat_neg_succ_of_nat, nat_abs_neg_of_nat]
| -[1+ m] (of_nat n) := by rewrite [mul_neg_succ_of_nat_of_nat, nat_abs_neg_of_nat]
| -[1+ m] -[1+ n] := rfl
end
/- multiplication -/
definition pmul (p q : ℕ × ℕ) : ℕ × ℕ :=
(pr1 p * pr1 q + pr2 p * pr2 q, pr1 p * pr2 q + pr2 p * pr1 q)
theorem repr_neg_of_nat (m : ℕ) : repr (neg_of_nat m) = (0, m) :=
nat.cases_on m rfl (take m', rfl)
-- note: we have =, not just ≡
theorem repr_mul : Π (a b : ℤ), repr (a * b) = pmul (repr a) (repr b)
| (of_nat m) (of_nat n) := calc
(m * n + 0 * 0, m * 0 + 0) = (m * n + 0 * 0, m * 0 + 0 * n) : by rewrite *zero_mul
| (of_nat m) -[1+ n] := calc
repr ((m : int) * -[1+ n]) = (m * 0 + 0, m * succ n + 0 * 0) : repr_neg_of_nat
... = (m * 0 + 0 * succ n, m * succ n + 0 * 0) : by rewrite *zero_mul
| -[1+ m] (of_nat n) := calc
repr (-[1+ m] * (n:int)) = (0 + succ m * 0, succ m * n) : repr_neg_of_nat
... = (0 + succ m * 0, 0 + succ m * n) : nat.zero_add
... = (0 * n + succ m * 0, 0 + succ m * n) : by rewrite zero_mul
| -[1+ m] -[1+ n] := calc
(succ m * succ n, 0) = (succ m * succ n, 0 * succ n) : by rewrite zero_mul
... = (0 + succ m * succ n, 0 * succ n) : nat.zero_add
theorem equiv_mul_prep {xa ya xb yb xn yn xm ym : ℕ}
(H1 : xa + yb = ya + xb) (H2 : xn + ym = yn + xm)
: xa*xn+ya*yn+(xb*ym+yb*xm) = xa*yn+ya*xn+(xb*xm+yb*ym) :=
nat.add_right_cancel (calc
xa*xn+ya*yn + (xb*ym+yb*xm) + (yb*xn+xb*yn + (xb*xn+yb*yn))
= xa*xn+ya*yn + (yb*xn+xb*yn) + (xb*ym+yb*xm + (xb*xn+yb*yn)) : by rewrite add.comm4
... = xa*xn+ya*yn + (yb*xn+xb*yn) + (xb*xn+yb*yn + (xb*ym+yb*xm)) : by rewrite {xb*ym+yb*xm +_}nat.add_comm
... = xa*xn+yb*xn + (ya*yn+xb*yn) + (xb*xn+xb*ym + (yb*yn+yb*xm)) : by exact !congr_arg2 !add.comm4 !add.comm4
... = ya*xn+xb*xn + (xa*yn+yb*yn) + (xb*yn+xb*xm + (yb*xn+yb*ym)) : by rewrite[-+left_distrib,-+right_distrib]; exact H1 ▸ H2 ▸ rfl
... = ya*xn+xa*yn + (xb*xn+yb*yn) + (xb*yn+yb*xn + (xb*xm+yb*ym)) : by exact !congr_arg2 !add.comm4 !add.comm4
... = xa*yn+ya*xn + (xb*xn+yb*yn) + (xb*yn+yb*xn + (xb*xm+yb*ym)) : by rewrite {xa*yn + _}nat.add_comm
... = xa*yn+ya*xn + (xb*xn+yb*yn) + (yb*xn+xb*yn + (xb*xm+yb*ym)) : by rewrite {xb*yn + _}nat.add_comm
... = xa*yn+ya*xn + (yb*xn+xb*yn) + (xb*xn+yb*yn + (xb*xm+yb*ym)) : by rewrite (!add.comm4)
... = xa*yn+ya*xn + (yb*xn+xb*yn) + (xb*xm+yb*ym + (xb*xn+yb*yn)) : by rewrite {xb*xn+yb*yn + _}nat.add_comm
... = xa*yn+ya*xn + (xb*xm+yb*ym) + (yb*xn+xb*yn + (xb*xn+yb*yn)) : by rewrite add.comm4)
theorem pmul_congr {p p' q q' : ℕ × ℕ} : p ≡ p' → q ≡ q' → pmul p q ≡ pmul p' q' := equiv_mul_prep
theorem pmul_comm (p q : ℕ × ℕ) : pmul p q = pmul q p :=
show (_,_) = (_,_),
begin
congruence,
{ congruence, repeat rewrite mul.comm },
{ rewrite add.comm, congruence, repeat rewrite mul.comm }
end
protected theorem mul_comm (a b : ℤ) : a * b = b * a :=
eq_of_repr_equiv_repr
((calc
repr (a * b) = pmul (repr a) (repr b) : repr_mul
... = pmul (repr b) (repr a) : pmul_comm
... = repr (b * a) : repr_mul) ▸ !equiv.refl)
private theorem pmul_assoc_prep {p1 p2 q1 q2 r1 r2 : ℕ} :
((p1*q1+p2*q2)*r1+(p1*q2+p2*q1)*r2, (p1*q1+p2*q2)*r2+(p1*q2+p2*q1)*r1) =
(p1*(q1*r1+q2*r2)+p2*(q1*r2+q2*r1), p1*(q1*r2+q2*r1)+p2*(q1*r1+q2*r2)) :=
begin
rewrite [+left_distrib, +right_distrib, *mul.assoc],
rewrite (add.comm4 (p1 * (q1 * r1)) (p2 * (q2 * r1)) (p1 * (q2 * r2)) (p2 * (q1 * r2))),
rewrite (add.comm (p2 * (q2 * r1)) (p2 * (q1 * r2))),
rewrite (add.comm4 (p1 * (q1 * r2)) (p2 * (q2 * r2)) (p1 * (q2 * r1)) (p2 * (q1 * r1))),
rewrite (add.comm (p2 * (q2 * r2)) (p2 * (q1 * r1)))
end
theorem pmul_assoc (p q r: ℕ × ℕ) : pmul (pmul p q) r = pmul p (pmul q r) := pmul_assoc_prep
protected theorem mul_assoc (a b c : ℤ) : (a * b) * c = a * (b * c) :=
eq_of_repr_equiv_repr
((calc
repr (a * b * c) = pmul (repr (a * b)) (repr c) : repr_mul
... = pmul (pmul (repr a) (repr b)) (repr c) : repr_mul
... = pmul (repr a) (pmul (repr b) (repr c)) : pmul_assoc
... = pmul (repr a) (repr (b * c)) : repr_mul
... = repr (a * (b * c)) : repr_mul) ▸ !equiv.refl)
protected theorem mul_one : Π (a : ℤ), a * 1 = a
| (of_nat m) := !int.zero_add -- zero_add happens to be def. = to this thm
| -[1+ m] := !nat.zero_add ▸ rfl
protected theorem one_mul (a : ℤ) : 1 * a = a :=
int.mul_comm a 1 ▸ int.mul_one a
private theorem mul_distrib_prep {a1 a2 b1 b2 c1 c2 : ℕ} :
((a1+b1)*c1+(a2+b2)*c2, (a1+b1)*c2+(a2+b2)*c1) =
(a1*c1+a2*c2+(b1*c1+b2*c2), a1*c2+a2*c1+(b1*c2+b2*c1)) :=
begin
rewrite +right_distrib, congruence,
{rewrite add.comm4},
{rewrite add.comm4}
end
protected theorem right_distrib (a b c : ℤ) : (a + b) * c = a * c + b * c :=
eq_of_repr_equiv_repr
(calc
repr ((a + b) * c) = pmul (repr (a + b)) (repr c) : repr_mul
... ≡ pmul (padd (repr a) (repr b)) (repr c) : pmul_congr !repr_add equiv.refl
... = padd (pmul (repr a) (repr c)) (pmul (repr b) (repr c)) : mul_distrib_prep
... = padd (repr (a * c)) (pmul (repr b) (repr c)) : repr_mul
... = padd (repr (a * c)) (repr (b * c)) : repr_mul
... ≡ repr (a * c + b * c) : repr_add)
protected theorem left_distrib (a b c : ℤ) : a * (b + c) = a * b + a * c :=
calc
a * (b + c) = (b + c) * a : int.mul_comm
... = b * a + c * a : int.right_distrib
... = a * b + c * a : int.mul_comm
... = a * b + a * c : int.mul_comm
protected theorem zero_ne_one : (0 : int) ≠ 1 :=
assume H : 0 = 1, !succ_ne_zero (of_nat.inj H)⁻¹
protected theorem eq_zero_sum_eq_zero_of_mul_eq_zero {a b : ℤ} (H : a * b = 0) : a = 0 ⊎ b = 0 :=
sum.imp eq_zero_of_nat_abs_eq_zero eq_zero_of_nat_abs_eq_zero
(eq_zero_sum_eq_zero_of_mul_eq_zero (by rewrite [-nat_abs_mul, H]))
protected definition integral_domain [reducible] [trans_instance] : integral_domain int :=
⦃integral_domain,
add := int.add,
add_assoc := int.add_assoc,
zero := 0,
zero_add := int.zero_add,
add_zero := int.add_zero,
neg := int.neg,
add_left_inv := int.add_left_inv,
add_comm := int.add_comm,
mul := int.mul,
mul_assoc := int.mul_assoc,
one := 1,
one_mul := int.one_mul,
mul_one := int.mul_one,
left_distrib := int.left_distrib,
right_distrib := int.right_distrib,
mul_comm := int.mul_comm,
zero_ne_one := int.zero_ne_one,
eq_zero_sum_eq_zero_of_mul_eq_zero := @int.eq_zero_sum_eq_zero_of_mul_eq_zero,
is_hset_carrier := is_hset_of_decidable_eq⦄
definition int_has_sub [reducible] [instance] [priority int.prio] : has_sub int :=
has_sub.mk has_sub.sub
definition int_has_dvd [reducible] [instance] [priority int.prio] : has_dvd int :=
has_dvd.mk has_dvd.dvd
/- additional properties -/
theorem of_nat_sub {m n : ℕ} (H : m ≥ n) : of_nat (m - n) = of_nat m - of_nat n :=
assert m - n + n = m, from nat.sub_add_cancel H,
begin
symmetry,
apply sub_eq_of_eq_add,
rewrite [-of_nat_add, this]
end
theorem neg_succ_of_nat_eq' (m : ℕ) : -[1+ m] = -m - 1 :=
by rewrite [neg_succ_of_nat_eq, neg_add]
definition succ (a : ℤ) := a + (succ zero)
definition pred (a : ℤ) := a - (succ zero)
definition nat_succ_eq_int_succ (n : ℕ) : nat.succ n = int.succ n := idp
theorem pred_succ (a : ℤ) : pred (succ a) = a := !sub_add_cancel
theorem succ_pred (a : ℤ) : succ (pred a) = a := !add_sub_cancel
theorem neg_succ (a : ℤ) : -succ a = pred (-a) :=
by rewrite [↑succ,neg_add]
theorem succ_neg_succ (a : ℤ) : succ (-succ a) = -a :=
by rewrite [neg_succ,succ_pred]
theorem neg_pred (a : ℤ) : -pred a = succ (-a) :=
by rewrite [↑pred,neg_sub,sub_eq_add_neg,add.comm]
theorem pred_neg_pred (a : ℤ) : pred (-pred a) = -a :=
by rewrite [neg_pred,pred_succ]
theorem pred_nat_succ (n : ℕ) : pred (nat.succ n) = n := pred_succ n
theorem neg_nat_succ (n : ℕ) : -nat.succ n = pred (-n) := !neg_succ
theorem succ_neg_nat_succ (n : ℕ) : succ (-nat.succ n) = -n := !succ_neg_succ
definition rec_nat_on [unfold 2] {P : ℤ → Type} (z : ℤ) (H0 : P 0)
(Hsucc : Π⦃n : ℕ⦄, P n → P (succ n)) (Hpred : Π⦃n : ℕ⦄, P (-n) → P (-nat.succ n)) : P z :=
int.rec (nat.rec H0 Hsucc) (λn, nat.rec H0 Hpred (nat.succ n)) z
--the only computation rule of rec_nat_on which is not definitional
theorem rec_nat_on_neg {P : ℤ → Type} (n : ℕ) (H0 : P zero)
(Hsucc : Π⦃n : ℕ⦄, P n → P (succ n)) (Hpred : Π⦃n : ℕ⦄, P (-n) → P (-nat.succ n))
: rec_nat_on (-nat.succ n) H0 Hsucc Hpred = Hpred (rec_nat_on (-n) H0 Hsucc Hpred) :=
nat.rec rfl (λn H, rfl) n
end int
|
9c919c33fe402cd1fa34ee8a968fddc50da09dff | f5f7e6fae601a5fe3cac7cc3ed353ed781d62419 | /src/tactic/ring.lean | 0bfe3e6667afc35410fc2456b65e26ebd70faa1a | [
"Apache-2.0"
] | permissive | EdAyers/mathlib | 9ecfb2f14bd6caad748b64c9c131befbff0fb4e0 | ca5d4c1f16f9c451cf7170b10105d0051db79e1b | refs/heads/master | 1,626,189,395,845 | 1,555,284,396,000 | 1,555,284,396,000 | 144,004,030 | 0 | 0 | Apache-2.0 | 1,533,727,664,000 | 1,533,727,663,000 | null | UTF-8 | Lean | false | false | 18,877 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
Evaluate expressions in the language of (semi-)rings.
Based on http://www.cs.ru.nl/~freek/courses/tt-2014/read/10.1.1.61.3041.pdf .
-/
import algebra.group_power tactic.norm_num
import tactic.converter.interactive
namespace tactic
namespace ring
def horner {α} [comm_semiring α] (a x : α) (n : ℕ) (b : α) := a * x ^ n + b
meta structure cache :=
(α : expr)
(univ : level)
(comm_semiring_inst : expr)
meta def mk_cache (e : expr) : tactic cache :=
do α ← infer_type e,
c ← mk_app ``comm_semiring [α] >>= mk_instance,
u ← mk_meta_univ,
infer_type α >>= unify (expr.sort (level.succ u)),
u ← get_univ_assignment u,
return ⟨α, u, c⟩
meta def cache.cs_app (c : cache) (n : name) : list expr → expr :=
(@expr.const tt n [c.univ] c.α c.comm_semiring_inst).mk_app
meta def cache.mk_app (c : cache) (n inst : name) (l : list expr) : tactic expr :=
do m ← mk_instance ((expr.const inst [c.univ] : expr) c.α),
return $ (@expr.const tt n [c.univ] c.α m).mk_app l
meta inductive horner_expr : Type
| const (e : expr) : horner_expr
| xadd (e : expr) (a : horner_expr) (x : expr) (n : expr × ℕ) (b : horner_expr) : horner_expr
meta def horner_expr.e : horner_expr → expr
| (horner_expr.const e) := e
| (horner_expr.xadd e _ _ _ _) := e
meta instance : has_coe horner_expr expr := ⟨horner_expr.e⟩
meta def horner_expr.xadd' (c : cache) (a : horner_expr) (x : expr) (n : expr × ℕ) (b : horner_expr): horner_expr :=
horner_expr.xadd (c.cs_app ``horner [a, x, n.1, b]) a x n b
open horner_expr
meta def horner_expr.to_string : horner_expr → string
| (const e) := to_string e
| (xadd e a x (_, n) b) :=
"(" ++ a.to_string ++ ") * (" ++ to_string x ++ ")^"
++ to_string n ++ " + " ++ b.to_string
meta def horner_expr.pp : horner_expr → tactic format
| (const e) := pp e
| (xadd e a x (_, n) b) := do
pa ← a.pp, pb ← b.pp, px ← pp x,
return $ "(" ++ pa ++ ") * (" ++ px ++ ")^" ++ to_string n ++ " + " ++ pb
meta instance : has_to_tactic_format horner_expr := ⟨horner_expr.pp⟩
meta def horner_expr.refl_conv (e : horner_expr) : tactic (horner_expr × expr) :=
do p ← mk_eq_refl e, return (e, p)
theorem zero_horner {α} [comm_semiring α] (x n b) :
@horner α _ 0 x n b = b :=
by simp [horner]
theorem horner_horner {α} [comm_semiring α] (a₁ x n₁ n₂ b n')
(h : n₁ + n₂ = n') :
@horner α _ (horner a₁ x n₁ 0) x n₂ b = horner a₁ x n' b :=
by simp [h.symm, horner, pow_add, mul_assoc]
meta def eval_horner (c : cache) : horner_expr → expr → expr × ℕ → horner_expr → tactic (horner_expr × expr)
| ha@(const a) x n b :=
if a.to_nat = some 0 then
return (b, c.cs_app ``zero_horner [x, n.1, b])
else (xadd' c ha x n b).refl_conv
| ha@(xadd a a₁ x₁ n₁ b₁) x n b :=
if x₁ = x ∧ b₁.e.to_nat = some 0 then do
(n', h) ← mk_app ``has_add.add [n₁.1, n.1] >>= norm_num,
return (xadd' c a₁ x (n', n₁.2 + n.2) b,
c.cs_app ``horner_horner [a₁, x, n₁.1, n.1, b, n', h])
else (xadd' c ha x n b).refl_conv
theorem const_add_horner {α} [comm_semiring α] (k a x n b b') (h : k + b = b') :
k + @horner α _ a x n b = horner a x n b' :=
by simp [h.symm, horner]
theorem horner_add_const {α} [comm_semiring α] (a x n b k b') (h : b + k = b') :
@horner α _ a x n b + k = horner a x n b' :=
by simp [h.symm, horner]
theorem horner_add_horner_lt {α} [comm_semiring α] (a₁ x n₁ b₁ a₂ n₂ b₂ k a' b')
(h₁ : n₁ + k = n₂) (h₂ : (a₁ + horner a₂ x k 0 : α) = a') (h₃ : b₁ + b₂ = b') :
@horner α _ a₁ x n₁ b₁ + horner a₂ x n₂ b₂ = horner a' x n₁ b' :=
by simp [h₂.symm, h₃.symm, h₁.symm, horner, pow_add, mul_add, mul_comm, mul_left_comm]
theorem horner_add_horner_gt {α} [comm_semiring α] (a₁ x n₁ b₁ a₂ n₂ b₂ k a' b')
(h₁ : n₂ + k = n₁) (h₂ : (horner a₁ x k 0 + a₂ : α) = a') (h₃ : b₁ + b₂ = b') :
@horner α _ a₁ x n₁ b₁ + horner a₂ x n₂ b₂ = horner a' x n₂ b' :=
by simp [h₂.symm, h₃.symm, h₁.symm, horner, pow_add, mul_add, mul_comm, mul_left_comm]
theorem horner_add_horner_eq {α} [comm_semiring α] (a₁ x n b₁ a₂ b₂ a' b' t)
(h₁ : a₁ + a₂ = a') (h₂ : b₁ + b₂ = b') (h₃ : horner a' x n b' = t) :
@horner α _ a₁ x n b₁ + horner a₂ x n b₂ = t :=
by simp [h₃.symm, h₂.symm, h₁.symm, horner, add_mul, mul_comm]
meta def eval_add (c : cache) : horner_expr → horner_expr → tactic (horner_expr × expr)
| (const e₁) (const e₂) := do
(e, p) ← mk_app ``has_add.add [e₁, e₂] >>= norm_num,
return (const e, p)
| he₁@(const e₁) he₂@(xadd e₂ a x n b) :=
if e₁.to_nat = some 0 then do
p ← mk_app ``zero_add [e₂],
return (he₂, p)
else do
(b', h) ← eval_add he₁ b,
return (xadd' c a x n b',
c.cs_app ``const_add_horner [e₁, a, x, n.1, b, b', h])
| he₁@(xadd e₁ a x n b) he₂@(const e₂) :=
if e₂.to_nat = some 0 then do
p ← mk_app ``add_zero [e₁],
return (he₁, p)
else do
(b', h) ← eval_add b he₂,
return (xadd' c a x n b',
c.cs_app ``horner_add_const [a, x, n.1, b, e₂, b', h])
| he₁@(xadd e₁ a₁ x₁ n₁ b₁) he₂@(xadd e₂ a₂ x₂ n₂ b₂) :=
if expr.lex_lt x₁ x₂ then do
(b', h) ← eval_add b₁ he₂,
return (xadd' c a₁ x₁ n₁ b',
c.cs_app ``horner_add_const [a₁, x₁, n₁.1, b₁, e₂, b', h])
else if x₁ ≠ x₂ then do
(b', h) ← eval_add he₁ b₂,
return (xadd' c a₂ x₂ n₂ b',
c.cs_app ``const_add_horner [e₁, a₂, x₂, n₂.1, b₂, b', h])
else if n₁.2 < n₂.2 then do
let k := n₂.2 - n₁.2,
ek ← expr.of_nat (expr.const `nat []) k,
(_, h₁) ← mk_app ``has_add.add [n₁.1, ek] >>= norm_num,
α0 ← expr.of_nat c.α 0,
(a', h₂) ← eval_add a₁ (xadd' c a₂ x₁ (ek, k) (const α0)),
(b', h₃) ← eval_add b₁ b₂,
return (xadd' c a' x₁ n₁ b',
c.cs_app ``horner_add_horner_lt [a₁, x₁, n₁.1, b₁, a₂, n₂.1, b₂, ek, a', b', h₁, h₂, h₃])
else if n₁ ≠ n₂ then do
let k := n₁.2 - n₂.2,
ek ← expr.of_nat (expr.const `nat []) k,
(_, h₁) ← mk_app ``has_add.add [n₂.1, ek] >>= norm_num,
α0 ← expr.of_nat c.α 0,
(a', h₂) ← eval_add (xadd' c a₁ x₁ (ek, k) (const α0)) a₂,
(b', h₃) ← eval_add b₁ b₂,
return (xadd' c a' x₁ n₂ b',
c.cs_app ``horner_add_horner_gt [a₁, x₁, n₁.1, b₁, a₂, n₂.1, b₂, ek, a', b', h₁, h₂, h₃])
else do
(a', h₁) ← eval_add a₁ a₂,
(b', h₂) ← eval_add b₁ b₂,
(t, h₃) ← eval_horner c a' x₁ n₁ b',
return (t, c.cs_app ``horner_add_horner_eq
[a₁, x₁, n₁.1, b₁, a₂, b₂, a', b', t, h₁, h₂, h₃])
theorem horner_neg {α} [comm_ring α] (a x n b a' b')
(h₁ : -a = a') (h₂ : -b = b') :
-@horner α _ a x n b = horner a' x n b' :=
by simp [h₂.symm, h₁.symm, horner]
meta def eval_neg (c : cache) : horner_expr → tactic (horner_expr × expr)
| (const e) := do
(e', p) ← mk_app ``has_neg.neg [e] >>= norm_num,
return (const e', p)
| (xadd e a x n b) := do
(a', h₁) ← eval_neg a,
(b', h₂) ← eval_neg b,
p ← c.mk_app ``horner_neg ``comm_ring [a, x, n.1, b, a', b', h₁, h₂],
return (xadd' c a' x n b', p)
theorem horner_const_mul {α} [comm_semiring α] (c a x n b a' b')
(h₁ : c * a = a') (h₂ : c * b = b') :
c * @horner α _ a x n b = horner a' x n b' :=
by simp [h₂.symm, h₁.symm, horner, mul_add, mul_assoc]
theorem horner_mul_const {α} [comm_semiring α] (a x n b c a' b')
(h₁ : a * c = a') (h₂ : b * c = b') :
@horner α _ a x n b * c = horner a' x n b' :=
by simp [h₂.symm, h₁.symm, horner, add_mul, mul_right_comm]
meta def eval_const_mul (c : cache) (k : expr) :
horner_expr → tactic (horner_expr × expr)
| (const e) := do
(e', p) ← mk_app ``has_mul.mul [k, e] >>= norm_num,
return (const e', p)
| (xadd e a x n b) := do
(a', h₁) ← eval_const_mul a,
(b', h₂) ← eval_const_mul b,
return (xadd' c a' x n b',
c.cs_app ``horner_const_mul [k, a, x, n.1, b, a', b', h₁, h₂])
theorem horner_mul_horner_zero {α} [comm_semiring α] (a₁ x n₁ b₁ a₂ n₂ aa t)
(h₁ : @horner α _ a₁ x n₁ b₁ * a₂ = aa)
(h₂ : horner aa x n₂ 0 = t) :
horner a₁ x n₁ b₁ * horner a₂ x n₂ 0 = t :=
by rw [← h₂, ← h₁];
simp [horner, mul_add, mul_comm, mul_left_comm, mul_assoc]
theorem horner_mul_horner {α} [comm_semiring α]
(a₁ x n₁ b₁ a₂ n₂ b₂ aa haa ab bb t)
(h₁ : @horner α _ a₁ x n₁ b₁ * a₂ = aa)
(h₂ : horner aa x n₂ 0 = haa)
(h₃ : a₁ * b₂ = ab) (h₄ : b₁ * b₂ = bb)
(H : haa + horner ab x n₁ bb = t) :
horner a₁ x n₁ b₁ * horner a₂ x n₂ b₂ = t :=
by rw [← H, ← h₂, ← h₁, ← h₃, ← h₄];
simp [horner, mul_add, mul_comm, mul_left_comm, mul_assoc]
meta def eval_mul (c : cache) : horner_expr → horner_expr → tactic (horner_expr × expr)
| (const e₁) (const e₂) := do
(e', p) ← mk_app ``has_mul.mul [e₁, e₂] >>= norm_num,
return (const e', p)
| (const e₁) e₂ :=
match e₁.to_nat with
| (some 0) := do
α0 ← expr.of_nat c.α 0,
p ← mk_app ``zero_mul [e₂],
return (const α0, p)
| (some 1) := do
p ← mk_app ``one_mul [e₂],
return (e₂, p)
| _ := eval_const_mul c e₁ e₂
end
| e₁ he₂@(const e₂) := do
p₁ ← mk_app ``mul_comm [e₁, e₂],
(e', p₂) ← eval_mul he₂ e₁,
p ← mk_eq_trans p₁ p₂, return (e', p)
| he₁@(xadd e₁ a₁ x₁ n₁ b₁) he₂@(xadd e₂ a₂ x₂ n₂ b₂) :=
if expr.lex_lt x₁ x₂ then do
(a', h₁) ← eval_mul a₁ he₂,
(b', h₂) ← eval_mul b₁ he₂,
return (xadd' c a' x₁ n₁ b',
c.cs_app ``horner_mul_const [a₁, x₁, n₁.1, b₁, e₂, a', b', h₁, h₂])
else if x₁ ≠ x₂ then do
(a', h₁) ← eval_mul he₁ a₂,
(b', h₂) ← eval_mul he₁ b₂,
return (xadd' c a' x₂ n₂ b',
c.cs_app ``horner_const_mul [e₁, a₂, x₂, n₂.1, b₂, a', b', h₁, h₂])
else do
(aa, h₁) ← eval_mul he₁ a₂,
α0 ← expr.of_nat c.α 0,
(haa, h₂) ← eval_horner c aa x₁ n₂ (const α0),
if b₂.e.to_nat = some 0 then
return (haa, c.cs_app ``horner_mul_horner_zero
[a₁, x₁, n₁.1, b₁, a₂, n₂.1, aa, haa, h₁, h₂])
else do
(ab, h₃) ← eval_mul a₁ b₂,
(bb, h₄) ← eval_mul b₁ b₂,
(t, H) ← eval_add c haa (xadd' c ab x₁ n₁ bb),
return (t, c.cs_app ``horner_mul_horner
[a₁, x₁, n₁.1, b₁, a₂, n₂.1, b₂, aa, haa, ab, bb, t, h₁, h₂, h₃, h₄, H])
theorem horner_pow {α} [comm_semiring α] (a x n m n' a')
(h₁ : n * m = n') (h₂ : a ^ m = a') :
@horner α _ a x n 0 ^ m = horner a' x n' 0 :=
by simp [h₁.symm, h₂.symm, horner, mul_pow, pow_mul]
meta def eval_pow (c : cache) : horner_expr → expr × ℕ → tactic (horner_expr × expr)
| e (_, 0) := do
α1 ← expr.of_nat c.α 1,
p ← mk_app ``pow_zero [e],
return (const α1, p)
| e (_, 1) := do
p ← mk_app ``pow_one [e],
return (e, p)
| (const e) (e₂, m) := do
(e', p) ← mk_app ``monoid.pow [e, e₂] >>= norm_num.derive,
return (const e', p)
| he@(xadd e a x n b) m :=
let N : expr := expr.const `nat [] in
match b.e.to_nat with
| some 0 := do
(n', h₁) ← mk_app ``has_mul.mul [n.1, m.1] >>= norm_num,
(a', h₂) ← eval_pow a m,
α0 ← expr.of_nat c.α 0,
return (xadd' c a' x (n', n.2 * m.2) (const α0),
c.cs_app ``horner_pow [a, x, n.1, m.1, n', a', h₁, h₂])
| _ := do
e₂ ← expr.of_nat N (m.2-1),
l ← mk_app ``monoid.pow [e, e₂],
(tl, hl) ← eval_pow he (e₂, m.2-1),
(t, p₂) ← eval_mul c tl he,
hr ← mk_eq_refl e,
p₂ ← c.mk_app ``norm_num.subst_into_prod ``has_mul [l, e, tl, e, t, hl, hr, p₂],
p₁ ← mk_app ``pow_succ' [e, e₂],
p ← mk_eq_trans p₁ p₂,
return (t, p)
end
theorem horner_atom {α} [comm_semiring α] (x : α) : x = horner 1 x 1 0 :=
by simp [horner]
meta def eval_atom (c : cache) (e : expr) : tactic (horner_expr × expr) :=
do α0 ← expr.of_nat c.α 0,
α1 ← expr.of_nat c.α 1,
n1 ← expr.of_nat (expr.const `nat []) 1,
return (xadd' c (const α1) e (n1, 1) (const α0), c.cs_app ``horner_atom [e])
lemma subst_into_pow {α} [monoid α] (l r tl tr t)
(prl : (l : α) = tl) (prr : (r : ℕ) = tr) (prt : tl ^ tr = t) : l ^ r = t :=
by simp [prl, prr, prt]
lemma unfold_sub {α} [add_group α] (a b c : α)
(h : a + -b = c) : a - b = c := h
lemma unfold_div {α} [division_ring α] (a b c : α)
(h : a * b⁻¹ = c) : a / b = c := h
meta def eval (c : cache) : expr → tactic (horner_expr × expr)
| `(%%e₁ + %%e₂) := do
(e₁', p₁) ← eval e₁,
(e₂', p₂) ← eval e₂,
(e', p') ← eval_add c e₁' e₂',
p ← c.mk_app ``norm_num.subst_into_sum ``has_add [e₁, e₂, e₁', e₂', e', p₁, p₂, p'],
return (e', p)
| `(%%e₁ - %%e₂) := do
e₂' ← mk_app ``has_neg.neg [e₂],
e ← mk_app ``has_add.add [e₁, e₂'],
(e', p) ← eval e,
p' ← c.mk_app ``unfold_sub ``add_group [e₁, e₂, e', p],
return (e', p')
| `(- %%e) := do
(e₁, p₁) ← eval e,
(e₂, p₂) ← eval_neg c e₁,
p ← c.mk_app ``norm_num.subst_into_neg ``has_neg [e, e₁, e₂, p₁, p₂],
return (e₂, p)
| `(%%e₁ * %%e₂) := do
(e₁', p₁) ← eval e₁,
(e₂', p₂) ← eval e₂,
(e', p') ← eval_mul c e₁' e₂',
p ← c.mk_app ``norm_num.subst_into_prod ``has_mul [e₁, e₂, e₁', e₂', e', p₁, p₂, p'],
return (e', p)
| e@`(has_inv.inv %%_) := (do
(e', p) ← norm_num.derive e,
e'.to_rat,
return (const e', p)) <|> eval_atom c e
| `(%%e₁ / %%e₂) := do
e₂' ← mk_app ``has_inv.inv [e₂],
e ← mk_app ``has_mul.mul [e₁, e₂'],
(e', p) ← eval e,
p' ← c.mk_app ``unfold_div ``division_ring [e₁, e₂, e', p],
return (e', p')
| e@`(@has_pow.pow _ _ %%P %%e₁ %%e₂) := do
(e₂', p₂) ← eval e₂,
match e₂'.e.to_nat, P with
| some k, `(monoid.has_pow) := do
(e₁', p₁) ← eval e₁,
(e', p') ← eval_pow c e₁' (e₂, k),
p ← c.mk_app ``subst_into_pow ``monoid [e₁, e₂, e₁', e₂', e', p₁, p₂, p'],
return (e', p)
| some k, `(nat.has_pow) := do
(e₁', p₁) ← eval e₁,
(e', p') ← eval_pow c e₁' (e₂, k),
p₃ ← c.mk_app ``subst_into_pow ``monoid [e₁, e₂, e₁', e₂', e', p₁, p₂, p'],
p₄ ← mk_app ``nat.pow_eq_pow [e₁, e₂] >>= mk_eq_symm,
p ← mk_eq_trans p₄ p₃,
return (e', p)
| _, _ := eval_atom c e
end
| e := match e.to_nat with
| some n := (const e).refl_conv
| none := eval_atom c e
end
meta def eval' (c : cache) (e : expr) : tactic (expr × expr) :=
do (e', p) ← eval c e, return (e', p)
theorem horner_def' {α} [comm_semiring α] (a x n b) : @horner α _ a x n b = x ^ n * a + b :=
by simp [horner, mul_comm]
theorem mul_assoc_rev {α} [semigroup α] (a b c : α) : a * (b * c) = a * b * c :=
by simp [mul_assoc]
theorem pow_add_rev {α} [monoid α] (a b : α) (m n : ℕ) : a ^ m * a ^ n = a ^ (m + n) :=
by simp [pow_add]
theorem pow_add_rev_right {α} [monoid α] (a b : α) (m n : ℕ) : b * a ^ m * a ^ n = b * a ^ (m + n) :=
by simp [pow_add, mul_assoc]
theorem add_neg_eq_sub {α} [add_group α] (a b : α) : a + -b = a - b := rfl
@[derive has_reflect]
inductive normalize_mode | raw | SOP | horner
meta def normalize (mode := normalize_mode.horner) (e : expr) : tactic (expr × expr) := do
pow_lemma ← simp_lemmas.mk.add_simp ``pow_one,
let lemmas := match mode with
| normalize_mode.SOP :=
[``horner_def', ``add_zero, ``mul_one, ``mul_add, ``mul_sub,
``mul_assoc_rev, ``pow_add_rev, ``pow_add_rev_right,
``mul_neg_eq_neg_mul_symm, ``add_neg_eq_sub]
| normalize_mode.horner :=
[``horner.equations._eqn_1, ``add_zero, ``one_mul, ``pow_one,
``neg_mul_eq_neg_mul_symm, ``add_neg_eq_sub]
| _ := []
end,
lemmas ← lemmas.mfoldl simp_lemmas.add_simp simp_lemmas.mk,
(_, e', pr) ← ext_simplify_core () {}
simp_lemmas.mk (λ _, failed) (λ _ _ _ _ e, do
c ← mk_cache e,
(new_e, pr) ← match mode with
| normalize_mode.raw := eval' c
| normalize_mode.horner := trans_conv (eval' c) (simplify lemmas [])
| normalize_mode.SOP :=
trans_conv (eval' c) $
trans_conv (simplify lemmas []) $
simp_bottom_up' (λ e, norm_num e <|> pow_lemma.rewrite e)
end e,
guard (¬ new_e =ₐ e),
return ((), new_e, some pr, ff))
(λ _ _ _ _ _, failed) `eq e,
return (e', pr)
end ring
namespace interactive
open interactive interactive.types lean.parser
open tactic.ring
local postfix `?`:9001 := optional
/-- Tactic for solving equations in the language of rings.
This version of `ring` fails if the target is not an equality
that is provable by the axioms of commutative (semi)rings. -/
meta def ring1 : tactic unit :=
do `(%%e₁ = %%e₂) ← target,
c ← mk_cache e₁,
(e₁', p₁) ← eval c e₁,
(e₂', p₂) ← eval c e₂,
is_def_eq e₁' e₂',
p ← mk_eq_symm p₂ >>= mk_eq_trans p₁,
tactic.exact p
meta def ring.mode : lean.parser ring.normalize_mode :=
with_desc "(SOP|raw|horner)?" $
do mode ← ident?, match mode with
| none := return ring.normalize_mode.horner
| some `horner := return ring.normalize_mode.horner
| some `SOP := return ring.normalize_mode.SOP
| some `raw := return ring.normalize_mode.raw
| _ := failed
end
/-- Tactic for solving equations in the language of rings.
Attempts to prove the goal outright if there is no `at`
specifier and the target is an equality, but if this
fails it falls back to rewriting all ring expressions
into a normal form. When writing a normal form,
`ring SOP` will use sum-of-products form instead of horner form. -/
meta def ring (SOP : parse ring.mode) (loc : parse location) : tactic unit :=
match loc with
| interactive.loc.ns [none] := ring1
| _ := failed
end <|>
do ns ← loc.get_locals,
tt ← tactic.replace_at (normalize SOP) ns loc.include_goal
| fail "ring failed to simplify",
when loc.include_goal $ try tactic.reflexivity
end interactive
end tactic
namespace conv.interactive
open conv interactive
open tactic tactic.interactive (ring.mode ring1)
open tactic.ring (normalize)
meta def ring (SOP : parse ring.mode) : conv unit :=
discharge_eq_lhs ring1
<|> replace_lhs (normalize SOP)
<|> fail "ring failed to simplify"
end conv.interactive
|
b8aa7fd43cf38687e859efff40aeb0e3a12a268a | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/data/dlist/instances.lean | eb0587f9f079b114e7a6b62b37f6f137cc0c79aa | [] | 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 | 963 | lean | /-
Copyright (c) 2018 Simon Hudon. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Simon Hudon
Traversable instance for dlists.
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.Lean3Lib.data.dlist
import Mathlib.control.traversable.equiv
import Mathlib.control.traversable.instances
import Mathlib.PostPort
universes u_1
namespace Mathlib
namespace dlist
/-- The natural equivalence between lists and difference lists, using
`dlist.of_list` and `dlist.to_list`. -/
def list_equiv_dlist (α : Type u_1) : List α ≃ dlist α :=
equiv.mk of_list to_list sorry sorry
protected instance traversable : traversable dlist :=
equiv.traversable list_equiv_dlist
protected instance is_lawful_traversable : is_lawful_traversable dlist :=
equiv.is_lawful_traversable list_equiv_dlist
protected instance inhabited {α : Type u_1} : Inhabited (dlist α) :=
{ default := empty }
|
daae701e8b58c958d71eb6eb2dfcfecbbd191bd5 | 7cef822f3b952965621309e88eadf618da0c8ae9 | /src/order/zorn.lean | 01c0fb0f68152daf9b24eb966967f34f2be52eed | [
"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 | 12,392 | 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
Zorn's lemmas.
Ported from Isabelle/HOL (written by Jacques D. Fleuriot, Tobias Nipkow, and Christian Sternagel).
-/
import data.set.lattice
noncomputable theory
universes u
open set classical
open_locale classical
namespace zorn
section chain
parameters {α : Type u} (r : α → α → Prop)
local infix ` ≺ `:50 := r
/-- A chain is a subset `c` satisfying
`x ≺ y ∨ x = y ∨ y ≺ x` for all `x y ∈ c`. -/
def chain (c : set α) := pairwise_on c (λx y, x ≺ y ∨ y ≺ x)
parameters {r}
theorem chain.total_of_refl [is_refl α r]
{c} (H : chain c) {x y} (hx : x ∈ c) (hy : y ∈ c) :
x ≺ y ∨ y ≺ x :=
if e : x = y then or.inl (e ▸ refl _) else H _ hx _ hy e
theorem chain.directed [is_refl α r]
{c} (H : chain c) {x y} (hx : x ∈ c) (hy : y ∈ c) :
∃ z, z ∈ c ∧ x ≺ z ∧ y ≺ z :=
match H.total_of_refl hx hy with
| or.inl h := ⟨y, hy, h, refl _⟩
| or.inr h := ⟨x, hx, refl _, h⟩
end
theorem chain.mono {c c'} : c' ⊆ c → chain c → chain c' :=
pairwise_on.mono
theorem chain.directed_on [is_refl α r] {c} (H : chain c) : directed_on (≺) c :=
λ x xc y yc, let ⟨z, hz, h⟩ := H.directed xc yc in ⟨z, hz, h⟩
theorem chain_insert {c : set α} {a : α} (hc : chain c) (ha : ∀b∈c, b ≠ a → a ≺ b ∨ b ≺ a) :
chain (insert a c) :=
forall_insert_of_forall
(assume x hx, forall_insert_of_forall (hc x hx) (assume hneq, (ha x hx hneq).symm))
(forall_insert_of_forall (assume x hx hneq, ha x hx $ assume h', hneq h'.symm) (assume h, (h rfl).rec _))
def super_chain (c₁ c₂ : set α) := chain c₂ ∧ c₁ ⊂ c₂
def is_max_chain (c : set α) := chain c ∧ ¬ (∃c', super_chain c c')
def succ_chain (c : set α) :=
if h : ∃c', chain c ∧ super_chain c c' then some h else c
theorem succ_spec {c : set α} (h : ∃c', chain c ∧ super_chain c c') :
super_chain c (succ_chain c) :=
let ⟨c', hc'⟩ := h in
have chain c ∧ super_chain c (some h),
from @some_spec _ (λc', chain c ∧ super_chain c c') _,
by simp [succ_chain, dif_pos, h, this.right]
theorem chain_succ {c : set α} (hc : chain c) : chain (succ_chain c) :=
if h : ∃c', chain c ∧ super_chain c c' then
(succ_spec h).left
else
by simp [succ_chain, dif_neg, h]; exact hc
theorem super_of_not_max {c : set α} (hc₁ : chain c) (hc₂ : ¬ is_max_chain c) :
super_chain c (succ_chain c) :=
begin
simp [is_max_chain, not_and_distrib, not_forall_not] at hc₂,
cases hc₂.neg_resolve_left hc₁ with c' hc',
exact succ_spec ⟨c', hc₁, hc'⟩
end
theorem succ_increasing {c : set α} : c ⊆ succ_chain c :=
if h : ∃c', chain c ∧ super_chain c c' then
have super_chain c (succ_chain c), from succ_spec h,
this.right.left
else by simp [succ_chain, dif_neg, h, subset.refl]
inductive chain_closure : set α → Prop
| succ : ∀{s}, chain_closure s → chain_closure (succ_chain s)
| union : ∀{s}, (∀a∈s, chain_closure a) → chain_closure (⋃₀ s)
theorem chain_closure_empty : chain_closure ∅ :=
have chain_closure (⋃₀ ∅),
from chain_closure.union $ assume a h, h.rec _,
by simp at this; assumption
theorem chain_closure_closure : chain_closure (⋃₀ chain_closure) :=
chain_closure.union $ assume s hs, hs
variables {c c₁ c₂ c₃ : set α}
private lemma chain_closure_succ_total_aux (hc₁ : chain_closure c₁) (hc₂ : chain_closure c₂)
(h : ∀{c₃}, chain_closure c₃ → c₃ ⊆ c₂ → c₂ = c₃ ∨ succ_chain c₃ ⊆ c₂) :
c₁ ⊆ c₂ ∨ succ_chain c₂ ⊆ c₁ :=
begin
induction hc₁,
case _root_.zorn.chain_closure.succ : c₃ hc₃ ih {
cases ih with ih ih,
{ have h := h hc₃ ih,
cases h with h h,
{ exact or.inr (h ▸ subset.refl _) },
{ exact or.inl h } },
{ exact or.inr (subset.trans ih succ_increasing) } },
case _root_.zorn.chain_closure.union : s hs ih {
refine (classical.or_iff_not_imp_right.2 $ λ hn, sUnion_subset $ λ a ha, _),
apply (ih a ha).resolve_right,
apply mt (λ h, _) hn,
exact subset.trans h (subset_sUnion_of_mem ha) }
end
private lemma chain_closure_succ_total (hc₁ : chain_closure c₁) (hc₂ : chain_closure c₂) (h : c₁ ⊆ c₂) :
c₂ = c₁ ∨ succ_chain c₁ ⊆ c₂ :=
begin
induction hc₂ generalizing c₁ hc₁ h,
case _root_.zorn.chain_closure.succ : c₂ hc₂ ih {
have h₁ : c₁ ⊆ c₂ ∨ @succ_chain α r c₂ ⊆ c₁ :=
(chain_closure_succ_total_aux hc₁ hc₂ $ assume c₁, ih),
cases h₁ with h₁ h₁,
{ have h₂ := ih hc₁ h₁,
cases h₂ with h₂ h₂,
{ exact (or.inr $ h₂ ▸ subset.refl _) },
{ exact (or.inr $ subset.trans h₂ succ_increasing) } },
{ exact (or.inl $ subset.antisymm h₁ h) } },
case _root_.zorn.chain_closure.union : s hs ih {
apply or.imp_left (assume h', subset.antisymm h' h),
apply classical.by_contradiction,
simp [not_or_distrib, sUnion_subset_iff, classical.not_forall],
intros c₃ hc₃ h₁ h₂,
have h := chain_closure_succ_total_aux hc₁ (hs c₃ hc₃) (assume c₄, ih _ hc₃),
cases h with h h,
{ have h' := ih c₃ hc₃ hc₁ h,
cases h' with h' h',
{ exact (h₁ $ h' ▸ subset.refl _) },
{ exact (h₂ $ subset.trans h' $ subset_sUnion_of_mem hc₃) } },
{ exact (h₁ $ subset.trans succ_increasing h) } }
end
theorem chain_closure_total (hc₁ : chain_closure c₁) (hc₂ : chain_closure c₂) : c₁ ⊆ c₂ ∨ c₂ ⊆ c₁ :=
have c₁ ⊆ c₂ ∨ succ_chain c₂ ⊆ c₁,
from chain_closure_succ_total_aux hc₁ hc₂ $ assume c₃ hc₃, chain_closure_succ_total hc₃ hc₂,
or.imp_right (assume : succ_chain c₂ ⊆ c₁, subset.trans succ_increasing this) this
theorem chain_closure_succ_fixpoint (hc₁ : chain_closure c₁) (hc₂ : chain_closure c₂)
(h_eq : succ_chain c₂ = c₂) : c₁ ⊆ c₂ :=
begin
induction hc₁,
case _root_.zorn.chain_closure.succ : c₁ hc₁ h {
exact or.elim (chain_closure_succ_total hc₁ hc₂ h)
(assume h, h ▸ h_eq.symm ▸ subset.refl c₂) id },
case _root_.zorn.chain_closure.union : s hs ih {
exact (sUnion_subset $ assume c₁ hc₁, ih c₁ hc₁) }
end
theorem chain_closure_succ_fixpoint_iff (hc : chain_closure c) :
succ_chain c = c ↔ c = ⋃₀ chain_closure :=
⟨assume h, subset.antisymm
(subset_sUnion_of_mem hc)
(chain_closure_succ_fixpoint chain_closure_closure hc h),
assume : c = ⋃₀{c : set α | chain_closure c},
subset.antisymm
(calc succ_chain c ⊆ ⋃₀{c : set α | chain_closure c} :
subset_sUnion_of_mem $ chain_closure.succ hc
... = c : this.symm)
succ_increasing⟩
theorem chain_chain_closure (hc : chain_closure c) : chain c :=
begin
induction hc,
case _root_.zorn.chain_closure.succ : c hc h {
exact chain_succ h },
case _root_.zorn.chain_closure.union : s hs h {
have h : ∀c∈s, zorn.chain c := h,
exact assume c₁ ⟨t₁, ht₁, (hc₁ : c₁ ∈ t₁)⟩ c₂ ⟨t₂, ht₂, (hc₂ : c₂ ∈ t₂)⟩ hneq,
have t₁ ⊆ t₂ ∨ t₂ ⊆ t₁, from chain_closure_total (hs _ ht₁) (hs _ ht₂),
or.elim this
(assume : t₁ ⊆ t₂, h t₂ ht₂ c₁ (this hc₁) c₂ hc₂ hneq)
(assume : t₂ ⊆ t₁, h t₁ ht₁ c₁ hc₁ c₂ (this hc₂) hneq) }
end
def max_chain := ⋃₀ chain_closure
/-- Hausdorff's maximality principle
There exists a maximal totally ordered subset of `α`.
Note that we do not require `α` to be partially ordered by `r`. -/
theorem max_chain_spec : is_max_chain max_chain :=
classical.by_contradiction $
assume : ¬ is_max_chain (⋃₀ chain_closure),
have super_chain (⋃₀ chain_closure) (succ_chain (⋃₀ chain_closure)),
from super_of_not_max (chain_chain_closure chain_closure_closure) this,
let ⟨h₁, h₂, (h₃ : (⋃₀ chain_closure) ≠ succ_chain (⋃₀ chain_closure))⟩ := this in
have succ_chain (⋃₀ chain_closure) = (⋃₀ chain_closure),
from (chain_closure_succ_fixpoint_iff chain_closure_closure).mpr rfl,
h₃ this.symm
/-- Zorn's lemma
If every chain has an upper bound, then there is a maximal element -/
theorem exists_maximal_of_chains_bounded
(h : ∀c, chain c → ∃ub, ∀a∈c, a ≺ ub) (trans : ∀{a b c}, a ≺ b → b ≺ c → a ≺ c) :
∃m, ∀a, m ≺ a → a ≺ m :=
have ∃ub, ∀a∈max_chain, a ≺ ub,
from h _ $ max_chain_spec.left,
let ⟨ub, (hub : ∀a∈max_chain, a ≺ ub)⟩ := this in
⟨ub, assume a ha,
have chain (insert a max_chain),
from chain_insert max_chain_spec.left $ assume b hb _, or.inr $ trans (hub b hb) ha,
have a ∈ max_chain, from
classical.by_contradiction $ assume h : a ∉ max_chain,
max_chain_spec.right $ ⟨insert a max_chain, this, ssubset_insert h⟩,
hub a this⟩
end chain
theorem zorn_partial_order {α : Type u} [partial_order α]
(h : ∀c:set α, @chain α (≤) c → ∃ub, ∀a∈c, a ≤ ub) : ∃m:α, ∀a, m ≤ a → a = m :=
let ⟨m, hm⟩ := @exists_maximal_of_chains_bounded α (≤) h (assume a b c, le_trans) in
⟨m, assume a ha, le_antisymm (hm a ha) ha⟩
theorem zorn_partial_order₀ {α : Type u} [partial_order α] (s : set α)
(ih : ∀ c ⊆ s, chain (≤) c → ∀ y ∈ c, ∃ ub ∈ s, ∀ z ∈ c, z ≤ ub)
(x : α) (hxs : x ∈ s) : ∃ m ∈ s, x ≤ m ∧ ∀ z ∈ s, m ≤ z → z = m :=
let ⟨⟨m, hms, hxm⟩, h⟩ := @zorn_partial_order {m // m ∈ s ∧ x ≤ m} _ (λ c hc, classical.by_cases
(assume hce : c = ∅, hce.symm ▸ ⟨⟨x, hxs, le_refl _⟩, λ _, false.elim⟩)
(assume hce : c ≠ ∅, let ⟨m, hmc⟩ := set.exists_mem_of_ne_empty hce in
let ⟨ub, hubs, hub⟩ := ih (subtype.val '' c) (image_subset_iff.2 $ λ z hzc, z.2.1)
(by rintro _ ⟨p, hpc, rfl⟩ _ ⟨q, hqc, rfl⟩ hpq;
exact hc p hpc q hqc (mt (by rintro rfl; refl) hpq)) m.1 (mem_image_of_mem _ hmc) in
⟨⟨ub, hubs, le_trans m.2.2 $ hub m.1 $ mem_image_of_mem _ hmc⟩, λ a hac, hub a.1 ⟨a, hac, rfl⟩⟩)) in
⟨m, hms, hxm, λ z hzs hmz, congr_arg subtype.val $ h ⟨z, hzs, le_trans hxm hmz⟩ hmz⟩
theorem zorn_subset {α : Type u} (S : set (set α))
(h : ∀c ⊆ S, chain (⊆) c → ∃ub ∈ S, ∀ s ∈ c, s ⊆ ub) :
∃ m ∈ S, ∀a ∈ S, m ⊆ a → a = m :=
begin
letI : partial_order S := partial_order.lift subtype.val (λ _ _, subtype.eq') (by apply_instance),
have : ∀c:set S, @chain S (≤) c → ∃ub, ∀a∈c, a ≤ ub,
{ intros c hc,
rcases h (subtype.val '' c) (image_subset_iff.2 _) _ with ⟨s, sS, hs⟩,
{ exact ⟨⟨s, sS⟩, λ ⟨x, hx⟩ H, hs _ (mem_image_of_mem _ H)⟩ },
{ rintro ⟨x, hx⟩ _, exact hx },
{ rintro _ ⟨x, cx, rfl⟩ _ ⟨y, cy, rfl⟩ xy,
exact hc x cx y cy (mt (congr_arg _) xy) } },
rcases zorn_partial_order this with ⟨⟨m, mS⟩, hm⟩,
exact ⟨m, mS, λ a aS ha, congr_arg subtype.val (hm ⟨a, aS⟩ ha)⟩
end
theorem zorn_subset₀ {α : Type u} (S : set (set α))
(H : ∀c ⊆ S, chain (⊆) c → c ≠ ∅ → ∃ub ∈ S, ∀ s ∈ c, s ⊆ ub) (x) (hx : x ∈ S) :
∃ m ∈ S, x ⊆ m ∧ ∀a ∈ S, m ⊆ a → a = m :=
begin
let T := {s ∈ S | x ⊆ s},
rcases zorn_subset T _ with ⟨m, ⟨mS, mx⟩, hm⟩,
{ exact ⟨m, mS, mx, λ a ha ha', hm a ⟨ha, subset.trans mx ha'⟩ ha'⟩ },
{ intros c cT hc,
by_cases c0 : c = ∅,
{ rw c0, exact ⟨x, ⟨hx, subset.refl _⟩, λ _, false.elim⟩ },
{ rcases H _ (subset.trans cT (sep_subset _ _)) hc c0 with ⟨ub, us, h⟩,
refine ⟨ub, ⟨us, _⟩, h⟩,
rcases ne_empty_iff_exists_mem.1 c0 with ⟨s, hs⟩,
exact subset.trans (cT hs).2 (h _ hs) } }
end
theorem chain.total {α : Type u} [preorder α]
{c} (H : @chain α (≤) c) :
∀ {x y}, x ∈ c → y ∈ c → x ≤ y ∨ y ≤ x :=
@chain.total_of_refl _ (≤) ⟨le_refl⟩ _ H
theorem chain.image {α β : Type*} (r : α → α → Prop)
(s : β → β → Prop) (f : α → β)
(h : ∀ x y, r x y → s (f x) (f y))
{c : set α} (hrc : chain r c) : chain s (f '' c) :=
λ x ⟨a, ha₁, ha₂⟩ y ⟨b, hb₁, hb₂⟩, ha₂ ▸ hb₂ ▸ λ hxy,
(hrc a ha₁ b hb₁ (mt (congr_arg f) $ hxy)).elim
(or.inl ∘ h _ _) (or.inr ∘ h _ _)
end zorn
|
49c19b2e66006d8645912e348b9d69d9e1b8ab29 | ad0c7d243dc1bd563419e2767ed42fb323d7beea | /tactic/auto_cases.lean | b9dc07bf81f67935aa5f6f2dbb9ff0b7ce41df94 | [
"Apache-2.0"
] | permissive | sebzim4500/mathlib | e0b5a63b1655f910dee30badf09bd7e191d3cf30 | 6997cafbd3a7325af5cb318561768c316ceb7757 | refs/heads/master | 1,585,549,958,618 | 1,538,221,723,000 | 1,538,221,723,000 | 150,869,076 | 0 | 0 | Apache-2.0 | 1,538,229,323,000 | 1,538,229,323,000 | null | UTF-8 | Lean | false | false | 1,591 | 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 logic.basic
import tactic.basic
import data.option
open tactic
meta def auto_cases_at (h : expr) : tactic string :=
do t' ← infer_type h,
t' ← whnf t',
let use_cases := match t' with
| `(empty) := tt
| `(pempty) := tt
| `(unit) := tt
| `(punit) := tt
| `(ulift _) := tt
| `(plift _) := tt
| `(prod _ _) := tt
| `(and _ _) := tt
| `(sigma _) := tt
| `(subtype _) := tt
| `(Exists _) := tt
| `(fin 0) := tt
| `(sum _ _) := tt -- This is perhaps dangerous!
| `(or _ _) := tt -- This is perhaps dangerous!
| _ := ff
end,
if use_cases then
do cases h, pp ← pp h, return ("cases " ++ pp.to_string)
else
match t' with
-- `cases` can be dangerous on `eq` and `quot`, producing mysterious errors during type checking.
-- instead we attempt `induction`
| `(eq _ _) := (do induction h, pp ← pp h, return ("induction " ++ pp.to_string))
| `(quot _) := do induction h, pp ← pp h, return ("induction " ++ pp.to_string)
| _ := failed
end
/-- Applies `cases` or `induction` on certain hypotheses. -/
meta def auto_cases : tactic string :=
do l ← local_context,
results ← successes (l.reverse.map(λ h, auto_cases_at h)),
when (results.empty) (fail "`auto_cases` did not find any hypotheses to apply `cases` or `induction` to"),
return (string.intercalate ", " results)
|
ed94ecc20821c9afc9510f0503b9b645e8de31ae | f1a12d4db0f46eee317d703e3336d33950a2fe7e | /dlo/dlo.lean | f5b22eeb6da348ef88619b0954e4a522b45ddbe4 | [
"Apache-2.0"
] | permissive | avigad/qelim | bce89b79c717b7649860d41a41a37e37c982624f | b7d22864f1f0a2d21adad0f4fb3fc7ba665f8e60 | refs/heads/master | 1,584,548,938,232 | 1,526,773,708,000 | 1,526,773,708,000 | 134,967,693 | 2 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 13,018 | lean | import ..common.ldeq
variables {α β : Type}
class dlo (α : Type) extends decidable_linear_order α :=
(inh : α)
(btw : ∀ {x z : α}, x < z → ∃ (y : α), x < y ∧ y < z)
(blw : ∀ (y : α), ∃ (x : α), x < y)
(abv : ∀ (x : α), ∃ (y : α), x < y)
open dlo
inductive adlo : Type
| lt : nat → nat → adlo
| eq : nat → nat → adlo
notation x `<'` y := adlo.lt x y
notation x `='` y := adlo.eq x y
meta def adlo_to_format : adlo → format
| (x <' y) := "(" ++ to_fmt x ++ "<" ++ to_fmt y ++ ")"
| (x =' y) := "(" ++ to_fmt x ++ "=" ++ to_fmt y ++ ")"
meta instance : has_to_format adlo := ⟨adlo_to_format⟩
def tval [H : dlo β] (n) (bs : list β) := list.nth_dft (@dlo.inh _ H) bs n
def dlo_val [H : dlo β] (bs : list β) : adlo → Prop
| (adlo.lt m n) := tval m bs < tval n bs
| (adlo.eq m n) := tval m bs = tval n bs
def dlo_neg : adlo → fm adlo
| (adlo.lt m n) := (A' (adlo.eq m n)) ∨' (A' (adlo.lt n m))
| (adlo.eq m n) := (A' (adlo.lt m n)) ∨' (A' (adlo.lt n m))
lemma dlo_neg_nqfree : ∀ (d : adlo), nqfree (dlo_neg d)
| (adlo.lt m n) := and.intro trivial trivial
| (adlo.eq m n) := and.intro trivial trivial
lemma dlo_neg_prsv [dlo β] : ∀ (d : adlo) (l : list β),
interp dlo_val l (dlo_neg d) ↔ interp dlo_val l (¬' A' d)
| (adlo.lt m n) l :=
begin
unfold dlo_neg, unfold interp,
unfold dlo_val,
apply iff.intro,
intro H, apply not_lt_of_ge,
apply le_of_lt_or_eq,
cases H with H H, apply or.inr,
apply eq.symm H, apply or.inl, apply H,
intro H, apply eq_or_lt_of_not_lt,
apply H
end
| (adlo.eq m n) l :=
begin
unfold dlo_neg, unfold interp, unfold dlo_val,
apply iff.intro, intro H, cases H with H H,
apply ne_of_lt H, apply ne_of_gt H,
intro H, apply lt_or_gt_of_ne H
end
def dlo_dep0 : adlo → Prop
| (adlo.lt m n) := m = 0 ∨ n = 0
| (adlo.eq m n) := m = 0 ∨ n = 0
def adlo_dec_dep0 : decidable_pred dlo_dep0
| (adlo.lt 0 n) := decidable.is_true (or.inl (eq.refl _))
| (adlo.lt m 0) := decidable.is_true (or.inr (eq.refl _))
| (adlo.lt (m+1) (n+1)) :=
decidable.is_false
(begin
intro H, cases H with H H,
cases H, cases H
end)
| (adlo.eq 0 n) := decidable.is_true (or.inl (eq.refl _))
| (adlo.eq m 0) := decidable.is_true (or.inr (eq.refl _))
| (adlo.eq (m+1) (n+1)) :=
decidable.is_false
(begin
intro H, cases H with H H,
cases H, cases H
end)
def dlo_decr : adlo → adlo
| (adlo.lt m n) := (adlo.lt (m-1) (n-1))
| (adlo.eq m n) := (adlo.eq (m-1) (n-1))
def pos_of_not_dep0_lt (m n) (H : ¬ dlo_dep0 (m <' n)) : (m > 0 ∧ n > 0) :=
begin
cases m, apply absurd _ H,
apply or.inl, refl,
cases n, apply absurd _ H,
apply or.inr, refl,
apply and.intro,
apply nat.zero_lt_succ,
apply nat.zero_lt_succ,
end
def pos_of_not_dep0_eq (m n) (H : ¬ dlo_dep0 (m =' n)) : (m > 0 ∧ n > 0) :=
begin
cases m, apply absurd _ H,
apply or.inl, refl,
cases n, apply absurd _ H,
apply or.inr, refl,
apply and.intro,
apply nat.zero_lt_succ,
apply nat.zero_lt_succ,
end
def dlo_decr_prsv [dlo β] :
∀ (a : adlo), ¬dlo_dep0 a → ∀ (b : β) (bs : list β), dlo_val bs (dlo_decr a) ↔ dlo_val (b :: bs) a :=
begin
intros a Ha b bs,
cases a with m n m n,
unfold dlo_decr,
repeat {unfold dlo_val}, unfold tval,
repeat {rewrite nth_dft_pred},
apply (pos_of_not_dep0_lt m n Ha)^.elim_right,
apply (pos_of_not_dep0_lt m n Ha)^.elim_left,
unfold dlo_decr,
repeat {unfold dlo_val}, unfold tval,
repeat {rewrite nth_dft_pred},
repeat {rewrite nth_dft_pred},
apply (pos_of_not_dep0_eq m n Ha)^.elim_right,
apply (pos_of_not_dep0_eq m n Ha)^.elim_left,
end
instance dlo_atom [dlo β] : atom_type adlo β :=
{ val := dlo_val,
neg := dlo_neg,
neg_nqfree := dlo_neg_nqfree,
neg_prsv := dlo_neg_prsv,
dep0 := dlo_dep0,
dec_dep0 := adlo_dec_dep0,
decr := dlo_decr,
decr_prsv := dlo_decr_prsv,
inh := dlo.inh β,
dec_eq := by tactic.mk_dec_eq_instance,
normal := λ _, false,
dec_normal := _,
neg_prsv_normal := λ _ h, by cases h,
decr_prsv_normal := λ _ h, by cases h, }
def dlt [dlo β] (m n) (bs : list β) := tval m bs < tval n bs
def deq [dlo β] (m n) (bs : list β) := tval m bs = tval n bs
def dle [dlo β] (m n) (bs : list β) := tval m bs ≤ tval n bs
lemma exp_val_lt [H : dlo β] {m n} {bs} :
@atom_type.val adlo β dlo_atom (adlo.lt m n) bs
↔ ((list.nth_dft (@dlo.inh _ H) bs m) < (list.nth_dft (@dlo.inh _ H) bs n)) :=
begin apply iff.refl end
def exp_decr_lt [dlo β] (m n) : @atom_type.decr adlo β dlo_atom (m <' n) = (m-1 <' n-1) := rfl
def dlo_solv0 : adlo → Prop
| (adlo.lt m n) := false
| (adlo.eq m n) := m = 0 ∨ n = 0
def dlo_dec_solv0 : decidable_pred dlo_solv0
| (adlo.lt m n) := is_false (λ H, by cases H)
| (adlo.eq m n) :=
begin
cases m with m m, apply is_true, apply or.inl, refl,
cases n with n n, apply is_true, apply or.inr, refl,
apply is_false, intro H, cases H with H H,
cases H, cases H
end
def dlo_dest_solv0 : ∀ (a : adlo) (H : dlo_solv0 a), nat
| (adlo.lt m n) H := by cases H
| (adlo.eq 0 n) _ := n
| (adlo.eq (m+1) 0) _ := m+1
| (adlo.eq (m+1) (n+1)) H :=
begin exfalso, cases H with H H; cases H end
lemma exp_dlo_dest_solv0_0n (n : nat) (H : dlo_solv0 (0 ='n)) :
dlo_dest_solv0 (0 =' n) H = n := by refl
lemma exp_dlo_dest_solv0_m0 (m : nat) (H : dlo_solv0 ((m+1) =' 0)) :
dlo_dest_solv0 ((m+1) =' 0) H = m+1 := by refl
lemma dlo_solv0_eq [dlo β] : ∀ {e : adlo} (He : dlo_solv0 e) {b} {bs}, dlo_val e (b::bs)
→ list.nth_dft (dlo.inh β) (b::bs) (dlo_dest_solv0 e He) = b
| (adlo.lt m n) He _ _ _ := by cases He
| (adlo.eq 0 n) He b bs HI :=
begin
cases n; unfold dlo_dest_solv0, refl,
unfold dlo_val at HI, apply eq.symm HI
end
| (adlo.eq m 0) He b bs HI :=
begin
cases m with m; unfold dlo_dest_solv0, refl,
unfold dlo_val at HI, apply HI
end
| (adlo.eq (m+1) (n+1)) He _ _ _ :=
begin cases He with He He; cases He end
def dlo_triv : adlo → Prop
| (adlo.lt m n) := false
| (adlo.eq m n) := m = n
def dlo_dec_triv : decidable_pred dlo_triv
| (adlo.lt m n) := begin apply is_false, apply id end
| (adlo.eq m n) :=
begin
cases (nat.decidable_eq m n) with HD HD,
apply is_false, intro HC, apply HD HC,
apply is_true, apply HD
end
lemma dlo_true_triv [dlo β] : ∀ a, dlo_triv a → ∀ (bs : list β), dlo_val a bs
| (adlo.lt m n) HT := by cases HT
| (adlo.eq m n) HT :=
begin
intro bs, unfold dlo_triv at HT,
rewrite HT, unfold dlo_val
end
def dlo_subst0 : adlo → adlo → adlo
| (i =' j) (m <' n) := subst_eqn i j m <' subst_eqn i j n
| (i =' j) (m =' n) := subst_eqn i j m =' subst_eqn i j n
| _ a := a
lemma dlo_true_subst [dlo β] : ∀ e, dlo_solv0 e
→ ∀ (bs : list β), dlo_val (dlo_subst0 e e) bs
| (adlo.lt m n) HT := by cases HT
| (adlo.eq m n) HT :=
begin
intro bs, cases HT with HT HT,
subst HT, unfold dlo_subst0,
cases n with n,
repeat {unfold subst_eqn},
unfold dlo_val,
repeat {unfold subst_eqn},
unfold dlo_val, refl,
rewrite HT, unfold dlo_subst0,
cases m with m, unfold dlo_val,
repeat {unfold subst_eqn},
unfold dlo_val, refl
end
lemma dlo_subst_prsv_aux_0n [dlo β] (n x) (bs) (H) : list.nth_dft (inh β) bs (subst_eqn 0 n x)
= list.nth_dft (inh β) (list.nth_dft (inh β) bs (dlo_dest_solv0 (0 =' n) H - 1) :: bs) x :=
begin
cases x with x, unfold subst_eqn,
rewrite exp_dlo_dest_solv0_0n,
rewrite nth_dft_head, refl
end
lemma dlo_subst_prsv_aux_m0 [dlo β] (m x) (bs) (H) : list.nth_dft (inh β) bs (subst_eqn m 0 x)
= list.nth_dft (inh β) (list.nth_dft (inh β) bs (dlo_dest_solv0 (m =' 0) H - 1) :: bs) x :=
begin
cases m with m, apply dlo_subst_prsv_aux_0n,
cases x with x, unfold subst_eqn,
rewrite exp_dlo_dest_solv0_m0,
rewrite nth_dft_head, refl, refl
end
lemma dlo_subst_prsv [dlo β] : ∀ {e : adlo} (He : dlo_solv0 e) {a : adlo} {bs : list β},
dlo_val (dlo_subst0 e a) bs ↔ dlo_val a ((list.nth_dft (dlo.inh β) bs (dlo_dest_solv0 e He - 1))::bs)
| (adlo.lt m n) H _ := by cases H
| (adlo.eq 0 n) _ (x <' y) :=
begin
intro bs, unfold dlo_subst0,
repeat {unfold dlo_val}, unfold tval,
repeat {rewrite dlo_subst_prsv_aux_0n}
end
| (adlo.eq 0 n) _ (x =' y) :=
begin
intro bs, unfold dlo_subst0,
repeat {unfold dlo_val}, unfold tval,
repeat {rewrite dlo_subst_prsv_aux_0n}
end
| (adlo.eq m 0) _ (x <' y) :=
begin
intro bs, unfold dlo_subst0,
repeat {unfold dlo_val}, unfold tval,
repeat {rewrite dlo_subst_prsv_aux_m0}
end
| (adlo.eq m 0) _ (x =' y) :=
begin
intro bs, unfold dlo_subst0,
repeat {unfold dlo_val}, unfold tval,
repeat {rewrite dlo_subst_prsv_aux_m0}
end
| (adlo.eq (m+1) (n+1)) H _ := by cases H with H H ; cases H
lemma dlo_dest_pos : ∀ {a} {Ha : dlo_solv0 a}, ¬ dlo_triv a → dlo_dest_solv0 a Ha > 0 :=
begin
intros a Ha HT, cases a with m n m n,
cases Ha, cases m ; cases n,
exfalso, apply HT, unfold dlo_triv,
unfold dlo_dest_solv0, apply nat.zero_lt_succ,
unfold dlo_dest_solv0, apply nat.zero_lt_succ,
unfold dlo_solv0 at Ha, cases Ha with Ha Ha ;
cases Ha
end
instance : decidable_eq adlo := by tactic.mk_dec_eq_instance
instance dlo_atomeq [H : dlo β] : atom_eq_type adlo β :=
{ dlo_atom with solv0 := dlo_solv0,
dec_solv0 := dlo_dec_solv0,
dest_solv0 := dlo_dest_solv0,
solv0_eq := @dlo_solv0_eq β _,
trivial := dlo_triv,
dec_triv := dlo_dec_triv,
true_triv := dlo_true_triv,
subst0 := dlo_subst0,
true_subst := dlo_true_subst,
subst_prsv := @dlo_subst_prsv β _,
dest_pos := @dlo_dest_pos }
def is_b_atm (a : adlo) :=
∃ n, (a = (n+1 <' 0)) ∨ (a = (0 <' n+1))
def is_lb_atm (a : adlo) := ∃ n, (a = (n+1 <' 0))
instance : decidable_pred is_b_atm
| (m+1 <' 0) := decidable.is_true
begin existsi m, apply or.inl rfl end
| (0 <' n+1) := decidable.is_true
begin existsi n, apply or.inr rfl end
| (m =' n) :=
begin
apply decidable.is_false, intro h,
cases h with h h ; cases h with h h ; cases h
end
| (0 <' 0) :=
begin
apply decidable.is_false, intro h,
cases h with h h ; cases h with h h ; cases h
end
| (m+1 <' n+1) :=
begin
apply decidable.is_false, intro h,
cases h with h h ; cases h with h h ; cases h
end
lemma dlo_dec_mem : ∀ (a : adlo) (as : list adlo), decidable (a ∈ as) :=
list.decidable_mem
def get_lb : adlo → option nat
| (m+1 <' 0) := some m
| _ := none
def get_ub : adlo → option nat
| (0 <' n+1) := some n
| _ := none
def is_lb (m) (as : list adlo) := (m+1 <' 0) ∈ as
def is_ub (n) (as : list adlo) := (0 <' n+1) ∈ as
def dlo_qe_lbs (as : list adlo) : list nat :=
list.omap get_lb as
lemma exp_plus_one {n : nat} : n + 1 = nat.succ n := rfl
lemma is_lb_of_mem_lbs {m} {as} :
m ∈ dlo_qe_lbs as → is_lb m as :=
begin
unfold dlo_qe_lbs, intro h,
rewrite exp_mem_omap at h,
cases h with a h, cases h with h1 h2,
cases a with x y, cases x with x ; cases y with y,
cases h2, cases h2, cases h2, apply h1, cases h2,
cases h2
end
lemma mem_lbs_of_is_lb {m} {as} :
is_lb m as → m ∈ dlo_qe_lbs as :=
begin
intro h, unfold dlo_qe_lbs, rewrite exp_mem_omap,
existsi (m+1 <' 0), apply and.intro, apply h, refl
end
lemma lbs_eq_nil_of_none_is_lb {as} :
¬ (∃ m, is_lb m as) → dlo_qe_lbs as = [] :=
begin
intro h, cases (dest_list $ dlo_qe_lbs as) with he he,
apply he, exfalso, apply h, cases he with m he,
cases he with ms hm, existsi m,
apply is_lb_of_mem_lbs, rewrite hm,
apply or.inl rfl
end
def dlo_qe_ubs (as : list adlo) : list nat :=
list.omap get_ub as
lemma is_ub_of_mem_ubs {n} {as} : n ∈ dlo_qe_ubs as → is_ub n as :=
begin
unfold dlo_qe_ubs, intro h,
rewrite exp_mem_omap at h,
cases h with a h, cases h with h1 h2,
cases a with x y, cases x with x ; cases y with y,
cases h2, cases h2, apply h1, repeat {cases h2}
end
lemma mem_ubs_of_is_ub {n} {as} :
is_ub n as → n ∈ dlo_qe_ubs as :=
begin
intro h, unfold dlo_qe_ubs, rewrite exp_mem_omap,
existsi (0 <' n+1), apply and.intro, apply h, refl
end
lemma ubs_eq_nil_of_none_is_ub {as} :
¬ (∃ n, is_ub n as) → dlo_qe_ubs as = [] :=
begin
intro h, cases (dest_list $ dlo_qe_ubs as) with he he,
apply he, exfalso, apply h, cases he with m he,
cases he with ms hm, existsi m,
apply is_ub_of_mem_ubs, rewrite hm,
apply or.inl rfl
end
-- def dlo_qelim [atom adlo β] : fm adlo → fm adlo :=
-- @lift_nnf_qe _ β _ dlo_qe
--
-- lemma dlo_qe_qfree : ∀ (p : fm adlo), nqfree p → qfree (dlo_qe p) := sorry
--
-- lemma dlo_qe_prsv [atom adlo β] : ∀ (p : fm adlo) (xs : list β), I (dlo_qe p) xs = ∃ x, I p (x::xs) := sorry
--
-- theorem dlo_qelim_prsv [atom adlo β] :
-- ∀ (p : fm adlo) (xs : list β), I (@dlo_qelim β _ p) xs = I p xs :=
-- lnq_prsv dlo_qe dlo_qe_qfree dlo_qe_prsv |
c342b1f15e2929cf180ec547e8cc15ef4517eaaf | 8eeb99d0fdf8125f5d39a0ce8631653f588ee817 | /src/linear_algebra/char_poly/coeff.lean | 354e825166be1f3979f6d110c9b4740810f12dfe | [
"Apache-2.0"
] | permissive | jesse-michael-han/mathlib | a15c58378846011b003669354cbab7062b893cfe | fa6312e4dc971985e6b7708d99a5bc3062485c89 | refs/heads/master | 1,625,200,760,912 | 1,602,081,753,000 | 1,602,081,753,000 | 181,787,230 | 0 | 0 | null | 1,555,460,682,000 | 1,555,460,682,000 | null | UTF-8 | Lean | false | false | 9,307 | lean | /-
Copyright (c) 2020 Aaron Anderson, Jalex Stark. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Aaron Anderson, Jalex Stark.
-/
import data.matrix.char_p
import linear_algebra.char_poly
import linear_algebra.matrix
import ring_theory.polynomial.basic
import algebra.polynomial.big_operators
import group_theory.perm.cycles
import field_theory.finite.basic
/-!
# Characteristic polynomials
We give methods for computing coefficients of the characteristic polynomial.
## Main definitions
- `char_poly_degree_eq_dim` proves that the degree of the characteristic polynomial
over a nonzero ring is the dimension of the matrix
- `det_eq_sign_char_poly_coeff` proves that the determinant is the constant term of the characteristic
polynomial, up to sign.
- `trace_eq_neg_char_poly_coeff` proves that the trace is the negative of the (d-1)th coefficient of the
characteristic polynomial, where d is the dimension of the matrix.
For a nonzero ring, this is the second-highest coefficient.
-/
noncomputable theory
universes u v w z
open polynomial matrix
open_locale big_operators
variables {R : Type u} [comm_ring R]
variables {n G : Type v} [decidable_eq n] [fintype n]
variables {α β : Type v} [decidable_eq α]
open finset
open polynomial
variable {M : matrix n n R}
lemma char_matrix_apply_nat_degree [nontrivial R] (i j : n) :
(char_matrix M i j).nat_degree = ite (i = j) 1 0 :=
by { by_cases i = j; simp [h, ← degree_eq_iff_nat_degree_eq_of_pos (nat.succ_pos 0)], }
lemma char_matrix_apply_nat_degree_le (i j : n) :
(char_matrix M i j).nat_degree ≤ ite (i = j) 1 0 :=
by split_ifs; simp [h, nat_degree_X_sub_C_le]
variable (M)
lemma char_poly_sub_diagonal_degree_lt :
(char_poly M - ∏ (i : n), (X - C (M i i))).degree < ↑(fintype.card n - 1) :=
begin
rw [char_poly, det, ← insert_erase (mem_univ (equiv.refl n)),
sum_insert (not_mem_erase (equiv.refl n) univ), add_comm],
simp only [char_matrix_apply_eq, one_mul, equiv.perm.sign_refl, id.def, int.cast_one,
units.coe_one, add_sub_cancel, equiv.coe_refl],
rw ← mem_degree_lt, apply submodule.sum_mem (degree_lt R (fintype.card n - 1)),
intros c hc, rw [← C_eq_int_cast, C_mul'],
apply submodule.smul_mem (degree_lt R (fintype.card n - 1)) ↑↑(equiv.perm.sign c),
rw mem_degree_lt, apply lt_of_le_of_lt degree_le_nat_degree _, rw with_bot.coe_lt_coe,
apply lt_of_le_of_lt _ (equiv.perm.fixed_point_card_lt_of_ne_one (ne_of_mem_erase hc)),
apply le_trans (polynomial.nat_degree_prod_le univ (λ i : n, (char_matrix M (c i) i))) _,
rw card_eq_sum_ones, rw sum_filter, apply sum_le_sum,
intros, apply char_matrix_apply_nat_degree_le,
end
lemma char_poly_coeff_eq_prod_coeff_of_le {k : ℕ} (h : fintype.card n - 1 ≤ k) :
(char_poly M).coeff k = (∏ i : n, (X - C (M i i))).coeff k :=
begin
apply eq_of_sub_eq_zero, rw ← coeff_sub, apply polynomial.coeff_eq_zero_of_degree_lt,
apply lt_of_lt_of_le (char_poly_sub_diagonal_degree_lt M) _, rw with_bot.coe_le_coe, apply h,
end
lemma det_of_card_zero (h : fintype.card n = 0) (M : matrix n n R) : M.det = 1 :=
by { rw fintype.card_eq_zero_iff at h, suffices : M = 1, { simp [this] }, ext, tauto }
theorem char_poly_degree_eq_dim [nontrivial R] (M : matrix n n R) :
(char_poly M).degree = fintype.card n :=
begin
by_cases fintype.card n = 0, rw h, unfold char_poly, rw det_of_card_zero, simpa,
rw ← sub_add_cancel (char_poly M) (∏ (i : n), (X - C (M i i))),
have h1 : (∏ (i : n), (X - C (M i i))).degree = fintype.card n,
{ rw degree_eq_iff_nat_degree_eq_of_pos, swap, apply nat.pos_of_ne_zero h,
rw nat_degree_prod', simp_rw nat_degree_X_sub_C, unfold fintype.card, simp,
simp_rw (monic_X_sub_C _).leading_coeff, simp, },
rw degree_add_eq_of_degree_lt, exact h1, rw h1,
apply lt_trans (char_poly_sub_diagonal_degree_lt M), rw with_bot.coe_lt_coe,
rw ← nat.pred_eq_sub_one, apply nat.pred_lt, apply h,
end
theorem char_poly_nat_degree_eq_dim [nontrivial R] (M : matrix n n R) :
(char_poly M).nat_degree = fintype.card n :=
nat_degree_eq_of_degree_eq_some (char_poly_degree_eq_dim M)
lemma char_poly_monic_of_nontrivial [nontrivial R] (M : matrix n n R) :
monic (char_poly M) :=
begin
by_cases fintype.card n = 0, rw [char_poly, det_of_card_zero h], apply monic_one,
have mon : (∏ (i : n), (X - C (M i i))).monic,
{ apply monic_prod_of_monic univ (λ i : n, (X - C (M i i))), simp [monic_X_sub_C], },
rw ← sub_add_cancel (∏ (i : n), (X - C (M i i))) (char_poly M) at mon,
rw monic at *, rw leading_coeff_add_of_degree_lt at mon, rw ← mon,
rw char_poly_degree_eq_dim, rw ← neg_sub, rw degree_neg,
apply lt_trans (char_poly_sub_diagonal_degree_lt M), rw with_bot.coe_lt_coe,
rw ← nat.pred_eq_sub_one, apply nat.pred_lt, apply h,
end
lemma char_poly_monic (M : matrix n n R) :
monic (char_poly M) :=
begin
classical, by_cases h : nontrivial R,
{ letI := h, apply char_poly_monic_of_nontrivial, },
{ rw nontrivial_iff at h, push_neg at h, apply h, }
end
theorem trace_eq_neg_char_poly_coeff [nonempty n] (M : matrix n n R) :
(matrix.trace n R R) M = -(char_poly M).coeff (fintype.card n - 1) :=
begin
by_cases nontrivial R; try { rw not_nontrivial_iff_subsingleton at h }; haveI := h, swap,
{ apply subsingleton.elim },
rw char_poly_coeff_eq_prod_coeff_of_le, swap, refl,
rw [fintype.card, prod_X_sub_C_coeff_card_pred univ (λ i : n, M i i)], simp,
rw [← fintype.card, fintype.card_pos_iff], apply_instance,
end
-- I feel like this should use polynomial.alg_hom_eval₂_algebra_map
lemma mat_poly_equiv_eval (M : matrix n n (polynomial R)) (r : R) (i j : n) :
(mat_poly_equiv M).eval ((scalar n) r) i j = (M i j).eval r :=
begin
unfold polynomial.eval, unfold eval₂,
transitivity finsupp.sum (mat_poly_equiv M) (λ (e : ℕ) (a : matrix n n R),
(a * (scalar n) r ^ e) i j),
{ unfold finsupp.sum, rw sum_apply, rw sum_apply, dsimp, refl, },
{ simp_rw ← (scalar n).map_pow, simp_rw ← (matrix.scalar.commute _ _).eq,
simp only [coe_scalar, matrix.one_mul, ring_hom.id_apply,
smul_apply, mul_eq_mul, algebra.smul_mul_assoc],
have h : ∀ x : ℕ, (λ (e : ℕ) (a : R), r ^ e * a) x 0 = 0 := by simp,
symmetry, rw ← finsupp.sum_map_range_index h, swap, refl,
refine congr (congr rfl _) (by {ext, rw mul_comm}), ext, rw finsupp.map_range_apply,
simp [apply_eq_coeff], }
end
lemma eval_det (M : matrix n n (polynomial R)) (r : R) :
polynomial.eval r M.det = (polynomial.eval (matrix.scalar n r) (mat_poly_equiv M)).det :=
begin
rw [polynomial.eval, ← coe_eval₂_ring_hom, ring_hom.map_det],
apply congr_arg det, ext, symmetry, convert mat_poly_equiv_eval _ _ _ _,
end
theorem det_eq_sign_char_poly_coeff (M : matrix n n R) :
M.det = (-1)^(fintype.card n) * (char_poly M).coeff 0:=
begin
rw [coeff_zero_eq_eval_zero, char_poly, eval_det, mat_poly_equiv_char_matrix, ← det_smul],
simp
end
variables {p : ℕ} [fact p.prime]
@[simp] lemma finite_field.char_poly_pow_card {K : Type*} [field K] [fintype K] (M : matrix n n K) :
char_poly (M ^ (fintype.card K)) = char_poly M :=
begin
by_cases hn : nonempty n,
{ letI := hn,
cases char_p.exists K with p hp, letI := hp,
rcases finite_field.card K p with ⟨⟨k, kpos⟩, ⟨hp, hk⟩⟩,
letI : fact p.prime := hp,
dsimp at hk, rw hk at *,
apply (frobenius_inj (polynomial K) p).iterate k,
repeat { rw iterate_frobenius, rw ← hk },
rw ← finite_field.expand_card,
unfold char_poly, rw [alg_hom.map_det, ← is_monoid_hom.map_pow],
apply congr_arg det,
apply mat_poly_equiv.injective, swap, { apply_instance },
rw [← mat_poly_equiv.coe_alg_hom, alg_hom.map_pow, mat_poly_equiv.coe_alg_hom,
mat_poly_equiv_char_matrix, hk, sub_pow_char_pow_of_commute, ← C_pow],
swap, { apply polynomial.commute_X },
-- the following is a nasty case bash that should be abstracted as a lemma
-- (and maybe it can be proven more... algebraically?)
ext, rw [coeff_sub, coeff_C],
by_cases hij : i = j; simp [char_matrix, hij, coeff_X_pow];
simp only [coeff_C]; split_ifs; simp *, },
{ congr, apply @subsingleton.elim _ (subsingleton_of_empty_left hn) _ _, },
end
@[simp] lemma zmod.char_poly_pow_card (M : matrix n n (zmod p)) :
char_poly (M ^ p) = char_poly M :=
by { have h := finite_field.char_poly_pow_card M, rwa zmod.card at h, }
lemma finite_field.trace_pow_card {K : Type*} [field K] [fintype K] [nonempty n] (M : matrix n n K) :
trace n K K (M ^ (fintype.card K)) = (trace n K K M) ^ (fintype.card K) :=
by rw [trace_eq_neg_char_poly_coeff, trace_eq_neg_char_poly_coeff,
finite_field.char_poly_pow_card, finite_field.pow_card]
lemma zmod.trace_pow_card {p:ℕ} [fact p.prime] [nonempty n] (M : matrix n n (zmod p)) :
trace n (zmod p) (zmod p) (M ^ p) = (trace n (zmod p) (zmod p) M)^p :=
by { have h := finite_field.trace_pow_card M, rwa zmod.card at h, }
namespace matrix
theorem is_integral : is_integral R M := ⟨char_poly M, ⟨char_poly_monic M, aeval_self_char_poly M⟩⟩
theorem min_poly_dvd_char_poly {K : Type*} [field K] (M : matrix n n K) :
(minimal_polynomial M.is_integral) ∣ char_poly M :=
minimal_polynomial.dvd M.is_integral (aeval_self_char_poly M)
end matrix
|
5870d9b4a13759e0aa1756c1251f7dee4500523a | 737dc4b96c97368cb66b925eeea3ab633ec3d702 | /tests/lean/conv1.lean | b94e7193cf8a2fc4ddf5d640e79903a704f8fed1 | [
"Apache-2.0"
] | permissive | Bioye97/lean4 | 1ace34638efd9913dc5991443777b01a08983289 | bc3900cbb9adda83eed7e6affeaade7cfd07716d | refs/heads/master | 1,690,589,820,211 | 1,631,051,000,000 | 1,631,067,598,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 2,711 | lean | set_option pp.analyze false
def p (x y : Nat) := x = y
example (x y : Nat) : p (x + y) (y + x + 0) := by
conv =>
whnf
congr
. skip
. whnf; skip
traceState
rw [Nat.add_comm]
rfl
example (x y : Nat) : p (x + y) (y + x + 0) := by
conv =>
whnf
rhs
whnf
traceState
rw [Nat.add_comm]
rfl
example (x y : Nat) : p (x + y) (y + x + 0) := by
conv =>
whnf
lhs
whnf
conv =>
rhs
whnf
traceState
apply Nat.add_comm x y
def f (x y z : Nat) : Nat :=
y
example (x y : Nat) : f x (x + y + 0) y = y + x := by
conv =>
lhs
arg 2
whnf
traceState
simp [f]
apply Nat.add_comm
example (x y : Nat) : f x (x + y + 0) y = y + x := by
conv =>
lhs
arg 2
change x + y
traceState
rw [Nat.add_comm]
example : id (fun x y => 0 + x + y) = Nat.add := by
conv =>
lhs
arg 1
ext a b
traceState
rw [Nat.zero_add]
traceState
example : id (fun x y => 0 + x + y) = Nat.add := by
conv =>
lhs
arg 1
intro a b
rw [Nat.zero_add]
example : id (fun x y => 0 + x + y) = Nat.add := by
conv =>
enter [1, 1, a, b]
traceState
rw [Nat.zero_add]
example (p : Nat → Prop) (h : ∀ a, p a) : ∀ a, p (id (0 + a)) := by
conv =>
intro x
traceState
arg 1
traceState
simp only [id]
traceState
rw [Nat.zero_add]
exact h
example (p : Prop) (x : Nat) : (x = x → p) → p := by
conv =>
congr
. traceState
congr
. simp
traceState
conv =>
lhs
simp
intros
assumption
example : (fun x => 0 + x) = id := by
conv =>
lhs
tactic => funext x
traceState
rw [Nat.zero_add]
example (p : Prop) (x : Nat) : (x = x → p) → p := by
conv =>
apply implies_congr
. apply implies_congr
simp
traceState
conv =>
lhs
simp
intros; assumption
example (x y : Nat) (f : Nat → Nat → Nat) (g : Nat → Nat) (h₁ : ∀ z, f z z = z) (h₂ : ∀ x y, f (g x) (g y) = y) : f (g (0 + y)) (f (g x) (g (0 + x))) = x := by
conv =>
pattern _ + _
apply Nat.zero_add
traceState
conv =>
pattern 0 + _
apply Nat.zero_add
traceState
simp [h₁, h₂]
example (x y : Nat) (h : y = 0) : x + ((y + x) + x) = x + (x + x) := by
conv =>
lhs
rhs
lhs
traceState
rw [h, Nat.zero_add]
example (p : Nat → Prop) (x y : Nat) (h : y = 0) : p (y + x) := by
conv => lhs
example (p : Nat → Prop) (x y : Nat) (h : y = 0) : p (y + x) := by
conv => arg 2
example (p : Prop) : p := by
conv => rhs
example (p : Nat → Prop) (x y : Nat) (h1 : y = 0) (h2 : p x) : p (y + x) := by
conv =>
rhs
traceState
rw [h1]
apply Nat.zero_add
exact h2
|
b34f14843533d37a8d6d71bc07b9434c406c29d2 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/ring_theory/polynomial/symmetric.lean | 33310236e4642314ab91f58ad5fa08d280de9235 | [
"Apache-2.0"
] | permissive | Vierkantor/mathlib | 0ea59ac32a3a43c93c44d70f441c4ee810ccceca | 83bc3b9ce9b13910b57bda6b56222495ebd31c2f | refs/heads/master | 1,658,323,012,449 | 1,652,256,003,000 | 1,652,256,003,000 | 209,296,341 | 0 | 1 | Apache-2.0 | 1,568,807,655,000 | 1,568,807,655,000 | null | UTF-8 | Lean | false | false | 8,189 | lean | /-
Copyright (c) 2020 Hanting Zhang. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Hanting Zhang, Johan Commelin
-/
import data.fintype.card
import data.mv_polynomial.rename
import data.mv_polynomial.comm_ring
import algebra.algebra.subalgebra.basic
/-!
# Symmetric Polynomials and Elementary Symmetric Polynomials
This file defines symmetric `mv_polynomial`s and elementary symmetric `mv_polynomial`s.
We also prove some basic facts about them.
## Main declarations
* `mv_polynomial.is_symmetric`
* `mv_polynomial.symmetric_subalgebra`
* `mv_polynomial.esymm`
## Notation
+ `esymm σ R n`, is the `n`th elementary symmetric polynomial in `mv_polynomial σ R`.
As in other polynomial files, we typically use the notation:
+ `σ τ : Type*` (indexing the variables)
+ `R S : Type*` `[comm_semiring R]` `[comm_semiring S]` (the coefficients)
+ `r : R` elements of the coefficient ring
+ `i : σ`, with corresponding monomial `X i`, often denoted `X_i` by mathematicians
+ `φ ψ : mv_polynomial σ R`
-/
open equiv (perm)
open_locale big_operators
noncomputable theory
namespace mv_polynomial
variables {σ : Type*} {R : Type*}
variables {τ : Type*} {S : Type*}
/-- A `mv_polynomial φ` is symmetric if it is invariant under
permutations of its variables by the `rename` operation -/
def is_symmetric [comm_semiring R] (φ : mv_polynomial σ R) : Prop :=
∀ e : perm σ, rename e φ = φ
variables (σ R)
/-- The subalgebra of symmetric `mv_polynomial`s. -/
def symmetric_subalgebra [comm_semiring R] : subalgebra R (mv_polynomial σ R) :=
{ carrier := set_of is_symmetric,
algebra_map_mem' := λ r e, rename_C e r,
mul_mem' := λ a b ha hb e, by rw [alg_hom.map_mul, ha, hb],
add_mem' := λ a b ha hb e, by rw [alg_hom.map_add, ha, hb] }
variables {σ R}
@[simp] lemma mem_symmetric_subalgebra [comm_semiring R] (p : mv_polynomial σ R) :
p ∈ symmetric_subalgebra σ R ↔ p.is_symmetric := iff.rfl
namespace is_symmetric
section comm_semiring
variables [comm_semiring R] [comm_semiring S] {φ ψ : mv_polynomial σ R}
@[simp]
lemma C (r : R) : is_symmetric (C r : mv_polynomial σ R) :=
(symmetric_subalgebra σ R).algebra_map_mem r
@[simp]
lemma zero : is_symmetric (0 : mv_polynomial σ R) :=
(symmetric_subalgebra σ R).zero_mem
@[simp]
lemma one : is_symmetric (1 : mv_polynomial σ R) :=
(symmetric_subalgebra σ R).one_mem
lemma add (hφ : is_symmetric φ) (hψ : is_symmetric ψ) : is_symmetric (φ + ψ) :=
(symmetric_subalgebra σ R).add_mem hφ hψ
lemma mul (hφ : is_symmetric φ) (hψ : is_symmetric ψ) : is_symmetric (φ * ψ) :=
(symmetric_subalgebra σ R).mul_mem hφ hψ
lemma smul (r : R) (hφ : is_symmetric φ) : is_symmetric (r • φ) :=
(symmetric_subalgebra σ R).smul_mem hφ r
@[simp]
lemma map (hφ : is_symmetric φ) (f : R →+* S) : is_symmetric (map f φ) :=
λ e, by rw [← map_rename, hφ]
end comm_semiring
section comm_ring
variables [comm_ring R] {φ ψ : mv_polynomial σ R}
lemma neg (hφ : is_symmetric φ) : is_symmetric (-φ) :=
(symmetric_subalgebra σ R).neg_mem hφ
lemma sub (hφ : is_symmetric φ) (hψ : is_symmetric ψ) : is_symmetric (φ - ψ) :=
(symmetric_subalgebra σ R).sub_mem hφ hψ
end comm_ring
end is_symmetric
section elementary_symmetric
open finset
variables (σ R) [comm_semiring R] [comm_semiring S] [fintype σ] [fintype τ]
/-- The `n`th elementary symmetric `mv_polynomial σ R`. -/
def esymm (n : ℕ) : mv_polynomial σ R :=
∑ t in powerset_len n univ, ∏ i in t, X i
/-- We can define `esymm σ R n` by summing over a subtype instead of over `powerset_len`. -/
lemma esymm_eq_sum_subtype (n : ℕ) : esymm σ R n =
∑ t : {s : finset σ // s.card = n}, ∏ i in (t : finset σ), X i :=
begin
rw esymm,
let i : Π (a : finset σ), a ∈ powerset_len n univ → {s : finset σ // s.card = n} :=
λ a ha, ⟨_, (mem_powerset_len.mp ha).2⟩,
refine sum_bij i (λ a ha, mem_univ (i a ha)) _ (λ _ _ _ _ hi, subtype.ext_iff_val.mp hi) _,
{ intros,
apply prod_congr,
simp only [subtype.coe_mk],
intros, refl,},
{ refine (λ b H, ⟨b.val, mem_powerset_len.mpr ⟨subset_univ b.val, b.property⟩, _⟩),
simp [i] },
end
/-- We can define `esymm σ R n` as a sum over explicit monomials -/
lemma esymm_eq_sum_monomial (n : ℕ) : esymm σ R n =
∑ t in powerset_len n univ, monomial (∑ i in t, finsupp.single i 1) 1 :=
begin
refine sum_congr rfl (λ x hx, _),
rw monic_monomial_eq,
rw finsupp.prod_pow,
rw ← prod_subset (λ y _, finset.mem_univ y : x ⊆ univ) (λ y _ hy, _),
{ refine prod_congr rfl (λ x' hx', _),
convert (pow_one _).symm,
convert (finsupp.apply_add_hom x' : (σ →₀ ℕ) →+ ℕ).map_sum _ x,
classical,
simp [finsupp.single_apply, finset.filter_eq', apply_ite, apply_ite finset.card],
rw if_pos, exact hx', },
{ convert pow_zero _,
convert (finsupp.apply_add_hom y : (σ →₀ ℕ) →+ ℕ).map_sum _ x,
classical,
simp [finsupp.single_apply, finset.filter_eq', apply_ite, apply_ite finset.card],
rw if_neg, exact hy }
end
@[simp] lemma esymm_zero : esymm σ R 0 = 1 :=
by simp only [esymm, powerset_len_zero, sum_singleton, prod_empty]
lemma map_esymm (n : ℕ) (f : R →+* S) : map f (esymm σ R n) = esymm σ S n :=
begin
rw [esymm, (map f).map_sum],
refine sum_congr rfl (λ x hx, _),
rw (map f).map_prod,
simp,
end
lemma rename_esymm (n : ℕ) (e : σ ≃ τ) : rename e (esymm σ R n) = esymm τ R n :=
begin
rw [esymm_eq_sum_subtype, esymm_eq_sum_subtype, (rename ⇑e).map_sum],
let e' : {s : finset σ // s.card = n} ≃ {s : finset τ // s.card = n} :=
equiv.subtype_equiv (equiv.finset_congr e) (by simp),
rw ← equiv.sum_comp e'.symm,
apply fintype.sum_congr,
intro,
calc _ = (∏ i in (e'.symm a : finset σ), (rename e) (X i)) : (rename e).map_prod _ _
... = (∏ i in (a : finset τ), (rename e) (X (e.symm i))) : prod_map (a : finset τ) _ _
... = _ : _,
apply finset.prod_congr rfl,
intros,
simp,
end
lemma esymm_is_symmetric (n : ℕ) : is_symmetric (esymm σ R n) :=
by { intro, rw rename_esymm }
lemma support_esymm'' (n : ℕ) [decidable_eq σ] [nontrivial R] :
(esymm σ R n).support = (powerset_len n (univ : finset σ)).bUnion
(λ t, (finsupp.single (∑ (i : σ) in t, finsupp.single i 1) (1:R)).support) :=
begin
rw esymm_eq_sum_monomial,
simp only [← single_eq_monomial],
convert finsupp.support_sum_eq_bUnion (powerset_len n (univ : finset σ)) _,
intros s t hst d,
simp only [finsupp.support_single_ne_zero one_ne_zero, and_imp, inf_eq_inter, mem_inter,
mem_singleton],
rintro h rfl,
have := congr_arg finsupp.support h,
rw [finsupp.support_sum_eq_bUnion, finsupp.support_sum_eq_bUnion] at this,
{ simp only [finsupp.support_single_ne_zero one_ne_zero, bUnion_singleton_eq_self] at this,
exact absurd this hst.symm },
all_goals { intros x y, simp [finsupp.support_single_disjoint] }
end
lemma support_esymm' (n : ℕ) [decidable_eq σ] [nontrivial R] :
(esymm σ R n).support =
(powerset_len n (univ : finset σ)).bUnion (λ t, {∑ (i : σ) in t, finsupp.single i 1}) :=
begin
rw support_esymm'',
congr,
funext,
exact finsupp.support_single_ne_zero one_ne_zero
end
lemma support_esymm (n : ℕ) [decidable_eq σ] [nontrivial R] :
(esymm σ R n).support =
(powerset_len n (univ : finset σ)).image (λ t, ∑ (i : σ) in t, finsupp.single i 1) :=
by { rw support_esymm', exact bUnion_singleton }
lemma degrees_esymm [nontrivial R]
(n : ℕ) (hpos : 0 < n) (hn : n ≤ fintype.card σ) :
(esymm σ R n).degrees = (univ : finset σ).val :=
begin
classical,
have : (finsupp.to_multiset ∘ λ (t : finset σ), ∑ (i : σ) in t, finsupp.single i 1) = finset.val,
{ funext, simp [finsupp.to_multiset_sum_single] },
rw [degrees, support_esymm, sup_finset_image, this, ←comp_sup_eq_sup_comp],
{ obtain ⟨k, rfl⟩ := nat.exists_eq_succ_of_ne_zero hpos.ne',
simpa using powerset_len_sup _ _ (nat.lt_of_succ_le hn) },
{ intros,
simp only [union_val, sup_eq_union],
congr },
{ refl }
end
end elementary_symmetric
end mv_polynomial
|
27746bcd93c78a9424a7435983cd46acbfd5ffd8 | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/parsing_only.lean | 8af35f38ad0b264bc1688a336f2223f35168976e | [
"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 | 192 | lean | --
constant f : nat → nat
constant g : nat → nat
notation a `+++` := f a
notation [parsing_only] a `***` := g a
#check 10 +++
#check 10 ***
#check Type.{8} -- Type₊ should not be used
|
afd1d79f2169d8505fc64161192c1713e788146c | 7bf54883c04ff2856c37f76a79599ceb380c1996 | /non-mathlib/quadratic_extension.lean | 48438ea64e9a85707cc0e164f8043e167a4badb5 | [] | no_license | anonymousLeanDocsHosting/lean-polynomials | 4094466bf19acc0d1a47b4cabb60d8c21ddb2b00 | 361ef4cb7b68ef47d43b85cfa2d13f2ea0a47613 | refs/heads/main | 1,691,112,899,935 | 1,631,819,522,000 | 1,631,819,522,000 | 405,448,439 | 0 | 2 | null | null | null | null | UTF-8 | Lean | false | false | 4,978 | lean | import field_definition
import field_results
import numbers
inductive item_plus_sqrt (f : Type) [myfld f] (rt : f) : Type
| ips : f -> f -> item_plus_sqrt
open item_plus_sqrt
def ips_zero (f : Type) [myfld f] (rt : f) : (item_plus_sqrt f rt) := ips myfld.zero myfld.zero
def ips_add (f : Type) [myfld f] (rt : f) : (item_plus_sqrt f rt) -> (item_plus_sqrt f rt) -> (item_plus_sqrt f rt)
| (ips a b) (ips c d) := (ips (myfld.add a c) (myfld.add b d))
def ips_negate (f : Type) [myfld f] (rt : f) : (item_plus_sqrt f rt) -> (item_plus_sqrt f rt)
| (ips a b) := (ips (myfld.negate a) (myfld.negate b))
def ips_mul (f : Type) [myfld f] (rt : f) : (item_plus_sqrt f rt) -> (item_plus_sqrt f rt) -> (item_plus_sqrt f rt)
| (ips a b) (ips c d) := (ips ((a .* c) .+ (b .* d .* rt)) ((a .* d) .+ (b .* c)))
def to_ips (f : Type) [myfld f] (rt : f) (x : f) : (item_plus_sqrt f rt) := (ips x myfld.zero)
lemma ips_add_comm (f : Type) [myfld f] (rt : f) (a b c d : f) :
ips_add f rt (ips a b) (ips c d) = ips_add f rt (ips c d) (ips a b) :=
begin
unfold ips_add, rw myfld.add_comm a c, rw myfld.add_comm b d,
end
lemma ips_add_assoc (f : Type) [myfld f] (rt : f) (a1 b1 a2 b2 a3 b3 : f) :
ips_add f rt (ips a1 b1) (ips_add f rt (ips a2 b2) (ips a3 b3)) =
ips_add f rt (ips_add f rt (ips a1 b1) (ips a2 b2)) (ips a3 b3) :=
begin
unfold ips_add, repeat {rw myfld.add_assoc},
end
lemma ips_mul_comm (f : Type) [myfld f] (rt : f) (a b c d : f) :
ips_mul f rt (ips a b) (ips c d) = ips_mul f rt (ips c d) (ips a b) :=
begin
unfold ips_mul, rw myfld.mul_comm a c, rw myfld.mul_comm b d,
rw myfld.mul_comm a d, rw myfld.mul_comm b c,
rw myfld.add_comm (c .* b) (d .* a),
end
def quadratic_formula (f : Type) [myfld f] [fld_not_char_two f] (b c : f) :
(item_plus_sqrt f ((b .* b) .+ ((four f) .* .- c))) :=
ips (.- b) .* (myfld.reciprocal (two f) (fld_not_char_two.not_char_two))
(myfld.reciprocal (two f) (fld_not_char_two.not_char_two))
def quadratic_subst_ips (f : Type) [myfld f] [fld_not_char_two f] (rt : f) (b c : f)
(x : item_plus_sqrt f rt) : (item_plus_sqrt f rt) :=
ips_add f rt (ips_mul f rt x x) (ips_add f rt (ips_mul f rt x (to_ips f rt b)) (to_ips f rt c))
lemma quadratic_formula_works (f : Type) [myfld f] [fld_not_char_two f] (b c : f) :
(quadratic_subst_ips f ((b .* b) .+ ((four f) .* .- c)) b c
(quadratic_formula f b c))
=
(ips myfld.zero myfld.zero) :=
begin
unfold quadratic_formula, unfold quadratic_subst_ips,
unfold to_ips, unfold ips_mul, unfold ips_add,
repeat {rw zero_simp}, repeat {rw zero_mul}, repeat {rw mul_zero}, rw simp_zero, rw zero_simp,
repeat {rw mul_negate, rw mul_negate_alt_simp}, rw mul_negate,
rw double_negative,
have tmp : ∀ (p q rt : f), (p = myfld.zero) -> (q = myfld.zero) ->
((ips p q) : (item_plus_sqrt f rt)) =
((ips myfld.zero myfld.zero) : (item_plus_sqrt f rt)),
intros p q rt h1 h2, rw h1, rw h2,
apply tmp, clear tmp,
rw mul_two_reciprocals,
rw [myfld.mul_comm b (myfld.reciprocal (two f) _)] {occs := occurrences.pos [2]},
rw <- myfld.mul_assoc _ (myfld.reciprocal (two f) _) _,
rw myfld.mul_assoc (myfld.reciprocal (two f) _) (myfld.reciprocal (two f) _) _,
rw mul_two_reciprocals, rw myfld.mul_comm b ((myfld.reciprocal _ _) .* _),
rw <- myfld.mul_assoc (myfld.reciprocal _ _) b b,
rw <- distrib_simp_alt,
have tmp : .- (b .* (myfld.reciprocal (two f) fld_not_char_two.not_char_two) .* b) =
.- ((myfld.reciprocal ((two f) .* (two f)) (mul_nonzero f (two f) (two f) fld_not_char_two.not_char_two fld_not_char_two.not_char_two))
.* ((b .* b) .+ (b .* b))),
rw <- mul_two_reciprocals, have tmp_tmp : ((b .* b) .+ (b .* b)) = (two f) .* (b .* b),
unfold two, rw distrib_simp, rw one_mul_simp,
rw tmp_tmp, rw myfld.mul_assoc _ (two f) _,
rw <- myfld.mul_assoc _ (myfld.reciprocal (two f) _) (two f),
rw myfld.mul_comm (myfld.reciprocal (two f) _) (two f), rw myfld.mul_reciprocal,
rw simp_mul_one, rw myfld.mul_comm b _, rw myfld.mul_assoc,
rw tmp, clear tmp, rw mul_negate_alt f _ ((b .* b) .+ (b .* b)),
rw myfld.add_assoc, rw <- distrib_simp_alt,
rw myfld.add_assoc (b .* b) (b .* b), rw myfld.add_comm _ (.- ((four f) .* c)),
rw <- myfld.add_assoc _ ((b .* b) .+ (b .* b)) _,
rw myfld.add_negate, rw zero_simp,
rw mul_negate_alt_simp, have tmp : (two f) .* (two f) = (four f), unfold four, rw two_plus_two,
rw reciprocal_rewrite f _ (four f) tmp, rw myfld.mul_assoc, rw myfld.mul_comm _ (four f),
rw myfld.mul_reciprocal, rw one_mul_simp, rw myfld.add_comm, rw myfld.add_negate,
clear tmp,
rw myfld.mul_comm _ (b .* (myfld.reciprocal (two f) fld_not_char_two.not_char_two)),
rw <- add_negate, rw <- distrib_simp_alt, rw only_one_reciprocal f (two f) _ (two_ne_zero f),
rw add_two_halves, rw simp_mul_one,
rw myfld.add_comm, rw myfld.mul_comm b _, rw myfld.add_negate,
end
|
d08ee8222971c3f1c6a01af51410b1b6787b4b02 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/measure_theory/constructions/borel_space/complex.lean | de7034d99a04238322bbec1e6c2e087b3823be64 | [
"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 | 790 | lean | /-
Copyright (c) 2020 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov
-/
import analysis.complex.basic
import measure_theory.constructions.borel_space.basic
/-! # Equip `ℂ` with the Borel sigma-algebra
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.-/
noncomputable theory
@[priority 900]
instance is_R_or_C.measurable_space {𝕜 : Type*} [is_R_or_C 𝕜] : measurable_space 𝕜 := borel 𝕜
@[priority 900]
instance is_R_or_C.borel_space {𝕜 : Type*} [is_R_or_C 𝕜] : borel_space 𝕜 := ⟨rfl⟩
instance complex.measurable_space : measurable_space ℂ := borel ℂ
instance complex.borel_space : borel_space ℂ := ⟨rfl⟩
|
477cbf1766dde216c53a373b1047d93c35b59912 | 5ae26df177f810c5006841e9c73dc56e01b978d7 | /src/category_theory/limits/cones.lean | dc82ec1473f73e83eb3d68f201a352e893dc0723 | [
"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 | 16,153 | 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, Floris van Doorn
-/
import category_theory.const
import category_theory.yoneda
import category_theory.concrete_category
import category_theory.equivalence
universes v u u' -- declare the `v`'s first; see `category_theory.category` for an explanation
open category_theory
-- There is an awkward difficulty with universes here.
-- If we allowed `J` to be a small category in `Prop`, we'd run into trouble
-- because `yoneda.obj (F : (J ⥤ C)ᵒᵖ)` will be a functor into `Sort (max v 1)`,
-- not into `Sort v`.
-- So we don't allow this case; it's not particularly useful anyway.
variables {J : Type v} [small_category J]
variables {C : Type u} [𝒞 : category.{v+1} C]
include 𝒞
open category_theory
open category_theory.category
open category_theory.functor
open opposite
namespace category_theory
namespace functor
variables {J C} (F : J ⥤ C)
/--
`F.cones` is the functor assigning to an object `X` the type of
natural transformations from the constant functor with value `X` to `F`.
An object representing this functor is a limit of `F`.
-/
def cones : Cᵒᵖ ⥤ Type v := (const J).op ⋙ (yoneda.obj F)
lemma cones_obj (X : Cᵒᵖ) : F.cones.obj X = ((const J).obj (unop X) ⟶ F) := rfl
@[simp] lemma cones_map_app {X₁ X₂ : Cᵒᵖ} (f : X₁ ⟶ X₂) (t : F.cones.obj X₁) (j : J) :
(F.cones.map f t).app j = f.unop ≫ t.app j := rfl
/--
`F.cocones` is the functor assigning to an object `X` the type of
natural transformations from `F` to the constant functor with value `X`.
An object corepresenting this functor is a colimit of `F`.
-/
def cocones : C ⥤ Type v := const J ⋙ coyoneda.obj (op F)
lemma cocones_obj (X : C) : F.cocones.obj X = (F ⟶ (const J).obj X) := rfl
@[simp] lemma cocones_map_app {X₁ X₂ : C} (f : X₁ ⟶ X₂) (t : F.cocones.obj X₁) (j : J) :
(F.cocones.map f t).app j = t.app j ≫ f := rfl
end functor
section
variables (J C)
def cones : (J ⥤ C) ⥤ (Cᵒᵖ ⥤ Type v) :=
{ obj := functor.cones,
map := λ F G f, whisker_left (const J).op (yoneda.map f) }
def cocones : (J ⥤ C)ᵒᵖ ⥤ (C ⥤ Type v) :=
{ obj := λ F, functor.cocones (unop F),
map := λ F G f, whisker_left (const J) (coyoneda.map f) }
variables {J C}
@[simp] lemma cones_obj (F : J ⥤ C) : (cones J C).obj F = F.cones := rfl
@[simp] lemma cones_map {F G : J ⥤ C} {f : F ⟶ G} :
(cones J C).map f = (whisker_left (const J).op (yoneda.map f)) := rfl
@[simp] lemma cocones_obj (F : (J ⥤ C)ᵒᵖ) : (cocones J C).obj F = (unop F).cocones := rfl
@[simp] lemma cocones_map {F G : (J ⥤ C)ᵒᵖ} {f : F ⟶ G} :
(cocones J C).map f = (whisker_left (const J) (coyoneda.map f)) := rfl
end
namespace limits
/--
A `c : cone F` is:
* an object `c.X` and
* a natural transformation `c.π : c.X ⟶ F` from the constant `c.X` functor to `F`.
`cone F` is equivalent, in the obvious way, to `Σ X, F.cones.obj X`.
-/
structure cone (F : J ⥤ C) :=
(X : C)
(π : (const J).obj X ⟶ F)
@[simp] lemma cone.w {F : J ⥤ C} (c : cone F) {j j' : J} (f : j ⟶ j') :
c.π.app j ≫ F.map f = c.π.app j' :=
by convert ←(c.π.naturality f).symm; apply id_comp
/--
A `c : cocone F` is
* an object `c.X` and
* a natural transformation `c.ι : F ⟶ c.X` from `F` to the constant `c.X` functor.
`cocone F` is equivalent, in the obvious way, to `Σ X, F.cocones.obj X`.
-/
structure cocone (F : J ⥤ C) :=
(X : C)
(ι : F ⟶ (const J).obj X)
@[simp] lemma cocone.w {F : J ⥤ C} (c : cocone F) {j j' : J} (f : j ⟶ j') :
F.map f ≫ c.ι.app j' = c.ι.app j :=
by convert ←(c.ι.naturality f); apply comp_id
variables {F : J ⥤ C}
namespace cone
@[simp] def extensions (c : cone F) : yoneda.obj c.X ⟶ F.cones :=
{ app := λ X f, ((const J).map f) ≫ c.π }
/-- A map to the vertex of a cone induces a cone by composition. -/
@[simp] def extend (c : cone F) {X : C} (f : X ⟶ c.X) : cone F :=
{ X := X,
π := c.extensions.app (op X) f }
@[simp] lemma extend_π (c : cone F) {X : Cᵒᵖ} (f : unop X ⟶ c.X) :
(extend c f).π = c.extensions.app X f :=
rfl
def whisker {K : Type v} [small_category K] (E : K ⥤ J) (c : cone F) : cone (E ⋙ F) :=
{ X := c.X,
π := whisker_left E c.π }
@[simp] lemma whisker_π_app (c : cone F) {K : Type v} [small_category K] (E : K ⥤ J) (k : K) :
(c.whisker E).π.app k = (c.π).app (E.obj k) := rfl
section
omit 𝒞
variables {m : Type v → Type v}
variables (hom : ∀ {α β : Type v}, m α → m β → (α → β) → Prop)
variables [h : concrete_category @hom]
include h
@[simp] lemma naturality_bundled {G : J ⥤ bundled m} (s : cone G) {j j' : J} (f : j ⟶ j') (x : s.X) :
(G.map f) ((s.π.app j) x) = (s.π.app j') x :=
congr_fun (congr_arg (λ k : s.X ⟶ G.obj j', (k : s.X → G.obj j')) (s.π.naturality f).symm) x
end
end cone
namespace cocone
@[simp] def extensions (c : cocone F) : coyoneda.obj (op c.X) ⟶ F.cocones :=
{ app := λ X f, c.ι ≫ (const J).map f }
/-- A map from the vertex of a cocone induces a cocone by composition. -/
@[simp] def extend (c : cocone F) {X : C} (f : c.X ⟶ X) : cocone F :=
{ X := X,
ι := c.extensions.app X f }
@[simp] lemma extend_ι (c : cocone F) {X : C} (f : c.X ⟶ X) :
(extend c f).ι = c.extensions.app X f :=
rfl
def whisker {K : Type v} [small_category K] (E : K ⥤ J) (c : cocone F) : cocone (E ⋙ F) :=
{ X := c.X,
ι := whisker_left E c.ι }
@[simp] lemma whisker_ι_app (c : cocone F) {K : Type v} [small_category K] (E : K ⥤ J) (k : K) :
(c.whisker E).ι.app k = (c.ι).app (E.obj k) := rfl
section
omit 𝒞
variables {m : Type v → Type v}
variables (hom : ∀ {α β : Type v}, m α → m β → (α → β) → Prop)
variables [h : concrete_category @hom]
include h
@[simp] lemma naturality_bundled {G : J ⥤ bundled m} (s : cocone G) {j j' : J} (f : j ⟶ j') (x : G.obj j) :
(s.ι.app j') ((G.map f) x) = (s.ι.app j) x :=
congr_fun (congr_arg (λ k : G.obj j ⟶ s.X, (k : G.obj j → s.X)) (s.ι.naturality f)) x
end
end cocone
structure cone_morphism (A B : cone F) :=
(hom : A.X ⟶ B.X)
(w' : ∀ j : J, hom ≫ B.π.app j = A.π.app j . obviously)
restate_axiom cone_morphism.w'
attribute [simp] cone_morphism.w
@[extensionality] lemma cone_morphism.ext {A B : cone F} {f g : cone_morphism A B}
(w : f.hom = g.hom) : f = g :=
by cases f; cases g; simpa using w
instance cone.category : category.{v+1} (cone F) :=
{ hom := λ A B, cone_morphism A B,
comp := λ X Y Z f g,
{ hom := f.hom ≫ g.hom,
w' := by intro j; rw [assoc, g.w, f.w] },
id := λ B, { hom := 𝟙 B.X } }
namespace cones
@[simp] lemma id.hom (c : cone F) : (𝟙 c : cone_morphism c c).hom = 𝟙 (c.X) := rfl
@[simp] lemma comp.hom {c d e : cone F} (f : c ⟶ d) (g : d ⟶ e) :
(f ≫ g).hom = f.hom ≫ g.hom := rfl
/-- To give an isomorphism between cones, it suffices to give an
isomorphism between their vertices which commutes with the cone
maps. -/
@[extensionality] def ext {c c' : cone F}
(φ : c.X ≅ c'.X) (w : ∀ j, c.π.app j = φ.hom ≫ c'.π.app j) : c ≅ c' :=
{ hom := { hom := φ.hom },
inv := { hom := φ.inv, w' := λ j, φ.inv_comp_eq.mpr (w j) } }
@[simp] lemma ext_hom_hom {c c' : cone F} (φ : c.X ≅ c'.X)
(w : ∀ j, c.π.app j = φ.hom ≫ c'.π.app j) : (ext φ w).hom.hom = φ.hom := rfl
def postcompose {G : J ⥤ C} (α : F ⟶ G) : cone F ⥤ cone G :=
{ obj := λ c, { X := c.X, π := c.π ≫ α },
map := λ c₁ c₂ f, { hom := f.hom, w' :=
by intro; erw ← category.assoc; simp [-category.assoc] } }
@[simp] lemma postcompose_obj_X {G : J ⥤ C} (α : F ⟶ G) (c : cone F) :
((postcompose α).obj c).X = c.X := rfl
@[simp] lemma postcompose_obj_π {G : J ⥤ C} (α : F ⟶ G) (c : cone F) :
((postcompose α).obj c).π = c.π ≫ α := rfl
@[simp] lemma postcompose_map_hom {G : J ⥤ C} (α : F ⟶ G) {c₁ c₂ : cone F} (f : c₁ ⟶ c₂) :
((postcompose α).map f).hom = f.hom := rfl
def postcompose_comp {G H : J ⥤ C} (α : F ⟶ G) (β : G ⟶ H) :
postcompose (α ≫ β) ≅ postcompose α ⋙ postcompose β :=
by { fapply nat_iso.of_components, { intro s, fapply ext, refl, obviously }, obviously }
def postcompose_id : postcompose (𝟙 F) ≅ functor.id (cone F) :=
by { fapply nat_iso.of_components, { intro s, fapply ext, refl, obviously }, obviously }
def postcompose_equivalence {G : J ⥤ C} (α : F ≅ G) : cone F ≌ cone G :=
begin
refine equivalence.mk (postcompose α.hom) (postcompose α.inv) _ _,
{ symmetry,
refine (postcompose_comp _ _).symm.trans _, rw [iso.hom_inv_id], exact postcompose_id },
{ refine (postcompose_comp _ _).symm.trans _, rw [iso.inv_hom_id], exact postcompose_id }
end
def forget : cone F ⥤ C :=
{ obj := λ t, t.X, map := λ s t f, f.hom }
@[simp] lemma forget_obj {t : cone F} : forget.obj t = t.X := rfl
@[simp] lemma forget_map {s t : cone F} {f : s ⟶ t} : forget.map f = f.hom := rfl
section
variables {D : Type u'} [𝒟 : category.{v+1} D]
include 𝒟
@[simp] def functoriality (G : C ⥤ D) : cone F ⥤ cone (F ⋙ G) :=
{ obj := λ A,
{ X := G.obj A.X,
π := { app := λ j, G.map (A.π.app j), naturality' := by intros; erw ←G.map_comp; tidy } },
map := λ X Y f,
{ hom := G.map f.hom,
w' := by intros; rw [←functor.map_comp, f.w] } }
end
end cones
structure cocone_morphism (A B : cocone F) :=
(hom : A.X ⟶ B.X)
(w' : ∀ j : J, A.ι.app j ≫ hom = B.ι.app j . obviously)
restate_axiom cocone_morphism.w'
attribute [simp] cocone_morphism.w
@[extensionality] lemma cocone_morphism.ext
{A B : cocone F} {f g : cocone_morphism A B} (w : f.hom = g.hom) : f = g :=
by cases f; cases g; simpa using w
instance cocone.category : category.{v+1} (cocone F) :=
{ hom := λ A B, cocone_morphism A B,
comp := λ _ _ _ f g,
{ hom := f.hom ≫ g.hom,
w' := by intro j; rw [←assoc, f.w, g.w] },
id := λ B, { hom := 𝟙 B.X } }
namespace cocones
@[simp] lemma id.hom (c : cocone F) : (𝟙 c : cocone_morphism c c).hom = 𝟙 (c.X) := rfl
@[simp] lemma comp.hom {c d e : cocone F} (f : c ⟶ d) (g : d ⟶ e) :
(f ≫ g).hom = f.hom ≫ g.hom := rfl
/-- To give an isomorphism between cocones, it suffices to give an
isomorphism between their vertices which commutes with the cocone
maps. -/
@[extensionality] def ext {c c' : cocone F}
(φ : c.X ≅ c'.X) (w : ∀ j, c.ι.app j ≫ φ.hom = c'.ι.app j) : c ≅ c' :=
{ hom := { hom := φ.hom },
inv := { hom := φ.inv, w' := λ j, φ.comp_inv_eq.mpr (w j).symm } }
@[simp] lemma ext_hom_hom {c c' : cocone F} (φ : c.X ≅ c'.X)
(w : ∀ j, c.ι.app j ≫ φ.hom = c'.ι.app j) : (ext φ w).hom.hom = φ.hom := rfl
def precompose {G : J ⥤ C} (α : G ⟶ F) : cocone F ⥤ cocone G :=
{ obj := λ c, { X := c.X, ι := α ≫ c.ι },
map := λ c₁ c₂ f, { hom := f.hom } }
@[simp] lemma precompose_obj_X {G : J ⥤ C} (α : G ⟶ F) (c : cocone F) :
((precompose α).obj c).X = c.X := rfl
@[simp] lemma precompose_obj_ι {G : J ⥤ C} (α : G ⟶ F) (c : cocone F) :
((precompose α).obj c).ι = α ≫ c.ι := rfl
@[simp] lemma precompose_map_hom {G : J ⥤ C} (α : G ⟶ F) {c₁ c₂ : cocone F} (f : c₁ ⟶ c₂) :
((precompose α).map f).hom = f.hom := rfl
def precompose_comp {G H : J ⥤ C} (α : F ⟶ G) (β : G ⟶ H) :
precompose (α ≫ β) ≅ precompose β ⋙ precompose α :=
by { fapply nat_iso.of_components, { intro s, fapply ext, refl, obviously }, obviously }
def precompose_id : precompose (𝟙 F) ≅ functor.id (cocone F) :=
by { fapply nat_iso.of_components, { intro s, fapply ext, refl, obviously }, obviously }
def precompose_equivalence {G : J ⥤ C} (α : G ≅ F) : cocone F ≌ cocone G :=
begin
refine equivalence.mk (precompose α.hom) (precompose α.inv) _ _,
{ symmetry, refine (precompose_comp _ _).symm.trans _, rw [iso.inv_hom_id], exact precompose_id },
{ refine (precompose_comp _ _).symm.trans _, rw [iso.hom_inv_id], exact precompose_id }
end
def forget : cocone F ⥤ C :=
{ obj := λ t, t.X, map := λ s t f, f.hom }
@[simp] lemma forget_obj {t : cocone F} : forget.obj t = t.X := rfl
@[simp] lemma forget_map {s t : cocone F} {f : s ⟶ t} : forget.map f = f.hom := rfl
section
variables {D : Type u'} [𝒟 : category.{v+1} D]
include 𝒟
@[simp] def functoriality (G : C ⥤ D) : cocone F ⥤ cocone (F ⋙ G) :=
{ obj := λ A,
{ X := G.obj A.X,
ι := { app := λ j, G.map (A.ι.app j), naturality' := by intros; erw ←G.map_comp; tidy } },
map := λ _ _ f,
{ hom := G.map f.hom,
w' := by intros; rw [←functor.map_comp, cocone_morphism.w] } }
end
end cocones
end limits
namespace functor
variables {D : Type u'} [category.{v+1} D]
variables {F : J ⥤ C} {G : J ⥤ C} (H : C ⥤ D)
open category_theory.limits
/-- The image of a cone in C under a functor G : C ⥤ D is a cone in D. -/
def map_cone (c : cone F) : cone (F ⋙ H) := (cones.functoriality H).obj c
/-- The image of a cocone in C under a functor G : C ⥤ D is a cocone in D. -/
def map_cocone (c : cocone F) : cocone (F ⋙ H) := (cocones.functoriality H).obj c
@[simp] lemma map_cone_X (c : cone F) : (H.map_cone c).X = H.obj c.X := rfl
@[simp] lemma map_cocone_X (c : cocone F) : (H.map_cocone c).X = H.obj c.X := rfl
def map_cone_inv [is_equivalence H]
(c : cone (F ⋙ H)) : cone F :=
let t := (inv H).map_cone c in
let α : (F ⋙ H) ⋙ inv H ⟶ F :=
((whisker_left F (is_equivalence.unit_iso H).inv) : F ⋙ (H ⋙ inv H) ⟶ _) ≫ (functor.right_unitor _).hom in
{ X := t.X,
π := ((category_theory.cones J C).map α).app (op t.X) t.π }
@[simp] lemma map_cone_inv_X [is_equivalence H] (c : cone (F ⋙ H)) : (H.map_cone_inv c).X = (inv H).obj c.X := rfl
def map_cone_morphism {c c' : cone F} (f : cone_morphism c c') :
cone_morphism (H.map_cone c) (H.map_cone c') := (cones.functoriality H).map f
def map_cocone_morphism {c c' : cocone F} (f : cocone_morphism c c') :
cocone_morphism (H.map_cocone c) (H.map_cocone c') := (cocones.functoriality H).map f
@[simp] lemma map_cone_π (c : cone F) (j : J) :
(map_cone H c).π.app j = H.map (c.π.app j) := rfl
@[simp] lemma map_cocone_ι (c : cocone F) (j : J) :
(map_cocone H c).ι.app j = H.map (c.ι.app j) := rfl
end functor
end category_theory
namespace category_theory.limits
variables {F : J ⥤ Cᵒᵖ}
def cone_of_cocone_left_op (c : cocone F.left_op) : cone F :=
{ X := op c.X,
π := nat_trans.right_op (c.ι ≫ (const.op_obj_unop (op c.X)).hom) }
@[simp] lemma cone_of_cocone_left_op_X (c : cocone F.left_op) :
(cone_of_cocone_left_op c).X = op c.X :=
rfl
@[simp] lemma cone_of_cocone_left_op_π_app (c : cocone F.left_op) (j) :
(cone_of_cocone_left_op c).π.app j = (c.ι.app (op j)).op :=
by { dsimp [cone_of_cocone_left_op], simp }
def cocone_left_op_of_cone (c : cone F) : cocone (F.left_op) :=
{ X := unop c.X,
ι := nat_trans.left_op c.π }
@[simp] lemma cocone_left_op_of_cone_X (c : cone F) :
(cocone_left_op_of_cone c).X = unop c.X :=
rfl
@[simp] lemma cocone_left_op_of_cone_ι_app (c : cone F) (j) :
(cocone_left_op_of_cone c).ι.app j = (c.π.app (unop j)).unop :=
by { dsimp [cocone_left_op_of_cone], simp }
def cocone_of_cone_left_op (c : cone F.left_op) : cocone F :=
{ X := op c.X,
ι := nat_trans.right_op ((const.op_obj_unop (op c.X)).hom ≫ c.π) }
@[simp] lemma cocone_of_cone_left_op_X (c : cone F.left_op) :
(cocone_of_cone_left_op c).X = op c.X :=
rfl
@[simp] lemma cocone_of_cone_left_op_ι_app (c : cone F.left_op) (j) :
(cocone_of_cone_left_op c).ι.app j = (c.π.app (op j)).op :=
by { dsimp [cocone_of_cone_left_op], simp }
def cone_left_op_of_cocone (c : cocone F) : cone (F.left_op) :=
{ X := unop c.X,
π := nat_trans.left_op c.ι }
@[simp] lemma cone_left_op_of_cocone_X (c : cocone F) :
(cone_left_op_of_cocone c).X = unop c.X :=
rfl
@[simp] lemma cone_left_op_of_cocone_π_app (c : cocone F) (j) :
(cone_left_op_of_cocone c).π.app j = (c.ι.app (unop j)).unop :=
by { dsimp [cone_left_op_of_cocone], simp }
end category_theory.limits
|
19359d25ed00dd21b707e61e3df117c1a6fa6e62 | ba4794a0deca1d2aaa68914cd285d77880907b5c | /src/game/world7/level10.lean | e3829f6006b6ed6c11baecbc3d4270c7f1803696 | [
"Apache-2.0"
] | permissive | ChrisHughes24/natural_number_game | c7c00aa1f6a95004286fd456ed13cf6e113159ce | 9d09925424da9f6275e6cfe427c8bcf12bb0944f | refs/heads/master | 1,600,715,773,528 | 1,573,910,462,000 | 1,573,910,462,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,353 | lean | import game.world6.level8 -- hide
import tactic.tauto
local attribute [instance, priority 10] classical.prop_decidable -- hide
/-
# Advanced proposition world.
## Level 10: `exfalso` and proof by contradiction.
It's certainly true that $(P\land(\lnot P)\implies Q$ for any propositions $P$
and $Q$, because the left hand side of the implication is false. But how do
we prove that `false` implies any proposition $Q$? A cheap way of doing it in
Lean is using the `exfalso` tactic, which changes any goal at all to `false`.
You might think this is a step backwards, but if you have a hypothesis `h : ¬ P`
then after `rw not_iff_imp_false at h,` you can `apply h,` to make progress.
Try solving this level without using `cc` or `tauto`, but using `exfalso` instead.
-/
/- Lemma : no-side-bar
If $P$ and $Q$ are true/false statements, then
$$(P\land(\lnot P))\implies Q.$$
-/
lemma contra (P Q : Prop) : (P ∧ ¬ P) → Q :=
begin
intro h,
cases h with p np,
rw not_iff_imp_false at np,
exfalso,
apply np,
exact p,
end
/-
OK that's enough logic -- now perhaps it's time to go on to Advanced Addition World!
Get to it via the main menu.
-/
/-
## Pro tip.
`¬ P` is actually `P → false` *by definition*. Try
commenting out `rw not_iff_imp_false at ...` by putting two minus signs `--`
before the `rw`. Does it still compile?
-/ |
8af1bbc69b06260da2d249144421132f45ee090b | 4727251e0cd73359b15b664c3170e5d754078599 | /src/algebra/category/Module/images.lean | 77d0c29fcb4409940b5b12a325254d97b7805372 | [
"Apache-2.0"
] | permissive | Vierkantor/mathlib | 0ea59ac32a3a43c93c44d70f441c4ee810ccceca | 83bc3b9ce9b13910b57bda6b56222495ebd31c2f | refs/heads/master | 1,658,323,012,449 | 1,652,256,003,000 | 1,652,256,003,000 | 209,296,341 | 0 | 1 | Apache-2.0 | 1,568,807,655,000 | 1,568,807,655,000 | null | UTF-8 | Lean | false | false | 3,734 | lean | /-
Copyright (c) 2022 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import algebra.category.Module.abelian
import category_theory.limits.shapes.images
import category_theory.limits.types
/-!
# The category of R-modules has images.
Note that we don't need to register any of the constructions here as instances, because we get them
from the fact that `Module R` is an abelian category.
-/
open category_theory
open category_theory.limits
universes u v
namespace Module
variables {R : Type u} [comm_ring R]
variables {G H : Module.{v} R} (f : G ⟶ H)
local attribute [ext] subtype.ext_val
section -- implementation details of `has_image` for Module; use the API, not these
/-- The image of a morphism in `Module R` is just the bundling of `linear_map.range f` -/
def image : Module R := Module.of R (linear_map.range f)
/-- The inclusion of `image f` into the target -/
def image.ι : image f ⟶ H := f.range.subtype
instance : mono (image.ι f) := concrete_category.mono_of_injective (image.ι f) subtype.val_injective
/-- The corestriction map to the image -/
def factor_thru_image : G ⟶ image f := f.range_restrict
lemma image.fac : factor_thru_image f ≫ image.ι f = f :=
by { ext, refl, }
local attribute [simp] image.fac
variables {f}
/-- The universal property for the image factorisation -/
noncomputable def image.lift (F' : mono_factorisation f) : image f ⟶ F'.I :=
{ to_fun :=
(λ x, F'.e (classical.indefinite_description _ x.2).1 : image f → F'.I),
map_add' :=
begin
intros x y,
haveI := F'.m_mono,
apply (mono_iff_injective F'.m).1, apply_instance,
rw [linear_map.map_add],
change (F'.e ≫ F'.m) _ = (F'.e ≫ F'.m) _ + (F'.e ≫ F'.m) _,
rw [F'.fac],
rw (classical.indefinite_description (λ z, f z = _) _).2,
rw (classical.indefinite_description (λ z, f z = _) _).2,
rw (classical.indefinite_description (λ z, f z = _) _).2,
refl,
end,
map_smul' := λ c x,
begin
haveI := F'.m_mono,
apply (mono_iff_injective F'.m).1, apply_instance,
rw [linear_map.map_smul],
change (F'.e ≫ F'.m) _ = _ • (F'.e ≫ F'.m) _,
rw [F'.fac],
rw (classical.indefinite_description (λ z, f z = _) _).2,
rw (classical.indefinite_description (λ z, f z = _) _).2,
refl,
end }
lemma image.lift_fac (F' : mono_factorisation f) : image.lift F' ≫ F'.m = image.ι f :=
begin
ext x,
change (F'.e ≫ F'.m) _ = _,
rw [F'.fac, (classical.indefinite_description _ x.2).2],
refl,
end
end
/-- The factorisation of any morphism in `Module R` through a mono. -/
def mono_factorisation : mono_factorisation f :=
{ I := image f,
m := image.ι f,
e := factor_thru_image f }
/-- The factorisation of any morphism in `Module R` through a mono has the universal property of
the image. -/
noncomputable def is_image : is_image (mono_factorisation f) :=
{ lift := image.lift,
lift_fac' := image.lift_fac }
/--
The categorical image of a morphism in `Module R`
agrees with the linear algebraic range.
-/
noncomputable def image_iso_range {G H : Module.{v} R} (f : G ⟶ H) :
limits.image f ≅ Module.of R f.range :=
is_image.iso_ext (image.is_image f) (is_image f)
@[simp, reassoc, elementwise]
lemma image_iso_range_inv_image_ι {G H : Module.{v} R} (f : G ⟶ H) :
(image_iso_range f).inv ≫ limits.image.ι f = Module.of_hom f.range.subtype :=
is_image.iso_ext_inv_m _ _
@[simp, reassoc, elementwise]
lemma image_iso_range_hom_subtype {G H : Module.{v} R} (f : G ⟶ H) :
(image_iso_range f).hom ≫ Module.of_hom f.range.subtype = limits.image.ι f :=
by erw [←image_iso_range_inv_image_ι f, iso.hom_inv_id_assoc]
end Module
|
b6e4c300490fc6e61c02c9840f229c2a5523768b | 618003631150032a5676f229d13a079ac875ff77 | /docs/tutorial/Zmod37.lean | c8168af6ee4f4b2d3e7ba4e3bdef0262bd9afc1c | [
"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 | 8,109 | lean | /- Integers mod 37
A demonstration of how to use equivalence relations and equivalence classes in Lean.
We define the "congruent mod 37" relation on integers, prove it is an equivalence
relation, define Zmod37 to be the equivalence classes, and put a ring structure on
the quotient.
-/
-- this import is helpful for some intermediate calculations
import tactic.ring
-- Definition of the equivalence relation
definition cong_mod37 (a b : ℤ) : Prop := ∃ (k : ℤ), k * 37 = b - a
-- Now check it's an equivalence reln!
theorem cong_mod_refl : reflexive (cong_mod37) :=
begin
intro x,
-- to prove cong_mod37 x x we just observe that k = 0 will do.
use (0 : ℤ), -- this is k
simp,
end
theorem cong_mod_symm : symmetric (cong_mod37) :=
begin
intros a b H,
-- H : cond_mod37 a b
cases H with l Hl,
-- Hl : l * 37 = (b - a)
-- Goal is to find an integer k with k * 37 = a - b
use -l,
simp [Hl],
end
theorem cong_mod_trans : transitive (cong_mod37) :=
begin
intros a b c Hab Hbc,
cases Hab with l Hl,
cases Hbc with m Hm,
-- Hl : l * 37 = b - a, and Hm : m * 37 = c - b
-- Goal : ∃ k, k * 37 = c - a
use (l + m),
rw [add_mul, Hl, Hm], ring
end
-- so we've now seen a general technique for proving a ≈ b -- use (the k that works)
theorem cong_mod_equiv : equivalence (cong_mod37) :=
⟨cong_mod_refl, cong_mod_symm, cong_mod_trans⟩
-- Now let's put an equivalence relation on ℤ
definition Zmod37.setoid : setoid ℤ := { r := cong_mod37, iseqv := cong_mod_equiv }
-- Tell the type class inference system about this equivalence relation.
local attribute [instance] Zmod37.setoid
-- Now we can make the quotient.
definition Zmod37 := quotient (Zmod37.setoid)
-- now a little bit of basic interface
namespace Zmod37
-- Let's give a name to the reduction mod 37 map.
definition reduce_mod37 : ℤ → Zmod37 := quot.mk (cong_mod37)
-- Let's now set up a coercion.
definition coe_int_Zmod37 : has_coe ℤ (Zmod37) := ⟨reduce_mod37⟩
-- Let's tell Lean that given an integer, it can consider it as
-- an integer mod 37 automatically.
local attribute [instance] coe_int_Zmod37
-- Notation for 0 and 1
instance : has_zero (Zmod37) := ⟨reduce_mod37 0⟩
instance : has_one (Zmod37) := ⟨reduce_mod37 1⟩
-- Add basic facts about 0 and 1 to the set of simp facts
@[simp] theorem of_int_zero : (0 : (Zmod37)) = reduce_mod37 0 := rfl
@[simp] theorem of_int_one : (1 : (Zmod37)) = reduce_mod37 1 := rfl
-- now back to the maths
-- here's a useful lemma -- it's needed to prove addition is well-defined on the quotient.
-- Note the use of quotient.sound to get from Zmod37 back to Z
lemma congr_add (a₁ a₂ b₁ b₂ : ℤ) : a₁ ≈ b₁ → a₂ ≈ b₂ → ⟦a₁ + a₂⟧ = ⟦b₁ + b₂⟧ :=
begin
intros H1 H2,
cases H1 with m Hm, -- Hm : m * 37 = b₁ - a₁
cases H2 with n Hn, -- Hn : n * 37 = b₂ - a₂
-- goal is ⟦a₁ + a₂⟧ = ⟦b₁ + b₂⟧
apply quotient.sound,
-- goal now a₁ + a₂ ≈ b₁ + b₂, and we know how to do these.
use (m + n),
rw [add_mul, Hm, Hn], ring
end
-- That lemma above is *exactly* what we need to make sure addition is
-- well-defined on Zmod37, so let's do this now, using quotient.lift
-- note: stuff like "add" is used everywhere so it's best to protect.
protected definition add : Zmod37 → Zmod37 → Zmod37 :=
quotient.lift₂ (λ a b : ℤ, ⟦a + b⟧) (begin
show ∀ (a₁ a₂ b₁ b₂ : ℤ), a₁ ≈ b₁ → a₂ ≈ b₂ → ⟦a₁ + a₂⟧ = ⟦b₁ + b₂⟧,
-- that's what quotient.lift₂ reduces us to doing. But we did it already!
exact congr_add,
end)
-- Now here's the lemma we need for the definition of neg
-- I spelt out the proof for add, here's a quick term proof for neg.
lemma congr_neg (a b : ℤ) : a ≈ b → ⟦-a⟧ = ⟦-b⟧ :=
λ ⟨m, Hm⟩, quotient.sound ⟨-m, by simp [Hm]⟩
protected def neg : Zmod37 → Zmod37 := quotient.lift (λ a : ℤ, ⟦-a⟧) congr_neg
-- For multiplication I won't even bother proving the lemma, I'll just let ring do it
protected def mul : Zmod37 → Zmod37 → Zmod37 :=
quotient.lift₂ (λ a b : ℤ, ⟦a * b⟧) (λ a₁ a₂ b₁ b₂ ⟨m₁, H₁⟩ ⟨m₂, H₂⟩,
quotient.sound ⟨b₁ * m₂ + a₂ * m₁, by rw [add_mul, mul_assoc, mul_assoc, H₁, H₂]; ring⟩)
-- this adds notation to the quotient
instance : has_add (Zmod37) := ⟨Zmod37.add⟩
instance : has_neg (Zmod37) := ⟨Zmod37.neg⟩
instance : has_mul (Zmod37) := ⟨Zmod37.mul⟩
-- these are now very cool proofs:
@[simp] lemma coe_add {a b : ℤ} : (↑(a + b) : Zmod37) = ↑a + ↑b := rfl
@[simp] lemma coe_neg {a : ℤ} : (↑(-a) : Zmod37) = -↑a := rfl
@[simp] lemma coe_mul {a b : ℤ} : (↑(a * b) : Zmod37) = ↑a * ↑b := rfl
-- Note that the proof of these results is `rfl`. If we had defined addition
-- on the quotient in the standard way that mathematicians do,
-- by choosing representatives and then adding them,
-- then the proof would not be rfl. This is the power of quotient.lift.
-- Now here's how to use quotient.induction_on and quotient.sound
instance : add_comm_group (Zmod37) :=
{ add_comm_group .
zero := 0, -- because we already defined has_zero
add := (+), -- could also have written has_add.add or Zmod37.add
neg := has_neg.neg,
zero_add :=
λ abar, quotient.induction_on abar (begin
-- goal is ∀ (a : ℤ), 0 + ⟦a⟧ = ⟦a⟧ -- that's what quotient.induction_on does for us
intro a,
apply quotient.sound, -- works because 0 + ⟦a⟧ is by definition ⟦0⟧ + ⟦a⟧ which
-- is by definition ⟦0 + a⟧
-- goal is now 0 + a ≈ a
-- here's the way we used to do it.
use (0 : ℤ),
simp,
-- but there are tricks now, which I'll show you with add_zero and add_assoc.
end),
add_assoc := λ abar bbar cbar,quotient.induction_on₃ abar bbar cbar (λ a b c,
begin
-- goal now ⟦a⟧ + ⟦b⟧ + ⟦c⟧ = ⟦a⟧ + (⟦b⟧ + ⟦c⟧)
apply quotient.sound,
-- goal now a + b + c ≈ a + (b + c)
rw add_assoc, -- done :-) because after a rw a goal is closed if it's of the form x ≈ x,
-- as ≈ is known by Lean to be reflexive.
end),
add_zero := -- I will intrroduce some more sneaky stuff now now
-- add_zero for Zmod37 follows from add_zero on Z.
-- Note use of $ instead of the brackets
λ abar, quotient.induction_on abar $ λ a, quotient.sound $ by rw add_zero,
-- that's it! Term mode proof.
add_left_neg := -- super-slow method not even using quotient.induction_on
begin
intro abar,
cases (quot.exists_rep abar) with a Ha,
rw [←Ha],
apply quot.sound,
use (0 : ℤ),
simp,
end,
-- but really all proofs should just look something like this
add_comm := λ abar bbar, quotient.induction_on₂ abar bbar $
λ _ _,quotient.sound $ by rw add_comm,
-- the noise at the beginning is just the machine; all the work is done by the rewrite
}
-- Now let's just nail this using all the tricks in the book. All ring axioms on the quotient
-- follow from the corresponding axioms for Z.
instance : comm_ring (Zmod37) :=
{
mul := Zmod37.mul, -- could have written (*)
-- Now look how the proof of mul_assoc is just the same structure as add_comm above
-- but with three variables not two
mul_assoc := λ a b c, quotient.induction_on₃ a b c $ λ _ _ _, quotient.sound $
by rw mul_assoc,
one := 1,
one_mul := λ a, quotient.induction_on a $ λ _, quotient.sound $ by rw one_mul,
mul_one := λ a, quotient.induction_on a $ λ _, quotient.sound $ by rw mul_one,
left_distrib := λ a b c, quotient.induction_on₃ a b c $ λ _ _ _, quotient.sound $
by rw left_distrib,
right_distrib := λ a b c, quotient.induction_on₃ a b c $ λ _ _ _, quotient.sound $
by rw right_distrib,
mul_comm := λ a b, quotient.induction_on₂ a b $ λ _ _, quotient.sound $ by rw mul_comm,
..Zmod37.add_comm_group
}
end Zmod37
|
57b96836193393d1710766690d4c7fc8c551a145 | 9028d228ac200bbefe3a711342514dd4e4458bff | /src/data/zsqrtd/gaussian_int.lean | 8a0fbfd8a91dfc11b23ce403c9b9eef115e9cad8 | [
"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 | 12,707 | lean | /-
Copyright (c) 2019 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Chris Hughes
-/
import data.zsqrtd.basic
import data.complex.basic
import ring_theory.principal_ideal_domain
import number_theory.quadratic_reciprocity
/-!
# Gaussian integers
The Gaussian integers are complex integer, complex numbers whose real and imaginary parts are both
integers.
## Main definitions
The Euclidean domain structure on `ℤ[i]` is defined in this file.
The homomorphism `to_complex` into the complex numbers is also defined in this file.
## Main statements
`prime_iff_mod_four_eq_three_of_nat_prime`
A prime natural number is prime in `ℤ[i]` if and only if it is `3` mod `4`
## Notations
This file uses the local notation `ℤ[i]` for `gaussian_int`
## Implementation notes
Gaussian integers are implemented using the more general definition `zsqrtd`, the type of integers
adjoined a square root of `d`, in this case `-1`. The definition is reducible, so that properties
and definitions about `zsqrtd` can easily be used.
-/
open zsqrtd complex
@[reducible] def gaussian_int : Type := zsqrtd (-1)
local notation `ℤ[i]` := gaussian_int
namespace gaussian_int
instance : has_repr ℤ[i] := ⟨λ x, "⟨" ++ repr x.re ++ ", " ++ repr x.im ++ "⟩"⟩
instance : comm_ring ℤ[i] := zsqrtd.comm_ring
section
local attribute [-instance] complex.field -- Avoid making things noncomputable unnecessarily.
/-- The embedding of the Gaussian integers into the complex numbers, as a ring homomorphism. -/
def to_complex : ℤ[i] →+* ℂ :=
begin
refine_struct { to_fun := λ x : ℤ[i], (x.re + x.im * I : ℂ), .. };
intros; apply complex.ext; dsimp; norm_cast; simp; abel
end
end
instance : has_coe (ℤ[i]) ℂ := ⟨to_complex⟩
lemma to_complex_def (x : ℤ[i]) : (x : ℂ) = x.re + x.im * I := rfl
lemma to_complex_def' (x y : ℤ) : ((⟨x, y⟩ : ℤ[i]) : ℂ) = x + y * I := by simp [to_complex_def]
lemma to_complex_def₂ (x : ℤ[i]) : (x : ℂ) = ⟨x.re, x.im⟩ :=
by apply complex.ext; simp [to_complex_def]
@[simp] lemma to_real_re (x : ℤ[i]) : ((x.re : ℤ) : ℝ) = (x : ℂ).re := by simp [to_complex_def]
@[simp] lemma to_real_im (x : ℤ[i]) : ((x.im : ℤ) : ℝ) = (x : ℂ).im := by simp [to_complex_def]
@[simp] lemma to_complex_re (x y : ℤ) : ((⟨x, y⟩ : ℤ[i]) : ℂ).re = x := by simp [to_complex_def]
@[simp] lemma to_complex_im (x y : ℤ) : ((⟨x, y⟩ : ℤ[i]) : ℂ).im = y := by simp [to_complex_def]
@[simp] lemma to_complex_add (x y : ℤ[i]) : ((x + y : ℤ[i]) : ℂ) = x + y := to_complex.map_add _ _
@[simp] lemma to_complex_mul (x y : ℤ[i]) : ((x * y : ℤ[i]) : ℂ) = x * y := to_complex.map_mul _ _
@[simp] lemma to_complex_one : ((1 : ℤ[i]) : ℂ) = 1 := to_complex.map_one
@[simp] lemma to_complex_zero : ((0 : ℤ[i]) : ℂ) = 0 := to_complex.map_zero
@[simp] lemma to_complex_neg (x : ℤ[i]) : ((-x : ℤ[i]) : ℂ) = -x := to_complex.map_neg _
@[simp] lemma to_complex_sub (x y : ℤ[i]) : ((x - y : ℤ[i]) : ℂ) = x - y := to_complex.map_sub _ _
@[simp] lemma to_complex_inj {x y : ℤ[i]} : (x : ℂ) = y ↔ x = y :=
by cases x; cases y; simp [to_complex_def₂]
@[simp] lemma to_complex_eq_zero {x : ℤ[i]} : (x : ℂ) = 0 ↔ x = 0 :=
by rw [← to_complex_zero, to_complex_inj]
@[simp] lemma nat_cast_real_norm (x : ℤ[i]) : (x.norm : ℝ) = (x : ℂ).norm_sq :=
by rw [norm, norm_sq]; simp
@[simp] lemma nat_cast_complex_norm (x : ℤ[i]) : (x.norm : ℂ) = (x : ℂ).norm_sq :=
by cases x; rw [norm, norm_sq]; simp
lemma norm_nonneg (x : ℤ[i]) : 0 ≤ norm x := norm_nonneg trivial _
@[simp] lemma norm_eq_zero {x : ℤ[i]} : norm x = 0 ↔ x = 0 :=
by rw [← @int.cast_inj ℝ _ _ _]; simp
lemma norm_pos {x : ℤ[i]} : 0 < norm x ↔ x ≠ 0 :=
by rw [lt_iff_le_and_ne, ne.def, eq_comm, norm_eq_zero]; simp [norm_nonneg]
@[simp] lemma coe_nat_abs_norm (x : ℤ[i]) : (x.norm.nat_abs : ℤ) = x.norm :=
int.nat_abs_of_nonneg (norm_nonneg _)
@[simp] lemma nat_cast_nat_abs_norm {α : Type*} [ring α]
(x : ℤ[i]) : (x.norm.nat_abs : α) = x.norm :=
by rw [← int.cast_coe_nat, coe_nat_abs_norm]
lemma nat_abs_norm_eq (x : ℤ[i]) : x.norm.nat_abs =
x.re.nat_abs * x.re.nat_abs + x.im.nat_abs * x.im.nat_abs :=
int.coe_nat_inj $ begin simp, simp [norm] end
protected def div (x y : ℤ[i]) : ℤ[i] :=
let n := (rat.of_int (norm y))⁻¹ in let c := y.conj in
⟨round (rat.of_int (x * c).re * n : ℚ),
round (rat.of_int (x * c).im * n : ℚ)⟩
instance : has_div ℤ[i] := ⟨gaussian_int.div⟩
lemma div_def (x y : ℤ[i]) : x / y = ⟨round ((x * conj y).re / norm y : ℚ),
round ((x * conj y).im / norm y : ℚ)⟩ :=
show zsqrtd.mk _ _ = _, by simp [rat.of_int_eq_mk, rat.mk_eq_div, div_eq_mul_inv]
lemma to_complex_div_re (x y : ℤ[i]) : ((x / y : ℤ[i]) : ℂ).re = round ((x / y : ℂ).re) :=
by rw [div_def, ← @rat.cast_round ℝ _ _];
simp [-rat.cast_round, mul_assoc, div_eq_mul_inv, mul_add, add_mul]
lemma to_complex_div_im (x y : ℤ[i]) : ((x / y : ℤ[i]) : ℂ).im = round ((x / y : ℂ).im) :=
by rw [div_def, ← @rat.cast_round ℝ _ _, ← @rat.cast_round ℝ _ _];
simp [-rat.cast_round, mul_assoc, div_eq_mul_inv, mul_add, add_mul]
local notation `abs'` := _root_.abs
lemma norm_sq_le_norm_sq_of_re_le_of_im_le {x y : ℂ} (hre : abs' x.re ≤ abs' y.re)
(him : abs' x.im ≤ abs' y.im) : x.norm_sq ≤ y.norm_sq :=
by rw [norm_sq, norm_sq, ← _root_.abs_mul_self, _root_.abs_mul,
← _root_.abs_mul_self y.re, _root_.abs_mul y.re,
← _root_.abs_mul_self x.im, _root_.abs_mul x.im,
← _root_.abs_mul_self y.im, _root_.abs_mul y.im]; exact
(add_le_add (mul_self_le_mul_self (abs_nonneg _) hre)
(mul_self_le_mul_self (abs_nonneg _) him))
lemma norm_sq_div_sub_div_lt_one (x y : ℤ[i]) :
((x / y : ℂ) - ((x / y : ℤ[i]) : ℂ)).norm_sq < 1 :=
calc ((x / y : ℂ) - ((x / y : ℤ[i]) : ℂ)).norm_sq =
((x / y : ℂ).re - ((x / y : ℤ[i]) : ℂ).re +
((x / y : ℂ).im - ((x / y : ℤ[i]) : ℂ).im) * I : ℂ).norm_sq :
congr_arg _ $ by apply complex.ext; simp
... ≤ (1 / 2 + 1 / 2 * I).norm_sq :
have abs' (2 / (2 * 2) : ℝ) = 1 / 2, by rw _root_.abs_of_nonneg; norm_num,
norm_sq_le_norm_sq_of_re_le_of_im_le
(by rw [to_complex_div_re]; simp [norm_sq, this];
simpa using abs_sub_round (x / y : ℂ).re)
(by rw [to_complex_div_im]; simp [norm_sq, this];
simpa using abs_sub_round (x / y : ℂ).im)
... < 1 : by simp [norm_sq]; norm_num
protected def mod (x y : ℤ[i]) : ℤ[i] := x - y * (x / y)
instance : has_mod ℤ[i] := ⟨gaussian_int.mod⟩
lemma mod_def (x y : ℤ[i]) : x % y = x - y * (x / y) := rfl
lemma norm_mod_lt (x : ℤ[i]) {y : ℤ[i]} (hy : y ≠ 0) : (x % y).norm < y.norm :=
have (y : ℂ) ≠ 0, by rwa [ne.def, ← to_complex_zero, to_complex_inj],
(@int.cast_lt ℝ _ _ _).1 $
calc ↑(norm (x % y)) = (x - y * (x / y : ℤ[i]) : ℂ).norm_sq : by simp [mod_def]
... = (y : ℂ).norm_sq * (((x / y) - (x / y : ℤ[i])) : ℂ).norm_sq :
by rw [← norm_sq_mul, mul_sub, mul_div_cancel' _ this]
... < (y : ℂ).norm_sq * 1 : mul_lt_mul_of_pos_left (norm_sq_div_sub_div_lt_one _ _)
(norm_sq_pos.2 this)
... = norm y : by simp
lemma nat_abs_norm_mod_lt (x : ℤ[i]) {y : ℤ[i]} (hy : y ≠ 0) :
(x % y).norm.nat_abs < y.norm.nat_abs :=
int.coe_nat_lt.1 (by simp [-int.coe_nat_lt, norm_mod_lt x hy])
lemma norm_le_norm_mul_left (x : ℤ[i]) {y : ℤ[i]} (hy : y ≠ 0) :
(norm x).nat_abs ≤ (norm (x * y)).nat_abs :=
by rw [norm_mul, int.nat_abs_mul];
exact le_mul_of_one_le_right (nat.zero_le _)
(int.coe_nat_le.1 (by rw [coe_nat_abs_norm]; exact int.add_one_le_of_lt (norm_pos.2 hy)))
instance : nontrivial ℤ[i] :=
⟨⟨0, 1, dec_trivial⟩⟩
instance : euclidean_domain ℤ[i] :=
{ quotient := (/),
remainder := (%),
quotient_zero := λ _, by simp [div_def]; refl,
quotient_mul_add_remainder_eq := λ _ _, by simp [mod_def],
r := _,
r_well_founded := measure_wf (int.nat_abs ∘ norm),
remainder_lt := nat_abs_norm_mod_lt,
mul_left_not_lt := λ a b hb0, not_lt_of_ge $ norm_le_norm_mul_left a hb0,
.. gaussian_int.comm_ring,
.. gaussian_int.nontrivial }
open principal_ideal_ring
lemma mod_four_eq_three_of_nat_prime_of_prime (p : ℕ) [hp : fact p.prime] (hpi : prime (p : ℤ[i])) :
p % 4 = 3 :=
hp.eq_two_or_odd.elim
(λ hp2, absurd hpi (mt irreducible_iff_prime.2 $
λ ⟨hu, h⟩, begin
have := h ⟨1, 1⟩ ⟨1, -1⟩ (hp2.symm ▸ rfl),
rw [← norm_eq_one_iff, ← norm_eq_one_iff] at this,
exact absurd this dec_trivial
end))
(λ hp1, by_contradiction $ λ hp3 : p % 4 ≠ 3,
have hp41 : p % 4 = 1,
begin
rw [← nat.mod_mul_left_mod p 2 2, show 2 * 2 = 4, from rfl] at hp1,
have := nat.mod_lt p (show 0 < 4, from dec_trivial),
revert this hp3 hp1,
generalize : p % 4 = m, dec_trivial!,
end,
let ⟨k, hk⟩ := (zmod.exists_pow_two_eq_neg_one_iff_mod_four_ne_three p).2 $
by rw hp41; exact dec_trivial in
begin
obtain ⟨k, k_lt_p, rfl⟩ : ∃ (k' : ℕ) (h : k' < p), (k' : zmod p) = k,
{ refine ⟨k.val, k.val_lt, zmod.cast_val k⟩ },
have hpk : p ∣ k ^ 2 + 1,
by rw [← char_p.cast_eq_zero_iff (zmod p) p]; simp *,
have hkmul : (k ^ 2 + 1 : ℤ[i]) = ⟨k, 1⟩ * ⟨k, -1⟩ :=
by simp [pow_two, zsqrtd.ext],
have hpne1 : p ≠ 1, from (ne_of_lt (hp.one_lt)).symm,
have hkltp : 1 + k * k < p * p,
from calc 1 + k * k ≤ k + k * k :
add_le_add_right (nat.pos_of_ne_zero
(λ hk0, by clear_aux_decl; simp [*, pow_succ'] at *)) _
... = k * (k + 1) : by simp [add_comm, mul_add]
... < p * p : mul_lt_mul k_lt_p k_lt_p (nat.succ_pos _) (nat.zero_le _),
have hpk₁ : ¬ (p : ℤ[i]) ∣ ⟨k, -1⟩ :=
λ ⟨x, hx⟩, lt_irrefl (p * x : ℤ[i]).norm.nat_abs $
calc (norm (p * x : ℤ[i])).nat_abs = (norm ⟨k, -1⟩).nat_abs : by rw hx
... < (norm (p : ℤ[i])).nat_abs : by simpa [add_comm, norm] using hkltp
... ≤ (norm (p * x : ℤ[i])).nat_abs : norm_le_norm_mul_left _
(λ hx0, (show (-1 : ℤ) ≠ 0, from dec_trivial) $
by simpa [hx0] using congr_arg zsqrtd.im hx),
have hpk₂ : ¬ (p : ℤ[i]) ∣ ⟨k, 1⟩ :=
λ ⟨x, hx⟩, lt_irrefl (p * x : ℤ[i]).norm.nat_abs $
calc (norm (p * x : ℤ[i])).nat_abs = (norm ⟨k, 1⟩).nat_abs : by rw hx
... < (norm (p : ℤ[i])).nat_abs : by simpa [add_comm, norm] using hkltp
... ≤ (norm (p * x : ℤ[i])).nat_abs : norm_le_norm_mul_left _
(λ hx0, (show (1 : ℤ) ≠ 0, from dec_trivial) $
by simpa [hx0] using congr_arg zsqrtd.im hx),
have hpu : ¬ is_unit (p : ℤ[i]), from mt norm_eq_one_iff.2
(by rw [norm_nat_cast, int.nat_abs_mul, nat.mul_eq_one_iff];
exact λ h, (ne_of_lt hp.one_lt).symm h.1),
obtain ⟨y, hy⟩ := hpk,
have := hpi.2.2 ⟨k, 1⟩ ⟨k, -1⟩ ⟨y, by rw [← hkmul, ← nat.cast_mul p, ← hy]; simp⟩,
clear_aux_decl, tauto
end)
lemma sum_two_squares_of_nat_prime_of_not_irreducible (p : ℕ) [hp : fact p.prime]
(hpi : ¬irreducible (p : ℤ[i])) : ∃ a b, a^2 + b^2 = p :=
have hpu : ¬ is_unit (p : ℤ[i]), from mt norm_eq_one_iff.2 $
by rw [norm_nat_cast, int.nat_abs_mul, nat.mul_eq_one_iff];
exact λ h, (ne_of_lt hp.one_lt).symm h.1,
have hab : ∃ a b, (p : ℤ[i]) = a * b ∧ ¬ is_unit a ∧ ¬ is_unit b,
by simpa [irreducible, hpu, not_forall, not_or_distrib] using hpi,
let ⟨a, b, hpab, hau, hbu⟩ := hab in
have hnap : (norm a).nat_abs = p, from ((hp.mul_eq_prime_pow_two_iff
(mt norm_eq_one_iff.1 hau) (mt norm_eq_one_iff.1 hbu)).1 $
by rw [← int.coe_nat_inj', int.coe_nat_pow, pow_two,
← @norm_nat_cast (-1), hpab];
simp).1,
⟨a.re.nat_abs, a.im.nat_abs, by simpa [nat_abs_norm_eq, pow_two] using hnap⟩
lemma prime_of_nat_prime_of_mod_four_eq_three (p : ℕ) [hp : fact p.prime] (hp3 : p % 4 = 3) :
prime (p : ℤ[i]) :=
irreducible_iff_prime.1 $ classical.by_contradiction $ λ hpi,
let ⟨a, b, hab⟩ := sum_two_squares_of_nat_prime_of_not_irreducible p hpi in
have ∀ a b : zmod 4, a^2 + b^2 ≠ p, by erw [← zmod.cast_mod_nat 4 p, hp3]; exact dec_trivial,
this a b (hab ▸ by simp)
/-- A prime natural number is prime in `ℤ[i]` if and only if it is `3` mod `4` -/
lemma prime_iff_mod_four_eq_three_of_nat_prime (p : ℕ) [hp : fact p.prime] :
prime (p : ℤ[i]) ↔ p % 4 = 3 :=
⟨mod_four_eq_three_of_nat_prime_of_prime p, prime_of_nat_prime_of_mod_four_eq_three p⟩
end gaussian_int
|
272a199268d3fa9a13129bdf6a28400a4e53591e | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/algebraic_topology/alternating_face_map_complex.lean | 9c05ce8e2a5c8e1b6ab104aaef1ee766f4fddd2e | [
"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 | 12,317 | lean | /-
Copyright (c) 2021 Joël Riou. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Joël Riou, Adam Topaz, Johan Commelin
-/
import algebra.homology.additive
import algebraic_topology.Moore_complex
import algebra.big_operators.fin
import category_theory.preadditive.opposite
import tactic.equiv_rw
/-!
# The alternating face map complex of a simplicial object in a preadditive category
We construct the alternating face map complex, as a
functor `alternating_face_map_complex : simplicial_object C ⥤ chain_complex C ℕ`
for any preadditive category `C`. For any simplicial object `X` in `C`,
this is the homological complex `... → X_2 → X_1 → X_0`
where the differentials are alternating sums of faces.
The dual version `alternating_coface_map_complex : cosimplicial_object C ⥤ cochain_complex C ℕ`
is also constructed.
We also construct the natural transformation
`inclusion_of_Moore_complex : normalized_Moore_complex A ⟶ alternating_face_map_complex A`
when `A` is an abelian category.
## References
* https://stacks.math.columbia.edu/tag/0194
* https://ncatlab.org/nlab/show/Moore+complex
-/
open category_theory category_theory.limits category_theory.subobject
open category_theory.preadditive category_theory.category
open opposite
open_locale big_operators
open_locale simplicial
noncomputable theory
namespace algebraic_topology
namespace alternating_face_map_complex
/-!
## Construction of the alternating face map complex
-/
variables {C : Type*} [category C] [preadditive C]
variables (X : simplicial_object C)
variables (Y : simplicial_object C)
/-- The differential on the alternating face map complex is the alternate
sum of the face maps -/
@[simp]
def obj_d (n : ℕ) : X _[n+1] ⟶ X _[n] :=
∑ (i : fin (n+2)), (-1 : ℤ)^(i : ℕ) • X.δ i
/--
## The chain complex relation `d ≫ d`
-/
lemma d_squared (n : ℕ) : obj_d X (n+1) ≫ obj_d X n = 0 :=
begin
/- we start by expanding d ≫ d as a double sum -/
dsimp,
rw comp_sum,
let d_l := λ (j : fin (n+3)), (-1 : ℤ)^(j : ℕ) • X.δ j,
let d_r := λ (i : fin (n+2)), (-1 : ℤ)^(i : ℕ) • X.δ i,
rw [show (λ i , (∑ j : fin (n+3), d_l j) ≫ d_r i) =
(λ i, ∑ j : fin (n+3), (d_l j ≫ d_r i)), by { ext i, rw sum_comp, }],
rw ← finset.sum_product',
/- then, we decompose the index set P into a subet S and its complement Sᶜ -/
let P := fin (n+2) × fin (n+3),
let S := finset.univ.filter (λ (ij : P), (ij.2 : ℕ) ≤ (ij.1 : ℕ)),
let term := λ (ij : P), d_l ij.2 ≫ d_r ij.1,
erw [show ∑ (ij : P), term ij =
(∑ ij in S, term ij) + (∑ ij in Sᶜ, term ij), by rw finset.sum_add_sum_compl],
rw [← eq_neg_iff_add_eq_zero, ← finset.sum_neg_distrib],
/- we are reduced to showing that two sums are equal, and this is obtained
by constructing a bijection φ : S -> Sᶜ, which maps (i,j) to (j,i+1),
and by comparing the terms -/
let φ : Π (ij : P), ij ∈ S → P := λ ij hij,
(fin.cast_lt ij.2
(lt_of_le_of_lt (finset.mem_filter.mp hij).right (fin.is_lt ij.1)), ij.1.succ),
apply finset.sum_bij φ,
{ -- φ(S) is contained in Sᶜ
intros ij hij,
simp only [finset.mem_univ, finset.compl_filter, finset.mem_filter, true_and,
fin.coe_succ, fin.coe_cast_lt] at hij ⊢,
linarith, },
{ /- identification of corresponding terms in both sums -/
rintro ⟨i, j⟩ hij,
simp only [term, d_l, d_r, φ, comp_zsmul, zsmul_comp, ← neg_smul, ← mul_smul,
pow_add, neg_mul, mul_one, fin.coe_cast_lt,
fin.coe_succ, pow_one, mul_neg, neg_neg],
let jj : fin (n+2) := (φ (i,j) hij).1,
have ineq : jj ≤ i, { rw ← fin.coe_fin_le, simpa using hij, },
rw [category_theory.simplicial_object.δ_comp_δ X ineq, fin.cast_succ_cast_lt, mul_comm] },
{ -- φ : S → Sᶜ is injective
rintro ⟨i, j⟩ ⟨i', j'⟩ hij hij' h,
rw [prod.mk.inj_iff],
refine ⟨by simpa using congr_arg prod.snd h, _⟩,
have h1 := congr_arg fin.cast_succ (congr_arg prod.fst h),
simpa [fin.cast_succ_cast_lt] using h1 },
{ -- φ : S → Sᶜ is surjective
rintro ⟨i', j'⟩ hij',
simp only [true_and, finset.mem_univ, finset.compl_filter, not_le,
finset.mem_filter] at hij',
refine ⟨(j'.pred _, fin.cast_succ i'), _, _⟩,
{ intro H,
simpa only [H, nat.not_lt_zero, fin.coe_zero] using hij' },
{ simpa only [true_and, finset.mem_univ, fin.coe_cast_succ, fin.coe_pred,
finset.mem_filter] using nat.le_pred_of_lt hij', },
{ simp only [prod.mk.inj_iff, fin.succ_pred, fin.cast_lt_cast_succ],
split; refl }, },
end
/-!
## Construction of the alternating face map complex functor
-/
/-- The alternating face map complex, on objects -/
def obj : chain_complex C ℕ := chain_complex.of (λ n, X _[n]) (obj_d X) (d_squared X)
@[simp]
lemma obj_X (X : simplicial_object C) (n : ℕ) :
(alternating_face_map_complex.obj X).X n = X _[n] := rfl
@[simp]
lemma obj_d_eq (X : simplicial_object C) (n : ℕ) :
(alternating_face_map_complex.obj X).d (n+1) n =
∑ (i : fin (n+2)), (-1 : ℤ)^(i : ℕ) • X.δ i :=
by apply chain_complex.of_d
variables {X} {Y}
/-- The alternating face map complex, on morphisms -/
def map (f : X ⟶ Y) : obj X ⟶ obj Y :=
chain_complex.of_hom _ _ _ _ _ _
(λ n, f.app (op [n]))
(λ n,
begin
dsimp,
rw [comp_sum, sum_comp],
apply finset.sum_congr rfl (λ x h, _),
rw [comp_zsmul, zsmul_comp],
congr' 1,
symmetry,
apply f.naturality,
end)
@[simp]
lemma map_f (f : X ⟶ Y) (n : ℕ) : (map f).f n = f.app (op [n]) := rfl
end alternating_face_map_complex
variables (C : Type*) [category C] [preadditive C]
/-- The alternating face map complex, as a functor -/
def alternating_face_map_complex : simplicial_object C ⥤ chain_complex C ℕ :=
{ obj := alternating_face_map_complex.obj,
map := λ X Y f, alternating_face_map_complex.map f }
variable {C}
@[simp]
lemma alternating_face_map_complex_obj_X (X : simplicial_object C) (n : ℕ) :
((alternating_face_map_complex C).obj X).X n = X _[n] := rfl
@[simp]
lemma alternating_face_map_complex_obj_d (X : simplicial_object C) (n : ℕ) :
((alternating_face_map_complex C).obj X).d (n+1) n =
alternating_face_map_complex.obj_d X n :=
by apply chain_complex.of_d
@[simp]
lemma alternating_face_map_complex_map_f {X Y : simplicial_object C} (f : X ⟶ Y) (n : ℕ) :
((alternating_face_map_complex C).map f).f n = f.app (op [n]) := rfl
lemma map_alternating_face_map_complex {D : Type*} [category D] [preadditive D]
(F : C ⥤ D) [F.additive] :
alternating_face_map_complex C ⋙ F.map_homological_complex _ =
(simplicial_object.whiskering C D).obj F ⋙ alternating_face_map_complex D :=
begin
apply category_theory.functor.ext,
{ intros X Y f,
ext n,
simp only [functor.comp_map, homological_complex.comp_f,
alternating_face_map_complex_map_f, functor.map_homological_complex_map_f,
homological_complex.eq_to_hom_f, eq_to_hom_refl, comp_id, id_comp,
simplicial_object.whiskering_obj_map_app], },
{ intro X,
apply homological_complex.ext,
{ rintros i j (rfl : j + 1 = i),
dsimp only [functor.comp_obj],
simpa only [functor.map_homological_complex_obj_d, alternating_face_map_complex_obj_d,
eq_to_hom_refl, id_comp, comp_id, alternating_face_map_complex.obj_d,
functor.map_sum, functor.map_zsmul], },
{ ext n,
refl, }, },
end
namespace alternating_face_map_complex
/-- The natural transformation which gives the augmentation of the alternating face map
complex attached to an augmented simplicial object. -/
@[simps]
def ε [limits.has_zero_object C] :
simplicial_object.augmented.drop ⋙ algebraic_topology.alternating_face_map_complex C ⟶
simplicial_object.augmented.point ⋙ chain_complex.single₀ C :=
{ app := λ X, begin
equiv_rw chain_complex.to_single₀_equiv _ _,
refine ⟨X.hom.app (op [0]), _⟩,
dsimp,
simp only [alternating_face_map_complex_obj_d, obj_d, fin.sum_univ_two,
fin.coe_zero, pow_zero, one_zsmul, fin.coe_one, pow_one, neg_smul, add_comp,
simplicial_object.δ_naturality, neg_comp],
apply add_right_neg,
end,
naturality' := λ X Y f, by { ext, exact congr_app f.w _, }, }
end alternating_face_map_complex
/-!
## Construction of the natural inclusion of the normalized Moore complex
-/
variables {A : Type*} [category A] [abelian A]
/-- The inclusion map of the Moore complex in the alternating face map complex -/
def inclusion_of_Moore_complex_map (X : simplicial_object A) :
(normalized_Moore_complex A).obj X ⟶ (alternating_face_map_complex A).obj X :=
chain_complex.of_hom _ _ _ _ _ _
(λ n, (normalized_Moore_complex.obj_X X n).arrow)
(λ n,
begin
/- we have to show the compatibility of the differentials on the alternating
face map complex with those defined on the normalized Moore complex:
we first get rid of the terms of the alternating sum that are obviously
zero on the normalized_Moore_complex -/
simp only [alternating_face_map_complex.obj_d],
rw comp_sum,
let t := λ (j : fin (n+2)), (normalized_Moore_complex.obj_X X (n+1)).arrow ≫
((-1 : ℤ)^(j : ℕ) • X.δ j),
have def_t : (∀ j : fin (n+2), t j = (normalized_Moore_complex.obj_X X (n+1)).arrow ≫
((-1 : ℤ)^(j : ℕ) • X.δ j)) := by { intro j, refl, },
rw [fin.sum_univ_succ t],
have null : ∀ j : fin (n+1), t j.succ = 0,
{ intro j,
rw [def_t, comp_zsmul, ← zsmul_zero ((-1 : ℤ)^(j.succ : ℕ))],
apply congr_arg,
rw normalized_Moore_complex.obj_X,
rw ← factor_thru_arrow _ _
(finset_inf_arrow_factors finset.univ _ j (by simp only [finset.mem_univ])),
slice_lhs 2 3 { rw kernel_subobject_arrow_comp (X.δ j.succ), },
simp only [comp_zero], },
rw [fintype.sum_eq_zero _ null],
simp only [add_zero],
/- finally, we study the remaining term which is induced by X.δ 0 -/
let eq := def_t 0,
rw [show (-1 : ℤ)^((0 : fin (n+2)) : ℕ) = 1, by ring] at eq,
rw one_smul at eq,
rw eq,
cases n; dsimp; simp,
end)
@[simp]
lemma inclusion_of_Moore_complex_map_f (X : simplicial_object A) (n : ℕ) :
(inclusion_of_Moore_complex_map X).f n = (normalized_Moore_complex.obj_X X n).arrow :=
chain_complex.of_hom_f _ _ _ _ _ _ _ _ n
variables (A)
/-- The inclusion map of the Moore complex in the alternating face map complex,
as a natural transformation -/
@[simps]
def inclusion_of_Moore_complex :
(normalized_Moore_complex A) ⟶ (alternating_face_map_complex A) :=
{ app := inclusion_of_Moore_complex_map, }
namespace alternating_coface_map_complex
variables (X Y : cosimplicial_object C)
/-- The differential on the alternating coface map complex is the alternate
sum of the coface maps -/
@[simp]
def obj_d (n : ℕ) : X.obj [n] ⟶ X.obj [n+1] :=
∑ (i : fin (n+2)), (-1 : ℤ)^(i : ℕ) • X.δ i
lemma d_eq_unop_d (n : ℕ) :
obj_d X n = (alternating_face_map_complex.obj_d
((cosimplicial_simplicial_equiv C).functor.obj (op X)) n).unop :=
by simpa only [obj_d, alternating_face_map_complex.obj_d, unop_sum, unop_zsmul]
lemma d_squared (n : ℕ) : obj_d X n ≫ obj_d X (n+1) = 0 :=
by simp only [d_eq_unop_d, ← unop_comp, alternating_face_map_complex.d_squared, unop_zero]
/-- The alternating coface map complex, on objects -/
def obj : cochain_complex C ℕ := cochain_complex.of (λ n, X.obj [n]) (obj_d X) (d_squared X)
variables {X} {Y}
/-- The alternating face map complex, on morphisms -/
@[simp]
def map (f : X ⟶ Y) : obj X ⟶ obj Y :=
cochain_complex.of_hom _ _ _ _ _ _
(λ n, f.app [n])
(λ n,
begin
dsimp,
rw [comp_sum, sum_comp],
apply finset.sum_congr rfl (λ x h, _),
rw [comp_zsmul, zsmul_comp],
congr' 1,
symmetry,
apply f.naturality,
end)
end alternating_coface_map_complex
variable (C)
/-- The alternating coface map complex, as a functor -/
@[simps]
def alternating_coface_map_complex : cosimplicial_object C ⥤ cochain_complex C ℕ :=
{ obj := alternating_coface_map_complex.obj,
map := λ X Y f, alternating_coface_map_complex.map f }
end algebraic_topology
|
96a07c8eaee3fa4dbb7caacb4539657f0361236a | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/category_theory/monoidal/internal/Module.lean | a8dcbc32b37acfa10ab52144b96b85f0647b4c1a | [
"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 | 6,062 | 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.category.Module.monoidal.basic
import algebra.category.Algebra.basic
import category_theory.monoidal.Mon_
/-!
# `Mon_ (Module R) ≌ Algebra R`
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
The category of internal monoid objects in `Module R`
is equivalent to the category of "native" bundled `R`-algebras.
Moreover, this equivalence is compatible with the forgetful functors to `Module R`.
-/
universes v u
open category_theory
open linear_map
open_locale tensor_product
local attribute [ext] tensor_product.ext
namespace Module
variables {R : Type u} [comm_ring R]
namespace Mon_Module_equivalence_Algebra
@[simps]
instance (A : Mon_ (Module.{u} R)) : ring A.X :=
{ one := A.one (1 : R),
mul := λ x y, A.mul (x ⊗ₜ y),
one_mul := λ x, by { convert linear_map.congr_fun A.one_mul ((1 : R) ⊗ₜ x), simp, },
mul_one := λ x, by { convert linear_map.congr_fun A.mul_one (x ⊗ₜ (1 : R)), simp, },
mul_assoc := λ x y z, by convert linear_map.congr_fun A.mul_assoc ((x ⊗ₜ y) ⊗ₜ z),
left_distrib := λ x y z,
begin
convert A.mul.map_add (x ⊗ₜ y) (x ⊗ₜ z),
rw ←tensor_product.tmul_add,
refl,
end,
right_distrib := λ x y z,
begin
convert A.mul.map_add (x ⊗ₜ z) (y ⊗ₜ z),
rw ←tensor_product.add_tmul,
refl,
end,
..(by apply_instance : add_comm_group A.X) }
instance (A : Mon_ (Module.{u} R)) : algebra R A.X :=
{ map_zero' := A.one.map_zero,
map_one' := rfl,
map_mul' := λ x y,
begin
have h := linear_map.congr_fun A.one_mul.symm (x ⊗ₜ (A.one y)),
rwa [monoidal_category.left_unitor_hom_apply, ←A.one.map_smul] at h,
end,
commutes' := λ r a,
begin dsimp,
have h₁ := linear_map.congr_fun A.one_mul (r ⊗ₜ a),
have h₂ := linear_map.congr_fun A.mul_one (a ⊗ₜ r),
exact h₁.trans h₂.symm,
end,
smul_def' := λ r a, (linear_map.congr_fun A.one_mul (r ⊗ₜ a)).symm,
..A.one }
@[simp] lemma algebra_map (A : Mon_ (Module.{u} R)) (r : R) : algebra_map R A.X r = A.one r := rfl
/--
Converting a monoid object in `Module R` to a bundled algebra.
-/
@[simps]
def functor : Mon_ (Module.{u} R) ⥤ Algebra R :=
{ obj := λ A, Algebra.of R A.X,
map := λ A B f,
{ to_fun := f.hom,
map_one' := linear_map.congr_fun f.one_hom (1 : R),
map_mul' := λ x y, linear_map.congr_fun f.mul_hom (x ⊗ₜ y),
commutes' := λ r, linear_map.congr_fun f.one_hom r,
..(f.hom.to_add_monoid_hom) }, }.
/--
Converting a bundled algebra to a monoid object in `Module R`.
-/
@[simps]
def inverse_obj (A : Algebra.{u} R) : Mon_ (Module.{u} R) :=
{ X := Module.of R A,
one := algebra.linear_map R A,
mul := linear_map.mul' R A,
one_mul' :=
begin
ext x,
dsimp only [Algebra.id_apply, tensor_product.mk_apply,
algebra.linear_map_apply, linear_map.compr₂_apply, function.comp_app,
ring_hom.map_one, Module.monoidal_category.hom_apply, Algebra.coe_comp,
Module.monoidal_category.left_unitor_hom_apply],
rw [linear_map.mul'_apply, monoidal_category.left_unitor_hom_apply, ← algebra.smul_def]
end,
mul_one' :=
begin
ext x,
dsimp only [Algebra.id_apply, tensor_product.mk_apply, algebra.linear_map_apply,
linear_map.compr₂_apply, function.comp_app, Module.monoidal_category.hom_apply,
Algebra.coe_comp],
rw [linear_map.mul'_apply, Module.monoidal_category.right_unitor_hom_apply,
← algebra.commutes, ← algebra.smul_def]
end,
mul_assoc' :=
begin
ext x y z,
dsimp only [Algebra.id_apply, tensor_product.mk_apply, linear_map.compr₂_apply,
function.comp_app, Module.monoidal_category.hom_apply,
Algebra.coe_comp, monoidal_category.associator_hom_apply],
simp only [linear_map.mul'_apply, mul_assoc]
end }
/--
Converting a bundled algebra to a monoid object in `Module R`.
-/
@[simps]
def inverse : Algebra.{u} R ⥤ Mon_ (Module.{u} R) :=
{ obj := inverse_obj,
map := λ A B f,
{ hom := f.to_linear_map,
one_hom' := linear_map.ext f.commutes,
mul_hom' := tensor_product.ext $ linear_map.ext₂ $ map_mul f, } }
end Mon_Module_equivalence_Algebra
open Mon_Module_equivalence_Algebra
/--
The category of internal monoid objects in `Module R`
is equivalent to the category of "native" bundled `R`-algebras.
-/
def Mon_Module_equivalence_Algebra : Mon_ (Module.{u} R) ≌ Algebra R :=
{ functor := functor,
inverse := inverse,
unit_iso := nat_iso.of_components
(λ A,
{ hom := { hom := { to_fun := id, map_add' := λ x y, rfl, map_smul' := λ r a, rfl, },
mul_hom' := by { ext, dsimp at *, refl } },
inv := { hom := { to_fun := id, map_add' := λ x y, rfl, map_smul' := λ r a, rfl, },
mul_hom' := by { ext, dsimp at *, refl } } })
(by tidy),
counit_iso := nat_iso.of_components (λ A,
{ hom :=
{ to_fun := id,
map_zero' := rfl,
map_add' := λ x y, rfl,
map_one' := (algebra_map R A).map_one,
map_mul' := λ x y, (@linear_map.mul'_apply R _ _ _ _ _ _ x y),
commutes' := λ r, rfl, },
inv :=
{ to_fun := id,
map_zero' := rfl,
map_add' := λ x y, rfl,
map_one' := (algebra_map R A).map_one.symm,
map_mul' := λ x y, (@linear_map.mul'_apply R _ _ _ _ _ _ x y).symm,
commutes' := λ r, rfl } }) (by { intros, refl }), }.
/--
The equivalence `Mon_ (Module R) ≌ Algebra R`
is naturally compatible with the forgetful functors to `Module R`.
-/
def Mon_Module_equivalence_Algebra_forget :
Mon_Module_equivalence_Algebra.functor ⋙ forget₂ (Algebra.{u} R) (Module.{u} R) ≅
Mon_.forget (Module.{u} R):=
nat_iso.of_components (λ A,
{ hom :=
{ to_fun := id,
map_add' := λ x y, rfl,
map_smul' := λ c x, rfl },
inv :=
{ to_fun := id,
map_add' := λ x y, rfl,
map_smul' := λ c x, rfl }, }) (by tidy)
end Module
|
f25a8973eb90cc7a29750784c0c175e3182f6bf0 | 35b83be3126daae10419b573c55e1fed009d3ae8 | /_target/deps/mathlib/data/complex/exponential.lean | 2503f9e069a0192811eaafd3d36f7319b14a21b2 | [] | 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 | 46,502 | lean | /-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes
-/
import algebra.archimedean
import data.nat.choose data.complex.basic
import tactic.linarith
local attribute [instance, priority 0] classical.prop_decidable
local notation `abs'` := _root_.abs
open is_absolute_value
section
open real is_absolute_value finset
lemma geo_sum_eq {α : Type*} [field α] {x : α} : ∀ (n : ℕ) (hx1 : x ≠ 1),
(range n).sum (λ m, x ^ m) = (1 - x ^ n) / (1 - x)
| 0 hx1 := by simp
| (n+1) hx1 := have 1 - x ≠ 0 := mt sub_eq_zero_iff_eq.1 hx1.symm,
by rw [sum_range_succ, ← mul_div_cancel (x ^ n) this, geo_sum_eq n hx1, ← add_div, _root_.pow_succ];
simp [mul_add, add_mul, mul_comm]
lemma geo_sum_inv_eq {α : Type*} [discrete_field α] {x : α} (n : ℕ) (hx1 : x ≠ 1) (hx0 : x ≠ 0) :
(range n).sum (λ m, x⁻¹ ^ m) = (x - x * x⁻¹ ^ n) / (x - 1) :=
have hx1' : x⁻¹ ≠ 1, from λ h, by rw [← @inv_inv' _ _ x, h] at hx1; simpa using hx1,
have h1x' : 1 - x⁻¹ ≠ 0, from sub_ne_zero.2 hx1'.symm,
have h1x : x - 1 ≠ 0, from sub_ne_zero.2 hx1,
by rw [geo_sum_eq _ hx1', div_eq_div_iff h1x' h1x];
simp [mul_add, add_mul, mul_inv_cancel hx0, mul_comm x, mul_left_comm x,
mul_assoc, inv_mul_cancel hx0]
lemma forall_ge_le_of_forall_le_succ {α : Type*} [preorder α] (f : ℕ → α) {m : ℕ}
(h : ∀ n ≥ m, f n.succ ≤ f n) : ∀ {l}, ∀ k ≥ m, k ≤ l → f l ≤ f k :=
begin
assume l k hkm hkl,
generalize hp : l - k = p,
have : l = k + p := add_comm p k ▸ (nat.sub_eq_iff_eq_add hkl).1 hp,
subst this,
clear hkl hp,
induction p with p ih,
{ simp },
{ exact le_trans (h _ (le_trans hkm (nat.le_add_right _ _))) ih }
end
variables {α : Type*} {β : Type*} [ring β]
[discrete_linear_ordered_field α] [archimedean α] {abv : β → α} [is_absolute_value abv]
lemma is_cau_of_decreasing_bounded (f : ℕ → α) {a : α} {m : ℕ} (ham : ∀ n ≥ m, abs (f n) ≤ a)
(hnm : ∀ n ≥ m, f n.succ ≤ f n) : is_cau_seq abs f :=
λ ε ε0,
let ⟨k, hk⟩ := archimedean.arch a ε0 in
have h : ∃ l, ∀ n ≥ m, a - add_monoid.smul l ε < f n :=
⟨k + k + 1, λ n hnm, lt_of_lt_of_le
(show a - add_monoid.smul (k + (k + 1)) ε < -abs (f n),
from lt_neg.1 $ lt_of_le_of_lt (ham n hnm) (begin
rw [neg_sub, lt_sub_iff_add_lt, add_monoid.add_smul],
exact add_lt_add_of_le_of_lt hk (lt_of_le_of_lt hk
(lt_add_of_pos_left _ ε0)),
end))
(neg_le.2 $ (abs_neg (f n)) ▸ le_abs_self _)⟩,
let l := nat.find h in
have hl : ∀ (n : ℕ), n ≥ m → f n > a - add_monoid.smul l ε := nat.find_spec h,
have hl0 : l ≠ 0 := λ hl0, not_lt_of_ge (ham m (le_refl _))
(lt_of_lt_of_le (by have := hl m (le_refl m); simpa [hl0] using this) (le_abs_self (f m))),
begin
cases classical.not_forall.1
(nat.find_min h (nat.pred_lt hl0)) with i hi,
rw [not_imp, not_lt] at hi,
existsi i,
assume j hj,
have hfij : f j ≤ f i := forall_ge_le_of_forall_le_succ f hnm _ hi.1 hj,
rw [abs_of_nonpos (sub_nonpos.2 hfij), neg_sub, sub_lt_iff_lt_add'],
exact calc f i ≤ a - add_monoid.smul (nat.pred l) ε : hi.2
... = a - add_monoid.smul l ε + ε :
by conv {to_rhs, rw [← nat.succ_pred_eq_of_pos (nat.pos_of_ne_zero hl0), succ_smul',
sub_add, add_sub_cancel] }
... < f j + ε : add_lt_add_right (hl j (le_trans hi.1 hj)) _
end
lemma is_cau_of_mono_bounded (f : ℕ → α) {a : α} {m : ℕ} (ham : ∀ n ≥ m, abs (f n) ≤ a)
(hnm : ∀ n ≥ m, f n ≤ f n.succ) : is_cau_seq abs f :=
begin
refine @eq.rec_on (ℕ → α) _ (is_cau_seq abs) _ _
(-⟨_, @is_cau_of_decreasing_bounded _ _ _ (λ n, -f n) a m (by simpa) (by simpa)⟩ : cau_seq α abs).2,
ext,
exact neg_neg _
end
lemma is_cau_series_of_abv_le_cau {f : ℕ → β} {g : ℕ → α} (n : ℕ) : (∀ m, n ≤ m → abv (f m) ≤ g m) →
is_cau_seq abs (λ n, (range n).sum g) → is_cau_seq abv (λ n, (range n).sum f) :=
begin
assume hm hg ε ε0,
cases hg (ε / 2) (div_pos ε0 (by norm_num)) with i hi,
existsi max n i,
assume j ji,
have hi₁ := hi j (le_trans (le_max_right n i) ji),
have hi₂ := hi (max n i) (le_max_right n i),
have sub_le := abs_sub_le ((range j).sum g) ((range i).sum g) ((range (max n i)).sum g),
have := add_lt_add hi₁ hi₂,
rw [abs_sub ((range (max n i)).sum g), add_halves ε] at this,
refine lt_of_le_of_lt (le_trans (le_trans _ (le_abs_self _)) sub_le) this,
generalize hk : j - max n i = k,
clear this hi₂ hi₁ hi ε0 ε hg sub_le,
rw nat.sub_eq_iff_eq_add ji at hk,
rw hk,
clear hk ji j,
induction k with k' hi,
{ simp [abv_zero abv] },
{ dsimp at *,
rw [nat.succ_add, sum_range_succ, sum_range_succ, add_assoc, add_assoc],
refine le_trans (abv_add _ _ _) _,
exact add_le_add (hm _ (le_add_of_nonneg_of_le (nat.zero_le _) (le_max_left _ _))) hi },
end
lemma is_cau_series_of_abv_cau {f : ℕ → β} : is_cau_seq abs (λ m, (range m).sum (λ n, abv (f n))) →
is_cau_seq abv (λ m, (range m).sum f) :=
is_cau_series_of_abv_le_cau 0 (λ n h, le_refl _)
lemma is_cau_geo_series {β : Type*} [field β] {abv : β → α} [is_absolute_value abv]
(x : β) (hx1 : abv x < 1) : is_cau_seq abv (λ n, (range n).sum (λ m, x ^ m)) :=
have hx1' : abv x ≠ 1 := λ h, by simpa [h, lt_irrefl] using hx1,
is_cau_series_of_abv_cau
begin
simp only [abv_pow abv, geo_sum_eq _ hx1'] {eta := ff},
refine @is_cau_of_mono_bounded _ _ _ _ ((1 : α) / (1 - abv x)) 0 _ _,
{ assume n hn,
rw abs_of_nonneg ,
refine div_le_div_of_le_of_pos (sub_le_self _ (abv_pow abv x n ▸ abv_nonneg _ _))
(sub_pos.2 hx1),
refine div_nonneg (sub_nonneg.2 _) (sub_pos.2 hx1),
clear hn,
induction n with n ih,
{ simp },
{ rw [_root_.pow_succ, ← one_mul (1 : α)],
refine mul_le_mul (le_of_lt hx1) ih (abv_pow abv x n ▸ abv_nonneg _ _) (by norm_num) } },
{ assume n hn,
refine div_le_div_of_le_of_pos (sub_le_sub_left _ _) (sub_pos.2 hx1),
rw [← one_mul (_ ^ n), _root_.pow_succ],
exact mul_le_mul_of_nonneg_right (le_of_lt hx1) (pow_nonneg (abv_nonneg _ _) _) }
end
lemma is_cau_geo_series_const (a : α) {x : α} (hx1 : abs x < 1) : is_cau_seq abs (λ m, (range m).sum (λ n, a * x ^ n)) :=
have is_cau_seq abs (λ m, a * (range m).sum (λ n, x ^ n)) := (cau_seq.const abs a * ⟨_, is_cau_geo_series x hx1⟩).2,
by simpa only [mul_sum]
lemma series_ratio_test {f : ℕ → β} (n : ℕ) (r : α)
(hr0 : 0 ≤ r) (hr1 : r < 1) (h : ∀ m, n ≤ m → abv (f m.succ) ≤ r * abv (f m)) :
is_cau_seq abv (λ m, (range m).sum f) :=
have har1 : abs r < 1, by rwa abs_of_nonneg hr0,
begin
refine is_cau_series_of_abv_le_cau n.succ _ (is_cau_geo_series_const (abv (f n.succ) * r⁻¹ ^ n.succ) har1),
assume m hmn,
cases classical.em (r = 0) with r_zero r_ne_zero,
{ have m_pos := lt_of_lt_of_le (nat.succ_pos n) hmn,
have := h m.pred (nat.le_of_succ_le_succ (by rwa [nat.succ_pred_eq_of_pos m_pos])),
simpa [r_zero, nat.succ_pred_eq_of_pos m_pos, pow_succ] },
generalize hk : m - n.succ = k,
have r_pos : 0 < r := lt_of_le_of_ne hr0 (ne.symm r_ne_zero),
replace hk : m = k + n.succ := (nat.sub_eq_iff_eq_add hmn).1 hk,
induction k with k ih generalizing m n,
{ rw [hk, zero_add, mul_right_comm, ← pow_inv _ _ r_ne_zero, ← div_eq_mul_inv, mul_div_cancel],
exact (ne_of_lt (pow_pos r_pos _)).symm },
{ have kn : k + n.succ ≥ n.succ, by rw ← zero_add n.succ; exact add_le_add (zero_le _) (by simp),
rw [hk, nat.succ_add, pow_succ' r, ← mul_assoc],
exact le_trans (by rw mul_comm; exact h _ (nat.le_of_succ_le kn))
(mul_le_mul_of_nonneg_right (ih (k + n.succ) n h kn rfl) hr0) }
end
lemma sum_range_diag_flip {α : Type*} [add_comm_monoid α] (n : ℕ) (f : ℕ → ℕ → α) :
(range n).sum (λ m, (range (m + 1)).sum (λ k, f k (m - k))) =
(range n).sum (λ m, (range (n - m)).sum (f m)) :=
have h₁ : ((range n).sigma (range ∘ nat.succ)).sum
(λ (a : Σ m, ℕ), f (a.2) (a.1 - a.2)) =
(range n).sum (λ m, (range (m + 1)).sum
(λ k, f k (m - k))) := sum_sigma,
have h₂ : ((range n).sigma (λ m, range (n - m))).sum (λ a : Σ (m : ℕ), ℕ, f (a.1) (a.2)) =
(range n).sum (λ m, sum (range (n - m)) (f m)) := sum_sigma,
h₁ ▸ h₂ ▸ sum_bij
(λ a _, ⟨a.2, a.1 - a.2⟩)
(λ a ha, have h₁ : a.1 < n := mem_range.1 (mem_sigma.1 ha).1,
have h₂ : a.2 < nat.succ a.1 := mem_range.1 (mem_sigma.1 ha).2,
mem_sigma.2 ⟨mem_range.2 (lt_of_lt_of_le h₂ h₁),
mem_range.2 ((nat.sub_lt_sub_right_iff (nat.le_of_lt_succ h₂)).2 h₁)⟩)
(λ _ _, rfl)
(λ ⟨a₁, a₂⟩ ⟨b₁, b₂⟩ ha hb h,
have ha : a₁ < n ∧ a₂ ≤ a₁ :=
⟨mem_range.1 (mem_sigma.1 ha).1, nat.le_of_lt_succ (mem_range.1 (mem_sigma.1 ha).2)⟩,
have hb : b₁ < n ∧ b₂ ≤ b₁ :=
⟨mem_range.1 (mem_sigma.1 hb).1, nat.le_of_lt_succ (mem_range.1 (mem_sigma.1 hb).2)⟩,
have h : a₂ = b₂ ∧ _ := sigma.mk.inj h,
have h' : a₁ = b₁ - b₂ + a₂ := (nat.sub_eq_iff_eq_add ha.2).1 (eq_of_heq h.2),
sigma.mk.inj_iff.2
⟨nat.sub_add_cancel hb.2 ▸ h'.symm ▸ h.1 ▸ rfl,
(heq_of_eq h.1)⟩)
(λ ⟨a₁, a₂⟩ ha,
have ha : a₁ < n ∧ a₂ < n - a₁ :=
⟨mem_range.1 (mem_sigma.1 ha).1, (mem_range.1 (mem_sigma.1 ha).2)⟩,
⟨⟨a₂ + a₁, a₁⟩, ⟨mem_sigma.2 ⟨mem_range.2 (nat.lt_sub_right_iff_add_lt.1 ha.2),
mem_range.2 (nat.lt_succ_of_le (nat.le_add_left _ _))⟩,
sigma.mk.inj_iff.2 ⟨rfl, heq_of_eq (nat.add_sub_cancel _ _).symm⟩⟩⟩)
lemma abv_sum_le_sum_abv {γ : Type*} (f : γ → β) (s : finset γ) :
abv (s.sum f) ≤ s.sum (abv ∘ f) :=
by haveI := classical.dec_eq γ; exact
finset.induction_on s (by simp [abv_zero abv])
(λ a s has ih, by rw [sum_insert has, sum_insert has];
exact le_trans (abv_add abv _ _) (add_le_add_left ih _))
lemma sum_range_sub_sum_range {α : Type*} [add_comm_group α] {f : ℕ → α}
{n m : ℕ} (hnm : n ≤ m) : (range m).sum f - (range n).sum f =
((range m).filter (λ k, n ≤ k)).sum f :=
begin
rw [← sum_sdiff (@filter_subset _ (λ k, n ≤ k) _ (range m)),
sub_eq_iff_eq_add, ← eq_sub_iff_add_eq, add_sub_cancel'],
refine finset.sum_congr
(finset.ext.2 $ λ a, ⟨λ h, by simp at *; finish,
λ h, have ham : a < m := lt_of_lt_of_le (mem_range.1 h) hnm,
by simp * at *⟩)
(λ _ _, rfl),
end
lemma cauchy_product {a b : ℕ → β}
(ha : is_cau_seq abs (λ m, (range m).sum (λ n, abv (a n))))
(hb : is_cau_seq abv (λ m, (range m).sum b)) (ε : α) (ε0 : 0 < ε) :
∃ i : ℕ, ∀ j ≥ i, abv ((range j).sum a * (range j).sum b -
(range j).sum (λ n, (range (n + 1)).sum (λ m, a m * b (n - m)))) < ε :=
let ⟨Q, hQ⟩ := cau_seq.bounded ⟨_, hb⟩ in
let ⟨P, hP⟩ := cau_seq.bounded ⟨_, ha⟩ in
have hP0 : 0 < P, from lt_of_le_of_lt (abs_nonneg _) (hP 0),
have hPε0 : 0 < ε / (2 * P),
from div_pos ε0 (mul_pos (show (2 : α) > 0, from by norm_num) hP0),
let ⟨N, hN⟩ := cau_seq.cauchy₂ ⟨_, hb⟩ hPε0 in
have hQε0 : 0 < ε / (4 * Q),
from div_pos ε0 (mul_pos (show (0 : α) < 4, by norm_num) (lt_of_le_of_lt (abv_nonneg _ _) (hQ 0))),
let ⟨M, hM⟩ := cau_seq.cauchy₂ ⟨_, ha⟩ hQε0 in
⟨2 * (max N M + 1), λ K hK,
have h₁ : sum (range K) (λ m, (range (m + 1)).sum (λ k, a k * b (m - k))) =
sum (range K) (λ m, sum (range (K - m)) (λ n, a m * b n)),
by simpa using sum_range_diag_flip K (λ m n, a m * b n),
have h₂ : (λ i, (range (K - i)).sum (λ k, a i * b k)) = (λ i, a i * (range (K - i)).sum b),
by simp [finset.mul_sum],
have h₃ : (range K).sum (λ i, a i * (range (K - i)).sum b) =
(range K).sum (λ i, a i * ((range (K - i)).sum b - (range K).sum b))
+ (range K).sum (λ i, a i * (range K).sum b),
by rw ← sum_add_distrib; simp [(mul_add _ _ _).symm],
have two_mul_two : (4 : α) = 2 * 2, by norm_num,
have hQ0 : Q ≠ 0, from λ h, by simpa [h, lt_irrefl] using hQε0,
have h2Q0 : 2 * Q ≠ 0, from mul_ne_zero two_ne_zero hQ0,
have hε : ε / (2 * P) * P + ε / (4 * Q) * (2 * Q) = ε,
by rw [← div_div_eq_div_mul, div_mul_cancel _ (ne.symm (ne_of_lt hP0)),
two_mul_two, mul_assoc, ← div_div_eq_div_mul, div_mul_cancel _ h2Q0, add_halves],
have hNMK : max N M + 1 < K,
from lt_of_lt_of_le (by rw two_mul; exact lt_add_of_pos_left _ (nat.succ_pos _)) hK,
have hKN : N < K,
from calc N ≤ max N M : le_max_left _ _
... < max N M + 1 : nat.lt_succ_self _
... < K : hNMK,
have hsumlesum : (range (max N M + 1)).sum (λ i, abv (a i) *
abv ((range (K - i)).sum b - (range K).sum b)) ≤ (range (max N M + 1)).sum
(λ i, abv (a i) * (ε / (2 * P))),
from sum_le_sum (λ m hmJ, mul_le_mul_of_nonneg_left
(le_of_lt (hN (K - m) K
(nat.le_sub_left_of_add_le (le_trans
(by rw two_mul; exact add_le_add (le_of_lt (mem_range.1 hmJ))
(le_trans (le_max_left _ _) (le_of_lt (lt_add_one _)))) hK))
(le_of_lt hKN))) (abv_nonneg abv _)),
have hsumltP : sum (range (max N M + 1)) (λ n, abv (a n)) < P :=
calc sum (range (max N M + 1)) (λ n, abv (a n))
= abs (sum (range (max N M + 1)) (λ n, abv (a n))) :
eq.symm (abs_of_nonneg (zero_le_sum (λ x h, abv_nonneg abv (a x))))
... < P : hP (max N M + 1),
begin
rw [h₁, h₂, h₃, sum_mul, ← sub_sub, sub_right_comm, sub_self, zero_sub, abv_neg abv],
refine lt_of_le_of_lt (abv_sum_le_sum_abv _ _) _,
suffices : (range (max N M + 1)).sum (λ (i : ℕ), abv (a i) * abv ((range (K - i)).sum b - (range K).sum b)) +
((range K).sum (λ (i : ℕ), abv (a i) * abv ((range (K - i)).sum b - (range K).sum b)) -(range (max N M + 1)).sum
(λ (i : ℕ), abv (a i) * abv ((range (K - i)).sum b - (range K).sum b))) < ε / (2 * P) * P + ε / (4 * Q) * (2 * Q),
{ rw hε at this, simpa [abv_mul abv] },
refine add_lt_add (lt_of_le_of_lt hsumlesum
(by rw [← sum_mul, mul_comm]; exact (mul_lt_mul_left hPε0).mpr hsumltP)) _,
rw sum_range_sub_sum_range (le_of_lt hNMK),
exact calc sum ((range K).filter (λ k, max N M + 1 ≤ k))
(λ i, abv (a i) * abv (sum (range (K - i)) b - sum (range K) b))
≤ sum ((range K).filter (λ k, max N M + 1 ≤ k)) (λ i, abv (a i) * (2 * Q)) :
sum_le_sum (λ n hn, begin
refine mul_le_mul_of_nonneg_left _ (abv_nonneg _ _),
rw sub_eq_add_neg,
refine le_trans (abv_add _ _ _) _,
rw [two_mul, abv_neg abv],
exact add_le_add (le_of_lt (hQ _)) (le_of_lt (hQ _)),
end)
... < ε / (4 * Q) * (2 * Q) :
by rw [← sum_mul, ← sum_range_sub_sum_range (le_of_lt hNMK)];
refine (mul_lt_mul_right $ by rw two_mul;
exact add_pos (lt_of_le_of_lt (abv_nonneg _ _) (hQ 0))
(lt_of_le_of_lt (abv_nonneg _ _) (hQ 0))).2
(lt_of_le_of_lt (le_abs_self _)
(hM _ _ (le_trans (nat.le_succ_of_le (le_max_right _ _)) (le_of_lt hNMK))
(nat.le_succ_of_le (le_max_right _ _))))
end⟩
end
open finset
namespace complex
lemma is_cau_abs_exp (z : ℂ) : is_cau_seq _root_.abs
(λ n, (range n).sum (λ m, abs (z ^ m / nat.fact m))) :=
let ⟨n, hn⟩ := exists_nat_gt (abs z) in
have hn0 : (0 : ℝ) < n, from lt_of_le_of_lt (abs_nonneg _) hn,
series_ratio_test n (complex.abs z / n) (div_nonneg_of_nonneg_of_pos (complex.abs_nonneg _) hn0)
(by rwa [div_lt_iff hn0, one_mul])
(λ m hm,
by rw [abs_abs, abs_abs, nat.fact_succ, pow_succ,
mul_comm m.succ, nat.cast_mul, ← div_div_eq_div_mul, mul_div_assoc,
mul_div_right_comm, abs_mul, abs_div, abs_cast_nat];
exact mul_le_mul_of_nonneg_right
(div_le_div_of_le_left (abs_nonneg _) (nat.cast_pos.2 (nat.succ_pos _)) hn0
(nat.cast_le.2 (le_trans hm (nat.le_succ _)))) (abs_nonneg _))
noncomputable theory
lemma is_cau_exp (z : ℂ) : is_cau_seq abs (λ n, (range n).sum (λ m, z ^ m / nat.fact m)) :=
is_cau_series_of_abv_cau (is_cau_abs_exp z)
def exp' (z : ℂ) : cau_seq ℂ complex.abs := ⟨λ n, (range n).sum (λ m, z ^ m / nat.fact m), is_cau_exp z⟩
def exp (z : ℂ) : ℂ := lim (exp' z)
def sin (z : ℂ) : ℂ := ((exp (-z * I) - exp (z * I)) * I) / 2
def cos (z : ℂ) : ℂ := (exp (z * I) + exp (-z * I)) / 2
def tan (z : ℂ) : ℂ := sin z / cos z
def sinh (z : ℂ) : ℂ := (exp z - exp (-z)) / 2
def cosh (z : ℂ) : ℂ := (exp z + exp (-z)) / 2
def tanh (z : ℂ) : ℂ := sinh z / cosh z
end complex
namespace real
open complex
def exp (x : ℝ) : ℝ := (exp x).re
def sin (x : ℝ) : ℝ := (sin x).re
def cos (x : ℝ) : ℝ := (cos x).re
def tan (x : ℝ) : ℝ := (tan x).re
def sinh (x : ℝ) : ℝ := (sinh x).re
def cosh (x : ℝ) : ℝ := (cosh x).re
def tanh (x : ℝ) : ℝ := (tanh x).re
end real
namespace complex
variables (x y : ℂ)
@[simp] lemma exp_zero : exp 0 = 1 :=
lim_eq_of_equiv_const $
λ ε ε0, ⟨1, λ j hj, begin
convert ε0,
cases j,
{ exact absurd hj (not_le_of_gt zero_lt_one) },
{ dsimp [exp'],
induction j with j ih,
{ dsimp [exp']; simp },
{ rw ← ih dec_trivial,
simp only [sum_range_succ, pow_succ],
simp } }
end⟩
lemma exp_add : exp (x + y) = exp x * exp y :=
show lim (⟨_, is_cau_exp (x + y)⟩ : cau_seq ℂ abs) =
lim (show cau_seq ℂ abs, from ⟨_, is_cau_exp x⟩)
* lim (show cau_seq ℂ abs, from ⟨_, is_cau_exp y⟩),
from
have hj : ∀ j : ℕ, (range j).sum
(λ m, (x + y) ^ m / m.fact) = (range j).sum
(λ i, (range (i + 1)).sum (λ k, x ^ k / k.fact *
(y ^ (i - k) / (i - k).fact))),
from assume j,
finset.sum_congr rfl (λ m hm, begin
rw [add_pow, div_eq_mul_inv, sum_mul],
refine finset.sum_congr rfl (λ i hi, _),
have h₁ : (choose m i : ℂ) ≠ 0 := nat.cast_ne_zero.2 (λ h,
by simpa [h, lt_irrefl] using choose_pos (nat.le_of_lt_succ (mem_range.1 hi))),
have h₂ := choose_mul_fact_mul_fact (nat.le_of_lt_succ $ finset.mem_range.1 hi),
rw [← h₂, nat.cast_mul, nat.cast_mul, mul_inv', mul_inv'],
simp only [mul_left_comm (choose m i : ℂ), mul_assoc, mul_left_comm (choose m i : ℂ)⁻¹,
mul_comm (choose m i : ℂ)],
rw inv_mul_cancel h₁,
simp [div_eq_mul_inv, mul_comm, mul_assoc, mul_left_comm]
end),
by rw lim_mul_lim;
exact eq.symm (lim_eq_lim_of_equiv (by dsimp; simp only [hj];
exact cauchy_product (is_cau_abs_exp x) (is_cau_exp y)))
lemma exp_ne_zero : exp x ≠ 0 :=
λ h, @zero_ne_one ℂ _ $
by rw [← exp_zero, ← add_neg_self x, exp_add, h]; simp
lemma exp_neg : exp (-x) = (exp x)⁻¹ :=
by rw [← domain.mul_left_inj (exp_ne_zero x), ← exp_add];
simp [mul_inv_cancel (exp_ne_zero x)]
lemma exp_sub : exp (x - y) = exp x / exp y :=
by simp [exp_add, exp_neg, div_eq_mul_inv]
@[simp] lemma exp_conj : exp (conj x) = conj (exp x) :=
begin
dsimp [exp],
rw [← lim_conj],
refine congr_arg lim _,
dsimp [exp', function.comp],
funext,
rw ← sum_hom conj conj_zero conj_add,
refine sum_congr rfl (λ n hn, _),
rw [conj_div, conj_pow, ← of_real_nat_cast, conj_of_real]
end
@[simp] lemma exp_of_real_im (x : ℝ) : (exp x).im = 0 :=
let ⟨r, hr⟩ := (eq_conj_iff_real (exp x)).1 (by rw [← exp_conj, conj_of_real]) in
by rw [hr, of_real_im]
lemma exp_of_real_re (x : ℝ) : (exp x).re = real.exp x := rfl
@[simp] lemma of_real_exp_of_real_re (x : ℝ) : ((exp x).re : ℂ) = exp x :=
complex.ext (by simp) (by simp)
@[simp] lemma of_real_exp (x : ℝ) : (real.exp x : ℂ) = exp x :=
complex.ext (by simp [real.exp]) (by simp [real.exp])
@[simp] lemma sin_zero : sin 0 = 0 := by simp [sin]
@[simp] lemma sin_neg : sin (-x) = -sin x :=
by simp [sin, exp_neg, (neg_div _ _).symm, add_mul]
lemma sin_add : sin (x + y) = sin x * cos y + cos x * sin y :=
begin
rw [← domain.mul_left_inj (@two_ne_zero' ℂ _ _ _),
← domain.mul_left_inj (@two_ne_zero' ℂ _ _ _)],
simp only [mul_add, add_mul, exp_add, div_mul_div, div_add_div_same,
mul_assoc, (div_div_eq_div_mul _ _ _).symm,
mul_div_cancel' _ (@two_ne_zero' ℂ _ _ _), sin, cos],
simp [mul_add, add_mul, exp_add],
ring
end
@[simp] lemma cos_zero : cos 0 = 1 := by simp [cos]
@[simp] lemma cos_neg : cos (-x) = cos x :=
by simp [cos, exp_neg]
lemma cos_add : cos (x + y) = cos x * cos y - sin x * sin y :=
begin
rw [← domain.mul_left_inj (@two_ne_zero' ℂ _ _ _),
← domain.mul_left_inj (@two_ne_zero' ℂ _ _ _)],
simp only [mul_add, add_mul, mul_sub, sub_mul, exp_add, div_mul_div,
div_add_div_same, mul_assoc, (div_div_eq_div_mul _ _ _).symm,
mul_div_cancel' _ (@two_ne_zero' ℂ _ _ _), sin, cos],
apply complex.ext; simp [mul_add, add_mul, exp_add]; ring
end
lemma sin_sub : sin (x - y) = sin x * cos y - cos x * sin y :=
by simp [sin_add, sin_neg, cos_neg]
lemma cos_sub : cos (x - y) = cos x * cos y + sin x * sin y :=
by simp [cos_add, sin_neg, cos_neg]
lemma sin_conj : sin (conj x) = conj (sin x) :=
begin
rw [sin, ← conj_neg_I, ← conj_mul, ← conj_neg, ← conj_mul,
exp_conj, exp_conj, ← conj_sub, sin, conj_div, conj_two,
← domain.mul_left_inj (@two_ne_zero' ℂ _ _ _),
mul_div_cancel' _ (@two_ne_zero' ℂ _ _ _),
mul_div_cancel' _ (@two_ne_zero' ℂ _ _ _)],
apply complex.ext; simp [sin, neg_add],
end
@[simp] lemma sin_of_real_im (x : ℝ) : (sin x).im = 0 :=
let ⟨r, hr⟩ := (eq_conj_iff_real (sin x)).1 (by rw [← sin_conj, conj_of_real]) in
by rw [hr, of_real_im]
lemma sin_of_real_re (x : ℝ) : (sin x).re = real.sin x := rfl
@[simp] lemma of_real_sin_of_real_re (x : ℝ) : ((sin x).re : ℂ) = sin x :=
by apply complex.ext; simp
@[simp] lemma of_real_sin (x : ℝ) : (real.sin x : ℂ) = sin x :=
by simp [real.sin]
lemma cos_conj : cos (conj x) = conj (cos x) :=
begin
rw [cos, ← conj_neg_I, ← conj_mul, ← conj_neg, ← conj_mul,
exp_conj, exp_conj, cos, conj_div, conj_two,
← domain.mul_left_inj (@two_ne_zero' ℂ _ _ _),
mul_div_cancel' _ (@two_ne_zero' ℂ _ _ _),
mul_div_cancel' _ (@two_ne_zero' ℂ _ _ _)],
apply complex.ext; simp
end
@[simp] lemma cos_of_real_im (x : ℝ) : (cos x).im = 0 :=
let ⟨r, hr⟩ := (eq_conj_iff_real (cos x)).1 (by rw [← cos_conj, conj_of_real]) in
by rw [hr, of_real_im]
lemma cos_of_real_re (x : ℝ) : (cos x).re = real.cos x := rfl
@[simp] lemma of_real_cos_of_real_re (x : ℝ) : ((cos x).re : ℂ) = cos x :=
by apply complex.ext; simp
@[simp] lemma of_real_cos (x : ℝ) : (real.cos x : ℂ) = cos x :=
by simp [real.cos, -cos_of_real_re]
@[simp] lemma tan_zero : tan 0 = 0 := by simp [tan]
lemma tan_eq_sin_div_cos : tan x = sin x / cos x := rfl
@[simp] lemma tan_neg : tan (-x) = -tan x := by simp [tan, neg_div]
lemma tan_conj : tan (conj x) = conj (tan x) :=
by rw [tan, sin_conj, cos_conj, ← conj_div, tan]
@[simp] lemma tan_of_real_im (x : ℝ) : (tan x).im = 0 :=
let ⟨r, hr⟩ := (eq_conj_iff_real (tan x)).1 (by rw [← tan_conj, conj_of_real]) in
by rw [hr, of_real_im]
lemma tan_of_real_re (x : ℝ) : (tan x).re = real.tan x := rfl
@[simp] lemma of_real_tan_of_real_re (x : ℝ) : ((tan x).re : ℂ) = tan x :=
by apply complex.ext; simp
@[simp] lemma of_real_tan (x : ℝ) : (real.tan x : ℂ) = tan x :=
by simp [real.tan, -tan_of_real_re]
lemma sin_pow_two_add_cos_pow_two : sin x ^ 2 + cos x ^ 2 = 1 :=
begin
simp only [pow_two, mul_sub, sub_mul, mul_add, add_mul, div_eq_mul_inv,
neg_mul_eq_neg_mul_symm, exp_neg, mul_comm (exp _), mul_left_comm (exp _),
mul_assoc, mul_left_comm (exp _)⁻¹, inv_mul_cancel (exp_ne_zero _), mul_inv',
mul_one, one_mul, sin, cos],
apply complex.ext; simp [norm_sq]; ring
end
lemma cos_two_mul : cos (2 * x) = 2 * cos x ^ 2 - 1 :=
by rw [two_mul, cos_add, ← pow_two, ← pow_two, eq_sub_iff_add_eq.2 (sin_pow_two_add_cos_pow_two x)];
simp [two_mul]
lemma sin_two_mul : sin (2 * x) = 2 * sin x * cos x :=
by rw [two_mul, sin_add, two_mul, add_mul, mul_comm]
lemma exp_mul_I : exp (x * I) = cos x + sin x * I :=
by rw [cos, sin, mul_comm (_ / 2) I, ← mul_div_assoc, mul_left_comm I, I_mul_I,
← add_div]; simp
lemma exp_add_mul_I : exp (x + y * I) = exp x * (cos y + sin y * I) :=
by rw [exp_add, exp_mul_I]
lemma exp_eq_exp_re_mul_sin_add_cos : exp x = exp x.re * (cos x.im + sin x.im * I) :=
by rw [← exp_add_mul_I, re_add_im]
@[simp] lemma sinh_zero : sinh 0 = 0 := by simp [sinh]
@[simp] lemma sinh_neg : sinh (-x) = -sinh x :=
by simp [sinh, exp_neg, (neg_div _ _).symm, add_mul]
lemma sinh_add : sinh (x + y) = sinh x * cosh y + cosh x * sinh y :=
begin
rw [← domain.mul_left_inj (@two_ne_zero' ℂ _ _ _),
← domain.mul_left_inj (@two_ne_zero' ℂ _ _ _)],
simp only [mul_add, add_mul, exp_add, div_mul_div, div_add_div_same,
mul_assoc, (div_div_eq_div_mul _ _ _).symm,
mul_div_cancel' _ (@two_ne_zero' ℂ _ _ _), sinh, cosh],
simp [mul_add, add_mul, exp_add],
ring
end
@[simp] lemma cosh_zero : cosh 0 = 1 := by simp [cosh]
@[simp] lemma cosh_neg : cosh (-x) = cosh x :=
by simp [cosh, exp_neg]
lemma cosh_add : cosh (x + y) = cosh x * cosh y + sinh x * sinh y :=
begin
rw [← domain.mul_left_inj (@two_ne_zero' ℂ _ _ _),
← domain.mul_left_inj (@two_ne_zero' ℂ _ _ _)],
simp only [mul_add, add_mul, mul_sub, sub_mul, exp_add, div_mul_div,
div_add_div_same, mul_assoc, (div_div_eq_div_mul _ _ _).symm,
mul_div_cancel' _ (@two_ne_zero' ℂ _ _ _), sinh, cosh],
apply complex.ext; simp [mul_add, add_mul, exp_add]; ring
end
lemma sinh_sub : sinh (x - y) = sinh x * cosh y - cosh x * sinh y :=
by simp [sinh_add, sinh_neg, cosh_neg]
lemma cosh_sub : cosh (x - y) = cosh x * cosh y - sinh x * sinh y :=
by simp [cosh_add, sinh_neg, cosh_neg]
lemma sinh_conj : sinh (conj x) = conj (sinh x) :=
by rw [sinh, ← conj_neg, exp_conj, exp_conj, ← conj_sub, sinh, conj_div, conj_two]
@[simp] lemma sinh_of_real_im (x : ℝ) : (sinh x).im = 0 :=
let ⟨r, hr⟩ := (eq_conj_iff_real (sinh x)).1 (by rw [← sinh_conj, conj_of_real]) in
by rw [hr, of_real_im]
lemma sinh_of_real_re (x : ℝ) : (sinh x).re = real.sinh x := rfl
@[simp] lemma of_real_sinh_of_real_re (x : ℝ) : ((sinh x).re : ℂ) = sinh x :=
by apply complex.ext; simp
@[simp] lemma of_real_sinh (x : ℝ) : (real.sinh x : ℂ) = sinh x :=
by simp [real.sinh]
lemma cosh_conj : cosh (conj x) = conj (cosh x) :=
by rw [cosh, ← conj_neg, exp_conj, exp_conj, ← conj_add, cosh, conj_div, conj_two]
@[simp] lemma cosh_of_real_im (x : ℝ) : (cosh x).im = 0 :=
let ⟨r, hr⟩ := (eq_conj_iff_real (cosh x)).1 (by rw [← cosh_conj, conj_of_real]) in
by rw [hr, of_real_im]
lemma cosh_of_real_re (x : ℝ) : (cosh x).re = real.cosh x := rfl
@[simp] lemma of_real_cosh_of_real_re (x : ℝ) : ((cosh x).re : ℂ) = cosh x :=
by apply complex.ext; simp
@[simp] lemma of_real_cosh (x : ℝ) : (real.cosh x : ℂ) = cosh x :=
by simp [real.cosh]
lemma tanh_eq_sinh_div_cosh : tanh x = sinh x / cosh x := rfl
@[simp] lemma tanh_zero : tanh 0 = 0 := by simp [tanh]
@[simp] lemma tanh_neg : tanh (-x) = -tanh x := by simp [tanh, neg_div]
lemma tanh_conj : tanh (conj x) = conj (tanh x) :=
by rw [tanh, sinh_conj, cosh_conj, ← conj_div, tanh]
@[simp] lemma tanh_of_real_im (x : ℝ) : (tanh x).im = 0 :=
let ⟨r, hr⟩ := (eq_conj_iff_real (tanh x)).1 (by rw [← tanh_conj, conj_of_real]) in
by rw [hr, of_real_im]
lemma tanh_of_real_re (x : ℝ) : (tanh x).re = real.tanh x := rfl
@[simp] lemma of_real_tanh_of_real_re (x : ℝ) : ((tanh x).re : ℂ) = tanh x :=
by apply complex.ext; simp
@[simp] lemma of_real_tanh (x : ℝ) : (real.tanh x : ℂ) = tanh x :=
by simp [real.tanh]
end complex
namespace real
open complex
variables (x y : ℝ)
@[simp] lemma exp_zero : exp 0 = 1 :=
by simp [real.exp]
lemma exp_add : exp (x + y) = exp x * exp y :=
by simp [exp_add, exp]
lemma exp_ne_zero : exp x ≠ 0 :=
λ h, exp_ne_zero x $ by rw [exp, ← of_real_inj] at h; simp * at *
lemma exp_neg : exp (-x) = (exp x)⁻¹ :=
by rw [← of_real_inj, exp, of_real_exp_of_real_re, of_real_neg, exp_neg,
of_real_inv, of_real_exp]
lemma exp_sub : exp (x - y) = exp x / exp y :=
by simp [exp_add, exp_neg, div_eq_mul_inv]
@[simp] lemma sin_zero : sin 0 = 0 := by simp [sin]
@[simp] lemma sin_neg : sin (-x) = -sin x :=
by simp [sin, exp_neg, (neg_div _ _).symm, add_mul]
lemma sin_add : sin (x + y) = sin x * cos y + cos x * sin y :=
by rw [← of_real_inj]; simp [sin, sin_add]
@[simp] lemma cos_zero : cos 0 = 1 := by simp [cos]
@[simp] lemma cos_neg : cos (-x) = cos x :=
by simp [cos, exp_neg]
lemma cos_add : cos (x + y) = cos x * cos y - sin x * sin y :=
by rw ← of_real_inj; simp [cos, cos_add]
lemma sin_sub : sin (x - y) = sin x * cos y - cos x * sin y :=
by simp [sin_add, sin_neg, cos_neg]
lemma cos_sub : cos (x - y) = cos x * cos y + sin x * sin y :=
by simp [cos_add, sin_neg, cos_neg]
lemma tan_eq_sin_div_cos : tan x = sin x / cos x :=
if h : complex.cos x = 0 then by simp [sin, cos, tan, *, complex.tan, div_eq_mul_inv] at *
else
by rw [sin, cos, tan, complex.tan, ← of_real_inj, div_eq_mul_inv, mul_re];
simp [norm_sq, (div_div_eq_div_mul _ _ _).symm, div_self h]; refl
@[simp] lemma tan_zero : tan 0 = 0 := by simp [tan]
@[simp] lemma tan_neg : tan (-x) = -tan x := by simp [tan, neg_div]
lemma sin_pow_two_add_cos_pow_two : sin x ^ 2 + cos x ^ 2 = 1 :=
by rw ← of_real_inj; simpa [sin, of_real_pow] using sin_pow_two_add_cos_pow_two x
lemma abs_sin_le_one : abs' (sin x) ≤ 1 :=
not_lt.1 $ λ h, lt_irrefl (1 * 1 : ℝ)
(calc 1 * 1 < abs' (sin x) * abs' (sin x) :
mul_lt_mul h (le_of_lt h) zero_lt_one (le_trans zero_le_one (le_of_lt h))
... = sin x ^ 2 : by rw [← _root_.abs_mul, abs_mul_self, pow_two]
... ≤ sin x ^ 2 + cos x ^ 2 : le_add_of_nonneg_right (pow_two_nonneg _)
... = 1 * 1 : by rw [sin_pow_two_add_cos_pow_two, one_mul])
lemma abs_cos_le_one : abs' (cos x) ≤ 1 :=
not_lt.1 $ λ h, lt_irrefl (1 * 1 : ℝ)
(calc 1 * 1 < abs' (cos x) * abs' (cos x) :
mul_lt_mul h (le_of_lt h) zero_lt_one (le_trans zero_le_one (le_of_lt h))
... = cos x ^ 2 : by rw [← _root_.abs_mul, abs_mul_self, pow_two]
... ≤ sin x ^ 2 + cos x ^ 2 : le_add_of_nonneg_left (pow_two_nonneg _)
... = 1 * 1 : by rw [sin_pow_two_add_cos_pow_two, one_mul])
lemma sin_le_one : sin x ≤ 1 :=
(abs_le.1 (abs_sin_le_one _)).2
lemma cos_le_one : cos x ≤ 1 :=
(abs_le.1 (abs_cos_le_one _)).2
lemma neg_one_le_sin : -1 ≤ sin x :=
(abs_le.1 (abs_sin_le_one _)).1
lemma neg_one_le_cos : -1 ≤ cos x :=
(abs_le.1 (abs_cos_le_one _)).1
lemma sin_pow_two_le_one : sin x ^ 2 ≤ 1 :=
by rw [pow_two, ← abs_mul_self, _root_.abs_mul];
exact mul_le_one (abs_sin_le_one _) (abs_nonneg _) (abs_sin_le_one _)
lemma cos_pow_two_le_one : cos x ^ 2 ≤ 1 :=
by rw [pow_two, ← abs_mul_self, _root_.abs_mul];
exact mul_le_one (abs_cos_le_one _) (abs_nonneg _) (abs_cos_le_one _)
lemma cos_two_mul : cos (2 * x) = 2 * cos x ^ 2 - 1 :=
by rw ← of_real_inj; simp [cos_two_mul, cos, pow_two]
lemma sin_two_mul : sin (2 * x) = 2 * sin x * cos x :=
by rw ← of_real_inj; simp [sin_two_mul, sin, pow_two]
@[simp] lemma sinh_zero : sinh 0 = 0 := by simp [sinh]
@[simp] lemma sinh_neg : sinh (-x) = -sinh x :=
by simp [sinh, exp_neg, (neg_div _ _).symm, add_mul]
lemma sinh_add : sinh (x + y) = sinh x * cosh y + cosh x * sinh y :=
by rw ← of_real_inj; simp [sinh, sinh_add]
@[simp] lemma cosh_zero : cosh 0 = 1 := by simp [cosh]
@[simp] lemma cosh_neg : cosh (-x) = cosh x :=
by simp [cosh, exp_neg]
lemma cosh_add : cosh (x + y) = cosh x * cosh y + sinh x * sinh y :=
by rw ← of_real_inj; simp [cosh, cosh_add]
lemma sinh_sub : sinh (x - y) = sinh x * cosh y - cosh x * sinh y :=
by simp [sinh_add, sinh_neg, cosh_neg]
lemma cosh_sub : cosh (x - y) = cosh x * cosh y - sinh x * sinh y :=
by simp [cosh_add, sinh_neg, cosh_neg]
lemma tanh_eq_sinh_div_cosh : tanh x = sinh x / cosh x :=
if h : complex.cosh x = 0 then by simp [sinh, cosh, tanh, *, complex.tanh, div_eq_mul_inv] at *
else
by rw [sinh, cosh, tanh, complex.tanh, ← of_real_inj, div_eq_mul_inv, mul_re];
simp [norm_sq, (div_div_eq_div_mul _ _ _).symm, div_self h]; refl
@[simp] lemma tanh_zero : tanh 0 = 0 := by simp [tanh]
@[simp] lemma tanh_neg : tanh (-x) = -tanh x := by simp [tanh, neg_div]
open is_absolute_value
/- TODO make this private and prove ∀ x -/
lemma add_one_le_exp_of_nonneg {x : ℝ} (hx : 0 ≤ x) : x + 1 ≤ exp x :=
show x + 1 ≤ lim (⟨(λ n : ℕ, ((exp' x) n).re), is_cau_seq_re (exp' x)⟩ : cau_seq ℝ abs'),
from real.le_lim (cau_seq.le_of_exists ⟨2,
λ j hj, show x + (1 : ℝ) ≤ ((range j).sum (λ m, (x ^ m / m.fact : ℂ))).re,
from have h₁ : (((λ m : ℕ, (x ^ m / m.fact : ℂ)) ∘ nat.succ) 0).re = x, by simp,
have h₂ : ((x : ℂ) ^ 0 / nat.fact 0).re = 1, by simp,
begin
rw [← nat.sub_add_cancel hj, sum_range_succ', sum_range_succ',
add_re, add_re, h₁, h₂, add_assoc, ← sum_hom complex.re zero_re add_re],
refine le_add_of_nonneg_of_le (zero_le_sum (λ m hm, _)) (le_refl _), dsimp [-nat.fact_succ],
rw [← of_real_pow, ← of_real_nat_cast, ← of_real_div, of_real_re],
exact div_nonneg (pow_nonneg hx _) (nat.cast_pos.2 (nat.fact_pos _)),
end⟩)
lemma one_le_exp {x : ℝ} (hx : 0 ≤ x) : 1 ≤ exp x :=
by linarith using [add_one_le_exp_of_nonneg hx]
lemma exp_pos (x : ℝ) : 0 < exp x :=
(le_total 0 x).elim (lt_of_lt_of_le zero_lt_one ∘ one_le_exp)
(λ h, by rw [← neg_neg x, real.exp_neg];
exact inv_pos (lt_of_lt_of_le zero_lt_one (one_le_exp (neg_nonneg.2 h))))
@[simp] lemma abs_exp (x : ℝ) : abs' (exp x) = exp x :=
abs_of_nonneg (le_of_lt (exp_pos _))
lemma exp_le_exp {x y : ℝ} (h : x ≤ y) : exp x ≤ exp y :=
by rw [← sub_add_cancel y x, real.exp_add];
exact (le_mul_iff_one_le_left (exp_pos _)).2 (one_le_exp (sub_nonneg.2 h))
lemma exp_lt_exp {x y : ℝ} (h : x < y) : exp x < exp y :=
by rw [← sub_add_cancel y x, real.exp_add];
exact (lt_mul_iff_one_lt_left (exp_pos _)).2
(lt_of_lt_of_le (by linarith) (add_one_le_exp_of_nonneg (by linarith)))
lemma exp_injective : function.injective exp :=
λ x y h, begin
rcases lt_trichotomy x y with h₁ | h₁ | h₁,
{ exact absurd h (ne_of_lt (exp_lt_exp h₁)) },
{ exact h₁ },
{ exact absurd h (ne.symm (ne_of_lt (exp_lt_exp h₁))) }
end
end real
namespace complex
lemma sum_div_fact_le {α : Type*} [discrete_linear_ordered_field α] (n j : ℕ) (hn : 0 < n) :
(sum (filter (λ k, n ≤ k) (range j)) (λ m : ℕ, (1 / m.fact : α))) ≤ n.succ * (n.fact * n)⁻¹ :=
calc (filter (λ k, n ≤ k) (range j)).sum (λ m : ℕ, (1 / m.fact : α))
= (range (j - n)).sum (λ m, 1 / (m + n).fact) :
sum_bij (λ m _, m - n)
(λ m hm, mem_range.2 $ (nat.sub_lt_sub_right_iff (by simp at hm; tauto)).2
(by simp at hm; tauto))
(λ m hm, by rw nat.sub_add_cancel; simp at *; tauto)
(λ a₁ a₂ ha₁ ha₂ h,
by rwa [nat.sub_eq_iff_eq_add, ← nat.sub_add_comm, eq_comm, nat.sub_eq_iff_eq_add, add_right_inj, eq_comm] at h;
simp at *; tauto)
(λ b hb, ⟨b + n, mem_filter.2 ⟨mem_range.2 $ nat.add_lt_of_lt_sub_right (mem_range.1 hb), nat.le_add_left _ _⟩,
by rw nat.add_sub_cancel⟩)
... ≤ (range (j - n)).sum (λ m, (nat.fact n * n.succ ^ m)⁻¹) :
sum_le_sum (λ m hm, begin
rw one_div_eq_inv,
refine (inv_le_inv (nat.cast_pos.2 (nat.fact_pos _)) _).2 _,
{ exact mul_pos (nat.cast_pos.2 (nat.fact_pos _)) (pow_pos (nat.cast_pos.2 (nat.succ_pos _)) _) },
{ rw [← nat.cast_pow, ← nat.cast_mul, nat.cast_le, add_comm],
exact nat.fact_mul_pow_le_fact }
end)
... = (nat.fact n)⁻¹ * (range (j - n)).sum (λ m, n.succ⁻¹ ^ m) :
by simp [mul_inv', mul_sum.symm, sum_mul.symm, -nat.fact_succ, mul_comm, inv_pow']
... = (n.succ - n.succ * n.succ⁻¹ ^ (j - n)) / (n.fact * n) :
have h₁ : (n.succ : α) ≠ 1, from @nat.cast_one α _ _ ▸ mt nat.cast_inj.1
(mt nat.succ_inj (nat.pos_iff_ne_zero.1 hn)),
have h₂ : (n.succ : α) ≠ 0, from nat.cast_ne_zero.2 (nat.succ_ne_zero _),
have h₃ : (n.fact * n : α) ≠ 0, from mul_ne_zero (nat.cast_ne_zero.2 (nat.pos_iff_ne_zero.1 (nat.fact_pos _)))
(nat.cast_ne_zero.2 (nat.pos_iff_ne_zero.1 hn)),
have h₄ : (n.succ - 1 : α) * (n.fact : ℕ) ≠ 0,
from mul_ne_zero (sub_ne_zero.2 h₁)
(nat.cast_ne_zero.2 (nat.pos_iff_ne_zero.1 (nat.fact_pos _))),
by rw [geo_sum_inv_eq _ h₁ h₂, mul_comm, ← div_eq_mul_inv, div_div_eq_div_mul,
div_eq_div_iff h₄ h₃];
simp [mul_add, add_mul, mul_comm, mul_assoc, mul_left_comm]
... ≤ n.succ / (n.fact * n) :
(div_le_div_right (mul_pos (nat.cast_pos.2 (nat.fact_pos _)) (nat.cast_pos.2 hn))).2
(sub_le_self _ (mul_nonneg (nat.cast_nonneg _) (pow_nonneg (inv_nonneg.2 (nat.cast_nonneg _)) _)))
lemma exp_bound {x : ℂ} (hx : abs x ≤ 1) {n : ℕ} (hn : 0 < n) :
abs (exp x - (range n).sum (λ m, x ^ m / m.fact)) ≤ abs x ^ n * (n.succ * (n.fact * n)⁻¹) :=
begin
rw [← lim_const ((range n).sum _), exp, sub_eq_add_neg, ← lim_neg, lim_add, ← lim_abs],
refine real.lim_le (cau_seq.le_of_exists ⟨n, λ j hj, _⟩),
show abs ((range j).sum (λ m, x ^ m / m.fact) - (range n).sum (λ m, x ^ m / m.fact))
≤ abs x ^ n * (n.succ * (n.fact * n)⁻¹),
rw sum_range_sub_sum_range hj,
exact calc abs (((range j).filter (λ k, n ≤ k)).sum (λ m : ℕ, (x ^ m / m.fact : ℂ)))
= abs (((range j).filter (λ k, n ≤ k)).sum (λ m : ℕ, (x ^ n * (x ^ (m - n) / m.fact) : ℂ))) :
congr_arg abs (sum_congr rfl (λ m hm, by rw [← mul_div_assoc, ← pow_add, nat.add_sub_cancel']; simp at hm; tauto))
... ≤ sum (filter (λ k, n ≤ k) (range j)) (λ m, abs (x ^ n * (_ / m.fact))) : abv_sum_le_sum_abv _ _
... ≤ sum (filter (λ k, n ≤ k) (range j)) (λ m, abs x ^ n * (1 / m.fact)) :
sum_le_sum (λ m hm, by
by rw [abs_mul, abv_pow abs, abs_div, abs_cast_nat];
exact mul_le_mul_of_nonneg_left ((div_le_div_right (nat.cast_pos.2 (nat.fact_pos _))).2
(by rw abv_pow abs; exact (pow_le_one _ (abs_nonneg _) hx)))
(pow_nonneg (abs_nonneg _) _))
... = abs x ^ n * (((range j).filter (λ k, n ≤ k)).sum (λ m : ℕ, (1 / m.fact : ℝ))) :
by simp [abs_mul, abv_pow abs, abs_div, mul_sum.symm]
... ≤ abs x ^ n * (n.succ * (n.fact * n)⁻¹) :
mul_le_mul_of_nonneg_left (sum_div_fact_le _ _ hn) (pow_nonneg (abs_nonneg _) _)
end
lemma abs_exp_sub_one_le {x : ℂ} (hx : abs x ≤ 1) :
abs (exp x - 1) ≤ 2 * abs x :=
calc abs (exp x - 1) = abs (exp x - (range 1).sum (λ m, x ^ m / m.fact)) :
by simp [sum_range_succ]
... ≤ abs x ^ 1 * ((nat.succ 1) * (nat.fact 1 * 1)⁻¹) :
exp_bound hx dec_trivial
... = 2 * abs x : by simp [two_mul, mul_two, mul_add, mul_comm]
end complex
namespace real
open complex finset
lemma cos_bound {x : ℝ} (hx : abs' x ≤ 1) : abs' (cos x - (1 - x ^ 2 / 2)) ≤ abs' x ^ 4 * (5 / 96) :=
calc abs' (cos x - (1 - x ^ 2 / 2)) = abs (complex.cos x - (1 - x ^ 2 / 2)) :
by rw ← abs_of_real; simp [of_real_bit0, of_real_one, of_real_inv]
... = abs ((complex.exp (x * I) + complex.exp (-x * I) - (2 - x ^ 2)) / 2) :
by simp [complex.cos, sub_div, add_div, neg_div, div_self (@two_ne_zero' ℂ _ _ _)]
... = abs (((complex.exp (x * I) - (range 4).sum (λ m, (x * I) ^ m / m.fact)) +
((complex.exp (-x * I) - (range 4).sum (λ m, (-x * I) ^ m / m.fact)))) / 2) :
congr_arg abs (congr_arg (λ x : ℂ, x / 2) begin
simp only [sum_range_succ],
simp [pow_succ],
apply complex.ext; simp [div_eq_mul_inv, norm_sq]; ring
end)
... ≤ abs ((complex.exp (x * I) - (range 4).sum (λ m, (x * I) ^ m / m.fact)) / 2) +
abs ((complex.exp (-x * I) - (range 4).sum (λ m, (-x * I) ^ m / m.fact)) / 2) :
by rw add_div; exact abs_add _ _
... = (abs ((complex.exp (x * I) - (range 4).sum (λ m, (x * I) ^ m / m.fact))) / 2 +
abs ((complex.exp (-x * I) - (range 4).sum (λ m, (-x * I) ^ m / m.fact))) / 2) :
by simp [complex.abs_div]
... ≤ ((complex.abs (x * I) ^ 4 * (nat.succ 4 * (nat.fact 4 * (4 : ℕ))⁻¹)) / 2 +
(complex.abs (-x * I) ^ 4 * (nat.succ 4 * (nat.fact 4 * (4 : ℕ))⁻¹)) / 2) :
add_le_add ((div_le_div_right (by norm_num)).2 (exp_bound (by simpa) dec_trivial))
((div_le_div_right (by norm_num)).2 (exp_bound (by simpa) dec_trivial))
... ≤ abs' x ^ 4 * (5 / 96) : by norm_num; simp [mul_assoc, mul_comm, mul_left_comm, mul_div_assoc]
lemma sin_bound {x : ℝ} (hx : abs' x ≤ 1) : abs' (sin x - (x - x ^ 3 / 6)) ≤ abs' x ^ 4 * (5 / 96) :=
calc abs' (sin x - (x - x ^ 3 / 6)) = abs (complex.sin x - (x - x ^ 3 / 6)) :
by rw ← abs_of_real; simp [of_real_bit0, of_real_one, of_real_inv]
... = abs (((complex.exp (-x * I) - complex.exp (x * I)) * I - (2 * x - x ^ 3 / 3)) / 2) :
by simp [complex.sin, sub_div, add_div, neg_div, mul_div_cancel_left _ (@two_ne_zero' ℂ _ _ _),
div_div_eq_div_mul, show (3 : ℂ) * 2 = 6, by norm_num]
... = abs ((((complex.exp (-x * I) - (range 4).sum (λ m, (-x * I) ^ m / m.fact)) -
(complex.exp (x * I) - (range 4).sum (λ m, (x * I) ^ m / m.fact))) * I) / 2) :
congr_arg abs (congr_arg (λ x : ℂ, x / 2) begin
simp only [sum_range_succ],
simp [pow_succ],
apply complex.ext; simp [div_eq_mul_inv, norm_sq]; ring
end)
... ≤ abs ((complex.exp (-x * I) - (range 4).sum (λ m, (-x * I) ^ m / m.fact)) * I / 2) +
abs (-((complex.exp (x * I) - (range 4).sum (λ m, (x * I) ^ m / m.fact)) * I) / 2) :
by rw [sub_mul, sub_eq_add_neg, add_div]; exact abs_add _ _
... = (abs ((complex.exp (x * I) - (range 4).sum (λ m, (x * I) ^ m / m.fact))) / 2 +
abs ((complex.exp (-x * I) - (range 4).sum (λ m, (-x * I) ^ m / m.fact))) / 2) :
by simp [complex.abs_div, complex.abs_mul]
... ≤ ((complex.abs (x * I) ^ 4 * (nat.succ 4 * (nat.fact 4 * (4 : ℕ))⁻¹)) / 2 +
(complex.abs (-x * I) ^ 4 * (nat.succ 4 * (nat.fact 4 * (4 : ℕ))⁻¹)) / 2) :
add_le_add ((div_le_div_right (by norm_num)).2 (exp_bound (by simpa) dec_trivial))
((div_le_div_right (by norm_num)).2 (exp_bound (by simpa) dec_trivial))
... ≤ abs' x ^ 4 * (5 / 96) : by norm_num; simp [mul_assoc, mul_comm, mul_left_comm, mul_div_assoc]
lemma cos_pos_of_le_one {x : ℝ} (hx : abs' x ≤ 1) : 0 < cos x :=
calc 0 < (1 - x ^ 2 / 2) - abs' x ^ 4 * (5 / 96) :
sub_pos.2 $ lt_sub_iff_add_lt.2
(calc abs' x ^ 4 * (5 / 96) + x ^ 2 / 2
≤ 1 * (5 / 96) + 1 / 2 :
add_le_add
(mul_le_mul_of_nonneg_right (pow_le_one _ (abs_nonneg _) hx) (by norm_num))
((div_le_div_right (by norm_num)).2 (by rw [pow_two, ← abs_mul_self, _root_.abs_mul];
exact mul_le_one hx (abs_nonneg _) hx))
... < 1 : by norm_num)
... ≤ cos x : sub_le.1 (abs_sub_le_iff.1 (cos_bound hx)).2
lemma sin_pos_of_pos_of_le_one {x : ℝ} (hx0 : 0 < x) (hx : x ≤ 1) : 0 < sin x :=
calc 0 < x - x ^ 3 / 6 - abs' x ^ 4 * (5 / 96) :
sub_pos.2 $ lt_sub_iff_add_lt.2
(calc abs' x ^ 4 * (5 / 96) + x ^ 3 / 6
≤ x * (5 / 96) + x / 6 :
add_le_add
(mul_le_mul_of_nonneg_right
(calc abs' x ^ 4 ≤ abs' x ^ 1 : pow_le_pow_of_le_one (abs_nonneg _)
(by rwa _root_.abs_of_nonneg (le_of_lt hx0))
dec_trivial
... = x : by simp [_root_.abs_of_nonneg (le_of_lt (hx0))]) (by norm_num))
((div_le_div_right (by norm_num)).2
(calc x ^ 3 ≤ x ^ 1 : pow_le_pow_of_le_one (le_of_lt hx0) hx dec_trivial
... = x : pow_one _))
... < x : by linarith)
... ≤ sin x : sub_le.1 (abs_sub_le_iff.1 (sin_bound
(by rwa [_root_.abs_of_nonneg (le_of_lt hx0)]))).2
lemma sin_pos_of_pos_of_le_two {x : ℝ} (hx0 : 0 < x) (hx : x ≤ 2) : 0 < sin x :=
have x / 2 ≤ 1, from div_le_of_le_mul (by norm_num) (by simpa),
calc 0 < 2 * sin (x / 2) * cos (x / 2) :
mul_pos (mul_pos (by norm_num) (sin_pos_of_pos_of_le_one (half_pos hx0) this))
(cos_pos_of_le_one (by rwa [_root_.abs_of_nonneg (le_of_lt (half_pos hx0))]))
... = sin x : by rw [← sin_two_mul, two_mul, add_halves]
lemma cos_one_le : cos 1 ≤ 2 / 3 :=
calc cos 1 ≤ abs' (1 : ℝ) ^ 4 * (5 / 96) + (1 - 1 ^ 2 / 2) :
sub_le_iff_le_add.1 (abs_sub_le_iff.1 (cos_bound (by simp))).1
... ≤ 2 / 3 : by norm_num
lemma cos_one_pos : 0 < cos 1 := cos_pos_of_le_one (by simp)
lemma cos_two_neg : cos 2 < 0 :=
calc cos 2 = cos (2 * 1) : congr_arg cos (mul_one _).symm
... = _ : real.cos_two_mul 1
... ≤ 2 * (2 / 3) ^ 2 - 1 :
sub_le_sub_right (mul_le_mul_of_nonneg_left
(by rw [pow_two, pow_two]; exact
mul_self_le_mul_self (le_of_lt cos_one_pos)
cos_one_le)
(by norm_num)) _
... < 0 : by norm_num
end real
namespace complex
lemma abs_cos_add_sin_mul_I (x : ℝ) : abs (cos x + sin x * I) = 1 :=
have _ := real.sin_pow_two_add_cos_pow_two x,
by simp [abs, norm_sq, pow_two, *, sin_of_real_re, cos_of_real_re, mul_re] at *
lemma abs_exp_eq_iff_re_eq {x y : ℂ} : abs (exp x) = abs (exp y) ↔ x.re = y.re :=
by rw [exp_eq_exp_re_mul_sin_add_cos, exp_eq_exp_re_mul_sin_add_cos y,
abs_mul, abs_mul, abs_cos_add_sin_mul_I, abs_cos_add_sin_mul_I,
← of_real_exp, ← of_real_exp, abs_of_nonneg (le_of_lt (real.exp_pos _)),
abs_of_nonneg (le_of_lt (real.exp_pos _)), mul_one, mul_one];
exact ⟨λ h, real.exp_injective h, congr_arg _⟩
@[simp] lemma abs_exp_of_real (x : ℝ) : abs (exp x) = real.exp x :=
by rw [← of_real_exp]; exact abs_of_nonneg (le_of_lt (real.exp_pos _))
end complex |
a183e4ce2582f69d8fe5361bb117e03480321026 | 46125763b4dbf50619e8846a1371029346f4c3db | /src/tactic/norm_cast.lean | 46f95c7cdbe9f07a3e7b10554325357354019921 | [
"Apache-2.0"
] | permissive | thjread/mathlib | a9d97612cedc2c3101060737233df15abcdb9eb1 | 7cffe2520a5518bba19227a107078d83fa725ddc | refs/heads/master | 1,615,637,696,376 | 1,583,953,063,000 | 1,583,953,063,000 | 246,680,271 | 0 | 0 | Apache-2.0 | 1,583,960,875,000 | 1,583,960,875,000 | null | UTF-8 | Lean | false | false | 11,896 | lean | /-
Copyright (c) 2019 Paul-Nicolas Madelaine. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Paul-Nicolas Madelaine
Normalizing casts inside expressions.
-/
import tactic.basic tactic.interactive tactic.converter.interactive
import data.buffer.parser
namespace tactic
/--
This is a work around to the fact that in some cases
mk_instance times out instead of failing
example: has_lift_t ℤ ℕ
mk_instance' is used when we assume the type class search
should end instantly
-/
meta def mk_instance' (e : expr) : tactic expr :=
try_for 1000 (mk_instance e)
end tactic
namespace expr
open tactic expr
meta def flip_eq (ty : expr) : tactic (expr × (expr → expr)) :=
do
(a, b) ← is_eq ty,
α ← infer_type a,
new_ty ← to_expr ``(%%b = %%a),
f ← to_expr ``(@eq.symm %%α %%a %%b),
return (new_ty, ⇑f)
meta def flip_iff (ty : expr) : tactic (expr × (expr → expr)) :=
do
(a, b) ← is_iff ty,
new_ty ← to_expr ``(%%b ↔ %%a),
f ← to_expr ``(@iff.symm %%a %%b),
return (new_ty, ⇑f)
end expr
namespace norm_cast
open tactic expr
private meta def new_name (n : name) : name := name.mk_string "reversed" n
private meta def aux_after_set (tac : expr → tactic (expr × (expr → expr))) :
expr → tactic (expr × (expr → expr))
| (pi n bi d b) := do
uniq_n ← mk_fresh_name,
let b' := b.instantiate_var (local_const uniq_n n bi d),
(b', f) ← aux_after_set b',
return $ (
pi n bi d $ b'.abstract_local uniq_n,
λ e, lam n bi d $ ( f $ e (local_const uniq_n n bi d) ).abstract_local uniq_n
)
| ty := tac ty
mk_simp_attribute push_cast "The `push_cast` simp attribute uses `move_cast` lemmas in the \"forward\" direction,
to move casts toward the leaf nodes of the expression."
/-- Called after the `move_cast` attribute is applied to a declaration. -/
private meta def after_set (decl : name) (prio : ℕ) (pers : bool) : tactic unit :=
do
(declaration.thm n l ty e) ← get_decl decl | failed,
let tac := λ ty, (flip_eq ty <|> flip_iff ty),
(ty', f) ← aux_after_set tac ty,
let e' := task.map f e,
let n' := new_name n,
add_decl (declaration.thm n' l ty' e'),
simp_attr.push_cast.set decl () tt
private meta def mk_cache : list name → tactic simp_lemmas :=
monad.foldl simp_lemmas.add_simp simp_lemmas.mk
/--
This is an attribute for simplification rules that are
used to normalize casts.
Let r be = or ↔, then elimination lemmas of the shape
Π ..., P ↑a1 ... ↑an r P a1 ... an should be given the
attribute elim_cast.
-/
@[user_attribute]
meta def elim_cast_attr : user_attribute simp_lemmas :=
{
name := `elim_cast,
descr := "attribute for lemmas of the shape Π ..., P ↑a1 ... ↑an = P a1 ... an",
cache_cfg :=
{ mk_cache := mk_cache,
dependencies := [], },
}
/--
This is an attribute for simplification rules that are
used to normalize casts.
Let r be = or ↔, then compositional lemmas of the shape
Π ..., ↑(P a1 ... an) r P ↑a1 ... ↑an should be given the
attribute move_cast.
-/
@[user_attribute]
meta def move_cast_attr : user_attribute simp_lemmas :=
{
name := `move_cast,
descr := "attribute for lemmas of the shape Π ..., ↑(P a1 ... an) = P ↑a1 ... ↑an",
after_set := some after_set,
cache_cfg :=
{ mk_cache := mk_cache ∘ (list.map new_name),
dependencies := [], },
}
private meta def get_cache : tactic simp_lemmas :=
do
a ← elim_cast_attr.get_cache,
b ← move_cast_attr.get_cache,
return $ simp_lemmas.join a b
/--
This is an attribute for simplification rules of the shape
Π ..., ↑↑a = ↑a or Π ..., ↑a = a.
They are used in a heuristic to infer intermediate casts.
-/
@[user_attribute]
meta def squash_cast_attr : user_attribute simp_lemmas :=
{
name := `squash_cast,
descr := "attribute for lemmas of the shape Π ..., ↑↑a = ↑a",
after_set := none,
cache_cfg := {
mk_cache := monad.foldl simp_lemmas.add_simp simp_lemmas.mk,
dependencies := [],
}
}
/-
This is an auxiliary function that proves e = new_e
using only squash_cast lemmas
-/
private meta def aux_simp (e new_e : expr) : tactic expr :=
do
s ← squash_cast_attr.get_cache,
(e', pr) ← s.rewrite new_e,
is_def_eq e e',
mk_eq_symm pr
/-
This is a supecial function for numerals:
- (1 : α) is rewritten as ((1 : ℕ) : α)
- (0 : α) is rewritten as ((0 : ℕ) : α)
-/
private meta def aux_num (_ : unit) (e : expr) : tactic (unit × expr × expr) :=
match e with
| `(0 : ℕ) := failed
| `(1 : ℕ) := failed
| `(@has_zero.zero %%α %%h) := do
coe_nat ← to_expr ``(has_lift_t ℕ %%α) >>= mk_instance',
new_e ← to_expr ``(@coe ℕ %%α %%coe_nat 0),
pr ← aux_simp e new_e,
return ((), new_e, pr)
| `(@has_one.one %%α %%h) := do
coe_nat ← to_expr ``(has_lift_t ℕ %%α) >>= mk_instance',
new_e ← to_expr ``(@coe ℕ %%α %%coe_nat 1),
pr ← aux_simp e new_e,
return ((), new_e, pr)
| _ := failed
end
/-
This is the main heuristic used alongside the elim_cast and move_cast lemmas.
An expression of the shape: op (↑(x : α) : γ) (↑(y : β) : γ)
is rewritten as: op (↑(↑(x : α) : β) : γ) (↑(y : β) : γ)
when the squash_cast lemmas can prove that (↑(x : α) : γ) = (↑(↑(x : α) : β) : γ)
-/
private meta def heur (_ : unit) (e : expr) : tactic (unit × expr × expr) :=
match e with
| (app (expr.app op x) y) :=
do
`(@coe %%α %%δ %%coe1 %%xx) ← return x,
`(@coe %%β %%γ %%coe2 %%yy) ← return y,
success_if_fail $ is_def_eq α β,
is_def_eq δ γ,
(do
coe3 ← mk_app `has_lift_t [α, β] >>= mk_instance',
new_x ← to_expr ``(@coe %%β %%δ %%coe2 (@coe %%α %%β %%coe3 %%xx)),
let new_e := app (app op new_x) y,
eq_x ← aux_simp x new_x,
pr ← mk_congr_arg op eq_x,
pr ← mk_congr_fun pr y,
return ((), new_e, pr)
) <|> (do
coe3 ← mk_app `has_lift_t [β, α] >>= mk_instance',
new_y ← to_expr ``(@coe %%α %%δ %%coe1 (@coe %%β %%α %%coe3 %%yy)),
let new_e := app (app op x) new_y,
eq_y ← aux_simp y new_y,
pr ← mk_congr_arg (app op x) eq_y,
return ((), new_e, pr)
)
| _ := failed
end
/-
simpa is used to discharge proofs
-/
private meta def prove : tactic unit :=
tactic.interactive.simpa none ff [] [] none
private meta def post (s : simp_lemmas) (_ : unit) (e : expr) : tactic (unit × expr × expr) :=
do
r ← mcond (is_prop e) (return `iff) (return `eq),
(new_e, pr) ← s.rewrite e prove r,
pr ← match r with
|`iff := mk_app `propext [pr]
| _ := return pr
end,
return ((), new_e, pr)
/-
Core function
-/
meta def derive (e : expr) : tactic (expr × expr) :=
do
s ← get_cache,
e ← instantiate_mvars e,
let cfg : simp_config := {fail_if_unchanged := ff},
-- step 1: casts are moved upwards and eliminated
((), new_e, pr1) ← simplify_bottom_up ()
(λ a e, post s a e <|> heur a e <|> aux_num a e)
e cfg,
-- step 2: casts are squashed
s ← squash_cast_attr.get_cache,
(new_e, pr2) ← simplify s [] new_e cfg,
guard (¬ new_e =ₐ e),
pr ← mk_eq_trans pr1 pr2,
return (new_e, pr)
end norm_cast
namespace tactic
open tactic expr
open norm_cast
private meta def aux_mod_cast (e : expr) (include_goal : bool := tt) : tactic expr :=
match e with
| local_const _ lc _ _ := do
e ← get_local lc,
replace_at derive [e] include_goal,
get_local lc
| e := do
t ← infer_type e,
e ← assertv `this t e,
replace_at derive [e] include_goal,
get_local `this
end
meta def exact_mod_cast (e : expr) : tactic unit :=
( do
new_e ← aux_mod_cast e,
exact new_e
) <|> fail "exact_mod_cast failed"
meta def apply_mod_cast (e : expr) : tactic (list (name × expr)) :=
( do
new_e ← aux_mod_cast e,
apply new_e
) <|> fail "apply_mod_cast failed"
meta def assumption_mod_cast : tactic unit :=
do {
let cfg : simp_config := {
fail_if_unchanged := ff,
canonize_instances := ff,
canonize_proofs := ff,
proj := ff
},
replace_at derive [] tt,
ctx ← local_context,
try_lst $ ctx.map (λ h, aux_mod_cast h ff >>= tactic.exact)
} <|> fail "assumption_mod_cast failed"
end tactic
namespace tactic.interactive
open tactic interactive tactic.interactive interactive.types expr lean.parser
open norm_cast
local postfix `?`:9001 := optional
/--
Normalize casts at the given locations by moving them "upwards".
As opposed to simp, norm_cast can be used without necessarily
closing the goal.
-/
meta def norm_cast (loc : parse location) : tactic unit :=
do
ns ← loc.get_locals,
tt ← replace_at derive ns loc.include_goal
| fail "norm_cast failed to simplify",
when loc.include_goal $ try tactic.reflexivity,
when loc.include_goal $ try tactic.triv,
when (¬ ns.empty) $ try tactic.contradiction
/--
Rewrite with the given rule and normalize casts between steps.
-/
meta def rw_mod_cast (rs : parse rw_rules) (loc : parse location) : tactic unit :=
( do
let cfg_norm : simp_config := {},
let cfg_rw : rewrite_cfg := {},
ns ← loc.get_locals,
monad.mapm' (λ r : rw_rule, do
save_info r.pos,
replace_at derive ns loc.include_goal,
rw ⟨[r], none⟩ loc {}
) rs.rules,
replace_at derive ns loc.include_goal,
skip
) <|> fail "rw_mod_cast failed"
/--
Normalize the goal and the given expression,
then close the goal with exact.
-/
meta def exact_mod_cast (e : parse texpr) : tactic unit :=
do
e ← i_to_expr e <|> do {
ty ← target,
e ← i_to_expr_strict ``(%%e : %%ty),
pty ← pp ty, ptgt ← pp e,
fail ("exact_mod_cast failed, expression type not directly " ++
"inferrable. Try:\n\nexact_mod_cast ...\nshow " ++
to_fmt pty ++ ",\nfrom " ++ ptgt : format)
},
tactic.exact_mod_cast e
/--
Normalize the goal and the given expression,
then apply the expression to the goal.
-/
meta def apply_mod_cast (e : parse texpr) : tactic unit :=
do
e ← i_to_expr_for_apply e,
concat_tags $ tactic.apply_mod_cast e
/--
Normalize the goal and every expression in the local context,
then close the goal with assumption.
-/
meta def assumption_mod_cast : tactic unit :=
tactic.assumption_mod_cast
/-- `push_cast` rewrites the expression to move casts toward the leaf nodes.
For example, `↑(a + b)` will be written to `↑a + ↑b`.
Equivalent to `simp only with push_cast`.
Can also be used at hypotheses.
-/
meta def push_cast (l : parse location): tactic unit :=
tactic.interactive.simp none tt [] [`push_cast] l
end tactic.interactive
namespace conv.interactive
open conv tactic tactic.interactive interactive interactive.types
open norm_cast (derive)
meta def norm_cast : conv unit := replace_lhs derive
end conv.interactive
@[elim_cast] lemma ge_from_le {α} [has_le α] : ∀ (x y : α), x ≥ y ↔ y ≤ x := λ _ _, iff.rfl
@[elim_cast] lemma gt_from_lt {α} [has_lt α] : ∀ (x y : α), x > y ↔ y < x := λ _ _, iff.rfl
@[elim_cast] lemma ne_from_not_eq {α} : ∀ (x y : α), x ≠ y ↔ ¬(x = y) := λ _ _, iff.rfl
attribute [squash_cast] int.coe_nat_zero
attribute [squash_cast] int.coe_nat_one
attribute [elim_cast] int.nat_abs_of_nat
attribute [move_cast] int.coe_nat_succ
attribute [move_cast] int.coe_nat_add
attribute [move_cast] int.coe_nat_sub
attribute [move_cast] int.coe_nat_mul
@[move_cast] lemma ite_cast {α β : Type} [has_coe α β]
{c : Prop} [decidable c] {a b : α} :
↑(ite c a b) = ite c (↑a : β) (↑b : β) :=
by by_cases h : c; simp [h]
add_hint_tactic "norm_cast at *"
|
2a790a34a20eb8504d67175d030ffb00943b1ab4 | 193da933cf42f2f9188bb47e3c973205bc2abc5c | /14_Relations/00_intro.lean | dc5dce4fbfac40cc1ffdb5914a0ee4422f578f02 | [] | no_license | pandaman64/cs-dm | aa4e2621c7a19e2dae911bc237c33e02fcb0c7a3 | bfd2f5fd2612472e15bd970c7870b5d0dd73bd1c | refs/heads/master | 1,647,620,340,607 | 1,570,055,187,000 | 1,570,055,187,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 21 | lean | -- UNDER CONSTRUCTION |
738af75b70483f1154f54a0ed9df03b53281f025 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/analysis/special_functions/arsinh_auto.lean | 61f29c94269bdfa4dd695f1f554e596900814b77 | [] | no_license | AurelienSaue/Mathlib4_auto | f538cfd0980f65a6361eadea39e6fc639e9dae14 | 590df64109b08190abe22358fabc3eae000943f2 | refs/heads/master | 1,683,906,849,776 | 1,622,564,669,000 | 1,622,564,669,000 | 371,723,747 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,914 | lean | /-
Copyright (c) 2020 James Arthur. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: James Arthur, Chris Hughes, Shing Tak Lam
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.analysis.special_functions.trigonometric
import Mathlib.PostPort
namespace Mathlib
/-!
# Inverse of the sinh function
In this file we prove that sinh is bijective and hence has an
inverse, arsinh.
## Main Results
- `sinh_injective`: The proof that `sinh` is injective
- `sinh_surjective`: The proof that `sinh` is surjective
- `sinh_bijective`: The proof `sinh` is bijective
- `arsinh`: The inverse function of `sinh`
## Tags
arsinh, arcsinh, argsinh, asinh, sinh injective, sinh bijective, sinh surjective
-/
namespace real
/-- `arsinh` is defined using a logarithm, `arsinh x = log (x + sqrt(1 + x^2))`. -/
def arsinh (x : ℝ) : ℝ := log (x + sqrt (1 + x ^ bit0 1))
/-- `sinh` is injective, `∀ a b, sinh a = sinh b → a = b`. -/
theorem sinh_injective : function.injective sinh := strict_mono.injective sinh_strict_mono
/-- `arsinh` is the right inverse of `sinh`. -/
theorem sinh_arsinh (x : ℝ) : sinh (arsinh x) = x := sorry
/-- `sinh` is surjective, `∀ b, ∃ a, sinh a = b`. In this case, we use `a = arsinh b`. -/
theorem sinh_surjective : function.surjective sinh := function.left_inverse.surjective sinh_arsinh
/-- `sinh` is bijective, both injective and surjective. -/
theorem sinh_bijective : function.bijective sinh :=
{ left := sinh_injective, right := sinh_surjective }
/-- A rearrangement and `sqrt` of `real.cosh_sq_sub_sinh_sq`. -/
theorem sqrt_one_add_sinh_sq (x : ℝ) : sqrt (1 + sinh x ^ bit0 1) = cosh x := sorry
/-- `arsinh` is the left inverse of `sinh`. -/
theorem arsinh_sinh (x : ℝ) : arsinh (sinh x) = x :=
function.right_inverse_of_injective_of_left_inverse sinh_injective sinh_arsinh x
end Mathlib |
205de91f64fcc12916bc693c5a47008ce3ba071d | f68ef9a599ec5575db7b285d4960e63c5d464ccc | /Exercises/Lista 7/cap14-LucasMoschen.lean | 41d24b87a5371c0f9fcbc60331b76adb04dce539 | [] | no_license | lucasmoschen/discrete-mathematics | a38d5970cc571b0b9d202bf6a43efeb8ed6f66e3 | 0f1945cc5eb094814c926cd6ae4a8b4c5c579a1e | refs/heads/master | 1,677,111,757,003 | 1,611,500,097,000 | 1,611,500,097,000 | 205,903,359 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 2,108 | lean | -- Lista 7: Capítulo 14
-- Lucas Moschen
-- Exercício 1
section
parameters {A : Type} {R : A → A → Prop}
parameter (irreflR : irreflexive R)
parameter (transR : transitive R)
variables a b c : A
local infix < := R
def R' (a b : A) : Prop := R a b ∨ a = b
local infix ≤ := R'
theorem reflR' (a : A) : a ≤ a :=
begin
have h1: a = a, from eq.refl a,
apply or.inr h1
end
theorem transR' {a b c : A} (h1 : a ≤ b) (h2 : b ≤ c):
a ≤ c :=
or.elim h1
(assume h3: a < b, or.elim h2
(assume h4: b < c, or.inl (transR h3 h4))
(assume h4: b = c, eq.subst h4 h1))
(assume h3: a = b, eq.subst (eq.symm h3) h2)
theorem antisymmR' {a b : A} (h1 : a ≤ b) (h2 : b ≤ a) :
a = b :=
or.elim h1
(assume h: a < b, or.elim h2
(assume h3: b < a, false.elim ((irreflR b) (transR h3 h)))
(assume h3: b = a, eq.symm h3))
(assume h: a = b, h)
end
-- Exercício 2
section
parameters {A : Type} {R : A → A → Prop}
parameter (reflR : reflexive R)
parameter (transR : transitive R)
def S (a b : A) : Prop := R a b ∧ R b a
example : transitive S :=
assume x y z,
assume h1 h2,
and.intro (transR h1.left h2.left) (transR h2.right h1.right)
end
-- Exercício 3
section
parameters {A : Type} {a b c : A} {R : A → A → Prop}
parameter (Rab : R a b)
parameter (Rbc : R b c)
parameter (nRac : ¬ R a c)
-- Prove one of the following two theorems:
theorem R_is_not_strict_partial_order :
¬(irreflexive R ∧ transitive R) :=
assume h: irreflexive R ∧ transitive R,
show false, from nRac (h.right Rab Rbc)
end
-- Exercício 4
open nat
example : 1 ≤ 4 :=
have h1: 1 < 1 + 1, from lt_succ_self 1,
have h2: (1 + 1) < (1 + 1) + 1, from lt_succ_self (1 + 1),
have h3: (1 + 1 + 1) < (1 + 1 + 1) + 1, from lt_succ_self (1 + 1 + 1),
have h4: 4 = 1 + 1 + 1 + 1, by simp,
have h5: 1 ≤ (1 + 1 + 1) + 1, from le_of_lt (lt_trans h1 (lt_trans h2 h3)),
eq.subst h4 h5 |
528247c1d14089f80c1fab579de1f0ff83877276 | a45212b1526d532e6e83c44ddca6a05795113ddc | /src/order/filter/basic.lean | 9dc4d5bff7f2b0e9a70e3716abcdecc9f22d1400 | [
"Apache-2.0"
] | permissive | fpvandoorn/mathlib | b21ab4068db079cbb8590b58fda9cc4bc1f35df4 | b3433a51ea8bc07c4159c1073838fc0ee9b8f227 | refs/heads/master | 1,624,791,089,608 | 1,556,715,231,000 | 1,556,715,231,000 | 165,722,980 | 5 | 0 | Apache-2.0 | 1,552,657,455,000 | 1,547,494,646,000 | Lean | UTF-8 | Lean | false | false | 81,812 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Jeremy Avigad
Theory of filters on sets.
-/
import order.galois_connection order.zorn
import data.set.finite data.list data.pfun
import algebra.pi_instances
import category.applicative
open lattice set
universes u v w x y
local attribute [instance] classical.prop_decidable
namespace lattice
variables {α : Type u} {ι : Sort v}
def complete_lattice.copy (c : complete_lattice α)
(le : α → α → Prop) (eq_le : le = @complete_lattice.le α c)
(top : α) (eq_top : top = @complete_lattice.top α c)
(bot : α) (eq_bot : bot = @complete_lattice.bot α c)
(sup : α → α → α) (eq_sup : sup = @complete_lattice.sup α c)
(inf : α → α → α) (eq_inf : inf = @complete_lattice.inf α c)
(Sup : set α → α) (eq_Sup : Sup = @complete_lattice.Sup α c)
(Inf : set α → α) (eq_Inf : Inf = @complete_lattice.Inf α c) :
complete_lattice α :=
begin
refine { le := le, top := top, bot := bot, sup := sup, inf := inf, Sup := Sup, Inf := Inf, ..};
subst_vars,
exact @complete_lattice.le_refl α c,
exact @complete_lattice.le_trans α c,
exact @complete_lattice.le_antisymm α c,
exact @complete_lattice.le_sup_left α c,
exact @complete_lattice.le_sup_right α c,
exact @complete_lattice.sup_le α c,
exact @complete_lattice.inf_le_left α c,
exact @complete_lattice.inf_le_right α c,
exact @complete_lattice.le_inf α c,
exact @complete_lattice.le_top α c,
exact @complete_lattice.bot_le α c,
exact @complete_lattice.le_Sup α c,
exact @complete_lattice.Sup_le α c,
exact @complete_lattice.Inf_le α c,
exact @complete_lattice.le_Inf α c
end
end lattice
open set lattice
section order
variables {α : Type u} (r : α → α → Prop)
local infix `≼` : 50 := r
lemma directed_on_Union {r} {ι : Sort v} {f : ι → set α} (hd : directed (⊆) f)
(h : ∀x, directed_on r (f x)) : directed_on r (⋃x, f x) :=
by simp only [directed_on, exists_prop, mem_Union, exists_imp_distrib]; exact
assume a₁ b₁ fb₁ a₂ b₂ fb₂,
let ⟨z, zb₁, zb₂⟩ := hd b₁ b₂,
⟨x, xf, xa₁, xa₂⟩ := h z a₁ (zb₁ fb₁) a₂ (zb₂ fb₂) in
⟨x, ⟨z, xf⟩, xa₁, xa₂⟩
end order
theorem directed_of_chain {α β r} [is_refl β r] {f : α → β} {c : set α}
(h : zorn.chain (f ⁻¹'o r) c) :
directed r (λx:{a:α // a ∈ c}, f (x.val)) :=
assume ⟨a, ha⟩ ⟨b, hb⟩, classical.by_cases
(assume : a = b, by simp only [this, exists_prop, and_self, subtype.exists];
exact ⟨b, hb, refl _⟩)
(assume : a ≠ b, (h a ha b hb this).elim
(λ h : r (f a) (f b), ⟨⟨b, hb⟩, h, refl _⟩)
(λ h : r (f b) (f a), ⟨⟨a, ha⟩, refl _, h⟩))
structure filter (α : Type*) :=
(sets : set (set α))
(univ_sets : set.univ ∈ sets)
(sets_of_superset {x y} : x ∈ sets → x ⊆ y → y ∈ sets)
(inter_sets {x y} : x ∈ sets → y ∈ sets → x ∩ y ∈ sets)
/-- If `F` is a filter on `α`, and `U` a subset of `α` then we can write `U ∈ F` as on paper. -/
@[reducible]
instance {α : Type*}: has_mem (set α) (filter α) := ⟨λ U F, U ∈ F.sets⟩
namespace filter
variables {α : Type u} {f g : filter α} {s t : set α}
lemma filter_eq : ∀{f g : filter α}, f.sets = g.sets → f = g
| ⟨a, _, _, _⟩ ⟨._, _, _, _⟩ rfl := rfl
lemma filter_eq_iff : f = g ↔ f.sets = g.sets :=
⟨congr_arg _, filter_eq⟩
protected lemma ext_iff : f = g ↔ ∀ s, s ∈ f ↔ s ∈ g :=
by rw [filter_eq_iff, ext_iff]
@[extensionality]
protected lemma ext : (∀ s, s ∈ f ↔ s ∈ g) → f = g :=
filter.ext_iff.2
lemma univ_mem_sets : univ ∈ f :=
f.univ_sets
lemma mem_sets_of_superset : ∀{x y : set α}, x ∈ f → x ⊆ y → y ∈ f :=
f.sets_of_superset
lemma inter_mem_sets : ∀{s t}, s ∈ f → t ∈ f → s ∩ t ∈ f :=
f.inter_sets
lemma univ_mem_sets' (h : ∀ a, a ∈ s): s ∈ f :=
mem_sets_of_superset univ_mem_sets (assume x _, h x)
lemma mp_sets (hs : s ∈ f) (h : {x | x ∈ s → x ∈ t} ∈ f) : t ∈ f :=
mem_sets_of_superset (inter_mem_sets hs h) $ assume x ⟨h₁, h₂⟩, h₂ h₁
lemma congr_sets (h : {x | x ∈ s ↔ x ∈ t} ∈ f) : s ∈ f ↔ t ∈ f :=
⟨λ hs, mp_sets hs (mem_sets_of_superset h (λ x, iff.mp)),
λ hs, mp_sets hs (mem_sets_of_superset h (λ x, iff.mpr))⟩
lemma Inter_mem_sets {β : Type v} {s : β → set α} {is : set β} (hf : finite is) :
(∀i∈is, s i ∈ f) → (⋂i∈is, s i) ∈ f :=
finite.induction_on hf
(assume hs, by simp only [univ_mem_sets, mem_empty_eq, Inter_neg, Inter_univ, not_false_iff])
(assume i is _ hf hi hs,
have h₁ : s i ∈ f, from hs i (by simp),
have h₂ : (⋂x∈is, s x) ∈ f, from hi $ assume a ha, hs _ $ by simp only [ha, mem_insert_iff, or_true],
by simp [inter_mem_sets h₁ h₂])
lemma exists_sets_subset_iff : (∃t ∈ f, t ⊆ s) ↔ s ∈ f :=
⟨assume ⟨t, ht, ts⟩, mem_sets_of_superset ht ts, assume hs, ⟨s, hs, subset.refl _⟩⟩
lemma monotone_mem_sets {f : filter α} : monotone (λs, s ∈ f) :=
assume s t hst h, mem_sets_of_superset h hst
end filter
namespace tactic.interactive
open tactic interactive
/-- `filter_upwards [h1, ⋯, hn]` replaces a goal of the form `s ∈ f`
and terms `h1 : t1 ∈ f, ⋯, hn : tn ∈ f` with `∀x, x ∈ t1 → ⋯ → x ∈ tn → x ∈ s`.
`filter_upwards [h1, ⋯, hn] e` is a short form for `{ filter_upwards [h1, ⋯, hn], exact e }`.
-/
meta def filter_upwards
(s : parse types.pexpr_list)
(e' : parse $ optional types.texpr) : tactic unit :=
do
s.reverse.mmap (λ e, eapplyc `filter.mp_sets >> eapply e),
eapplyc `filter.univ_mem_sets',
match e' with
| some e := interactive.exact e
| none := skip
end
end tactic.interactive
namespace filter
variables {α : Type u} {β : Type v} {γ : Type w} {ι : Sort x}
section principal
/-- The principal filter of `s` is the collection of all supersets of `s`. -/
def principal (s : set α) : filter α :=
{ sets := {t | s ⊆ t},
univ_sets := subset_univ s,
sets_of_superset := assume x y hx hy, subset.trans hx hy,
inter_sets := assume x y, subset_inter }
instance : inhabited (filter α) :=
⟨principal ∅⟩
@[simp] lemma mem_principal_sets {s t : set α} : s ∈ principal t ↔ t ⊆ s := iff.rfl
lemma mem_principal_self (s : set α) : s ∈ principal s := subset.refl _
end principal
section join
/-- The join of a filter of filters is defined by the relation `s ∈ join f ↔ {t | s ∈ t} ∈ f`. -/
def join (f : filter (filter α)) : filter α :=
{ sets := {s | {t : filter α | s ∈ t} ∈ f},
univ_sets := by simp only [univ_mem_sets, mem_set_of_eq]; exact univ_mem_sets,
sets_of_superset := assume x y hx xy,
mem_sets_of_superset hx $ assume f h, mem_sets_of_superset h xy,
inter_sets := assume x y hx hy,
mem_sets_of_superset (inter_mem_sets hx hy) $ assume f ⟨h₁, h₂⟩, inter_mem_sets h₁ h₂ }
@[simp] lemma mem_join_sets {s : set α} {f : filter (filter α)} :
s ∈ join f ↔ {t | s ∈ filter.sets t} ∈ f := iff.rfl
end join
section lattice
instance : partial_order (filter α) :=
{ le := λf g, g.sets ⊆ f.sets,
le_antisymm := assume a b h₁ h₂, filter_eq $ subset.antisymm h₂ h₁,
le_refl := assume a, subset.refl _,
le_trans := assume a b c h₁ h₂, subset.trans h₂ h₁ }
theorem le_def {f g : filter α} : f ≤ g ↔ ∀ x ∈ g, x ∈ f := iff.rfl
/-- `generate_sets g s`: `s` is in the filter closure of `g`. -/
inductive generate_sets (g : set (set α)) : set α → Prop
| basic {s : set α} : s ∈ g → generate_sets s
| univ {} : generate_sets univ
| superset {s t : set α} : generate_sets s → s ⊆ t → generate_sets t
| inter {s t : set α} : generate_sets s → generate_sets t → generate_sets (s ∩ t)
/-- `generate g` is the smallest filter containing the sets `g`. -/
def generate (g : set (set α)) : filter α :=
{ sets := {s | generate_sets g s},
univ_sets := generate_sets.univ,
sets_of_superset := assume x y, generate_sets.superset,
inter_sets := assume s t, generate_sets.inter }
lemma sets_iff_generate {s : set (set α)} {f : filter α} : f ≤ filter.generate s ↔ s ⊆ f.sets :=
iff.intro
(assume h u hu, h $ generate_sets.basic $ hu)
(assume h u hu, hu.rec_on h univ_mem_sets
(assume x y _ hxy hx, mem_sets_of_superset hx hxy)
(assume x y _ _ hx hy, inter_mem_sets hx hy))
protected def mk_of_closure (s : set (set α)) (hs : (generate s).sets = s) : filter α :=
{ sets := s,
univ_sets := hs ▸ (univ_mem_sets : univ ∈ generate s),
sets_of_superset := assume x y, hs ▸ (mem_sets_of_superset : x ∈ generate s → x ⊆ y → y ∈ generate s),
inter_sets := assume x y, hs ▸ (inter_mem_sets : x ∈ generate s → y ∈ generate s → x ∩ y ∈ generate s) }
lemma mk_of_closure_sets {s : set (set α)} {hs : (generate s).sets = s} :
filter.mk_of_closure s hs = generate s :=
filter.ext $ assume u,
show u ∈ (filter.mk_of_closure s hs).sets ↔ u ∈ (generate s).sets, from hs.symm ▸ iff.refl _
/- Galois insertion from sets of sets into a filters. -/
def gi_generate (α : Type*) :
@galois_insertion (set (set α)) (order_dual (filter α)) _ _ filter.generate filter.sets :=
{ gc := assume s f, sets_iff_generate,
le_l_u := assume f u, generate_sets.basic,
choice := λs hs, filter.mk_of_closure s (le_antisymm hs $ sets_iff_generate.1 $ le_refl _),
choice_eq := assume s hs, mk_of_closure_sets }
/-- The infimum of filters is the filter generated by intersections
of elements of the two filters. -/
instance : has_inf (filter α) := ⟨λf g : filter α,
{ sets := {s | ∃ (a ∈ f) (b ∈ g), a ∩ b ⊆ s },
univ_sets := ⟨_, univ_mem_sets, _, univ_mem_sets, inter_subset_left _ _⟩,
sets_of_superset := assume x y ⟨a, ha, b, hb, h⟩ xy, ⟨a, ha, b, hb, subset.trans h xy⟩,
inter_sets := assume x y ⟨a, ha, b, hb, hx⟩ ⟨c, hc, d, hd, hy⟩,
⟨_, inter_mem_sets ha hc, _, inter_mem_sets hb hd,
calc a ∩ c ∩ (b ∩ d) = (a ∩ b) ∩ (c ∩ d) : by ac_refl
... ⊆ x ∩ y : inter_subset_inter hx hy⟩ }⟩
@[simp] lemma mem_inf_sets {f g : filter α} {s : set α} :
s ∈ f ⊓ g ↔ ∃t₁∈f.sets, ∃t₂∈g.sets, t₁ ∩ t₂ ⊆ s := iff.rfl
lemma mem_inf_sets_of_left {f g : filter α} {s : set α} (h : s ∈ f) : s ∈ f ⊓ g :=
⟨s, h, univ, univ_mem_sets, inter_subset_left _ _⟩
lemma mem_inf_sets_of_right {f g : filter α} {s : set α} (h : s ∈ g) : s ∈ f ⊓ g :=
⟨univ, univ_mem_sets, s, h, inter_subset_right _ _⟩
lemma inter_mem_inf_sets {α : Type u} {f g : filter α} {s t : set α}
(hs : s ∈ f) (ht : t ∈ g) : s ∩ t ∈ f ⊓ g :=
inter_mem_sets (mem_inf_sets_of_left hs) (mem_inf_sets_of_right ht)
instance : has_top (filter α) :=
⟨{ sets := {s | ∀x, x ∈ s},
univ_sets := assume x, mem_univ x,
sets_of_superset := assume x y hx hxy a, hxy (hx a),
inter_sets := assume x y hx hy a, mem_inter (hx _) (hy _) }⟩
lemma mem_top_sets_iff_forall {s : set α} : s ∈ (⊤ : filter α) ↔ (∀x, x ∈ s) :=
iff.refl _
@[simp] lemma mem_top_sets {s : set α} : s ∈ (⊤ : filter α) ↔ s = univ :=
by rw [mem_top_sets_iff_forall, eq_univ_iff_forall]
section complete_lattice
/- We lift the complete lattice along the Galois connection `generate` / `sets`. Unfortunately,
we want to have different definitional equalities for the lattice operations. So we define them
upfront and change the lattice operations for the complete lattice instance. -/
private def original_complete_lattice : complete_lattice (filter α) :=
@order_dual.lattice.complete_lattice _ (gi_generate α).lift_complete_lattice
local attribute [instance] original_complete_lattice
instance : complete_lattice (filter α) := original_complete_lattice.copy
/- le -/ filter.partial_order.le rfl
/- top -/ (filter.lattice.has_top).1
(top_unique $ assume s hs, by have := univ_mem_sets ; finish)
/- bot -/ _ rfl
/- sup -/ _ rfl
/- inf -/ (filter.lattice.has_inf).1
begin
ext f g : 2,
exact le_antisymm
(le_inf (assume s, mem_inf_sets_of_left) (assume s, mem_inf_sets_of_right))
(assume s ⟨a, ha, b, hb, hs⟩, show s ∈ complete_lattice.inf f g, from
mem_sets_of_superset (inter_mem_sets
(@inf_le_left (filter α) _ _ _ _ ha)
(@inf_le_right (filter α) _ _ _ _ hb)) hs)
end
/- Sup -/ (join ∘ principal) (by ext s x; exact (@mem_bInter_iff _ _ s filter.sets x).symm)
/- Inf -/ _ rfl
end complete_lattice
lemma bot_sets_eq : (⊥ : filter α).sets = univ := rfl
lemma sup_sets_eq {f g : filter α} : (f ⊔ g).sets = f.sets ∩ g.sets :=
(gi_generate α).gc.u_inf
lemma Sup_sets_eq {s : set (filter α)} : (Sup s).sets = (⋂f∈s, (f:filter α).sets) :=
(gi_generate α).gc.u_Inf
lemma supr_sets_eq {f : ι → filter α} : (supr f).sets = (⋂i, (f i).sets) :=
(gi_generate α).gc.u_infi
lemma generate_empty : filter.generate ∅ = (⊤ : filter α) :=
(gi_generate α).gc.l_bot
lemma generate_univ : filter.generate univ = (⊥ : filter α) :=
mk_of_closure_sets.symm
lemma generate_union {s t : set (set α)} :
filter.generate (s ∪ t) = filter.generate s ⊓ filter.generate t :=
(gi_generate α).gc.l_sup
lemma generate_Union {s : ι → set (set α)} :
filter.generate (⋃ i, s i) = (⨅ i, filter.generate (s i)) :=
(gi_generate α).gc.l_supr
@[simp] lemma mem_bot_sets {s : set α} : s ∈ (⊥ : filter α) :=
trivial
@[simp] lemma mem_sup_sets {f g : filter α} {s : set α} :
s ∈ f ⊔ g ↔ s ∈ f ∧ s ∈ g :=
iff.rfl
@[simp] lemma mem_Sup_sets {x : set α} {s : set (filter α)} :
x ∈ Sup s ↔ (∀f∈s, x ∈ (f:filter α)) :=
iff.rfl
@[simp] lemma mem_supr_sets {x : set α} {f : ι → filter α} :
x ∈ supr f ↔ (∀i, x ∈ f i) :=
by simp only [supr_sets_eq, iff_self, mem_Inter]
@[simp] lemma le_principal_iff {s : set α} {f : filter α} : f ≤ principal s ↔ s ∈ f :=
show (∀{t}, s ⊆ t → t ∈ f) ↔ s ∈ f,
from ⟨assume h, h (subset.refl s), assume hs t ht, mem_sets_of_superset hs ht⟩
lemma principal_mono {s t : set α} : principal s ≤ principal t ↔ s ⊆ t :=
by simp only [le_principal_iff, iff_self, mem_principal_sets]
lemma monotone_principal : monotone (principal : set α → filter α) :=
by simp only [monotone, principal_mono]; exact assume a b h, h
@[simp] lemma principal_eq_iff_eq {s t : set α} : principal s = principal t ↔ s = t :=
by simp only [le_antisymm_iff, le_principal_iff, mem_principal_sets]; refl
@[simp] lemma join_principal_eq_Sup {s : set (filter α)} : join (principal s) = Sup s := rfl
/- lattice equations -/
lemma empty_in_sets_eq_bot {f : filter α} : ∅ ∈ f ↔ f = ⊥ :=
⟨assume h, bot_unique $ assume s _, mem_sets_of_superset h (empty_subset s),
assume : f = ⊥, this.symm ▸ mem_bot_sets⟩
lemma inhabited_of_mem_sets {f : filter α} {s : set α} (hf : f ≠ ⊥) (hs : s ∈ f) :
∃x, x ∈ s :=
have ∅ ∉ f.sets, from assume h, hf $ empty_in_sets_eq_bot.mp h,
have s ≠ ∅, from assume h, this (h ▸ hs),
exists_mem_of_ne_empty this
lemma filter_eq_bot_of_not_nonempty {f : filter α} (ne : ¬ nonempty α) : f = ⊥ :=
empty_in_sets_eq_bot.mp $ univ_mem_sets' $ assume x, false.elim (ne ⟨x⟩)
lemma forall_sets_neq_empty_iff_neq_bot {f : filter α} :
(∀ (s : set α), s ∈ f → s ≠ ∅) ↔ f ≠ ⊥ :=
by
simp only [(@empty_in_sets_eq_bot α f).symm, ne.def];
exact ⟨assume h hs, h _ hs rfl, assume h s hs eq, h $ eq ▸ hs⟩
lemma mem_sets_of_neq_bot {f : filter α} {s : set α} (h : f ⊓ principal (-s) = ⊥) : s ∈ f :=
have ∅ ∈ f ⊓ principal (- s), from h.symm ▸ mem_bot_sets,
let ⟨s₁, hs₁, s₂, (hs₂ : -s ⊆ s₂), (hs : s₁ ∩ s₂ ⊆ ∅)⟩ := this in
by filter_upwards [hs₁] assume a ha, classical.by_contradiction $ assume ha', hs ⟨ha, hs₂ ha'⟩
lemma infi_sets_eq {f : ι → filter α} (h : directed (≥) f) (ne : nonempty ι) :
(infi f).sets = (⋃ i, (f i).sets) :=
let ⟨i⟩ := ne, u := { filter .
sets := (⋃ i, (f i).sets),
univ_sets := by simp only [mem_Union]; exact ⟨i, univ_mem_sets⟩,
sets_of_superset := by simp only [mem_Union, exists_imp_distrib];
intros x y i hx hxy; exact ⟨i, mem_sets_of_superset hx hxy⟩,
inter_sets :=
begin
simp only [mem_Union, exists_imp_distrib],
assume x y a hx b hy,
rcases h a b with ⟨c, ha, hb⟩,
exact ⟨c, inter_mem_sets (ha hx) (hb hy)⟩
end } in
subset.antisymm
(show u ≤ infi f, from le_infi $ assume i, le_supr (λi, (f i).sets) i)
(Union_subset $ assume i, infi_le f i)
lemma mem_infi {f : ι → filter α} (h : directed (≥) f) (ne : nonempty ι) (s):
s ∈ infi f ↔ s ∈ ⋃ i, (f i).sets :=
show s ∈ (infi f).sets ↔ s ∈ ⋃ i, (f i).sets, by rw infi_sets_eq h ne
lemma infi_sets_eq' {f : β → filter α} {s : set β}
(h : directed_on (f ⁻¹'o (≥)) s) (ne : ∃i, i ∈ s) :
(⨅ i∈s, f i).sets = (⋃ i ∈ s, (f i).sets) :=
let ⟨i, hi⟩ := ne in
calc (⨅ i ∈ s, f i).sets = (⨅ t : {t // t ∈ s}, (f t.val)).sets : by rw [infi_subtype]; refl
... = (⨆ t : {t // t ∈ s}, (f t.val).sets) : infi_sets_eq
(assume ⟨x, hx⟩ ⟨y, hy⟩, match h x hx y hy with ⟨z, h₁, h₂, h₃⟩ := ⟨⟨z, h₁⟩, h₂, h₃⟩ end)
⟨⟨i, hi⟩⟩
... = (⨆ t ∈ {t | t ∈ s}, (f t).sets) : by rw [supr_subtype]; refl
lemma infi_sets_eq_finite (f : ι → filter α) :
(⨅i, f i).sets = (⋃t:finset (plift ι), (⨅i∈t, f (plift.down i)).sets) :=
begin
rw [infi_eq_infi_finset, infi_sets_eq],
exact (directed_of_sup $ λs₁ s₂ hs, infi_le_infi $ λi, infi_le_infi_const $ λh, hs h),
apply_instance
end
lemma mem_infi_finite {f : ι → filter α} (s):
s ∈ infi f ↔ s ∈ ⋃t:finset (plift ι), (⨅i∈t, f (plift.down i)).sets :=
show s ∈ (infi f).sets ↔ s ∈ ⋃t:finset (plift ι), (⨅i∈t, f (plift.down i)).sets,
by rw infi_sets_eq_finite
@[simp] lemma sup_join {f₁ f₂ : filter (filter α)} : (join f₁ ⊔ join f₂) = join (f₁ ⊔ f₂) :=
filter_eq $ set.ext $ assume x,
by simp only [supr_sets_eq, join, mem_sup_sets, iff_self, mem_set_of_eq]
@[simp] lemma supr_join {ι : Sort w} {f : ι → filter (filter α)} :
(⨆x, join (f x)) = join (⨆x, f x) :=
filter_eq $ set.ext $ assume x,
by simp only [supr_sets_eq, join, iff_self, mem_Inter, mem_set_of_eq]
instance : bounded_distrib_lattice (filter α) :=
{ le_sup_inf :=
begin
assume x y z s,
simp only [and_assoc, mem_inf_sets, mem_sup_sets, exists_prop, exists_imp_distrib, and_imp],
intros hs t₁ ht₁ t₂ ht₂ hts,
exact ⟨s ∪ t₁,
x.sets_of_superset hs $ subset_union_left _ _,
y.sets_of_superset ht₁ $ subset_union_right _ _,
s ∪ t₂,
x.sets_of_superset hs $ subset_union_left _ _,
z.sets_of_superset ht₂ $ subset_union_right _ _,
subset.trans (@le_sup_inf (set α) _ _ _ _) (union_subset (subset.refl _) hts)⟩
end,
..filter.lattice.complete_lattice }
/- the complementary version with ⨆i, f ⊓ g i does not hold! -/
lemma infi_sup_eq {f : filter α} {g : ι → filter α} : (⨅ x, f ⊔ g x) = f ⊔ infi g :=
begin
refine le_antisymm _ (le_infi $ assume i, sup_le_sup (le_refl f) $ infi_le _ _),
rintros t ⟨h₁, h₂⟩,
rw [infi_sets_eq_finite] at h₂,
simp only [mem_Union, (finset.inf_eq_infi _ _).symm] at h₂,
rcases h₂ with ⟨s, hs⟩,
suffices : (⨅i, f ⊔ g i) ≤ f ⊔ s.inf (λi, g i.down), { exact this ⟨h₁, hs⟩ },
refine finset.induction_on s _ _,
{ exact le_sup_right_of_le le_top },
{ rintros ⟨i⟩ s his ih,
rw [finset.inf_insert, sup_inf_left],
exact le_inf (infi_le _ _) ih }
end
lemma mem_infi_sets_finset {s : finset α} {f : α → filter β} :
∀t, t ∈ (⨅a∈s, f a) ↔ (∃p:α → set β, (∀a∈s, p a ∈ f a) ∧ (⋂a∈s, p a) ⊆ t) :=
show ∀t, t ∈ (⨅a∈s, f a) ↔ (∃p:α → set β, (∀a∈s, p a ∈ f a) ∧ (⨅a∈s, p a) ≤ t),
begin
simp only [(finset.inf_eq_infi _ _).symm],
refine finset.induction_on s _ _,
{ simp only [finset.not_mem_empty, false_implies_iff, finset.inf_empty, top_le_iff,
imp_true_iff, mem_top_sets, true_and, exists_const],
intros; refl },
{ intros a s has ih t,
simp only [ih, finset.forall_mem_insert, finset.inf_insert, mem_inf_sets,
exists_prop, iff_iff_implies_and_implies, exists_imp_distrib, and_imp, and_assoc] {contextual := tt},
split,
{ intros t₁ ht₁ t₂ p hp ht₂ ht,
existsi function.update p a t₁,
have : ∀a'∈s, function.update p a t₁ a' = p a',
from assume a' ha',
have a' ≠ a, from assume h, has $ h ▸ ha',
function.update_noteq this,
have eq : s.inf (λj, function.update p a t₁ j) = s.inf (λj, p j) :=
finset.inf_congr rfl this,
simp only [this, ht₁, hp, function.update_same, true_and, imp_true_iff, eq] {contextual := tt},
exact subset.trans (inter_subset_inter (subset.refl _) ht₂) ht },
assume p hpa hp ht,
exact ⟨p a, hpa, (s.inf p), ⟨⟨p, hp, le_refl _⟩, ht⟩⟩ }
end
/- principal equations -/
@[simp] lemma inf_principal {s t : set α} : principal s ⊓ principal t = principal (s ∩ t) :=
le_antisymm
(by simp; exact ⟨s, subset.refl s, t, subset.refl t, by simp⟩)
(by simp [le_inf_iff, inter_subset_left, inter_subset_right])
@[simp] lemma sup_principal {s t : set α} : principal s ⊔ principal t = principal (s ∪ t) :=
filter_eq $ set.ext $
by simp only [union_subset_iff, union_subset_iff, mem_sup_sets, forall_const, iff_self, mem_principal_sets]
@[simp] lemma supr_principal {ι : Sort w} {s : ι → set α} : (⨆x, principal (s x)) = principal (⋃i, s i) :=
filter_eq $ set.ext $ assume x, by simp only [supr_sets_eq, mem_principal_sets, mem_Inter];
exact (@supr_le_iff (set α) _ _ _ _).symm
lemma principal_univ : principal (univ : set α) = ⊤ :=
top_unique $ by simp only [le_principal_iff, mem_top_sets, eq_self_iff_true]
lemma principal_empty : principal (∅ : set α) = ⊥ :=
bot_unique $ assume s _, empty_subset _
@[simp] lemma principal_eq_bot_iff {s : set α} : principal s = ⊥ ↔ s = ∅ :=
⟨assume h, principal_eq_iff_eq.mp $ by simp only [principal_empty, h, eq_self_iff_true],
assume h, by simp only [h, principal_empty, eq_self_iff_true]⟩
lemma inf_principal_eq_bot {f : filter α} {s : set α} (hs : -s ∈ f) : f ⊓ principal s = ⊥ :=
empty_in_sets_eq_bot.mp ⟨_, hs, s, mem_principal_self s, assume x ⟨h₁, h₂⟩, h₁ h₂⟩
theorem mem_inf_principal (f : filter α) (s t : set α) :
s ∈ f ⊓ principal t ↔ { x | x ∈ t → x ∈ s } ∈ f :=
begin
simp only [mem_inf_sets, mem_principal_sets, exists_prop], split,
{ rintros ⟨u, ul, v, tsubv, uvinter⟩,
apply filter.mem_sets_of_superset ul,
intros x xu xt, exact uvinter ⟨xu, tsubv xt⟩ },
intro h, refine ⟨_, h, t, set.subset.refl t, _⟩,
rintros x ⟨hx, xt⟩,
exact hx xt
end
end lattice
section map
/-- The forward map of a filter -/
def map (m : α → β) (f : filter α) : filter β :=
{ sets := preimage m ⁻¹' f.sets,
univ_sets := univ_mem_sets,
sets_of_superset := assume s t hs st, mem_sets_of_superset hs $ preimage_mono st,
inter_sets := assume s t hs ht, inter_mem_sets hs ht }
@[simp] lemma map_principal {s : set α} {f : α → β} :
map f (principal s) = principal (set.image f s) :=
filter_eq $ set.ext $ assume a, image_subset_iff.symm
variables {f : filter α} {m : α → β} {m' : β → γ} {s : set α} {t : set β}
@[simp] lemma mem_map : t ∈ map m f ↔ {x | m x ∈ t} ∈ f := iff.rfl
lemma image_mem_map (hs : s ∈ f) : m '' s ∈ map m f :=
f.sets_of_superset hs $ subset_preimage_image m s
lemma range_mem_map : range m ∈ map m f :=
by rw ←image_univ; exact image_mem_map univ_mem_sets
lemma mem_map_sets_iff : t ∈ map m f ↔ (∃s∈f, m '' s ⊆ t) :=
iff.intro
(assume ht, ⟨set.preimage m t, ht, image_preimage_subset _ _⟩)
(assume ⟨s, hs, ht⟩, mem_sets_of_superset (image_mem_map hs) ht)
@[simp] lemma map_id : filter.map id f = f :=
filter_eq $ rfl
@[simp] lemma map_compose : filter.map m' ∘ filter.map m = filter.map (m' ∘ m) :=
funext $ assume _, filter_eq $ rfl
@[simp] lemma map_map : filter.map m' (filter.map m f) = filter.map (m' ∘ m) f :=
congr_fun (@@filter.map_compose m m') f
end map
section comap
/-- The inverse map of a filter -/
def comap (m : α → β) (f : filter β) : filter α :=
{ sets := { s | ∃t∈ f, m ⁻¹' t ⊆ s },
univ_sets := ⟨univ, univ_mem_sets, by simp only [subset_univ, preimage_univ]⟩,
sets_of_superset := assume a b ⟨a', ha', ma'a⟩ ab,
⟨a', ha', subset.trans ma'a ab⟩,
inter_sets := assume a b ⟨a', ha₁, ha₂⟩ ⟨b', hb₁, hb₂⟩,
⟨a' ∩ b', inter_mem_sets ha₁ hb₁, inter_subset_inter ha₂ hb₂⟩ }
end comap
/-- The cofinite filter is the filter of subsets whose complements are finite. -/
def cofinite : filter α :=
{ sets := {s | finite (- s)},
univ_sets := by simp only [compl_univ, finite_empty, mem_set_of_eq],
sets_of_superset := assume s t (hs : finite (-s)) (st: s ⊆ t),
finite_subset hs $ @lattice.neg_le_neg (set α) _ _ _ st,
inter_sets := assume s t (hs : finite (-s)) (ht : finite (-t)),
by simp only [compl_inter, finite_union, ht, hs, mem_set_of_eq] }
lemma cofinite_ne_bot (hi : set.infinite (@set.univ α)) : @cofinite α ≠ ⊥ :=
forall_sets_neq_empty_iff_neq_bot.mp
$ λ s hs hn, by change set.finite _ at hs;
rw [hn, set.compl_empty] at hs; exact hi hs
/-- The monadic bind operation on filter is defined the usual way in terms of `map` and `join`.
Unfortunately, this `bind` does not result in the expected applicative. See `filter.seq` for the
applicative instance. -/
def bind (f : filter α) (m : α → filter β) : filter β := join (map m f)
/-- The applicative sequentiation operation. This is not induced by the bind operation. -/
def seq (f : filter (α → β)) (g : filter α) : filter β :=
⟨{ s | ∃u∈ f, ∃t∈ g, (∀m∈u, ∀x∈t, (m : α → β) x ∈ s) },
⟨univ, univ_mem_sets, univ, univ_mem_sets, by simp only [forall_prop_of_true, mem_univ, forall_true_iff]⟩,
assume s₀ s₁ ⟨t₀, t₁, h₀, h₁, h⟩ hst, ⟨t₀, t₁, h₀, h₁, assume x hx y hy, hst $ h _ hx _ hy⟩,
assume s₀ s₁ ⟨t₀, ht₀, t₁, ht₁, ht⟩ ⟨u₀, hu₀, u₁, hu₁, hu⟩,
⟨t₀ ∩ u₀, inter_mem_sets ht₀ hu₀, t₁ ∩ u₁, inter_mem_sets ht₁ hu₁,
assume x ⟨hx₀, hx₁⟩ x ⟨hy₀, hy₁⟩, ⟨ht _ hx₀ _ hy₀, hu _ hx₁ _ hy₁⟩⟩⟩
instance : has_pure filter := ⟨λ(α : Type u) x, principal {x}⟩
instance : has_bind filter := ⟨@filter.bind⟩
instance : has_seq filter := ⟨@filter.seq⟩
instance : functor filter := { map := @filter.map }
section
-- this section needs to be before applicative, otherwise the wrong instance will be chosen
protected def monad : monad filter := { map := @filter.map }
local attribute [instance] filter.monad
protected def is_lawful_monad : is_lawful_monad filter :=
{ id_map := assume α f, filter_eq rfl,
pure_bind := assume α β a f, by simp only [bind, Sup_image, image_singleton,
join_principal_eq_Sup, lattice.Sup_singleton, map_principal, eq_self_iff_true],
bind_assoc := assume α β γ f m₁ m₂, filter_eq rfl,
bind_pure_comp_eq_map := assume α β f x, filter_eq $
by simp only [bind, join, map, preimage, principal, set.subset_univ, eq_self_iff_true,
function.comp_app, mem_set_of_eq, singleton_subset_iff] }
end
instance : applicative filter := { map := @filter.map, seq := @filter.seq }
instance : alternative filter :=
{ failure := λα, ⊥,
orelse := λα x y, x ⊔ y }
@[simp] lemma pure_def (x : α) : pure x = principal {x} := rfl
@[simp] lemma mem_pure {a : α} {s : set α} : a ∈ s → s ∈ (pure a : filter α) :=
by simp only [imp_self, pure_def, mem_principal_sets, singleton_subset_iff]; exact id
@[simp] lemma mem_pure_iff {a : α} {s : set α} : s ∈ (pure a : filter α) ↔ a ∈ s :=
by rw [pure_def, mem_principal_sets, set.singleton_subset_iff]
@[simp] lemma map_def {α β} (m : α → β) (f : filter α) : m <$> f = map m f := rfl
@[simp] lemma bind_def {α β} (f : filter α) (m : α → filter β) : f >>= m = bind f m := rfl
/- map and comap equations -/
section map
variables {f f₁ f₂ : filter α} {g g₁ g₂ : filter β} {m : α → β} {m' : β → γ} {s : set α} {t : set β}
@[simp] theorem mem_comap_sets : s ∈ comap m g ↔ ∃t∈ g, m ⁻¹' t ⊆ s := iff.rfl
theorem preimage_mem_comap (ht : t ∈ g) : m ⁻¹' t ∈ comap m g :=
⟨t, ht, subset.refl _⟩
lemma comap_id : comap id f = f :=
le_antisymm (assume s, preimage_mem_comap) (assume s ⟨t, ht, hst⟩, mem_sets_of_superset ht hst)
lemma comap_comap_comp {m : γ → β} {n : β → α} : comap m (comap n f) = comap (n ∘ m) f :=
le_antisymm
(assume c ⟨b, hb, (h : preimage (n ∘ m) b ⊆ c)⟩, ⟨preimage n b, preimage_mem_comap hb, h⟩)
(assume c ⟨b, ⟨a, ha, (h₁ : preimage n a ⊆ b)⟩, (h₂ : preimage m b ⊆ c)⟩,
⟨a, ha, show preimage m (preimage n a) ⊆ c, from subset.trans (preimage_mono h₁) h₂⟩)
@[simp] theorem comap_principal {t : set β} : comap m (principal t) = principal (m ⁻¹' t) :=
filter_eq $ set.ext $ assume s,
⟨assume ⟨u, (hu : t ⊆ u), (b : preimage m u ⊆ s)⟩, subset.trans (preimage_mono hu) b,
assume : preimage m t ⊆ s, ⟨t, subset.refl t, this⟩⟩
lemma map_le_iff_le_comap : map m f ≤ g ↔ f ≤ comap m g :=
⟨assume h s ⟨t, ht, hts⟩, mem_sets_of_superset (h ht) hts, assume h s ht, h ⟨_, ht, subset.refl _⟩⟩
lemma gc_map_comap (m : α → β) : galois_connection (map m) (comap m) :=
assume f g, map_le_iff_le_comap
lemma map_mono (h : f₁ ≤ f₂) : map m f₁ ≤ map m f₂ := (gc_map_comap m).monotone_l h
lemma monotone_map : monotone (map m) | a b := map_mono
lemma comap_mono (h : g₁ ≤ g₂) : comap m g₁ ≤ comap m g₂ := (gc_map_comap m).monotone_u h
lemma monotone_comap : monotone (comap m) | a b := comap_mono
@[simp] lemma map_bot : map m ⊥ = ⊥ := (gc_map_comap m).l_bot
@[simp] lemma map_sup : map m (f₁ ⊔ f₂) = map m f₁ ⊔ map m f₂ := (gc_map_comap m).l_sup
@[simp] lemma map_supr {f : ι → filter α} : map m (⨆i, f i) = (⨆i, map m (f i)) :=
(gc_map_comap m).l_supr
@[simp] lemma comap_top : comap m ⊤ = ⊤ := (gc_map_comap m).u_top
@[simp] lemma comap_inf : comap m (g₁ ⊓ g₂) = comap m g₁ ⊓ comap m g₂ := (gc_map_comap m).u_inf
@[simp] lemma comap_infi {f : ι → filter β} : comap m (⨅i, f i) = (⨅i, comap m (f i)) :=
(gc_map_comap m).u_infi
lemma le_comap_top (f : α → β) (l : filter α) : l ≤ comap f ⊤ :=
by rw [comap_top]; exact le_top
lemma map_comap_le : map m (comap m g) ≤ g := (gc_map_comap m).l_u_le _
lemma le_comap_map : f ≤ comap m (map m f) := (gc_map_comap m).le_u_l _
@[simp] lemma comap_bot : comap m ⊥ = ⊥ :=
bot_unique $ assume s _, ⟨∅, by simp only [mem_bot_sets], by simp only [empty_subset, preimage_empty]⟩
lemma comap_supr {ι} {f : ι → filter β} {m : α → β} :
comap m (supr f) = (⨆i, comap m (f i)) :=
le_antisymm
(assume s hs,
have ∀i, ∃t, t ∈ f i ∧ m ⁻¹' t ⊆ s, by simpa only [mem_comap_sets, exists_prop, mem_supr_sets] using mem_supr_sets.1 hs,
let ⟨t, ht⟩ := classical.axiom_of_choice this in
⟨⋃i, t i, mem_supr_sets.2 $ assume i, (f i).sets_of_superset (ht i).1 (subset_Union _ _),
begin
rw [preimage_Union, Union_subset_iff],
assume i,
exact (ht i).2
end⟩)
(supr_le $ assume i, monotone_comap $ le_supr _ _)
lemma comap_Sup {s : set (filter β)} {m : α → β} : comap m (Sup s) = (⨆f∈s, comap m f) :=
by simp only [Sup_eq_supr, comap_supr, eq_self_iff_true]
lemma comap_sup : comap m (g₁ ⊔ g₂) = comap m g₁ ⊔ comap m g₂ :=
le_antisymm
(assume s ⟨⟨t₁, ht₁, hs₁⟩, ⟨t₂, ht₂, hs₂⟩⟩,
⟨t₁ ∪ t₂,
⟨g₁.sets_of_superset ht₁ (subset_union_left _ _), g₂.sets_of_superset ht₂ (subset_union_right _ _)⟩,
union_subset hs₁ hs₂⟩)
(sup_le (comap_mono le_sup_left) (comap_mono le_sup_right))
lemma map_comap {f : filter β} {m : α → β} (hf : range m ∈ f) : (f.comap m).map m = f :=
le_antisymm
map_comap_le
(assume t' ⟨t, ht, sub⟩, by filter_upwards [ht, hf]; rintros x hxt ⟨y, rfl⟩; exact sub hxt)
lemma comap_map {f : filter α} {m : α → β} (h : ∀ x y, m x = m y → x = y) :
comap m (map m f) = f :=
have ∀s, preimage m (image m s) = s,
from assume s, preimage_image_eq s h,
le_antisymm
(assume s hs, ⟨
image m s,
f.sets_of_superset hs $ by simp only [this, subset.refl],
by simp only [this, subset.refl]⟩)
le_comap_map
lemma le_of_map_le_map_inj' {f g : filter α} {m : α → β} {s : set α}
(hsf : s ∈ f) (hsg : s ∈ g) (hm : ∀x∈s, ∀y∈s, m x = m y → x = y)
(h : map m f ≤ map m g) : f ≤ g :=
assume t ht, by filter_upwards [hsf, h $ image_mem_map (inter_mem_sets hsg ht)]
assume a has ⟨b, ⟨hbs, hb⟩, h⟩,
have b = a, from hm _ hbs _ has h,
this ▸ hb
lemma le_of_map_le_map_inj_iff {f g : filter α} {m : α → β} {s : set α}
(hsf : s ∈ f) (hsg : s ∈ g) (hm : ∀x∈s, ∀y∈s, m x = m y → x = y) :
map m f ≤ map m g ↔ f ≤ g :=
iff.intro (le_of_map_le_map_inj' hsf hsg hm) map_mono
lemma eq_of_map_eq_map_inj' {f g : filter α} {m : α → β} {s : set α}
(hsf : s ∈ f) (hsg : s ∈ g) (hm : ∀x∈s, ∀y∈s, m x = m y → x = y)
(h : map m f = map m g) : f = g :=
le_antisymm
(le_of_map_le_map_inj' hsf hsg hm $ le_of_eq h)
(le_of_map_le_map_inj' hsg hsf hm $ le_of_eq h.symm)
lemma map_inj {f g : filter α} {m : α → β} (hm : ∀ x y, m x = m y → x = y) (h : map m f = map m g) :
f = g :=
have comap m (map m f) = comap m (map m g), by rw h,
by rwa [comap_map hm, comap_map hm] at this
theorem le_map_comap_of_surjective' {f : α → β} {l : filter β} {u : set β} (ul : u ∈ l)
(hf : ∀ y ∈ u, ∃ x, f x = y) :
l ≤ map f (comap f l) :=
assume s ⟨t, tl, ht⟩,
have t ∩ u ⊆ s, from
assume x ⟨xt, xu⟩,
exists.elim (hf x xu) $ λ a faeq,
by { rw ←faeq, apply ht, change f a ∈ t, rw faeq, exact xt },
mem_sets_of_superset (inter_mem_sets tl ul) this
theorem map_comap_of_surjective' {f : α → β} {l : filter β} {u : set β} (ul : u ∈ l)
(hf : ∀ y ∈ u, ∃ x, f x = y) :
map f (comap f l) = l :=
le_antisymm map_comap_le (le_map_comap_of_surjective' ul hf)
theorem le_map_comap_of_surjective {f : α → β} (hf : function.surjective f) (l : filter β) :
l ≤ map f (comap f l) :=
le_map_comap_of_surjective' univ_mem_sets (λ y _, hf y)
theorem map_comap_of_surjective {f : α → β} (hf : function.surjective f) (l : filter β) :
map f (comap f l) = l :=
le_antisymm map_comap_le (le_map_comap_of_surjective hf l)
lemma comap_neq_bot {f : filter β} {m : α → β}
(hm : ∀t∈ f, ∃a, m a ∈ t) : comap m f ≠ ⊥ :=
forall_sets_neq_empty_iff_neq_bot.mp $ assume s ⟨t, ht, t_s⟩,
let ⟨a, (ha : a ∈ preimage m t)⟩ := hm t ht in
neq_bot_of_le_neq_bot (ne_empty_of_mem ha) t_s
lemma comap_neq_bot_of_surj {f : filter β} {m : α → β}
(hf : f ≠ ⊥) (hm : ∀b, ∃a, m a = b) : comap m f ≠ ⊥ :=
comap_neq_bot $ assume t ht,
let
⟨b, (hx : b ∈ t)⟩ := inhabited_of_mem_sets hf ht,
⟨a, (ha : m a = b)⟩ := hm b
in ⟨a, ha.symm ▸ hx⟩
@[simp] lemma map_eq_bot_iff : map m f = ⊥ ↔ f = ⊥ :=
⟨by rw [←empty_in_sets_eq_bot, ←empty_in_sets_eq_bot]; exact id,
assume h, by simp only [h, eq_self_iff_true, map_bot]⟩
lemma map_ne_bot (hf : f ≠ ⊥) : map m f ≠ ⊥ :=
assume h, hf $ by rwa [map_eq_bot_iff] at h
lemma sInter_comap_sets (f : α → β) (F : filter β) :
⋂₀(comap f F).sets = ⋂ U ∈ F, f ⁻¹' U :=
begin
ext x,
suffices : (∀ (A : set α) (B : set β), B ∈ F → f ⁻¹' B ⊆ A → x ∈ A) ↔
∀ (B : set β), B ∈ F → f x ∈ B,
by simp only [mem_sInter, mem_Inter, mem_comap_sets, this, and_imp, mem_comap_sets, exists_prop, mem_sInter,
iff_self, mem_Inter, mem_preimage_eq, exists_imp_distrib],
split,
{ intros h U U_in,
simpa only [set.subset.refl, forall_prop_of_true, mem_preimage_eq] using h (f ⁻¹' U) U U_in },
{ intros h V U U_in f_U_V,
exact f_U_V (h U U_in) },
end
end map
lemma map_cong {m₁ m₂ : α → β} {f : filter α} (h : {x | m₁ x = m₂ x} ∈ f) :
map m₁ f = map m₂ f :=
have ∀(m₁ m₂ : α → β) (h : {x | m₁ x = m₂ x} ∈ f), map m₁ f ≤ map m₂ f,
begin
intros m₁ m₂ h s hs,
show {x | m₁ x ∈ s} ∈ f,
filter_upwards [h, hs],
simp only [subset_def, mem_preimage_eq, mem_set_of_eq, forall_true_iff] {contextual := tt}
end,
le_antisymm (this m₁ m₂ h) (this m₂ m₁ $ mem_sets_of_superset h $ assume x, eq.symm)
-- this is a generic rule for monotone functions:
lemma map_infi_le {f : ι → filter α} {m : α → β} :
map m (infi f) ≤ (⨅ i, map m (f i)) :=
le_infi $ assume i, map_mono $ infi_le _ _
lemma map_infi_eq {f : ι → filter α} {m : α → β} (hf : directed (≥) f) (hι : nonempty ι) :
map m (infi f) = (⨅ i, map m (f i)) :=
le_antisymm
map_infi_le
(assume s (hs : preimage m s ∈ infi f),
have ∃i, preimage m s ∈ f i,
by simp only [infi_sets_eq hf hι, mem_Union] at hs; assumption,
let ⟨i, hi⟩ := this in
have (⨅ i, map m (f i)) ≤ principal s, from
infi_le_of_le i $ by simp only [le_principal_iff, mem_map]; assumption,
by simp only [filter.le_principal_iff] at this; assumption)
lemma map_binfi_eq {ι : Type w} {f : ι → filter α} {m : α → β} {p : ι → Prop}
(h : directed_on (f ⁻¹'o (≥)) {x | p x}) (ne : ∃i, p i) :
map m (⨅i (h : p i), f i) = (⨅i (h: p i), map m (f i)) :=
let ⟨i, hi⟩ := ne in
calc map m (⨅i (h : p i), f i) = map m (⨅i:subtype p, f i.val) : by simp only [infi_subtype, eq_self_iff_true]
... = (⨅i:subtype p, map m (f i.val)) : map_infi_eq
(assume ⟨x, hx⟩ ⟨y, hy⟩, match h x hx y hy with ⟨z, h₁, h₂, h₃⟩ := ⟨⟨z, h₁⟩, h₂, h₃⟩ end)
⟨⟨i, hi⟩⟩
... = (⨅i (h : p i), map m (f i)) : by simp only [infi_subtype, eq_self_iff_true]
lemma map_inf' {f g : filter α} {m : α → β} {t : set α} (htf : t ∈ f) (htg : t ∈ g)
(h : ∀x∈t, ∀y∈t, m x = m y → x = y) : map m (f ⊓ g) = map m f ⊓ map m g :=
begin
refine le_antisymm
(le_inf (map_mono inf_le_left) (map_mono inf_le_right))
(assume s hs, _),
simp only [map, mem_inf_sets, exists_prop, mem_map, mem_preimage_eq, mem_inf_sets] at hs ⊢,
rcases hs with ⟨t₁, h₁, t₂, h₂, hs⟩,
refine ⟨m '' (t₁ ∩ t), _, m '' (t₂ ∩ t), _, _⟩,
{ filter_upwards [h₁, htf] assume a h₁ h₂, mem_image_of_mem _ ⟨h₁, h₂⟩ },
{ filter_upwards [h₂, htg] assume a h₁ h₂, mem_image_of_mem _ ⟨h₁, h₂⟩ },
{ rw [image_inter_on],
{ refine image_subset_iff.2 _,
exact λ x ⟨⟨h₁, _⟩, h₂, _⟩, hs ⟨h₁, h₂⟩ },
{ exact λ x ⟨_, hx⟩ y ⟨_, hy⟩, h x hx y hy } }
end
lemma map_inf {f g : filter α} {m : α → β} (h : ∀ x y, m x = m y → x = y) :
map m (f ⊓ g) = map m f ⊓ map m g :=
map_inf' univ_mem_sets univ_mem_sets (assume x _ y _, h x y)
lemma map_eq_comap_of_inverse {f : filter α} {m : α → β} {n : β → α}
(h₁ : m ∘ n = id) (h₂ : n ∘ m = id) : map m f = comap n f :=
le_antisymm
(assume b ⟨a, ha, (h : preimage n a ⊆ b)⟩, f.sets_of_superset ha $
calc a = preimage (n ∘ m) a : by simp only [h₂, preimage_id, eq_self_iff_true]
... ⊆ preimage m b : preimage_mono h)
(assume b (hb : preimage m b ∈ f),
⟨preimage m b, hb, show preimage (m ∘ n) b ⊆ b, by simp only [h₁]; apply subset.refl⟩)
lemma map_swap_eq_comap_swap {f : filter (α × β)} : prod.swap <$> f = comap prod.swap f :=
map_eq_comap_of_inverse prod.swap_swap_eq prod.swap_swap_eq
lemma le_map {f : filter α} {m : α → β} {g : filter β} (h : ∀s∈ f, m '' s ∈ g) :
g ≤ f.map m :=
assume s hs, mem_sets_of_superset (h _ hs) $ image_preimage_subset _ _
section applicative
@[simp] lemma mem_pure_sets {a : α} {s : set α} :
s ∈ (pure a : filter α) ↔ a ∈ s :=
by simp only [iff_self, pure_def, mem_principal_sets, singleton_subset_iff]
lemma singleton_mem_pure_sets {a : α} : {a} ∈ (pure a : filter α) :=
by simp only [mem_singleton, pure_def, mem_principal_sets, singleton_subset_iff]
@[simp] lemma pure_neq_bot {α : Type u} {a : α} : pure a ≠ (⊥ : filter α) :=
by simp only [pure, has_pure.pure, ne.def, not_false_iff, singleton_ne_empty, principal_eq_bot_iff]
lemma mem_seq_sets_def {f : filter (α → β)} {g : filter α} {s : set β} :
s ∈ f.seq g ↔ (∃u ∈ f, ∃t ∈ g, ∀x∈u, ∀y∈t, (x : α → β) y ∈ s) :=
iff.refl _
lemma mem_seq_sets_iff {f : filter (α → β)} {g : filter α} {s : set β} :
s ∈ f.seq g ↔ (∃u ∈ f, ∃t ∈ g, set.seq u t ⊆ s) :=
by simp only [mem_seq_sets_def, seq_subset, exists_prop, iff_self]
lemma mem_map_seq_iff {f : filter α} {g : filter β} {m : α → β → γ} {s : set γ} :
s ∈ (f.map m).seq g ↔ (∃t u, t ∈ g ∧ u ∈ f ∧ ∀x∈u, ∀y∈t, m x y ∈ s) :=
iff.intro
(assume ⟨t, ht, s, hs, hts⟩, ⟨s, m ⁻¹' t, hs, ht, assume a, hts _⟩)
(assume ⟨t, s, ht, hs, hts⟩, ⟨m '' s, image_mem_map hs, t, ht, assume f ⟨a, has, eq⟩, eq ▸ hts _ has⟩)
lemma seq_mem_seq_sets {f : filter (α → β)} {g : filter α} {s : set (α → β)} {t : set α}
(hs : s ∈ f) (ht : t ∈ g): s.seq t ∈ f.seq g :=
⟨s, hs, t, ht, assume f hf a ha, ⟨f, hf, a, ha, rfl⟩⟩
lemma le_seq {f : filter (α → β)} {g : filter α} {h : filter β}
(hh : ∀t ∈ f, ∀u ∈ g, set.seq t u ∈ h) : h ≤ seq f g :=
assume s ⟨t, ht, u, hu, hs⟩, mem_sets_of_superset (hh _ ht _ hu) $
assume b ⟨m, hm, a, ha, eq⟩, eq ▸ hs _ hm _ ha
lemma seq_mono {f₁ f₂ : filter (α → β)} {g₁ g₂ : filter α}
(hf : f₁ ≤ f₂) (hg : g₁ ≤ g₂) : f₁.seq g₁ ≤ f₂.seq g₂ :=
le_seq $ assume s hs t ht, seq_mem_seq_sets (hf hs) (hg ht)
@[simp] lemma pure_seq_eq_map (g : α → β) (f : filter α) : seq (pure g) f = f.map g :=
begin
refine le_antisymm (le_map $ assume s hs, _) (le_seq $ assume s hs t ht, _),
{ rw ← singleton_seq, apply seq_mem_seq_sets _ hs,
simp only [mem_singleton, pure_def, mem_principal_sets, singleton_subset_iff] },
{ rw mem_pure_sets at hs,
refine sets_of_superset (map g f) (image_mem_map ht) _,
rintros b ⟨a, ha, rfl⟩, exact ⟨g, hs, a, ha, rfl⟩ }
end
@[simp] lemma map_pure (f : α → β) (a : α) : map f (pure a) = pure (f a) :=
le_antisymm
(le_principal_iff.2 $ sets_of_superset (map f (pure a)) (image_mem_map singleton_mem_pure_sets) $
by simp only [image_singleton, mem_singleton, singleton_subset_iff])
(le_map $ assume s, begin
simp only [mem_image, pure_def, mem_principal_sets, singleton_subset_iff],
exact assume has, ⟨a, has, rfl⟩
end)
@[simp] lemma seq_pure (f : filter (α → β)) (a : α) : seq f (pure a) = map (λg:α → β, g a) f :=
begin
refine le_antisymm (le_map $ assume s hs, _) (le_seq $ assume s hs t ht, _),
{ rw ← seq_singleton, exact seq_mem_seq_sets hs
(by simp only [mem_singleton, pure_def, mem_principal_sets, singleton_subset_iff]) },
{ rw mem_pure_sets at ht,
refine sets_of_superset (map (λg:α→β, g a) f) (image_mem_map hs) _,
rintros b ⟨g, hg, rfl⟩, exact ⟨g, hg, a, ht, rfl⟩ }
end
@[simp] lemma seq_assoc (x : filter α) (g : filter (α → β)) (h : filter (β → γ)) :
seq h (seq g x) = seq (seq (map (∘) h) g) x :=
begin
refine le_antisymm (le_seq $ assume s hs t ht, _) (le_seq $ assume s hs t ht, _),
{ rcases mem_seq_sets_iff.1 hs with ⟨u, hu, v, hv, hs⟩,
rcases mem_map_sets_iff.1 hu with ⟨w, hw, hu⟩,
refine mem_sets_of_superset _
(set.seq_mono (subset.trans (set.seq_mono hu (subset.refl _)) hs) (subset.refl _)),
rw ← set.seq_seq,
exact seq_mem_seq_sets hw (seq_mem_seq_sets hv ht) },
{ rcases mem_seq_sets_iff.1 ht with ⟨u, hu, v, hv, ht⟩,
refine mem_sets_of_superset _ (set.seq_mono (subset.refl _) ht),
rw set.seq_seq,
exact seq_mem_seq_sets (seq_mem_seq_sets (image_mem_map hs) hu) hv }
end
lemma prod_map_seq_comm (f : filter α) (g : filter β) :
(map prod.mk f).seq g = seq (map (λb a, (a, b)) g) f :=
begin
refine le_antisymm (le_seq $ assume s hs t ht, _) (le_seq $ assume s hs t ht, _),
{ rcases mem_map_sets_iff.1 hs with ⟨u, hu, hs⟩,
refine mem_sets_of_superset _ (set.seq_mono hs (subset.refl _)),
rw ← set.prod_image_seq_comm,
exact seq_mem_seq_sets (image_mem_map ht) hu },
{ rcases mem_map_sets_iff.1 hs with ⟨u, hu, hs⟩,
refine mem_sets_of_superset _ (set.seq_mono hs (subset.refl _)),
rw set.prod_image_seq_comm,
exact seq_mem_seq_sets (image_mem_map ht) hu }
end
instance : is_lawful_functor (filter : Type u → Type u) :=
{ id_map := assume α f, map_id,
comp_map := assume α β γ f g a, map_map.symm }
instance : is_lawful_applicative (filter : Type u → Type u) :=
{ pure_seq_eq_map := assume α β, pure_seq_eq_map,
map_pure := assume α β, map_pure,
seq_pure := assume α β, seq_pure,
seq_assoc := assume α β γ, seq_assoc }
instance : is_comm_applicative (filter : Type u → Type u) :=
⟨assume α β f g, prod_map_seq_comm f g⟩
lemma {l} seq_eq_filter_seq {α β : Type l} (f : filter (α → β)) (g : filter α) :
f <*> g = seq f g := rfl
end applicative
/- bind equations -/
section bind
@[simp] lemma mem_bind_sets {s : set β} {f : filter α} {m : α → filter β} :
s ∈ bind f m ↔ ∃t ∈ f, ∀x ∈ t, s ∈ m x :=
calc s ∈ bind f m ↔ {a | s ∈ m a} ∈ f : by simp only [bind, mem_map, iff_self, mem_join_sets, mem_set_of_eq]
... ↔ (∃t ∈ f, t ⊆ {a | s ∈ m a}) : exists_sets_subset_iff.symm
... ↔ (∃t ∈ f, ∀x ∈ t, s ∈ m x) : iff.refl _
lemma bind_mono {f : filter α} {g h : α → filter β} (h₁ : {a | g a ≤ h a} ∈ f) :
bind f g ≤ bind f h :=
assume x h₂, show (_ ∈ f), by filter_upwards [h₁, h₂] assume s gh' h', gh' h'
lemma bind_sup {f g : filter α} {h : α → filter β} :
bind (f ⊔ g) h = bind f h ⊔ bind g h :=
by simp only [bind, sup_join, map_sup, eq_self_iff_true]
lemma bind_mono2 {f g : filter α} {h : α → filter β} (h₁ : f ≤ g) :
bind f h ≤ bind g h :=
assume s h', h₁ h'
lemma principal_bind {s : set α} {f : α → filter β} :
(bind (principal s) f) = (⨆x ∈ s, f x) :=
show join (map f (principal s)) = (⨆x ∈ s, f x),
by simp only [Sup_image, join_principal_eq_Sup, map_principal, eq_self_iff_true]
end bind
lemma infi_neq_bot_of_directed {f : ι → filter α}
(hn : nonempty α) (hd : directed (≥) f) (hb : ∀i, f i ≠ ⊥) : (infi f) ≠ ⊥ :=
let ⟨x⟩ := hn in
assume h, have he: ∅ ∈ (infi f), from h.symm ▸ (mem_bot_sets : ∅ ∈ (⊥ : filter α)),
classical.by_cases
(assume : nonempty ι,
have ∃i, ∅ ∈ f i,
by rw [mem_infi hd this] at he; simp only [mem_Union] at he; assumption,
let ⟨i, hi⟩ := this in
hb i $ bot_unique $
assume s _, (f i).sets_of_superset hi $ empty_subset _)
(assume : ¬ nonempty ι,
have univ ⊆ (∅ : set α),
begin
rw [←principal_mono, principal_univ, principal_empty, ←h],
exact (le_infi $ assume i, false.elim $ this ⟨i⟩)
end,
this $ mem_univ x)
lemma infi_neq_bot_iff_of_directed {f : ι → filter α}
(hn : nonempty α) (hd : directed (≥) f) : (infi f) ≠ ⊥ ↔ (∀i, f i ≠ ⊥) :=
⟨assume neq_bot i eq_bot, neq_bot $ bot_unique $ infi_le_of_le i $ eq_bot ▸ le_refl _,
infi_neq_bot_of_directed hn hd⟩
lemma mem_infi_sets {f : ι → filter α} (i : ι) : ∀{s}, s ∈ f i → s ∈ ⨅i, f i :=
show (⨅i, f i) ≤ f i, from infi_le _ _
@[elab_as_eliminator]
lemma infi_sets_induct {f : ι → filter α} {s : set α} (hs : s ∈ infi f) {p : set α → Prop}
(uni : p univ)
(ins : ∀{i s₁ s₂}, s₁ ∈ f i → p s₂ → p (s₁ ∩ s₂))
(upw : ∀{s₁ s₂}, s₁ ⊆ s₂ → p s₁ → p s₂) : p s :=
begin
rw [mem_infi_finite] at hs,
simp only [mem_Union, (finset.inf_eq_infi _ _).symm] at hs,
rcases hs with ⟨is, his⟩,
revert s,
refine finset.induction_on is _ _,
{ assume s hs, rwa [mem_top_sets.1 hs] },
{ rintros ⟨i⟩ js his ih s hs,
rw [finset.inf_insert, mem_inf_sets] at hs,
rcases hs with ⟨s₁, hs₁, s₂, hs₂, hs⟩,
exact upw hs (ins hs₁ (ih hs₂)) }
end
/- tendsto -/
/-- `tendsto` is the generic "limit of a function" predicate.
`tendsto f l₁ l₂` asserts that for every `l₂` neighborhood `a`,
the `f`-preimage of `a` is an `l₁` neighborhood. -/
def tendsto (f : α → β) (l₁ : filter α) (l₂ : filter β) := l₁.map f ≤ l₂
lemma tendsto_def {f : α → β} {l₁ : filter α} {l₂ : filter β} :
tendsto f l₁ l₂ ↔ ∀ s ∈ l₂, f ⁻¹' s ∈ l₁ := iff.rfl
lemma tendsto_iff_comap {f : α → β} {l₁ : filter α} {l₂ : filter β} :
tendsto f l₁ l₂ ↔ l₁ ≤ l₂.comap f :=
map_le_iff_le_comap
lemma tendsto.congr' {f₁ f₂ : α → β} {l₁ : filter α} {l₂ : filter β}
(hl : {x | f₁ x = f₂ x} ∈ l₁) (h : tendsto f₁ l₁ l₂) : tendsto f₂ l₁ l₂ :=
by rwa [tendsto, ←map_cong hl]
theorem tendsto.congr'r {f₁ f₂ : α → β} {l₁ : filter α} {l₂ : filter β}
(h : ∀ x, f₁ x = f₂ x) : tendsto f₁ l₁ l₂ ↔ tendsto f₂ l₁ l₂ :=
iff_of_eq (by congr'; exact funext h)
theorem tendsto.congr {f₁ f₂ : α → β} {l₁ : filter α} {l₂ : filter β}
(h : ∀ x, f₁ x = f₂ x) : tendsto f₁ l₁ l₂ → tendsto f₂ l₁ l₂ :=
(tendsto.congr'r h).1
lemma tendsto_id' {x y : filter α} : x ≤ y → tendsto id x y :=
by simp only [tendsto, map_id, forall_true_iff] {contextual := tt}
lemma tendsto_id {x : filter α} : tendsto id x x := tendsto_id' $ le_refl x
lemma tendsto.comp {f : α → β} {g : β → γ} {x : filter α} {y : filter β} {z : filter γ}
(hf : tendsto f x y) (hg : tendsto g y z) : tendsto (g ∘ f) x z :=
calc map (g ∘ f) x = map g (map f x) : by rw [map_map]
... ≤ map g y : map_mono hf
... ≤ z : hg
lemma tendsto_le_left {f : α → β} {x y : filter α} {z : filter β}
(h : y ≤ x) : tendsto f x z → tendsto f y z :=
le_trans (map_mono h)
lemma tendsto_le_right {f : α → β} {x : filter α} {y z : filter β}
(h₁ : y ≤ z) (h₂ : tendsto f x y) : tendsto f x z :=
le_trans h₂ h₁
lemma tendsto_map {f : α → β} {x : filter α} : tendsto f x (map f x) := le_refl (map f x)
lemma tendsto_map' {f : β → γ} {g : α → β} {x : filter α} {y : filter γ}
(h : tendsto (f ∘ g) x y) : tendsto f (map g x) y :=
by rwa [tendsto, map_map]
lemma tendsto_map'_iff {f : β → γ} {g : α → β} {x : filter α} {y : filter γ} :
tendsto f (map g x) y ↔ tendsto (f ∘ g) x y :=
by rw [tendsto, map_map]; refl
lemma tendsto_comap {f : α → β} {x : filter β} : tendsto f (comap f x) x :=
map_comap_le
lemma tendsto_comap_iff {f : α → β} {g : β → γ} {a : filter α} {c : filter γ} :
tendsto f a (c.comap g) ↔ tendsto (g ∘ f) a c :=
⟨assume h, h.comp tendsto_comap, assume h, map_le_iff_le_comap.mp $ by rwa [map_map]⟩
lemma tendsto_comap'_iff {m : α → β} {f : filter α} {g : filter β} {i : γ → α}
(h : range i ∈ f) : tendsto (m ∘ i) (comap i f) g ↔ tendsto m f g :=
by rw [tendsto, ← map_compose]; simp only [(∘), map_comap h, tendsto]
lemma comap_eq_of_inverse {f : filter α} {g : filter β} {φ : α → β} (ψ : β → α)
(eq : ψ ∘ φ = id) (hφ : tendsto φ f g) (hψ : tendsto ψ g f) : comap φ g = f :=
begin
refine le_antisymm (le_trans (comap_mono $ map_le_iff_le_comap.1 hψ) _) (map_le_iff_le_comap.1 hφ),
rw [comap_comap_comp, eq, comap_id],
exact le_refl _
end
lemma map_eq_of_inverse {f : filter α} {g : filter β} {φ : α → β} (ψ : β → α)
(eq : φ ∘ ψ = id) (hφ : tendsto φ f g) (hψ : tendsto ψ g f) : map φ f = g :=
begin
refine le_antisymm hφ (le_trans _ (map_mono hψ)),
rw [map_map, eq, map_id],
exact le_refl _
end
lemma tendsto_inf {f : α → β} {x : filter α} {y₁ y₂ : filter β} :
tendsto f x (y₁ ⊓ y₂) ↔ tendsto f x y₁ ∧ tendsto f x y₂ :=
by simp only [tendsto, lattice.le_inf_iff, iff_self]
lemma tendsto_inf_left {f : α → β} {x₁ x₂ : filter α} {y : filter β}
(h : tendsto f x₁ y) : tendsto f (x₁ ⊓ x₂) y :=
le_trans (map_mono inf_le_left) h
lemma tendsto_inf_right {f : α → β} {x₁ x₂ : filter α} {y : filter β}
(h : tendsto f x₂ y) : tendsto f (x₁ ⊓ x₂) y :=
le_trans (map_mono inf_le_right) h
lemma tendsto_infi {f : α → β} {x : filter α} {y : ι → filter β} :
tendsto f x (⨅i, y i) ↔ ∀i, tendsto f x (y i) :=
by simp only [tendsto, iff_self, lattice.le_infi_iff]
lemma tendsto_infi' {f : α → β} {x : ι → filter α} {y : filter β} (i : ι) :
tendsto f (x i) y → tendsto f (⨅i, x i) y :=
tendsto_le_left (infi_le _ _)
lemma tendsto_principal {f : α → β} {a : filter α} {s : set β} :
tendsto f a (principal s) ↔ {a | f a ∈ s} ∈ a :=
by simp only [tendsto, le_principal_iff, mem_map, iff_self]
lemma tendsto_principal_principal {f : α → β} {s : set α} {t : set β} :
tendsto f (principal s) (principal t) ↔ ∀a∈s, f a ∈ t :=
by simp only [tendsto, image_subset_iff, le_principal_iff, map_principal, mem_principal_sets]; refl
lemma tendsto_pure_pure (f : α → β) (a : α) :
tendsto f (pure a) (pure (f a)) :=
show filter.map f (pure a) ≤ pure (f a),
by rw [filter.map_pure]; exact le_refl _
lemma tendsto_const_pure {a : filter α} {b : β} : tendsto (λa, b) a (pure b) :=
by simp [tendsto]; exact univ_mem_sets
lemma tendsto_if {l₁ : filter α} {l₂ : filter β}
{f g : α → β} {p : α → Prop} [decidable_pred p]
(h₀ : tendsto f (l₁ ⊓ principal p) l₂)
(h₁ : tendsto g (l₁ ⊓ principal { x | ¬ p x }) l₂) :
tendsto (λ x, if p x then f x else g x) l₁ l₂ :=
begin
revert h₀ h₁, simp only [tendsto_def, mem_inf_principal],
intros h₀ h₁ s hs,
apply mem_sets_of_superset (inter_mem_sets (h₀ s hs) (h₁ s hs)),
rintros x ⟨hp₀, hp₁⟩, dsimp,
by_cases h : p x,
{ rw if_pos h, exact hp₀ h },
rw if_neg h, exact hp₁ h
end
section prod
variables {s : set α} {t : set β} {f : filter α} {g : filter β}
/- The product filter cannot be defined using the monad structure on filters. For example:
F := do {x <- seq, y <- top, return (x, y)}
hence:
s ∈ F <-> ∃n, [n..∞] × univ ⊆ s
G := do {y <- top, x <- seq, return (x, y)}
hence:
s ∈ G <-> ∀i:ℕ, ∃n, [n..∞] × {i} ⊆ s
Now ⋃i, [i..∞] × {i} is in G but not in F.
As product filter we want to have F as result.
-/
/-- Product of filters. This is the filter generated by cartesian products
of elements of the component filters. -/
protected def prod (f : filter α) (g : filter β) : filter (α × β) :=
f.comap prod.fst ⊓ g.comap prod.snd
lemma prod_mem_prod {s : set α} {t : set β} {f : filter α} {g : filter β}
(hs : s ∈ f) (ht : t ∈ g) : set.prod s t ∈ filter.prod f g :=
inter_mem_inf_sets (preimage_mem_comap hs) (preimage_mem_comap ht)
lemma mem_prod_iff {s : set (α×β)} {f : filter α} {g : filter β} :
s ∈ filter.prod f g ↔ (∃ t₁ ∈ f, ∃ t₂ ∈ g, set.prod t₁ t₂ ⊆ s) :=
begin
simp only [filter.prod],
split,
exact assume ⟨t₁, ⟨s₁, hs₁, hts₁⟩, t₂, ⟨s₂, hs₂, hts₂⟩, h⟩,
⟨s₁, hs₁, s₂, hs₂, subset.trans (inter_subset_inter hts₁ hts₂) h⟩,
exact assume ⟨t₁, ht₁, t₂, ht₂, h⟩,
⟨prod.fst ⁻¹' t₁, ⟨t₁, ht₁, subset.refl _⟩, prod.snd ⁻¹' t₂, ⟨t₂, ht₂, subset.refl _⟩, h⟩
end
lemma tendsto_fst {f : filter α} {g : filter β} : tendsto prod.fst (filter.prod f g) f :=
tendsto_inf_left tendsto_comap
lemma tendsto_snd {f : filter α} {g : filter β} : tendsto prod.snd (filter.prod f g) g :=
tendsto_inf_right tendsto_comap
lemma tendsto.prod_mk {f : filter α} {g : filter β} {h : filter γ} {m₁ : α → β} {m₂ : α → γ}
(h₁ : tendsto m₁ f g) (h₂ : tendsto m₂ f h) : tendsto (λx, (m₁ x, m₂ x)) f (filter.prod g h) :=
tendsto_inf.2 ⟨tendsto_comap_iff.2 h₁, tendsto_comap_iff.2 h₂⟩
lemma prod_infi_left {f : ι → filter α} {g : filter β} (i : ι) :
filter.prod (⨅i, f i) g = (⨅i, filter.prod (f i) g) :=
by rw [filter.prod, comap_infi, infi_inf i]; simp only [filter.prod, eq_self_iff_true]
lemma prod_infi_right {f : filter α} {g : ι → filter β} (i : ι) :
filter.prod f (⨅i, g i) = (⨅i, filter.prod f (g i)) :=
by rw [filter.prod, comap_infi, inf_infi i]; simp only [filter.prod, eq_self_iff_true]
lemma prod_mono {f₁ f₂ : filter α} {g₁ g₂ : filter β} (hf : f₁ ≤ f₂) (hg : g₁ ≤ g₂) :
filter.prod f₁ g₁ ≤ filter.prod f₂ g₂ :=
inf_le_inf (comap_mono hf) (comap_mono hg)
lemma prod_comap_comap_eq {α₁ : Type u} {α₂ : Type v} {β₁ : Type w} {β₂ : Type x}
{f₁ : filter α₁} {f₂ : filter α₂} {m₁ : β₁ → α₁} {m₂ : β₂ → α₂} :
filter.prod (comap m₁ f₁) (comap m₂ f₂) = comap (λp:β₁×β₂, (m₁ p.1, m₂ p.2)) (filter.prod f₁ f₂) :=
by simp only [filter.prod, comap_comap_comp, eq_self_iff_true, comap_inf]
lemma prod_comm' : filter.prod f g = comap (prod.swap) (filter.prod g f) :=
by simp only [filter.prod, comap_comap_comp, (∘), inf_comm, prod.fst_swap,
eq_self_iff_true, prod.snd_swap, comap_inf]
lemma prod_comm : filter.prod f g = map (λp:β×α, (p.2, p.1)) (filter.prod g f) :=
by rw [prod_comm', ← map_swap_eq_comap_swap]; refl
lemma prod_map_map_eq {α₁ : Type u} {α₂ : Type v} {β₁ : Type w} {β₂ : Type x}
{f₁ : filter α₁} {f₂ : filter α₂} {m₁ : α₁ → β₁} {m₂ : α₂ → β₂} :
filter.prod (map m₁ f₁) (map m₂ f₂) = map (λp:α₁×α₂, (m₁ p.1, m₂ p.2)) (filter.prod f₁ f₂) :=
le_antisymm
(assume s hs,
let ⟨s₁, hs₁, s₂, hs₂, h⟩ := mem_prod_iff.mp hs in
filter.sets_of_superset _ (prod_mem_prod (image_mem_map hs₁) (image_mem_map hs₂)) $
calc set.prod (m₁ '' s₁) (m₂ '' s₂) = (λp:α₁×α₂, (m₁ p.1, m₂ p.2)) '' set.prod s₁ s₂ :
set.prod_image_image_eq
... ⊆ _ : by rwa [image_subset_iff])
((tendsto_fst.comp (le_refl _)).prod_mk (tendsto_snd.comp (le_refl _)))
lemma map_prod (m : α × β → γ) (f : filter α) (g : filter β) :
map m (f.prod g) = (f.map (λa b, m (a, b))).seq g :=
begin
simp [filter.ext_iff, mem_prod_iff, mem_map_seq_iff],
assume s,
split,
exact assume ⟨t, ht, s, hs, h⟩, ⟨s, hs, t, ht, assume x hx y hy, @h ⟨x, y⟩ ⟨hx, hy⟩⟩,
exact assume ⟨s, hs, t, ht, h⟩, ⟨t, ht, s, hs, assume ⟨x, y⟩ ⟨hx, hy⟩, h x hx y hy⟩
end
lemma prod_eq {f : filter α} {g : filter β} : f.prod g = (f.map prod.mk).seq g :=
have h : _ := map_prod id f g, by rwa [map_id] at h
lemma prod_inf_prod {f₁ f₂ : filter α} {g₁ g₂ : filter β} :
filter.prod f₁ g₁ ⊓ filter.prod f₂ g₂ = filter.prod (f₁ ⊓ f₂) (g₁ ⊓ g₂) :=
by simp only [filter.prod, comap_inf, inf_comm, inf_assoc, lattice.inf_left_comm]
@[simp] lemma prod_bot {f : filter α} : filter.prod f (⊥ : filter β) = ⊥ := by simp [filter.prod]
@[simp] lemma bot_prod {g : filter β} : filter.prod (⊥ : filter α) g = ⊥ := by simp [filter.prod]
@[simp] lemma prod_principal_principal {s : set α} {t : set β} :
filter.prod (principal s) (principal t) = principal (set.prod s t) :=
by simp only [filter.prod, comap_principal, principal_eq_iff_eq, comap_principal, inf_principal]; refl
@[simp] lemma prod_pure_pure {a : α} {b : β} : filter.prod (pure a) (pure b) = pure (a, b) :=
by simp
lemma prod_eq_bot {f : filter α} {g : filter β} : filter.prod f g = ⊥ ↔ (f = ⊥ ∨ g = ⊥) :=
begin
split,
{ assume h,
rcases mem_prod_iff.1 (empty_in_sets_eq_bot.2 h) with ⟨s, hs, t, ht, hst⟩,
rw [subset_empty_iff, set.prod_eq_empty_iff] at hst,
cases hst with s_eq t_eq,
{ left, exact empty_in_sets_eq_bot.1 (s_eq ▸ hs) },
{ right, exact empty_in_sets_eq_bot.1 (t_eq ▸ ht) } },
{ rintros (rfl | rfl),
exact bot_prod,
exact prod_bot }
end
lemma prod_neq_bot {f : filter α} {g : filter β} : filter.prod f g ≠ ⊥ ↔ (f ≠ ⊥ ∧ g ≠ ⊥) :=
by rw [(≠), prod_eq_bot, not_or_distrib]
lemma tendsto_prod_iff {f : α × β → γ} {x : filter α} {y : filter β} {z : filter γ} :
filter.tendsto f (filter.prod x y) z ↔
∀ W ∈ z, ∃ U ∈ x, ∃ V ∈ y, ∀ x y, x ∈ U → y ∈ V → f (x, y) ∈ W :=
by simp only [tendsto_def, mem_prod_iff, prod_sub_preimage_iff, exists_prop, iff_self]
end prod
/- at_top and at_bot -/
/-- `at_top` is the filter representing the limit `→ ∞` on an ordered set.
It is generated by the collection of up-sets `{b | a ≤ b}`.
(The preorder need not have a top element for this to be well defined,
and indeed is trivial when a top element exists.) -/
def at_top [preorder α] : filter α := ⨅ a, principal {b | a ≤ b}
/-- `at_bot` is the filter representing the limit `→ -∞` on an ordered set.
It is generated by the collection of down-sets `{b | b ≤ a}`.
(The preorder need not have a bottom element for this to be well defined,
and indeed is trivial when a bottom element exists.) -/
def at_bot [preorder α] : filter α := ⨅ a, principal {b | b ≤ a}
lemma mem_at_top [preorder α] (a : α) : {b : α | a ≤ b} ∈ @at_top α _ :=
mem_infi_sets a $ subset.refl _
@[simp] lemma at_top_ne_bot [nonempty α] [semilattice_sup α] : (at_top : filter α) ≠ ⊥ :=
infi_neq_bot_of_directed (by apply_instance)
(assume a b, ⟨a ⊔ b, by simp only [ge, le_principal_iff, forall_const, set_of_subset_set_of,
mem_principal_sets, and_self, sup_le_iff, forall_true_iff] {contextual := tt}⟩)
(assume a, by simp only [principal_eq_bot_iff, ne.def, principal_eq_bot_iff]; exact ne_empty_of_mem (le_refl a))
@[simp] lemma mem_at_top_sets [nonempty α] [semilattice_sup α] {s : set α} :
s ∈ (at_top : filter α) ↔ ∃a:α, ∀b≥a, b ∈ s :=
let ⟨a⟩ := ‹nonempty α› in
iff.intro
(assume h, infi_sets_induct h ⟨a, by simp only [forall_const, mem_univ, forall_true_iff]⟩
(assume a s₁ s₂ ha ⟨b, hb⟩, ⟨a ⊔ b,
assume c hc, ⟨ha $ le_trans le_sup_left hc, hb _ $ le_trans le_sup_right hc⟩⟩)
(assume s₁ s₂ h ⟨a, ha⟩, ⟨a, assume b hb, h $ ha _ hb⟩))
(assume ⟨a, h⟩, mem_infi_sets a $ assume x, h x)
lemma map_at_top_eq [nonempty α] [semilattice_sup α] {f : α → β} :
at_top.map f = (⨅a, principal $ f '' {a' | a ≤ a'}) :=
calc map f (⨅a, principal {a' | a ≤ a'}) = (⨅a, map f $ principal {a' | a ≤ a'}) :
map_infi_eq (assume a b, ⟨a ⊔ b, by simp only [ge, le_principal_iff, forall_const, set_of_subset_set_of,
mem_principal_sets, and_self, sup_le_iff, forall_true_iff] {contextual := tt}⟩)
(by apply_instance)
... = (⨅a, principal $ f '' {a' | a ≤ a'}) : by simp only [map_principal, eq_self_iff_true]
lemma tendsto_at_top [preorder β] (m : α → β) (f : filter α) :
tendsto m f at_top ↔ (∀b, {a | b ≤ m a} ∈ f) :=
by simp only [at_top, tendsto_infi, tendsto_principal]; refl
lemma tendsto_at_top' [nonempty α] [semilattice_sup α] (f : α → β) (l : filter β) :
tendsto f at_top l ↔ (∀s ∈ l, ∃a, ∀b≥a, f b ∈ s) :=
by simp only [tendsto_def, mem_at_top_sets]; refl
theorem tendsto_at_top_principal [nonempty β] [semilattice_sup β] {f : β → α} {s : set α} :
tendsto f at_top (principal s) ↔ ∃N, ∀n≥N, f n ∈ s :=
by rw [tendsto_iff_comap, comap_principal, le_principal_iff, mem_at_top_sets]; refl
/-- A function `f` grows to infinity independent of an order-preserving embedding `e`. -/
lemma tendsto_at_top_embedding {α β γ : Type*} [preorder β] [preorder γ]
{f : α → β} {e : β → γ} {l : filter α}
(hm : ∀b₁ b₂, e b₁ ≤ e b₂ ↔ b₁ ≤ b₂) (hu : ∀c, ∃b, c ≤ e b) :
tendsto (e ∘ f) l at_top ↔ tendsto f l at_top :=
begin
rw [tendsto_at_top, tendsto_at_top],
split,
{ assume hc b,
filter_upwards [hc (e b)] assume a, (hm b (f a)).1 },
{ assume hb c,
rcases hu c with ⟨b, hc⟩,
filter_upwards [hb b] assume a ha, le_trans hc ((hm b (f a)).2 ha) }
end
lemma tendsto_at_top_at_top [nonempty α] [semilattice_sup α] [preorder β] (f : α → β) :
tendsto f at_top at_top ↔ ∀ b : β, ∃ i : α, ∀ a : α, i ≤ a → b ≤ f a :=
iff.trans tendsto_infi $ forall_congr $ assume b, tendsto_at_top_principal
lemma tendsto_finset_image_at_top_at_top {i : β → γ} {j : γ → β} (h : ∀x, j (i x) = x) :
tendsto (λs:finset γ, s.image j) at_top at_top :=
tendsto_infi.2 $ assume s, tendsto_infi' (s.image i) $ tendsto_principal_principal.2 $
assume t (ht : s.image i ⊆ t),
calc s = (s.image i).image j :
by simp only [finset.image_image, (∘), h]; exact finset.image_id.symm
... ⊆ t.image j : finset.image_subset_image ht
lemma prod_at_top_at_top_eq {β₁ β₂ : Type*} [inhabited β₁] [inhabited β₂] [semilattice_sup β₁]
[semilattice_sup β₂] : filter.prod (@at_top β₁ _) (@at_top β₂ _) = @at_top (β₁ × β₂) _ :=
by simp [at_top, prod_infi_left (default β₁), prod_infi_right (default β₂), infi_prod];
exact infi_comm
lemma prod_map_at_top_eq {α₁ α₂ β₁ β₂ : Type*} [inhabited β₁] [inhabited β₂]
[semilattice_sup β₁] [semilattice_sup β₂] (u₁ : β₁ → α₁) (u₂ : β₂ → α₂) :
filter.prod (map u₁ at_top) (map u₂ at_top) = map (prod.map u₁ u₂) at_top :=
by rw [prod_map_map_eq, prod_at_top_at_top_eq, prod.map_def]
/-- A function `f` maps upwards closed sets (at_top sets) to upwards closed sets when it is a
Galois insertion. The Galois "insertion" and "connection" is weakened to only require it to be an
insertion and a connetion above `b'`. -/
lemma map_at_top_eq_of_gc [semilattice_sup α] [semilattice_sup β] {f : α → β} (g : β → α) (b' : β)(hf : monotone f) (gc : ∀a, ∀b≥b', f a ≤ b ↔ a ≤ g b) (hgi : ∀b≥b', b ≤ f (g b)) :
map f at_top = at_top :=
begin
rw [@map_at_top_eq α _ ⟨g b'⟩],
refine le_antisymm
(le_infi $ assume b, infi_le_of_le (g (b ⊔ b')) $ principal_mono.2 $ image_subset_iff.2 _)
(le_infi $ assume a, infi_le_of_le (f a ⊔ b') $ principal_mono.2 _),
{ assume a ha, exact (le_trans le_sup_left $ le_trans (hgi _ le_sup_right) $ hf ha) },
{ assume b hb,
have hb' : b' ≤ b := le_trans le_sup_right hb,
exact ⟨g b, (gc _ _ hb').1 (le_trans le_sup_left hb),
le_antisymm ((gc _ _ hb').2 (le_refl _)) (hgi _ hb')⟩ }
end
lemma map_add_at_top_eq_nat (k : ℕ) : map (λa, a + k) at_top = at_top :=
map_at_top_eq_of_gc (λa, a - k) k
(assume a b h, add_le_add_right h k)
(assume a b h, (nat.le_sub_right_iff_add_le h).symm)
(assume a h, by rw [nat.sub_add_cancel h])
lemma map_sub_at_top_eq_nat (k : ℕ) : map (λa, a - k) at_top = at_top :=
map_at_top_eq_of_gc (λa, a + k) 0
(assume a b h, nat.sub_le_sub_right h _)
(assume a b _, nat.sub_le_right_iff_le_add)
(assume b _, by rw [nat.add_sub_cancel])
lemma tendso_add_at_top_nat (k : ℕ) : tendsto (λa, a + k) at_top at_top :=
le_of_eq (map_add_at_top_eq_nat k)
lemma tendso_sub_at_top_nat (k : ℕ) : tendsto (λa, a - k) at_top at_top :=
le_of_eq (map_sub_at_top_eq_nat k)
lemma tendsto_add_at_top_iff_nat {f : ℕ → α} {l : filter α} (k : ℕ) :
tendsto (λn, f (n + k)) at_top l ↔ tendsto f at_top l :=
show tendsto (f ∘ (λn, n + k)) at_top l ↔ tendsto f at_top l,
by rw [← tendsto_map'_iff, map_add_at_top_eq_nat]
lemma map_div_at_top_eq_nat (k : ℕ) (hk : k > 0) : map (λa, a / k) at_top = at_top :=
map_at_top_eq_of_gc (λb, b * k + (k - 1)) 1
(assume a b h, nat.div_le_div_right h)
(assume a b _,
calc a / k ≤ b ↔ a / k < b + 1 : by rw [← nat.succ_eq_add_one, nat.lt_succ_iff]
... ↔ a < (b + 1) * k : nat.div_lt_iff_lt_mul _ _ hk
... ↔ _ :
begin
cases k,
exact (lt_irrefl _ hk).elim,
simp [mul_add, add_mul, nat.succ_add, nat.lt_succ_iff]
end)
(assume b _,
calc b = (b * k) / k : by rw [nat.mul_div_cancel b hk]
... ≤ (b * k + (k - 1)) / k : nat.div_le_div_right $ nat.le_add_right _ _)
/- ultrafilter -/
section ultrafilter
open zorn
variables {f g : filter α}
/-- An ultrafilter is a minimal (maximal in the set order) proper filter. -/
def is_ultrafilter (f : filter α) := f ≠ ⊥ ∧ ∀g, g ≠ ⊥ → g ≤ f → f ≤ g
lemma ultrafilter_unique (hg : is_ultrafilter g) (hf : f ≠ ⊥) (h : f ≤ g) : f = g :=
le_antisymm h (hg.right _ hf h)
lemma le_of_ultrafilter {g : filter α} (hf : is_ultrafilter f) (h : f ⊓ g ≠ ⊥) :
f ≤ g :=
le_of_inf_eq $ ultrafilter_unique hf h inf_le_left
/-- Equivalent characterization of ultrafilters:
A filter f is an ultrafilter if and only if for each set s,
-s belongs to f if and only if s does not belong to f. -/
lemma ultrafilter_iff_compl_mem_iff_not_mem :
is_ultrafilter f ↔ (∀ s, -s ∈ f ↔ s ∉ f) :=
⟨assume hf s,
⟨assume hns hs,
hf.1 $ empty_in_sets_eq_bot.mp $ by convert f.inter_sets hs hns; rw [inter_compl_self],
assume hs,
have f ≤ principal (-s), from
le_of_ultrafilter hf $ assume h, hs $ mem_sets_of_neq_bot $
by simp only [h, eq_self_iff_true, lattice.neg_neg],
by simp only [le_principal_iff] at this; assumption⟩,
assume hf,
⟨mt empty_in_sets_eq_bot.mpr ((hf ∅).mp (by convert f.univ_sets; rw [compl_empty])),
assume g hg g_le s hs, classical.by_contradiction $ mt (hf s).mpr $
assume : - s ∈ f,
have s ∩ -s ∈ g, from inter_mem_sets hs (g_le this),
by simp only [empty_in_sets_eq_bot, hg, inter_compl_self] at this; contradiction⟩⟩
lemma mem_or_compl_mem_of_ultrafilter (hf : is_ultrafilter f) (s : set α) :
s ∈ f ∨ - s ∈ f :=
classical.or_iff_not_imp_left.2 (ultrafilter_iff_compl_mem_iff_not_mem.mp hf s).mpr
lemma mem_or_mem_of_ultrafilter {s t : set α} (hf : is_ultrafilter f) (h : s ∪ t ∈ f) :
s ∈ f ∨ t ∈ f :=
(mem_or_compl_mem_of_ultrafilter hf s).imp_right
(assume : -s ∈ f, by filter_upwards [this, h] assume x hnx hx, hx.resolve_left hnx)
lemma mem_of_finite_sUnion_ultrafilter {s : set (set α)} (hf : is_ultrafilter f) (hs : finite s)
: ⋃₀ s ∈ f → ∃t∈s, t ∈ f :=
finite.induction_on hs (by simp only [empty_in_sets_eq_bot, hf.left, mem_empty_eq, sUnion_empty,
forall_prop_of_false, exists_false, not_false_iff, exists_prop_of_false]) $
λ t s' ht' hs' ih, by simp only [exists_prop, mem_insert_iff, set.sUnion_insert]; exact
assume h, (mem_or_mem_of_ultrafilter hf h).elim
(assume : t ∈ f, ⟨t, or.inl rfl, this⟩)
(assume h, let ⟨t, hts', ht⟩ := ih h in ⟨t, or.inr hts', ht⟩)
lemma mem_of_finite_Union_ultrafilter {is : set β} {s : β → set α}
(hf : is_ultrafilter f) (his : finite is) (h : (⋃i∈is, s i) ∈ f) : ∃i∈is, s i ∈ f :=
have his : finite (image s is), from finite_image s his,
have h : (⋃₀ image s is) ∈ f, from by simp only [sUnion_image, set.sUnion_image]; assumption,
let ⟨t, ⟨i, hi, h_eq⟩, (ht : t ∈ f)⟩ := mem_of_finite_sUnion_ultrafilter hf his h in
⟨i, hi, h_eq.symm ▸ ht⟩
lemma ultrafilter_map {f : filter α} {m : α → β} (h : is_ultrafilter f) : is_ultrafilter (map m f) :=
by rw ultrafilter_iff_compl_mem_iff_not_mem at ⊢ h; exact assume s, h (m ⁻¹' s)
lemma ultrafilter_pure {a : α} : is_ultrafilter (pure a) :=
begin
rw ultrafilter_iff_compl_mem_iff_not_mem, intro s,
rw [mem_pure_sets, mem_pure_sets], exact iff.rfl
end
lemma ultrafilter_bind {f : filter α} (hf : is_ultrafilter f) {m : α → filter β}
(hm : ∀ a, is_ultrafilter (m a)) : is_ultrafilter (f.bind m) :=
begin
simp only [ultrafilter_iff_compl_mem_iff_not_mem] at ⊢ hf hm, intro s,
dsimp [bind, join, map],
simp only [hm], apply hf
end
/-- The ultrafilter lemma: Any proper filter is contained in an ultrafilter. -/
lemma exists_ultrafilter (h : f ≠ ⊥) : ∃u, u ≤ f ∧ is_ultrafilter u :=
let
τ := {f' // f' ≠ ⊥ ∧ f' ≤ f},
r : τ → τ → Prop := λt₁ t₂, t₂.val ≤ t₁.val,
⟨a, ha⟩ := inhabited_of_mem_sets h univ_mem_sets,
top : τ := ⟨f, h, le_refl f⟩,
sup : Π(c:set τ), chain r c → τ :=
λc hc, ⟨⨅a:{a:τ // a ∈ insert top c}, a.val.val,
infi_neq_bot_of_directed ⟨a⟩
(directed_of_chain $ chain_insert hc $ assume ⟨b, _, hb⟩ _ _, or.inl hb)
(assume ⟨⟨a, ha, _⟩, _⟩, ha),
infi_le_of_le ⟨top, mem_insert _ _⟩ (le_refl _)⟩
in
have ∀c (hc: chain r c) a (ha : a ∈ c), r a (sup c hc),
from assume c hc a ha, infi_le_of_le ⟨a, mem_insert_of_mem _ ha⟩ (le_refl _),
have (∃ (u : τ), ∀ (a : τ), r u a → r a u),
from zorn (assume c hc, ⟨sup c hc, this c hc⟩) (assume f₁ f₂ f₃ h₁ h₂, le_trans h₂ h₁),
let ⟨uτ, hmin⟩ := this in
⟨uτ.val, uτ.property.right, uτ.property.left, assume g hg₁ hg₂,
hmin ⟨g, hg₁, le_trans hg₂ uτ.property.right⟩ hg₂⟩
/-- Construct an ultrafilter extending a given filter.
The ultrafilter lemma is the assertion that such a filter exists;
we use the axiom of choice to pick one. -/
noncomputable def ultrafilter_of (f : filter α) : filter α :=
if h : f = ⊥ then ⊥ else classical.epsilon (λu, u ≤ f ∧ is_ultrafilter u)
lemma ultrafilter_of_spec (h : f ≠ ⊥) : ultrafilter_of f ≤ f ∧ is_ultrafilter (ultrafilter_of f) :=
begin
have h' := classical.epsilon_spec (exists_ultrafilter h),
simp only [ultrafilter_of, dif_neg, h, dif_neg, not_false_iff],
simp only at h',
assumption
end
lemma ultrafilter_of_le : ultrafilter_of f ≤ f :=
if h : f = ⊥ then by simp only [ultrafilter_of, dif_pos, h, dif_pos, eq_self_iff_true, le_bot_iff]; exact le_refl _
else (ultrafilter_of_spec h).left
lemma ultrafilter_ultrafilter_of (h : f ≠ ⊥) : is_ultrafilter (ultrafilter_of f) :=
(ultrafilter_of_spec h).right
lemma ultrafilter_of_ultrafilter (h : is_ultrafilter f) : ultrafilter_of f = f :=
ultrafilter_unique h (ultrafilter_ultrafilter_of h.left).left ultrafilter_of_le
/-- A filter equals the intersection of all the ultrafilters which contain it. -/
lemma sup_of_ultrafilters (f : filter α) : f = ⨆ (g) (u : is_ultrafilter g) (H : g ≤ f), g :=
begin
refine le_antisymm _ (supr_le $ λ g, supr_le $ λ u, supr_le $ λ H, H),
intros s hs,
-- If s ∉ f.sets, we'll apply the ultrafilter lemma to the restriction of f to -s.
by_contradiction hs',
let j : (-s) → α := subtype.val,
have j_inv_s : j ⁻¹' s = ∅, by
erw [←preimage_inter_range, subtype.val_range, inter_compl_self, preimage_empty],
let f' := comap j f,
have : f' ≠ ⊥,
{ apply mt empty_in_sets_eq_bot.mpr,
rintro ⟨t, htf, ht⟩,
suffices : t ⊆ s, from absurd (f.sets_of_superset htf this) hs',
rw [subset_empty_iff] at ht,
have : j '' (j ⁻¹' t) = ∅, by rw [ht, image_empty],
erw [image_preimage_eq_inter_range, subtype.val_range, ←subset_compl_iff_disjoint,
set.compl_compl] at this,
exact this },
rcases exists_ultrafilter this with ⟨g', g'f', u'⟩,
simp only [supr_sets_eq, mem_Inter] at hs,
have := hs (g'.map subtype.val) (ultrafilter_map u') (map_le_iff_le_comap.mpr g'f'),
rw [←le_principal_iff, map_le_iff_le_comap, comap_principal, j_inv_s, principal_empty,
le_bot_iff] at this,
exact absurd this u'.1
end
/-- The `tendsto` relation can be checked on ultrafilters. -/
lemma tendsto_iff_ultrafilter (f : α → β) (l₁ : filter α) (l₂ : filter β) :
tendsto f l₁ l₂ ↔ ∀ g, is_ultrafilter g → g ≤ l₁ → g.map f ≤ l₂ :=
⟨assume h g u gx, le_trans (map_mono gx) h,
assume h, by rw [sup_of_ultrafilters l₁]; simpa only [tendsto, map_supr, supr_le_iff]⟩
/- The ultrafilter monad. The monad structure on ultrafilters is the
restriction of the one on filters. -/
def ultrafilter (α : Type u) : Type u := {f : filter α // is_ultrafilter f}
def ultrafilter.map (m : α → β) (u : ultrafilter α) : ultrafilter β :=
⟨u.val.map m, ultrafilter_map u.property⟩
def ultrafilter.pure (x : α) : ultrafilter α := ⟨pure x, ultrafilter_pure⟩
def ultrafilter.bind (u : ultrafilter α) (m : α → ultrafilter β) : ultrafilter β :=
⟨u.val.bind (λ a, (m a).val), ultrafilter_bind u.property (λ a, (m a).property)⟩
instance ultrafilter.has_pure : has_pure ultrafilter := ⟨@ultrafilter.pure⟩
instance ultrafilter.has_bind : has_bind ultrafilter := ⟨@ultrafilter.bind⟩
instance ultrafilter.functor : functor ultrafilter := { map := @ultrafilter.map }
instance ultrafilter.monad : monad ultrafilter := { map := @ultrafilter.map }
noncomputable def hyperfilter : filter α := ultrafilter_of cofinite
lemma hyperfilter_le_cofinite (hi : set.infinite (@set.univ α)) : @hyperfilter α ≤ cofinite :=
(ultrafilter_of_spec (cofinite_ne_bot hi)).1
lemma is_ultrafilter_hyperfilter (hi : set.infinite (@set.univ α)) : is_ultrafilter (@hyperfilter α) :=
(ultrafilter_of_spec (cofinite_ne_bot hi)).2
theorem nmem_hyperfilter_of_finite (hi : set.infinite (@set.univ α)) {s : set α} (hf : set.finite s) :
s ∉ @hyperfilter α :=
λ hy,
have hx : -s ∉ hyperfilter :=
λ hs, (ultrafilter_iff_compl_mem_iff_not_mem.mp (is_ultrafilter_hyperfilter hi) s).mp hs hy,
have ht : -s ∈ cofinite.sets := by show -s ∈ {s | _}; rwa [set.mem_set_of_eq, lattice.neg_neg],
hx $ hyperfilter_le_cofinite hi ht
theorem compl_mem_hyperfilter_of_finite (hi : set.infinite (@set.univ α)) {s : set α} (hf : set.finite s) :
-s ∈ @hyperfilter α :=
(ultrafilter_iff_compl_mem_iff_not_mem.mp (is_ultrafilter_hyperfilter hi) s).mpr $
nmem_hyperfilter_of_finite hi hf
theorem mem_hyperfilter_of_finite_compl (hi : set.infinite (@set.univ α)) {s : set α} (hf : set.finite (-s)) :
s ∈ @hyperfilter α :=
have h : _ := compl_mem_hyperfilter_of_finite hi hf,
by rwa [lattice.neg_neg] at h
section
local attribute [instance] filter.monad filter.is_lawful_monad
instance ultrafilter.is_lawful_monad : is_lawful_monad ultrafilter :=
{ id_map := assume α f, subtype.eq (id_map f.val),
pure_bind := assume α β a f, subtype.eq (pure_bind a (subtype.val ∘ f)),
bind_assoc := assume α β γ f m₁ m₂, subtype.eq (filter_eq rfl),
bind_pure_comp_eq_map := assume α β f x, subtype.eq (bind_pure_comp_eq_map _ f x.val) }
end
lemma ultrafilter.eq_iff_val_le_val {u v : ultrafilter α} : u = v ↔ u.val ≤ v.val :=
⟨assume h, by rw h; exact le_refl _,
assume h, by rw subtype.ext; apply ultrafilter_unique v.property u.property.1 h⟩
lemma exists_ultrafilter_iff (f : filter α) : (∃ (u : ultrafilter α), u.val ≤ f) ↔ f ≠ ⊥ :=
⟨assume ⟨u, uf⟩, lattice.neq_bot_of_le_neq_bot u.property.1 uf,
assume h, let ⟨u, uf, hu⟩ := exists_ultrafilter h in ⟨⟨u, hu⟩, uf⟩⟩
end ultrafilter
end filter
namespace filter
variables {α β γ : Type u} {f : β → filter α} {s : γ → set α}
open list
lemma mem_traverse_sets :
∀(fs : list β) (us : list γ),
forall₂ (λb c, s c ∈ f b) fs us → traverse s us ∈ traverse f fs
| [] [] forall₂.nil := mem_pure_sets.2 $ mem_singleton _
| (f::fs) (u::us) (forall₂.cons h hs) := seq_mem_seq_sets (image_mem_map h) (mem_traverse_sets fs us hs)
lemma mem_traverse_sets_iff (fs : list β) (t : set (list α)) :
t ∈ traverse f fs ↔
(∃us:list (set α), forall₂ (λb (s : set α), s ∈ f b) fs us ∧ sequence us ⊆ t) :=
begin
split,
{ induction fs generalizing t,
case nil { simp only [sequence, pure_def, imp_self, forall₂_nil_left_iff, pure_def,
exists_eq_left, mem_principal_sets, set.pure_def, singleton_subset_iff, traverse_nil] },
case cons : b fs ih t {
assume ht,
rcases mem_seq_sets_iff.1 ht with ⟨u, hu, v, hv, ht⟩,
rcases mem_map_sets_iff.1 hu with ⟨w, hw, hwu⟩,
rcases ih v hv with ⟨us, hus, hu⟩,
exact ⟨w :: us, forall₂.cons hw hus, subset.trans (set.seq_mono hwu hu) ht⟩ } },
{ rintros ⟨us, hus, hs⟩,
exact mem_sets_of_superset (mem_traverse_sets _ _ hus) hs }
end
lemma sequence_mono :
∀(as bs : list (filter α)), forall₂ (≤) as bs → sequence as ≤ sequence bs
| [] [] forall₂.nil := le_refl _
| (a::as) (b::bs) (forall₂.cons h hs) := seq_mono (map_mono h) (sequence_mono as bs hs)
end filter
|
01c31fc967e2f7975b3a1820b020b46f41ad5eb1 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/algebra/category/Group/biproducts.lean | 7616b1378093f70fd2a8834c6284032ff7e533ae | [
"Apache-2.0"
] | permissive | alreadydone/mathlib | dc0be621c6c8208c581f5170a8216c5ba6721927 | c982179ec21091d3e102d8a5d9f5fe06c8fafb73 | refs/heads/master | 1,685,523,275,196 | 1,670,184,141,000 | 1,670,184,141,000 | 287,574,545 | 0 | 0 | Apache-2.0 | 1,670,290,714,000 | 1,597,421,623,000 | Lean | UTF-8 | Lean | false | false | 4,603 | 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.pi
import algebra.category.Group.preadditive
import category_theory.preadditive.biproducts
import algebra.category.Group.limits
/-!
# The category of abelian groups has finite biproducts
-/
open category_theory
open category_theory.limits
open_locale big_operators
universes w u
namespace AddCommGroup
-- As `AddCommGroup` is preadditive, and has all limits, it automatically has biproducts.
instance : has_binary_biproducts AddCommGroup :=
has_binary_biproducts.of_has_binary_products
instance : has_finite_biproducts AddCommGroup :=
has_finite_biproducts.of_has_finite_products
-- We now construct explicit limit data,
-- so we can compare the biproducts to the usual unbundled constructions.
/--
Construct limit data for a binary product in `AddCommGroup`, using `AddCommGroup.of (G × H)`.
-/
@[simps cone_X is_limit_lift]
def binary_product_limit_cone (G H : AddCommGroup.{u}) : limits.limit_cone (pair G H) :=
{ cone :=
{ X := AddCommGroup.of (G × H),
π := { app := λ j, discrete.cases_on j
(λ j, walking_pair.cases_on j (add_monoid_hom.fst G H) (add_monoid_hom.snd G H)),
naturality' := by rintros ⟨⟨⟩⟩ ⟨⟨⟩⟩ ⟨⟨⟨⟩⟩⟩; refl, }},
is_limit :=
{ lift := λ s, add_monoid_hom.prod (s.π.app ⟨walking_pair.left⟩) (s.π.app ⟨walking_pair.right⟩),
fac' := by { rintros s (⟨⟩|⟨⟩); { ext x, simp, } },
uniq' := λ s m w, begin
ext; [rw ← w ⟨walking_pair.left⟩, rw ← w ⟨walking_pair.right⟩]; refl,
end, } }
@[simp] lemma binary_product_limit_cone_cone_π_app_left (G H : AddCommGroup.{u}) :
(binary_product_limit_cone G H).cone.π.app ⟨walking_pair.left⟩ = add_monoid_hom.fst G H := rfl
@[simp] lemma binary_product_limit_cone_cone_π_app_right (G H : AddCommGroup.{u}) :
(binary_product_limit_cone G H).cone.π.app ⟨walking_pair.right⟩ = add_monoid_hom.snd G H := rfl
/--
We verify that the biproduct in AddCommGroup is isomorphic to
the cartesian product of the underlying types:
-/
@[simps hom_apply] noncomputable
def biprod_iso_prod (G H : AddCommGroup.{u}) : (G ⊞ H : AddCommGroup) ≅ AddCommGroup.of (G × H) :=
is_limit.cone_point_unique_up_to_iso
(binary_biproduct.is_limit G H)
(binary_product_limit_cone G H).is_limit
@[simp, elementwise] lemma biprod_iso_prod_inv_comp_fst (G H : AddCommGroup.{u}) :
(biprod_iso_prod G H).inv ≫ biprod.fst = add_monoid_hom.fst G H :=
is_limit.cone_point_unique_up_to_iso_inv_comp _ _ (discrete.mk walking_pair.left)
@[simp, elementwise] lemma biprod_iso_prod_inv_comp_snd (G H : AddCommGroup.{u}) :
(biprod_iso_prod G H).inv ≫ biprod.snd = add_monoid_hom.snd G H :=
is_limit.cone_point_unique_up_to_iso_inv_comp _ _ (discrete.mk walking_pair.right)
namespace has_limit
variables {J : Type w} (f : J → AddCommGroup.{max w u})
/--
The map from an arbitrary cone over a indexed family of abelian groups
to the cartesian product of those groups.
-/
@[simps]
def lift (s : fan f) :
s.X ⟶ AddCommGroup.of (Π j,f j) :=
{ to_fun := λ x j, s.π.app ⟨j⟩ x,
map_zero' := by { ext, simp },
map_add' := λ x y, by { ext, simp }, }
/--
Construct limit data for a product in `AddCommGroup`, using `AddCommGroup.of (Π j, F.obj j)`.
-/
@[simps] def product_limit_cone : limits.limit_cone (discrete.functor f) :=
{ cone :=
{ X := AddCommGroup.of (Π j, f j),
π := discrete.nat_trans (λ j, pi.eval_add_monoid_hom (λ j, f j) j.as), },
is_limit :=
{ lift := lift f,
fac' := λ s j, by { cases j, ext, simp, },
uniq' := λ s m w,
begin
ext x j,
dsimp only [has_limit.lift],
simp only [add_monoid_hom.coe_mk],
exact congr_arg (λ g : s.X ⟶ f j, (g : s.X → f j) x) (w ⟨j⟩),
end, }, }
end has_limit
open has_limit
variables {J : Type} [fintype J]
/--
We verify that the biproduct we've just defined is isomorphic to the AddCommGroup structure
on the dependent function type
-/
@[simps hom_apply] noncomputable
def biproduct_iso_pi (f : J → AddCommGroup.{u}) :
(⨁ f : AddCommGroup) ≅ AddCommGroup.of (Π j, f j) :=
is_limit.cone_point_unique_up_to_iso
(biproduct.is_limit f)
(product_limit_cone f).is_limit
@[simp, elementwise] lemma biproduct_iso_pi_inv_comp_π (f : J → AddCommGroup.{u}) (j : J) :
(biproduct_iso_pi f).inv ≫ biproduct.π f j = pi.eval_add_monoid_hom (λ j, f j) j :=
is_limit.cone_point_unique_up_to_iso_inv_comp _ _ (discrete.mk j)
end AddCommGroup
|
efe6be733d4818669bc382e00bc7d8c8a4dfdd4b | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/category_theory/limits/shapes/multiequalizer.lean | 094b360ab504ddf7b731022e24ade0ea60baedb7 | [
"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 | 26,542 | lean | /-
Copyright (c) 2021 Adam Topaz. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Adam Topaz
-/
import category_theory.limits.shapes.products
import category_theory.limits.shapes.equalizers
import category_theory.limits.cone_category
/-!
# Multi-(co)equalizers
A *multiequalizer* is an equalizer of two morphisms between two products.
Since both products and equalizers are limits, such an object is again a limit.
This file provides the diagram whose limit is indeed such an object.
In fact, it is well-known that any limit can be obtained as a multiequalizer.
The dual construction (multicoequalizers) is also provided.
## Projects
Prove that a multiequalizer can be identified with
an equalizer between products (and analogously for multicoequalizers).
Prove that the limit of any diagram is a multiequalizer (and similarly for colimits).
-/
namespace category_theory.limits
open category_theory
universes w v u
/-- The type underlying the multiequalizer diagram. -/
@[nolint unused_arguments]
inductive walking_multicospan {L R : Type w} (fst snd : R → L) : Type w
| left : L → walking_multicospan
| right : R → walking_multicospan
/-- The type underlying the multiecoqualizer diagram. -/
@[nolint unused_arguments]
inductive walking_multispan {L R : Type w} (fst snd : L → R) : Type w
| left : L → walking_multispan
| right : R → walking_multispan
namespace walking_multicospan
variables {L R : Type w} {fst snd : R → L}
instance [inhabited L] : inhabited (walking_multicospan fst snd) :=
⟨left default⟩
/-- Morphisms for `walking_multicospan`. -/
inductive hom : Π (a b : walking_multicospan fst snd), Type w
| id (A) : hom A A
| fst (b) : hom (left (fst b)) (right b)
| snd (b) : hom (left (snd b)) (right b)
instance {a : walking_multicospan fst snd} : inhabited (hom a a) :=
⟨hom.id _⟩
/-- Composition of morphisms for `walking_multicospan`. -/
def hom.comp : Π {A B C : walking_multicospan fst snd} (f : hom A B) (g : hom B C),
hom A C
| _ _ _ (hom.id X) f := f
| _ _ _ (hom.fst b) (hom.id X) := hom.fst b
| _ _ _ (hom.snd b) (hom.id X) := hom.snd b
instance : small_category (walking_multicospan fst snd) :=
{ hom := hom,
id := hom.id,
comp := λ X Y Z, hom.comp,
id_comp' := by { rintro (_|_) (_|_) (_|_|_), tidy },
comp_id' := by { rintro (_|_) (_|_) (_|_|_), tidy },
assoc' := by { rintro (_|_) (_|_) (_|_) (_|_) (_|_|_) (_|_|_) (_|_|_), tidy } }
end walking_multicospan
namespace walking_multispan
variables {L R : Type v} {fst snd : L → R}
instance [inhabited L] : inhabited (walking_multispan fst snd) :=
⟨left default⟩
/-- Morphisms for `walking_multispan`. -/
inductive hom : Π (a b : walking_multispan fst snd), Type v
| id (A) : hom A A
| fst (a) : hom (left a) (right (fst a))
| snd (a) : hom (left a) (right (snd a))
instance {a : walking_multispan fst snd} : inhabited (hom a a) :=
⟨hom.id _⟩
/-- Composition of morphisms for `walking_multispan`. -/
def hom.comp : Π {A B C : walking_multispan fst snd} (f : hom A B) (g : hom B C),
hom A C
| _ _ _ (hom.id X) f := f
| _ _ _ (hom.fst a) (hom.id X) := hom.fst a
| _ _ _ (hom.snd a) (hom.id X) := hom.snd a
instance : small_category (walking_multispan fst snd) :=
{ hom := hom,
id := hom.id,
comp := λ X Y Z, hom.comp,
id_comp' := by { rintro (_|_) (_|_) (_|_|_), tidy },
comp_id' := by { rintro (_|_) (_|_) (_|_|_), tidy },
assoc' := by { rintro (_|_) (_|_) (_|_) (_|_) (_|_|_) (_|_|_) (_|_|_), tidy } }
end walking_multispan
/-- This is a structure encapsulating the data necessary to define a `multicospan`. -/
@[nolint has_nonempty_instance]
structure multicospan_index (C : Type u) [category.{v} C] :=
(L R : Type w)
(fst_to snd_to : R → L)
(left : L → C)
(right : R → C)
(fst : Π b, left (fst_to b) ⟶ right b)
(snd : Π b, left (snd_to b) ⟶ right b)
/-- This is a structure encapsulating the data necessary to define a `multispan`. -/
@[nolint has_nonempty_instance]
structure multispan_index (C : Type u) [category.{v} C] :=
(L R : Type w)
(fst_from snd_from : L → R)
(left : L → C)
(right : R → C)
(fst : Π a, left a ⟶ right (fst_from a))
(snd : Π a, left a ⟶ right (snd_from a))
namespace multicospan_index
variables {C : Type u} [category.{v} C] (I : multicospan_index C)
/-- The multicospan associated to `I : multicospan_index`. -/
def multicospan : walking_multicospan I.fst_to I.snd_to ⥤ C :=
{ obj := λ x,
match x with
| walking_multicospan.left a := I.left a
| walking_multicospan.right b := I.right b
end,
map := λ x y f,
match x, y, f with
| _, _, walking_multicospan.hom.id x := 𝟙 _
| _, _, walking_multicospan.hom.fst b := I.fst _
| _, _, walking_multicospan.hom.snd b := I.snd _
end,
map_id' := by { rintros (_|_), tidy },
map_comp' := by { rintros (_|_) (_|_) (_|_) (_|_|_) (_|_|_), tidy } }
@[simp] lemma multicospan_obj_left (a) :
I.multicospan.obj (walking_multicospan.left a) = I.left a := rfl
@[simp] lemma multicospan_obj_right (b) :
I.multicospan.obj (walking_multicospan.right b) = I.right b := rfl
@[simp] lemma multicospan_map_fst (b) :
I.multicospan.map (walking_multicospan.hom.fst b) = I.fst b := rfl
@[simp] lemma multicospan_map_snd (b) :
I.multicospan.map (walking_multicospan.hom.snd b) = I.snd b := rfl
variables [has_product I.left] [has_product I.right]
/-- The induced map `∏ I.left ⟶ ∏ I.right` via `I.fst`. -/
noncomputable
def fst_pi_map : ∏ I.left ⟶ ∏ I.right := pi.lift (λ b, pi.π I.left (I.fst_to b) ≫ I.fst b)
/-- The induced map `∏ I.left ⟶ ∏ I.right` via `I.snd`. -/
noncomputable
def snd_pi_map : ∏ I.left ⟶ ∏ I.right := pi.lift (λ b, pi.π I.left (I.snd_to b) ≫ I.snd b)
@[simp, reassoc]
lemma fst_pi_map_π (b) : I.fst_pi_map ≫ pi.π I.right b = pi.π I.left _ ≫ I.fst b :=
by simp [fst_pi_map]
@[simp, reassoc]
lemma snd_pi_map_π (b) : I.snd_pi_map ≫ pi.π I.right b = pi.π I.left _ ≫ I.snd b :=
by simp [snd_pi_map]
/--
Taking the multiequalizer over the multicospan index is equivalent to taking the equalizer over
the two morphsims `∏ I.left ⇉ ∏ I.right`. This is the diagram of the latter.
-/
@[simps] protected noncomputable
def parallel_pair_diagram := parallel_pair I.fst_pi_map I.snd_pi_map
end multicospan_index
namespace multispan_index
variables {C : Type u} [category.{v} C] (I : multispan_index C)
/-- The multispan associated to `I : multispan_index`. -/
def multispan : walking_multispan I.fst_from I.snd_from ⥤ C :=
{ obj := λ x,
match x with
| walking_multispan.left a := I.left a
| walking_multispan.right b := I.right b
end,
map := λ x y f,
match x, y, f with
| _, _, walking_multispan.hom.id x := 𝟙 _
| _, _, walking_multispan.hom.fst b := I.fst _
| _, _, walking_multispan.hom.snd b := I.snd _
end,
map_id' := by { rintros (_|_), tidy },
map_comp' := by { rintros (_|_) (_|_) (_|_) (_|_|_) (_|_|_), tidy } }
@[simp] lemma multispan_obj_left (a) :
I.multispan.obj (walking_multispan.left a) = I.left a := rfl
@[simp] lemma multispan_obj_right (b) :
I.multispan.obj (walking_multispan.right b) = I.right b := rfl
@[simp] lemma multispan_map_fst (a) :
I.multispan.map (walking_multispan.hom.fst a) = I.fst a := rfl
@[simp] lemma multispan_map_snd (a) :
I.multispan.map (walking_multispan.hom.snd a) = I.snd a := rfl
variables [has_coproduct I.left] [has_coproduct I.right]
/-- The induced map `∐ I.left ⟶ ∐ I.right` via `I.fst`. -/
noncomputable
def fst_sigma_map : ∐ I.left ⟶ ∐ I.right := sigma.desc (λ b, I.fst b ≫ sigma.ι _ (I.fst_from b))
/-- The induced map `∐ I.left ⟶ ∐ I.right` via `I.snd`. -/
noncomputable
def snd_sigma_map : ∐ I.left ⟶ ∐ I.right := sigma.desc (λ b, I.snd b ≫ sigma.ι _ (I.snd_from b))
@[simp, reassoc]
lemma ι_fst_sigma_map (b) : sigma.ι I.left b ≫ I.fst_sigma_map = I.fst b ≫ sigma.ι I.right _ :=
by simp [fst_sigma_map]
@[simp, reassoc]
lemma ι_snd_sigma_map (b) : sigma.ι I.left b ≫ I.snd_sigma_map = I.snd b ≫ sigma.ι I.right _ :=
by simp [snd_sigma_map]
/--
Taking the multicoequalizer over the multispan index is equivalent to taking the coequalizer over
the two morphsims `∐ I.left ⇉ ∐ I.right`. This is the diagram of the latter.
-/
protected noncomputable
abbreviation parallel_pair_diagram := parallel_pair I.fst_sigma_map I.snd_sigma_map
end multispan_index
variables {C : Type u} [category.{v} C]
/-- A multifork is a cone over a multicospan. -/
@[nolint has_nonempty_instance]
abbreviation multifork (I : multicospan_index C) := cone I.multicospan
/-- A multicofork is a cocone over a multispan. -/
@[nolint has_nonempty_instance]
abbreviation multicofork (I : multispan_index C) := cocone I.multispan
namespace multifork
variables {I : multicospan_index C} (K : multifork I)
/-- The maps from the cone point of a multifork to the objects on the left. -/
def ι (a : I.L) : K.X ⟶ I.left a := K.π.app (walking_multicospan.left _)
@[simp] lemma app_left_eq_ι (a) : K.π.app (walking_multicospan.left a) = K.ι a := rfl
@[simp] lemma app_right_eq_ι_comp_fst (b) :
K.π.app (walking_multicospan.right b) = K.ι (I.fst_to b) ≫ I.fst b :=
by { rw ← K.w (walking_multicospan.hom.fst b), refl }
@[reassoc] lemma app_right_eq_ι_comp_snd (b) :
K.π.app (walking_multicospan.right b) = K.ι (I.snd_to b) ≫ I.snd b :=
by { rw ← K.w (walking_multicospan.hom.snd b), refl }
@[simp, reassoc] lemma hom_comp_ι (K₁ K₂ : multifork I) (f : K₁ ⟶ K₂) (j : I.L) :
f.hom ≫ K₂.ι j = K₁.ι j := f.w (walking_multicospan.left j)
/-- Construct a multifork using a collection `ι` of morphisms. -/
@[simps]
def of_ι (I : multicospan_index C) (P : C) (ι : Π a, P ⟶ I.left a)
(w : ∀ b, ι (I.fst_to b) ≫ I.fst b = ι (I.snd_to b) ≫ I.snd b) :
multifork I :=
{ X := P,
π :=
{ app := λ x,
match x with
| walking_multicospan.left a := ι _
| walking_multicospan.right b := ι (I.fst_to b) ≫ I.fst b
end,
naturality' := begin
rintros (_|_) (_|_) (_|_|_),
any_goals { symmetry, dsimp, rw category.id_comp, apply category.comp_id },
{ dsimp, rw category.id_comp, refl },
{ dsimp, rw category.id_comp, apply w }
end } }
@[simp, reassoc]
lemma condition (b) :
K.ι (I.fst_to b) ≫ I.fst b = K.ι (I.snd_to b) ≫ I.snd b :=
by rw [←app_right_eq_ι_comp_fst, ←app_right_eq_ι_comp_snd]
/-- This definition provides a convenient way to show that a multifork is a limit. -/
@[simps]
def is_limit.mk
(lift : Π (E : multifork I), E.X ⟶ K.X)
(fac : ∀ (E : multifork I) (i : I.L), lift E ≫ K.ι i = E.ι i)
(uniq : ∀ (E : multifork I) (m : E.X ⟶ K.X),
(∀ i : I.L, m ≫ K.ι i = E.ι i) → m = lift E) : is_limit K :=
{ lift := lift,
fac' := begin
rintros E (a|b),
{ apply fac },
{ rw [← E.w (walking_multicospan.hom.fst b), ← K.w (walking_multicospan.hom.fst b),
← category.assoc],
congr' 1,
apply fac }
end,
uniq' := begin
rintros E m hm,
apply uniq,
intros i,
apply hm,
end }
variables [has_product I.left] [has_product I.right]
@[simp, reassoc]
lemma pi_condition : pi.lift K.ι ≫ I.fst_pi_map = pi.lift K.ι ≫ I.snd_pi_map :=
by { ext, discrete_cases, simp, }
/-- Given a multifork, we may obtain a fork over `∏ I.left ⇉ ∏ I.right`. -/
@[simps X] noncomputable
def to_pi_fork (K : multifork I) : fork I.fst_pi_map I.snd_pi_map :=
{ X := K.X,
π :=
{ app := λ x,
match x with
| walking_parallel_pair.zero := pi.lift K.ι
| walking_parallel_pair.one := pi.lift K.ι ≫ I.fst_pi_map
end,
naturality' :=
begin
rintros (_|_) (_|_) (_|_|_),
any_goals { symmetry, dsimp, rw category.id_comp, apply category.comp_id },
all_goals { change 𝟙 _ ≫ _ ≫ _ = pi.lift _ ≫ _, simp }
end } }
@[simp] lemma to_pi_fork_π_app_zero : K.to_pi_fork.ι = pi.lift K.ι := rfl
@[simp] lemma to_pi_fork_π_app_one :
K.to_pi_fork.π.app walking_parallel_pair.one = pi.lift K.ι ≫ I.fst_pi_map := rfl
variable (I)
/-- Given a fork over `∏ I.left ⇉ ∏ I.right`, we may obtain a multifork. -/
@[simps X] noncomputable
def of_pi_fork (c : fork I.fst_pi_map I.snd_pi_map) : multifork I :=
{ X := c.X,
π :=
{ app := λ x,
match x with
| walking_multicospan.left a := c.ι ≫ pi.π _ _
| walking_multicospan.right b := c.ι ≫ I.fst_pi_map ≫ pi.π _ _
end,
naturality' :=
begin
rintros (_|_) (_|_) (_|_|_),
any_goals { symmetry, dsimp, rw category.id_comp, apply category.comp_id },
{ change 𝟙 _ ≫ _ ≫ _ = (_ ≫ _) ≫ _, simp },
{ change 𝟙 _ ≫ _ ≫ _ = (_ ≫ _) ≫ _, rw c.condition_assoc, simp }
end } }
@[simp] lemma of_pi_fork_π_app_left (c : fork I.fst_pi_map I.snd_pi_map) (a) :
(of_pi_fork I c).ι a = c.ι ≫ pi.π _ _ := rfl
@[simp] lemma of_pi_fork_π_app_right (c : fork I.fst_pi_map I.snd_pi_map) (a) :
(of_pi_fork I c).π.app (walking_multicospan.right a) = c.ι ≫ I.fst_pi_map ≫ pi.π _ _ := rfl
end multifork
namespace multicospan_index
variables (I : multicospan_index C) [has_product I.left] [has_product I.right]
local attribute [tidy] tactic.case_bash
/-- `multifork.to_pi_fork` is functorial. -/
@[simps] noncomputable
def to_pi_fork_functor : multifork I ⥤ fork I.fst_pi_map I.snd_pi_map :=
{ obj := multifork.to_pi_fork,
map := λ K₁ K₂ f,
{ hom := f.hom,
w' := begin
rintro (_|_),
{ ext, dsimp, simp },
{ ext,
simp only [multifork.to_pi_fork_π_app_one, multifork.pi_condition, category.assoc],
dsimp [snd_pi_map],
simp },
end } }
/-- `multifork.of_pi_fork` is functorial. -/
@[simps] noncomputable
def of_pi_fork_functor : fork I.fst_pi_map I.snd_pi_map ⥤ multifork I :=
{ obj := multifork.of_pi_fork I, map := λ K₁ K₂ f, { hom := f.hom, w' := by rintros (_|_); simp } }
/--
The category of multiforks is equivalent to the category of forks over `∏ I.left ⇉ ∏ I.right`.
It then follows from `category_theory.is_limit_of_preserves_cone_terminal` (or `reflects`) that it
preserves and reflects limit cones.
-/
@[simps] noncomputable
def multifork_equiv_pi_fork : multifork I ≌ fork I.fst_pi_map I.snd_pi_map :=
{ functor := to_pi_fork_functor I,
inverse := of_pi_fork_functor I,
unit_iso := nat_iso.of_components (λ K, cones.ext (iso.refl _)
(by { rintros (_|_); dsimp; simp[←fork.app_one_eq_ι_comp_left, -fork.app_one_eq_ι_comp_left] }))
(λ K₁ K₂ f, by { ext, simp }),
counit_iso := nat_iso.of_components (λ K, fork.ext (iso.refl _) (by { ext ⟨j⟩, dsimp, simp }))
(λ K₁ K₂ f, by { ext, simp }) }
end multicospan_index
namespace multicofork
variables {I : multispan_index C} (K : multicofork I)
/-- The maps to the cocone point of a multicofork from the objects on the right. -/
def π (b : I.R) : I.right b ⟶ K.X :=
K.ι.app (walking_multispan.right _)
@[simp] lemma π_eq_app_right (b) : K.ι.app (walking_multispan.right _) = K.π b := rfl
@[simp] lemma fst_app_right (a) :
K.ι.app (walking_multispan.left a) = I.fst a ≫ K.π _ :=
by { rw ← K.w (walking_multispan.hom.fst a), refl }
@[reassoc] lemma snd_app_right (a) :
K.ι.app (walking_multispan.left a) = I.snd a ≫ K.π _ :=
by { rw ← K.w (walking_multispan.hom.snd a), refl }
/-- Construct a multicofork using a collection `π` of morphisms. -/
@[simps]
def of_π (I : multispan_index C) (P : C) (π : Π b, I.right b ⟶ P)
(w : ∀ a, I.fst a ≫ π (I.fst_from a) = I.snd a ≫ π (I.snd_from a)) :
multicofork I :=
{ X := P,
ι :=
{ app := λ x,
match x with
| walking_multispan.left a := I.fst a ≫ π _
| walking_multispan.right b := π _
end,
naturality' := begin
rintros (_|_) (_|_) (_|_|_),
any_goals { dsimp, rw category.comp_id, apply category.id_comp },
{ dsimp, rw category.comp_id, refl },
{ dsimp, rw category.comp_id, apply (w _).symm }
end } }
@[simp, reassoc]
lemma condition (a) : I.fst a ≫ K.π (I.fst_from a) = I.snd a ≫ K.π (I.snd_from a) :=
by rw [←K.snd_app_right, ←K.fst_app_right]
/-- This definition provides a convenient way to show that a multicofork is a colimit. -/
@[simps]
def is_colimit.mk
(desc : Π (E : multicofork I), K.X ⟶ E.X)
(fac : ∀ (E : multicofork I) (i : I.R), K.π i ≫ desc E = E.π i)
(uniq : ∀ (E : multicofork I) (m : K.X ⟶ E.X),
(∀ i : I.R, K.π i ≫ m = E.π i) → m = desc E) : is_colimit K :=
{ desc := desc,
fac' := begin
rintros S (a|b),
{ rw [← K.w (walking_multispan.hom.fst a), ← S.w (walking_multispan.hom.fst a),
category.assoc],
congr' 1,
apply fac },
{ apply fac },
end,
uniq' := begin
intros S m hm,
apply uniq,
intros i,
apply hm
end }
variables [has_coproduct I.left] [has_coproduct I.right]
@[simp, reassoc]
lemma sigma_condition :
I.fst_sigma_map ≫ sigma.desc K.π = I.snd_sigma_map ≫ sigma.desc K.π :=
by { ext, discrete_cases, simp, }
/-- Given a multicofork, we may obtain a cofork over `∐ I.left ⇉ ∐ I.right`. -/
@[simps X] noncomputable
def to_sigma_cofork (K : multicofork I) : cofork I.fst_sigma_map I.snd_sigma_map :=
{ X := K.X,
ι :=
{ app := λ x,
match x with
| walking_parallel_pair.zero := I.fst_sigma_map ≫ sigma.desc K.π
| walking_parallel_pair.one := sigma.desc K.π
end,
naturality' :=
begin
rintros (_|_) (_|_) (_|_|_),
any_goals { dsimp, rw category.comp_id, apply category.id_comp },
all_goals { change _ ≫ sigma.desc _ = (_ ≫ _) ≫ 𝟙 _, simp }
end } }
@[simp] lemma to_sigma_cofork_π : K.to_sigma_cofork.π = sigma.desc K.π := rfl
variable (I)
/-- Given a cofork over `∐ I.left ⇉ ∐ I.right`, we may obtain a multicofork. -/
@[simps X] noncomputable
def of_sigma_cofork (c : cofork I.fst_sigma_map I.snd_sigma_map) : multicofork I :=
{ X := c.X,
ι :=
{ app := λ x,
match x with
| walking_multispan.left a := (sigma.ι I.left a : _) ≫ I.fst_sigma_map ≫ c.π
| walking_multispan.right b := (sigma.ι I.right b : _) ≫ c.π
end,
naturality' :=
begin
rintros (_|_) (_|_) (_|_|_),
any_goals { dsimp, rw category.comp_id, apply category.id_comp },
{ change _ ≫ _ ≫ _ = (_ ≫ _) ≫ _, dsimp,
simp only [cofork.condition, category.comp_id],
rw [←I.ι_fst_sigma_map_assoc, c.condition] },
{ change _ ≫ _ ≫ _ = (_ ≫ _) ≫ 𝟙 _,
rw c.condition, simp }
end } }
@[simp] lemma of_sigma_cofork_ι_app_left (c : cofork I.fst_sigma_map I.snd_sigma_map) (a) :
(of_sigma_cofork I c).ι.app (walking_multispan.left a) =
(sigma.ι I.left a : _) ≫ I.fst_sigma_map ≫ c.π := rfl
@[simp] lemma of_sigma_cofork_ι_app_right (c : cofork I.fst_sigma_map I.snd_sigma_map) (b) :
(of_sigma_cofork I c).ι.app (walking_multispan.right b) = (sigma.ι I.right b : _) ≫ c.π := rfl
end multicofork
namespace multispan_index
variables (I : multispan_index C) [has_coproduct I.left] [has_coproduct I.right]
local attribute [tidy] tactic.case_bash
/-- `multicofork.to_sigma_cofork` is functorial. -/
@[simps] noncomputable
def to_sigma_cofork_functor : multicofork I ⥤ cofork I.fst_sigma_map I.snd_sigma_map :=
{ obj := multicofork.to_sigma_cofork, map := λ K₁ K₂ f, { hom := f.hom } }
/-- `multicofork.of_sigma_cofork` is functorial. -/
@[simps] noncomputable
def of_sigma_cofork_functor : cofork I.fst_sigma_map I.snd_sigma_map ⥤ multicofork I :=
{ obj := multicofork.of_sigma_cofork I,
map := λ K₁ K₂ f, { hom := f.hom, w' := by rintros (_|_); simp } }
/--
The category of multicoforks is equivalent to the category of coforks over `∐ I.left ⇉ ∐ I.right`.
It then follows from `category_theory.is_colimit_of_preserves_cocone_initial` (or `reflects`) that
it preserves and reflects colimit cocones.
-/
@[simps] noncomputable
def multicofork_equiv_sigma_cofork : multicofork I ≌ cofork I.fst_sigma_map I.snd_sigma_map :=
{ functor := to_sigma_cofork_functor I,
inverse := of_sigma_cofork_functor I,
unit_iso := nat_iso.of_components (λ K, cocones.ext (iso.refl _)
(by { rintros (_|_); dsimp; simp }))
(λ K₁ K₂ f, by { ext, simp }),
counit_iso := nat_iso.of_components (λ K, cofork.ext (iso.refl _)
(by { ext ⟨j⟩, dsimp, simp only [category.comp_id, colimit.ι_desc, cofan.mk_ι_app], refl }))
(λ K₁ K₂ f, by { ext, dsimp, simp, }) }
end multispan_index
/-- For `I : multicospan_index C`, we say that it has a multiequalizer if the associated
multicospan has a limit. -/
abbreviation has_multiequalizer (I : multicospan_index C) :=
has_limit I.multicospan
noncomputable theory
/-- The multiequalizer of `I : multicospan_index C`. -/
abbreviation multiequalizer (I : multicospan_index C) [has_multiequalizer I] : C :=
limit I.multicospan
/-- For `I : multispan_index C`, we say that it has a multicoequalizer if
the associated multicospan has a limit. -/
abbreviation has_multicoequalizer (I : multispan_index C) :=
has_colimit I.multispan
/-- The multiecoqualizer of `I : multispan_index C`. -/
abbreviation multicoequalizer (I : multispan_index C) [has_multicoequalizer I] : C :=
colimit I.multispan
namespace multiequalizer
variables (I : multicospan_index C) [has_multiequalizer I]
/-- The canonical map from the multiequalizer to the objects on the left. -/
abbreviation ι (a : I.L) : multiequalizer I ⟶ I.left a :=
limit.π _ (walking_multicospan.left a)
/-- The multifork associated to the multiequalizer. -/
abbreviation multifork : multifork I :=
limit.cone _
@[simp]
lemma multifork_ι (a) :
(multiequalizer.multifork I).ι a = multiequalizer.ι I a := rfl
@[simp]
lemma multifork_π_app_left (a) :
(multiequalizer.multifork I).π.app (walking_multicospan.left a) =
multiequalizer.ι I a := rfl
@[reassoc]
lemma condition (b) :
multiequalizer.ι I (I.fst_to b) ≫ I.fst b =
multiequalizer.ι I (I.snd_to b) ≫ I.snd b :=
multifork.condition _ _
/-- Construct a morphism to the multiequalizer from its universal property. -/
abbreviation lift (W : C) (k : Π a, W ⟶ I.left a)
(h : ∀ b, k (I.fst_to b) ≫ I.fst b = k (I.snd_to b) ≫ I.snd b) :
W ⟶ multiequalizer I :=
limit.lift _ (multifork.of_ι I _ k h)
@[simp, reassoc]
lemma lift_ι (W : C) (k : Π a, W ⟶ I.left a)
(h : ∀ b, k (I.fst_to b) ≫ I.fst b = k (I.snd_to b) ≫ I.snd b) (a) :
multiequalizer.lift I _ k h ≫ multiequalizer.ι I a = k _ :=
limit.lift_π _ _
@[ext]
lemma hom_ext {W : C} (i j : W ⟶ multiequalizer I)
(h : ∀ a, i ≫ multiequalizer.ι I a =
j ≫ multiequalizer.ι I a) :
i = j :=
limit.hom_ext
begin
rintro (a|b),
{ apply h },
simp_rw [← limit.w I.multicospan (walking_multicospan.hom.fst b),
← category.assoc, h],
end
variables [has_product I.left] [has_product I.right]
instance : has_equalizer I.fst_pi_map I.snd_pi_map :=
⟨⟨⟨_,is_limit.of_preserves_cone_terminal
I.multifork_equiv_pi_fork.functor (limit.is_limit _)⟩⟩⟩
/-- The multiequalizer is isomorphic to the equalizer of `∏ I.left ⇉ ∏ I.right`. -/
def iso_equalizer : multiequalizer I ≅ equalizer I.fst_pi_map I.snd_pi_map :=
limit.iso_limit_cone ⟨_, is_limit.of_preserves_cone_terminal
I.multifork_equiv_pi_fork.inverse (limit.is_limit _)⟩
/-- The canonical injection `multiequalizer I ⟶ ∏ I.left`. -/
def ι_pi : multiequalizer I ⟶ ∏ I.left :=
(iso_equalizer I).hom ≫ equalizer.ι I.fst_pi_map I.snd_pi_map
@[simp, reassoc]
lemma ι_pi_π (a) : ι_pi I ≫ pi.π I.left a = ι I a :=
by { rw [ι_pi, category.assoc, ← iso.eq_inv_comp, iso_equalizer], simpa }
instance : mono (ι_pi I) := @@mono_comp _ _ _ _ equalizer.ι_mono
end multiequalizer
namespace multicoequalizer
variables (I : multispan_index C) [has_multicoequalizer I]
/-- The canonical map from the multiequalizer to the objects on the left. -/
abbreviation π (b : I.R) : I.right b ⟶ multicoequalizer I :=
colimit.ι I.multispan (walking_multispan.right _)
/-- The multicofork associated to the multicoequalizer. -/
abbreviation multicofork : multicofork I :=
colimit.cocone _
@[simp]
lemma multicofork_π (b) :
(multicoequalizer.multicofork I).π b = multicoequalizer.π I b := rfl
@[simp]
lemma multicofork_ι_app_right (b) :
(multicoequalizer.multicofork I).ι.app (walking_multispan.right b) =
multicoequalizer.π I b := rfl
@[reassoc]
lemma condition (a) :
I.fst a ≫ multicoequalizer.π I (I.fst_from a) =
I.snd a ≫ multicoequalizer.π I (I.snd_from a) :=
multicofork.condition _ _
/-- Construct a morphism from the multicoequalizer from its universal property. -/
abbreviation desc (W : C) (k : Π b, I.right b ⟶ W)
(h : ∀ a, I.fst a ≫ k (I.fst_from a) = I.snd a ≫ k (I.snd_from a)) :
multicoequalizer I ⟶ W :=
colimit.desc _ (multicofork.of_π I _ k h)
@[simp, reassoc]
lemma π_desc (W : C) (k : Π b, I.right b ⟶ W)
(h : ∀ a, I.fst a ≫ k (I.fst_from a) = I.snd a ≫ k (I.snd_from a)) (b) :
multicoequalizer.π I b ≫ multicoequalizer.desc I _ k h = k _ :=
colimit.ι_desc _ _
@[ext]
lemma hom_ext {W : C} (i j : multicoequalizer I ⟶ W)
(h : ∀ b, multicoequalizer.π I b ≫ i = multicoequalizer.π I b ≫ j) :
i = j :=
colimit.hom_ext
begin
rintro (a|b),
{ simp_rw [← colimit.w I.multispan (walking_multispan.hom.fst a),
category.assoc, h] },
{ apply h },
end
variables [has_coproduct I.left] [has_coproduct I.right]
instance : has_coequalizer I.fst_sigma_map I.snd_sigma_map :=
⟨⟨⟨_,is_colimit.of_preserves_cocone_initial
I.multicofork_equiv_sigma_cofork.functor (colimit.is_colimit _)⟩⟩⟩
/-- The multicoequalizer is isomorphic to the coequalizer of `∐ I.left ⇉ ∐ I.right`. -/
def iso_coequalizer : multicoequalizer I ≅ coequalizer I.fst_sigma_map I.snd_sigma_map :=
colimit.iso_colimit_cocone ⟨_, is_colimit.of_preserves_cocone_initial
I.multicofork_equiv_sigma_cofork.inverse (colimit.is_colimit _)⟩
/-- The canonical projection `∐ I.right ⟶ multicoequalizer I`. -/
def sigma_π : ∐ I.right ⟶ multicoequalizer I :=
coequalizer.π I.fst_sigma_map I.snd_sigma_map ≫ (iso_coequalizer I).inv
@[simp, reassoc]
lemma ι_sigma_π (b) : sigma.ι I.right b ≫ sigma_π I = π I b :=
by { rw [sigma_π, ← category.assoc, iso.comp_inv_eq, iso_coequalizer], simpa }
instance : epi (sigma_π I) := @@epi_comp _ _ coequalizer.π_epi _ _
end multicoequalizer
end category_theory.limits
|
7baf9f9655fcb705826e89f023d160303c158e68 | bbecf0f1968d1fba4124103e4f6b55251d08e9c4 | /src/data/nat/interval.lean | c6cd7876e29a9d2cfa51ae2be623466389f18400 | [
"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 | 6,564 | lean | /-
Copyright (c) 2021 Yaël Dillies. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yaël Dillies
-/
import data.finset.interval
/-!
# Finite intervals of naturals
This file proves that `ℕ` is a `locally_finite_order` and calculates the cardinality of its
intervals as finsets and fintypes.
## TODO
Some lemmas can be generalized using `ordered_group`, `canonically_ordered_monoid` or `succ_order`
and subsequently be moved upstream to `data.finset.interval`.
-/
open finset nat
instance : locally_finite_order ℕ :=
{ finset_Icc := λ a b, (list.range' a (b + 1 - a)).to_finset,
finset_Ico := λ a b, (list.range' a (b - a)).to_finset,
finset_Ioc := λ a b, (list.range' (a + 1) (b - a)).to_finset,
finset_Ioo := λ a b, (list.range' (a + 1) (b - a - 1)).to_finset,
finset_mem_Icc := λ a b x, begin
rw [list.mem_to_finset, list.mem_range'],
cases le_or_lt a b,
{ rw [add_sub_cancel_of_le (nat.lt_succ_of_le h).le, nat.lt_succ_iff] },
{ rw [nat.sub_eq_zero_iff_le.2 h, add_zero],
exact iff_of_false (λ hx, hx.2.not_le hx.1) (λ hx, h.not_le (hx.1.trans hx.2)) }
end,
finset_mem_Ico := λ a b x, begin
rw [list.mem_to_finset, list.mem_range'],
cases le_or_lt a b,
{ rw [add_sub_cancel_of_le h] },
{ rw [nat.sub_eq_zero_iff_le.2 h.le, add_zero],
exact iff_of_false (λ hx, hx.2.not_le hx.1) (λ hx, h.not_le (hx.1.trans hx.2.le)) }
end,
finset_mem_Ioc := λ a b x, begin
rw [list.mem_to_finset, list.mem_range'],
cases le_or_lt a b,
{ rw [←succ_sub_succ, add_sub_cancel_of_le (succ_le_succ h), nat.lt_succ_iff,
nat.succ_le_iff] },
{ rw [nat.sub_eq_zero_iff_le.2 h.le, add_zero],
exact iff_of_false (λ hx, hx.2.not_le hx.1) (λ hx, h.not_le (hx.1.le.trans hx.2)) }
end,
finset_mem_Ioo := λ a b x, begin
rw [list.mem_to_finset, list.mem_range', nat.sub_sub],
cases le_or_lt (a + 1) b,
{ rw [add_sub_cancel_of_le h, nat.succ_le_iff] },
{ rw [nat.sub_eq_zero_iff_le.2 h.le, add_zero],
exact iff_of_false (λ hx, hx.2.not_le hx.1) (λ hx, h.not_le (hx.1.trans hx.2)) }
end }
namespace nat
variables (a b c : ℕ)
lemma Icc_eq_range' : Icc a b = (list.range' a (b + 1 - a)).to_finset := rfl
lemma Ico_eq_range' : Ico a b = (list.range' a (b - a)).to_finset := rfl
lemma Ioc_eq_range' : Ioc a b = (list.range' (a + 1) (b - a)).to_finset := rfl
lemma Ioo_eq_range' : Ioo a b = (list.range' (a + 1) (b - a - 1)).to_finset := rfl
lemma Iio_eq_range : Iio = range :=
by { ext b x, rw [mem_Iio, mem_range] }
lemma Ico_zero_eq_range : Ico 0 a = range a :=
by rw [←bot_eq_zero, ←Iio_eq_Ico, Iio_eq_range]
lemma _root_.finset.range_eq_Ico : range = Ico 0 := by { funext, exact (Ico_zero_eq_range n).symm }
@[simp] lemma card_Icc : (Icc a b).card = b + 1 - a :=
by rw [Icc_eq_range', list.card_to_finset, (list.nodup_range' _ _).erase_dup, list.length_range']
@[simp] lemma card_Ico : (Ico a b).card = b - a :=
by rw [Ico_eq_range', list.card_to_finset, (list.nodup_range' _ _).erase_dup, list.length_range']
@[simp] lemma card_Ioc : (Ioc a b).card = b - a :=
by rw [Ioc_eq_range', list.card_to_finset, (list.nodup_range' _ _).erase_dup, list.length_range']
@[simp] lemma card_Ioo : (Ioo a b).card = b - a - 1 :=
by rw [Ioo_eq_range', list.card_to_finset, (list.nodup_range' _ _).erase_dup, list.length_range']
@[simp] lemma card_fintype_Icc : fintype.card (set.Icc a b) = b + 1 - a :=
by rw [←card_Icc, fintype.card_of_finset]
@[simp] lemma card_fintype_Ico : fintype.card (set.Ico a b) = b - a :=
by rw [←card_Ico, fintype.card_of_finset]
@[simp] lemma card_fintype_Ioc : fintype.card (set.Ioc a b) = b - a :=
by rw [←card_Ioc, fintype.card_of_finset]
@[simp] lemma card_fintype_Ioo : fintype.card (set.Ioo a b) = b - a - 1 :=
by rw [←card_Ioo, fintype.card_of_finset]
-- TODO@Yaël: Generalize all the following lemmas to `succ_order`
lemma Icc_succ_left : Icc a.succ b = Ioc a b :=
by { ext x, rw [mem_Icc, mem_Ioc, succ_le_iff] }
lemma Ico_succ_right : Ico a b.succ = Icc a b :=
by { ext x, rw [mem_Ico, mem_Icc, lt_succ_iff] }
lemma Ico_succ_left : Ico a.succ b = Ioo a b :=
by { ext x, rw [mem_Ico, mem_Ioo, succ_le_iff] }
lemma Icc_pred_right {b : ℕ} (h : 0 < b) : Icc a (b - 1) = Ico a b :=
by { ext x, rw [mem_Icc, mem_Ico, lt_iff_le_pred h] }
lemma Ico_succ_succ : Ico a.succ b.succ = Ioc a b :=
by { ext x, rw [mem_Ico, mem_Ioc, succ_le_iff, lt_succ_iff] }
@[simp] lemma Ico_succ_singleton : Ico a (a + 1) = {a} :=
by rw [Ico_succ_right, Icc_self]
@[simp] lemma Ico_pred_singleton {a : ℕ} (h : 0 < a) : Ico (a - 1) a = {a - 1} :=
by rw [←Icc_pred_right _ h, Icc_self]
variables {a b c}
lemma Ico_succ_right_eq_insert_Ico (h : a ≤ b) : Ico a (b + 1) = insert b (Ico a b) :=
by rw [Ico_succ_right, ←Ico_insert_right h]
lemma Ico_insert_succ_left (h : a < b) : insert a (Ico a.succ b) = Ico a b :=
by rw [Ico_succ_left, ←Ioo_insert_left h]
lemma image_sub_const_Ico (h : c ≤ a) :
(Ico a b).image (λ x, x - c) = Ico (a - c) (b - c) :=
begin
ext x,
rw mem_image,
split,
{ rintro ⟨x, hx, rfl⟩,
rw [mem_Ico] at ⊢ hx,
exact ⟨sub_le_sub_right' hx.1 _, sub_lt_sub_right_of_le (h.trans hx.1) hx.2⟩ },
{ rintro h,
refine ⟨x + c, _, add_sub_cancel_right _ _⟩,
rw mem_Ico at ⊢ h,
exact ⟨sub_le_iff_right.1 h.1, lt_sub_iff_right.1 h.2⟩ }
end
lemma Ico_image_const_sub_eq_Ico (hac : a ≤ c) :
(Ico a b).image (λ x, c - x) = Ico (c + 1 - b) (c + 1 - a) :=
begin
ext x,
rw [mem_image, mem_Ico],
split,
{ rintro ⟨x, hx, rfl⟩,
rw mem_Ico at hx,
refine ⟨_, ((sub_le_sub_iff_left' hac).2 hx.1).trans_lt ((sub_lt_sub_iff_right' hac).2
(nat.lt_succ_self _))⟩,
cases lt_or_le c b,
{ rw nat.sub_eq_zero_of_le h,
exact zero_le _ },
{ rw ←succ_sub_succ c,
exact (sub_le_sub_iff_left' (succ_le_succ $ hx.2.le.trans h)).2 hx.2 } },
{ rintro ⟨hb, ha⟩,
rw [lt_sub_iff_left, lt_succ_iff] at ha,
have hx : x ≤ c := (nat.le_add_left _ _).trans ha,
refine ⟨c - x, _, nat.sub_sub_self hx⟩,
{ rw mem_Ico,
exact ⟨le_sub_of_add_le_right' ha, (sub_lt_iff_left hx).2 $ succ_le_iff.1 $
sub_le_iff_right.1 hb⟩ } }
end
lemma range_image_pred_top_sub (n : ℕ) :
(finset.range n).image (λ j, n - 1 - j) = finset.range n :=
begin
cases n,
{ rw [range_zero, image_empty] },
{ rw [finset.range_eq_Ico, Ico_image_const_sub_eq_Ico (zero_le _)],
simp_rw [succ_sub_succ, nat.sub_zero, nat.sub_self] }
end
end nat
|
bdc434a0c303c8576ff6c42c6fbba4c9f784de75 | b70031c8e2c5337b91d7e70f1e0c5f528f7b0e77 | /src/analysis/calculus/times_cont_diff.lean | 42cde032a3ff121adaff3197abbfb05a227b6ddb | [
"Apache-2.0"
] | permissive | molodiuc/mathlib | cae2ba3ef1601c1f42ca0b625c79b061b63fef5b | 98ebe5a6739fbe254f9ee9d401882d4388f91035 | refs/heads/master | 1,674,237,127,059 | 1,606,353,533,000 | 1,606,353,533,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 134,003 | 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.calculus.mean_value
/-!
# Higher differentiability
A function is `C^1` on a domain if it is differentiable there, and its derivative is continuous.
By induction, it is `C^n` if it is `C^{n-1}` and its (n-1)-th derivative is `C^1` there or,
equivalently, if it is `C^1` and its derivative is `C^{n-1}`.
Finally, it is `C^∞` if it is `C^n` for all n.
We formalize these notions by defining iteratively the `n+1`-th derivative of a function as the
derivative of the `n`-th derivative. It is called `iterated_fderiv 𝕜 n f x` where `𝕜` is the
field, `n` is the number of iterations, `f` is the function and `x` is the point, and it is given
as an `n`-multilinear map. We also define a version `iterated_fderiv_within` relative to a domain,
as well as predicates `times_cont_diff_within_at`, `times_cont_diff_at`, `times_cont_diff_on` and
`times_cont_diff` saying that the function is `C^n` within a set at a point, at a point, on a set
and on the whole space respectively.
To avoid the issue of choice when choosing a derivative in sets where the derivative is not
necessarily unique, `times_cont_diff_on` is not defined directly in terms of the
regularity of the specific choice `iterated_fderiv_within 𝕜 n f s` inside `s`, but in terms of the
existence of a nice sequence of derivatives, expressed with a predicate
`has_ftaylor_series_up_to_on`.
We prove basic properties of these notions.
## Main definitions and results
Let `f : E → F` be a map between normed vector spaces over a nondiscrete normed field `𝕜`.
* `formal_multilinear_series 𝕜 E F`: a family of `n`-multilinear maps for all `n`, designed to
model the sequence of derivatives of a function.
* `has_ftaylor_series_up_to n f p`: expresses that the formal multilinear series `p` is a sequence
of iterated derivatives of `f`, up to the `n`-th term (where `n` is a natural number or `∞`).
* `has_ftaylor_series_up_to_on n f p s`: same thing, but inside a set `s`. The notion of derivative
is now taken inside `s`. In particular, derivatives don't have to be unique.
* `times_cont_diff 𝕜 n f`: expresses that `f` is `C^n`, i.e., it admits a Taylor series up to
rank `n`.
* `times_cont_diff_on 𝕜 n f s`: expresses that `f` is `C^n` in `s`.
* `times_cont_diff_at 𝕜 n f x`: expresses that `f` is `C^n` around `x`.
* `times_cont_diff_within_at 𝕜 n f s x`: expresses that `f` is `C^n` around `x` within the set `s`.
* `iterated_fderiv_within 𝕜 n f s x` is an `n`-th derivative of `f` over the field `𝕜` on the
set `s` at the point `x`. It is a continuous multilinear map from `E^n` to `F`, defined as a
derivative within `s` of `iterated_fderiv_within 𝕜 (n-1) f s` if one exists, and `0` otherwise.
* `iterated_fderiv 𝕜 n f x` is the `n`-th derivative of `f` over the field `𝕜` at the point `x`.
It is a continuous multilinear map from `E^n` to `F`, defined as a derivative of
`iterated_fderiv 𝕜 (n-1) f` if one exists, and `0` otherwise.
In sets of unique differentiability, `times_cont_diff_on 𝕜 n f s` can be expressed in terms of the
properties of `iterated_fderiv_within 𝕜 m f s` for `m ≤ n`. In the whole space,
`times_cont_diff 𝕜 n f` can be expressed in terms of the properties of `iterated_fderiv 𝕜 m f`
for `m ≤ n`.
We also prove that the usual operations (addition, multiplication, difference, composition, and
so on) preserve `C^n` functions.
## Implementation notes
The definitions in this file are designed to work on any field `𝕜`. They are sometimes slightly more
complicated than the naive definitions one would guess from the intuition over the real or complex
numbers, but they are designed to circumvent the lack of gluing properties and partitions of unity
in general. In the usual situations, they coincide with the usual definitions.
### Definition of `C^n` functions in domains
One could define `C^n` functions in a domain `s` by fixing an arbitrary choice of derivatives (this
is what we do with `iterated_fderiv_within`) and requiring that all these derivatives up to `n` are
continuous. If the derivative is not unique, this could lead to strange behavior like two `C^n`
functions `f` and `g` on `s` whose sum is not `C^n`. A better definition is thus to say that a
function is `C^n` inside `s` if it admits a sequence of derivatives up to `n` inside `s`.
This definition still has the problem that a function which is locally `C^n` would not need to
be `C^n`, as different choices of sequences of derivatives around different points might possibly
not be glued together to give a globally defined sequence of derivatives. (Note that this issue
can not happen over reals, thanks to partition of unity, but the behavior over a general field is
not so clear, and we want a definition for general fields). Also, there are locality
problems for the order parameter: one could image a function which, for each `n`, has a nice
sequence of derivatives up to order `n`, but they do not coincide for varying `n` and can therefore
not be glued to give rise to an infinite sequence of derivatives. This would give a function
which is `C^n` for all `n`, but not `C^∞`. We solve this issue by putting locality conditions
in space and order in our definition of `times_cont_diff_within_at` and `times_cont_diff_on`.
The resulting definition is slightly more complicated to work with (in fact not so much), but it
gives rise to completely satisfactory theorems.
For instance, with this definition, a real function which is `C^m` (but not better) on `(-1/m, 1/m)`
for each natural `m` is by definition `C^∞` at `0`.
There is another issue with the definition of `times_cont_diff_within_at 𝕜 n f s x`. We can
require the existence and good behavior of derivatives up to order `n` on a neighborhood of `x`
within `s`. However, this does not imply continuity or differentiability within `s` of the function
at `x` when `x` does not belong to `s`. Therefore, we require such existence and good behavior on
a neighborhood of `x` within `s ∪ {x}` (which appears as `insert x s` in this file).
### Side of the composition, and universe issues
With a naïve direct definition, the `n`-th derivative of a function belongs to the space
`E →L[𝕜] (E →L[𝕜] (E ... F)...)))` where there are n iterations of `E →L[𝕜]`. This space
may also be seen as the space of continuous multilinear functions on `n` copies of `E` with
values in `F`, by uncurrying. This is the point of view that is usually adopted in textbooks,
and that we also use. This means that the definition and the first proofs are slightly involved,
as one has to keep track of the uncurrying operation. The uncurrying can be done from the
left or from the right, amounting to defining the `n+1`-th derivative either as the derivative of
the `n`-th derivative, or as the `n`-th derivative of the derivative.
For proofs, it would be more convenient to use the latter approach (from the right),
as it means to prove things at the `n+1`-th step we only need to understand well enough the
derivative in `E →L[𝕜] F` (contrary to the approach from the left, where one would need to know
enough on the `n`-th derivative to deduce things on the `n+1`-th derivative).
However, the definition from the right leads to a universe polymorphism problem: if we define
`iterated_fderiv 𝕜 (n + 1) f x = iterated_fderiv 𝕜 n (fderiv 𝕜 f) x` by induction, we need to
generalize over all spaces (as `f` and `fderiv 𝕜 f` don't take values in the same space). It is
only possible to generalize over all spaces in some fixed universe in an inductive definition.
For `f : E → F`, then `fderiv 𝕜 f` is a map `E → (E →L[𝕜] F)`. Therefore, the definition will only
work if `F` and `E →L[𝕜] F` are in the same universe.
This issue does not appear with the definition from the left, where one does not need to generalize
over all spaces. Therefore, we use the definition from the left. This means some proofs later on
become a little bit more complicated: to prove that a function is `C^n`, the most efficient approach
is to exhibit a formula for its `n`-th derivative and prove it is continuous (contrary to the
inductive approach where one would prove smoothness statements without giving a formula for the
derivative). In the end, this approach is still satisfactory as it is good to have formulas for the
iterated derivatives in various constructions.
One point where we depart from this explicit approach is in the proof of smoothness of a
composition: there is a formula for the `n`-th derivative of a composition (Faà di Bruno's formula),
but it is very complicated and barely usable, while the inductive proof is very simple. Thus, we
give the inductive proof. As explained above, it works by generalizing over the target space, hence
it only works well if all spaces belong to the same universe. To get the general version, we lift
things to a common universe using a trick.
### Variables management
The textbook definitions and proofs use various identifications and abuse of notations, for instance
when saying that the natural space in which the derivative lives, i.e.,
`E →L[𝕜] (E →L[𝕜] ( ... →L[𝕜] F))`, is the same as a space of multilinear maps. When doing things
formally, we need to provide explicit maps for these identifications, and chase some diagrams to see
everything is compatible with the identifications. In particular, one needs to check that taking the
derivative and then doing the identification, or first doing the identification and then taking the
derivative, gives the same result. The key point for this is that taking the derivative commutes
with continuous linear equivalences. Therefore, we need to implement all our identifications with
continuous linear equivs.
## 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.
In this file, we denote `⊤ : with_top ℕ` with `∞`.
## Tags
derivative, differentiability, higher derivative, `C^n`, multilinear, Taylor series, formal series
-/
noncomputable theory
open_locale classical big_operators
local notation `∞` := (⊤ : with_top ℕ)
universes u v w
local attribute [instance, priority 1001]
normed_group.to_add_comm_group normed_space.to_semimodule add_comm_group.to_add_comm_monoid
open set fin
open_locale topological_space
variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜]
{E : Type*} [normed_group E] [normed_space 𝕜 E]
{F : Type*} [normed_group F] [normed_space 𝕜 F]
{G : Type*} [normed_group G] [normed_space 𝕜 G]
{s s₁ t u : set E} {f f₁ : E → F} {g : F → G} {x : E} {c : F}
{b : E × F → 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]
def formal_multilinear_series
(𝕜 : Type*) [nondiscrete_normed_field 𝕜]
(E : Type*) [normed_group E] [normed_space 𝕜 E]
(F : Type*) [normed_group F] [normed_space 𝕜 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. -/
local attribute [reducible] formal_multilinear_series
instance : module 𝕜 (formal_multilinear_series 𝕜 E F) :=
begin
letI : ∀ n, module 𝕜 (continuous_multilinear_map 𝕜 (λ (i : fin n), E) F) :=
λ n, by apply_instance,
apply_instance
end
end module
namespace formal_multilinear_series
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 𝕜 (λ (i : fin (n + 1)), E) F) (q n)
/-- 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 }
end formal_multilinear_series
/-! ### Functions with a Taylor series on a domain -/
variable {p : E → formal_multilinear_series 𝕜 E F}
/-- `has_ftaylor_series_up_to_on n f p s` registers the fact that `p 0 = f` and `p (m+1)` is a
derivative of `p m` for `m < n`, and is continuous for `m ≤ n`. This is a predicate analogous to
`has_fderiv_within_at` but for higher order derivatives. -/
structure has_ftaylor_series_up_to_on (n : with_top ℕ)
(f : E → F) (p : E → formal_multilinear_series 𝕜 E F) (s : set E) : Prop :=
(zero_eq : ∀ x ∈ s, (p x 0).uncurry0 = f x)
(fderiv_within : ∀ (m : ℕ) (hm : (m : with_top ℕ) < n), ∀ x ∈ s,
has_fderiv_within_at (λ y, p y m) (p x m.succ).curry_left s x)
(cont : ∀ (m : ℕ) (hm : (m : with_top ℕ) ≤ n), continuous_on (λ x, p x m) s)
lemma has_ftaylor_series_up_to_on.zero_eq' {n : with_top ℕ}
(h : has_ftaylor_series_up_to_on n f p s) {x : E} (hx : x ∈ s) :
p x 0 = (continuous_multilinear_curry_fin0 𝕜 E F).symm (f x) :=
by { rw ← h.zero_eq x hx, symmetry, exact continuous_multilinear_map.uncurry0_curry0 _ }
/-- If two functions coincide on a set `s`, then a Taylor series for the first one is as well a
Taylor series for the second one. -/
lemma has_ftaylor_series_up_to_on.congr {n : with_top ℕ}
(h : has_ftaylor_series_up_to_on n f p s) (h₁ : ∀ x ∈ s, f₁ x = f x) :
has_ftaylor_series_up_to_on n f₁ p s :=
begin
refine ⟨λ x hx, _, h.fderiv_within, h.cont⟩,
rw h₁ x hx,
exact h.zero_eq x hx
end
lemma has_ftaylor_series_up_to_on.mono {n : with_top ℕ}
(h : has_ftaylor_series_up_to_on n f p s) {t : set E} (hst : t ⊆ s) :
has_ftaylor_series_up_to_on n f p t :=
⟨λ x hx, h.zero_eq x (hst hx),
λ m hm x hx, (h.fderiv_within m hm x (hst hx)).mono hst,
λ m hm, (h.cont m hm).mono hst⟩
lemma has_ftaylor_series_up_to_on.of_le {m n : with_top ℕ}
(h : has_ftaylor_series_up_to_on n f p s) (hmn : m ≤ n) :
has_ftaylor_series_up_to_on m f p s :=
⟨h.zero_eq,
λ k hk x hx, h.fderiv_within k (lt_of_lt_of_le hk hmn) x hx,
λ k hk, h.cont k (le_trans hk hmn)⟩
lemma has_ftaylor_series_up_to_on.continuous_on {n : with_top ℕ}
(h : has_ftaylor_series_up_to_on n f p s) : continuous_on f s :=
begin
have := (h.cont 0 bot_le).congr (λ x hx, (h.zero_eq' hx).symm),
rwa continuous_linear_equiv.comp_continuous_on_iff at this
end
lemma has_ftaylor_series_up_to_on_zero_iff :
has_ftaylor_series_up_to_on 0 f p s ↔ continuous_on f s ∧ (∀ x ∈ s, (p x 0).uncurry0 = f x) :=
begin
refine ⟨λ H, ⟨H.continuous_on, H.zero_eq⟩,
λ H, ⟨H.2, λ m hm, false.elim (not_le.2 hm bot_le), _⟩⟩,
assume m hm,
have : (m : with_top ℕ) = ((0 : ℕ) : with_bot ℕ) := le_antisymm hm bot_le,
rw with_top.coe_eq_coe at this,
rw this,
have : ∀ x ∈ s, p x 0 = (continuous_multilinear_curry_fin0 𝕜 E F).symm (f x),
by { assume x hx, rw ← H.2 x hx, symmetry, exact continuous_multilinear_map.uncurry0_curry0 _ },
rw [continuous_on_congr this, continuous_linear_equiv.comp_continuous_on_iff],
exact H.1
end
lemma has_ftaylor_series_up_to_on_top_iff :
(has_ftaylor_series_up_to_on ∞ f p s) ↔ (∀ (n : ℕ), has_ftaylor_series_up_to_on n f p s) :=
begin
split,
{ assume H n, exact H.of_le le_top },
{ assume H,
split,
{ exact (H 0).zero_eq },
{ assume m hm,
apply (H m.succ).fderiv_within m (with_top.coe_lt_coe.2 (lt_add_one m)) },
{ assume m hm,
apply (H m).cont m (le_refl _) } }
end
/-- If a function has a Taylor series at order at least `1`, then the term of order `1` of this
series is a derivative of `f`. -/
lemma has_ftaylor_series_up_to_on.has_fderiv_within_at {n : with_top ℕ}
(h : has_ftaylor_series_up_to_on n f p s) (hn : 1 ≤ n) (hx : x ∈ s) :
has_fderiv_within_at f (continuous_multilinear_curry_fin1 𝕜 E F (p x 1)) s x :=
begin
have A : ∀ y ∈ s, f y = (continuous_multilinear_curry_fin0 𝕜 E F) (p y 0),
{ assume y hy, rw ← h.zero_eq y hy, refl },
suffices H : has_fderiv_within_at
(λ y, continuous_multilinear_curry_fin0 𝕜 E F (p y 0))
(continuous_multilinear_curry_fin1 𝕜 E F (p x 1)) s x,
by exact H.congr A (A x hx),
rw continuous_linear_equiv.comp_has_fderiv_within_at_iff',
have : ((0 : ℕ) : with_top ℕ) < n :=
lt_of_lt_of_le (with_top.coe_lt_coe.2 nat.zero_lt_one) hn,
convert h.fderiv_within _ this x hx,
ext y v,
change (p x 1) (snoc 0 y) = (p x 1) (cons y v),
unfold_coes,
congr' with i,
rw unique.eq_default i,
refl
end
lemma has_ftaylor_series_up_to_on.differentiable_on {n : with_top ℕ}
(h : has_ftaylor_series_up_to_on n f p s) (hn : 1 ≤ n) : differentiable_on 𝕜 f s :=
λ x hx, (h.has_fderiv_within_at hn hx).differentiable_within_at
/-- `p` is a Taylor series of `f` up to `n+1` if and only if `p` is a Taylor series up to `n`, and
`p (n + 1)` is a derivative of `p n`. -/
theorem has_ftaylor_series_up_to_on_succ_iff_left {n : ℕ} :
has_ftaylor_series_up_to_on (n + 1) f p s ↔
has_ftaylor_series_up_to_on n f p s
∧ (∀ x ∈ s, has_fderiv_within_at (λ y, p y n) (p x n.succ).curry_left s x)
∧ continuous_on (λ x, p x (n + 1)) s :=
begin
split,
{ assume h,
exact ⟨h.of_le (with_top.coe_le_coe.2 (nat.le_succ n)),
h.fderiv_within _ (with_top.coe_lt_coe.2 (lt_add_one n)),
h.cont (n + 1) (le_refl _)⟩ },
{ assume h,
split,
{ exact h.1.zero_eq },
{ assume m hm,
by_cases h' : m < n,
{ exact h.1.fderiv_within m (with_top.coe_lt_coe.2 h') },
{ have : m = n := nat.eq_of_lt_succ_of_not_lt (with_top.coe_lt_coe.1 hm) h',
rw this,
exact h.2.1 } },
{ assume m hm,
by_cases h' : m ≤ n,
{ apply h.1.cont m (with_top.coe_le_coe.2 h') },
{ have : m = (n + 1) := le_antisymm (with_top.coe_le_coe.1 hm) (not_le.1 h'),
rw this,
exact h.2.2 } } }
end
/-- `p` is a Taylor series of `f` up to `n+1` if and only if `p.shift` is a Taylor series up to `n`
for `p 1`, which is a derivative of `f`. -/
theorem has_ftaylor_series_up_to_on_succ_iff_right {n : ℕ} :
has_ftaylor_series_up_to_on ((n + 1) : ℕ) f p s ↔
(∀ x ∈ s, (p x 0).uncurry0 = f x)
∧ (∀ x ∈ s, has_fderiv_within_at (λ y, p y 0) (p x 1).curry_left s x)
∧ has_ftaylor_series_up_to_on n
(λ x, continuous_multilinear_curry_fin1 𝕜 E F (p x 1)) (λ x, (p x).shift) s :=
begin
split,
{ assume H,
refine ⟨H.zero_eq, H.fderiv_within 0 (with_top.coe_lt_coe.2 (nat.succ_pos n)), _⟩,
split,
{ assume x hx, refl },
{ assume m (hm : (m : with_top ℕ) < n) x (hx : x ∈ s),
have A : (m.succ : with_top ℕ) < n.succ,
by { rw with_top.coe_lt_coe at ⊢ hm, exact nat.lt_succ_iff.mpr hm },
change has_fderiv_within_at
((continuous_multilinear_curry_right_equiv 𝕜 (λ i : fin m.succ, E) F).symm
∘ (λ (y : E), p y m.succ))
(p x m.succ.succ).curry_right.curry_left s x,
rw continuous_linear_equiv.comp_has_fderiv_within_at_iff',
convert H.fderiv_within _ A x hx,
ext y v,
change (p x m.succ.succ) (snoc (cons y (init v)) (v (last _)))
= (p x (nat.succ (nat.succ m))) (cons y v),
rw [← cons_snoc_eq_snoc_cons, snoc_init_self] },
{ assume m (hm : (m : with_top ℕ) ≤ n),
have A : (m.succ : with_top ℕ) ≤ n.succ,
by { rw with_top.coe_le_coe at ⊢ hm, exact nat.pred_le_iff.mp hm },
change continuous_on ((continuous_multilinear_curry_right_equiv 𝕜 (λ i : fin m.succ, E) F).symm
∘ (λ (y : E), p y m.succ)) s,
rw continuous_linear_equiv.comp_continuous_on_iff,
exact H.cont _ A } },
{ rintros ⟨Hzero_eq, Hfderiv_zero, Htaylor⟩,
split,
{ exact Hzero_eq },
{ assume m (hm : (m : with_top ℕ) < n.succ) x (hx : x ∈ s),
cases m,
{ exact Hfderiv_zero x hx },
{ have A : (m : with_top ℕ) < n,
by { rw with_top.coe_lt_coe at hm ⊢, exact nat.lt_of_succ_lt_succ hm },
have : has_fderiv_within_at ((continuous_multilinear_curry_right_equiv 𝕜 (λ i : fin m.succ, E) F).symm
∘ (λ (y : E), p y m.succ)) ((p x).shift m.succ).curry_left s x :=
Htaylor.fderiv_within _ A x hx,
rw continuous_linear_equiv.comp_has_fderiv_within_at_iff' at this,
convert this,
ext y v,
change (p x (nat.succ (nat.succ m))) (cons y v)
= (p x m.succ.succ) (snoc (cons y (init v)) (v (last _))),
rw [← cons_snoc_eq_snoc_cons, snoc_init_self] } },
{ assume m (hm : (m : with_top ℕ) ≤ n.succ),
cases m,
{ have : differentiable_on 𝕜 (λ x, p x 0) s :=
λ x hx, (Hfderiv_zero x hx).differentiable_within_at,
exact this.continuous_on },
{ have A : (m : with_top ℕ) ≤ n,
by { rw with_top.coe_le_coe at hm ⊢, exact nat.lt_succ_iff.mp hm },
have : continuous_on ((continuous_multilinear_curry_right_equiv 𝕜 (λ i : fin m.succ, E) F).symm
∘ (λ (y : E), p y m.succ)) s :=
Htaylor.cont _ A,
rwa continuous_linear_equiv.comp_continuous_on_iff at this } } }
end
/-! ### Smooth functions within a set around a point -/
variable (𝕜)
/-- A function is continuously differentiable up to order `n` within a set `s` at a point `x` if
it admits continuous derivatives up to order `n` in a neighborhood of `x` in `s ∪ {x}`.
For `n = ∞`, we only require that this holds up to any finite order (where the neighborhood may
depend on the finite order we consider).
For instance, a real function which is `C^m` on `(-1/m, 1/m)` for each natural `m`, but not
better, is `C^∞` at `0` within `univ`.
-/
def times_cont_diff_within_at (n : with_top ℕ) (f : E → F) (s : set E) (x : E) :=
∀ (m : ℕ), (m : with_top ℕ) ≤ n →
∃ u ∈ 𝓝[insert x s] x, ∃ p : E → formal_multilinear_series 𝕜 E F,
has_ftaylor_series_up_to_on m f p u
variable {𝕜}
lemma times_cont_diff_within_at_nat {n : ℕ} :
times_cont_diff_within_at 𝕜 n f s x ↔
∃ u ∈ 𝓝[insert x s] x, ∃ p : E → formal_multilinear_series 𝕜 E F,
has_ftaylor_series_up_to_on n f p u :=
⟨λ H, H n (le_refl _), λ ⟨u, hu, p, hp⟩ m hm, ⟨u, hu, p, hp.of_le hm⟩⟩
lemma times_cont_diff_within_at.of_le {m n : with_top ℕ}
(h : times_cont_diff_within_at 𝕜 n f s x) (hmn : m ≤ n) :
times_cont_diff_within_at 𝕜 m f s x :=
λ k hk, h k (le_trans hk hmn)
lemma times_cont_diff_within_at_iff_forall_nat_le {n : with_top ℕ} :
times_cont_diff_within_at 𝕜 n f s x ↔ ∀ m : ℕ, ↑m ≤ n → times_cont_diff_within_at 𝕜 m f s x :=
⟨λ H m hm, H.of_le hm, λ H m hm, H m hm _ le_rfl⟩
lemma times_cont_diff_within_at_top :
times_cont_diff_within_at 𝕜 ∞ f s x ↔ ∀ (n : ℕ), times_cont_diff_within_at 𝕜 n f s x :=
times_cont_diff_within_at_iff_forall_nat_le.trans $ by simp only [forall_prop_of_true, le_top]
lemma times_cont_diff_within_at.continuous_within_at {n : with_top ℕ}
(h : times_cont_diff_within_at 𝕜 n f s x) : continuous_within_at f s x :=
begin
rcases h 0 bot_le with ⟨u, hu, p, H⟩,
rw [mem_nhds_within_insert] at hu,
exact (H.continuous_on.continuous_within_at hu.1).mono_of_mem hu.2
end
lemma times_cont_diff_within_at.congr_of_eventually_eq {n : with_top ℕ}
(h : times_cont_diff_within_at 𝕜 n f s x) (h₁ : f₁ =ᶠ[𝓝[s] x] f) (hx : f₁ x = f x) :
times_cont_diff_within_at 𝕜 n f₁ s x :=
λ m hm, let ⟨u, hu, p, H⟩ := h m hm in
⟨{x ∈ u | f₁ x = f x}, filter.inter_mem_sets hu (mem_nhds_within_insert.2 ⟨hx, h₁⟩), p,
(H.mono (sep_subset _ _)).congr (λ _, and.right)⟩
lemma times_cont_diff_within_at.congr_of_eventually_eq' {n : with_top ℕ}
(h : times_cont_diff_within_at 𝕜 n f s x) (h₁ : f₁ =ᶠ[𝓝[s] x] f) (hx : x ∈ s) :
times_cont_diff_within_at 𝕜 n f₁ s x :=
h.congr_of_eventually_eq h₁ $ h₁.self_of_nhds_within hx
lemma filter.eventually_eq.times_cont_diff_within_at_iff {n : with_top ℕ}
(h₁ : f₁ =ᶠ[𝓝[s] x] f) (hx : f₁ x = f x) :
times_cont_diff_within_at 𝕜 n f₁ s x ↔ times_cont_diff_within_at 𝕜 n f s x :=
⟨λ H, times_cont_diff_within_at.congr_of_eventually_eq H h₁.symm hx.symm,
λ H, H.congr_of_eventually_eq h₁ hx⟩
lemma times_cont_diff_within_at.congr {n : with_top ℕ}
(h : times_cont_diff_within_at 𝕜 n f s x) (h₁ : ∀ y ∈ s, f₁ y = f y) (hx : f₁ x = f x) :
times_cont_diff_within_at 𝕜 n f₁ s x :=
h.congr_of_eventually_eq (filter.eventually_eq_of_mem self_mem_nhds_within h₁) hx
lemma times_cont_diff_within_at.mono_of_mem {n : with_top ℕ}
(h : times_cont_diff_within_at 𝕜 n f s x) {t : set E} (hst : s ∈ 𝓝[t] x) :
times_cont_diff_within_at 𝕜 n f t x :=
begin
assume m hm,
rcases h m hm with ⟨u, hu, p, H⟩,
exact ⟨u, nhds_within_le_of_mem (insert_mem_nhds_within_insert hst) hu, p, H⟩
end
lemma times_cont_diff_within_at.mono {n : with_top ℕ}
(h : times_cont_diff_within_at 𝕜 n f s x) {t : set E} (hst : t ⊆ s) :
times_cont_diff_within_at 𝕜 n f t x :=
h.mono_of_mem $ filter.mem_sets_of_superset self_mem_nhds_within hst
lemma times_cont_diff_within_at.congr_nhds {n : with_top ℕ}
(h : times_cont_diff_within_at 𝕜 n f s x) {t : set E} (hst : 𝓝[s] x = 𝓝[t] x) :
times_cont_diff_within_at 𝕜 n f t x :=
h.mono_of_mem $ hst ▸ self_mem_nhds_within
lemma times_cont_diff_within_at_congr_nhds {n : with_top ℕ} {t : set E} (hst : 𝓝[s] x = 𝓝[t] x) :
times_cont_diff_within_at 𝕜 n f s x ↔ times_cont_diff_within_at 𝕜 n f t x :=
⟨λ h, h.congr_nhds hst, λ h, h.congr_nhds hst.symm⟩
lemma times_cont_diff_within_at_inter' {n : with_top ℕ} (h : t ∈ 𝓝[s] x) :
times_cont_diff_within_at 𝕜 n f (s ∩ t) x ↔ times_cont_diff_within_at 𝕜 n f s x :=
times_cont_diff_within_at_congr_nhds $ eq.symm $ nhds_within_restrict'' _ h
lemma times_cont_diff_within_at_inter {n : with_top ℕ} (h : t ∈ 𝓝 x) :
times_cont_diff_within_at 𝕜 n f (s ∩ t) x ↔ times_cont_diff_within_at 𝕜 n f s x :=
times_cont_diff_within_at_inter' (mem_nhds_within_of_mem_nhds h)
/-- If a function is `C^n` within a set at a point, with `n ≥ 1`, then it is differentiable
within this set at this point. -/
lemma times_cont_diff_within_at.differentiable_within_at' {n : with_top ℕ}
(h : times_cont_diff_within_at 𝕜 n f s x) (hn : 1 ≤ n) :
differentiable_within_at 𝕜 f (insert x s) x :=
begin
rcases h 1 hn with ⟨u, hu, p, H⟩,
rcases mem_nhds_within.1 hu with ⟨t, t_open, xt, tu⟩,
rw inter_comm at tu,
have := ((H.mono tu).differentiable_on (le_refl _)) x ⟨mem_insert x s, xt⟩,
exact (differentiable_within_at_inter (mem_nhds_sets t_open xt)).1 this,
end
lemma times_cont_diff_within_at.differentiable_within_at {n : with_top ℕ}
(h : times_cont_diff_within_at 𝕜 n f s x) (hn : 1 ≤ n) :
differentiable_within_at 𝕜 f s x :=
(h.differentiable_within_at' hn).mono (subset_insert x s)
/-- A function is `C^(n + 1)` on a domain iff locally, it has a derivative which is `C^n`. -/
theorem times_cont_diff_within_at_succ_iff_has_fderiv_within_at {n : ℕ} :
times_cont_diff_within_at 𝕜 ((n + 1) : ℕ) f s x
↔ ∃ u ∈ 𝓝[insert x s] x, ∃ f' : E → (E →L[𝕜] F),
(∀ x ∈ u, has_fderiv_within_at f (f' x) u x) ∧ (times_cont_diff_within_at 𝕜 n f' u x) :=
begin
split,
{ assume h,
rcases h n.succ (le_refl _) with ⟨u, hu, p, Hp⟩,
refine ⟨u, hu, λ y, (continuous_multilinear_curry_fin1 𝕜 E F) (p y 1),
λ y hy, Hp.has_fderiv_within_at (with_top.coe_le_coe.2 (nat.le_add_left 1 n)) hy, _⟩,
assume m hm,
refine ⟨u, _, λ (y : E), (p y).shift, _⟩,
{ convert self_mem_nhds_within,
have : x ∈ insert x s, by simp,
exact (insert_eq_of_mem (mem_of_mem_nhds_within this hu)) },
{ rw has_ftaylor_series_up_to_on_succ_iff_right at Hp,
exact Hp.2.2.of_le hm } },
{ rintros ⟨u, hu, f', f'_eq_deriv, Hf'⟩,
rw times_cont_diff_within_at_nat,
rcases Hf' n (le_refl _) with ⟨v, hv, p', Hp'⟩,
refine ⟨v ∩ u, _, λ x, (p' x).unshift (f x), _⟩,
{ apply filter.inter_mem_sets _ hu,
apply nhds_within_le_of_mem hu,
exact nhds_within_mono _ (subset_insert x u) hv },
{ rw has_ftaylor_series_up_to_on_succ_iff_right,
refine ⟨λ y hy, rfl, λ y hy, _, _⟩,
{ change has_fderiv_within_at (λ (z : E), (continuous_multilinear_curry_fin0 𝕜 E F).symm (f z))
((formal_multilinear_series.unshift (p' y) (f y) 1).curry_left) (v ∩ u) y,
rw continuous_linear_equiv.comp_has_fderiv_within_at_iff',
convert (f'_eq_deriv y hy.2).mono (inter_subset_right v u),
rw ← Hp'.zero_eq y hy.1,
ext z,
change ((p' y 0) (init (@cons 0 (λ i, E) z 0))) (@cons 0 (λ i, E) z 0 (last 0))
= ((p' y 0) 0) z,
unfold_coes,
congr },
{ convert (Hp'.mono (inter_subset_left v u)).congr (λ x hx, Hp'.zero_eq x hx.1),
{ ext x y,
change p' x 0 (init (@snoc 0 (λ i : fin 1, E) 0 y)) y = p' x 0 0 y,
rw init_snoc },
{ ext x k v y,
change p' x k (init (@snoc k (λ i : fin k.succ, E) v y))
(@snoc k (λ i : fin k.succ, E) v y (last k)) = p' x k v y,
rw [snoc_last, init_snoc] } } } }
end
/-! ### Smooth functions within a set -/
variable (𝕜)
/-- A function is continuously differentiable up to `n` on `s` if, for any point `x` in `s`, it
admits continuous derivatives up to order `n` on a neighborhood of `x` in `s`.
For `n = ∞`, we only require that this holds up to any finite order (where the neighborhood may
depend on the finite order we consider).
-/
definition times_cont_diff_on (n : with_top ℕ) (f : E → F) (s : set E) :=
∀ x ∈ s, times_cont_diff_within_at 𝕜 n f s x
variable {𝕜}
lemma times_cont_diff_on.times_cont_diff_within_at {n : with_top ℕ}
(h : times_cont_diff_on 𝕜 n f s) (hx : x ∈ s) :
times_cont_diff_within_at 𝕜 n f s x :=
h x hx
lemma times_cont_diff_within_at.times_cont_diff_on {n : with_top ℕ} {m : ℕ}
(hm : (m : with_top ℕ) ≤ n) (h : times_cont_diff_within_at 𝕜 n f s x) :
∃ u ∈ 𝓝[insert x s] x, u ⊆ insert x s ∧ times_cont_diff_on 𝕜 m f u :=
begin
rcases h m hm with ⟨u, u_nhd, p, hp⟩,
refine ⟨u ∩ insert x s, filter.inter_mem_sets u_nhd self_mem_nhds_within,
inter_subset_right _ _, _⟩,
assume y hy m' hm',
refine ⟨u ∩ insert x s, _, p, (hp.mono (inter_subset_left _ _)).of_le hm'⟩,
convert self_mem_nhds_within,
exact insert_eq_of_mem hy
end
lemma times_cont_diff_on.of_le {m n : with_top ℕ}
(h : times_cont_diff_on 𝕜 n f s) (hmn : m ≤ n) :
times_cont_diff_on 𝕜 m f s :=
λ x hx, (h x hx).of_le hmn
lemma times_cont_diff_on_iff_forall_nat_le {n : with_top ℕ} :
times_cont_diff_on 𝕜 n f s ↔ ∀ m : ℕ, ↑m ≤ n → times_cont_diff_on 𝕜 m f s :=
⟨λ H m hm, H.of_le hm, λ H x hx m hm, H m hm x hx m le_rfl⟩
lemma times_cont_diff_on_top :
times_cont_diff_on 𝕜 ∞ f s ↔ ∀ (n : ℕ), times_cont_diff_on 𝕜 n f s :=
times_cont_diff_on_iff_forall_nat_le.trans $ by simp only [le_top, forall_prop_of_true]
lemma times_cont_diff_on_all_iff_nat :
(∀ n, times_cont_diff_on 𝕜 n f s) ↔ (∀ n : ℕ, times_cont_diff_on 𝕜 n f s) :=
begin
refine ⟨λ H n, H n, _⟩,
rintro H (_|n),
exacts [times_cont_diff_on_top.2 H, H n]
end
lemma times_cont_diff_on.continuous_on {n : with_top ℕ}
(h : times_cont_diff_on 𝕜 n f s) : continuous_on f s :=
λ x hx, (h x hx).continuous_within_at
lemma times_cont_diff_on.congr {n : with_top ℕ}
(h : times_cont_diff_on 𝕜 n f s) (h₁ : ∀ x ∈ s, f₁ x = f x) :
times_cont_diff_on 𝕜 n f₁ s :=
λ x hx, (h x hx).congr h₁ (h₁ x hx)
lemma times_cont_diff_on_congr {n : with_top ℕ} (h₁ : ∀ x ∈ s, f₁ x = f x) :
times_cont_diff_on 𝕜 n f₁ s ↔ times_cont_diff_on 𝕜 n f s :=
⟨λ H, H.congr (λ x hx, (h₁ x hx).symm), λ H, H.congr h₁⟩
lemma times_cont_diff_on.mono {n : with_top ℕ}
(h : times_cont_diff_on 𝕜 n f s) {t : set E} (hst : t ⊆ s) :
times_cont_diff_on 𝕜 n f t :=
λ x hx, (h x (hst hx)).mono hst
lemma times_cont_diff_on.congr_mono {n : with_top ℕ}
(hf : times_cont_diff_on 𝕜 n f s) (h₁ : ∀ x ∈ s₁, f₁ x = f x) (hs : s₁ ⊆ s) :
times_cont_diff_on 𝕜 n f₁ s₁ :=
(hf.mono hs).congr h₁
/-- If a function is `C^n` on a set with `n ≥ 1`, then it is differentiable there. -/
lemma times_cont_diff_on.differentiable_on {n : with_top ℕ}
(h : times_cont_diff_on 𝕜 n f s) (hn : 1 ≤ n) : differentiable_on 𝕜 f s :=
λ x hx, (h x hx).differentiable_within_at hn
/-- If a function is `C^n` around each point in a set, then it is `C^n` on the set. -/
lemma times_cont_diff_on_of_locally_times_cont_diff_on {n : with_top ℕ}
(h : ∀ x ∈ s, ∃u, is_open u ∧ x ∈ u ∧ times_cont_diff_on 𝕜 n f (s ∩ u)) :
times_cont_diff_on 𝕜 n f s :=
begin
assume x xs,
rcases h x xs with ⟨u, u_open, xu, hu⟩,
apply (times_cont_diff_within_at_inter _).1 (hu x ⟨xs, xu⟩),
exact mem_nhds_sets u_open xu
end
/-- A function is `C^(n + 1)` on a domain iff locally, it has a derivative which is `C^n`. -/
theorem times_cont_diff_on_succ_iff_has_fderiv_within_at {n : ℕ} :
times_cont_diff_on 𝕜 ((n + 1) : ℕ) f s
↔ ∀ x ∈ s, ∃ u ∈ 𝓝[insert x s] x, ∃ f' : E → (E →L[𝕜] F),
(∀ x ∈ u, has_fderiv_within_at f (f' x) u x) ∧ (times_cont_diff_on 𝕜 n f' u) :=
begin
split,
{ assume h x hx,
rcases (h x hx) n.succ (le_refl _) with ⟨u, hu, p, Hp⟩,
refine ⟨u, hu, λ y, (continuous_multilinear_curry_fin1 𝕜 E F) (p y 1),
λ y hy, Hp.has_fderiv_within_at (with_top.coe_le_coe.2 (nat.le_add_left 1 n)) hy, _⟩,
rw has_ftaylor_series_up_to_on_succ_iff_right at Hp,
assume z hz m hm,
refine ⟨u, _, λ (x : E), (p x).shift, Hp.2.2.of_le hm⟩,
convert self_mem_nhds_within,
exact insert_eq_of_mem hz, },
{ assume h x hx,
rw times_cont_diff_within_at_succ_iff_has_fderiv_within_at,
rcases h x hx with ⟨u, u_nhbd, f', hu, hf'⟩,
have : x ∈ u := mem_of_mem_nhds_within (mem_insert _ _) u_nhbd,
exact ⟨u, u_nhbd, f', hu, hf' x this⟩ }
end
/-! ### Iterated derivative within a set -/
variable (𝕜)
/--
The `n`-th derivative of a function along a set, defined inductively by saying that the `n+1`-th
derivative of `f` is the derivative of the `n`-th derivative of `f` along this set, together with
an uncurrying step to see it as a multilinear map in `n+1` variables..
-/
noncomputable def iterated_fderiv_within (n : ℕ) (f : E → F) (s : set E) :
E → (E [×n]→L[𝕜] F) :=
nat.rec_on n
(λ x, continuous_multilinear_map.curry0 𝕜 E (f x))
(λ n rec x, continuous_linear_map.uncurry_left (fderiv_within 𝕜 rec s x))
/-- Formal Taylor series associated to a function within a set. -/
def ftaylor_series_within (f : E → F) (s : set E) (x : E) : formal_multilinear_series 𝕜 E F :=
λ n, iterated_fderiv_within 𝕜 n f s x
variable {𝕜}
@[simp] lemma iterated_fderiv_within_zero_apply (m : (fin 0) → E) :
(iterated_fderiv_within 𝕜 0 f s x : ((fin 0) → E) → F) m = f x := rfl
lemma iterated_fderiv_within_zero_eq_comp :
iterated_fderiv_within 𝕜 0 f s = (continuous_multilinear_curry_fin0 𝕜 E F).symm ∘ f := rfl
lemma iterated_fderiv_within_succ_apply_left {n : ℕ} (m : fin (n + 1) → E):
(iterated_fderiv_within 𝕜 (n + 1) f s x : (fin (n + 1) → E) → F) m
= (fderiv_within 𝕜 (iterated_fderiv_within 𝕜 n f s) s x : E → (E [×n]→L[𝕜] F)) (m 0) (tail m) := rfl
/-- Writing explicitly the `n+1`-th derivative as the composition of a currying linear equiv,
and the derivative of the `n`-th derivative. -/
lemma iterated_fderiv_within_succ_eq_comp_left {n : ℕ} :
iterated_fderiv_within 𝕜 (n + 1) f s =
(continuous_multilinear_curry_left_equiv 𝕜 (λ(i : fin (n + 1)), E) F)
∘ (fderiv_within 𝕜 (iterated_fderiv_within 𝕜 n f s) s) := rfl
theorem iterated_fderiv_within_succ_apply_right {n : ℕ}
(hs : unique_diff_on 𝕜 s) (hx : x ∈ s) (m : fin (n + 1) → E) :
(iterated_fderiv_within 𝕜 (n + 1) f s x : (fin (n + 1) → E) → F) m
= iterated_fderiv_within 𝕜 n (λy, fderiv_within 𝕜 f s y) s x (init m) (m (last n)) :=
begin
induction n with n IH generalizing x,
{ rw [iterated_fderiv_within_succ_eq_comp_left, iterated_fderiv_within_zero_eq_comp,
iterated_fderiv_within_zero_apply,
function.comp_apply, continuous_linear_equiv.comp_fderiv_within _ (hs x hx)],
refl },
{ let I := (continuous_multilinear_curry_right_equiv 𝕜 (λ (i : fin (n + 1)), E) F),
have A : ∀ y ∈ s, iterated_fderiv_within 𝕜 n.succ f s y
= (I ∘ (iterated_fderiv_within 𝕜 n (λy, fderiv_within 𝕜 f s y) s)) y,
by { assume y hy, ext m, rw @IH m y hy, refl },
calc
(iterated_fderiv_within 𝕜 (n+2) f s x : (fin (n+2) → E) → F) m =
(fderiv_within 𝕜 (iterated_fderiv_within 𝕜 n.succ f s) s x
: E → (E [×(n + 1)]→L[𝕜] F)) (m 0) (tail m) : rfl
... = (fderiv_within 𝕜 (I ∘ (iterated_fderiv_within 𝕜 n (fderiv_within 𝕜 f s) s)) s x
: E → (E [×(n + 1)]→L[𝕜] F)) (m 0) (tail m) :
by rw fderiv_within_congr (hs x hx) A (A x hx)
... = (I ∘ fderiv_within 𝕜 ((iterated_fderiv_within 𝕜 n (fderiv_within 𝕜 f s) s)) s x
: E → (E [×(n + 1)]→L[𝕜] F)) (m 0) (tail m) :
by { rw continuous_linear_equiv.comp_fderiv_within _ (hs x hx), refl }
... = (fderiv_within 𝕜 ((iterated_fderiv_within 𝕜 n (λ y, fderiv_within 𝕜 f s y) s)) s x
: E → (E [×n]→L[𝕜] (E →L[𝕜] F))) (m 0) (init (tail m)) ((tail m) (last n)) : rfl
... = iterated_fderiv_within 𝕜 (nat.succ n) (λ y, fderiv_within 𝕜 f s y) s x
(init m) (m (last (n + 1))) :
by { rw [iterated_fderiv_within_succ_apply_left, tail_init_eq_init_tail], refl } }
end
/-- Writing explicitly the `n+1`-th derivative as the composition of a currying linear equiv,
and the `n`-th derivative of the derivative. -/
lemma iterated_fderiv_within_succ_eq_comp_right {n : ℕ} (hs : unique_diff_on 𝕜 s) (hx : x ∈ s) :
iterated_fderiv_within 𝕜 (n + 1) f s x =
((continuous_multilinear_curry_right_equiv 𝕜 (λ(i : fin (n + 1)), E) F)
∘ (iterated_fderiv_within 𝕜 n (λy, fderiv_within 𝕜 f s y) s)) x :=
by { ext m, rw iterated_fderiv_within_succ_apply_right hs hx, refl }
@[simp] lemma iterated_fderiv_within_one_apply
(hs : unique_diff_on 𝕜 s) (hx : x ∈ s) (m : (fin 1) → E) :
(iterated_fderiv_within 𝕜 1 f s x : ((fin 1) → E) → F) m
= (fderiv_within 𝕜 f s x : E → F) (m 0) :=
by { rw [iterated_fderiv_within_succ_apply_right hs hx, iterated_fderiv_within_zero_apply], refl }
/-- If two functions coincide on a set `s` of unique differentiability, then their iterated
differentials within this set coincide. -/
lemma iterated_fderiv_within_congr {n : ℕ}
(hs : unique_diff_on 𝕜 s) (hL : ∀y∈s, f₁ y = f y) (hx : x ∈ s) :
iterated_fderiv_within 𝕜 n f₁ s x = iterated_fderiv_within 𝕜 n f s x :=
begin
induction n with n IH generalizing x,
{ ext m, simp [hL x hx] },
{ have : fderiv_within 𝕜 (λ y, iterated_fderiv_within 𝕜 n f₁ s y) s x
= fderiv_within 𝕜 (λ y, iterated_fderiv_within 𝕜 n f s y) s x :=
fderiv_within_congr (hs x hx) (λ y hy, IH hy) (IH hx),
ext m,
rw [iterated_fderiv_within_succ_apply_left, iterated_fderiv_within_succ_apply_left, this] }
end
/-- The iterated differential within a set `s` at a point `x` is not modified if one intersects
`s` with an open set containing `x`. -/
lemma iterated_fderiv_within_inter_open {n : ℕ} (hu : is_open u)
(hs : unique_diff_on 𝕜 (s ∩ u)) (hx : x ∈ s ∩ u) :
iterated_fderiv_within 𝕜 n f (s ∩ u) x = iterated_fderiv_within 𝕜 n f s x :=
begin
induction n with n IH generalizing x,
{ ext m, simp },
{ have A : fderiv_within 𝕜 (λ y, iterated_fderiv_within 𝕜 n f (s ∩ u) y) (s ∩ u) x
= fderiv_within 𝕜 (λ y, iterated_fderiv_within 𝕜 n f s y) (s ∩ u) x :=
fderiv_within_congr (hs x hx) (λ y hy, IH hy) (IH hx),
have B : fderiv_within 𝕜 (λ y, iterated_fderiv_within 𝕜 n f s y) (s ∩ u) x
= fderiv_within 𝕜 (λ y, iterated_fderiv_within 𝕜 n f s y) s x :=
fderiv_within_inter (mem_nhds_sets hu hx.2)
((unique_diff_within_at_inter (mem_nhds_sets hu hx.2)).1 (hs x hx)),
ext m,
rw [iterated_fderiv_within_succ_apply_left, iterated_fderiv_within_succ_apply_left, A, B] }
end
/-- The iterated differential within a set `s` at a point `x` is not modified if one intersects
`s` with a neighborhood of `x` within `s`. -/
lemma iterated_fderiv_within_inter' {n : ℕ}
(hu : u ∈ 𝓝[s] x) (hs : unique_diff_on 𝕜 s) (xs : x ∈ s) :
iterated_fderiv_within 𝕜 n f (s ∩ u) x = iterated_fderiv_within 𝕜 n f s x :=
begin
obtain ⟨v, v_open, xv, vu⟩ : ∃ v, is_open v ∧ x ∈ v ∧ v ∩ s ⊆ u := mem_nhds_within.1 hu,
have A : (s ∩ u) ∩ v = s ∩ v,
{ apply subset.antisymm (inter_subset_inter (inter_subset_left _ _) (subset.refl _)),
exact λ y ⟨ys, yv⟩, ⟨⟨ys, vu ⟨yv, ys⟩⟩, yv⟩ },
have : iterated_fderiv_within 𝕜 n f (s ∩ v) x = iterated_fderiv_within 𝕜 n f s x :=
iterated_fderiv_within_inter_open v_open (hs.inter v_open) ⟨xs, xv⟩,
rw ← this,
have : iterated_fderiv_within 𝕜 n f ((s ∩ u) ∩ v) x = iterated_fderiv_within 𝕜 n f (s ∩ u) x,
{ refine iterated_fderiv_within_inter_open v_open _ ⟨⟨xs, vu ⟨xv, xs⟩⟩, xv⟩,
rw A,
exact hs.inter v_open },
rw A at this,
rw ← this
end
/-- The iterated differential within a set `s` at a point `x` is not modified if one intersects
`s` with a neighborhood of `x`. -/
lemma iterated_fderiv_within_inter {n : ℕ}
(hu : u ∈ 𝓝 x) (hs : unique_diff_on 𝕜 s) (xs : x ∈ s) :
iterated_fderiv_within 𝕜 n f (s ∩ u) x = iterated_fderiv_within 𝕜 n f s x :=
iterated_fderiv_within_inter' (mem_nhds_within_of_mem_nhds hu) hs xs
@[simp] lemma times_cont_diff_on_zero :
times_cont_diff_on 𝕜 0 f s ↔ continuous_on f s :=
begin
refine ⟨λ H, H.continuous_on, λ H, _⟩,
assume x hx m hm,
have : (m : with_top ℕ) = 0 := le_antisymm hm bot_le,
rw this,
refine ⟨insert x s, self_mem_nhds_within, ftaylor_series_within 𝕜 f s, _⟩,
rw has_ftaylor_series_up_to_on_zero_iff,
exact ⟨by rwa insert_eq_of_mem hx, λ x hx, by simp [ftaylor_series_within]⟩
end
lemma times_cont_diff_within_at_zero (hx : x ∈ s) :
times_cont_diff_within_at 𝕜 0 f s x ↔ ∃ u ∈ 𝓝[s] x, continuous_on f (s ∩ u) :=
begin
split,
{ intros h,
obtain ⟨u, H, p, hp⟩ := h 0 (by norm_num),
refine ⟨u, _, _⟩,
{ simpa [hx] using H },
{ simp only [with_top.coe_zero, has_ftaylor_series_up_to_on_zero_iff] at hp,
exact hp.1.mono (inter_subset_right s u) } },
{ rintros ⟨u, H, hu⟩,
rw ← times_cont_diff_within_at_inter' H,
have h' : x ∈ s ∩ u := ⟨hx, mem_of_mem_nhds_within hx H⟩,
exact (times_cont_diff_on_zero.mpr hu).times_cont_diff_within_at h' }
end
/-- On a set with unique differentiability, any choice of iterated differential has to coincide
with the one we have chosen in `iterated_fderiv_within 𝕜 m f s`. -/
theorem has_ftaylor_series_up_to_on.eq_ftaylor_series_of_unique_diff_on {n : with_top ℕ}
(h : has_ftaylor_series_up_to_on n f p s)
{m : ℕ} (hmn : (m : with_top ℕ) ≤ n) (hs : unique_diff_on 𝕜 s) (hx : x ∈ s) :
p x m = iterated_fderiv_within 𝕜 m f s x :=
begin
induction m with m IH generalizing x,
{ rw [h.zero_eq' hx, iterated_fderiv_within_zero_eq_comp] },
{ have A : (m : with_top ℕ) < n := lt_of_lt_of_le (with_top.coe_lt_coe.2 (lt_add_one m)) hmn,
have : has_fderiv_within_at (λ (y : E), iterated_fderiv_within 𝕜 m f s y)
(continuous_multilinear_map.curry_left (p x (nat.succ m))) s x :=
(h.fderiv_within m A x hx).congr (λ y hy, (IH (le_of_lt A) hy).symm) (IH (le_of_lt A) hx).symm,
rw [iterated_fderiv_within_succ_eq_comp_left, function.comp_apply, this.fderiv_within (hs x hx)],
exact (continuous_multilinear_map.uncurry_curry_left _).symm }
end
/-- When a function is `C^n` in a set `s` of unique differentiability, it admits
`ftaylor_series_within 𝕜 f s` as a Taylor series up to order `n` in `s`. -/
theorem times_cont_diff_on.ftaylor_series_within {n : with_top ℕ}
(h : times_cont_diff_on 𝕜 n f s) (hs : unique_diff_on 𝕜 s) :
has_ftaylor_series_up_to_on n f (ftaylor_series_within 𝕜 f s) s :=
begin
split,
{ assume x hx,
simp only [ftaylor_series_within, continuous_multilinear_map.uncurry0_apply,
iterated_fderiv_within_zero_apply] },
{ assume m hm x hx,
rcases (h x hx) m.succ (with_top.add_one_le_of_lt hm) with ⟨u, hu, p, Hp⟩,
rw insert_eq_of_mem hx at hu,
rcases mem_nhds_within.1 hu with ⟨o, o_open, xo, ho⟩,
rw inter_comm at ho,
have : p x m.succ = ftaylor_series_within 𝕜 f s x m.succ,
{ change p x m.succ = iterated_fderiv_within 𝕜 m.succ f s x,
rw ← iterated_fderiv_within_inter (mem_nhds_sets o_open xo) hs hx,
exact (Hp.mono ho).eq_ftaylor_series_of_unique_diff_on (le_refl _)
(hs.inter o_open) ⟨hx, xo⟩ },
rw [← this, ← has_fderiv_within_at_inter (mem_nhds_sets o_open xo)],
have A : ∀ y ∈ s ∩ o, p y m = ftaylor_series_within 𝕜 f s y m,
{ rintros y ⟨hy, yo⟩,
change p y m = iterated_fderiv_within 𝕜 m f s y,
rw ← iterated_fderiv_within_inter (mem_nhds_sets o_open yo) hs hy,
exact (Hp.mono ho).eq_ftaylor_series_of_unique_diff_on (with_top.coe_le_coe.2 (nat.le_succ m))
(hs.inter o_open) ⟨hy, yo⟩ },
exact ((Hp.mono ho).fderiv_within m (with_top.coe_lt_coe.2 (lt_add_one m)) x ⟨hx, xo⟩).congr
(λ y hy, (A y hy).symm) (A x ⟨hx, xo⟩).symm },
{ assume m hm,
apply continuous_on_of_locally_continuous_on,
assume x hx,
rcases h x hx m hm with ⟨u, hu, p, Hp⟩,
rcases mem_nhds_within.1 hu with ⟨o, o_open, xo, ho⟩,
rw insert_eq_of_mem hx at ho,
rw inter_comm at ho,
refine ⟨o, o_open, xo, _⟩,
have A : ∀ y ∈ s ∩ o, p y m = ftaylor_series_within 𝕜 f s y m,
{ rintros y ⟨hy, yo⟩,
change p y m = iterated_fderiv_within 𝕜 m f s y,
rw ← iterated_fderiv_within_inter (mem_nhds_sets o_open yo) hs hy,
exact (Hp.mono ho).eq_ftaylor_series_of_unique_diff_on (le_refl _)
(hs.inter o_open) ⟨hy, yo⟩ },
exact ((Hp.mono ho).cont m (le_refl _)).congr (λ y hy, (A y hy).symm) }
end
lemma times_cont_diff_on_of_continuous_on_differentiable_on {n : with_top ℕ}
(Hcont : ∀ (m : ℕ), (m : with_top ℕ) ≤ n →
continuous_on (λ x, iterated_fderiv_within 𝕜 m f s x) s)
(Hdiff : ∀ (m : ℕ), (m : with_top ℕ) < n →
differentiable_on 𝕜 (λ x, iterated_fderiv_within 𝕜 m f s x) s) :
times_cont_diff_on 𝕜 n f s :=
begin
assume x hx m hm,
rw insert_eq_of_mem hx,
refine ⟨s, self_mem_nhds_within, ftaylor_series_within 𝕜 f s, _⟩,
split,
{ assume y hy,
simp only [ftaylor_series_within, continuous_multilinear_map.uncurry0_apply,
iterated_fderiv_within_zero_apply] },
{ assume k hk y hy,
convert (Hdiff k (lt_of_lt_of_le hk hm) y hy).has_fderiv_within_at,
simp only [ftaylor_series_within, iterated_fderiv_within_succ_eq_comp_left,
continuous_linear_equiv.coe_apply, function.comp_app, coe_fn_coe_base],
exact continuous_linear_map.curry_uncurry_left _ },
{ assume k hk,
exact Hcont k (le_trans hk hm) }
end
lemma times_cont_diff_on_of_differentiable_on {n : with_top ℕ}
(h : ∀(m : ℕ), (m : with_top ℕ) ≤ n → differentiable_on 𝕜 (iterated_fderiv_within 𝕜 m f s) s) :
times_cont_diff_on 𝕜 n f s :=
times_cont_diff_on_of_continuous_on_differentiable_on
(λ m hm, (h m hm).continuous_on) (λ m hm, (h m (le_of_lt hm)))
lemma times_cont_diff_on.continuous_on_iterated_fderiv_within {n : with_top ℕ} {m : ℕ}
(h : times_cont_diff_on 𝕜 n f s) (hmn : (m : with_top ℕ) ≤ n) (hs : unique_diff_on 𝕜 s) :
continuous_on (iterated_fderiv_within 𝕜 m f s) s :=
(h.ftaylor_series_within hs).cont m hmn
lemma times_cont_diff_on.differentiable_on_iterated_fderiv_within {n : with_top ℕ} {m : ℕ}
(h : times_cont_diff_on 𝕜 n f s) (hmn : (m : with_top ℕ) < n) (hs : unique_diff_on 𝕜 s) :
differentiable_on 𝕜 (iterated_fderiv_within 𝕜 m f s) s :=
λ x hx, ((h.ftaylor_series_within hs).fderiv_within m hmn x hx).differentiable_within_at
lemma times_cont_diff_on_iff_continuous_on_differentiable_on {n : with_top ℕ}
(hs : unique_diff_on 𝕜 s) :
times_cont_diff_on 𝕜 n f s ↔
(∀ (m : ℕ), (m : with_top ℕ) ≤ n →
continuous_on (λ x, iterated_fderiv_within 𝕜 m f s x) s)
∧ (∀ (m : ℕ), (m : with_top ℕ) < n →
differentiable_on 𝕜 (λ x, iterated_fderiv_within 𝕜 m f s x) s) :=
begin
split,
{ assume h,
split,
{ assume m hm, exact h.continuous_on_iterated_fderiv_within hm hs },
{ assume m hm, exact h.differentiable_on_iterated_fderiv_within hm hs } },
{ assume h,
exact times_cont_diff_on_of_continuous_on_differentiable_on h.1 h.2 }
end
/-- A function is `C^(n + 1)` on a domain with unique derivatives if and only if it is
differentiable there, and its derivative (expressed with `fderiv_within`) is `C^n`. -/
theorem times_cont_diff_on_succ_iff_fderiv_within {n : ℕ} (hs : unique_diff_on 𝕜 s) :
times_cont_diff_on 𝕜 ((n + 1) : ℕ) f s ↔
differentiable_on 𝕜 f s ∧ times_cont_diff_on 𝕜 n (λ y, fderiv_within 𝕜 f s y) s :=
begin
split,
{ assume H,
refine ⟨H.differentiable_on (with_top.coe_le_coe.2 (nat.le_add_left 1 n)), λ x hx, _⟩,
rcases times_cont_diff_within_at_succ_iff_has_fderiv_within_at.1 (H x hx)
with ⟨u, hu, f', hff', hf'⟩,
rcases mem_nhds_within.1 hu with ⟨o, o_open, xo, ho⟩,
rw [inter_comm, insert_eq_of_mem hx] at ho,
have := hf'.mono ho,
rw times_cont_diff_within_at_inter' (mem_nhds_within_of_mem_nhds (mem_nhds_sets o_open xo))
at this,
apply this.congr_of_eventually_eq' _ hx,
have : o ∩ s ∈ 𝓝[s] x := mem_nhds_within.2 ⟨o, o_open, xo, subset.refl _⟩,
rw inter_comm at this,
apply filter.eventually_eq_of_mem this (λ y hy, _),
have A : fderiv_within 𝕜 f (s ∩ o) y = f' y :=
((hff' y (ho hy)).mono ho).fderiv_within (hs.inter o_open y hy),
rwa fderiv_within_inter (mem_nhds_sets o_open hy.2) (hs y hy.1) at A, },
{ rintros ⟨hdiff, h⟩ x hx,
rw [times_cont_diff_within_at_succ_iff_has_fderiv_within_at, insert_eq_of_mem hx],
exact ⟨s, self_mem_nhds_within, fderiv_within 𝕜 f s,
λ y hy, (hdiff y hy).has_fderiv_within_at, h x hx⟩ }
end
/-- A function is `C^(n + 1)` on an open domain if and only if it is
differentiable there, and its derivative (expressed with `fderiv`) is `C^n`. -/
theorem times_cont_diff_on_succ_iff_fderiv_of_open {n : ℕ} (hs : is_open s) :
times_cont_diff_on 𝕜 ((n + 1) : ℕ) f s ↔
differentiable_on 𝕜 f s ∧ times_cont_diff_on 𝕜 n (λ y, fderiv 𝕜 f y) s :=
begin
rw times_cont_diff_on_succ_iff_fderiv_within hs.unique_diff_on,
congr' 2,
rw ← iff_iff_eq,
apply times_cont_diff_on_congr,
assume x hx,
exact fderiv_within_of_open hs hx
end
/-- A function is `C^∞` on a domain with unique derivatives if and only if it is differentiable
there, and its derivative (expressed with `fderiv_within`) is `C^∞`. -/
theorem times_cont_diff_on_top_iff_fderiv_within (hs : unique_diff_on 𝕜 s) :
times_cont_diff_on 𝕜 ∞ f s ↔
differentiable_on 𝕜 f s ∧ times_cont_diff_on 𝕜 ∞ (λ y, fderiv_within 𝕜 f s y) s :=
begin
split,
{ assume h,
refine ⟨h.differentiable_on le_top, _⟩,
apply times_cont_diff_on_top.2 (λ n, ((times_cont_diff_on_succ_iff_fderiv_within hs).1 _).2),
exact h.of_le le_top },
{ assume h,
refine times_cont_diff_on_top.2 (λ n, _),
have A : (n : with_top ℕ) ≤ ∞ := le_top,
apply ((times_cont_diff_on_succ_iff_fderiv_within hs).2 ⟨h.1, h.2.of_le A⟩).of_le,
exact with_top.coe_le_coe.2 (nat.le_succ n) }
end
/-- A function is `C^∞` on an open domain if and only if it is differentiable there, and its
derivative (expressed with `fderiv`) is `C^∞`. -/
theorem times_cont_diff_on_top_iff_fderiv_of_open (hs : is_open s) :
times_cont_diff_on 𝕜 ∞ f s ↔
differentiable_on 𝕜 f s ∧ times_cont_diff_on 𝕜 ∞ (λ y, fderiv 𝕜 f y) s :=
begin
rw times_cont_diff_on_top_iff_fderiv_within hs.unique_diff_on,
congr' 2,
rw ← iff_iff_eq,
apply times_cont_diff_on_congr,
assume x hx,
exact fderiv_within_of_open hs hx
end
lemma times_cont_diff_on.fderiv_within {m n : with_top ℕ}
(hf : times_cont_diff_on 𝕜 n f s) (hs : unique_diff_on 𝕜 s) (hmn : m + 1 ≤ n) :
times_cont_diff_on 𝕜 m (λ y, fderiv_within 𝕜 f s y) s :=
begin
cases m,
{ change ∞ + 1 ≤ n at hmn,
have : n = ∞, by simpa using hmn,
rw this at hf,
exact ((times_cont_diff_on_top_iff_fderiv_within hs).1 hf).2 },
{ change (m.succ : with_top ℕ) ≤ n at hmn,
exact ((times_cont_diff_on_succ_iff_fderiv_within hs).1 (hf.of_le hmn)).2 }
end
lemma times_cont_diff_on.fderiv_of_open {m n : with_top ℕ}
(hf : times_cont_diff_on 𝕜 n f s) (hs : is_open s) (hmn : m + 1 ≤ n) :
times_cont_diff_on 𝕜 m (λ y, fderiv 𝕜 f y) s :=
(hf.fderiv_within hs.unique_diff_on hmn).congr (λ x hx, (fderiv_within_of_open hs hx).symm)
lemma times_cont_diff_on.continuous_on_fderiv_within {n : with_top ℕ}
(h : times_cont_diff_on 𝕜 n f s) (hs : unique_diff_on 𝕜 s) (hn : 1 ≤ n) :
continuous_on (λ x, fderiv_within 𝕜 f s x) s :=
((times_cont_diff_on_succ_iff_fderiv_within hs).1 (h.of_le hn)).2.continuous_on
lemma times_cont_diff_on.continuous_on_fderiv_of_open {n : with_top ℕ}
(h : times_cont_diff_on 𝕜 n f s) (hs : is_open s) (hn : 1 ≤ n) :
continuous_on (λ x, fderiv 𝕜 f x) s :=
((times_cont_diff_on_succ_iff_fderiv_of_open hs).1 (h.of_le hn)).2.continuous_on
/-- If a function is at least `C^1`, its bundled derivative (mapping `(x, v)` to `Df(x) v`) is
continuous. -/
lemma times_cont_diff_on.continuous_on_fderiv_within_apply
{n : with_top ℕ} (h : times_cont_diff_on 𝕜 n f s) (hs : unique_diff_on 𝕜 s) (hn : 1 ≤ n) :
continuous_on (λp : E × E, (fderiv_within 𝕜 f s p.1 : E → F) p.2) (set.prod s univ) :=
begin
have A : continuous (λq : (E →L[𝕜] F) × E, q.1 q.2) := is_bounded_bilinear_map_apply.continuous,
have B : continuous_on (λp : E × E, (fderiv_within 𝕜 f s p.1, p.2)) (set.prod s univ),
{ apply continuous_on.prod _ continuous_snd.continuous_on,
exact continuous_on.comp (h.continuous_on_fderiv_within hs hn) continuous_fst.continuous_on
(prod_subset_preimage_fst _ _) },
exact A.comp_continuous_on B
end
/-! ### Functions with a Taylor series on the whole space -/
/-- `has_ftaylor_series_up_to n f p` registers the fact that `p 0 = f` and `p (m+1)` is a
derivative of `p m` for `m < n`, and is continuous for `m ≤ n`. This is a predicate analogous to
`has_fderiv_at` but for higher order derivatives. -/
structure has_ftaylor_series_up_to (n : with_top ℕ)
(f : E → F) (p : E → formal_multilinear_series 𝕜 E F) : Prop :=
(zero_eq : ∀ x, (p x 0).uncurry0 = f x)
(fderiv : ∀ (m : ℕ) (hm : (m : with_top ℕ) < n), ∀ x,
has_fderiv_at (λ y, p y m) (p x m.succ).curry_left x)
(cont : ∀ (m : ℕ) (hm : (m : with_top ℕ) ≤ n), continuous (λ x, p x m))
lemma has_ftaylor_series_up_to.zero_eq' {n : with_top ℕ}
(h : has_ftaylor_series_up_to n f p) (x : E) :
p x 0 = (continuous_multilinear_curry_fin0 𝕜 E F).symm (f x) :=
by { rw ← h.zero_eq x, symmetry, exact continuous_multilinear_map.uncurry0_curry0 _ }
lemma has_ftaylor_series_up_to_on_univ_iff {n : with_top ℕ} :
has_ftaylor_series_up_to_on n f p univ ↔ has_ftaylor_series_up_to n f p :=
begin
split,
{ assume H,
split,
{ exact λ x, H.zero_eq x (mem_univ x) },
{ assume m hm x,
rw ← has_fderiv_within_at_univ,
exact H.fderiv_within m hm x (mem_univ x) },
{ assume m hm,
rw continuous_iff_continuous_on_univ,
exact H.cont m hm } },
{ assume H,
split,
{ exact λ x hx, H.zero_eq x },
{ assume m hm x hx,
rw has_fderiv_within_at_univ,
exact H.fderiv m hm x },
{ assume m hm,
rw ← continuous_iff_continuous_on_univ,
exact H.cont m hm } }
end
lemma has_ftaylor_series_up_to.has_ftaylor_series_up_to_on {n : with_top ℕ}
(h : has_ftaylor_series_up_to n f p) (s : set E) :
has_ftaylor_series_up_to_on n f p s :=
(has_ftaylor_series_up_to_on_univ_iff.2 h).mono (subset_univ _)
lemma has_ftaylor_series_up_to.of_le {m n : with_top ℕ}
(h : has_ftaylor_series_up_to n f p) (hmn : m ≤ n) :
has_ftaylor_series_up_to m f p :=
by { rw ← has_ftaylor_series_up_to_on_univ_iff at h ⊢, exact h.of_le hmn }
lemma has_ftaylor_series_up_to.continuous {n : with_top ℕ}
(h : has_ftaylor_series_up_to n f p) : continuous f :=
begin
rw ← has_ftaylor_series_up_to_on_univ_iff at h,
rw continuous_iff_continuous_on_univ,
exact h.continuous_on
end
lemma has_ftaylor_series_up_to_zero_iff :
has_ftaylor_series_up_to 0 f p ↔ continuous f ∧ (∀ x, (p x 0).uncurry0 = f x) :=
by simp [has_ftaylor_series_up_to_on_univ_iff.symm, continuous_iff_continuous_on_univ,
has_ftaylor_series_up_to_on_zero_iff]
/-- If a function has a Taylor series at order at least `1`, then the term of order `1` of this
series is a derivative of `f`. -/
lemma has_ftaylor_series_up_to.has_fderiv_at {n : with_top ℕ}
(h : has_ftaylor_series_up_to n f p) (hn : 1 ≤ n) (x : E) :
has_fderiv_at f (continuous_multilinear_curry_fin1 𝕜 E F (p x 1)) x :=
begin
rw [← has_fderiv_within_at_univ],
exact (has_ftaylor_series_up_to_on_univ_iff.2 h).has_fderiv_within_at hn (mem_univ _)
end
lemma has_ftaylor_series_up_to.differentiable {n : with_top ℕ}
(h : has_ftaylor_series_up_to n f p) (hn : 1 ≤ n) : differentiable 𝕜 f :=
λ x, (h.has_fderiv_at hn x).differentiable_at
/-- `p` is a Taylor series of `f` up to `n+1` if and only if `p.shift` is a Taylor series up to `n`
for `p 1`, which is a derivative of `f`. -/
theorem has_ftaylor_series_up_to_succ_iff_right {n : ℕ} :
has_ftaylor_series_up_to ((n + 1) : ℕ) f p ↔
(∀ x, (p x 0).uncurry0 = f x)
∧ (∀ x, has_fderiv_at (λ y, p y 0) (p x 1).curry_left x)
∧ has_ftaylor_series_up_to n
(λ x, continuous_multilinear_curry_fin1 𝕜 E F (p x 1)) (λ x, (p x).shift) :=
by simp [has_ftaylor_series_up_to_on_succ_iff_right, has_ftaylor_series_up_to_on_univ_iff.symm,
-add_comm, -with_zero.coe_add]
/-! ### Smooth functions at a point -/
variable (𝕜)
/-- A function is continuously differentiable up to `n` at a point `x` if, for any integer `k ≤ n`,
there is a neighborhood of `x` where `f` admits derivatives up to order `n`, which are continuous.
-/
def times_cont_diff_at (n : with_top ℕ) (f : E → F) (x : E) :=
times_cont_diff_within_at 𝕜 n f univ x
variable {𝕜}
theorem times_cont_diff_within_at_univ {n : with_top ℕ} :
times_cont_diff_within_at 𝕜 n f univ x ↔ times_cont_diff_at 𝕜 n f x :=
iff.rfl
lemma times_cont_diff_at_top :
times_cont_diff_at 𝕜 ∞ f x ↔ ∀ (n : ℕ), times_cont_diff_at 𝕜 n f x :=
by simp [← times_cont_diff_within_at_univ, times_cont_diff_within_at_top]
lemma times_cont_diff_at.times_cont_diff_within_at {n : with_top ℕ}
(h : times_cont_diff_at 𝕜 n f x) : times_cont_diff_within_at 𝕜 n f s x :=
h.mono (subset_univ _)
lemma times_cont_diff_within_at.times_cont_diff_at {n : with_top ℕ}
(h : times_cont_diff_within_at 𝕜 n f s x) (hx : s ∈ 𝓝 x) :
times_cont_diff_at 𝕜 n f x :=
by rwa [times_cont_diff_at, ← times_cont_diff_within_at_inter hx, univ_inter]
lemma times_cont_diff_at.congr_of_eventually_eq {n : with_top ℕ}
(h : times_cont_diff_at 𝕜 n f x) (hg : f₁ =ᶠ[𝓝 x] f) :
times_cont_diff_at 𝕜 n f₁ x :=
h.congr_of_eventually_eq' (by rwa nhds_within_univ) (mem_univ x)
lemma times_cont_diff_at.of_le {m n : with_top ℕ}
(h : times_cont_diff_at 𝕜 n f x) (hmn : m ≤ n) :
times_cont_diff_at 𝕜 m f x :=
h.of_le hmn
lemma times_cont_diff_at.continuous_at {n : with_top ℕ}
(h : times_cont_diff_at 𝕜 n f x) : continuous_at f x :=
by simpa [continuous_within_at_univ] using h.continuous_within_at
/-- If a function is `C^n` with `n ≥ 1` at a point, then it is differentiable there. -/
lemma times_cont_diff_at.differentiable_at {n : with_top ℕ}
(h : times_cont_diff_at 𝕜 n f x) (hn : 1 ≤ n) : differentiable_at 𝕜 f x :=
by simpa [hn, differentiable_within_at_univ] using h.differentiable_within_at
/-- A function is `C^(n + 1)` at a point iff locally, it has a derivative which is `C^n`. -/
theorem times_cont_diff_at_succ_iff_has_fderiv_at {n : ℕ} :
times_cont_diff_at 𝕜 ((n + 1) : ℕ) f x
↔ (∃ f' : E → (E →L[𝕜] F), (∃ u ∈ 𝓝 x, (∀ x ∈ u, has_fderiv_at f (f' x) x))
∧ (times_cont_diff_at 𝕜 n f' x)) :=
begin
rw [← times_cont_diff_within_at_univ, times_cont_diff_within_at_succ_iff_has_fderiv_within_at],
simp only [nhds_within_univ, exists_prop, mem_univ, insert_eq_of_mem],
split,
{ rintros ⟨u, H, f', h_fderiv, h_times_cont_diff⟩,
rcases mem_nhds_sets_iff.mp H with ⟨t, htu, ht, hxt⟩,
refine ⟨f', ⟨t, _⟩, h_times_cont_diff.times_cont_diff_at H⟩,
refine ⟨mem_nhds_sets_iff.mpr ⟨t, subset.rfl, ht, hxt⟩, _⟩,
intros y hyt,
refine (h_fderiv y (htu hyt)).has_fderiv_at _,
exact mem_nhds_sets_iff.mpr ⟨t, htu, ht, hyt⟩ },
{ rintros ⟨f', ⟨u, H, h_fderiv⟩, h_times_cont_diff⟩,
refine ⟨u, H, f', _, h_times_cont_diff.times_cont_diff_within_at⟩,
intros x hxu,
exact (h_fderiv x hxu).has_fderiv_within_at }
end
/-! ### Smooth functions -/
variable (𝕜)
/-- A function is continuously differentiable up to `n` if it admits derivatives up to
order `n`, which are continuous. Contrary to the case of definitions in domains (where derivatives
might not be unique) we do not need to localize the definition in space or time.
-/
definition times_cont_diff (n : with_top ℕ) (f : E → F) :=
∃ p : E → formal_multilinear_series 𝕜 E F, has_ftaylor_series_up_to n f p
variable {𝕜}
theorem times_cont_diff_on_univ {n : with_top ℕ} :
times_cont_diff_on 𝕜 n f univ ↔ times_cont_diff 𝕜 n f :=
begin
split,
{ assume H,
use ftaylor_series_within 𝕜 f univ,
rw ← has_ftaylor_series_up_to_on_univ_iff,
exact H.ftaylor_series_within unique_diff_on_univ },
{ rintros ⟨p, hp⟩ x hx m hm,
exact ⟨univ, filter.univ_sets _, p, (hp.has_ftaylor_series_up_to_on univ).of_le hm⟩ }
end
lemma times_cont_diff_iff_times_cont_diff_at {n : with_top ℕ} :
times_cont_diff 𝕜 n f ↔ ∀ x, times_cont_diff_at 𝕜 n f x :=
by simp [← times_cont_diff_on_univ, times_cont_diff_on, times_cont_diff_at]
lemma times_cont_diff.times_cont_diff_at {n : with_top ℕ} (h : times_cont_diff 𝕜 n f) :
times_cont_diff_at 𝕜 n f x :=
times_cont_diff_iff_times_cont_diff_at.1 h x
lemma times_cont_diff.times_cont_diff_within_at {n : with_top ℕ} (h : times_cont_diff 𝕜 n f) :
times_cont_diff_within_at 𝕜 n f s x :=
h.times_cont_diff_at.times_cont_diff_within_at
lemma times_cont_diff_top :
times_cont_diff 𝕜 ∞ f ↔ ∀ (n : ℕ), times_cont_diff 𝕜 n f :=
by simp [times_cont_diff_on_univ.symm, times_cont_diff_on_top]
lemma times_cont_diff_all_iff_nat :
(∀ n, times_cont_diff 𝕜 n f) ↔ (∀ n : ℕ, times_cont_diff 𝕜 n f) :=
by simp only [← times_cont_diff_on_univ, times_cont_diff_on_all_iff_nat]
lemma times_cont_diff.times_cont_diff_on {n : with_top ℕ}
(h : times_cont_diff 𝕜 n f) : times_cont_diff_on 𝕜 n f s :=
(times_cont_diff_on_univ.2 h).mono (subset_univ _)
@[simp] lemma times_cont_diff_zero :
times_cont_diff 𝕜 0 f ↔ continuous f :=
begin
rw [← times_cont_diff_on_univ, continuous_iff_continuous_on_univ],
exact times_cont_diff_on_zero
end
lemma times_cont_diff_at_zero :
times_cont_diff_at 𝕜 0 f x ↔ ∃ u ∈ 𝓝 x, continuous_on f u :=
by { rw ← times_cont_diff_within_at_univ, simp [times_cont_diff_within_at_zero, nhds_within_univ] }
lemma times_cont_diff.of_le {m n : with_top ℕ}
(h : times_cont_diff 𝕜 n f) (hmn : m ≤ n) :
times_cont_diff 𝕜 m f :=
times_cont_diff_on_univ.1 $ (times_cont_diff_on_univ.2 h).of_le hmn
lemma times_cont_diff.continuous {n : with_top ℕ}
(h : times_cont_diff 𝕜 n f) : continuous f :=
times_cont_diff_zero.1 (h.of_le bot_le)
/-- If a function is `C^n` with `n ≥ 1`, then it is differentiable. -/
lemma times_cont_diff.differentiable {n : with_top ℕ}
(h : times_cont_diff 𝕜 n f) (hn : 1 ≤ n) : differentiable 𝕜 f :=
differentiable_on_univ.1 $ (times_cont_diff_on_univ.2 h).differentiable_on hn
/-! ### Iterated derivative -/
variable (𝕜)
/-- The `n`-th derivative of a function, as a multilinear map, defined inductively. -/
noncomputable def iterated_fderiv (n : ℕ) (f : E → F) :
E → (E [×n]→L[𝕜] F) :=
nat.rec_on n
(λ x, continuous_multilinear_map.curry0 𝕜 E (f x))
(λ n rec x, continuous_linear_map.uncurry_left (fderiv 𝕜 rec x))
/-- Formal Taylor series associated to a function within a set. -/
def ftaylor_series (f : E → F) (x : E) : formal_multilinear_series 𝕜 E F :=
λ n, iterated_fderiv 𝕜 n f x
variable {𝕜}
@[simp] lemma iterated_fderiv_zero_apply (m : (fin 0) → E) :
(iterated_fderiv 𝕜 0 f x : ((fin 0) → E) → F) m = f x := rfl
lemma iterated_fderiv_zero_eq_comp :
iterated_fderiv 𝕜 0 f = (continuous_multilinear_curry_fin0 𝕜 E F).symm ∘ f := rfl
lemma iterated_fderiv_succ_apply_left {n : ℕ} (m : fin (n + 1) → E):
(iterated_fderiv 𝕜 (n + 1) f x : (fin (n + 1) → E) → F) m
= (fderiv 𝕜 (iterated_fderiv 𝕜 n f) x : E → (E [×n]→L[𝕜] F)) (m 0) (tail m) := rfl
/-- Writing explicitly the `n+1`-th derivative as the composition of a currying linear equiv,
and the derivative of the `n`-th derivative. -/
lemma iterated_fderiv_succ_eq_comp_left {n : ℕ} :
iterated_fderiv 𝕜 (n + 1) f =
(continuous_multilinear_curry_left_equiv 𝕜 (λ(i : fin (n + 1)), E) F)
∘ (fderiv 𝕜 (iterated_fderiv 𝕜 n f)) := rfl
lemma iterated_fderiv_within_univ {n : ℕ} :
iterated_fderiv_within 𝕜 n f univ = iterated_fderiv 𝕜 n f :=
begin
induction n with n IH,
{ ext x, simp },
{ ext x m,
rw [iterated_fderiv_succ_apply_left, iterated_fderiv_within_succ_apply_left, IH,
fderiv_within_univ] }
end
lemma ftaylor_series_within_univ :
ftaylor_series_within 𝕜 f univ = ftaylor_series 𝕜 f :=
begin
ext1 x, ext1 n,
change iterated_fderiv_within 𝕜 n f univ x = iterated_fderiv 𝕜 n f x,
rw iterated_fderiv_within_univ
end
theorem iterated_fderiv_succ_apply_right {n : ℕ} (m : fin (n + 1) → E) :
(iterated_fderiv 𝕜 (n + 1) f x : (fin (n + 1) → E) → F) m
= iterated_fderiv 𝕜 n (λy, fderiv 𝕜 f y) x (init m) (m (last n)) :=
begin
rw [← iterated_fderiv_within_univ, ← iterated_fderiv_within_univ, ← fderiv_within_univ],
exact iterated_fderiv_within_succ_apply_right unique_diff_on_univ (mem_univ _) _
end
/-- Writing explicitly the `n+1`-th derivative as the composition of a currying linear equiv,
and the `n`-th derivative of the derivative. -/
lemma iterated_fderiv_succ_eq_comp_right {n : ℕ} :
iterated_fderiv 𝕜 (n + 1) f x =
((continuous_multilinear_curry_right_equiv 𝕜 (λ(i : fin (n + 1)), E) F)
∘ (iterated_fderiv 𝕜 n (λy, fderiv 𝕜 f y))) x :=
by { ext m, rw iterated_fderiv_succ_apply_right, refl }
@[simp] lemma iterated_fderiv_one_apply (m : (fin 1) → E) :
(iterated_fderiv 𝕜 1 f x : ((fin 1) → E) → F) m
= (fderiv 𝕜 f x : E → F) (m 0) :=
by { rw [iterated_fderiv_succ_apply_right, iterated_fderiv_zero_apply], refl }
/-- When a function is `C^n` in a set `s` of unique differentiability, it admits
`ftaylor_series_within 𝕜 f s` as a Taylor series up to order `n` in `s`. -/
theorem times_cont_diff_on_iff_ftaylor_series {n : with_top ℕ} :
times_cont_diff 𝕜 n f ↔ has_ftaylor_series_up_to n f (ftaylor_series 𝕜 f) :=
begin
split,
{ rw [← times_cont_diff_on_univ, ← has_ftaylor_series_up_to_on_univ_iff,
← ftaylor_series_within_univ],
exact λ h, times_cont_diff_on.ftaylor_series_within h unique_diff_on_univ },
{ assume h, exact ⟨ftaylor_series 𝕜 f, h⟩ }
end
lemma times_cont_diff_iff_continuous_differentiable {n : with_top ℕ} :
times_cont_diff 𝕜 n f ↔
(∀ (m : ℕ), (m : with_top ℕ) ≤ n → continuous (λ x, iterated_fderiv 𝕜 m f x))
∧ (∀ (m : ℕ), (m : with_top ℕ) < n → differentiable 𝕜 (λ x, iterated_fderiv 𝕜 m f x)) :=
by simp [times_cont_diff_on_univ.symm, continuous_iff_continuous_on_univ,
differentiable_on_univ.symm, iterated_fderiv_within_univ,
times_cont_diff_on_iff_continuous_on_differentiable_on unique_diff_on_univ]
lemma times_cont_diff_of_differentiable_iterated_fderiv {n : with_top ℕ}
(h : ∀(m : ℕ), (m : with_top ℕ) ≤ n → differentiable 𝕜 (iterated_fderiv 𝕜 m f)) :
times_cont_diff 𝕜 n f :=
times_cont_diff_iff_continuous_differentiable.2
⟨λ m hm, (h m hm).continuous, λ m hm, (h m (le_of_lt hm))⟩
/-- A function is `C^(n + 1)` on a domain with unique derivatives if and only if it is differentiable
there, and its derivative is `C^n`. -/
theorem times_cont_diff_succ_iff_fderiv {n : ℕ} :
times_cont_diff 𝕜 ((n + 1) : ℕ) f ↔
differentiable 𝕜 f ∧ times_cont_diff 𝕜 n (λ y, fderiv 𝕜 f y) :=
by simp [times_cont_diff_on_univ.symm, differentiable_on_univ.symm, fderiv_within_univ.symm,
- fderiv_within_univ, times_cont_diff_on_succ_iff_fderiv_within unique_diff_on_univ,
-with_zero.coe_add, -add_comm]
/-- A function is `C^∞` on a domain with unique derivatives if and only if it is differentiable
there, and its derivative is `C^∞`. -/
theorem times_cont_diff_top_iff_fderiv :
times_cont_diff 𝕜 ∞ f ↔
differentiable 𝕜 f ∧ times_cont_diff 𝕜 ∞ (λ y, fderiv 𝕜 f y) :=
begin
simp [times_cont_diff_on_univ.symm, differentiable_on_univ.symm, fderiv_within_univ.symm,
- fderiv_within_univ],
rw times_cont_diff_on_top_iff_fderiv_within unique_diff_on_univ,
end
lemma times_cont_diff.continuous_fderiv {n : with_top ℕ}
(h : times_cont_diff 𝕜 n f) (hn : 1 ≤ n) :
continuous (λ x, fderiv 𝕜 f x) :=
((times_cont_diff_succ_iff_fderiv).1 (h.of_le hn)).2.continuous
/-- If a function is at least `C^1`, its bundled derivative (mapping `(x, v)` to `Df(x) v`) is
continuous. -/
lemma times_cont_diff.continuous_fderiv_apply {n : with_top ℕ}
(h : times_cont_diff 𝕜 n f) (hn : 1 ≤ n) :
continuous (λp : E × E, (fderiv 𝕜 f p.1 : E → F) p.2) :=
begin
have A : continuous (λq : (E →L[𝕜] F) × E, q.1 q.2) := is_bounded_bilinear_map_apply.continuous,
have B : continuous (λp : E × E, (fderiv 𝕜 f p.1, p.2)),
{ apply continuous.prod_mk _ continuous_snd,
exact continuous.comp (h.continuous_fderiv hn) continuous_fst },
exact A.comp B
end
/-! ### Constants -/
lemma iterated_fderiv_within_zero_fun {n : ℕ} :
iterated_fderiv 𝕜 n (λ x : E, (0 : F)) = 0 :=
begin
induction n with n IH,
{ ext m, simp },
{ ext x m,
rw [iterated_fderiv_succ_apply_left, IH],
change (fderiv 𝕜 (λ (x : E), (0 : (E [×n]→L[𝕜] F))) x : E → (E [×n]→L[𝕜] F)) (m 0) (tail m) = _,
rw fderiv_const,
refl }
end
lemma times_cont_diff_zero_fun {n : with_top ℕ} :
times_cont_diff 𝕜 n (λ x : E, (0 : F)) :=
begin
apply times_cont_diff_of_differentiable_iterated_fderiv (λm hm, _),
rw iterated_fderiv_within_zero_fun,
apply differentiable_const (0 : (E [×m]→L[𝕜] F))
end
/--
Constants are `C^∞`.
-/
lemma times_cont_diff_const {n : with_top ℕ} {c : F} : times_cont_diff 𝕜 n (λx : E, c) :=
begin
suffices h : times_cont_diff 𝕜 ∞ (λx : E, c), by exact h.of_le le_top,
rw times_cont_diff_top_iff_fderiv,
refine ⟨differentiable_const c, _⟩,
rw fderiv_const,
exact times_cont_diff_zero_fun
end
lemma times_cont_diff_on_const {n : with_top ℕ} {c : F} {s : set E} :
times_cont_diff_on 𝕜 n (λx : E, c) s :=
times_cont_diff_const.times_cont_diff_on
lemma times_cont_diff_at_const {n : with_top ℕ} {c : F} :
times_cont_diff_at 𝕜 n (λx : E, c) x :=
times_cont_diff_const.times_cont_diff_at
lemma times_cont_diff_within_at_const {n : with_top ℕ} {c : F} :
times_cont_diff_within_at 𝕜 n (λx : E, c) s x :=
times_cont_diff_at_const.times_cont_diff_within_at
@[nontriviality] lemma times_cont_diff_of_subsingleton [subsingleton F] {n : with_top ℕ} :
times_cont_diff 𝕜 n f :=
by { rw [subsingleton.elim f (λ _, 0)], exact times_cont_diff_const }
@[nontriviality] lemma times_cont_diff_at_of_subsingleton [subsingleton F] {n : with_top ℕ} :
times_cont_diff_at 𝕜 n f x :=
by { rw [subsingleton.elim f (λ _, 0)], exact times_cont_diff_at_const }
@[nontriviality] lemma times_cont_diff_within_at_of_subsingleton [subsingleton F] {n : with_top ℕ} :
times_cont_diff_within_at 𝕜 n f s x :=
by { rw [subsingleton.elim f (λ _, 0)], exact times_cont_diff_within_at_const }
@[nontriviality] lemma times_cont_diff_on_of_subsingleton [subsingleton F] {n : with_top ℕ} :
times_cont_diff_on 𝕜 n f s :=
by { rw [subsingleton.elim f (λ _, 0)], exact times_cont_diff_on_const }
/-! ### Linear functions -/
/--
Unbundled bounded linear functions are `C^∞`.
-/
lemma is_bounded_linear_map.times_cont_diff {n : with_top ℕ} (hf : is_bounded_linear_map 𝕜 f) :
times_cont_diff 𝕜 n f :=
begin
suffices h : times_cont_diff 𝕜 ∞ f, by exact h.of_le le_top,
rw times_cont_diff_top_iff_fderiv,
refine ⟨hf.differentiable, _⟩,
simp [hf.fderiv],
exact times_cont_diff_const
end
lemma continuous_linear_map.times_cont_diff {n : with_top ℕ} (f : E →L[𝕜] F) :
times_cont_diff 𝕜 n f :=
f.is_bounded_linear_map.times_cont_diff
/--
The first projection in a product is `C^∞`.
-/
lemma times_cont_diff_fst {n : with_top ℕ} : times_cont_diff 𝕜 n (prod.fst : E × F → E) :=
is_bounded_linear_map.times_cont_diff is_bounded_linear_map.fst
/--
The first projection on a domain in a product is `C^∞`.
-/
lemma times_cont_diff_on_fst {s : set (E×F)} {n : with_top ℕ} :
times_cont_diff_on 𝕜 n (prod.fst : E × F → E) s :=
times_cont_diff.times_cont_diff_on times_cont_diff_fst
/--
The first projection at a point in a product is `C^∞`.
-/
lemma times_cont_diff_at_fst {p : E × F} {n : with_top ℕ} :
times_cont_diff_at 𝕜 n (prod.fst : E × F → E) p :=
times_cont_diff_fst.times_cont_diff_at
/--
The first projection within a domain at a point in a product is `C^∞`.
-/
lemma times_cont_diff_within_at_fst {s : set (E × F)} {p : E × F} {n : with_top ℕ} :
times_cont_diff_within_at 𝕜 n (prod.fst : E × F → E) s p :=
times_cont_diff_fst.times_cont_diff_within_at
/--
The second projection in a product is `C^∞`.
-/
lemma times_cont_diff_snd {n : with_top ℕ} : times_cont_diff 𝕜 n (prod.snd : E × F → F) :=
is_bounded_linear_map.times_cont_diff is_bounded_linear_map.snd
/--
The second projection on a domain in a product is `C^∞`.
-/
lemma times_cont_diff_on_snd {s : set (E×F)} {n : with_top ℕ} :
times_cont_diff_on 𝕜 n (prod.snd : E × F → F) s :=
times_cont_diff.times_cont_diff_on times_cont_diff_snd
/--
The second projection at a point in a product is `C^∞`.
-/
lemma times_cont_diff_at_snd {p : E × F} {n : with_top ℕ} :
times_cont_diff_at 𝕜 n (prod.snd : E × F → F) p :=
times_cont_diff_snd.times_cont_diff_at
/--
The second projection within a domain at a point in a product is `C^∞`.
-/
lemma times_cont_diff_within_at_snd {s : set (E × F)} {p : E × F} {n : with_top ℕ} :
times_cont_diff_within_at 𝕜 n (prod.snd : E × F → F) s p :=
times_cont_diff_snd.times_cont_diff_within_at
/--
The identity is `C^∞`.
-/
lemma times_cont_diff_id {n : with_top ℕ} : times_cont_diff 𝕜 n (id : E → E) :=
is_bounded_linear_map.id.times_cont_diff
lemma times_cont_diff_within_at_id {n : with_top ℕ} {s x} :
times_cont_diff_within_at 𝕜 n (id : E → E) s x :=
times_cont_diff_id.times_cont_diff_within_at
lemma times_cont_diff_at_id {n : with_top ℕ} {x} :
times_cont_diff_at 𝕜 n (id : E → E) x :=
times_cont_diff_id.times_cont_diff_at
lemma times_cont_diff_on_id {n : with_top ℕ} {s} :
times_cont_diff_on 𝕜 n (id : E → E) s :=
times_cont_diff_id.times_cont_diff_on
/--
Bilinear functions are `C^∞`.
-/
lemma is_bounded_bilinear_map.times_cont_diff {n : with_top ℕ} (hb : is_bounded_bilinear_map 𝕜 b) :
times_cont_diff 𝕜 n b :=
begin
suffices h : times_cont_diff 𝕜 ∞ b, by exact h.of_le le_top,
rw times_cont_diff_top_iff_fderiv,
refine ⟨hb.differentiable, _⟩,
simp [hb.fderiv],
exact hb.is_bounded_linear_map_deriv.times_cont_diff
end
/-- If `f` admits a Taylor series `p` in a set `s`, and `g` is linear, then `g ∘ f` admits a Taylor
series whose `k`-th term is given by `g ∘ (p k)`. -/
lemma has_ftaylor_series_up_to_on.continuous_linear_map_comp {n : with_top ℕ} (g : F →L[𝕜] G)
(hf : has_ftaylor_series_up_to_on n f p s) :
has_ftaylor_series_up_to_on n (g ∘ f) (λ x k, g.comp_continuous_multilinear_map (p x k)) s :=
begin
split,
{ assume x hx, simp [(hf.zero_eq x hx).symm] },
{ assume m hm x hx,
let A : (E [×m]→L[𝕜] F) → (E [×m]→L[𝕜] G) := λ f, g.comp_continuous_multilinear_map f,
have hA : is_bounded_linear_map 𝕜 A :=
is_bounded_bilinear_map_comp_multilinear.is_bounded_linear_map_right _,
have := hf.fderiv_within m hm x hx,
convert has_fderiv_at.comp_has_fderiv_within_at x (hA.has_fderiv_at) this },
{ assume m hm,
let A : (E [×m]→L[𝕜] F) → (E [×m]→L[𝕜] G) :=
λ f, g.comp_continuous_multilinear_map f,
have hA : is_bounded_linear_map 𝕜 A :=
is_bounded_bilinear_map_comp_multilinear.is_bounded_linear_map_right _,
exact hA.continuous.comp_continuous_on (hf.cont m hm) }
end
/-- Composition by continuous linear maps on the left preserves `C^n` functions in a domain
at a point. -/
lemma times_cont_diff_within_at.continuous_linear_map_comp {n : with_top ℕ} (g : F →L[𝕜] G)
(hf : times_cont_diff_within_at 𝕜 n f s x) :
times_cont_diff_within_at 𝕜 n (g ∘ f) s x :=
begin
assume m hm,
rcases hf m hm with ⟨u, hu, p, hp⟩,
exact ⟨u, hu, _, hp.continuous_linear_map_comp g⟩,
end
/-- Composition by continuous linear maps on the left preserves `C^n` functions in a domain
at a point. -/
lemma times_cont_diff_at.continuous_linear_map_comp {n : with_top ℕ} (g : F →L[𝕜] G)
(hf : times_cont_diff_at 𝕜 n f x) :
times_cont_diff_at 𝕜 n (g ∘ f) x :=
times_cont_diff_within_at.continuous_linear_map_comp g hf
/-- Composition by continuous linear maps on the left preserves `C^n` functions on domains. -/
lemma times_cont_diff_on.continuous_linear_map_comp {n : with_top ℕ} (g : F →L[𝕜] G)
(hf : times_cont_diff_on 𝕜 n f s) :
times_cont_diff_on 𝕜 n (g ∘ f) s :=
λ x hx, (hf x hx).continuous_linear_map_comp g
/-- Composition by continuous linear maps on the left preserves `C^n` functions. -/
lemma times_cont_diff.continuous_linear_map_comp {n : with_top ℕ} {f : E → F} (g : F →L[𝕜] G)
(hf : times_cont_diff 𝕜 n f) : times_cont_diff 𝕜 n (λx, g (f x)) :=
times_cont_diff_on_univ.1 $ times_cont_diff_on.continuous_linear_map_comp
_ (times_cont_diff_on_univ.2 hf)
/-- Composition by continuous linear equivs on the left respects higher differentiability on
domains. -/
lemma continuous_linear_equiv.comp_times_cont_diff_within_at_iff
{n : with_top ℕ} (e : F ≃L[𝕜] G) :
times_cont_diff_within_at 𝕜 n (e ∘ f) s x ↔ times_cont_diff_within_at 𝕜 n f s x :=
begin
split,
{ assume H,
have : f = e.symm ∘ (e ∘ f),
by { ext y, simp only [function.comp_app], rw e.symm_apply_apply (f y) },
rw this,
exact H.continuous_linear_map_comp _ },
{ assume H,
exact H.continuous_linear_map_comp _ }
end
/-- Composition by continuous linear equivs on the left respects higher differentiability on
domains. -/
lemma continuous_linear_equiv.comp_times_cont_diff_on_iff
{n : with_top ℕ} (e : F ≃L[𝕜] G) :
times_cont_diff_on 𝕜 n (e ∘ f) s ↔ times_cont_diff_on 𝕜 n f s :=
by simp [times_cont_diff_on, e.comp_times_cont_diff_within_at_iff]
/-- If `f` admits a Taylor series `p` in a set `s`, and `g` is linear, then `f ∘ g` admits a Taylor
series in `g ⁻¹' s`, whose `k`-th term is given by `p k (g v₁, ..., g vₖ)` . -/
lemma has_ftaylor_series_up_to_on.comp_continuous_linear_map {n : with_top ℕ}
(hf : has_ftaylor_series_up_to_on n f p s) (g : G →L[𝕜] E) :
has_ftaylor_series_up_to_on n (f ∘ g)
(λ x k, (p (g x) k).comp_continuous_linear_map (λ _, g)) (g ⁻¹' s) :=
begin
let A : Π m : ℕ, (E [×m]→L[𝕜] F) → (G [×m]→L[𝕜] F) :=
λ m h, h.comp_continuous_linear_map (λ _, g),
have hA : ∀ m, is_bounded_linear_map 𝕜 (A m) :=
λ m, is_bounded_linear_map_continuous_multilinear_map_comp_linear g,
split,
{ assume x hx,
simp only [(hf.zero_eq (g x) hx).symm, function.comp_app],
change p (g x) 0 (λ (i : fin 0), g 0) = p (g x) 0 0,
rw continuous_linear_map.map_zero,
refl },
{ assume m hm x hx,
convert ((hA m).has_fderiv_at).comp_has_fderiv_within_at x
((hf.fderiv_within m hm (g x) hx).comp x (g.has_fderiv_within_at) (subset.refl _)),
ext y v,
change p (g x) (nat.succ m) (g ∘ (cons y v)) = p (g x) m.succ (cons (g y) (g ∘ v)),
rw comp_cons },
{ assume m hm,
exact (hA m).continuous.comp_continuous_on
((hf.cont m hm).comp g.continuous.continuous_on (subset.refl _)) }
end
/-- Composition by continuous linear maps on the right preserves `C^n` functions at a point on
a domain. -/
lemma times_cont_diff_within_at.comp_continuous_linear_map {n : with_top ℕ} {x : G}
(g : G →L[𝕜] E) (hf : times_cont_diff_within_at 𝕜 n f s (g x)) :
times_cont_diff_within_at 𝕜 n (f ∘ g) (g ⁻¹' s) x :=
begin
assume m hm,
rcases hf m hm with ⟨u, hu, p, hp⟩,
refine ⟨g ⁻¹' u, _, _, hp.comp_continuous_linear_map g⟩,
apply continuous_within_at.preimage_mem_nhds_within',
{ exact g.continuous.continuous_within_at },
{ apply nhds_within_mono (g x) _ hu,
rw image_insert_eq,
exact insert_subset_insert (image_preimage_subset g s) }
end
/-- Composition by continuous linear maps on the right preserves `C^n` functions on domains. -/
lemma times_cont_diff_on.comp_continuous_linear_map {n : with_top ℕ}
(hf : times_cont_diff_on 𝕜 n f s) (g : G →L[𝕜] E) :
times_cont_diff_on 𝕜 n (f ∘ g) (g ⁻¹' s) :=
λ x hx, (hf (g x) hx).comp_continuous_linear_map g
/-- Composition by continuous linear maps on the right preserves `C^n` functions. -/
lemma times_cont_diff.comp_continuous_linear_map {n : with_top ℕ} {f : E → F} {g : G →L[𝕜] E}
(hf : times_cont_diff 𝕜 n f) : times_cont_diff 𝕜 n (f ∘ g) :=
times_cont_diff_on_univ.1 $
times_cont_diff_on.comp_continuous_linear_map (times_cont_diff_on_univ.2 hf) _
/-- Composition by continuous linear equivs on the right respects higher differentiability at a
point in a domain. -/
lemma continuous_linear_equiv.times_cont_diff_within_at_comp_iff {n : with_top ℕ} (e : G ≃L[𝕜] E) :
times_cont_diff_within_at 𝕜 n (f ∘ e) (e ⁻¹' s) (e.symm x) ↔
times_cont_diff_within_at 𝕜 n f s x :=
begin
split,
{ assume H,
have A : f = (f ∘ e) ∘ e.symm,
by { ext y, simp only [function.comp_app], rw e.apply_symm_apply y },
have B : e.symm ⁻¹' (e ⁻¹' s) = s,
by { rw [← preimage_comp, e.self_comp_symm], refl },
rw [A, ← B],
exact H.comp_continuous_linear_map _},
{ assume H,
have : x = e (e.symm x), by simp,
rw this at H,
exact H.comp_continuous_linear_map _ },
end
/-- Composition by continuous linear equivs on the right respects higher differentiability on
domains. -/
lemma continuous_linear_equiv.times_cont_diff_on_comp_iff {n : with_top ℕ} (e : G ≃L[𝕜] E) :
times_cont_diff_on 𝕜 n (f ∘ e) (e ⁻¹' s) ↔ times_cont_diff_on 𝕜 n f s :=
begin
refine ⟨λ H, _, λ H, H.comp_continuous_linear_map _⟩,
have A : f = (f ∘ e) ∘ e.symm,
by { ext y, simp only [function.comp_app], rw e.apply_symm_apply y },
have B : e.symm ⁻¹' (e ⁻¹' s) = s,
by { rw [← preimage_comp, e.self_comp_symm], refl },
rw [A, ← B],
exact H.comp_continuous_linear_map _
end
/-- If two functions `f` and `g` admit Taylor series `p` and `q` in a set `s`, then the cartesian
product of `f` and `g` admits the cartesian product of `p` and `q` as a Taylor series. -/
lemma has_ftaylor_series_up_to_on.prod {n : with_top ℕ} (hf : has_ftaylor_series_up_to_on n f p s)
{g : E → G} {q : E → formal_multilinear_series 𝕜 E G} (hg : has_ftaylor_series_up_to_on n g q s) :
has_ftaylor_series_up_to_on n (λ y, (f y, g y)) (λ y k, (p y k).prod (q y k)) s :=
begin
split,
{ assume x hx, rw [← hf.zero_eq x hx, ← hg.zero_eq x hx], refl },
{ assume m hm x hx,
let A : (E [×m]→L[𝕜] F) × (E [×m]→L[𝕜] G) → (E [×m]→L[𝕜] (F × G)) := λ p, p.1.prod p.2,
have hA : is_bounded_linear_map 𝕜 A := is_bounded_linear_map_prod_multilinear,
convert hA.has_fderiv_at.comp_has_fderiv_within_at x
((hf.fderiv_within m hm x hx).prod (hg.fderiv_within m hm x hx)) },
{ assume m hm,
let A : (E [×m]→L[𝕜] F) × (E [×m]→L[𝕜] G) → (E [×m]→L[𝕜] (F × G)) := λ p, p.1.prod p.2,
have hA : is_bounded_linear_map 𝕜 A := is_bounded_linear_map_prod_multilinear,
exact hA.continuous.comp_continuous_on ((hf.cont m hm).prod (hg.cont m hm)) }
end
/-- The cartesian product of `C^n` functions at a point in a domain is `C^n`. -/
lemma times_cont_diff_within_at.prod {n : with_top ℕ} {s : set E} {f : E → F} {g : E → G}
(hf : times_cont_diff_within_at 𝕜 n f s x) (hg : times_cont_diff_within_at 𝕜 n g s x) :
times_cont_diff_within_at 𝕜 n (λx:E, (f x, g x)) s x :=
begin
assume m hm,
rcases hf m hm with ⟨u, hu, p, hp⟩,
rcases hg m hm with ⟨v, hv, q, hq⟩,
exact ⟨u ∩ v, filter.inter_mem_sets hu hv, _,
(hp.mono (inter_subset_left u v)).prod (hq.mono (inter_subset_right u v))⟩
end
/-- The cartesian product of `C^n` functions on domains is `C^n`. -/
lemma times_cont_diff_on.prod {n : with_top ℕ} {s : set E} {f : E → F} {g : E → G}
(hf : times_cont_diff_on 𝕜 n f s) (hg : times_cont_diff_on 𝕜 n g s) :
times_cont_diff_on 𝕜 n (λx:E, (f x, g x)) s :=
λ x hx, (hf x hx).prod (hg x hx)
/-- The cartesian product of `C^n` functions at a point is `C^n`. -/
lemma times_cont_diff_at.prod {n : with_top ℕ} {f : E → F} {g : E → G}
(hf : times_cont_diff_at 𝕜 n f x) (hg : times_cont_diff_at 𝕜 n g x) :
times_cont_diff_at 𝕜 n (λx:E, (f x, g x)) x :=
times_cont_diff_within_at_univ.1 $ times_cont_diff_within_at.prod (times_cont_diff_within_at_univ.2 hf)
(times_cont_diff_within_at_univ.2 hg)
/--
The cartesian product of `C^n` functions is `C^n`.
-/
lemma times_cont_diff.prod {n : with_top ℕ} {f : E → F} {g : E → G}
(hf : times_cont_diff 𝕜 n f) (hg : times_cont_diff 𝕜 n g) :
times_cont_diff 𝕜 n (λx:E, (f x, g x)) :=
times_cont_diff_on_univ.1 $ times_cont_diff_on.prod (times_cont_diff_on_univ.2 hf)
(times_cont_diff_on_univ.2 hg)
/-!
### Composition of `C^n` functions
We show that the composition of `C^n` functions is `C^n`. One way to prove it would be to write
the `n`-th derivative of the composition (this is Faà di Bruno's formula) and check its continuity,
but this is very painful. Instead, we go for a simple inductive proof. Assume it is done for `n`.
Then, to check it for `n+1`, one needs to check that the derivative of `g ∘ f` is `C^n`, i.e.,
that `Dg(f x) ⬝ Df(x)` is `C^n`. The term `Dg (f x)` is the composition of two `C^n` functions, so
it is `C^n` by the inductive assumption. The term `Df(x)` is also `C^n`. Then, the matrix
multiplication is the application of a bilinear map (which is `C^∞`, and therefore `C^n`) to
`x ↦ (Dg(f x), Df x)`. As the composition of two `C^n` maps, it is again `C^n`, and we are done.
There is a subtlety in this argument: we apply the inductive assumption to functions on other Banach
spaces. In maths, one would say: prove by induction over `n` that, for all `C^n` maps between all
pairs of Banach spaces, their composition is `C^n`. In Lean, this is fine as long as the spaces
stay in the same universe. This is not the case in the above argument: if `E` lives in universe `u`
and `F` lives in universe `v`, then linear maps from `E` to `F` (to which the derivative of `f`
belongs) is in universe `max u v`. If one could quantify over finitely many universes, the above
proof would work fine, but this is not the case. One could still write the proof considering spaces
in any universe in `u, v, w, max u v, max v w, max u v w`, but it would be extremely tedious and
lead to a lot of duplication. Instead, we formulate the above proof when all spaces live in the same
universe (where everything is fine), and then we deduce the general result by lifting all our spaces
to a common universe. We use the trick that any space `H` is isomorphic through a continuous linear
equiv to `continuous_multilinear_map (λ (i : fin 0), E × F × G) H` to change the universe level,
and then argue that composing with such a linear equiv does not change the fact of being `C^n`,
which we have already proved previously.
-/
/-- Auxiliary lemma proving that the composition of `C^n` functions on domains is `C^n` when all
spaces live in the same universe. Use instead `times_cont_diff_on.comp` which removes the universe
assumption (but is deduced from this one). -/
private lemma times_cont_diff_on.comp_same_univ
{Eu : Type u} [normed_group Eu] [normed_space 𝕜 Eu]
{Fu : Type u} [normed_group Fu] [normed_space 𝕜 Fu]
{Gu : Type u} [normed_group Gu] [normed_space 𝕜 Gu]
{n : with_top ℕ} {s : set Eu} {t : set Fu} {g : Fu → Gu} {f : Eu → Fu}
(hg : times_cont_diff_on 𝕜 n g t) (hf : times_cont_diff_on 𝕜 n f s) (st : s ⊆ f ⁻¹' t) :
times_cont_diff_on 𝕜 n (g ∘ f) s :=
begin
unfreezingI { induction n using with_top.nat_induction with n IH Itop generalizing Eu Fu Gu },
{ rw times_cont_diff_on_zero at hf hg ⊢,
exact continuous_on.comp hg hf st },
{ rw times_cont_diff_on_succ_iff_has_fderiv_within_at at hg ⊢,
assume x hx,
rcases (times_cont_diff_on_succ_iff_has_fderiv_within_at.1 hf) x hx
with ⟨u, hu, f', hf', f'_diff⟩,
rcases hg (f x) (st hx) with ⟨v, hv, g', hg', g'_diff⟩,
rw insert_eq_of_mem hx at hu ⊢,
have xu : x ∈ u := mem_of_mem_nhds_within hx hu,
let w := s ∩ (u ∩ f⁻¹' v),
have wv : w ⊆ f ⁻¹' v := λ y hy, hy.2.2,
have wu : w ⊆ u := λ y hy, hy.2.1,
have ws : w ⊆ s := λ y hy, hy.1,
refine ⟨w, _, λ y, (g' (f y)).comp (f' y), _, _⟩,
show w ∈ 𝓝[s] x,
{ apply filter.inter_mem_sets self_mem_nhds_within,
apply filter.inter_mem_sets hu,
apply continuous_within_at.preimage_mem_nhds_within',
{ rw ← continuous_within_at_inter' hu,
exact (hf' x xu).differentiable_within_at.continuous_within_at.mono
(inter_subset_right _ _) },
{ apply nhds_within_mono _ _ hv,
exact subset.trans (image_subset_iff.mpr st) (subset_insert (f x) t) } },
show ∀ y ∈ w,
has_fderiv_within_at (g ∘ f) ((g' (f y)).comp (f' y)) w y,
{ rintros y ⟨ys, yu, yv⟩,
exact (hg' (f y) yv).comp y ((hf' y yu).mono wu) wv },
show times_cont_diff_on 𝕜 n (λ y, (g' (f y)).comp (f' y)) w,
{ have A : times_cont_diff_on 𝕜 n (λ y, g' (f y)) w :=
IH g'_diff ((hf.of_le (with_top.coe_le_coe.2 (nat.le_succ n))).mono ws) wv,
have B : times_cont_diff_on 𝕜 n f' w := f'_diff.mono wu,
have C : times_cont_diff_on 𝕜 n (λ y, (f' y, g' (f y))) w :=
times_cont_diff_on.prod B A,
have D : times_cont_diff_on 𝕜 n (λ(p : (Eu →L[𝕜] Fu) × (Fu →L[𝕜] Gu)), p.2.comp p.1) univ :=
is_bounded_bilinear_map_comp.times_cont_diff.times_cont_diff_on,
exact IH D C (subset_univ _) } },
{ rw times_cont_diff_on_top at hf hg ⊢,
assume n,
apply Itop n (hg n) (hf n) st }
end
/-- The composition of `C^n` functions on domains is `C^n`. -/
lemma times_cont_diff_on.comp
{n : with_top ℕ} {s : set E} {t : set F} {g : F → G} {f : E → F}
(hg : times_cont_diff_on 𝕜 n g t) (hf : times_cont_diff_on 𝕜 n f s) (st : s ⊆ f ⁻¹' t) :
times_cont_diff_on 𝕜 n (g ∘ f) s :=
begin
/- we lift all the spaces to a common universe, as we have already proved the result in this
situation. For the lift, we use the trick that `H` is isomorphic through a
continuous linear equiv to `continuous_multilinear_map 𝕜 (λ (i : fin 0), (E × F × G)) H`, and
continuous linear equivs respect smoothness classes. -/
let Eu := continuous_multilinear_map 𝕜 (λ (i : fin 0), (E × F × G)) E,
letI : normed_group Eu := by apply_instance,
letI : normed_space 𝕜 Eu := by apply_instance,
let Fu := continuous_multilinear_map 𝕜 (λ (i : fin 0), (E × F × G)) F,
letI : normed_group Fu := by apply_instance,
letI : normed_space 𝕜 Fu := by apply_instance,
let Gu := continuous_multilinear_map 𝕜 (λ (i : fin 0), (E × F × G)) G,
letI : normed_group Gu := by apply_instance,
letI : normed_space 𝕜 Gu := by apply_instance,
-- declare the isomorphisms
let isoE : Eu ≃L[𝕜] E := continuous_multilinear_curry_fin0 𝕜 (E × F × G) E,
let isoF : Fu ≃L[𝕜] F := continuous_multilinear_curry_fin0 𝕜 (E × F × G) F,
let isoG : Gu ≃L[𝕜] G := continuous_multilinear_curry_fin0 𝕜 (E × F × G) G,
-- lift the functions to the new spaces, check smoothness there, and then go back.
let fu : Eu → Fu := (isoF.symm ∘ f) ∘ isoE,
have fu_diff : times_cont_diff_on 𝕜 n fu (isoE ⁻¹' s),
by rwa [isoE.times_cont_diff_on_comp_iff, isoF.symm.comp_times_cont_diff_on_iff],
let gu : Fu → Gu := (isoG.symm ∘ g) ∘ isoF,
have gu_diff : times_cont_diff_on 𝕜 n gu (isoF ⁻¹' t),
by rwa [isoF.times_cont_diff_on_comp_iff, isoG.symm.comp_times_cont_diff_on_iff],
have main : times_cont_diff_on 𝕜 n (gu ∘ fu) (isoE ⁻¹' s),
{ apply times_cont_diff_on.comp_same_univ gu_diff fu_diff,
assume y hy,
simp only [fu, continuous_linear_equiv.coe_apply, function.comp_app, mem_preimage],
rw isoF.apply_symm_apply (f (isoE y)),
exact st hy },
have : gu ∘ fu = (isoG.symm ∘ (g ∘ f)) ∘ isoE,
{ ext y,
simp only [function.comp_apply, gu, fu],
rw isoF.apply_symm_apply (f (isoE y)) },
rwa [this, isoE.times_cont_diff_on_comp_iff, isoG.symm.comp_times_cont_diff_on_iff] at main
end
/-- The composition of `C^n` functions on domains is `C^n`. -/
lemma times_cont_diff_on.comp'
{n : with_top ℕ} {s : set E} {t : set F} {g : F → G} {f : E → F}
(hg : times_cont_diff_on 𝕜 n g t) (hf : times_cont_diff_on 𝕜 n f s) :
times_cont_diff_on 𝕜 n (g ∘ f) (s ∩ f⁻¹' t) :=
hg.comp (hf.mono (inter_subset_left _ _)) (inter_subset_right _ _)
/-- The composition of a `C^n` function on a domain with a `C^n` function is `C^n`. -/
lemma times_cont_diff.comp_times_cont_diff_on {n : with_top ℕ} {s : set E} {g : F → G} {f : E → F}
(hg : times_cont_diff 𝕜 n g) (hf : times_cont_diff_on 𝕜 n f s) :
times_cont_diff_on 𝕜 n (g ∘ f) s :=
(times_cont_diff_on_univ.2 hg).comp hf subset_preimage_univ
/-- The composition of `C^n` functions is `C^n`. -/
lemma times_cont_diff.comp {n : with_top ℕ} {g : F → G} {f : E → F}
(hg : times_cont_diff 𝕜 n g) (hf : times_cont_diff 𝕜 n f) :
times_cont_diff 𝕜 n (g ∘ f) :=
times_cont_diff_on_univ.1 $ times_cont_diff_on.comp (times_cont_diff_on_univ.2 hg)
(times_cont_diff_on_univ.2 hf) (subset_univ _)
/-- The composition of `C^n` functions at points in domains is `C^n`. -/
lemma times_cont_diff_within_at.comp
{n : with_top ℕ} {s : set E} {t : set F} {g : F → G} {f : E → F} (x : E)
(hg : times_cont_diff_within_at 𝕜 n g t (f x))
(hf : times_cont_diff_within_at 𝕜 n f s x) (st : s ⊆ f ⁻¹' t) :
times_cont_diff_within_at 𝕜 n (g ∘ f) s x :=
begin
assume m hm,
rcases hg.times_cont_diff_on hm with ⟨u, u_nhd, ut, hu⟩,
rcases hf.times_cont_diff_on hm with ⟨v, v_nhd, vs, hv⟩,
have xmem : x ∈ f ⁻¹' u ∩ v :=
⟨(mem_of_mem_nhds_within (mem_insert (f x) _) u_nhd : _),
mem_of_mem_nhds_within (mem_insert x s) v_nhd⟩,
have : f ⁻¹' u ∈ 𝓝[insert x s] x,
{ apply hf.continuous_within_at.insert_self.preimage_mem_nhds_within',
apply nhds_within_mono _ _ u_nhd,
rw image_insert_eq,
exact insert_subset_insert (image_subset_iff.mpr st) },
have Z := ((hu.comp (hv.mono (inter_subset_right (f ⁻¹' u) v)) (inter_subset_left _ _))
.times_cont_diff_within_at) xmem m (le_refl _),
have : 𝓝[f ⁻¹' u ∩ v] x = 𝓝[insert x s] x,
{ have A : f ⁻¹' u ∩ v = (insert x s) ∩ (f ⁻¹' u ∩ v),
{ apply subset.antisymm _ (inter_subset_right _ _),
rintros y ⟨hy1, hy2⟩,
simp [hy1, hy2, vs hy2] },
rw [A, ← nhds_within_restrict''],
exact filter.inter_mem_sets this v_nhd },
rwa [insert_eq_of_mem xmem, this] at Z,
end
/-- The composition of `C^n` functions at points in domains is `C^n`. -/
lemma times_cont_diff_within_at.comp' {n : with_top ℕ} {s : set E} {t : set F} {g : F → G}
{f : E → F} (x : E)
(hg : times_cont_diff_within_at 𝕜 n g t (f x)) (hf : times_cont_diff_within_at 𝕜 n f s x) :
times_cont_diff_within_at 𝕜 n (g ∘ f) (s ∩ f⁻¹' t) x :=
hg.comp x (hf.mono (inter_subset_left _ _)) (inter_subset_right _ _)
lemma times_cont_diff_at.comp_times_cont_diff_within_at {n} (x : E)
(hg : times_cont_diff_at 𝕜 n g (f x)) (hf : times_cont_diff_within_at 𝕜 n f s x) :
times_cont_diff_within_at 𝕜 n (g ∘ f) s x :=
hg.comp x hf (maps_to_univ _ _)
/-- The composition of `C^n` functions at points is `C^n`. -/
lemma times_cont_diff_at.comp {n : with_top ℕ} (x : E)
(hg : times_cont_diff_at 𝕜 n g (f x))
(hf : times_cont_diff_at 𝕜 n f x) :
times_cont_diff_at 𝕜 n (g ∘ f) x :=
hg.comp x hf subset_preimage_univ
lemma times_cont_diff.comp_times_cont_diff_within_at
{n : with_top ℕ} {g : F → G} {f : E → F} (h : times_cont_diff 𝕜 n g)
(hf : times_cont_diff_within_at 𝕜 n f t x) :
times_cont_diff_within_at 𝕜 n (g ∘ f) t x :=
begin
have : times_cont_diff_within_at 𝕜 n g univ (f x) :=
h.times_cont_diff_at.times_cont_diff_within_at,
exact this.comp x hf (subset_univ _),
end
lemma times_cont_diff.comp_times_cont_diff_at
{n : with_top ℕ} {g : F → G} {f : E → F} (x : E)
(hg : times_cont_diff 𝕜 n g)
(hf : times_cont_diff_at 𝕜 n f x) :
times_cont_diff_at 𝕜 n (g ∘ f) x :=
hg.comp_times_cont_diff_within_at hf
/-- The bundled derivative of a `C^{n+1}` function is `C^n`. -/
lemma times_cont_diff_on_fderiv_within_apply {m n : with_top ℕ} {s : set E}
{f : E → F} (hf : times_cont_diff_on 𝕜 n f s) (hs : unique_diff_on 𝕜 s) (hmn : m + 1 ≤ n) :
times_cont_diff_on 𝕜 m (λp : E × E, (fderiv_within 𝕜 f s p.1 : E →L[𝕜] F) p.2)
(set.prod s (univ : set E)) :=
begin
have A : times_cont_diff 𝕜 m (λp : (E →L[𝕜] F) × E, p.1 p.2),
{ apply is_bounded_bilinear_map.times_cont_diff,
exact is_bounded_bilinear_map_apply },
have B : times_cont_diff_on 𝕜 m
(λ (p : E × E), ((fderiv_within 𝕜 f s p.fst), p.snd)) (set.prod s univ),
{ apply times_cont_diff_on.prod _ _,
{ have I : times_cont_diff_on 𝕜 m (λ (x : E), fderiv_within 𝕜 f s x) s :=
hf.fderiv_within hs hmn,
have J : times_cont_diff_on 𝕜 m (λ (x : E × E), x.1) (set.prod s univ) :=
times_cont_diff_fst.times_cont_diff_on,
exact times_cont_diff_on.comp I J (prod_subset_preimage_fst _ _) },
{ apply times_cont_diff.times_cont_diff_on _ ,
apply is_bounded_linear_map.snd.times_cont_diff } },
exact A.comp_times_cont_diff_on B
end
/-- The bundled derivative of a `C^{n+1}` function is `C^n`. -/
lemma times_cont_diff.times_cont_diff_fderiv_apply {n m : with_top ℕ} {f : E → F}
(hf : times_cont_diff 𝕜 n f) (hmn : m + 1 ≤ n) :
times_cont_diff 𝕜 m (λp : E × E, (fderiv 𝕜 f p.1 : E →L[𝕜] F) p.2) :=
begin
rw ← times_cont_diff_on_univ at ⊢ hf,
rw [← fderiv_within_univ, ← univ_prod_univ],
exact times_cont_diff_on_fderiv_within_apply hf unique_diff_on_univ hmn
end
/-! ### Sum of two functions -/
/- The sum is smooth. -/
lemma times_cont_diff_add {n : with_top ℕ} :
times_cont_diff 𝕜 n (λp : F × F, p.1 + p.2) :=
(is_bounded_linear_map.fst.add is_bounded_linear_map.snd).times_cont_diff
/-- The sum of two `C^n` functions within a set at a point is `C^n` within this set
at this point. -/
lemma times_cont_diff_within_at.add {n : with_top ℕ} {s : set E} {f g : E → F}
(hf : times_cont_diff_within_at 𝕜 n f s x) (hg : times_cont_diff_within_at 𝕜 n g s x) :
times_cont_diff_within_at 𝕜 n (λx, f x + g x) s x :=
times_cont_diff_add.times_cont_diff_within_at.comp x (hf.prod hg) subset_preimage_univ
/-- The sum of two `C^n` functions at a point is `C^n` at this point. -/
lemma times_cont_diff_at.add {n : with_top ℕ} {f g : E → F}
(hf : times_cont_diff_at 𝕜 n f x) (hg : times_cont_diff_at 𝕜 n g x) :
times_cont_diff_at 𝕜 n (λx, f x + g x) x :=
by rw [← times_cont_diff_within_at_univ] at *; exact hf.add hg
/-- The sum of two `C^n`functions is `C^n`. -/
lemma times_cont_diff.add {n : with_top ℕ} {f g : E → F}
(hf : times_cont_diff 𝕜 n f) (hg : times_cont_diff 𝕜 n g) :
times_cont_diff 𝕜 n (λx, f x + g x) :=
times_cont_diff_add.comp (hf.prod hg)
/-- The sum of two `C^n` functions on a domain is `C^n`. -/
lemma times_cont_diff_on.add {n : with_top ℕ} {s : set E} {f g : E → F}
(hf : times_cont_diff_on 𝕜 n f s) (hg : times_cont_diff_on 𝕜 n g s) :
times_cont_diff_on 𝕜 n (λx, f x + g x) s :=
λ x hx, (hf x hx).add (hg x hx)
/-! ### Negative -/
/- The negative is smooth. -/
lemma times_cont_diff_neg {n : with_top ℕ} :
times_cont_diff 𝕜 n (λp : F, -p) :=
is_bounded_linear_map.id.neg.times_cont_diff
/-- The negative of a `C^n` function within a domain at a point is `C^n` within this domain at
this point. -/
lemma times_cont_diff_within_at.neg {n : with_top ℕ} {s : set E} {f : E → F}
(hf : times_cont_diff_within_at 𝕜 n f s x) : times_cont_diff_within_at 𝕜 n (λx, -f x) s x :=
times_cont_diff_neg.times_cont_diff_within_at.comp x hf subset_preimage_univ
/-- The negative of a `C^n` function at a point is `C^n` at this point. -/
lemma times_cont_diff_at.neg {n : with_top ℕ} {f : E → F}
(hf : times_cont_diff_at 𝕜 n f x) : times_cont_diff_at 𝕜 n (λx, -f x) x :=
by rw ← times_cont_diff_within_at_univ at *; exact hf.neg
/-- The negative of a `C^n`function is `C^n`. -/
lemma times_cont_diff.neg {n : with_top ℕ} {f : E → F} (hf : times_cont_diff 𝕜 n f) :
times_cont_diff 𝕜 n (λx, -f x) :=
times_cont_diff_neg.comp hf
/-- The negative of a `C^n` function on a domain is `C^n`. -/
lemma times_cont_diff_on.neg {n : with_top ℕ} {s : set E} {f : E → F}
(hf : times_cont_diff_on 𝕜 n f s) : times_cont_diff_on 𝕜 n (λx, -f x) s :=
λ x hx, (hf x hx).neg
/-! ### Subtraction -/
/-- The difference of two `C^n` functions within a set at a point is `C^n` within this set
at this point. -/
lemma times_cont_diff_within_at.sub {n : with_top ℕ} {s : set E} {f g : E → F}
(hf : times_cont_diff_within_at 𝕜 n f s x) (hg : times_cont_diff_within_at 𝕜 n g s x) :
times_cont_diff_within_at 𝕜 n (λx, f x - g x) s x :=
hf.add hg.neg
/-- The difference of two `C^n` functions at a point is `C^n` at this point. -/
lemma times_cont_diff_at.sub {n : with_top ℕ} {f g : E → F}
(hf : times_cont_diff_at 𝕜 n f x) (hg : times_cont_diff_at 𝕜 n g x) :
times_cont_diff_at 𝕜 n (λx, f x - g x) x :=
hf.add hg.neg
/-- The difference of two `C^n` functions on a domain is `C^n`. -/
lemma times_cont_diff_on.sub {n : with_top ℕ} {s : set E} {f g : E → F}
(hf : times_cont_diff_on 𝕜 n f s) (hg : times_cont_diff_on 𝕜 n g s) :
times_cont_diff_on 𝕜 n (λx, f x - g x) s :=
hf.add hg.neg
/-- The difference of two `C^n` functions is `C^n`. -/
lemma times_cont_diff.sub {n : with_top ℕ} {f g : E → F}
(hf : times_cont_diff 𝕜 n f) (hg : times_cont_diff 𝕜 n g) : times_cont_diff 𝕜 n (λx, f x - g x) :=
hf.add hg.neg
/-! ### Sum of finitely many functions -/
lemma times_cont_diff_within_at.sum
{ι : Type*} {f : ι → E → F} {s : finset ι} {n : with_top ℕ} {t : set E} {x : E}
(h : ∀ i ∈ s, times_cont_diff_within_at 𝕜 n (λ x, f i x) t x) :
times_cont_diff_within_at 𝕜 n (λ x, (∑ i in s, f i x)) t x :=
begin
classical,
induction s using finset.induction_on with i s is IH,
{ simp [times_cont_diff_within_at_const] },
{ simp only [is, finset.sum_insert, not_false_iff],
exact (h _ (finset.mem_insert_self i s)).add (IH (λ j hj, h _ (finset.mem_insert_of_mem hj))) }
end
lemma times_cont_diff_at.sum
{ι : Type*} {f : ι → E → F} {s : finset ι} {n : with_top ℕ} {x : E}
(h : ∀ i ∈ s, times_cont_diff_at 𝕜 n (λ x, f i x) x) :
times_cont_diff_at 𝕜 n (λ x, (∑ i in s, f i x)) x :=
by rw [← times_cont_diff_within_at_univ] at *; exact times_cont_diff_within_at.sum h
lemma times_cont_diff_on.sum
{ι : Type*} {f : ι → E → F} {s : finset ι} {n : with_top ℕ} {t : set E}
(h : ∀ i ∈ s, times_cont_diff_on 𝕜 n (λ x, f i x) t) :
times_cont_diff_on 𝕜 n (λ x, (∑ i in s, f i x)) t :=
λ x hx, times_cont_diff_within_at.sum (λ i hi, h i hi x hx)
lemma times_cont_diff.sum
{ι : Type*} {f : ι → E → F} {s : finset ι} {n : with_top ℕ}
(h : ∀ i ∈ s, times_cont_diff 𝕜 n (λ x, f i x)) :
times_cont_diff 𝕜 n (λ x, (∑ i in s, f i x)) :=
by simp [← times_cont_diff_on_univ] at *; exact times_cont_diff_on.sum h
/-! ### Product of two functions -/
/- The product is smooth. -/
lemma times_cont_diff_mul {n : with_top ℕ} :
times_cont_diff 𝕜 n (λ p : 𝕜 × 𝕜, p.1 * p.2) :=
is_bounded_bilinear_map_mul.times_cont_diff
/-- The product of two `C^n` functions within a set at a point is `C^n` within this set
at this point. -/
lemma times_cont_diff_within_at.mul {n : with_top ℕ} {s : set E} {f g : E → 𝕜}
(hf : times_cont_diff_within_at 𝕜 n f s x) (hg : times_cont_diff_within_at 𝕜 n g s x) :
times_cont_diff_within_at 𝕜 n (λ x, f x * g x) s x :=
times_cont_diff_mul.times_cont_diff_within_at.comp x (hf.prod hg) subset_preimage_univ
/-- The product of two `C^n` functions at a point is `C^n` at this point. -/
lemma times_cont_diff_at.mul {n : with_top ℕ} {f g : E → 𝕜}
(hf : times_cont_diff_at 𝕜 n f x) (hg : times_cont_diff_at 𝕜 n g x) :
times_cont_diff_at 𝕜 n (λ x, f x * g x) x :=
by rw [← times_cont_diff_within_at_univ] at *; exact hf.mul hg
/-- The product of two `C^n` functions on a domain is `C^n`. -/
lemma times_cont_diff_on.mul {n : with_top ℕ} {s : set E} {f g : E → 𝕜}
(hf : times_cont_diff_on 𝕜 n f s) (hg : times_cont_diff_on 𝕜 n g s) :
times_cont_diff_on 𝕜 n (λ x, f x * g x) s :=
λ x hx, (hf x hx).mul (hg x hx)
/-- The product of two `C^n`functions is `C^n`. -/
lemma times_cont_diff.mul {n : with_top ℕ} {f g : E → 𝕜}
(hf : times_cont_diff 𝕜 n f) (hg : times_cont_diff 𝕜 n g) :
times_cont_diff 𝕜 n (λ x, f x * g x) :=
times_cont_diff_mul.comp (hf.prod hg)
lemma times_cont_diff_within_at.div_const {f : E → 𝕜} {n} {c : 𝕜}
(hf : times_cont_diff_within_at 𝕜 n f s x) :
times_cont_diff_within_at 𝕜 n (λ x, f x / c) s x :=
hf.mul times_cont_diff_within_at_const
lemma times_cont_diff_at.div_const {f : E → 𝕜} {n} {c : 𝕜} (hf : times_cont_diff_at 𝕜 n f x) :
times_cont_diff_at 𝕜 n (λ x, f x / c) x :=
hf.mul times_cont_diff_at_const
lemma times_cont_diff_on.div_const {f : E → 𝕜} {n} {c : 𝕜} (hf : times_cont_diff_on 𝕜 n f s) :
times_cont_diff_on 𝕜 n (λ x, f x / c) s :=
hf.mul times_cont_diff_on_const
lemma times_cont_diff.div_const {f : E → 𝕜} {n} {c : 𝕜} (hf : times_cont_diff 𝕜 n f) :
times_cont_diff 𝕜 n (λ x, f x / c) :=
hf.mul times_cont_diff_const
lemma times_cont_diff.pow {n : with_top ℕ} {f : E → 𝕜}
(hf : times_cont_diff 𝕜 n f) :
∀ m : ℕ, times_cont_diff 𝕜 n (λ x, (f x) ^ m)
| 0 := by simpa using times_cont_diff_const
| (m + 1) := hf.mul (times_cont_diff.pow m)
/-! ### Scalar multiplication -/
/- The scalar multiplication is smooth. -/
lemma times_cont_diff_smul {n : with_top ℕ} :
times_cont_diff 𝕜 n (λ p : 𝕜 × F, p.1 • p.2) :=
is_bounded_bilinear_map_smul.times_cont_diff
/-- The scalar multiplication of two `C^n` functions within a set at a point is `C^n` within this
set at this point. -/
lemma times_cont_diff_within_at.smul {n : with_top ℕ} {s : set E} {f : E → 𝕜} {g : E → F}
(hf : times_cont_diff_within_at 𝕜 n f s x) (hg : times_cont_diff_within_at 𝕜 n g s x) :
times_cont_diff_within_at 𝕜 n (λ x, f x • g x) s x :=
times_cont_diff_smul.times_cont_diff_within_at.comp x (hf.prod hg) subset_preimage_univ
/-- The scalar multiplication of two `C^n` functions at a point is `C^n` at this point. -/
lemma times_cont_diff_at.smul {n : with_top ℕ} {f : E → 𝕜} {g : E → F}
(hf : times_cont_diff_at 𝕜 n f x) (hg : times_cont_diff_at 𝕜 n g x) :
times_cont_diff_at 𝕜 n (λ x, f x • g x) x :=
by rw [← times_cont_diff_within_at_univ] at *; exact hf.smul hg
/-- The scalar multiplication of two `C^n` functions is `C^n`. -/
lemma times_cont_diff.smul {n : with_top ℕ} {f : E → 𝕜} {g : E → F}
(hf : times_cont_diff 𝕜 n f) (hg : times_cont_diff 𝕜 n g) :
times_cont_diff 𝕜 n (λ x, f x • g x) :=
times_cont_diff_smul.comp (hf.prod hg)
/-- The scalar multiplication of two `C^n` functions on a domain is `C^n`. -/
lemma times_cont_diff_on.smul {n : with_top ℕ} {s : set E} {f : E → 𝕜} {g : E → F}
(hf : times_cont_diff_on 𝕜 n f s) (hg : times_cont_diff_on 𝕜 n g s) :
times_cont_diff_on 𝕜 n (λ x, f x • g x) s :=
λ x hx, (hf x hx).smul (hg x hx)
/-! ### Cartesian product of two functions-/
section prod_map
variables {E' : Type*} [normed_group E'] [normed_space 𝕜 E']
{F' : Type*} [normed_group F'] [normed_space 𝕜 F']
{n : with_top ℕ}
/-- The product map of two `C^n` functions within a set at a point is `C^n`
within the product set at the product point. -/
lemma times_cont_diff_within_at.prod_map'
{s : set E} {t : set E'} {f : E → F} {g : E' → F'} {p : E × E'}
(hf : times_cont_diff_within_at 𝕜 n f s p.1) (hg : times_cont_diff_within_at 𝕜 n g t p.2) :
times_cont_diff_within_at 𝕜 n (prod.map f g) (set.prod s t) p :=
(hf.comp p times_cont_diff_within_at_fst (prod_subset_preimage_fst _ _)).prod
(hg.comp p times_cont_diff_within_at_snd (prod_subset_preimage_snd _ _))
lemma times_cont_diff_within_at.prod_map
{s : set E} {t : set E'} {f : E → F} {g : E' → F'} {x : E} {y : E'}
(hf : times_cont_diff_within_at 𝕜 n f s x) (hg : times_cont_diff_within_at 𝕜 n g t y) :
times_cont_diff_within_at 𝕜 n (prod.map f g) (set.prod s t) (x, y) :=
times_cont_diff_within_at.prod_map' hf hg
/-- The product map of two `C^n` functions on a set is `C^n` on the product set. -/
lemma times_cont_diff_on.prod_map {E' : Type*} [normed_group E'] [normed_space 𝕜 E']
{F' : Type*} [normed_group F'] [normed_space 𝕜 F']
{s : set E} {t : set E'} {n : with_top ℕ} {f : E → F} {g : E' → F'}
(hf : times_cont_diff_on 𝕜 n f s) (hg : times_cont_diff_on 𝕜 n g t) :
times_cont_diff_on 𝕜 n (prod.map f g) (set.prod s t) :=
(hf.comp times_cont_diff_on_fst (prod_subset_preimage_fst _ _)).prod
(hg.comp (times_cont_diff_on_snd) (prod_subset_preimage_snd _ _))
/-- The product map of two `C^n` functions within a set at a point is `C^n`
within the product set at the product point. -/
lemma times_cont_diff_at.prod_map {f : E → F} {g : E' → F'} {x : E} {y : E'}
(hf : times_cont_diff_at 𝕜 n f x) (hg : times_cont_diff_at 𝕜 n g y) :
times_cont_diff_at 𝕜 n (prod.map f g) (x, y) :=
begin
rw times_cont_diff_at at *,
convert hf.prod_map hg,
simp only [univ_prod_univ]
end
/-- The product map of two `C^n` functions within a set at a point is `C^n`
within the product set at the product point. -/
lemma times_cont_diff_at.prod_map' {f : E → F} {g : E' → F'} {p : E × E'}
(hf : times_cont_diff_at 𝕜 n f p.1) (hg : times_cont_diff_at 𝕜 n g p.2) :
times_cont_diff_at 𝕜 n (prod.map f g) p :=
begin
rcases p,
exact times_cont_diff_at.prod_map hf hg
end
/-- The product map of two `C^n` functions is `C^n`. -/
lemma times_cont_diff.prod_map
{f : E → F} {g : E' → F'}
(hf : times_cont_diff 𝕜 n f) (hg : times_cont_diff 𝕜 n g) :
times_cont_diff 𝕜 n (prod.map f g) :=
begin
rw times_cont_diff_iff_times_cont_diff_at at *,
exact λ ⟨x, y⟩, (hf x).prod_map (hg y)
end
end prod_map
/-! ### Inversion in a complete normed algebra -/
section algebra_inverse
variables (𝕜) {R : Type*} [normed_ring R] [normed_algebra 𝕜 R]
open normed_ring continuous_linear_map ring
/-- In a complete normed algebra, the operation of inversion is `C^n`, for all `n`, at each
invertible element. The proof is by induction, bootstrapping using an identity expressing the
derivative of inversion as a bilinear map of inversion itself. -/
lemma times_cont_diff_at_ring_inverse [complete_space R] {n : with_top ℕ} (x : units R) :
times_cont_diff_at 𝕜 n ring.inverse (x : R) :=
begin
induction n using with_top.nat_induction with n IH Itop,
{ intros m hm,
refine ⟨{y : R | is_unit y}, _, _⟩,
{ simp [nhds_within_univ],
exact x.nhds },
{ use (ftaylor_series_within 𝕜 inverse univ),
rw [le_antisymm hm bot_le, has_ftaylor_series_up_to_on_zero_iff],
split,
{ rintros _ ⟨x', hx'⟩,
rw ← hx',
exact (inverse_continuous_at x').continuous_within_at },
{ simp [ftaylor_series_within] } } },
{ apply times_cont_diff_at_succ_iff_has_fderiv_at.mpr,
refine ⟨λ (x : R), - lmul_left_right 𝕜 R (inverse x, inverse x), _, _⟩,
{ refine ⟨{y : R | is_unit y}, x.nhds, _⟩,
intros y hy,
cases mem_set_of_eq.mp hy with y' hy',
rw [← hy', inverse_unit],
exact @has_fderiv_at_ring_inverse 𝕜 _ _ _ _ _ y' },
{ exact (lmul_left_right_is_bounded_bilinear 𝕜 R).times_cont_diff.neg.comp_times_cont_diff_at
(x : R) (IH.prod IH) } },
{ exact times_cont_diff_at_top.mpr Itop }
end
variables (𝕜) {𝕜' : Type*} [normed_field 𝕜'] [normed_algebra 𝕜 𝕜'] [complete_space 𝕜']
lemma times_cont_diff_at_inv {x : 𝕜'} (hx : x ≠ 0) {n} :
times_cont_diff_at 𝕜 n has_inv.inv x :=
by simpa only [inverse_eq_has_inv] using times_cont_diff_at_ring_inverse 𝕜 (units.mk0 x hx)
variable {𝕜}
-- TODO: the next few lemmas don't need `𝕜` or `𝕜'` to be complete
-- A good way to show this is to generalize `times_cont_diff_at_ring_inverse` to the setting
-- of a function `f` such that `∀ᶠ x in 𝓝 a, x * f x = 1`.
lemma times_cont_diff_within_at.inv {f : E → 𝕜'} {n} (hf : times_cont_diff_within_at 𝕜 n f s x)
(hx : f x ≠ 0) :
times_cont_diff_within_at 𝕜 n (λ x, (f x)⁻¹) s x :=
(times_cont_diff_at_inv 𝕜 hx).comp_times_cont_diff_within_at x hf
lemma times_cont_diff_at.inv {f : E → 𝕜'} {n} (hf : times_cont_diff_at 𝕜 n f x) (hx : f x ≠ 0) :
times_cont_diff_at 𝕜 n (λ x, (f x)⁻¹) x :=
hf.inv hx
-- TODO: generalize to `f g : E → 𝕜'`
lemma times_cont_diff_within_at.div [complete_space 𝕜] {f g : E → 𝕜} {n}
(hf : times_cont_diff_within_at 𝕜 n f s x) (hg : times_cont_diff_within_at 𝕜 n g s x)
(hx : g x ≠ 0) :
times_cont_diff_within_at 𝕜 n (λ x, f x / g x) s x :=
hf.mul (hg.inv hx)
lemma times_cont_diff_at.div [complete_space 𝕜] {f g : E → 𝕜} {n}
(hf : times_cont_diff_at 𝕜 n f x) (hg : times_cont_diff_at 𝕜 n g x)
(hx : g x ≠ 0) :
times_cont_diff_at 𝕜 n (λ x, f x / g x) x :=
hf.div hg hx
lemma times_cont_diff.div [complete_space 𝕜] {f g : E → 𝕜} {n}
(hf : times_cont_diff 𝕜 n f) (hg : times_cont_diff 𝕜 n g)
(h0 : ∀ x, g x ≠ 0) :
times_cont_diff 𝕜 n (λ x, f x / g x) :=
begin
simp only [times_cont_diff_iff_times_cont_diff_at] at *,
exact λ x, (hf x).div (hg x) (h0 x)
end
end algebra_inverse
/-! ### Inversion of continuous linear maps between Banach spaces -/
section map_inverse
open continuous_linear_map
/-- At a continuous linear equivalence `e : E ≃L[𝕜] F` between Banach spaces, the operation of
inversion is `C^n`, for all `n`. -/
lemma times_cont_diff_at_map_inverse [complete_space E] {n : with_top ℕ} (e : E ≃L[𝕜] F) :
times_cont_diff_at 𝕜 n inverse (e : E →L[𝕜] F) :=
begin
nontriviality E,
-- first, we use the lemma `to_ring_inverse` to rewrite in terms of `ring.inverse` in the ring
-- `E →L[𝕜] E`
let O₁ : (E →L[𝕜] E) → (F →L[𝕜] E) := λ f, f.comp (e.symm : (F →L[𝕜] E)),
let O₂ : (E →L[𝕜] F) → (E →L[𝕜] E) := λ f, (e.symm : (F →L[𝕜] E)).comp f,
have : continuous_linear_map.inverse = O₁ ∘ ring.inverse ∘ O₂ :=
funext (to_ring_inverse e),
rw this,
-- `O₁` and `O₂` are `times_cont_diff`, so we reduce to proving that `ring.inverse` is `times_cont_diff`
have h₁ : times_cont_diff 𝕜 n O₁,
from is_bounded_bilinear_map_comp.times_cont_diff.comp
(times_cont_diff_const.prod times_cont_diff_id),
have h₂ : times_cont_diff 𝕜 n O₂,
from is_bounded_bilinear_map_comp.times_cont_diff.comp
(times_cont_diff_id.prod times_cont_diff_const),
refine h₁.times_cont_diff_at.comp _ (times_cont_diff_at.comp _ _ h₂.times_cont_diff_at),
convert times_cont_diff_at_ring_inverse 𝕜 (1 : units (E →L[𝕜] E)),
simp [O₂, one_def]
end
end map_inverse
section function_inverse
open continuous_linear_map
/-- If `f` is a local homeomorphism and the point `a` is in its target, and if `f` is `n` times
continuously differentiable at `f.symm a`, and if the derivative at `f.symm a` is a continuous linear
equivalence, then `f.symm` is `n` times continuously differentiable at the point `a`.
This is one of the easy parts of the inverse function theorem: it assumes that we already have
an inverse function. -/
theorem times_cont_diff_at.of_local_homeomorph [complete_space E] {n : with_top ℕ}
{f : local_homeomorph E F} {f₀' : E ≃L[𝕜] F} {a : F} (ha : a ∈ f.target)
(hf₀' : has_fderiv_at f (f₀' : E →L[𝕜] F) (f.symm a)) (hf : times_cont_diff_at 𝕜 n f (f.symm a)) :
times_cont_diff_at 𝕜 n f.symm a :=
begin
-- We prove this by induction on `n`
induction n using with_top.nat_induction with n IH Itop,
{ rw times_cont_diff_at_zero,
exact ⟨f.target, mem_nhds_sets f.open_target ha, f.continuous_inv_fun⟩ },
{ obtain ⟨f', ⟨u, hu, hff'⟩, hf'⟩ := times_cont_diff_at_succ_iff_has_fderiv_at.mp hf,
apply times_cont_diff_at_succ_iff_has_fderiv_at.mpr,
-- For showing `n.succ` times continuous differentiability (the main inductive step), it
-- suffices to produce the derivative and show that it is `n` times continuously differentiable
have eq_f₀' : f' (f.symm a) = f₀',
{ exact has_fderiv_at_unique (hff' (f.symm a) (mem_of_nhds hu)) hf₀' },
-- This follows by a bootstrapping formula expressing the derivative as a function of `f` itself
refine ⟨inverse ∘ f' ∘ f.symm, _, _⟩,
{ -- We first check that the derivative of `f` is that formula
have h_nhds : {y : E | ∃ (e : E ≃L[𝕜] F), ↑e = f' y} ∈ 𝓝 ((f.symm) a),
{ have hf₀' := f₀'.nhds,
rw ← eq_f₀' at hf₀',
exact hf'.continuous_at.preimage_mem_nhds hf₀' },
obtain ⟨t, htu, ht, htf⟩ := mem_nhds_sets_iff.mp (filter.inter_mem_sets hu h_nhds),
use f.target ∩ (f.symm) ⁻¹' t,
refine ⟨mem_nhds_sets _ _, _⟩,
{ exact f.preimage_open_of_open_symm ht },
{ exact mem_inter ha (mem_preimage.mpr htf) },
intros x hx,
obtain ⟨hxu, e, he⟩ := htu hx.2,
have h_deriv : has_fderiv_at f ↑e ((f.symm) x),
{ rw he,
exact hff' (f.symm x) hxu },
convert h_deriv.of_local_homeomorph hx.1,
simp [← he] },
{ -- Then we check that the formula, being a composition of `times_cont_diff` pieces, is
-- itself `times_cont_diff`
have h_deriv₁ : times_cont_diff_at 𝕜 n inverse (f' (f.symm a)),
{ rw eq_f₀',
exact times_cont_diff_at_map_inverse _ },
have h_deriv₂ : times_cont_diff_at 𝕜 n f.symm a,
{ refine IH (hf.of_le _),
norm_cast,
exact nat.le_succ n },
exact (h_deriv₁.comp _ hf').comp _ h_deriv₂ } },
{ refine times_cont_diff_at_top.mpr _,
intros n,
exact Itop n (times_cont_diff_at_top.mp hf n) }
end
end function_inverse
section real
/-!
### Results over `ℝ`
The results in this section rely on the Mean Value Theorem, and therefore hold only over `ℝ` (and
its extension fields such as `ℂ`).
-/
variables
{E' : Type*} [normed_group E'] [normed_space ℝ E']
{F' : Type*} [normed_group F'] [normed_space ℝ F']
/-- If a function has a Taylor series at order at least 1, then at points in the interior of the
domain of definition, the term of order 1 of this series is a strict derivative of `f`. -/
lemma has_ftaylor_series_up_to_on.has_strict_fderiv_at
{s : set E'} {f : E' → F'} {x : E'} {p : E' → formal_multilinear_series ℝ E' F'} {n : with_top ℕ}
(hf : has_ftaylor_series_up_to_on n f p s) (hn : 1 ≤ n) (hs : s ∈ 𝓝 x) :
has_strict_fderiv_at f ((continuous_multilinear_curry_fin1 ℝ E' F') (p x 1)) x :=
begin
let f' := λ x, (continuous_multilinear_curry_fin1 ℝ E' F') (p x 1),
have hf' : ∀ x, x ∈ s → has_fderiv_within_at f (f' x) s x :=
λ x, has_ftaylor_series_up_to_on.has_fderiv_within_at hf hn,
have hcont : continuous_on f' s :=
(continuous_multilinear_curry_fin1 ℝ E' F').continuous.comp_continuous_on (hf.cont 1 hn),
exact strict_fderiv_of_cont_diff hf' hcont hs,
end
/-- If a function is `C^n` with `1 ≤ n` around a point, then the derivative of `f` at this point
is also a strict derivative. -/
lemma times_cont_diff_at.has_strict_fderiv_at {f : E' → F'} {x : E'} {n : with_top ℕ}
(hf : times_cont_diff_at ℝ n f x) (hn : 1 ≤ n) :
has_strict_fderiv_at f (fderiv ℝ f x) x :=
begin
rcases hf 1 hn with ⟨u, H, p, hp⟩,
simp only [nhds_within_univ, mem_univ, insert_eq_of_mem] at H,
have := hp.has_strict_fderiv_at (by norm_num) H,
convert this,
exact this.has_fderiv_at.fderiv
end
/-- If a function is `C^n` with `1 ≤ n` around a point, and its derivative at that point is given to
us as `f'`, then `f'` is also a strict derivative. -/
lemma times_cont_diff_at.has_strict_fderiv_at'
{f : E' → F'} {f' : E' →L[ℝ] F'} {x : E'}
{n : with_top ℕ} (hf : times_cont_diff_at ℝ n f x) (hf' : has_fderiv_at f f' x) (hn : 1 ≤ n) :
has_strict_fderiv_at f f' x :=
by simpa only [hf'.fderiv] using hf.has_strict_fderiv_at hn
/-- If a function is `C^n` with `1 ≤ n`, then the derivative of `f` is also a strict derivative. -/
lemma times_cont_diff.has_strict_fderiv_at
{f : E' → F'} {x : E'} {n : with_top ℕ} (hf : times_cont_diff ℝ n f) (hn : 1 ≤ n) :
has_strict_fderiv_at f (fderiv ℝ f x) x :=
hf.times_cont_diff_at.has_strict_fderiv_at hn
end real
section deriv
/-!
### One dimension
All results up to now have been expressed in terms of the general Fréchet derivative `fderiv`. For
maps defined on the field, the one-dimensional derivative `deriv` is often easier to use. In this
paragraph, we reformulate some higher smoothness results in terms of `deriv`.
-/
variables {f₂ : 𝕜 → F} {s₂ : set 𝕜}
open continuous_linear_map (smul_right)
/-- A function is `C^(n + 1)` on a domain with unique derivatives if and only if it is
differentiable there, and its derivative (formulated with `deriv_within`) is `C^n`. -/
theorem times_cont_diff_on_succ_iff_deriv_within {n : ℕ} (hs : unique_diff_on 𝕜 s₂) :
times_cont_diff_on 𝕜 ((n + 1) : ℕ) f₂ s₂ ↔
differentiable_on 𝕜 f₂ s₂ ∧ times_cont_diff_on 𝕜 n (deriv_within f₂ s₂) s₂ :=
begin
rw times_cont_diff_on_succ_iff_fderiv_within hs,
congr' 2,
rw ← iff_iff_eq,
split,
{ assume h,
have : deriv_within f₂ s₂ = (λ u : 𝕜 →L[𝕜] F, u 1) ∘ (fderiv_within 𝕜 f₂ s₂),
by { ext x, refl },
simp only [this],
apply times_cont_diff.comp_times_cont_diff_on _ h,
exact (is_bounded_bilinear_map_apply.is_bounded_linear_map_left _).times_cont_diff },
{ assume h,
have : fderiv_within 𝕜 f₂ s₂ = (λ u, smul_right 1 u) ∘ (λ x, deriv_within f₂ s₂ x),
by { ext x, simp [deriv_within] },
simp only [this],
apply times_cont_diff.comp_times_cont_diff_on _ h,
exact (is_bounded_bilinear_map_smul_right.is_bounded_linear_map_right _).times_cont_diff }
end
/-- A function is `C^(n + 1)` on an open domain if and only if it is
differentiable there, and its derivative (formulated with `deriv`) is `C^n`. -/
theorem times_cont_diff_on_succ_iff_deriv_of_open {n : ℕ} (hs : is_open s₂) :
times_cont_diff_on 𝕜 ((n + 1) : ℕ) f₂ s₂ ↔
differentiable_on 𝕜 f₂ s₂ ∧ times_cont_diff_on 𝕜 n (deriv f₂) s₂ :=
begin
rw times_cont_diff_on_succ_iff_deriv_within hs.unique_diff_on,
congr' 2,
rw ← iff_iff_eq,
apply times_cont_diff_on_congr,
assume x hx,
exact deriv_within_of_open hs hx
end
/-- A function is `C^∞` on a domain with unique derivatives if and only if it is differentiable
there, and its derivative (formulated with `deriv_within`) is `C^∞`. -/
theorem times_cont_diff_on_top_iff_deriv_within (hs : unique_diff_on 𝕜 s₂) :
times_cont_diff_on 𝕜 ∞ f₂ s₂ ↔
differentiable_on 𝕜 f₂ s₂ ∧ times_cont_diff_on 𝕜 ∞ (deriv_within f₂ s₂) s₂ :=
begin
split,
{ assume h,
refine ⟨h.differentiable_on le_top, _⟩,
apply times_cont_diff_on_top.2 (λ n, ((times_cont_diff_on_succ_iff_deriv_within hs).1 _).2),
exact h.of_le le_top },
{ assume h,
refine times_cont_diff_on_top.2 (λ n, _),
have A : (n : with_top ℕ) ≤ ∞ := le_top,
apply ((times_cont_diff_on_succ_iff_deriv_within hs).2 ⟨h.1, h.2.of_le A⟩).of_le,
exact with_top.coe_le_coe.2 (nat.le_succ n) }
end
/-- A function is `C^∞` on an open domain if and only if it is differentiable
there, and its derivative (formulated with `deriv`) is `C^∞`. -/
theorem times_cont_diff_on_top_iff_deriv_of_open (hs : is_open s₂) :
times_cont_diff_on 𝕜 ∞ f₂ s₂ ↔
differentiable_on 𝕜 f₂ s₂ ∧ times_cont_diff_on 𝕜 ∞ (deriv f₂) s₂ :=
begin
rw times_cont_diff_on_top_iff_deriv_within hs.unique_diff_on,
congr' 2,
rw ← iff_iff_eq,
apply times_cont_diff_on_congr,
assume x hx,
exact deriv_within_of_open hs hx
end
lemma times_cont_diff_on.deriv_within {m n : with_top ℕ}
(hf : times_cont_diff_on 𝕜 n f₂ s₂) (hs : unique_diff_on 𝕜 s₂) (hmn : m + 1 ≤ n) :
times_cont_diff_on 𝕜 m (deriv_within f₂ s₂) s₂ :=
begin
cases m,
{ change ∞ + 1 ≤ n at hmn,
have : n = ∞, by simpa using hmn,
rw this at hf,
exact ((times_cont_diff_on_top_iff_deriv_within hs).1 hf).2 },
{ change (m.succ : with_top ℕ) ≤ n at hmn,
exact ((times_cont_diff_on_succ_iff_deriv_within hs).1 (hf.of_le hmn)).2 }
end
lemma times_cont_diff_on.deriv_of_open {m n : with_top ℕ}
(hf : times_cont_diff_on 𝕜 n f₂ s₂) (hs : is_open s₂) (hmn : m + 1 ≤ n) :
times_cont_diff_on 𝕜 m (deriv f₂) s₂ :=
(hf.deriv_within hs.unique_diff_on hmn).congr (λ x hx, (deriv_within_of_open hs hx).symm)
lemma times_cont_diff_on.continuous_on_deriv_within {n : with_top ℕ}
(h : times_cont_diff_on 𝕜 n f₂ s₂) (hs : unique_diff_on 𝕜 s₂) (hn : 1 ≤ n) :
continuous_on (deriv_within f₂ s₂) s₂ :=
((times_cont_diff_on_succ_iff_deriv_within hs).1 (h.of_le hn)).2.continuous_on
lemma times_cont_diff_on.continuous_on_deriv_of_open {n : with_top ℕ}
(h : times_cont_diff_on 𝕜 n f₂ s₂) (hs : is_open s₂) (hn : 1 ≤ n) :
continuous_on (deriv f₂) s₂ :=
((times_cont_diff_on_succ_iff_deriv_of_open hs).1 (h.of_le hn)).2.continuous_on
/-- A function is `C^(n + 1)` on a domain with unique derivatives if and only if it is
differentiable there, and its derivative is `C^n`. -/
theorem times_cont_diff_succ_iff_deriv {n : ℕ} :
times_cont_diff 𝕜 ((n + 1) : ℕ) f₂ ↔
differentiable 𝕜 f₂ ∧ times_cont_diff 𝕜 n (deriv f₂) :=
by simp only [← times_cont_diff_on_univ, times_cont_diff_on_succ_iff_deriv_of_open, is_open_univ,
differentiable_on_univ]
end deriv
section restrict_scalars
/-!
### Restricting from `ℂ` to `ℝ`, or generally from `𝕜'` to `𝕜`
If a function is `n` times continuously differentiable over `ℂ`, then it is `n` times continuously
differentiable over `ℝ`. In this paragraph, we give variants of this statement, in the general
situation where `ℂ` and `ℝ` are replaced respectively by `𝕜'` and `𝕜` where `𝕜'` is a normed algebra
over `𝕜`.
-/
variables (𝕜) {𝕜' : Type*} [nondiscrete_normed_field 𝕜'] [normed_algebra 𝕜 𝕜']
variables [normed_space 𝕜' E] [is_scalar_tower 𝕜 𝕜' E]
variables [normed_space 𝕜' F] [is_scalar_tower 𝕜 𝕜' F]
variables {p' : E → formal_multilinear_series 𝕜' E F} {n : with_top ℕ}
/-- Reinterpret a formal `𝕜'`-multilinear series as a formal `𝕜`-multilinear series, where `𝕜'` is a
normed algebra over `𝕜`. -/
@[simp] def formal_multilinear_series.restrict_scalars (p : formal_multilinear_series 𝕜' E F) :
formal_multilinear_series 𝕜 E F :=
λ n, (p n).restrict_scalars 𝕜
lemma has_ftaylor_series_up_to_on.restrict_scalars
(h : has_ftaylor_series_up_to_on n f p' s) :
has_ftaylor_series_up_to_on n f (λ x, (p' x).restrict_scalars 𝕜) s :=
{ zero_eq := λ x hx, h.zero_eq x hx,
fderiv_within :=
begin
intros m hm x hx,
convert ((continuous_multilinear_map.restrict_scalars_linear 𝕜).has_fderiv_at)
.comp_has_fderiv_within_at _ ((h.fderiv_within m hm x hx).restrict_scalars 𝕜),
end,
cont := λ m hm, continuous_multilinear_map.continuous_restrict_scalars.comp_continuous_on
(h.cont m hm) }
lemma times_cont_diff_within_at.restrict_scalars (h : times_cont_diff_within_at 𝕜' n f s x) :
times_cont_diff_within_at 𝕜 n f s x :=
begin
intros m hm,
rcases h m hm with ⟨u, u_mem, p', hp'⟩,
exact ⟨u, u_mem, _, hp'.restrict_scalars _⟩
end
lemma times_cont_diff_on.restrict_scalars (h : times_cont_diff_on 𝕜' n f s) :
times_cont_diff_on 𝕜 n f s :=
λ x hx, (h x hx).restrict_scalars _
lemma times_cont_diff_at.restrict_scalars (h : times_cont_diff_at 𝕜' n f x) :
times_cont_diff_at 𝕜 n f x :=
times_cont_diff_within_at_univ.1 $ h.times_cont_diff_within_at.restrict_scalars _
lemma times_cont_diff.restrict_scalars (h : times_cont_diff 𝕜' n f) :
times_cont_diff 𝕜 n f :=
times_cont_diff_iff_times_cont_diff_at.2 $ λ x, h.times_cont_diff_at.restrict_scalars _
end restrict_scalars
|
bd4e5058d5161093bf26ef333c911a7b45ee46bf | 0f5090f82d527e0df5bf3adac9f9e2e1d81d71e2 | /src/apurva/test.lean | a023135492af7ad8d103c9059fde418a1914fdfc | [] | no_license | apurvanakade/mc2020-lean-projects | 36eb42c4baccc37183635c36f8e1b3afa4ec1230 | 02466225aa629ab1232043bcc0a053a099fdb939 | refs/heads/master | 1,688,791,717,534 | 1,597,874,092,000 | 1,597,874,092,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 410 | lean | import data.fintype.basic
import data.matrix.basic
open_locale matrix
def matrix_extension {k : ℕ} (A : matrix (fin k) (fin k) ℕ) : matrix (fin (k+1)) (fin (k+1)) ℕ
:=
λ i j,
match i, j with
| ⟨0, _⟩, ⟨0, _⟩ := 1
| ⟨0, _⟩, _ := 0
| _, ⟨0, _⟩ := 0
| ⟨x+1, hx⟩, ⟨y+1, hy⟩ := A ⟨x, nat.lt_of_succ_lt_succ hx⟩ ⟨y, nat.lt_of_succ_lt_succ hy⟩
end |
9ec9c7ba51573587d045e08bf442ac78775458fb | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/tactic/rewrite_all/basic.lean | 46c91ffd96cdec50a69232410afe9609f8f76a6b | [
"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,951 | lean | /-
Copyright (c) 2018 Keeley Hoek. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Keeley Hoek, Scott Morrison
-/
import data.mllist
import tactic.core
open tactic
@[derive decidable_eq, derive inhabited]
inductive side
| L
| R
def side.other : side → side
| side.L := side.R
| side.R := side.L
def side.to_string : side → string
| side.L := "L"
| side.R := "R"
instance : has_to_string side := ⟨side.to_string⟩
namespace tactic.rewrite_all
meta structure cfg extends rewrite_cfg :=
(try_simp : bool := ff)
(discharger : tactic unit := skip)
-- Warning: rewrite_search can't produce tactic scripts when the simplifier is used.
(simplifier : expr → tactic (expr × expr) := λ e, failed)
meta structure tracked_rewrite :=
(exp : expr)
(proof : tactic expr)
-- If `addr` is not provided by the underlying implementation of `rewrite_all` (i.e. kabstract)
-- `rewrite_search` will not be able to produce tactic scripts.
(addr : option (list side))
namespace tracked_rewrite
meta def eval (rw : tracked_rewrite) : tactic (expr × expr) :=
do prf ← rw.proof,
return (rw.exp, prf)
meta def replace_target (rw : tracked_rewrite) : tactic unit :=
do (exp, prf) ← rw.eval,
tactic.replace_target exp prf
private meta def replace_target_side (new_target lam : pexpr) (prf : expr) : tactic unit :=
do new_target ← to_expr new_target tt ff,
prf' ← to_expr ``(congr_arg %%lam %%prf) tt ff,
tactic.replace_target new_target prf'
meta def replace_target_lhs (rw : tracked_rewrite) : tactic unit :=
do (new_lhs, prf) ← rw.eval,
`(%%_ = %%rhs) ← target,
replace_target_side ``(%%new_lhs = %%rhs) ``(λ L, L = %%rhs) prf
meta def replace_target_rhs (rw : tracked_rewrite) : tactic unit :=
do (new_rhs, prf) ← rw.eval,
`(%%lhs = %%_) ← target,
replace_target_side ``(%%lhs = %%new_rhs) ``(λ R, %%lhs = R) prf
end tracked_rewrite
end tactic.rewrite_all
|
8dd26a15ed4e7816dfd1590e7bee320c7704330f | a7eef317ddec01b9fc6cfbb876fe7ac00f205ac7 | /src/category_theory/elements.lean | 493834f3250648b85d050fb600501eec48bc8f6b | [
"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 | 4,395 | lean | /-
Copyright (c) 2019 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import category_theory.comma
import category_theory.groupoid
/-!
# The category of elements
This file defines the category of elements, also known as (a special case of) the Grothendieck construction.
Given a functor `F : C ⥤ Type`, an object of `F.elements` is a pair `(X : C, x : F.obj X)`.
A morphism `(X, x) ⟶ (Y, y)` is a morphism `f : X ⟶ Y` in `C`, so `F.map f` takes `x` to `y`.
## Implementation notes
This construction is equivalent to a special case of a comma construction, so this is mostly just
a more convenient API. We prove the equivalence in `category_theory.category_of_elements.comma_equivalence`.
## References
* [Emily Riehl, *Category Theory in Context*, Section 2.4][riehl2017]
* <https://en.wikipedia.org/wiki/Category_of_elements>
* <https://ncatlab.org/nlab/show/category+of+elements>
## Tags
category of elements, Grothendieck construction, comma category
-/
namespace category_theory
universes w v u
variables {C : Type u} [category.{v} C]
/--
The type of objects for the category of elements of a functor `F : C ⥤ Type`
is a pair `(X : C, x : F.obj X)`.
-/
@[nolint has_inhabited_instance]
def functor.elements (F : C ⥤ Type w) := (Σ c : C, F.obj c)
/-- The category structure on `F.elements`, for `F : C ⥤ Type`.
A morphism `(X, x) ⟶ (Y, y)` is a morphism `f : X ⟶ Y` in `C`, so `F.map f` takes `x` to `y`.
-/
instance category_of_elements (F : C ⥤ Type w) : category.{v} F.elements :=
{ hom := λ p q, { f : p.1 ⟶ q.1 // (F.map f) p.2 = q.2 },
id := λ p, ⟨𝟙 p.1, by obviously⟩,
comp := λ p q r f g, ⟨f.val ≫ g.val, by obviously⟩ }
namespace category_of_elements
@[ext]
lemma ext (F : C ⥤ Type w) {x y : F.elements} (f g : x ⟶ y) (w : f.val = g.val) : f = g :=
subtype.ext_val w
@[simp] lemma comp_val {F : C ⥤ Type w} {p q r : F.elements} {f : p ⟶ q} {g : q ⟶ r} :
(f ≫ g).val = f.val ≫ g.val := rfl
@[simp] lemma id_val {F : C ⥤ Type w} {p : F.elements} : (𝟙 p : p ⟶ p).val = 𝟙 p.1 := rfl
end category_of_elements
instance groupoid_of_elements {G : Type u} [groupoid.{v} G] (F : G ⥤ Type w) : groupoid F.elements :=
{ inv := λ p q f, ⟨inv f.val,
calc F.map (inv f.val) q.2 = F.map (inv f.val) (F.map f.val p.2) : by rw f.2
... = (F.map f.val ≫ F.map (inv f.val)) p.2 : by simp
... = p.2 : by {rw ←functor.map_comp, simp}⟩, }
namespace category_of_elements
variable (F : C ⥤ Type w)
/-- The functor out of the category of elements which forgets the element. -/
@[simps]
def π : F.elements ⥤ C :=
{ obj := λ X, X.1,
map := λ X Y f, f.val }
/-- The forward direction of the equivalence `F.elements ≅ (*, F)`. -/
def to_comma : F.elements ⥤ comma (functor.from_punit punit) F :=
{ obj := λ X, { left := punit.star, right := X.1, hom := λ _, X.2 },
map := λ X Y f, { right := f.val } }
@[simp] lemma to_comma_obj (X) :
(to_comma F).obj X = { left := punit.star, right := X.1, hom := λ _, X.2 } := rfl
@[simp] lemma to_comma_map {X Y} (f : X ⟶ Y) :
(to_comma F).map f = { right := f.val } := rfl
/-- The reverse direction of the equivalence `F.elements ≅ (*, F)`. -/
def from_comma : comma (functor.from_punit punit) F ⥤ F.elements :=
{ obj := λ X, ⟨X.right, X.hom (punit.star)⟩,
map := λ X Y f, ⟨f.right, congr_fun f.w'.symm punit.star⟩ }
@[simp] lemma from_comma_obj (X) :
(from_comma F).obj X = ⟨X.right, X.hom (punit.star)⟩ := rfl
@[simp] lemma from_comma_map {X Y} (f : X ⟶ Y) :
(from_comma F).map f = ⟨f.right, congr_fun f.w'.symm punit.star⟩ := rfl
/-- The equivalence between the category of elements `F.elements`
and the comma category `(*, F)`. -/
def comma_equivalence : F.elements ≌ comma (functor.from_punit punit) F :=
equivalence.mk (to_comma F) (from_comma F)
(nat_iso.of_components (λ X, eq_to_iso (by tidy)) (by tidy))
(nat_iso.of_components
(λ X, { hom := { right := 𝟙 _ }, inv := { right := 𝟙 _ } })
(by tidy))
@[simp] lemma comma_equivalence_functor : (comma_equivalence F).functor = to_comma F := rfl
@[simp] lemma comma_equivalence_inverse : (comma_equivalence F).inverse = from_comma F := rfl
end category_of_elements
end category_theory
|
43cd5c8c2791f0769581d93de2d1a66ba5f92356 | f0050a24971f1b7315211eec6e02a8eee618ce6b | /src/common/default.lean | a5b8520fd2a4dc8dee30fbc0557e3375c9a85e13 | [
"Apache-2.0"
] | permissive | ttowncompiled/excaLibur | 9574f2acb0bafcd59f59423b63a62c15442ea5f7 | 7d8371bf998012d4f8c49d3fe2bf540e2517c688 | refs/heads/master | 1,670,710,035,703 | 1,599,670,584,000 | 1,599,670,584,000 | 292,720,923 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 167 | lean | /-
Copyright (c) Ian Riley. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Ian Riley
-/
prelude
import .basic .stmt
|
5e96d6f076b9215509001faab3fe93536eab17a3 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/ring_theory/finite_presentation.lean | 39908602603d6c7de99083a776858506625793cb | [
"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 | 19,539 | lean | /-
Copyright (c) 2020 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin
-/
import ring_theory.finite_type
import ring_theory.mv_polynomial.tower
/-!
# Finiteness conditions in commutative algebra
In this file we define several notions of finiteness that are common in commutative algebra.
## Main declarations
- `module.finite`, `algebra.finite`, `ring_hom.finite`, `alg_hom.finite`
all of these express that some object is finitely generated *as module* over some base ring.
- `algebra.finite_type`, `ring_hom.finite_type`, `alg_hom.finite_type`
all of these express that some object is finitely generated *as algebra* over some base ring.
- `algebra.finite_presentation`, `ring_hom.finite_presentation`, `alg_hom.finite_presentation`
all of these express that some object is finitely presented *as algebra* over some base ring.
-/
open function (surjective)
open_locale big_operators polynomial
section module_and_algebra
variables (R A B M N : Type*)
/-- An algebra over a commutative semiring is `finite_presentation` if it is the quotient of a
polynomial ring in `n` variables by a finitely generated ideal. -/
def algebra.finite_presentation [comm_semiring R] [semiring A] [algebra R A] : Prop :=
∃ (n : ℕ) (f : mv_polynomial (fin n) R →ₐ[R] A),
surjective f ∧ f.to_ring_hom.ker.fg
namespace algebra
variables [comm_ring R] [comm_ring A] [algebra R A] [comm_ring B] [algebra R B]
variables [add_comm_group M] [module R M]
variables [add_comm_group N] [module R N]
namespace finite_type
variables {R A B}
/-- A finitely presented algebra is of finite type. -/
lemma of_finite_presentation : finite_presentation R A → finite_type R A :=
begin
rintro ⟨n, f, hf⟩,
apply (finite_type.iff_quotient_mv_polynomial'').2,
exact ⟨n, f, hf.1⟩
end
end finite_type
namespace finite_presentation
variables {R A B}
/-- An algebra over a Noetherian ring is finitely generated if and only if it is finitely
presented. -/
lemma of_finite_type [is_noetherian_ring R] : finite_type R A ↔ finite_presentation R A :=
begin
refine ⟨λ h, _, algebra.finite_type.of_finite_presentation⟩,
obtain ⟨n, f, hf⟩ := algebra.finite_type.iff_quotient_mv_polynomial''.1 h,
refine ⟨n, f, hf, _⟩,
have hnoet : is_noetherian_ring (mv_polynomial (fin n) R) := by apply_instance,
replace hnoet := (is_noetherian_ring_iff.1 hnoet).noetherian,
exact hnoet f.to_ring_hom.ker,
end
/-- If `e : A ≃ₐ[R] B` and `A` is finitely presented, then so is `B`. -/
lemma equiv (hfp : finite_presentation R A) (e : A ≃ₐ[R] B) : finite_presentation R B :=
begin
obtain ⟨n, f, hf⟩ := hfp,
use [n, alg_hom.comp ↑e f],
split,
{ exact function.surjective.comp e.surjective hf.1 },
suffices hker : (alg_hom.comp ↑e f).to_ring_hom.ker = f.to_ring_hom.ker,
{ rw hker, exact hf.2 },
{ have hco : (alg_hom.comp ↑e f).to_ring_hom = ring_hom.comp ↑e.to_ring_equiv f.to_ring_hom,
{ have h : (alg_hom.comp ↑e f).to_ring_hom = e.to_alg_hom.to_ring_hom.comp f.to_ring_hom := rfl,
have h1 : ↑(e.to_ring_equiv) = (e.to_alg_hom).to_ring_hom := rfl,
rw [h, h1] },
rw [ring_hom.ker_eq_comap_bot, hco, ← ideal.comap_comap, ← ring_hom.ker_eq_comap_bot,
ring_hom.ker_coe_equiv (alg_equiv.to_ring_equiv e), ring_hom.ker_eq_comap_bot] }
end
variable (R)
/-- The ring of polynomials in finitely many variables is finitely presented. -/
protected lemma mv_polynomial (ι : Type u_2) [finite ι] :
finite_presentation R (mv_polynomial ι R) :=
by casesI nonempty_fintype ι; exact
let eqv := (mv_polynomial.rename_equiv R $ fintype.equiv_fin ι).symm in
⟨fintype.card ι, eqv, eqv.surjective,
((ring_hom.injective_iff_ker_eq_bot _).1 eqv.injective).symm ▸ submodule.fg_bot⟩
/-- `R` is finitely presented as `R`-algebra. -/
lemma self : finite_presentation R R :=
equiv (finite_presentation.mv_polynomial R pempty) (mv_polynomial.is_empty_alg_equiv R pempty)
/-- `R[X]` is finitely presented as `R`-algebra. -/
lemma polynomial : finite_presentation R R[X] :=
equiv (finite_presentation.mv_polynomial R punit) (mv_polynomial.punit_alg_equiv R)
variable {R}
/-- The quotient of a finitely presented algebra by a finitely generated ideal is finitely
presented. -/
protected lemma quotient {I : ideal A} (h : I.fg) (hfp : finite_presentation R A) :
finite_presentation R (A ⧸ I) :=
begin
obtain ⟨n, f, hf⟩ := hfp,
refine ⟨n, (ideal.quotient.mkₐ R I).comp f, _, _⟩,
{ exact (ideal.quotient.mkₐ_surjective R I).comp hf.1 },
{ refine ideal.fg_ker_comp _ _ hf.2 _ hf.1,
simp [h] }
end
/-- If `f : A →ₐ[R] B` is surjective with finitely generated kernel and `A` is finitely presented,
then so is `B`. -/
lemma of_surjective {f : A →ₐ[R] B} (hf : function.surjective f) (hker : f.to_ring_hom.ker.fg)
(hfp : finite_presentation R A) : finite_presentation R B :=
equiv (hfp.quotient hker) (ideal.quotient_ker_alg_equiv_of_surjective hf)
lemma iff : finite_presentation R A ↔
∃ n (I : ideal (mv_polynomial (fin n) R)) (e : (_ ⧸ I) ≃ₐ[R] A), I.fg :=
begin
split,
{ rintros ⟨n, f, hf⟩,
exact ⟨n, f.to_ring_hom.ker, ideal.quotient_ker_alg_equiv_of_surjective hf.1, hf.2⟩ },
{ rintros ⟨n, I, e, hfg⟩,
exact equiv ((finite_presentation.mv_polynomial R _).quotient hfg) e }
end
/-- An algebra is finitely presented if and only if it is a quotient of a polynomial ring whose
variables are indexed by a fintype by a finitely generated ideal. -/
lemma iff_quotient_mv_polynomial' : finite_presentation R A ↔ ∃ (ι : Type u_2) (_ : fintype ι)
(f : mv_polynomial ι R →ₐ[R] A), surjective f ∧ f.to_ring_hom.ker.fg :=
begin
split,
{ rintro ⟨n, f, hfs, hfk⟩,
set ulift_var := mv_polynomial.rename_equiv R equiv.ulift,
refine ⟨ulift (fin n), infer_instance, f.comp ulift_var.to_alg_hom,
hfs.comp ulift_var.surjective,
ideal.fg_ker_comp _ _ _ hfk ulift_var.surjective⟩,
convert submodule.fg_bot,
exact ring_hom.ker_coe_equiv ulift_var.to_ring_equiv, },
{ rintro ⟨ι, hfintype, f, hf⟩,
resetI,
have equiv := mv_polynomial.rename_equiv R (fintype.equiv_fin ι),
refine ⟨fintype.card ι, f.comp equiv.symm,
hf.1.comp (alg_equiv.symm equiv).surjective,
ideal.fg_ker_comp _ f _ hf.2 equiv.symm.surjective⟩,
convert submodule.fg_bot,
exact ring_hom.ker_coe_equiv (equiv.symm.to_ring_equiv), }
end
/-- If `A` is a finitely presented `R`-algebra, then `mv_polynomial (fin n) A` is finitely presented
as `R`-algebra. -/
lemma mv_polynomial_of_finite_presentation (hfp : finite_presentation R A) (ι : Type*)
[finite ι] : finite_presentation R (mv_polynomial ι A) :=
begin
rw iff_quotient_mv_polynomial' at hfp ⊢,
classical,
obtain ⟨ι', _, f, hf_surj, hf_ker⟩ := hfp,
resetI,
let g := (mv_polynomial.map_alg_hom f).comp (mv_polynomial.sum_alg_equiv R ι ι').to_alg_hom,
casesI nonempty_fintype (ι ⊕ ι'),
refine ⟨ι ⊕ ι', by apply_instance, g,
(mv_polynomial.map_surjective f.to_ring_hom hf_surj).comp (alg_equiv.surjective _),
ideal.fg_ker_comp _ _ _ _ (alg_equiv.surjective _)⟩,
{ convert submodule.fg_bot,
exact ring_hom.ker_coe_equiv (mv_polynomial.sum_alg_equiv R ι ι').to_ring_equiv },
{ rw [alg_hom.to_ring_hom_eq_coe, mv_polynomial.map_alg_hom_coe_ring_hom, mv_polynomial.ker_map],
exact hf_ker.map mv_polynomial.C, }
end
/-- If `A` is an `R`-algebra and `S` is an `A`-algebra, both finitely presented, then `S` is
finitely presented as `R`-algebra. -/
lemma trans [algebra A B] [is_scalar_tower R A B] (hfpA : finite_presentation R A)
(hfpB : finite_presentation A B) : finite_presentation R B :=
begin
obtain ⟨n, I, e, hfg⟩ := iff.1 hfpB,
exact equiv ((mv_polynomial_of_finite_presentation hfpA _).quotient hfg) (e.restrict_scalars R)
end
open mv_polynomial
-- We follow the proof of https://stacks.math.columbia.edu/tag/0561
-- TODO: extract out helper lemmas and tidy proof.
lemma of_restrict_scalars_finite_presentation [algebra A B] [is_scalar_tower R A B]
(hRB : finite_presentation R B) [hRA : finite_type R A] : finite_presentation A B :=
begin
classical,
obtain ⟨n, f, hf, s, hs⟩ := hRB,
let RX := mv_polynomial (fin n) R, let AX := mv_polynomial (fin n) A,
refine ⟨n, mv_polynomial.aeval (f ∘ X), _, _⟩,
{ rw [← algebra.range_top_iff_surjective, ← algebra.adjoin_range_eq_range_aeval, set.range_comp,
_root_.eq_top_iff, ← @adjoin_adjoin_of_tower R A B, adjoin_image,
adjoin_range_X, algebra.map_top, (algebra.range_top_iff_surjective _).mpr hf],
exact subset_adjoin },
{ obtain ⟨t, ht⟩ := hRA.out,
have := λ i : t, hf (algebra_map A B i),
choose t' ht',
have ht'' : algebra.adjoin R ((algebra_map A AX) '' t ∪ set.range (X : _ → AX)) = ⊤,
{ rw [adjoin_union_eq_adjoin_adjoin, ← subalgebra.restrict_scalars_top R],
congr' 1,
swap, { exact subalgebra.is_scalar_tower_mid _ },
rw [adjoin_algebra_map, ht],
apply subalgebra.restrict_scalars_injective R,
rw [← adjoin_restrict_scalars, adjoin_range_X, subalgebra.restrict_scalars_top,
subalgebra.restrict_scalars_top] },
let g : t → AX := λ x, C (x : A) - map (algebra_map R A) (t' x),
refine ⟨s.image (map (algebra_map R A)) ∪ t.attach.image g, _⟩,
rw [finset.coe_union, finset.coe_image, finset.coe_image, finset.attach_eq_univ,
finset.coe_univ, set.image_univ],
let s₀ := _, let I := _, change ideal.span s₀ = I,
have leI : ideal.span s₀ ≤ I,
{ rw [ideal.span_le],
rintros _ (⟨x, hx, rfl⟩|⟨⟨x, hx⟩, rfl⟩),
all_goals
{ dsimp [g], rw [ring_hom.mem_ker, alg_hom.to_ring_hom_eq_coe, alg_hom.coe_to_ring_hom] },
{ rw [mv_polynomial.aeval_map_algebra_map, ← aeval_unique],
have := ideal.subset_span hx,
rwa hs at this },
{ rw [map_sub, mv_polynomial.aeval_map_algebra_map, ← aeval_unique,
aeval_C, ht', subtype.coe_mk, sub_self] } },
apply leI.antisymm,
intros x hx,
rw [ring_hom.mem_ker, alg_hom.to_ring_hom_eq_coe, alg_hom.coe_to_ring_hom] at hx,
let s₀ := _, change x ∈ ideal.span s₀,
have : x ∈ (map (algebra_map R A) : _ →+* AX).srange.to_add_submonoid ⊔
(ideal.span s₀).to_add_submonoid,
{ have : x ∈ (⊤ : subalgebra R AX) := trivial,
rw ← ht'' at this,
apply adjoin_induction this,
{ rintros _ (⟨x, hx, rfl⟩|⟨i, rfl⟩),
{ rw [algebra_map_eq, ← sub_add_cancel (C x) (map (algebra_map R A) (t' ⟨x, hx⟩)),
add_comm],
apply add_submonoid.add_mem_sup,
{ exact set.mem_range_self _ },
{ apply ideal.subset_span,
apply set.mem_union_right,
exact set.mem_range_self ⟨x, hx⟩ } },
{ apply add_submonoid.mem_sup_left,
exact ⟨X i, map_X _ _⟩ } },
{ intro r, apply add_submonoid.mem_sup_left, exact ⟨C r, map_C _ _⟩ },
{ intros _ _ h₁ h₂, exact add_mem h₁ h₂ },
{ intros x₁ x₂ h₁ h₂,
obtain ⟨_, ⟨p₁, rfl⟩, q₁, hq₁, rfl⟩ := add_submonoid.mem_sup.mp h₁,
obtain ⟨_, ⟨p₂, rfl⟩, q₂, hq₂, rfl⟩ := add_submonoid.mem_sup.mp h₂,
rw [add_mul, mul_add, add_assoc, ← map_mul],
apply add_submonoid.add_mem_sup,
{ exact set.mem_range_self _ },
{ refine add_mem (ideal.mul_mem_left _ _ hq₂) (ideal.mul_mem_right _ _ hq₁) } } },
obtain ⟨_, ⟨p, rfl⟩, q, hq, rfl⟩ := add_submonoid.mem_sup.mp this,
rw [map_add, aeval_map_algebra_map, ← aeval_unique, (show aeval (f ∘ X) q = 0, from leI hq),
add_zero] at hx,
suffices : ideal.span (s : set RX) ≤ (ideal.span s₀).comap (map $ algebra_map R A),
{ refine add_mem _ hq, rw hs at this, exact this hx },
rw ideal.span_le,
intros x hx,
apply ideal.subset_span,
apply set.mem_union_left,
exact set.mem_image_of_mem _ hx }
end
/-- This is used to prove the strictly stronger `ker_fg_of_surjective`. Use it instead. -/
-- TODO: extract out helper lemmas and tidy proof.
lemma ker_fg_of_mv_polynomial {n : ℕ} (f : mv_polynomial (fin n) R →ₐ[R] A)
(hf : function.surjective f) (hfp : finite_presentation R A) : f.to_ring_hom.ker.fg :=
begin
classical,
obtain ⟨m, f', hf', s, hs⟩ := hfp,
let RXn := mv_polynomial (fin n) R, let RXm := mv_polynomial (fin m) R,
have := λ (i : fin n), hf' (f $ X i),
choose g hg,
have := λ (i : fin m), hf (f' $ X i),
choose h hh,
let aeval_h : RXm →ₐ[R] RXn := aeval h,
let g' : fin n → RXn := λ i, X i - aeval_h (g i),
refine ⟨finset.univ.image g' ∪ s.image aeval_h, _⟩,
simp only [finset.coe_image, finset.coe_union, finset.coe_univ, set.image_univ],
have hh' : ∀ x, f (aeval_h x) = f' x,
{ intro x, rw [← f.coe_to_ring_hom, map_aeval], simp_rw [alg_hom.coe_to_ring_hom, hh],
rw [alg_hom.comp_algebra_map, ← aeval_eq_eval₂_hom, ← aeval_unique] },
let s' := set.range g' ∪ aeval_h '' s,
have leI : ideal.span s' ≤ f.to_ring_hom.ker,
{ rw ideal.span_le,
rintros _ (⟨i, rfl⟩|⟨x, hx, rfl⟩),
{ change f (g' i) = 0, rw [map_sub, ← hg, hh', sub_self], },
{ change f (aeval_h x) = 0,
rw hh',
change x ∈ f'.to_ring_hom.ker,
rw ← hs,
exact ideal.subset_span hx } },
apply leI.antisymm,
intros x hx,
have : x ∈ aeval_h.range.to_add_submonoid ⊔ (ideal.span s').to_add_submonoid,
{ have : x ∈ adjoin R (set.range X : set RXn) := by { rw [adjoin_range_X], trivial },
apply adjoin_induction this,
{ rintros _ ⟨i, rfl⟩,
rw [← sub_add_cancel (X i) (aeval h (g i)), add_comm],
apply add_submonoid.add_mem_sup,
{ exact set.mem_range_self _ },
{ apply submodule.subset_span,
apply set.mem_union_left,
exact set.mem_range_self _ } },
{ intros r, apply add_submonoid.mem_sup_left, exact ⟨C r, aeval_C _ _⟩ },
{ intros _ _ h₁ h₂, exact add_mem h₁ h₂ },
{ intros p₁ p₂ h₁ h₂,
obtain ⟨_, ⟨x₁, rfl⟩, y₁, hy₁, rfl⟩ := add_submonoid.mem_sup.mp h₁,
obtain ⟨_, ⟨x₂, rfl⟩, y₂, hy₂, rfl⟩ := add_submonoid.mem_sup.mp h₂,
rw [mul_add, add_mul, add_assoc, ← map_mul],
apply add_submonoid.add_mem_sup,
{ exact set.mem_range_self _ },
{ exact add_mem (ideal.mul_mem_right _ _ hy₁) (ideal.mul_mem_left _ _ hy₂) } } },
obtain ⟨_, ⟨x, rfl⟩, y, hy, rfl⟩ := add_submonoid.mem_sup.mp this,
refine add_mem _ hy,
simp only [ring_hom.mem_ker, alg_hom.to_ring_hom_eq_coe, alg_hom.coe_to_ring_hom, map_add,
(show f y = 0, from leI hy), add_zero, hh'] at hx,
suffices : ideal.span (s : set RXm) ≤ (ideal.span s').comap aeval_h,
{ apply this, rwa hs },
rw ideal.span_le,
intros x hx,
apply submodule.subset_span,
apply set.mem_union_right,
exact set.mem_image_of_mem _ hx
end
/-- If `f : A →ₐ[R] B` is a sujection between finitely-presented `R`-algebras, then the kernel of
`f` is finitely generated. -/
lemma ker_fg_of_surjective (f : A →ₐ[R] B) (hf : function.surjective f)
(hRA : finite_presentation R A) (hRB : finite_presentation R B) : f.to_ring_hom.ker.fg :=
begin
obtain ⟨n, g, hg, hg'⟩ := hRA,
convert (ker_fg_of_mv_polynomial (f.comp g) (hf.comp hg) hRB).map g.to_ring_hom,
simp_rw [ring_hom.ker_eq_comap_bot, alg_hom.to_ring_hom_eq_coe, alg_hom.comp_to_ring_hom],
rw [← ideal.comap_comap, ideal.map_comap_of_surjective (g : mv_polynomial (fin n) R →+* A) hg],
end
end finite_presentation
end algebra
end module_and_algebra
namespace ring_hom
variables {A B C : Type*} [comm_ring A] [comm_ring B] [comm_ring C]
/-- A ring morphism `A →+* B` is of `finite_presentation` if `B` is finitely presented as
`A`-algebra. -/
def finite_presentation (f : A →+* B) : Prop := @algebra.finite_presentation A B _ _ f.to_algebra
namespace finite_type
lemma of_finite_presentation {f : A →+* B} (hf : f.finite_presentation) : f.finite_type :=
@algebra.finite_type.of_finite_presentation A B _ _ f.to_algebra hf
end finite_type
namespace finite_presentation
variables (A)
lemma id : finite_presentation (ring_hom.id A) := algebra.finite_presentation.self A
variables {A}
lemma comp_surjective {f : A →+* B} {g : B →+* C} (hf : f.finite_presentation) (hg : surjective g)
(hker : g.ker.fg) : (g.comp f).finite_presentation :=
@algebra.finite_presentation.of_surjective A B C _ _ f.to_algebra _ (g.comp f).to_algebra
{ to_fun := g, commutes' := λ a, rfl, .. g } hg hker hf
lemma of_surjective (f : A →+* B) (hf : surjective f) (hker : f.ker.fg) : f.finite_presentation :=
by { rw ← f.comp_id, exact (id A).comp_surjective hf hker}
lemma of_finite_type [is_noetherian_ring A] {f : A →+* B} : f.finite_type ↔ f.finite_presentation :=
@algebra.finite_presentation.of_finite_type A B _ _ f.to_algebra _
lemma comp {g : B →+* C} {f : A →+* B} (hg : g.finite_presentation) (hf : f.finite_presentation) :
(g.comp f).finite_presentation :=
@algebra.finite_presentation.trans A B C _ _ f.to_algebra _ (g.comp f).to_algebra g.to_algebra
{ smul_assoc := λ a b c, begin
simp only [algebra.smul_def, ring_hom.map_mul, mul_assoc],
refl
end }
hf hg
lemma of_comp_finite_type (f : A →+* B) {g : B →+* C} (hg : (g.comp f).finite_presentation)
(hf : f.finite_type) : g.finite_presentation :=
@@algebra.finite_presentation.of_restrict_scalars_finite_presentation _ _ f.to_algebra _
(g.comp f).to_algebra g.to_algebra
(@@is_scalar_tower.of_algebra_map_eq' _ _ _ f.to_algebra g.to_algebra (g.comp f).to_algebra rfl)
hg hf
end finite_presentation
end ring_hom
namespace alg_hom
variables {R A B C : Type*} [comm_ring R]
variables [comm_ring A] [comm_ring B] [comm_ring C]
variables [algebra R A] [algebra R B] [algebra R C]
/-- An algebra morphism `A →ₐ[R] B` is of `finite_presentation` if it is of finite presentation as
ring morphism. In other words, if `B` is finitely presented as `A`-algebra. -/
def finite_presentation (f : A →ₐ[R] B) : Prop := f.to_ring_hom.finite_presentation
namespace finite_type
variables {R A}
lemma of_finite_presentation {f : A →ₐ[R] B} (hf : f.finite_presentation) : f.finite_type :=
ring_hom.finite_type.of_finite_presentation hf
end finite_type
namespace finite_presentation
variables (R A)
lemma id : finite_presentation (alg_hom.id R A) := ring_hom.finite_presentation.id A
variables {R A}
lemma comp {g : B →ₐ[R] C} {f : A →ₐ[R] B} (hg : g.finite_presentation)
(hf : f.finite_presentation) : (g.comp f).finite_presentation :=
ring_hom.finite_presentation.comp hg hf
lemma comp_surjective {f : A →ₐ[R] B} {g : B →ₐ[R] C} (hf : f.finite_presentation)
(hg : surjective g) (hker : g.to_ring_hom.ker.fg) : (g.comp f).finite_presentation :=
ring_hom.finite_presentation.comp_surjective hf hg hker
lemma of_surjective (f : A →ₐ[R] B) (hf : surjective f) (hker : f.to_ring_hom.ker.fg) :
f.finite_presentation :=
ring_hom.finite_presentation.of_surjective f hf hker
lemma of_finite_type [is_noetherian_ring A] {f : A →ₐ[R] B} :
f.finite_type ↔ f.finite_presentation :=
ring_hom.finite_presentation.of_finite_type
lemma of_comp_finite_type (f : A →ₐ[R] B) {g : B →ₐ[R] C} (h : (g.comp f).finite_presentation)
(h' : f.finite_type) : g.finite_presentation :=
h.of_comp_finite_type _ h'
end finite_presentation
end alg_hom
|
cfa513039c5fa998da89f4f18cca1586f11e1b78 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /src/Lean/Structure.lean | 19b5493dbe363324dd8204ad07dc388ae39d013e | [
"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 | 9,111 | 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
Helper functions for retrieving structure information.
-/
import Lean.Environment
import Lean.ProjFns
namespace Lean
structure StructureFieldInfo where
fieldName : Name
projFn : Name
/-- It is `some parentStructName` if it is a subobject, and `parentStructName` is the name of the parent structure -/
subobject? : Option Name
binderInfo : BinderInfo
autoParam? : Option Expr := none
deriving Inhabited, Repr
def StructureFieldInfo.lt (i₁ i₂ : StructureFieldInfo) : Bool :=
Name.quickLt i₁.fieldName i₂.fieldName
structure StructureInfo where
structName : Name
fieldNames : Array Name := #[] -- sorted by field position in the structure
fieldInfo : Array StructureFieldInfo := #[] -- sorted by `fieldName`
deriving Inhabited
def StructureInfo.lt (i₁ i₂ : StructureInfo) : Bool :=
Name.quickLt i₁.structName i₂.structName
def StructureInfo.getProjFn? (info : StructureInfo) (i : Nat) : Option Name :=
if h : i < info.fieldNames.size then
let fieldName := info.fieldNames.get ⟨i, h⟩
info.fieldInfo.binSearch { fieldName := fieldName, projFn := default, subobject? := none, binderInfo := default } StructureFieldInfo.lt |>.map (·.projFn)
else
none
/-- Auxiliary state for structures defined in the current module. -/
private structure StructureState where
map : PersistentHashMap Name StructureInfo := {}
deriving Inhabited
builtin_initialize structureExt : SimplePersistentEnvExtension StructureInfo StructureState ← registerSimplePersistentEnvExtension {
addImportedFn := fun _ => {}
addEntryFn := fun s e => { s with map := s.map.insert e.structName e }
toArrayFn := fun es => es.toArray.qsort StructureInfo.lt
}
structure StructureDescr where
structName : Name
fields : Array StructureFieldInfo -- Should use the order the field appear in the constructor.
deriving Inhabited
def registerStructure (env : Environment) (e : StructureDescr) : Environment :=
structureExt.addEntry env {
structName := e.structName
fieldNames := e.fields.map fun e => e.fieldName
fieldInfo := e.fields.qsort StructureFieldInfo.lt
}
def getStructureInfo? (env : Environment) (structName : Name) : Option StructureInfo :=
match env.getModuleIdxFor? structName with
| some modIdx => structureExt.getModuleEntries env modIdx |>.binSearch { structName } StructureInfo.lt
| none => structureExt.getState env |>.map.find? structName
def getStructureCtor (env : Environment) (constName : Name) : ConstructorVal :=
match env.find? constName with
| some (.inductInfo { isRec := false, ctors := [ctorName], .. }) =>
match env.find? ctorName with
| some (ConstantInfo.ctorInfo val) => val
| _ => panic! "ill-formed environment"
| _ => panic! "structure expected"
/-- Get direct field names for the given structure. -/
def getStructureFields (env : Environment) (structName : Name) : Array Name :=
if let some info := getStructureInfo? env structName then
info.fieldNames
else
panic! "structure expected"
def getFieldInfo? (env : Environment) (structName : Name) (fieldName : Name) : Option StructureFieldInfo :=
if let some info := getStructureInfo? env structName then
info.fieldInfo.binSearch { fieldName := fieldName, projFn := default, subobject? := none, binderInfo := default } StructureFieldInfo.lt
else
none
/-- If `fieldName` represents the relation to a parent structure `S`, return `S` -/
def isSubobjectField? (env : Environment) (structName : Name) (fieldName : Name) : Option Name :=
if let some fieldInfo := getFieldInfo? env structName fieldName then
fieldInfo.subobject?
else
none
/-- Return immediate parent structures -/
def getParentStructures (env : Environment) (structName : Name) : Array Name :=
let fieldNames := getStructureFields env structName;
fieldNames.foldl (init := #[]) fun acc fieldName =>
match isSubobjectField? env structName fieldName with
| some parentStructName => acc.push parentStructName
| none => acc
/-- Return all parent structures -/
partial def getAllParentStructures (env : Environment) (structName : Name) : Array Name :=
visit structName |>.run #[] |>.2
where
visit (structName : Name) : StateT (Array Name) Id Unit := do
for p in getParentStructures env structName do
modify fun s => s.push p
visit p
/-- `findField? env S fname`. If `fname` is defined in a parent `S'` of `S`, return `S'` -/
partial def findField? (env : Environment) (structName : Name) (fieldName : Name) : Option Name :=
if (getStructureFields env structName).contains fieldName then
some structName
else
getParentStructures env structName |>.findSome? fun parentStructName => findField? env parentStructName fieldName
private partial def getStructureFieldsFlattenedAux (env : Environment) (structName : Name) (fullNames : Array Name) (includeSubobjectFields : Bool) : Array Name :=
(getStructureFields env structName).foldl (init := fullNames) fun fullNames fieldName =>
match isSubobjectField? env structName fieldName with
| some parentStructName =>
let fullNames := if includeSubobjectFields then fullNames.push fieldName else fullNames
getStructureFieldsFlattenedAux env parentStructName fullNames includeSubobjectFields
| none => fullNames.push fieldName
/-- Return field names for the given structure, including "flattened" fields from parent
structures. To omit `toParent` projections, set `includeSubobjectFields := false`.
For example, given `Bar` such that
```lean
structure Foo where a : Nat
structure Bar extends Foo where b : Nat
```
return `#[toFoo,a,b]` or `#[a,b]` with subobject fields omitted. -/
def getStructureFieldsFlattened (env : Environment) (structName : Name) (includeSubobjectFields := true) : Array Name :=
getStructureFieldsFlattenedAux env structName #[] includeSubobjectFields
/--
Return true if `constName` is the name of an inductive datatype
created using the `structure` or `class` commands.
We perform the check by testing whether auxiliary projection functions
have been created. -/
def isStructure (env : Environment) (constName : Name) : Bool :=
getStructureInfo? env constName |>.isSome
def getProjFnForField? (env : Environment) (structName : Name) (fieldName : Name) : Option Name :=
if let some fieldInfo := getFieldInfo? env structName fieldName then
some fieldInfo.projFn
else
none
def getProjFnInfoForField? (env : Environment) (structName : Name) (fieldName : Name) : Option (Name × ProjectionFunctionInfo) :=
if let some projFn := getProjFnForField? env structName fieldName then
(projFn, ·) <$> env.getProjectionFnInfo? projFn
else
none
def mkDefaultFnOfProjFn (projFn : Name) : Name :=
projFn ++ `_default
def getDefaultFnForField? (env : Environment) (structName : Name) (fieldName : Name) : Option Name :=
if let some projName := getProjFnForField? env structName fieldName then
let defFn := mkDefaultFnOfProjFn projName
if env.contains defFn then defFn else none
else
-- Check if we have a default function for a default values overridden by substructure.
let defFn := mkDefaultFnOfProjFn (structName ++ fieldName)
if env.contains defFn then defFn else none
partial def getPathToBaseStructureAux (env : Environment) (baseStructName : Name) (structName : Name) (path : List Name) : Option (List Name) :=
if baseStructName == structName then
some path.reverse
else
let fieldNames := getStructureFields env structName;
fieldNames.findSome? fun fieldName =>
match isSubobjectField? env structName fieldName with
| none => none
| some parentStructName =>
match getProjFnForField? env structName fieldName with
| none => none
| some projFn => getPathToBaseStructureAux env baseStructName parentStructName (projFn :: path)
/--
If `baseStructName` is an ancestor structure for `structName`, then return a sequence of projection functions
to go from `structName` to `baseStructName`.
-/
def getPathToBaseStructure? (env : Environment) (baseStructName : Name) (structName : Name) : Option (List Name) :=
getPathToBaseStructureAux env baseStructName structName []
/-- Return true iff `constName` is the a non-recursive inductive datatype that has only one constructor. -/
def isStructureLike (env : Environment) (constName : Name) : Bool :=
match env.find? constName with
| some (.inductInfo { isRec := false, ctors := [_], numIndices := 0, .. }) => true
| _ => false
/-- Return number of fields for a structure-like type -/
def getStructureLikeNumFields (env : Environment) (constName : Name) : Nat :=
match env.find? constName with
| some (.inductInfo { isRec := false, ctors := [ctor], numIndices := 0, .. }) =>
match env.find? ctor with
| some (.ctorInfo { numFields := n, .. }) => n
| _ => 0
| _ => 0
end Lean
|
12941fcd5bf8b4e0673fbc7b20203935c93cd16c | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/tactic/omega/main.lean | 08dd7073e68766d8341f864b0b6ddfc4cf7f4ef0 | [
"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 | 5,674 | lean | /-
Copyright (c) 2019 Seul Baek. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Seul Baek
-/
/-
A tactic for discharging linear integer & natural
number arithmetic goals using the Omega test.
-/
import tactic.omega.int.main
import tactic.omega.nat.main
namespace omega
open tactic
meta def select_domain (t s : tactic (option bool)) : tactic (option bool) :=
do a ← t, b ← s,
match a, b with
| a, none := return a
| none, b := return b
| (some tt), (some tt) := return (some tt)
| (some ff), (some ff) := return (some ff)
| _, _ := failed
end
meta def type_domain (x : expr) : tactic (option bool) :=
if x = `(int)
then return (some tt)
else if x = `(nat)
then return (some ff)
else failed
/-- Detects domain of a formula from its expr.
* Returns none, if domain can be either ℤ or ℕ
* Returns some tt, if domain is exclusively ℤ
* Returns some ff, if domain is exclusively ℕ
* Fails, if domain is neither ℤ nor ℕ -/
meta def form_domain : expr → tactic (option bool)
| `(¬ %%px) := form_domain px
| `(%%px ∨ %%qx) := select_domain (form_domain px) (form_domain qx)
| `(%%px ∧ %%qx) := select_domain (form_domain px) (form_domain qx)
| `(%%px ↔ %%qx) := select_domain (form_domain px) (form_domain qx)
| `(%%(expr.pi _ _ px qx)) :=
monad.cond
(if expr.has_var px then return tt else is_prop px)
(select_domain (form_domain px) (form_domain qx))
(select_domain (type_domain px) (form_domain qx))
| `(@has_lt.lt %%dx %%h _ _) := type_domain dx
| `(@has_le.le %%dx %%h _ _) := type_domain dx
| `(@eq %%dx _ _) := type_domain dx
| `(@ge %%dx %%h _ _) := type_domain dx
| `(@gt %%dx %%h _ _) := type_domain dx
| `(@ne %%dx _ _) := type_domain dx
| `(true) := return none
| `(false) := return none
| x := failed
meta def goal_domain_aux (x : expr) : tactic bool :=
(omega.int.wff x >> return tt) <|> (omega.nat.wff x >> return ff)
/-- Use the current goal to determine.
Return tt if the domain is ℤ, and return ff if it is ℕ -/
meta def goal_domain : tactic bool :=
do gx ← target,
hxs ← local_context >>= monad.mapm infer_type,
app_first goal_domain_aux (gx::hxs)
/-- Return tt if the domain is ℤ, and return ff if it is ℕ -/
meta def determine_domain (opt : list name) : tactic bool :=
if `int ∈ opt
then return tt
else if `nat ∈ opt
then return ff
else goal_domain
end omega
open lean.parser interactive omega
/-- Attempts to discharge goals in the quantifier-free fragment of
linear integer and natural number arithmetic using the Omega test.
Guesses the correct domain by looking at the goal and hypotheses,
and then reverts all relevant hypotheses and variables.
Use `omega manual` to disable automatic reverts, and `omega int` or
`omega nat` to specify the domain.
-/
meta def tactic.interactive.omega (opt : parse (many ident)) : tactic unit :=
do is_int ← determine_domain opt,
let is_manual : bool := if `manual ∈ opt then tt else ff,
if is_int
then omega_int is_manual
else omega_nat is_manual
add_hint_tactic "omega"
declare_trace omega
/--
`omega` attempts to discharge goals in the quantifier-free fragment of linear integer and natural
number arithmetic using the Omega test. In other words, the core procedure of `omega` works with
goals of the form
```lean
∀ x₁, ... ∀ xₖ, P
```
where `x₁, ... xₖ` are integer (resp. natural number) variables, and `P` is a quantifier-free
formula of linear integer (resp. natural number) arithmetic. For instance:
```lean
example : ∀ (x y : int), (x ≤ 5 ∧ y ≤ 3) → x + y ≤ 8 := by omega
```
By default, `omega` tries to guess the correct domain by looking at the goal and hypotheses, and
then reverts all relevant hypotheses and variables (e.g., all variables of type `nat` and `Prop`s
in linear natural number arithmetic, if the domain was determined to be `nat`) to universally close
the goal before calling the main procedure. Therefore, `omega` will often work even if the goal
is not in the above form:
```lean
example (x y : nat) (h : 2 * x + 1 = 2 * y) : false := by omega
```
But this behaviour is not always optimal, since it may revert irrelevant hypotheses or incorrectly
guess the domain. Use `omega manual` to disable automatic reverts, and `omega int` or `omega nat`
to specify the domain.
```lean
example (x y z w : int) (h1 : 3 * y ≥ x) (h2 : z > 19 * w) : 3 * x ≤ 9 * y :=
by {revert h1 x y, omega manual}
example (i : int) (n : nat) (h1 : i = 0) (h2 : n < n) : false := by omega nat
example (n : nat) (h1 : n < 34) (i : int) (h2 : i * 9 = -72) : i = -8 :=
by {revert h2 i, omega manual int}
```
`omega` handles `nat` subtraction by repeatedly rewriting goals of the form `P[t-s]` into
`P[x] ∧ (t = s + x ∨ (t ≤ s ∧ x = 0))`, where `x` is fresh. This means that each (distinct)
occurrence of subtraction will cause the goal size to double during DNF transformation.
`omega` implements the real shadow step of the Omega test, but not the dark and gray shadows.
Therefore, it should (in principle) succeed whenever the negation of the goal has no real solution,
but it may fail if a real solution exists, even if there is no integer/natural number solution.
You can enable `set_option trace.omega true` to see how `omega` interprets your goal.
-/
add_tactic_doc
{ name := "omega",
category := doc_category.tactic,
decl_names := [`tactic.interactive.omega],
tags := ["finishing", "arithmetic", "decision procedure"] }
|
6acc2daffafd15b9401c045387e3d01d8bf3dccc | 92e157ec9825b5e4597a6d715a8928703bc8e3b2 | /src/mywork/notes.lean | c586034fb96f34210ddf9eaad306d542b9ef8d17 | [] | no_license | exb3dg/cs2120f21 | 9e566bc508762573c023d3e70f83cb839c199ec8 | 319b8bf0d63bf96437bf17970ce0198d0b3525cd | refs/heads/main | 1,692,970,909,568 | 1,634,584,540,000 | 1,634,584,540,000 | 399,947,025 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 3,076 | lean | namespace implies
axioms (P Q : Prop) /- assuming P and Q are arbitrary propositions -/
def if_P_is_true_them_so_is_Q : Prop := P → Q /- if P is true then Q is true -/
-- need a proof (axiom) that P → Q and P itself
axiom p : P /- p is the name" P is the funcrion -/
-- assumme P is true
-- assue we have a proof of P (p)
axiom pq : P → Q /- pq is the "name" P → Q is the function -/
-- assume that we have a proof, pq, of P → Q
-- intro for implies: assume premise, show conclusion
-- elimination rule for implies:
#check pq /- apply pq to prove -/
#check p /- apply p to prove-/
#check (pq p) /- look at Infoview pq p : Q-/
/-
Suppose P and Q are propositions and you
know that P → Q and that P are both true.
Show thta Q is true.
Proof: Apply the truth of P → Q to the
truth of P to derive the truth of Q.
Proof: By the elimination rule for → with
pq applied to p.
Proof: By "modus ponens". QED
-/
end implies
namespace all
/- FORALL -/
axioms
(T : Type)
(P : T → Prop)
(t : T)
(a : ∀ (x : T), P x) /- forall x of type T it has property P-/
-- Does t have property P? Yes, bc t is an object of type T and all c of type T has property P
example : P t := a t /- P apply to t (propisition), a apply to t-/
#check a t
/-
AND & →
-/
axioms (P Q : Prop) /- Want a proof of P ∧ Q. -/
/-
***GIT Notes***
distributed version control system (VCS)
- everyone has a local repository (based on last sync)
* git --version --> will tell you what version you have
* git config --global user.na,e "Ellianna Bailey"
* git config --global user.email "exb3dg@virginia.edu"
* git config --list --> to see configuration
* git help config --> put any action wher config is for info
* git init
* rm --> remove
* ls --> ???
* touch .gitignore --> simple text file that git will ignore
* git add .gitignore --> add .gitignore files to staging area
* git add -A --> add everything to staging area
* git reset --> remove files from staging area
* git commit --> ???
* git log --> log of commits
* git diff -> show changes to code
* git status --> status of files ie commited, untracked/tracked
* git pull upstream main --> pulls main repository
* git push origin main --> sends your changes
*homeowork*
How to write a conditional?
Introductional rule for ∧ and vs. implies →
Have command in lean
intros in lean
rw, exact, apply
*Reasoning*
Inductive - reasonings to hypotheses
Abductive - formation of a hypothesis
Deductive - assumed truths --> truths derived from axioms --> from axioms build theorems
Introduction rule - a rule that creates a proof
Elimination rule - use proofs
Axiom for Equality
1) Axiom of Reflexivity
2) Axiom of Substitutability of Equals
Rules
- Symmetric
- Transitivity
Functions are conjectures
Need proofs to get from conjectures to theorems
For all: Assume that you are given an arbitrary object of that type
Reflexive, transitive, and symmetric =
and.intro - and
eq.refl any object of any type is equal to itself
Proof: a false proposition has no proofs (else it'd be true!)
|
81029c2f66370dc265911fddd0231d0f8d6a2bc1 | b7f22e51856f4989b970961f794f1c435f9b8f78 | /hott/types/int/basic.hlean | 5e06aac0e001f504a72246aad07132781f8dd129 | [
"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 | 25,832 | hlean | /-
Copyright (c) 2014 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Floris van Doorn, Jeremy Avigad
The integers, with addition, multiplication, and subtraction. The representation of the integers is
chosen to compute efficiently.
To faciliate proving things about these operations, we show that the integers are a quotient of
ℕ × ℕ with the usual equivalence relation, ≡, and functions
abstr : ℕ × ℕ → ℤ
repr : ℤ → ℕ × ℕ
satisfying:
abstr_repr (a : ℤ) : abstr (repr a) = a
repr_abstr (p : ℕ × ℕ) : repr (abstr p) ≡ p
abstr_eq (p q : ℕ × ℕ) : p ≡ q → abstr p = abstr q
For example, to "lift" statements about add to statements about padd, we need to prove the
following:
repr_add (a b : ℤ) : repr (a + b) = padd (repr a) (repr b)
padd_congr (p p' q q' : ℕ × ℕ) (H1 : p ≡ p') (H2 : q ≡ q') : padd p q ≡ p' q'
-/
import types.nat.sub algebra.relation types.prod
open prod relation nat
open decidable binary
open algebra eq lift
/- the type of integers -/
inductive int : Type :=
| of_nat : nat → int
| neg_succ_of_nat : nat → int
notation `ℤ` := int
definition int.of_num [coercion] [reducible] [constructor] (n : num) : ℤ :=
int.of_nat (nat.of_num n)
namespace int
attribute int.of_nat [coercion]
notation `-[1+ ` n `]` := int.neg_succ_of_nat n -- for pretty-printing output
protected definition prio : num := num.pred nat.prio
definition int_has_zero [instance] [priority int.prio] : has_zero int :=
has_zero.mk (of_nat 0)
definition int_has_one [instance] [priority int.prio] : has_one int :=
has_one.mk (of_nat 1)
theorem of_nat_zero : of_nat (0:nat) = (0:int) :=
rfl
theorem of_nat_one : of_nat (1:nat) = (1:int) :=
rfl
/- definitions of basic functions -/
definition neg_of_nat : ℕ → ℤ
| 0 := 0
| (succ m) := -[1+ m]
definition sub_nat_nat (m n : ℕ) : ℤ :=
match (n - m : nat) with
| 0 := of_nat (m - n) -- m ≥ n
| (succ k) := -[1+ k] -- m < n, and n - m = succ k
end
protected definition neg (a : ℤ) : ℤ :=
int.cases_on a neg_of_nat succ
protected definition add : ℤ → ℤ → ℤ
| (of_nat m) (of_nat n) := _root_.add m n
| (of_nat m) -[1+ n] := sub_nat_nat m (succ n)
| -[1+ m] (of_nat n) := sub_nat_nat n (succ m)
| -[1+ m] -[1+ n] := neg_of_nat (succ m + succ n)
protected definition mul : ℤ → ℤ → ℤ
| (of_nat m) (of_nat n) := m * n
| (of_nat m) -[1+ n] := neg_of_nat (m * succ n)
| -[1+ m] (of_nat n) := neg_of_nat (succ m * n)
| -[1+ m] -[1+ n] := succ m * succ n
/- notation -/
definition int_has_add [instance] [priority int.prio] : has_add int := has_add.mk int.add
definition int_has_neg [instance] [priority int.prio] : has_neg int := has_neg.mk int.neg
definition int_has_mul [instance] [priority int.prio] : has_mul int := has_mul.mk int.mul
lemma mul_of_nat_of_nat (m n : nat) : of_nat m * of_nat n = of_nat (m * n) :=
rfl
lemma mul_of_nat_neg_succ_of_nat (m n : nat) : of_nat m * -[1+ n] = neg_of_nat (m * succ n) :=
rfl
lemma mul_neg_succ_of_nat_of_nat (m n : nat) : -[1+ m] * of_nat n = neg_of_nat (succ m * n) :=
rfl
lemma mul_neg_succ_of_nat_neg_succ_of_nat (m n : nat) : -[1+ m] * -[1+ n] = succ m * succ n :=
rfl
/- some basic functions and properties -/
theorem of_nat.inj {m n : ℕ} (H : of_nat m = of_nat n) : m = n :=
down (int.no_confusion H imp.id)
theorem eq_of_of_nat_eq_of_nat {m n : ℕ} (H : of_nat m = of_nat n) : m = n :=
of_nat.inj H
theorem of_nat_eq_of_nat_iff (m n : ℕ) : of_nat m = of_nat n ↔ m = n :=
iff.intro of_nat.inj !ap
theorem neg_succ_of_nat.inj {m n : ℕ} (H : neg_succ_of_nat m = neg_succ_of_nat n) : m = n :=
down (int.no_confusion H imp.id)
theorem neg_succ_of_nat_eq (n : ℕ) : -[1+ n] = -(n + 1) := rfl
private definition has_decidable_eq₂ : Π (a b : ℤ), decidable (a = b)
| (of_nat m) (of_nat n) := decidable_of_decidable_of_iff
(nat.has_decidable_eq m n) (iff.symm (of_nat_eq_of_nat_iff m n))
| (of_nat m) -[1+ n] := inr (by contradiction)
| -[1+ m] (of_nat n) := inr (by contradiction)
| -[1+ m] -[1+ n] := if H : m = n then
inl (ap neg_succ_of_nat H) else inr (not.mto neg_succ_of_nat.inj H)
definition has_decidable_eq [instance] [priority int.prio] : decidable_eq ℤ := has_decidable_eq₂
theorem of_nat_add (n m : nat) : of_nat (n + m) = of_nat n + of_nat m := rfl
theorem of_nat_succ (n : ℕ) : of_nat (succ n) = of_nat n + 1 := rfl
theorem of_nat_mul (n m : ℕ) : of_nat (n * m) = of_nat n * of_nat m := rfl
theorem sub_nat_nat_of_ge {m n : ℕ} (H : m ≥ n) : sub_nat_nat m n = of_nat (m - n) :=
show sub_nat_nat m n = nat.cases_on 0 (m -[nat] n) _, from (sub_eq_zero_of_le H) ▸ rfl
section
local attribute sub_nat_nat [reducible]
theorem sub_nat_nat_of_lt {m n : ℕ} (H : m < n) : sub_nat_nat m n = -[1+ pred (n - m)] :=
have H1 : n - m = succ (pred (n - m)), from inverse (succ_pred_of_pos (nat.sub_pos_of_lt H)),
show sub_nat_nat m n = nat.cases_on (succ (nat.pred (n - m))) (m -[nat] n) _, from H1 ▸ rfl
end
definition nat_abs (a : ℤ) : ℕ := int.cases_on a id succ
theorem nat_abs_of_nat (n : ℕ) : nat_abs n = n := rfl
theorem eq_zero_of_nat_abs_eq_zero : Π {a : ℤ}, nat_abs a = 0 → a = 0
| (of_nat m) H := ap of_nat H
| -[1+ m'] H := absurd H !succ_ne_zero
theorem nat_abs_zero : nat_abs (0:int) = (0:nat) :=
rfl
theorem nat_abs_one : nat_abs (1:int) = (1:nat) :=
rfl
/- int is a quotient of ordered pairs of natural numbers -/
protected definition equiv (p q : ℕ × ℕ) : Type₀ := pr1 p + pr2 q = pr2 p + pr1 q
local infix ≡ := int.equiv
protected theorem equiv.refl [refl] {p : ℕ × ℕ} : p ≡ p := !add.comm
protected theorem equiv.symm [symm] {p q : ℕ × ℕ} (H : p ≡ q) : q ≡ p :=
calc
pr1 q + pr2 p = pr2 p + pr1 q : by rewrite add.comm
... = pr1 p + pr2 q : H⁻¹
... = pr2 q + pr1 p : by rewrite add.comm
protected theorem equiv.trans [trans] {p q r : ℕ × ℕ} (H1 : p ≡ q) (H2 : q ≡ r) : p ≡ r :=
add.right_cancel (calc
pr1 p + pr2 r + pr2 q = pr1 p + pr2 q + pr2 r : by rewrite add.right_comm
... = pr2 p + pr1 q + pr2 r : {H1}
... = pr2 p + (pr1 q + pr2 r) : by rewrite add.assoc
... = pr2 p + (pr2 q + pr1 r) : {H2}
... = pr2 p + pr2 q + pr1 r : by rewrite add.assoc
... = pr2 p + pr1 r + pr2 q : by rewrite add.right_comm)
protected theorem equiv_equiv : is_equivalence int.equiv :=
is_equivalence.mk @equiv.refl @equiv.symm @equiv.trans
protected theorem equiv_cases {p q : ℕ × ℕ} (H : p ≡ q) :
(pr1 p ≥ pr2 p × pr1 q ≥ pr2 q) ⊎ (pr1 p < pr2 p × pr1 q < pr2 q) :=
sum.elim (@le_sum_gt _ _ (pr2 p) (pr1 p))
(suppose pr1 p ≥ pr2 p,
have pr2 p + pr1 q ≥ pr2 p + pr2 q, from H ▸ add_le_add_right this (pr2 q),
sum.inl (pair `pr1 p ≥ pr2 p` (le_of_add_le_add_left this)))
(suppose H₁ : pr1 p < pr2 p,
have pr2 p + pr1 q < pr2 p + pr2 q, from H ▸ add_lt_add_right H₁ (pr2 q),
sum.inr (pair H₁ (lt_of_add_lt_add_left this)))
protected theorem equiv_of_eq {p q : ℕ × ℕ} (H : p = q) : p ≡ q := H ▸ equiv.refl
/- the representation and abstraction functions -/
definition abstr (a : ℕ × ℕ) : ℤ := sub_nat_nat (pr1 a) (pr2 a)
theorem abstr_of_ge {p : ℕ × ℕ} (H : pr1 p ≥ pr2 p) : abstr p = of_nat (pr1 p - pr2 p) :=
sub_nat_nat_of_ge H
theorem abstr_of_lt {p : ℕ × ℕ} (H : pr1 p < pr2 p) :
abstr p = -[1+ pred (pr2 p - pr1 p)] :=
sub_nat_nat_of_lt H
definition repr : ℤ → ℕ × ℕ
| (of_nat m) := (m, 0)
| -[1+ m] := (0, succ m)
theorem abstr_repr : Π (a : ℤ), abstr (repr a) = a
| (of_nat m) := (sub_nat_nat_of_ge (zero_le m))
| -[1+ m] := rfl
theorem repr_sub_nat_nat (m n : ℕ) : repr (sub_nat_nat m n) ≡ (m, n) :=
nat.lt_ge_by_cases
(take H : m < n,
have H1 : repr (sub_nat_nat m n) = (0, n - m), by
rewrite [sub_nat_nat_of_lt H, -(succ_pred_of_pos (nat.sub_pos_of_lt H))],
H1⁻¹ ▸ (!zero_add ⬝ (nat.sub_add_cancel (le_of_lt H))⁻¹))
(take H : m ≥ n,
have H1 : repr (sub_nat_nat m n) = (m - n, 0), from sub_nat_nat_of_ge H ▸ rfl,
H1⁻¹ ▸ ((nat.sub_add_cancel H) ⬝ !zero_add⁻¹))
theorem repr_abstr (p : ℕ × ℕ) : repr (abstr p) ≡ p :=
!prod.eta ▸ !repr_sub_nat_nat
theorem abstr_eq {p q : ℕ × ℕ} (Hequiv : p ≡ q) : abstr p = abstr q :=
sum.elim (int.equiv_cases Hequiv)
(prod.rec (assume (Hp : pr1 p ≥ pr2 p) (Hq : pr1 q ≥ pr2 q),
have H : pr1 p - pr2 p = pr1 q - pr2 q, from
calc pr1 p - pr2 p
= pr1 p + pr2 q - pr2 q - pr2 p : by rewrite nat.add_sub_cancel
... = pr2 p + pr1 q - pr2 q - pr2 p : Hequiv
... = pr2 p + (pr1 q - pr2 q) - pr2 p : nat.add_sub_assoc Hq
... = pr1 q - pr2 q + pr2 p - pr2 p : by rewrite add.comm
... = pr1 q - pr2 q : by rewrite nat.add_sub_cancel,
abstr_of_ge Hp ⬝ (H ▸ rfl) ⬝ (abstr_of_ge Hq)⁻¹))
(prod.rec (assume (Hp : pr1 p < pr2 p) (Hq : pr1 q < pr2 q),
have H : pr2 p - pr1 p = pr2 q - pr1 q, from
calc pr2 p - pr1 p
= pr2 p + pr1 q - pr1 q - pr1 p : by rewrite nat.add_sub_cancel
... = pr1 p + pr2 q - pr1 q - pr1 p : Hequiv
... = pr1 p + (pr2 q - pr1 q) - pr1 p : nat.add_sub_assoc (le_of_lt Hq)
... = pr2 q - pr1 q + pr1 p - pr1 p : by rewrite add.comm
... = pr2 q - pr1 q : by rewrite nat.add_sub_cancel,
abstr_of_lt Hp ⬝ (H ▸ rfl) ⬝ (abstr_of_lt Hq)⁻¹))
theorem equiv_iff (p q : ℕ × ℕ) : (p ≡ q) ↔ (abstr p = abstr q) :=
iff.intro abstr_eq (assume H, equiv.trans (H ▸ equiv.symm (repr_abstr p)) (repr_abstr q))
theorem equiv_iff3 (p q : ℕ × ℕ) : (p ≡ q) ↔ ((p ≡ p) × (q ≡ q) × (abstr p = abstr q)) :=
iff.trans !equiv_iff (iff.symm
(iff.trans (prod_iff_right !equiv.refl) (prod_iff_right !equiv.refl)))
theorem eq_abstr_of_equiv_repr {a : ℤ} {p : ℕ × ℕ} (Hequiv : repr a ≡ p) : a = abstr p :=
!abstr_repr⁻¹ ⬝ abstr_eq Hequiv
theorem eq_of_repr_equiv_repr {a b : ℤ} (H : repr a ≡ repr b) : a = b :=
eq_abstr_of_equiv_repr H ⬝ !abstr_repr
section
local attribute abstr [reducible]
local attribute dist [reducible]
theorem nat_abs_abstr : Π (p : ℕ × ℕ), nat_abs (abstr p) = dist (pr1 p) (pr2 p)
| (m, n) := nat.lt_ge_by_cases
(assume H : m < n,
calc
nat_abs (abstr (m, n)) = nat_abs (-[1+ pred (n - m)]) : int.abstr_of_lt H
... = n - m : succ_pred_of_pos (nat.sub_pos_of_lt H)
... = dist m n : dist_eq_sub_of_le (le_of_lt H))
(assume H : m ≥ n, (abstr_of_ge H)⁻¹ ▸ (dist_eq_sub_of_ge H)⁻¹)
end
theorem cases_of_nat_succ (a : ℤ) : (Σn : ℕ, a = of_nat n) ⊎ (Σn : ℕ, a = - (of_nat (succ n))) :=
int.cases_on a (take m, sum.inl (sigma.mk _ rfl)) (take m, sum.inr (sigma.mk _ rfl))
theorem cases_of_nat (a : ℤ) : (Σn : ℕ, a = of_nat n) ⊎ (Σn : ℕ, a = - of_nat n) :=
sum.imp_right (sigma.rec (take n, (sigma.mk _))) !cases_of_nat_succ
theorem by_cases_of_nat {P : ℤ → Type} (a : ℤ)
(H1 : Πn : ℕ, P (of_nat n)) (H2 : Πn : ℕ, P (- of_nat n)) :
P a :=
sum.elim (cases_of_nat a)
(assume H, obtain (n : ℕ) (H3 : a = n), from H, H3⁻¹ ▸ H1 n)
(assume H, obtain (n : ℕ) (H3 : a = -n), from H, H3⁻¹ ▸ H2 n)
theorem by_cases_of_nat_succ {P : ℤ → Type} (a : ℤ)
(H1 : Πn : ℕ, P (of_nat n)) (H2 : Πn : ℕ, P (- of_nat (succ n))) :
P a :=
sum.elim (cases_of_nat_succ a)
(assume H, obtain (n : ℕ) (H3 : a = n), from H, H3⁻¹ ▸ H1 n)
(assume H, obtain (n : ℕ) (H3 : a = -(succ n)), from H, H3⁻¹ ▸ H2 n)
/-
int is a ring
-/
/- addition -/
definition padd (p q : ℕ × ℕ) : ℕ × ℕ := (pr1 p + pr1 q, pr2 p + pr2 q)
theorem repr_add : Π (a b : ℤ), repr (add a b) ≡ padd (repr a) (repr b)
| (of_nat m) (of_nat n) := !equiv.refl
| (of_nat m) -[1+ n] :=
begin
change repr (sub_nat_nat m (succ n)) ≡ (m + 0, 0 + succ n),
rewrite [zero_add, add_zero],
apply repr_sub_nat_nat
end
| -[1+ m] (of_nat n) :=
begin
change repr (-[1+ m] + n) ≡ (0 + n, succ m + 0),
rewrite [zero_add, add_zero],
apply repr_sub_nat_nat
end
| -[1+ m] -[1+ n] := !repr_sub_nat_nat
theorem padd_congr {p p' q q' : ℕ × ℕ} (Ha : p ≡ p') (Hb : q ≡ q') : padd p q ≡ padd p' q' :=
calc pr1 p + pr1 q + (pr2 p' + pr2 q')
= pr1 p + pr2 p' + (pr1 q + pr2 q') : add.comm4
... = pr2 p + pr1 p' + (pr1 q + pr2 q') : {Ha}
... = pr2 p + pr1 p' + (pr2 q + pr1 q') : {Hb}
... = pr2 p + pr2 q + (pr1 p' + pr1 q') : add.comm4
theorem padd_comm (p q : ℕ × ℕ) : padd p q = padd q p :=
calc (pr1 p + pr1 q, pr2 p + pr2 q)
= (pr1 q + pr1 p, pr2 p + pr2 q) : by rewrite add.comm
... = (pr1 q + pr1 p, pr2 q + pr2 p) : by rewrite (add.comm (pr2 p) (pr2 q))
theorem padd_assoc (p q r : ℕ × ℕ) : padd (padd p q) r = padd p (padd q r) :=
calc (pr1 p + pr1 q + pr1 r, pr2 p + pr2 q + pr2 r)
= (pr1 p + (pr1 q + pr1 r), pr2 p + pr2 q + pr2 r) : by rewrite add.assoc
... = (pr1 p + (pr1 q + pr1 r), pr2 p + (pr2 q + pr2 r)) : by rewrite add.assoc
protected theorem add_comm (a b : ℤ) : a + b = b + a :=
eq_of_repr_equiv_repr (equiv.trans !repr_add
(equiv.symm (!padd_comm ▸ !repr_add)))
protected theorem add_assoc (a b c : ℤ) : a + b + c = a + (b + c) :=
eq_of_repr_equiv_repr (calc
repr (a + b + c)
≡ padd (repr (a + b)) (repr c) : repr_add
... ≡ padd (padd (repr a) (repr b)) (repr c) : padd_congr !repr_add !equiv.refl
... = padd (repr a) (padd (repr b) (repr c)) : !padd_assoc
... ≡ padd (repr a) (repr (b + c)) : padd_congr !equiv.refl !repr_add
... ≡ repr (a + (b + c)) : repr_add)
protected theorem add_zero : Π (a : ℤ), a + 0 = a := int.rec (λm, rfl) (λm, rfl)
protected theorem zero_add (a : ℤ) : 0 + a = a := !int.add_comm ▸ !int.add_zero
/- negation -/
definition pneg (p : ℕ × ℕ) : ℕ × ℕ := (pr2 p, pr1 p)
-- note: this is =, not just ≡
theorem repr_neg : Π (a : ℤ), repr (- a) = pneg (repr a)
| 0 := rfl
| (succ m) := rfl
| -[1+ m] := rfl
theorem pneg_congr {p p' : ℕ × ℕ} (H : p ≡ p') : pneg p ≡ pneg p' := inverse H
theorem pneg_pneg (p : ℕ × ℕ) : pneg (pneg p) = p := !prod.eta
theorem nat_abs_neg (a : ℤ) : nat_abs (-a) = nat_abs a :=
calc
nat_abs (-a) = nat_abs (abstr (repr (-a))) : abstr_repr
... = nat_abs (abstr (pneg (repr a))) : repr_neg
... = dist (pr1 (pneg (repr a))) (pr2 (pneg (repr a))) : nat_abs_abstr
... = dist (pr2 (pneg (repr a))) (pr1 (pneg (repr a))) : dist.comm
... = nat_abs (abstr (repr a)) : nat_abs_abstr
... = nat_abs a : abstr_repr
theorem padd_pneg (p : ℕ × ℕ) : padd p (pneg p) ≡ (0, 0) :=
show pr1 p + pr2 p + 0 = pr2 p + pr1 p + 0,
by rewrite [nat.add_comm (pr1 p)]
theorem padd_padd_pneg (p q : ℕ × ℕ) : padd (padd p q) (pneg q) ≡ p :=
calc pr1 p + pr1 q + pr2 q + pr2 p
= pr1 p + (pr1 q + pr2 q) + pr2 p : add.assoc
... = pr1 p + (pr1 q + pr2 q + pr2 p) : add.assoc
... = pr1 p + (pr2 q + pr1 q + pr2 p) : add.comm
... = pr1 p + (pr2 q + pr2 p + pr1 q) : add.right_comm
... = pr1 p + (pr2 p + pr2 q + pr1 q) : add.comm
... = pr2 p + pr2 q + pr1 q + pr1 p : add.comm
protected theorem add_left_inv (a : ℤ) : -a + a = 0 :=
have H : repr (-a + a) ≡ repr 0, from
calc
repr (-a + a) ≡ padd (repr (neg a)) (repr a) : repr_add
... = padd (pneg (repr a)) (repr a) : repr_neg
... ≡ repr 0 : padd_pneg,
eq_of_repr_equiv_repr H
/- nat abs -/
definition pabs (p : ℕ × ℕ) : ℕ := dist (pr1 p) (pr2 p)
theorem pabs_congr {p q : ℕ × ℕ} (H : p ≡ q) : pabs p = pabs q :=
calc
pabs p = nat_abs (abstr p) : nat_abs_abstr
... = nat_abs (abstr q) : abstr_eq H
... = pabs q : nat_abs_abstr
theorem nat_abs_eq_pabs_repr (a : ℤ) : nat_abs a = pabs (repr a) :=
calc
nat_abs a = nat_abs (abstr (repr a)) : abstr_repr
... = pabs (repr a) : nat_abs_abstr
theorem nat_abs_add_le (a b : ℤ) : nat_abs (a + b) ≤ nat_abs a + nat_abs b :=
calc
nat_abs (a + b) = pabs (repr (a + b)) : nat_abs_eq_pabs_repr
... = pabs (padd (repr a) (repr b)) : pabs_congr !repr_add
... ≤ pabs (repr a) + pabs (repr b) : dist_add_add_le_add_dist_dist
... = pabs (repr a) + nat_abs b : nat_abs_eq_pabs_repr
... = nat_abs a + nat_abs b : nat_abs_eq_pabs_repr
theorem nat_abs_neg_of_nat (n : nat) : nat_abs (neg_of_nat n) = n :=
begin cases n, reflexivity, reflexivity end
section
local attribute nat_abs [reducible]
theorem nat_abs_mul : Π (a b : ℤ), nat_abs (a * b) = (nat_abs a) * (nat_abs b)
| (of_nat m) (of_nat n) := rfl
| (of_nat m) -[1+ n] := by rewrite [mul_of_nat_neg_succ_of_nat, nat_abs_neg_of_nat]
| -[1+ m] (of_nat n) := by rewrite [mul_neg_succ_of_nat_of_nat, nat_abs_neg_of_nat]
| -[1+ m] -[1+ n] := rfl
end
/- multiplication -/
definition pmul (p q : ℕ × ℕ) : ℕ × ℕ :=
(pr1 p * pr1 q + pr2 p * pr2 q, pr1 p * pr2 q + pr2 p * pr1 q)
theorem repr_neg_of_nat (m : ℕ) : repr (neg_of_nat m) = (0, m) :=
nat.cases_on m rfl (take m', rfl)
-- note: we have =, not just ≡
theorem repr_mul : Π (a b : ℤ), repr (a * b) = pmul (repr a) (repr b)
| (of_nat m) (of_nat n) := calc
(m * n + 0 * 0, m * 0 + 0) = (m * n + 0 * 0, m * 0 + 0 * n) : by rewrite *zero_mul
| (of_nat m) -[1+ n] := calc
repr ((m : int) * -[1+ n]) = (m * 0 + 0, m * succ n + 0 * 0) : repr_neg_of_nat
... = (m * 0 + 0 * succ n, m * succ n + 0 * 0) : by rewrite *zero_mul
| -[1+ m] (of_nat n) := calc
repr (-[1+ m] * (n:int)) = (0 + succ m * 0, succ m * n) : repr_neg_of_nat
... = (0 + succ m * 0, 0 + succ m * n) : by rewrite [zero_add (succ m * n)]
... = (0 * n + succ m * 0, 0 + succ m * n) : by rewrite zero_mul
| -[1+ m] -[1+ n] := calc
(succ m * succ n, 0) = (succ m * succ n, 0 * succ n) : by rewrite zero_mul
... = (0 + succ m * succ n, 0 * succ n) : by rewrite nat.zero_add
theorem equiv_mul_prep {xa ya xb yb xn yn xm ym : ℕ}
(H1 : xa + yb = ya + xb) (H2 : xn + ym = yn + xm)
: xa*xn+ya*yn+(xb*ym+yb*xm) = xa*yn+ya*xn+(xb*xm+yb*ym) :=
nat.add_right_cancel (calc
xa*xn+ya*yn + (xb*ym+yb*xm) + (yb*xn+xb*yn + (xb*xn+yb*yn))
= xa*xn+ya*yn + (yb*xn+xb*yn) + (xb*ym+yb*xm + (xb*xn+yb*yn)) : by rewrite add.comm4
... = xa*xn+ya*yn + (yb*xn+xb*yn) + (xb*xn+yb*yn + (xb*ym+yb*xm)) : by rewrite {xb*ym+yb*xm +_}nat.add_comm
... = xa*xn+yb*xn + (ya*yn+xb*yn) + (xb*xn+xb*ym + (yb*yn+yb*xm)) : by exact !congr_arg2 !add.comm4 !add.comm4
... = ya*xn+xb*xn + (xa*yn+yb*yn) + (xb*yn+xb*xm + (yb*xn+yb*ym)) : by xrewrite[-+left_distrib,-+right_distrib, H1, H2]
... = ya*xn+xa*yn + (xb*xn+yb*yn) + (xb*yn+yb*xn + (xb*xm+yb*ym)) : by exact !congr_arg2 !add.comm4 !add.comm4
... = xa*yn+ya*xn + (xb*xn+yb*yn) + (xb*yn+yb*xn + (xb*xm+yb*ym)) : by rewrite {xa*yn + _}nat.add_comm
... = xa*yn+ya*xn + (xb*xn+yb*yn) + (yb*xn+xb*yn + (xb*xm+yb*ym)) : by rewrite {xb*yn + _}nat.add_comm
... = xa*yn+ya*xn + (yb*xn+xb*yn) + (xb*xn+yb*yn + (xb*xm+yb*ym)) : by rewrite (!add.comm4)
... = xa*yn+ya*xn + (yb*xn+xb*yn) + (xb*xm+yb*ym + (xb*xn+yb*yn)) : by rewrite {xb*xn+yb*yn + _}nat.add_comm
... = xa*yn+ya*xn + (xb*xm+yb*ym) + (yb*xn+xb*yn + (xb*xn+yb*yn)) : by rewrite add.comm4)
theorem pmul_congr {p p' q q' : ℕ × ℕ} : p ≡ p' → q ≡ q' → pmul p q ≡ pmul p' q' := equiv_mul_prep
theorem pmul_comm (p q : ℕ × ℕ) : pmul p q = pmul q p :=
show (_,_) = (_,_),
begin
congruence,
{ congruence, repeat rewrite mul.comm },
{ rewrite add.comm, congruence, repeat rewrite mul.comm }
end
protected theorem mul_comm (a b : ℤ) : a * b = b * a :=
eq_of_repr_equiv_repr
((calc
repr (a * b) = pmul (repr a) (repr b) : repr_mul
... = pmul (repr b) (repr a) : pmul_comm
... = repr (b * a) : repr_mul) ▸ !equiv.refl)
private theorem pmul_assoc_prep {p1 p2 q1 q2 r1 r2 : ℕ} :
((p1*q1+p2*q2)*r1+(p1*q2+p2*q1)*r2, (p1*q1+p2*q2)*r2+(p1*q2+p2*q1)*r1) =
(p1*(q1*r1+q2*r2)+p2*(q1*r2+q2*r1), p1*(q1*r2+q2*r1)+p2*(q1*r1+q2*r2)) :=
begin
rewrite [+left_distrib, +right_distrib, *mul.assoc],
xrewrite (add.comm4 (p1 * (q1 * r1)) (p2 * (q2 * r1)) (p1 * (q2 * r2)) (p2 * (q1 * r2))),
rewrite (add.comm (p2 * (q2 * r1)) (p2 * (q1 * r2))),
xrewrite (add.comm4 (p1 * (q1 * r2)) (p2 * (q2 * r2)) (p1 * (q2 * r1)) (p2 * (q1 * r1))),
rewrite (add.comm (p2 * (q2 * r2)) (p2 * (q1 * r1)))
end
theorem pmul_assoc (p q r: ℕ × ℕ) : pmul (pmul p q) r = pmul p (pmul q r) := pmul_assoc_prep
protected theorem mul_assoc (a b c : ℤ) : (a * b) * c = a * (b * c) :=
eq_of_repr_equiv_repr
((calc
repr (a * b * c) = pmul (repr (a * b)) (repr c) : repr_mul
... = pmul (pmul (repr a) (repr b)) (repr c) : repr_mul
... = pmul (repr a) (pmul (repr b) (repr c)) : pmul_assoc
... = pmul (repr a) (repr (b * c)) : repr_mul
... = repr (a * (b * c)) : repr_mul) ▸ !equiv.refl)
protected theorem mul_one : Π (a : ℤ), a * 1 = a
| (of_nat m) := !int.zero_add -- zero_add happens to be def. = to this thm
| -[1+ m] := !nat.zero_add ▸ rfl
protected theorem one_mul (a : ℤ) : 1 * a = a :=
int.mul_comm a 1 ▸ int.mul_one a
private theorem mul_distrib_prep {a1 a2 b1 b2 c1 c2 : ℕ} :
((a1+b1)*c1+(a2+b2)*c2, (a1+b1)*c2+(a2+b2)*c1) =
(a1*c1+a2*c2+(b1*c1+b2*c2), a1*c2+a2*c1+(b1*c2+b2*c1)) :=
begin
rewrite +right_distrib, congruence,
{rewrite add.comm4},
{rewrite add.comm4}
end
protected theorem right_distrib (a b c : ℤ) : (a + b) * c = a * c + b * c :=
eq_of_repr_equiv_repr
(calc
repr ((a + b) * c) = pmul (repr (a + b)) (repr c) : repr_mul
... ≡ pmul (padd (repr a) (repr b)) (repr c) : pmul_congr !repr_add equiv.refl
... = padd (pmul (repr a) (repr c)) (pmul (repr b) (repr c)) : mul_distrib_prep
... = padd (repr (a * c)) (pmul (repr b) (repr c)) : repr_mul
... = padd (repr (a * c)) (repr (b * c)) : repr_mul
... ≡ repr (a * c + b * c) : repr_add)
protected theorem left_distrib (a b c : ℤ) : a * (b + c) = a * b + a * c :=
calc
a * (b + c) = (b + c) * a : int.mul_comm
... = b * a + c * a : int.right_distrib
... = a * b + c * a : int.mul_comm
... = a * b + a * c : int.mul_comm
protected theorem zero_ne_one : (0 : int) ≠ 1 :=
assume H : 0 = 1, !succ_ne_zero (of_nat.inj H)⁻¹
protected theorem eq_zero_sum_eq_zero_of_mul_eq_zero {a b : ℤ} (H : a * b = 0) : a = 0 ⊎ b = 0 :=
sum.imp eq_zero_of_nat_abs_eq_zero eq_zero_of_nat_abs_eq_zero
(eq_zero_sum_eq_zero_of_mul_eq_zero (by rewrite [-nat_abs_mul, H]))
protected definition integral_domain [trans_instance] : integral_domain int :=
⦃integral_domain,
add := int.add,
add_assoc := int.add_assoc,
zero := 0,
zero_add := int.zero_add,
add_zero := int.add_zero,
neg := int.neg,
add_left_inv := int.add_left_inv,
add_comm := int.add_comm,
mul := int.mul,
mul_assoc := int.mul_assoc,
one := 1,
one_mul := int.one_mul,
mul_one := int.mul_one,
left_distrib := int.left_distrib,
right_distrib := int.right_distrib,
mul_comm := int.mul_comm,
zero_ne_one := int.zero_ne_one,
eq_zero_sum_eq_zero_of_mul_eq_zero := @int.eq_zero_sum_eq_zero_of_mul_eq_zero,
is_set_carrier := is_set_of_decidable_eq⦄
definition int_has_sub [instance] [priority int.prio] : has_sub int :=
has_sub.mk has_sub.sub
definition int_has_dvd [instance] [priority int.prio] : has_dvd int :=
has_dvd.mk has_dvd.dvd
/- additional properties -/
theorem of_nat_sub {m n : ℕ} (H : m ≥ n) : of_nat (m - n) = of_nat m - of_nat n :=
have m - n + n = m, from nat.sub_add_cancel H,
begin
symmetry,
apply sub_eq_of_eq_add,
rewrite [-of_nat_add, this]
end
theorem neg_succ_of_nat_eq' (m : ℕ) : -[1+ m] = -m - 1 :=
by xrewrite [neg_succ_of_nat_eq, neg_add]
definition succ (a : ℤ) := a + (succ zero)
definition pred (a : ℤ) := a - (succ zero)
definition nat_succ_eq_int_succ (n : ℕ) : nat.succ n = int.succ n := idp
theorem pred_succ (a : ℤ) : pred (succ a) = a := !sub_add_cancel
theorem succ_pred (a : ℤ) : succ (pred a) = a := !add_sub_cancel
theorem neg_succ (a : ℤ) : -succ a = pred (-a) :=
by rewrite [↑succ,neg_add]
theorem succ_neg_succ (a : ℤ) : succ (-succ a) = -a :=
by rewrite [neg_succ,succ_pred]
theorem neg_pred (a : ℤ) : -pred a = succ (-a) :=
by rewrite [↑pred,neg_sub,sub_eq_add_neg,add.comm]
theorem pred_neg_pred (a : ℤ) : pred (-pred a) = -a :=
by rewrite [neg_pred,pred_succ]
theorem pred_nat_succ (n : ℕ) : pred (nat.succ n) = n := pred_succ n
theorem neg_nat_succ (n : ℕ) : -nat.succ n = pred (-n) := !neg_succ
theorem succ_neg_nat_succ (n : ℕ) : succ (-nat.succ n) = -n := !succ_neg_succ
definition rec_nat_on [unfold 2] {P : ℤ → Type} (z : ℤ) (H0 : P 0)
(Hsucc : Π⦃n : ℕ⦄, P n → P (succ n)) (Hpred : Π⦃n : ℕ⦄, P (-n) → P (-nat.succ n)) : P z :=
int.rec (nat.rec H0 Hsucc) (λn, nat.rec H0 Hpred (nat.succ n)) z
--the only computation rule of rec_nat_on which is not definitional
theorem rec_nat_on_neg {P : ℤ → Type} (n : ℕ) (H0 : P zero)
(Hsucc : Π⦃n : ℕ⦄, P n → P (succ n)) (Hpred : Π⦃n : ℕ⦄, P (-n) → P (-nat.succ n))
: rec_nat_on (-nat.succ n) H0 Hsucc Hpred = Hpred (rec_nat_on (-n) H0 Hsucc Hpred) :=
nat.rec rfl (λn H, rfl) n
end int
|
90a29c576ef7a6257abc7f26eea5751df2659c23 | a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940 | /src/Init/Data/Repr.lean | ec662a76c46a4c608dd58cad17521561f62b8ec7 | [
"Apache-2.0"
] | permissive | WojciechKarpiel/lean4 | 7f89706b8e3c1f942b83a2c91a3a00b05da0e65b | f6e1314fa08293dea66a329e05b6c196a0189163 | refs/heads/master | 1,686,633,402,214 | 1,625,821,189,000 | 1,625,821,258,000 | 384,640,886 | 0 | 0 | Apache-2.0 | 1,625,903,617,000 | 1,625,903,026,000 | null | UTF-8 | Lean | false | false | 6,786 | lean | /-
Copyright (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
-/
prelude
import Init.Data.Format.Basic
import Init.Data.Int.Basic
import Init.Data.Nat.Div
import Init.Data.UInt
import Init.Control.Id
open Sum Subtype Nat
open Std
class Repr (α : Type u) where
reprPrec : α → Nat → Format
export Repr (reprPrec)
abbrev repr [Repr α] (a : α) : Format :=
reprPrec a 0
abbrev reprStr [Repr α] (a : α) : String :=
reprPrec a 0 |>.pretty
abbrev reprArg [Repr α] (a : α) : Format :=
reprPrec a max_prec
/- Auxiliary class for marking types that should be considered atomic by `Repr` methods.
We use it at `Repr (List α)` to decide whether `bracketFill` should be used or not. -/
class ReprAtom (α : Type u)
-- This instance is needed because `id` is not reducible
instance [Repr α] : Repr (id α) :=
inferInstanceAs (Repr α)
instance [Repr α] : Repr (Id α) :=
inferInstanceAs (Repr α)
instance : Repr Bool where
reprPrec
| true, _ => "true"
| false, _ => "false"
def Repr.addAppParen (f : Format) (prec : Nat) : Format :=
if prec >= max_prec then
Format.paren f
else
f
instance : Repr (Decidable p) where
reprPrec
| Decidable.isTrue _, prec => Repr.addAppParen "isTrue _" prec
| Decidable.isFalse _, prec => Repr.addAppParen "isFalse _" prec
instance : Repr PUnit.{u+1} where
reprPrec _ _ := "PUnit.unit"
instance [Repr α] : Repr (ULift.{v} α) where
reprPrec v prec :=
Repr.addAppParen ("ULift.up " ++ reprArg v.1) prec
instance : Repr Unit where
reprPrec v _ := "()"
instance [Repr α] : Repr (Option α) where
reprPrec
| none, _ => "none"
| some a, prec => Repr.addAppParen ("some " ++ reprArg a) prec
instance [Repr α] [Repr β] : Repr (Sum α β) where
reprPrec
| Sum.inl a, prec => Repr.addAppParen ("Sum.inl " ++ reprArg a) prec
| Sum.inr b, prec => Repr.addAppParen ("Sum.inr " ++ reprArg b) prec
class ReprTuple (α : Type u) where
reprTuple : α → List Format → List Format
export ReprTuple (reprTuple)
instance [Repr α] : ReprTuple α where
reprTuple a xs := repr a :: xs
instance [Repr α] [ReprTuple β] : ReprTuple (α × β) where
reprTuple | (a, b), xs => reprTuple b (repr a :: xs)
instance [Repr α] [ReprTuple β] : Repr (α × β) where
reprPrec | (a, b), _ => Format.bracket "(" (Format.joinSep (reprTuple b [repr a]).reverse ("," ++ Format.line)) ")"
instance {β : α → Type v} [Repr α] [s : (x : α) → Repr (β x)] : Repr (Sigma β) where
reprPrec | ⟨a, b⟩, _ => Format.bracket "⟨" (repr a ++ ", " ++ repr b) "⟩"
instance {p : α → Prop} [Repr α] : Repr (Subtype p) where
reprPrec s prec := reprPrec s.val prec
namespace Nat
def digitChar (n : Nat) : Char :=
if n = 0 then '0' else
if n = 1 then '1' else
if n = 2 then '2' else
if n = 3 then '3' else
if n = 4 then '4' else
if n = 5 then '5' else
if n = 6 then '6' else
if n = 7 then '7' else
if n = 8 then '8' else
if n = 9 then '9' else
if n = 0xa then 'a' else
if n = 0xb then 'b' else
if n = 0xc then 'c' else
if n = 0xd then 'd' else
if n = 0xe then 'e' else
if n = 0xf then 'f' else
'*'
def toDigitsCore (base : Nat) : Nat → Nat → List Char → List Char
| 0, n, ds => ds
| fuel+1, n, ds =>
let d := digitChar <| n % base;
let n' := n / base;
if n' = 0 then d::ds
else toDigitsCore base fuel n' (d::ds)
def toDigits (base : Nat) (n : Nat) : List Char :=
toDigitsCore base (n+1) n []
protected def repr (n : Nat) : String :=
(toDigits 10 n).asString
def superDigitChar (n : Nat) : Char :=
if n = 0 then '⁰' else
if n = 1 then '¹' else
if n = 2 then '²' else
if n = 3 then '³' else
if n = 4 then '⁴' else
if n = 5 then '⁵' else
if n = 6 then '⁶' else
if n = 7 then '⁷' else
if n = 8 then '⁸' else
if n = 9 then '⁹' else
'*'
partial def toSuperDigitsAux : Nat → List Char → List Char
| n, ds =>
let d := superDigitChar <| n % 10;
let n' := n / 10;
if n' = 0 then d::ds
else toSuperDigitsAux n' (d::ds)
def toSuperDigits (n : Nat) : List Char :=
toSuperDigitsAux n []
def toSuperscriptString (n : Nat) : String :=
(toSuperDigits n).asString
end Nat
instance : Repr Nat where
reprPrec n _ := Nat.repr n
def Int.repr : Int → String
| ofNat m => Nat.repr m
| negSucc m => "-" ++ Nat.repr (succ m)
instance : Repr Int where
reprPrec i _ := i.repr
def hexDigitRepr (n : Nat) : String :=
String.singleton <| Nat.digitChar n
def charToHex (c : Char) : String :=
let n := Char.toNat c;
let d2 := n / 16;
let d1 := n % 16;
hexDigitRepr d2 ++ hexDigitRepr d1
def Char.quoteCore (c : Char) : String :=
if c = '\n' then "\\n"
else if c = '\t' then "\\t"
else if c = '\\' then "\\\\"
else if c = '\"' then "\\\""
else if c.toNat <= 31 ∨ c = '\x7f' then "\\x" ++ charToHex c
else String.singleton c
def Char.quote (c : Char) : String :=
"'" ++ Char.quoteCore c ++ "'"
instance : Repr Char where
reprPrec c _ := c.quote
protected def Char.repr (c : Char) : String :=
c.quote
def String.quote (s : String) : String :=
if s.isEmpty then "\"\""
else s.foldl (fun s c => s ++ c.quoteCore) "\"" ++ "\""
instance : Repr String where
reprPrec s _ := s.quote
instance : Repr Substring where
reprPrec s _ := Format.text <| String.quote s.toString ++ ".toSubstring"
instance : Repr String.Iterator where
reprPrec | ⟨s, pos⟩, prec => Repr.addAppParen ("String.Iterator.mk " ++ reprArg s ++ " " ++ reprArg pos) prec
instance (n : Nat) : Repr (Fin n) where
reprPrec f _ := repr f.val
instance : Repr UInt8 where
reprPrec n _ := repr n.toNat
instance : Repr UInt16 where
reprPrec n _ := repr n.toNat
instance : Repr UInt32 where
reprPrec n _ := repr n.toNat
instance : Repr UInt64 where
reprPrec n _ := repr n.toNat
instance : Repr USize where
reprPrec n _ := repr n.toNat
instance [Repr α] : Repr (List α) where
reprPrec
| [], _ => "[]"
| as, _ => Format.bracket "[" (@Format.joinSep _ ⟨repr⟩ as ("," ++ Format.line)) "]"
instance [Repr α] [ReprAtom α] : Repr (List α) where
reprPrec
| [], _ => "[]"
| as, _ => Format.bracketFill "[" (@Format.joinSep _ ⟨repr⟩ as ("," ++ Format.line)) "]"
instance : ReprAtom Bool := ⟨⟩
instance : ReprAtom Nat := ⟨⟩
instance : ReprAtom Int := ⟨⟩
instance : ReprAtom Char := ⟨⟩
instance : ReprAtom String := ⟨⟩
instance : ReprAtom UInt8 := ⟨⟩
instance : ReprAtom UInt16 := ⟨⟩
instance : ReprAtom UInt32 := ⟨⟩
instance : ReprAtom UInt64 := ⟨⟩
instance : ReprAtom USize := ⟨⟩
deriving instance Repr for Lean.SourceInfo
|
9aa266156118e48f53af13bd62a5c0f6f0768ea1 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/interactive/userWidget.lean | 96a56240cfe762ef67831da8edab15a4dec6b8f2 | [
"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 | 298 | lean | import Lean
open Lean Widget
@[widget]
def widget1 : UserWidgetDefinition := {
name := "my fancy widget"
javascript:= "
import * as React from 'react';
export default function (props) {
return React.createElement('p', {}, 'hello')
}"
}
#widget widget1 (Json.mkObj [])
--^ widgets
|
884e09c80bb83f6ae1031738554eb5c7b711ef77 | 05f637fa14ac28031cb1ea92086a0f4eb23ff2b1 | /tests/lean/simp_tac.lean | 5917ddf4262279de9bc24baa00fd89d120888ce4 | [
"Apache-2.0"
] | permissive | codyroux/lean0.1 | 1ce92751d664aacff0529e139083304a7bbc8a71 | 0dc6fb974aa85ed6f305a2f4b10a53a44ee5f0ef | refs/heads/master | 1,610,830,535,062 | 1,402,150,480,000 | 1,402,150,480,000 | 19,588,851 | 2 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 286 | lean | import tactic
-- Create a simple rewrite set
rewrite_set simple
add_rewrite Nat::add_zeror Nat::add_zerol Nat::add_comm eq_id : simple
-- Prove the following theorem using the simplifier with the rewrite set simple
theorem Test (a b : Nat) : 0 + a + 0 + b = b + a := (by simp simple)
|
e0df8cecd8fcec30b41fd36d0ead8ab8f42de878 | 3d2a7f1582fe5bae4d0bdc2fe86e997521239a65 | /cs-lib/src/spatial-reasoning-lib.lean | 3f1e9ecf632913b3eb0922a1efe9a1e0781d6f32 | [] | no_license | own-pt/common-sense-lean | e4fa643ae010459de3d1bf673be7cbc7062563c9 | f672210aecb4172f5bae265e43e6867397e13b1c | refs/heads/master | 1,622,065,660,261 | 1,589,487,533,000 | 1,589,487,533,000 | 254,167,782 | 3 | 2 | null | 1,589,487,535,000 | 1,586,370,214,000 | Lean | UTF-8 | Lean | false | false | 2,230 | lean | import tiny
constants DirectionalAttribute North South East West Front Behind : U
-- (OppositeDirection North South)
-- (instance North DirectionalAttribute)
axiom north_is_direcional_attribute : ins North DirectionalAttribute
-- (<=>
-- (orientation ?OBJ1 ?OBJ2 North)
-- (orientation ?OBJ2 ?OBJ1 South))
axiom north_south : ∀ OBJ1 OBJ2,
(orientation OBJ1 OBJ2 North) ↔
(orientation OBJ2 OBJ1 South)
-- (=>
-- (and
-- (orientation ?OBJ1 ?OBJ2 ?DIR)
-- (instance ?DIR PositionalAttribute)
-- (OppositeDirection ?DIR ?OPPDIR))
-- (orientation ?OBJ2 ?OBJ1 ?OPPDIR))
axiom oposite_directions : ∀ OBJ1 OBJ2 DIR OPPDIR,
(orientation OBJ1 OBJ2 DIR)
∧ (ins DIR PositionalAttribute)
∧ (OppositeDirection DIR OPPDIR)
→ (orientation OBJ2 OBJ1 OPPDIR)
-- (OppositeDirection East West)
-- (OppositeDirection Northeast Southwest)
-- (OppositeDirection Upstream Downstream)
-- (OppositeDirection Front Behind)
-- (OppositeDirection Left Right)
-- (subclass TransitivePositionalAttribute PositionalAttribute)
axiom transitive_positional_attribute_is_positional_attribute :
subclass TransitivePositionalAttribute PositionalAttribute
-- (instance North TransitivePositionalAttribute)
-- (instance South TransitivePositionalAttribute)
-- (instance East TransitivePositionalAttribute)
-- (instance West TransitivePositionalAttribute)
axiom north_transitivepositionalattribute :
ins North TransitivePositionalAttribute
axiom south_transitivepositionalattribute :
ins South TransitivePositionalAttribute
axiom east_transitivepositionalattribute :
ins East TransitivePositionalAttribute
axiom west_transitivepositionalattribute :
ins West TransitivePositionalAttribute
axiom front_transitivepositionalattribute :
ins Front TransitivePositionalAttribute
axiom behind_transitivepositionalattribute :
ins Behind TransitivePositionalAttribute
-- (=>
-- (and
-- (orientation ?A ?B ?P)
-- (orientation ?B ?C ?P)
-- (instance ?P TransitivePositionalAttribute))
-- (orientation ?A ?C ?P))
axiom transitive_positional_attribute : ∀ A B C P,
(orientation A B P)
∧ (orientation B C P)
∧ (ins P TransitivePositionalAttribute)
|
aa657c70a6124331a8174bc187cd413a730b2bc6 | 3dc4623269159d02a444fe898d33e8c7e7e9461b | /.github/workflows/group-representation/group_representation.lean | 4aadad3b13be5d6729b73325a1b427f5b873f476 | [] | no_license | Or7ando/lean | cc003e6c41048eae7c34aa6bada51c9e9add9e66 | d41169cf4e416a0d42092fb6bdc14131cee9dd15 | refs/heads/master | 1,650,600,589,722 | 1,587,262,906,000 | 1,587,262,906,000 | 255,387,160 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 13,778 | lean | /- Copyright (c) 2020 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: ...
-/
import linear_algebra.basic
import algebra.group.hom
/- we will probably need to import other files soon too, like `linear_algebra.finite_dimensional`. -/
-- set_option trace.simplify true
run_cmd mk_simp_attr `RW_REP
meta def rw_simp : tactic unit :=
`[ try {simp only with RW_REP}, try {exact rfl}]
run_cmd add_interactive [`rw_simp]
universe variables u v w w'
class has_coe_inv (a : Sort u) (b : Sort v) :=
(coe : a → b)
notation `inv`:max x:max := has_coe_inv
open group
open linear_map
open linear_equiv
open submodule
open linear_map.general_linear_group
/-
I thinck i add three lemma into mathlib line 1922 at the file linear_algebra.bassic
def to_linear_map (f : general_linear_group R M) : M →ₗ[R] M :=(to_linear_equiv f).to_linear_map
def to_linear_map_inv (f : general_linear_group R M) :
M →ₗ[R] M := (to_linear_equiv f⁻¹).to_linear_map
def to_fun (f : general_linear_group R M) : M → M := f.val
-/
attribute [RW_REP] coe_add coe_neg coe_smul coe_mk subtype.eta eq.symm
namespace NOTATION
notation `GL` := general_linear_group
notation `L`:80 f :80 := general_linear_group.to_linear_map f
notation `F`:80 f :82 := general_linear_group.to_fun f --- add in mathlib
notation a` ⊚ `:80 b:80 := linear_map.comp a b
end NOTATION
/- maybe needs a shorter name -/
/-- A representation of a group `G` is an `R`-module `M` with a group homomorphisme from `G` to
`GL(M)`. Normally `M` is a vector space, but we don't need that for the definition. -/
def group_representation (G R M : Type*) [group G] [ring R] [add_comm_group M] [module R M] :
Type* := G →* GL R M
-- open NOTATION
variables {G : Type u} {R : Type v} {M : Type w} {M' : Type w'}
[group G] [ring R] [add_comm_group M] [module R M] [add_comm_group M'] [module R M']
instance : has_coe_to_fun (group_representation G R M) := ⟨_, λ g, g.to_fun⟩ ---
def has_coe_to (ρ : group_representation G R M) : G → (M →ₗ[R] M ) := λ g, L ρ g
notation `⟦` ρ `⟧` := has_coe_to ρ
namespace MY_TEST
variables (f : M →ₗ[R] M) ( x y : M)
variables (ρ : group_representation G R M)
include ρ
example : f (x+ y) = f(x)+f(y) := f.add x y
@[RW_REP] theorem linearity (g : G ) (x y : M): ⟦ ρ ⟧ g (x+y) = ⟦ρ⟧ g (x) + ⟦ρ⟧ g (y) :=
begin exact (⟦ρ⟧ g).add x y end
@[RW_REP] theorem smul' (g : G) (r : R)(m : M) : (⟦ ρ⟧ g) (r • m) = r • ((⟦ ρ ⟧ g) m) := begin
exact ( ⟦ ρ ⟧ g).smul r m,
end
variables (g g' : G)
variables (p : submodule R M)
@[RW_REP]lemma F_linearity (x y : M) (g : G) : (F ρ g) (x+y) = (F ρ g) x + (F ρ g) y := begin
exact ( L ρ g).add x y, --- the same for L !
end
variables (h : ∀ x : M, ∀ g : G, (L ρ g) x ∈ p)
--- le mécanisme est le suivant :
--- ρ : G →* GL R M
--- le problème étant que :: c'est un morphsime de groupe mais c'est une structure
--- GL R M donc convertion merdique via L
--- Il y a ⇑
theorem L_to_F (g : G) : (F ρ g) = ⟦ρ⟧ g := rfl
example (ρ : group_representation G R M) ( g g' : G) : ρ (g * g') = ρ g * ρ g' := ρ.map_mul g g'
@[RW_REP]lemma rmap_mul (ρ : group_representation G R M) ( g g' : G) :
⟦ ρ ⟧ (g * g') = ⟦ρ⟧ g ⊚ ⟦ ρ ⟧ g' :=
begin
ext, rw comp_apply, iterate 3 {rw ← L_to_F}, rw ρ.map_mul,exact rfl,
end
-- @[RW_REP]lemma rmap_mul' (ρ : group_representation G R M) ( g g' : G) :
-- ⟦ρ⟧ g ⊚ ⟦ ρ ⟧ g' = ⟦ ρ ⟧ (g * g') :=
-- begin
-- ext, rw comp_apply, iterate 3{rw ← L_to_F}, rw ρ.map_mul,exact rfl,
-- end
@[RW_REP] lemma rmap_one (ρ : group_representation G R M) :
⟦ ρ ⟧ (1) = linear_map.id := begin
ext,rw ← L_to_F,rw ρ.map_one,exact rfl,
end
@[RW_REP] lemma rmap_inv_mul (ρ : group_representation G R M)(g: G) :
⟦ ρ ⟧ (g * g⁻¹ ) = linear_map.id := begin
rw mul_inv_self,exact rmap_one ρ,
end
@[RW_REP] lemma rmap_mul_inv (ρ : group_representation G R M)(g: G) :
⟦ ρ ⟧ (g⁻¹ * g ) = linear_map.id := begin
rw inv_mul_self,exact rmap_one ρ,
end
@[RW_REP] lemma rmap_inv' (ρ : group_representation G R M) (g : G) :
⟦ρ⟧ g ⊚ ⟦ ρ ⟧ g⁻¹ = linear_map.id := begin
rw ← rmap_mul,exact rmap_inv_mul ρ g,
end
@[RW_REP] lemma rmap_inv''(ρ : group_representation G R M) (g : G) :
⟦ρ⟧ g⁻¹ ⊚ ⟦ ρ ⟧ g = linear_map.id := begin
rw ← rmap_mul,exact rmap_mul_inv ρ g ,
end
@[RW_REP] lemma rmap_inv_apply'' (ρ : group_representation G R M) (g : G)(x : M) :
(⟦ρ⟧ g⁻¹ ⊚ ⟦ ρ ⟧ g ) x = x := begin
rw rmap_inv'',exact rfl,
end
@[RW_REP] lemma rmap_inv_apply' (ρ : group_representation G R M) (g : G)(x : M) :
(⟦ρ⟧ g ⊚ ⟦ ρ ⟧ g⁻¹ ) x = x := begin
rw rmap_inv',exact rfl,
end
def has_inv (ρ : group_representation G R M)(g : G) : M ≃ₗ[R] M := {
to_fun := ⟦ ρ ⟧ g ,
add := linearity ρ g ,
smul := smul' ρ g,
inv_fun := ⟦ ρ ⟧ g⁻¹,
left_inv := rmap_inv_apply'' ρ g,
right_inv := rmap_inv_apply' ρ g
}
-- @[RW_REP] lemma rmap_inv (ρ : group_representation G R M)(g : G) : -- 207
-- ⟦ ρ ⟧ g⁻¹ = to_linear_map_inv (has_inv' ρ g ) := begin
-- ext,
-- sorry,
-- end
@[RW_REP]lemma star_is_oo (ρ : group_representation G R M) ( g g' : G) :
⟦ρ⟧ g ⊚ ⟦ ρ ⟧ g' = ⟦ρ⟧ g * ⟦ ρ ⟧ g' := by rw_simp
@[RW_REP]lemma rmap_map_assoc (ρ : group_representation G R M)( g1 g2 g3 : G) : ⟦ρ⟧ (g1 * g2 *g3) =
⟦ρ⟧ (g1) ⊚ (⟦ρ⟧ g2 ⊚ ⟦ρ⟧ g3) :=
begin
rw group.mul_assoc,rw rmap_mul,rw rmap_mul,
-- rw_simp,
end
example (ρ : group_representation G R M)( g1 g2 g3 g4 : G) : ⟦ρ⟧ (g1 * (g2 *g3 * g4)) =
⟦ρ⟧ (g1) ⊚ (⟦ρ⟧ g2 ⊚ ⟦ρ⟧ g3) * ⟦ ρ ⟧ g4 :=
begin
rw_simp,
end
@[RW_REP]lemma times_to_oo (ρ : group_representation G R M)( g g' : G) : ⟦ ρ ⟧ (g * g') = ⟦ρ⟧ g * ⟦ ρ ⟧ g' := begin
rw_simp,
end
example (ρ : group_representation G R M)( g1 g2 g3 : G) : ⟦ρ⟧ (g1 * g2 *g3) =
⟦ρ⟧ (g1) ⊚ ⟦ρ⟧ g2 * ⟦ρ⟧ g3 :=
begin
rw_simp,
end
@[RW_REP]lemma mul_to_composition_of_function (ρ : group_representation G R M) ( g g' : G) :
⟦ ρ⟧ (g * g') = ( ⟦ ρ⟧ g ) * (⟦ ρ ⟧ g') := begin
rw_simp,
end
@[RW_REP]lemma mixte_linearity (ρ : group_representation G R M) ( g g' : G) (x y : M) (r : R):
⟦ ρ⟧ (g * g') (x+r • y) = ⟦ ρ ⟧ g ( ⟦ ρ ⟧ g' x )+ r • ⟦ ρ ⟧ g ( ⟦ ρ ⟧ g' y ) := begin
iterate 2 {rw ← comp_apply},rw_simp, rw ← rmap_mul,
end
-- @[RW_REP]lemma L_to_F (g : G) : (L ρ g).to_fun = (F ρ g) := rfl
example : ⟦ ρ ⟧ (g * g') = (L ρ g) ⊚ (L ρ g') := by rw_simp
lemma mul_one (ρ : group_representation G R M) : (L ρ 1) = 1 := begin
rw ρ.map_one, exact rfl,
end
instance has_coe_too : -----------------
is_monoid_hom (has_coe_to ρ : G → (M →ₗ[R] M)) :=
{ map_one := rmap_one ρ,
map_mul := rmap_mul ρ}
def new_groupe_representation :
( group_representation G R M) → G →* (M →ₗ[R] M) := λ ρ, { to_fun := ⟦ρ⟧ ,
map_one' := by rw_simp,
map_mul' := by {intros,rw_simp} }
end MY_TEST
namespace group_representation
/- do we want this instance? Then we don't have to write `(ρ g).1 x` instead of `ρ g x`. -/
-- instance : has_coe (general_linear_group R M) (M →ₗ[R] M) := ⟨λ x, x.1⟩
protected structure morphism (ρ : group_representation G R M) (π : group_representation G R M') :
Type (max w w') :=
(linear_map : M →ₗ[R] M')
(commute : ∀(g : G), linear_map ⊚ (⟦ ρ ⟧ g) = (⟦ π ⟧ g) ⊚ linear_map)
infixr ` ⟶₁ `:25 := morphism
protected structure equiv (ρ : group_representation G R M) (π : group_representation G R M') :
Type (max w w') :=
(f : M ≃ₗ[R] M')
(commute : ∀(g : G), to_linear_map f ⊚ ⟦ ρ ⟧ g = ⟦π⟧ g ⊚ to_linear_map f)
variables (ρ : group_representation G R M) (π : group_representation G R M')
instance has_coe_to_linear_map : has_coe (equiv ρ π) (M →ₗ[R] M') := ⟨λ φ ,to_linear_map φ.f⟩
lemma coe (φ : equiv ρ π ) : ↑φ = to_linear_map φ.f := rfl
lemma coe_ext (φ : equiv ρ π )(g : G) : (↑φ) ⊚ (⟦ρ⟧ g)= (⟦π ⟧ g) ⊚ (↑φ) := begin
rw coe,rw φ.commute,
end
#print has_coe
#print has_inv
instance inverse : has_coe_inv (equiv ρ π) (M' →ₗ[R] M) := ⟨ λ φ, to_linear_map φ.f.symm ⟩
lemma coe_inv (φ : equiv ρ π ) : ↑φ = to_linear_map φ.f.symm := rfl
lemma heye (ρ : group_representation G R M) (π : group_representation G R M') (φ : equiv ρ π ) :
( φ : M' →ₗ[R] M) ⊚ (↑φ) = (linear_map.id : M →ₗ[R] M) :=
begin
sorry,
end
variables (g g' : G)(x : M)
-- example (x y : M) (g : G) : ρ g (x+y)= ρ g x + ρ g y := begin rw (L ρ g).add x y, end
namespace stability
/-
We define the notion of stable submodule.
We make a sub-representation.
ligne 384 algebra module submodule (conduit)
il y a des lemmes de convertions.
-/
variables {ρ1 : group_representation G R M}{p : submodule R M}
/-
Strategy maths : We have ρ g x ∈ p for x ∈ p so
you have a map : ρ' g : p → p ... linear_map, invertible (restriction of ρ g⁻¹ ) and trivial trivial trivial
For lean : this is not trivial. We have to verify some stuff.
Lemma to try to deal with convertion
-/
@[RW_REP]lemma sub_module.eq_trans (x y : M) (hx : x ∈ p)(hy : y ∈ p) :
(x : M) = (y : M) → (⟨x,hx⟩ : p) = (⟨ y,hy⟩ : p ) := begin
intros,congr ; try { assumption },
end
@[RW_REP] lemma sub_module.eq_trans' (x y : p) : (x : M) = (y : M) → x = y := begin
intros,rcases x,rcases y,congr; try {assumption},
end
-- lemma sub_module_val (x : M) (hx : x ∈ p) : (⟨x,hx ⟩ : p).val = (x : M) := rfl
def stable_sub_module (ρ : group_representation G R M)(p : submodule R M) :=
∀ g : G, ∀ x : p, ( ⟦ ρ ⟧ g) x ∈ p
/-
First Step : we define G → (p →ₗ[R] p)
-/
def restriction (hyp_stab : stable_sub_module ρ p) : G → (p →ₗ[R] p) := λ g, begin
exact {
to_fun := λ x, ⟨( ⟦ ρ⟧ g ) x, hyp_stab g x⟩,
add := by {intros x y, rw_simp},
smul := by {intro c, intros x, rw_simp},
},
end
open MY_TEST
@[RW_REP]lemma restriction_ext (h : stable_sub_module ρ p) (y : p)
: (( ⟦ρ⟧ g) y : M ) = (restriction ρ h g y : M) := rfl
@[RW_REP]lemma restriction_ext' (h : stable_sub_module ρ p) (y : p)
: (restriction ρ h g y : M) = (( ⟦ρ⟧ g) y : M ) := rfl
def restriction_equiv (h : stable_sub_module ρ p) (g : G) : (p ≃ p) :=
{ to_fun := (restriction ρ h g),
inv_fun := (restriction ρ h g⁻¹),
left_inv := begin
intros x,
apply sub_module.eq_trans',
iterate 2 {rw ← restriction_ext},
rw ← comp_apply,
apply rmap_inv_apply'',
-- rw [← comp_apply,← mul_to_composition_of_linear_map, inv_mul_self, ρ.map_one],
-- exact rfl,end,
end
, right_inv := begin
intros x,
apply sub_module.eq_trans',
iterate 2 {rw ← restriction_ext},
rw ← comp_apply,
apply rmap_inv_apply',
end }
def Restriction (h : stable_sub_module ρ p) (g : G) : p ≃ₗ[R] p :=
{ .. restriction ρ h g, .. restriction_equiv ρ h g}
/-
Helper rfl
-/
def sub_representation (h : stable_sub_module ρ p) : group_representation G R p :=
{ to_fun := λ g, of_linear_equiv (Restriction ρ h g),
map_one' := begin
rw units.ext_iff, --- Creer un helper pour la sous structure car c'est chiant
ext,rcases x,
apply sub_module.eq_trans,
rw rmap_one,exact rfl,
end,
map_mul' := begin intros g1 g2,rw units.ext_iff, ext, rcases x,
apply sub_module.eq_trans,rw_simp,rw of_linear_equiv_val,
rw rmap_mul,
rw comp_apply, exact rfl,
end }
variables (h : stable_sub_module ρ p)
#check sub_representation ρ h
notation ρ `/`h := sub_representation ρ h
#check ⟦ ρ / h⟧ g
@[RW_REP]lemma sub_representation.val (ρ : group_representation G R M) (h : stable_sub_module ρ p)( x : p) :
(⟦ρ⟧ g ) x.val = ( ⟦ ρ / h ⟧ g) x := rfl
@[RW_REP] lemma rw_sub_module_action_to (ρ : group_representation G R M) (h : stable_sub_module ρ p) (x : p) :
(⟦ρ ⟧ g) x = ⟦ρ / h⟧ g x :=
begin
-- rw_simp, --- joke :D
exact rfl,
end
example (ρ : group_representation G R M) (h : stable_sub_module ρ p) (x y : p)(r : R) (g g' : G): true :=
begin
have R : ⟦ ρ ⟧ g ( ⟦ ρ ⟧ g' x )+ r • ⟦ ρ ⟧ g ( ⟦ ρ ⟧ g' y ) = ⟦ ρ / h ⟧ (g * g') (x+ r • y),
iterate 2 {rw ← comp_apply}, rw ← rmap_mul,rw ← smul',rw ← linearity,rw_simp,
trivial,
end
variables ( e r t : ( (M →ₗ[R] M)))
#check e*t
end stability
namespace sum
/-
Define direct sum of representation
-/
end sum
end group_representation |
530daa4a823030202dd964bb972c2f252cb4df05 | 271e26e338b0c14544a889c31c30b39c989f2e0f | /stage0/src/Init/Lean/Util/Message.lean | 6e7e5b95311f8c4fd65a558a7d9f6ea9c000bfdd | [
"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 | 6,324 | lean | /-
Copyright (c) 2018 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Sebastian Ullrich, Leonardo de Moura
Message Type used by the Lean frontend
-/
prelude
import Init.Data.ToString
import Init.Lean.Data.Position
import Init.Lean.Syntax
import Init.Lean.MetavarContext
import Init.Lean.Environment
namespace Lean
def mkErrorStringWithPos (fileName : String) (line col : Nat) (msg : String) : String :=
fileName ++ ":" ++ toString line ++ ":" ++ toString col ++ " " ++ toString msg
inductive MessageSeverity
| information | warning | error
structure MessageDataContext :=
(env : Environment) (mctx : MetavarContext) (lctx : LocalContext) (opts : Options)
/- Structure message data. We use it for reporting errors, trace messages, etc. -/
inductive MessageData
| ofFormat : Format → MessageData
| ofSyntax : Syntax → MessageData
| ofExpr : Expr → MessageData
| ofLevel : Level → MessageData
| ofName : Name → MessageData
/- `withContext ctx d` specifies the pretty printing context `(env, mctx, lctx, opts)` for the nested expressions in `d`. -/
| withContext : MessageDataContext → MessageData → MessageData
/- Lifted `Format.nest` -/
| nest : Nat → MessageData → MessageData
/- Lifted `Format.group` -/
| group : MessageData → MessageData
/- Lifted `Format.compose` -/
| compose : MessageData → MessageData → MessageData
/- Tagged sections. `Name` should be viewed as a "kind", and is used by `MessageData` inspector functions.
Example: an inspector that tries to find "definitional equality failures" may look for the tag "DefEqFailure". -/
| tagged : Name → MessageData → MessageData
| node : Array MessageData → MessageData
namespace MessageData
instance : Inhabited MessageData := ⟨MessageData.ofFormat (arbitrary _)⟩
@[init] def stxMaxDepthOption : IO Unit :=
registerOption `syntaxMaxDepth { defValue := (2 : Nat), group := "", descr := "maximum depth when displaying syntax objects in messages" }
def getSyntaxMaxDepth (opts : Options) : Nat :=
opts.getNat `syntaxMaxDepth 2
partial def formatAux : Option MessageDataContext → MessageData → Format
| _, ofFormat fmt => fmt
| _, ofLevel u => fmt u
| _, ofName n => fmt n
| some ctx, ofSyntax s => s.formatStx (getSyntaxMaxDepth ctx.opts)
| none, ofSyntax s => s.formatStx
| none, ofExpr e => format (toString e)
| some ctx, ofExpr e => format (toString (ctx.mctx.instantiateMVars e).1) -- TODO: invoke pretty printer
| _, withContext ctx d => formatAux (some ctx) d
| ctx, tagged cls d => Format.sbracket (format cls) ++ " " ++ formatAux ctx d
| ctx, nest n d => Format.nest n (formatAux ctx d)
| ctx, compose d₁ d₂ => formatAux ctx d₁ ++ formatAux ctx d₂
| ctx, group d => Format.group (formatAux ctx d)
| ctx, node ds => Format.nest 2 $ ds.foldl (fun r d => r ++ Format.line ++ formatAux ctx d) Format.nil
instance : HasAppend MessageData := ⟨compose⟩
instance : HasFormat MessageData := ⟨fun d => formatAux none d⟩
instance coeOfFormat : HasCoe Format MessageData := ⟨ofFormat⟩
instance coeOfLevel : HasCoe Level MessageData := ⟨ofLevel⟩
instance coeOfExpr : HasCoe Expr MessageData := ⟨ofExpr⟩
instance coeOfName : HasCoe Name MessageData := ⟨ofName⟩
instance coeOfSyntax : HasCoe Syntax MessageData := ⟨ofSyntax⟩
instance coeOfOptExpr : HasCoe (Option Expr) MessageData :=
⟨fun o => match o with | none => "none" | some e => ofExpr e⟩
partial def arrayExpr.toMessageData (es : Array Expr) : Nat → MessageData → MessageData
| i, acc =>
if h : i < es.size then
let e := es.get ⟨i, h⟩;
let acc := if i == 0 then acc ++ ofExpr e else acc ++ ", " ++ ofExpr e;
arrayExpr.toMessageData (i+1) acc
else
acc ++ "]"
instance coeOfArrayExpr : HasCoe (Array Expr) MessageData := ⟨fun es => arrayExpr.toMessageData es 0 "#["⟩
def bracket (l : String) (f : MessageData) (r : String) : MessageData := group (nest l.length $ l ++ f ++ r)
def paren (f : MessageData) : MessageData := bracket "(" f ")"
def sbracket (f : MessageData) : MessageData := bracket "[" f "]"
def joinSep : List MessageData → MessageData → MessageData
| [], sep => Format.nil
| [a], sep => a
| a::as, sep => a ++ sep ++ joinSep as sep
def ofList: List MessageData → MessageData
| [] => "[]"
| xs => sbracket $ joinSep xs ("," ++ Format.line)
def ofArray (msgs : Array MessageData) : MessageData :=
ofList msgs.toList
end MessageData
structure Message :=
(fileName : String)
(pos : Position)
(endPos : Option Position := none)
(severity : MessageSeverity := MessageSeverity.error)
(caption : String := "")
(data : MessageData)
namespace Message
protected def toString (msg : Message) : String :=
mkErrorStringWithPos msg.fileName msg.pos.line msg.pos.column
((match msg.severity with
| MessageSeverity.information => ""
| MessageSeverity.warning => "warning: "
| MessageSeverity.error => "error: ") ++
(if msg.caption == "" then "" else msg.caption ++ ":\n") ++ toString (fmt msg.data))
instance : Inhabited Message :=
⟨{ fileName := "", pos := ⟨0, 1⟩, data := arbitrary _}⟩
instance : HasToString Message :=
⟨Message.toString⟩
end Message
structure MessageLog :=
(msgs : PersistentArray Message := {})
namespace MessageLog
def empty : MessageLog := ⟨{}⟩
def isEmpty (log : MessageLog) : Bool :=
log.msgs.isEmpty
instance : Inhabited MessageLog := ⟨{}⟩
def add (msg : Message) (log : MessageLog) : MessageLog :=
⟨log.msgs.push msg⟩
protected def append (l₁ l₂ : MessageLog) : MessageLog :=
⟨l₁.msgs ++ l₂.msgs⟩
instance : HasAppend MessageLog :=
⟨MessageLog.append⟩
def hasErrors (log : MessageLog) : Bool :=
log.msgs.any $ fun m => match m.severity with
| MessageSeverity.error => true
| _ => false
def forM {m : Type → Type} [Monad m] (log : MessageLog) (f : Message → m Unit) : m Unit :=
log.msgs.forM f
def toList (log : MessageLog) : List Message :=
(log.msgs.foldl (fun acc msg => msg :: acc) []).reverse
end MessageLog
end Lean
|
7efabcf7719fb71c8e2d2be76690f8c1c7f205d0 | 5a5e1bb8063d7934afac91f30aa17c715821040b | /lean3SOS/src/test/test.lean | 608bd5201a2948178a4716a9f95ac23b0562f1fd | [] | no_license | ramonfmir/leanSOS | 1883392d73710db5c6e291a2abd03a6c5b44a42b | 14b50713dc887f6d408b7b2bce1f8af5bb619958 | refs/heads/main | 1,683,348,826,105 | 1,622,056,982,000 | 1,622,056,982,000 | 341,232,766 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 4,344 | lean | /-
Testing out the tactic.
-/
import tactic.ring2
import tactic.ring
import tactic.show_term
import data.real.basic
import data.mv_polynomial.basic
import lib.poly lib.psd .sos float.basic
open mv_polynomial poly
-- Test intermediate steps.
-- noncomputable def p : mv_polynomial ℕ ℝ := (X 1) * (X 1)
-- noncomputable def ms : fin 1 → mv_polynomial ℕ ℝ := λ _, X 1
-- def Q : fin 1 → fin 1 → ℝ := λ _ _, 1
-- lemma Qsymmetric : matrix.symmetric Q :=
-- by prove_symmetric
-- lemma Qsymmetric2 : matrix.symmetric (λ _ _, 1 : matrix (fin 1) (fin 1) ℝ) :=
-- by prove_symmetric
-- lemma Qmsp : p = matrix.dot_product ms (matrix.mul_vec (matrix.to_poly Q) ms) :=
-- by prove_poly_eq
-- lemma Qcholesky : @cholesky_decomposition (fin 1) _ (fin 1) _ ℝ _ Q Qsymmetric :=
-- by prove_cholesky ``(λ _ _, 1)
-- -- Experiments with the ring tactic.
-- example : (C 1) + (C 1) = ((C 2) : mv_polynomial ℕ ℝ) :=
-- begin
-- simp; ring,
-- end
-- example : (X 1) + (X 1) = ((C 2) * (X 1) : mv_polynomial ℕ ℝ) :=
-- begin
-- simp; ring,
-- end
-- example : finset.univ.sum (λ x : fin 2, (C 1 : mv_polynomial ℕ ℚ)) = C 2 :=
-- begin
-- simp,
-- end
-- example :
-- ((X 1) * (X 1) + (C 2) * (X 1) * (X 2) + (X 2) * (X 2) : mv_polynomial ℕ ℚ)
-- = matrix.dot_product
-- (list_to_vector 2 (list_to_monomials [[1], [2]]) (by simp))
-- ((matrix.to_poly
-- (list_to_matrix 2 2 [[1, 1], [1, 1]] (by simp) (λ i, by fin_cases i; simp))
-- : matrix (fin 2) (fin 2) (mv_polynomial ℕ ℚ)).mul_vec
-- (list_to_vector 2 (list_to_monomials [[1], [2]]) (by simp))) :=
-- begin
-- prove_poly_eq,
-- end
#check real.of_cauchy
set_option timeout 1000000
#eval if ((C (float.mk2 1 0)) = (1 : mv_polynomial ℕ float)) then 0 else 1
#eval if ((C (1 : ℝ)) = (1 : mv_polynomial ℕ ℝ)) then 0 else 1
example : (C (rat.of_int 1 : ℚ)) = (1 : mv_polynomial ℕ ℚ) :=
begin
refl,
end
example : (C (float.mk ⟨1, 0⟩)) = (1 : mv_polynomial ℕ float) :=
begin
show_term { refl, }
end
example : (C (1 : ℝ)) * (X 1) = (X 1 : mv_polynomial ℕ ℝ) :=
begin
simp,
end
example {α} [linear_ordered_comm_ring α]
: (C (1 : α)) * (X 1) = (X 1 : mv_polynomial ℕ α) :=
begin
show_term { simp, }
end
example : (C (rat.of_int 1 : ℚ)) * (X 1) = (X 1 : mv_polynomial ℕ ℚ) :=
begin
simp, sorry,
end
example : (C (1 : float)) * (X 1) = (X 1 : mv_polynomial ℕ float) :=
begin
simp,
end
example : (1 : float) • (X 1) = (X 1 : mv_polynomial ℕ float) :=
begin
show_term {
simp, }
end
#check one_smul
example : C (1 + 0) * (X 1) = (X 1 : mv_polynomial ℕ ℚ) :=
begin
simp,
end
@[simp] lemma avo : float.mk ⟨1, 0⟩ = 1 := rfl
example : (C (float.mk ⟨1, 0⟩)) * (X 1) = (X 1 : mv_polynomial ℕ float) :=
begin
simp,
end
example : (rat.of_int 1) + (rat.of_int 2) = rat.of_int 3 :=
begin
simp [rat.of_int], ring,
end
@[simp] theorem add_def (a b c d : ℤ)
: (float.mk ⟨a, b⟩) + (float.mk ⟨c, d⟩) =
float.mk (if b ≤ d
then ⟨a + c * 2 ^ int.to_nat (d - b), b⟩
else ⟨c + a * 2 ^ int.to_nat (b - d), d⟩ ) :=
begin
sorry,
end
example : (float.mk ⟨1, -1⟩) + (float.mk ⟨3, -1⟩) = float.mk ⟨2, 0⟩ :=
begin
simp [add_def], split_ifs; try {contradiction}, simp [float.mk], show to_rat _ = _,
simp [to_rat], norm_num,
end
example :
(C (float.mk ⟨1, 1⟩)) * (X 1) + (C (float.mk ⟨3, 1⟩)) * (X 1)
= (C (float.mk ⟨2, 0⟩)) * (X 1 : mv_polynomial ℕ float) :=
begin
simp, ring,
end
-- Test whole thing.
-- set_option trace.app_builder true
-- set_option timeout 1000000
#eval if (1 : ℕ) = 2 then 1 else 0
#eval if (((C (float.mk2 1 0)) : mv_polynomial ℕ float) = (C (1 : float))) then 1 else 0
-- 0 ≤ x^2
example : (C (0 : float)) ≤ (X 1) * (X 1) :=
begin
sos,
{ simp [matrix.dot_product, matrix.mul_vec, matrix.to_poly],
simp only [matrix.map, list.map, list.foldl, float.mk, list_to_vector,
list_to_monomials, list_to_matrix, list_to_monomial, fin.sum_univ_succ], dsimp,
ring, sorry, },
sorry,
end
-- 0 ≤ x^2 + 2xy + y^2
example : (C (0 : ℚ)) ≤ (((X 1) * (X 1)) + ((C 2) * (X 1) * (X 2)) + ((X 2) * (X 2)) : mv_polynomial ℕ ℚ) :=
begin
--sos,
sorry,
end
-- 0 ≤ 1 + x + x^2 ([[1,1/2],[1,1/2]])
|
24b94d7bcbd6dc510a71855a76e4a5af9ca2747c | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/algebra/field.lean | 3143a720d93a0137d35858f147b0002075af4e38 | [
"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 | 14,110 | 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, Johannes Hölzl, Mario Carneiro
-/
import algebra.ring.basic
import algebra.group_with_zero
/-!
# Fields and division rings
This file introduces fields and division rings (also known as skewfields) and proves some basic
statements about them. For a more extensive theory of fields, see the `field_theory` folder.
## Main definitions
* `division_ring`: introduces the notion of a division ring as a `ring` such that `0 ≠ 1` and
`a * a⁻¹ = 1` for `a ≠ 0`
* `field`: a division ring which is also a commutative ring.
* `is_field`: a predicate on a ring that it is a field, i.e. that the multiplication is commutative,
that it has more than one element and that all non-zero elements have a multiplicative inverse.
In contrast to `field`, which contains the data of a function associating to an element of the
field its multiplicative inverse, this predicate only assumes the existence and can therefore more
easily be used to e.g. transfer along ring isomorphisms.
## Implementation details
By convention `0⁻¹ = 0` in a field or division ring. This is due to the fact that working with total
functions has the advantage of not constantly having to check that `x ≠ 0` when writing `x⁻¹`. With
this convention in place, some statements like `(a + b) * c⁻¹ = a * c⁻¹ + b * c⁻¹` still remain
true, while others like the defining property `a * a⁻¹ = 1` need the assumption `a ≠ 0`. If you are
a beginner in using Lean and are confused by that, you can read more about why this convention is
taken in Kevin Buzzard's
[blogpost](https://xenaproject.wordpress.com/2020/07/05/division-by-zero-in-type-theory-a-faq/)
A division ring or field is an example of a `group_with_zero`. If you cannot find
a division ring / field lemma that does not involve `+`, you can try looking for
a `group_with_zero` lemma instead.
## Tags
field, division ring, skew field, skew-field, skewfield
-/
open set
set_option old_structure_cmd true
universe u
variables {K : Type u}
/-- A `division_ring` is a `ring` with multiplicative inverses for nonzero elements -/
@[protect_proj, ancestor ring div_inv_monoid nontrivial]
class division_ring (K : Type u) extends ring K, div_inv_monoid K, nontrivial K :=
(mul_inv_cancel : ∀ {a : K}, a ≠ 0 → a * a⁻¹ = 1)
(inv_zero : (0 : K)⁻¹ = 0)
section division_ring
variables [division_ring K] {a b : K}
/-- Every division ring is a `group_with_zero`. -/
@[priority 100] -- see Note [lower instance priority]
instance division_ring.to_group_with_zero :
group_with_zero K :=
{ .. ‹division_ring K›,
.. (infer_instance : semiring K) }
lemma inverse_eq_has_inv : (ring.inverse : K → K) = has_inv.inv :=
begin
ext x,
by_cases hx : x = 0,
{ simp [hx] },
{ exact ring.inverse_unit (units.mk0 x hx) }
end
attribute [field_simps] inv_eq_one_div
local attribute [simp]
division_def mul_comm mul_assoc
mul_left_comm mul_inv_cancel inv_mul_cancel
lemma one_div_neg_one_eq_neg_one : (1:K) / (-1) = -1 :=
have (-1) * (-1) = (1:K), by rw [neg_mul_neg, one_mul],
eq.symm (eq_one_div_of_mul_eq_one this)
lemma one_div_neg_eq_neg_one_div (a : K) : 1 / (- a) = - (1 / a) :=
calc
1 / (- a) = 1 / ((-1) * a) : by rw neg_eq_neg_one_mul
... = (1 / a) * (1 / (- 1)) : by rw one_div_mul_one_div_rev
... = (1 / a) * (-1) : by rw one_div_neg_one_eq_neg_one
... = - (1 / a) : by rw [mul_neg_eq_neg_mul_symm, mul_one]
lemma div_neg_eq_neg_div (a b : K) : b / (- a) = - (b / a) :=
calc
b / (- a) = b * (1 / (- a)) : by rw [← inv_eq_one_div, division_def]
... = b * -(1 / a) : by rw one_div_neg_eq_neg_one_div
... = -(b * (1 / a)) : by rw neg_mul_eq_mul_neg
... = - (b / a) : by rw mul_one_div
lemma neg_div (a b : K) : (-b) / a = - (b / a) :=
by rw [neg_eq_neg_one_mul, mul_div_assoc, ← neg_eq_neg_one_mul]
@[field_simps] lemma neg_div' {K : Type*} [division_ring K] (a b : K) : - (b / a) = (-b) / a :=
by simp [neg_div]
lemma neg_div_neg_eq (a b : K) : (-a) / (-b) = a / b :=
by rw [div_neg_eq_neg_div, neg_div, neg_neg]
@[field_simps] lemma div_add_div_same (a b c : K) : a / c + b / c = (a + b) / c :=
by simpa only [div_eq_mul_inv] using (right_distrib a b (c⁻¹)).symm
lemma same_add_div {a b : K} (h : b ≠ 0) : (b + a) / b = 1 + a / b :=
by simpa only [← @div_self _ _ b h] using (div_add_div_same b a b).symm
lemma one_add_div {a b : K} (h : b ≠ 0 ) : 1 + a / b = (b + a) / b := (same_add_div h).symm
lemma div_add_same {a b : K} (h : b ≠ 0) : (a + b) / b = a / b + 1 :=
by simpa only [← @div_self _ _ b h] using (div_add_div_same a b b).symm
lemma div_add_one {a b : K} (h : b ≠ 0) : a / b + 1 = (a + b) / b := (div_add_same h).symm
lemma div_sub_div_same (a b c : K) : (a / c) - (b / c) = (a - b) / c :=
by rw [sub_eq_add_neg, ← neg_div, div_add_div_same, sub_eq_add_neg]
lemma same_sub_div {a b : K} (h : b ≠ 0) : (b - a) / b = 1 - a / b :=
by simpa only [← @div_self _ _ b h] using (div_sub_div_same b a b).symm
lemma one_sub_div {a b : K} (h : b ≠ 0) : 1 - a / b = (b - a) / b := (same_sub_div h).symm
lemma div_sub_same {a b : K} (h : b ≠ 0) : (a - b) / b = a / b - 1 :=
by simpa only [← @div_self _ _ b h] using (div_sub_div_same a b b).symm
lemma div_sub_one {a b : K} (h : b ≠ 0) : a / b - 1 = (a - b) / b := (div_sub_same h).symm
lemma neg_inv : - a⁻¹ = (- a)⁻¹ :=
by rw [inv_eq_one_div, inv_eq_one_div, div_neg_eq_neg_div]
lemma add_div (a b c : K) : (a + b) / c = a / c + b / c :=
(div_add_div_same _ _ _).symm
lemma sub_div (a b c : K) : (a - b) / c = a / c - b / c :=
(div_sub_div_same _ _ _).symm
lemma div_neg (a : K) : a / -b = -(a / b) :=
by rw [← div_neg_eq_neg_div]
lemma inv_neg : (-a)⁻¹ = -(a⁻¹) :=
by rw neg_inv
lemma one_div_mul_add_mul_one_div_eq_one_div_add_one_div (ha : a ≠ 0) (hb : b ≠ 0) :
(1 / a) * (a + b) * (1 / b) = 1 / a + 1 / b :=
by rw [(left_distrib (1 / a)), (one_div_mul_cancel ha), right_distrib, one_mul,
mul_assoc, (mul_one_div_cancel hb), mul_one, add_comm]
lemma one_div_mul_sub_mul_one_div_eq_one_div_add_one_div (ha : a ≠ 0) (hb : b ≠ 0) :
(1 / a) * (b - a) * (1 / b) = 1 / a - 1 / b :=
by rw [(mul_sub_left_distrib (1 / a)), (one_div_mul_cancel ha), mul_sub_right_distrib,
one_mul, mul_assoc, (mul_one_div_cancel hb), mul_one]
lemma add_div_eq_mul_add_div (a b : K) {c : K} (hc : c ≠ 0) : a + b / c = (a * c + b) / c :=
(eq_div_iff_mul_eq hc).2 $ by rw [right_distrib, (div_mul_cancel _ hc)]
@[priority 100] -- see Note [lower instance priority]
instance division_ring.to_domain : domain K :=
{ ..‹division_ring K›, ..(by apply_instance : semiring K),
..(by apply_instance : no_zero_divisors K) }
end division_ring
/-- A `field` is a `comm_ring` with multiplicative inverses for nonzero elements -/
@[protect_proj, ancestor comm_ring div_inv_monoid nontrivial]
class field (K : Type u) extends comm_ring K, div_inv_monoid K, nontrivial K :=
(mul_inv_cancel : ∀ {a : K}, a ≠ 0 → a * a⁻¹ = 1)
(inv_zero : (0 : K)⁻¹ = 0)
section field
variable [field K]
@[priority 100] -- see Note [lower instance priority]
instance field.to_division_ring : division_ring K :=
{ ..show field K, by apply_instance }
/-- Every field is a `comm_group_with_zero`. -/
@[priority 100] -- see Note [lower instance priority]
instance field.to_comm_group_with_zero :
comm_group_with_zero K :=
{ .. (_ : group_with_zero K), .. ‹field K› }
local attribute [simp] mul_assoc mul_comm mul_left_comm
lemma div_add_div (a : K) {b : K} (c : K) {d : K} (hb : b ≠ 0) (hd : d ≠ 0) :
(a / b) + (c / d) = ((a * d) + (b * c)) / (b * d) :=
by rw [← mul_div_mul_right _ b hd, ← mul_div_mul_left c d hb, div_add_div_same]
lemma one_div_add_one_div {a b : K} (ha : a ≠ 0) (hb : b ≠ 0) : 1 / a + 1 / b = (a + b) / (a * b) :=
by rw [div_add_div _ _ ha hb, one_mul, mul_one, add_comm]
@[field_simps] lemma div_sub_div (a : K) {b : K} (c : K) {d : K} (hb : b ≠ 0) (hd : d ≠ 0) :
(a / b) - (c / d) = ((a * d) - (b * c)) / (b * d) :=
begin
simp only [sub_eq_add_neg],
rw [neg_eq_neg_one_mul, ← mul_div_assoc, div_add_div _ _ hb hd,
← mul_assoc, mul_comm b, mul_assoc, ← neg_eq_neg_one_mul]
end
lemma inv_add_inv {a b : K} (ha : a ≠ 0) (hb : b ≠ 0) : a⁻¹ + b⁻¹ = (a + b) / (a * b) :=
by rw [inv_eq_one_div, inv_eq_one_div, one_div_add_one_div ha hb]
lemma inv_sub_inv {a b : K} (ha : a ≠ 0) (hb : b ≠ 0) : a⁻¹ - b⁻¹ = (b - a) / (a * b) :=
by rw [inv_eq_one_div, inv_eq_one_div, div_sub_div _ _ ha hb, one_mul, mul_one]
@[field_simps] lemma add_div' (a b c : K) (hc : c ≠ 0) : b + a / c = (b * c + a) / c :=
by simpa using div_add_div b a one_ne_zero hc
@[field_simps] lemma sub_div' (a b c : K) (hc : c ≠ 0) : b - a / c = (b * c - a) / c :=
by simpa using div_sub_div b a one_ne_zero hc
@[field_simps] lemma div_add' (a b c : K) (hc : c ≠ 0) : a / c + b = (a + b * c) / c :=
by rwa [add_comm, add_div', add_comm]
@[field_simps] lemma div_sub' (a b c : K) (hc : c ≠ 0) : a / c - b = (a - c * b) / c :=
by simpa using div_sub_div a b hc one_ne_zero
@[priority 100] -- see Note [lower instance priority]
instance field.to_integral_domain : integral_domain K :=
{ ..‹field K›, ..division_ring.to_domain }
end field
section is_field
/-- A predicate to express that a ring is a field.
This is mainly useful because such a predicate does not contain data,
and can therefore be easily transported along ring isomorphisms.
Additionaly, this is useful when trying to prove that
a particular ring structure extends to a field. -/
structure is_field (R : Type u) [ring R] : Prop :=
(exists_pair_ne : ∃ (x y : R), x ≠ y)
(mul_comm : ∀ (x y : R), x * y = y * x)
(mul_inv_cancel : ∀ {a : R}, a ≠ 0 → ∃ b, a * b = 1)
/-- Transferring from field to is_field -/
lemma field.to_is_field (R : Type u) [field R] : is_field R :=
{ mul_inv_cancel := λ a ha, ⟨a⁻¹, field.mul_inv_cancel ha⟩,
..‹field R› }
open_locale classical
/-- Transferring from is_field to field -/
noncomputable def is_field.to_field (R : Type u) [ring R] (h : is_field R) : field R :=
{ inv := λ a, if ha : a = 0 then 0 else classical.some (is_field.mul_inv_cancel h ha),
inv_zero := dif_pos rfl,
mul_inv_cancel := λ a ha,
begin
convert classical.some_spec (is_field.mul_inv_cancel h ha),
exact dif_neg ha
end,
.. ‹ring R›, ..h }
/-- For each field, and for each nonzero element of said field, there is a unique inverse.
Since `is_field` doesn't remember the data of an `inv` function and as such,
a lemma that there is a unique inverse could be useful.
-/
lemma uniq_inv_of_is_field (R : Type u) [ring R] (hf : is_field R) :
∀ (x : R), x ≠ 0 → ∃! (y : R), x * y = 1 :=
begin
intros x hx,
apply exists_unique_of_exists_of_unique,
{ exact hf.mul_inv_cancel hx },
{ intros y z hxy hxz,
calc y = y * (x * z) : by rw [hxz, mul_one]
... = (x * y) * z : by rw [← mul_assoc, hf.mul_comm y x]
... = z : by rw [hxy, one_mul] }
end
end is_field
namespace ring_hom
section
variables {R : Type*} [semiring R] [division_ring K] (f : R →+* K)
@[simp] lemma map_units_inv (u : units R) :
f ↑u⁻¹ = (f ↑u)⁻¹ :=
(f : R →* K).map_units_inv u
end
section
variables {R K' : Type*} [division_ring K] [semiring R] [nontrivial R] [division_ring K']
(f : K →+* R) (g : K →+* K') {x y : K}
lemma map_ne_zero : f x ≠ 0 ↔ x ≠ 0 := f.to_monoid_with_zero_hom.map_ne_zero
@[simp] lemma map_eq_zero : f x = 0 ↔ x = 0 := f.to_monoid_with_zero_hom.map_eq_zero
variables (x y)
lemma map_inv : g x⁻¹ = (g x)⁻¹ := g.to_monoid_with_zero_hom.map_inv' x
lemma map_div : g (x / y) = g x / g y := g.to_monoid_with_zero_hom.map_div x y
protected lemma injective : function.injective f := f.injective_iff.2 $ λ x, f.map_eq_zero.1
end
end ring_hom
section noncomputable_defs
variables {R : Type*} [nontrivial R]
/-- Constructs a `division_ring` structure on a `ring` consisting only of units and 0. -/
noncomputable def division_ring_of_is_unit_or_eq_zero [hR : ring R]
(h : ∀ (a : R), is_unit a ∨ a = 0) : division_ring R :=
{ .. (group_with_zero_of_is_unit_or_eq_zero h), .. hR }
/-- Constructs a `field` structure on a `comm_ring` consisting only of units and 0. -/
noncomputable def field_of_is_unit_or_eq_zero [hR : comm_ring R]
(h : ∀ (a : R), is_unit a ∨ a = 0) : field R :=
{ .. (group_with_zero_of_is_unit_or_eq_zero h), .. hR }
end noncomputable_defs
/-- Pullback a `division_ring` along an injective function.
See note [reducible non-instances]. -/
@[reducible]
protected def function.injective.division_ring [division_ring K] {K'}
[has_zero K'] [has_mul K'] [has_add K'] [has_neg K'] [has_sub K'] [has_one K'] [has_inv K']
[has_div K']
(f : K' → K) (hf : function.injective f) (zero : f 0 = 0) (one : f 1 = 1)
(add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y)
(neg : ∀ x, f (-x) = -f x) (sub : ∀ x y, f (x - y) = f x - f y)
(inv : ∀ x, f (x⁻¹) = (f x)⁻¹) (div : ∀ x y, f (x / y) = f x / f y) :
division_ring K' :=
{ .. hf.group_with_zero f zero one mul inv div,
.. hf.ring f zero one add mul neg sub }
/-- Pullback a `field` along an injective function.
See note [reducible non-instances]. -/
@[reducible]
protected def function.injective.field [field K] {K'}
[has_zero K'] [has_mul K'] [has_add K'] [has_neg K'] [has_sub K'] [has_one K'] [has_inv K']
[has_div K']
(f : K' → K) (hf : function.injective f) (zero : f 0 = 0) (one : f 1 = 1)
(add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y)
(neg : ∀ x, f (-x) = -f x) (sub : ∀ x y, f (x - y) = f x - f y)
(inv : ∀ x, f (x⁻¹) = (f x)⁻¹) (div : ∀ x y, f (x / y) = f x / f y) :
field K' :=
{ .. hf.comm_group_with_zero f zero one mul inv div,
.. hf.comm_ring f zero one add mul neg sub }
|
b5490a1983ef8bc17a793cb615de576fb4360cea | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/data/rbtree/basic.lean | fe262dbc6d7a58f4dcf0c654d81c17b83df84f34 | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 8,853 | lean | /-
Copyright (c) 2017 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import data.rbtree.init
import logic.is_empty
import tactic.interactive
universe u
meta def tactic.interactive.blast_disjs : tactic unit :=
`[cases_type* or]
namespace rbnode
variables {α : Type u}
open color nat
inductive is_node_of : rbnode α → rbnode α → α → rbnode α → Prop
| of_red (l v r) : is_node_of (red_node l v r) l v r
| of_black (l v r) : is_node_of (black_node l v r) l v r
def lift (lt : α → α → Prop) : option α → option α → Prop
| (some a) (some b) := lt a b
| _ _ := true
inductive is_searchable (lt : α → α → Prop) : rbnode α → option α → option α → Prop
| leaf_s {lo hi} (hlt : lift lt lo hi) : is_searchable leaf lo hi
| red_s {l r v lo hi} (hs₁ : is_searchable l lo (some v)) (hs₂ : is_searchable r (some v) hi) :
is_searchable (red_node l v r) lo hi
| black_s {l r v lo hi} (hs₁ : is_searchable l lo (some v)) (hs₂ : is_searchable r (some v) hi) :
is_searchable (black_node l v r) lo hi
meta def is_searchable_tactic : tactic unit :=
`[
constructor_matching*
[is_searchable _ leaf _ _,
is_searchable _ (red_node _ _ _) _ _,
is_searchable _ (black_node _ _ _) _ _];
cases_matching*
[is_searchable _ leaf _ _,
is_searchable _ (red_node _ _ _) _ _,
is_searchable _ (black_node _ _ _) _ _];
try { assumption }
]
open rbnode (mem)
open is_searchable
section is_searchable_lemmas
variable {lt : α → α → Prop}
lemma lo_lt_hi {t : rbnode α} {lt} [is_trans α lt] :
∀ {lo hi}, is_searchable lt t lo hi → lift lt lo hi :=
begin
induction t; intros lo hi hs,
case leaf { cases hs, assumption },
all_goals
{ cases hs,
have h₁ := t_ih_lchild hs_hs₁,
have h₂ := t_ih_rchild hs_hs₂,
cases lo; cases hi; simp [lift] at *,
apply trans_of lt h₁ h₂, }
end
lemma is_searchable_of_is_searchable_of_incomp [is_strict_weak_order α lt] {t} :
∀ {lo hi hi'} (hc : ¬ lt hi' hi ∧ ¬ lt hi hi') (hs : is_searchable lt t lo (some hi)),
is_searchable lt t lo (some hi') :=
begin
classical,
induction t; intros; is_searchable_tactic,
{ cases lo; simp [lift, *] at *, apply lt_of_lt_of_incomp, assumption, exact ⟨hc.2, hc.1⟩ },
all_goals { apply t_ih_rchild hc hs_hs₂ }
end
lemma is_searchable_of_incomp_of_is_searchable [is_strict_weak_order α lt] {t} :
∀ {lo lo' hi} (hc : ¬ lt lo' lo ∧ ¬ lt lo lo') (hs : is_searchable lt t (some lo) hi),
is_searchable lt t (some lo') hi :=
begin
classical,
induction t; intros; is_searchable_tactic,
{ cases hi; simp [lift, *] at *, apply lt_of_incomp_of_lt, assumption, assumption },
all_goals { apply t_ih_lchild hc hs_hs₁ }
end
lemma is_searchable_some_low_of_is_searchable_of_lt {t} [is_trans α lt] :
∀ {lo hi lo'} (hlt : lt lo' lo) (hs : is_searchable lt t (some lo) hi),
is_searchable lt t (some lo') hi :=
begin
induction t; intros; is_searchable_tactic,
{ cases hi; simp [lift, *] at *, apply trans_of lt hlt, assumption },
all_goals { apply t_ih_lchild hlt hs_hs₁ }
end
lemma is_searchable_none_low_of_is_searchable_some_low {t} :
∀ {y hi} (hlt : is_searchable lt t (some y) hi), is_searchable lt t none hi :=
begin
induction t; intros; is_searchable_tactic,
{ simp [lift] },
all_goals { apply t_ih_lchild hlt_hs₁ }
end
lemma is_searchable_some_high_of_is_searchable_of_lt {t} [is_trans α lt] :
∀ {lo hi hi'} (hlt : lt hi hi') (hs : is_searchable lt t lo (some hi)),
is_searchable lt t lo (some hi') :=
begin
induction t; intros; is_searchable_tactic,
{ cases lo; simp [lift, *] at *, apply trans_of lt, assumption, assumption},
all_goals { apply t_ih_rchild hlt hs_hs₂ }
end
lemma is_searchable_none_high_of_is_searchable_some_high {t} :
∀ {lo y} (hlt : is_searchable lt t lo (some y)), is_searchable lt t lo none :=
begin
induction t; intros; is_searchable_tactic,
{ cases lo; simp [lift] },
all_goals { apply t_ih_rchild hlt_hs₂ }
end
lemma range [is_strict_weak_order α lt] {t : rbnode α} {x} :
∀ {lo hi}, is_searchable lt t lo hi → mem lt x t → lift lt lo (some x) ∧ lift lt (some x) hi :=
begin
classical,
induction t,
case leaf { simp [mem] },
all_goals { -- red_node and black_node are identical
intros lo hi h₁ h₂, cases h₁,
simp only [mem] at h₂,
have val_hi : lift lt (some t_val) hi, { apply lo_lt_hi, assumption },
have lo_val : lift lt lo (some t_val), { apply lo_lt_hi, assumption },
blast_disjs,
{ have h₃ : lift lt lo (some x) ∧ lift lt (some x) (some t_val),
{ apply t_ih_lchild, assumption, assumption },
cases h₃ with lo_x x_val,
split,
show lift lt lo (some x), { assumption },
show lift lt (some x ) hi,
{ cases hi with hi; simp [lift] at *,
apply trans_of lt x_val val_hi } },
{ cases h₂,
cases lo with lo; cases hi with hi; simp [lift] at *,
{ apply lt_of_incomp_of_lt _ val_hi, simp [*] },
{ apply lt_of_lt_of_incomp lo_val, simp [*] },
split,
{ apply lt_of_lt_of_incomp lo_val, simp [*] },
{ apply lt_of_incomp_of_lt _ val_hi, simp [*] } },
{ have h₃ : lift lt (some t_val) (some x) ∧ lift lt (some x) hi,
{ apply t_ih_rchild, assumption, assumption },
cases h₃ with val_x x_hi,
cases lo with lo; cases hi with hi; simp [lift] at *,
{ assumption },
{ apply trans_of lt lo_val val_x },
split,
{ apply trans_of lt lo_val val_x, },
{ assumption } } }
end
lemma lt_of_mem_left [is_strict_weak_order α lt] {y : α} {t l r : rbnode α} :
∀ {lo hi}, is_searchable lt t lo hi → is_node_of t l y r → ∀ {x}, mem lt x l → lt x y :=
begin
intros _ _ hs hn x hm, cases hn; cases hs,
all_goals { exact (range hs_hs₁ hm).2 }
end
lemma lt_of_mem_right [is_strict_weak_order α lt] {y : α} {t l r : rbnode α} :
∀ {lo hi}, is_searchable lt t lo hi → is_node_of t l y r → ∀ {z}, mem lt z r → lt y z :=
begin
intros _ _ hs hn z hm, cases hn; cases hs,
all_goals { exact (range hs_hs₂ hm).1 }
end
lemma lt_of_mem_left_right [is_strict_weak_order α lt] {y : α} {t l r : rbnode α} :
∀ {lo hi}, is_searchable lt t lo hi → is_node_of t l y r →
∀ {x z}, mem lt x l → mem lt z r → lt x z :=
begin
intros _ _ hs hn x z hm₁ hm₂, cases hn; cases hs,
all_goals
{ have h₁ := range hs_hs₁ hm₁,
have h₂ := range hs_hs₂ hm₂,
exact trans_of lt h₁.2 h₂.1, }
end
end is_searchable_lemmas
inductive is_red_black : rbnode α → color → nat → Prop
| leaf_rb : is_red_black leaf black 0
| red_rb {v l r n} (rb_l : is_red_black l black n) (rb_r : is_red_black r black n) :
is_red_black (red_node l v r) red n
| black_rb {v l r n c₁ c₂} (rb_l : is_red_black l c₁ n) (rb_r : is_red_black r c₂ n) :
is_red_black (black_node l v r) black (succ n)
open is_red_black
lemma depth_min : ∀ {c n} {t : rbnode α}, is_red_black t c n → n ≤ depth min t :=
begin
intros c n' t h,
induction h,
case leaf_rb {exact le_refl _},
case red_rb { simp [depth],
have : min (depth min h_l) (depth min h_r) ≥ h_n,
{ apply le_min; assumption },
apply le_succ_of_le, assumption },
case black_rb { simp [depth],
apply succ_le_succ,
apply le_min; assumption }
end
private def upper : color → nat → nat
| red n := 2*n + 1
| black n := 2*n
private lemma upper_le : ∀ c n, upper c n ≤ 2 * n + 1
| red n := by exact le_refl _
| black n := by apply le_succ
lemma depth_max' : ∀ {c n} {t : rbnode α}, is_red_black t c n → depth max t ≤ upper c n :=
begin
intros c n' t h,
induction h,
case leaf_rb { simp [max, depth, upper, nat.mul_zero] },
case red_rb
{ suffices : succ (max (depth max h_l) (depth max h_r)) ≤ 2 * h_n + 1,
{ simp [depth, upper, *] at * },
apply succ_le_succ,
apply max_le; assumption },
case black_rb
{ have : depth max h_l ≤ 2*h_n + 1, from le_trans h_ih_rb_l (upper_le _ _),
have : depth max h_r ≤ 2*h_n + 1, from le_trans h_ih_rb_r (upper_le _ _),
suffices new : max (depth max h_l) (depth max h_r) + 1 ≤ 2 * h_n + 2*1,
{ simp [depth, upper, succ_eq_add_one, nat.left_distrib, *] at * },
apply succ_le_succ, apply max_le; assumption }
end
lemma depth_max {c n} {t : rbnode α} (h : is_red_black t c n) : depth max t ≤ 2 * n + 1:=
le_trans (depth_max' h) (upper_le _ _)
lemma balanced {c n} {t : rbnode α} (h : is_red_black t c n) : depth max t ≤ 2 * depth min t + 1 :=
begin
have : 2 * depth min t + 1 ≥ 2 * n + 1,
{ apply succ_le_succ, apply nat.mul_le_mul_left, apply depth_min h },
apply le_trans, apply depth_max h, apply this
end
end rbnode
|
9100d979387fbb115e72d07e3a3fe84e9b8e30e8 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/Lean3Lib/init/meta/default.lean | ff81e5f50713203ba677d1cd6be074a289487497 | [] | no_license | AurelienSaue/Mathlib4_auto | f538cfd0980f65a6361eadea39e6fc639e9dae14 | 590df64109b08190abe22358fabc3eae000943f2 | refs/heads/master | 1,683,906,849,776 | 1,622,564,669,000 | 1,622,564,669,000 | 371,723,747 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,911 | lean | /-
Copyright (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.meta.name
import Mathlib.Lean3Lib.init.meta.options
import Mathlib.Lean3Lib.init.meta.format
import Mathlib.Lean3Lib.init.meta.rb_map
import Mathlib.Lean3Lib.init.meta.level
import Mathlib.Lean3Lib.init.meta.expr
import Mathlib.Lean3Lib.init.meta.environment
import Mathlib.Lean3Lib.init.meta.attribute
import Mathlib.Lean3Lib.init.meta.tactic
import Mathlib.Lean3Lib.init.meta.contradiction_tactic
import Mathlib.Lean3Lib.init.meta.constructor_tactic
import Mathlib.Lean3Lib.init.meta.injection_tactic
import Mathlib.Lean3Lib.init.meta.relation_tactics
import Mathlib.Lean3Lib.init.meta.fun_info
import Mathlib.Lean3Lib.init.meta.congr_lemma
import Mathlib.Lean3Lib.init.meta.match_tactic
import Mathlib.Lean3Lib.init.meta.ac_tactics
import Mathlib.Lean3Lib.init.meta.backward
import Mathlib.Lean3Lib.init.meta.rewrite_tactic
import Mathlib.Lean3Lib.init.meta.derive
import Mathlib.Lean3Lib.init.meta.mk_dec_eq_instance
import Mathlib.Lean3Lib.init.meta.simp_tactic
import Mathlib.Lean3Lib.init.meta.set_get_option_tactics
import Mathlib.Lean3Lib.init.meta.interactive
import Mathlib.Lean3Lib.init.meta.converter.default
import Mathlib.Lean3Lib.init.meta.vm
import Mathlib.Lean3Lib.init.meta.comp_value_tactics
import Mathlib.Lean3Lib.init.meta.smt.default
import Mathlib.Lean3Lib.init.meta.async_tactic
import Mathlib.Lean3Lib.init.meta.ref
import Mathlib.Lean3Lib.init.meta.hole_command
import Mathlib.Lean3Lib.init.meta.congr_tactic
import Mathlib.Lean3Lib.init.meta.local_context
import Mathlib.Lean3Lib.init.meta.type_context
import Mathlib.Lean3Lib.init.meta.module_info
import Mathlib.Lean3Lib.init.meta.expr_address
import Mathlib.Lean3Lib.init.meta.tagged_format
namespace Mathlib
|
9118ce2f366fd8bc070e9049664f2511548afc9c | 59a4b050600ed7b3d5826a8478db0a9bdc190252 | /src/category_theory/currying_2.lean | 418df230b85545ade0bf49becad52a858ee15fcc | [] | no_license | rwbarton/lean-category-theory | f720268d800b62a25d69842ca7b5d27822f00652 | 00df814d463406b7a13a56f5dcda67758ba1b419 | refs/heads/master | 1,585,366,296,767 | 1,536,151,349,000 | 1,536,151,349,000 | 147,652,096 | 0 | 0 | null | 1,536,226,960,000 | 1,536,226,960,000 | null | UTF-8 | Lean | false | false | 1,652 | lean | -- import category_theory.currying
-- namespace category_theory
-- universes u₁ u₂ v₂
-- variables (C : Type u₁) [small_category C] (D : Type u₁) [small_category D] (E : Type u₂) [ℰ : category.{u₂ v₂} E]
-- include ℰ
-- local attribute [back] category.id -- this is usually a bad idea, but just what we needed here
-- def currying' : Equivalence (C ⥤ (D ⥤ E)) ((C × D) ⥤ E) :=
-- { functor := uncurry,
-- inverse := curry,
-- isomorphism_1 :=
-- { hom := { app := λ X, { app := λ Y, {
-- app := by obviously,
-- naturality := begin
-- tidy,
-- -- erw [category.assoc_lemma, category.comp_id_lemma, functor.map_id_lemma], refl,
-- -- 12/6/3 (old) vs 16/8/7 (new)
-- erw category.assoc_lemma,
-- erw category.comp_id_lemma,
-- erw functor.map_id_lemma,
-- refl,
-- -- erw category.assoc_lemma,
-- -- erw category.comp_id_lemma,
-- -- erw ←nat_trans.naturality_lemma,
-- -- erw functor.map_id_lemma,
-- -- erw category.comp_id_lemma,
-- -- erw category.id_comp_lemma,
-- rewrite_search_using [`search] {trace_result := tt, trace := tt, visualise := tt}
-- end },
-- naturality := sorry }, naturality := sorry },
-- inv := sorry,
-- hom_inv_id := sorry,
-- inv_hom_id := sorry },
-- isomorphism_2 := sorry }
-- set_option pp.proofs true
-- end category_theory |
fd873e9508d6136b1e35e152f2b1790da9023a41 | e07b1aca72e83a272dd59d24c6e0fa246034d774 | /src/tutorials/06_sub_sequences.lean | a68433c25ee4641d0b4512a60ccba3fb150b044e | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | pedrominicz/learn | 637a343bd4f8669d76819ac660a2d2d3e0958710 | b79b802a9846c86c21d4b6f3e17af36e7382f0ef | refs/heads/master | 1,671,746,990,402 | 1,670,778,113,000 | 1,670,778,113,000 | 265,735,177 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 6,287 | lean | import tuto_lib
/-
This file continues the elementary study of limits of sequences.
It can be skipped if the previous file was too easy, it won't introduce
any new tactic or trick.
Remember useful lemmas:
abs_le (x y : ℝ) : |x| ≤ y ↔ -y ≤ x ∧ x ≤ y
abs_add (x y : ℝ) : |x + y| ≤ |x| + |y|
abs_sub (x y : ℝ) : |x - y| = |y - x|
ge_max_iff (p q r) : r ≥ max p q ↔ r ≥ p ∧ r ≥ q
le_max_left p q : p ≤ max p q
le_max_right p q : q ≤ max p q
and the definition:
def seq_limit (u : ℕ → ℝ) (l : ℝ) : Prop :=
∀ ε > 0, ∃ N, ∀ n ≥ N, |u n - l| ≤ ε
You can also use a property proved in the previous file:
unique_limit : seq_limit u l → seq_limit u l' → l = l'
def extraction (φ : ℕ → ℕ) := ∀ n m, n < m → φ n < φ m
-/
variable {φ : ℕ → ℕ}
example : extraction φ → ∀ n, n ≤ φ n :=
begin
intros h n,
induction n with n hn,
{ exact nat.zero_le _ },
{ specialize h n (n+1) (by linarith),
exact nat.succ_le_of_lt (by linarith [h]) },
end
/-
The next lemma is proved by an easy induction, but we haven't seen induction
in this tutorial. If you did the natural number game then you can delete
the proof below and try to reconstruct it.
-/
/-- An extraction is greater than id -/
lemma id_le_extraction' : extraction φ → ∀ n, n ≤ φ n :=
begin
intros hyp n,
induction n with n hn,
{ exact nat.zero_le _ },
{ exact nat.succ_le_of_lt (by linarith [hyp n (n+1) (by linarith)]) },
end
/-- Extractions take arbitrarily large values for arbitrarily large
inputs. -/
-- 0039
lemma extraction_ge : extraction φ → ∀ N N', ∃ n ≥ N', φ n ≥ N :=
begin
intros h N N',
use max N N',
split,
{ exact le_sup_right },
{ transitivity max N N',
{ exact id_le_extraction' h (max N N') },
{ exact le_sup_left } }
end
/-- A real number `a` is a cluster point of a sequence `u`
if `u` has a subsequence converging to `a`.
def cluster_point (u : ℕ → ℝ) (a : ℝ) :=
∃ φ, extraction φ ∧ seq_limit (u ∘ φ) a
-/
variables {u : ℕ → ℝ} {a l : ℝ}
/-
In the exercise, we use `∃ n ≥ N, ...` which is the abbreviation of
`∃ n, n ≥ N ∧ ...`.
Lean can read this abbreviation, but displays it as the confusing:
`∃ (n : ℕ) (H : n ≥ N)`
One gets used to it. Alternatively, one can get rid of it using the lemma
exists_prop {p q : Prop} : (∃ (h : p), q) ↔ p ∧ q
-/
/-- If `a` is a cluster point of `u` then there are values of
`u` arbitrarily close to `a` for arbitrarily large input. -/
-- 0040
lemma near_cluster (h : cluster_point u a) :
∀ ε > 0, ∀ N, ∃ n ≥ N, |u n - a| ≤ ε :=
begin
intros ε ε_pos N,
rcases h with ⟨φ, h, hu⟩,
cases hu ε ε_pos with N' hN',
rcases extraction_ge h N N' with ⟨n, h, hn⟩,
exact ⟨φ n, hn, hN' n h⟩
end
/-
The above exercice can be done in five lines.
Hint: you can use the anonymous constructor syntax when proving
existential statements.
-/
--lemma extraction_ge : extraction φ → ∀ N N', ∃ n ≥ N', φ n ≥ N :=
/-- If `u` tends to `l` then its subsequences tend to `l`. -/
-- 0041
lemma subseq_tendsto_of_tendsto' (h : seq_limit u l) (hφ : extraction φ) :
seq_limit (u ∘ φ) l :=
begin
intros ε ε_pos,
cases h ε ε_pos with N hN,
use N,
intros n hn,
apply hN,
calc
N ≤ n : hn
... ≤ φ n : id_le_extraction hφ n
end
#find _ → (_ : ℝ) = _
/-- If `u` tends to `l` all its cluster points are equal to `l`. -/
-- 0042
lemma cluster_limit (hl : seq_limit u l) (ha : cluster_point u a) : a = l :=
begin
-- I will leave this proof unpolished and document my thought process. This
-- should be a simple question of applying the lemmas above. First, I will
-- unfold the definitions because I always struggle to remember them.
unfold seq_limit at hl,
unfold cluster_point at ha,
-- There is no reason why `ha` shouldn't be cased (except if you want to make
-- the proof small).
rcases ha with ⟨φ, hφ, hu⟩,
-- I just realized I don't know how to an `ℝ` equality. To the mathlib docs!
-- ...okay, the quick skim through the docs wasn't fruitful, neither was the
-- `#find` above.
--
-- And I cheated, I took a glimpse at the solution and it uses a lemma
-- used in the previous tutorial... Darn, I should have thought!
apply unique_limit hu,
-- Okay, now the problem got interesting!
unfold seq_limit at hu,
-- `seq_limit` in goal that means... `intros` time!
intros ε ε_pos,
cases hl ε ε_pos with N hN,
use φ N,
intros n hn,
-- Okay, everything from the last comment to here was pretty straight
-- forward. Now, it looks like the trick from the last lemma will suffice.
apply hN,
-- Firstly, `ge` sucks.
unfold ge at *,
calc
N ≤ φ N : id_le_extraction hφ N
... ≤ n : hn
... ≤ φ n : id_le_extraction hφ n
-- After writing `calc`, it was just a question of adding `by
-- library_search` at each step and accepting the solutions, because I am
-- lazy.
end
/-- Cauchy_sequence sequence -/
def cauchy_sequence (u : ℕ → ℝ) := ∀ ε > 0, ∃ N, ∀ p q, p ≥ N → q ≥ N → |u p - u q| ≤ ε
-- 0043
example : (∃ l, seq_limit u l) → cauchy_sequence u :=
begin
rintros ⟨l, hl⟩ ε ε_pos,
unfold seq_limit at hl,
cases hl (ε/2) (by linarith) with N hN,
use N,
intros p q hp hq,
have := hN p hp,
have := hN q hq,
calc
|u p - u q| ≤ |(u p - l) + (l - u q)| : by ring
... ≤ |u p - l| + |l - u q| : by apply abs_add
... ≤ |u p - l| + |u q - l| : by rw abs_sub (u q) l
... ≤ ε : by linarith,
end
/-
In the next exercise, you can reuse
near_cluster : cluster_point u a → ∀ ε > 0, ∀ N, ∃ n ≥ N, |u n - a| ≤ ε
-/
-- 0044
example (hu : cauchy_sequence u) (hl : cluster_point u l) : seq_limit u l :=
begin
intros ε ε_pos,
unfold cluster_point at hl,
cases hu (ε/2) (by linarith) with N hN,
rcases near_cluster hl (ε/2) (by linarith) N with ⟨N', hNN', hN'⟩,
use N,
intros n hn,
have := hN n N' hn hNN',
calc
|u n - l| ≤ |(u n - u N') + (u N' - l)| : by ring
... ≤ |u n - u N'| + |u N' - l| : by apply abs_add
... ≤ ε : by linarith,
end
|
43320e1e56caa6f8468a5a7c64442a6d6a593c6e | 4727251e0cd73359b15b664c3170e5d754078599 | /src/algebraic_topology/alternating_face_map_complex.lean | 2e2c7649b4e6e27ad19b34833a930803becfb1c0 | [
"Apache-2.0"
] | permissive | Vierkantor/mathlib | 0ea59ac32a3a43c93c44d70f441c4ee810ccceca | 83bc3b9ce9b13910b57bda6b56222495ebd31c2f | refs/heads/master | 1,658,323,012,449 | 1,652,256,003,000 | 1,652,256,003,000 | 209,296,341 | 0 | 1 | Apache-2.0 | 1,568,807,655,000 | 1,568,807,655,000 | null | UTF-8 | Lean | false | false | 8,708 | lean | /-
Copyright (c) 2021 Joël Riou. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Joël Riou, Adam Topaz, Johan Commelin
-/
import algebra.homology.additive
import algebraic_topology.Moore_complex
import algebra.big_operators.fin
/-!
# The alternating face map complex of a simplicial object in a preadditive category
We construct the alternating face map complex, as a
functor `alternating_face_map_complex : simplicial_object C ⥤ chain_complex C ℕ`
for any preadditive category `C`. For any simplicial object `X` in `C`,
this is the homological complex `... → X_2 → X_1 → X_0`
where the differentials are alternating sums of faces.
We also construct the natural transformation
`inclusion_of_Moore_complex : normalized_Moore_complex A ⟶ alternating_face_map_complex A`
when `A` is an abelian category.
## References
* https://stacks.math.columbia.edu/tag/0194
* https://ncatlab.org/nlab/show/Moore+complex
-/
open category_theory category_theory.limits category_theory.subobject
open category_theory.preadditive category_theory.category
open opposite
open_locale big_operators
open_locale simplicial
noncomputable theory
namespace algebraic_topology
namespace alternating_face_map_complex
/-!
## Construction of the alternating face map complex
-/
variables {C : Type*} [category C] [preadditive C]
variables (X : simplicial_object C)
variables (Y : simplicial_object C)
/-- The differential on the alternating face map complex is the alternate
sum of the face maps -/
@[simp]
def obj_d (n : ℕ) : X _[n+1] ⟶ X _[n] :=
∑ (i : fin (n+2)), (-1 : ℤ)^(i : ℕ) • X.δ i
/--
## The chain complex relation `d ≫ d`
-/
lemma d_squared (n : ℕ) : obj_d X (n+1) ≫ obj_d X n = 0 :=
begin
/- we start by expanding d ≫ d as a double sum -/
dsimp,
rw comp_sum,
let d_l := λ (j : fin (n+3)), (-1 : ℤ)^(j : ℕ) • X.δ j,
let d_r := λ (i : fin (n+2)), (-1 : ℤ)^(i : ℕ) • X.δ i,
rw [show (λ i , (∑ j : fin (n+3), d_l j) ≫ d_r i) =
(λ i, ∑ j : fin (n+3), (d_l j ≫ d_r i)), by { ext i, rw sum_comp, }],
rw ← finset.sum_product',
/- then, we decompose the index set P into a subet S and its complement Sᶜ -/
let P := fin (n+2) × fin (n+3),
let S := finset.univ.filter (λ (ij : P), (ij.2 : ℕ) ≤ (ij.1 : ℕ)),
let term := λ (ij : P), d_l ij.2 ≫ d_r ij.1,
erw [show ∑ (ij : P), term ij =
(∑ ij in S, term ij) + (∑ ij in Sᶜ, term ij), by rw finset.sum_add_sum_compl],
rw [← eq_neg_iff_add_eq_zero, ← finset.sum_neg_distrib],
/- we are reduced to showing that two sums are equal, and this is obtained
by constructing a bijection φ : S -> Sᶜ, which maps (i,j) to (j,i+1),
and by comparing the terms -/
let φ : Π (ij : P), ij ∈ S → P := λ ij hij,
(fin.cast_lt ij.2
(lt_of_le_of_lt (finset.mem_filter.mp hij).right (fin.is_lt ij.1)), ij.1.succ),
apply finset.sum_bij φ,
{ -- φ(S) is contained in Sᶜ
intros ij hij,
simp only [finset.mem_univ, finset.compl_filter, finset.mem_filter, true_and,
fin.coe_succ, fin.coe_cast_lt] at hij ⊢,
linarith, },
{ /- identification of corresponding terms in both sums -/
rintro ⟨i, j⟩ hij,
simp only [term, d_l, d_r, φ, comp_zsmul, zsmul_comp, ← neg_smul, ← mul_smul,
pow_add, neg_mul, mul_one, fin.coe_cast_lt,
fin.coe_succ, pow_one, mul_neg, neg_neg],
let jj : fin (n+2) := (φ (i,j) hij).1,
have ineq : jj ≤ i, { rw ← fin.coe_fin_le, simpa using hij, },
rw [category_theory.simplicial_object.δ_comp_δ X ineq, fin.cast_succ_cast_lt, mul_comm] },
{ -- φ : S → Sᶜ is injective
rintro ⟨i, j⟩ ⟨i', j'⟩ hij hij' h,
rw [prod.mk.inj_iff],
refine ⟨by simpa using congr_arg prod.snd h, _⟩,
have h1 := congr_arg fin.cast_succ (congr_arg prod.fst h),
simpa [fin.cast_succ_cast_lt] using h1 },
{ -- φ : S → Sᶜ is surjective
rintro ⟨i', j'⟩ hij',
simp only [true_and, finset.mem_univ, finset.compl_filter, not_le,
finset.mem_filter] at hij',
refine ⟨(j'.pred _, fin.cast_succ i'), _, _⟩,
{ intro H,
simpa only [H, nat.not_lt_zero, fin.coe_zero] using hij' },
{ simpa only [true_and, finset.mem_univ, fin.coe_cast_succ, fin.coe_pred,
finset.mem_filter] using nat.le_pred_of_lt hij', },
{ simp only [prod.mk.inj_iff, fin.succ_pred, fin.cast_lt_cast_succ],
split; refl }, },
end
/-!
## Construction of the alternating face map complex functor
-/
/-- The alternating face map complex, on objects -/
def obj : chain_complex C ℕ := chain_complex.of (λ n, X _[n]) (obj_d X) (d_squared X)
variables {X} {Y}
/-- The alternating face map complex, on morphisms -/
@[simp]
def map (f : X ⟶ Y) : obj X ⟶ obj Y :=
chain_complex.of_hom _ _ _ _ _ _
(λ n, f.app (op [n]))
(λ n,
begin
dsimp,
rw [comp_sum, sum_comp],
apply finset.sum_congr rfl (λ x h, _),
rw [comp_zsmul, zsmul_comp],
apply congr_arg,
erw f.naturality,
refl,
end)
end alternating_face_map_complex
variables (C : Type*) [category C] [preadditive C]
/-- The alternating face map complex, as a functor -/
@[simps]
def alternating_face_map_complex : simplicial_object C ⥤ chain_complex C ℕ :=
{ obj := alternating_face_map_complex.obj,
map := λ X Y f, alternating_face_map_complex.map f }
variables {C}
lemma map_alternating_face_map_complex {D : Type*} [category D] [preadditive D]
(F : C ⥤ D) [F.additive] :
alternating_face_map_complex C ⋙ F.map_homological_complex _ =
(simplicial_object.whiskering C D).obj F ⋙ alternating_face_map_complex D :=
begin
apply category_theory.functor.ext,
{ intros X Y f,
ext n,
simp only [functor.comp_map, alternating_face_map_complex.map,
alternating_face_map_complex_map, functor.map_homological_complex_map_f,
chain_complex.of_hom_f, simplicial_object.whiskering_obj_map_app,
homological_complex.comp_f, homological_complex.eq_to_hom_f,
eq_to_hom_refl, comp_id, id_comp], },
{ intro X,
erw chain_complex.map_chain_complex_of,
congr,
ext n,
simp only [alternating_face_map_complex.obj_d, functor.map_sum],
congr,
ext,
apply functor.map_zsmul, },
end
/-!
## Construction of the natural inclusion of the normalized Moore complex
-/
variables {A : Type*} [category A] [abelian A]
/-- The inclusion map of the Moore complex in the alternating face map complex -/
def inclusion_of_Moore_complex_map (X : simplicial_object A) :
(normalized_Moore_complex A).obj X ⟶ (alternating_face_map_complex A).obj X :=
chain_complex.of_hom _ _ _ _ _ _
(λ n, (normalized_Moore_complex.obj_X X n).arrow)
(λ n,
begin
/- we have to show the compatibility of the differentials on the alternating
face map complex with those defined on the normalized Moore complex:
we first get rid of the terms of the alternating sum that are obviously
zero on the normalized_Moore_complex -/
simp only [alternating_face_map_complex.obj_d],
rw comp_sum,
let t := λ (j : fin (n+2)), (normalized_Moore_complex.obj_X X (n+1)).arrow ≫
((-1 : ℤ)^(j : ℕ) • X.δ j),
have def_t : (∀ j : fin (n+2), t j = (normalized_Moore_complex.obj_X X (n+1)).arrow ≫
((-1 : ℤ)^(j : ℕ) • X.δ j)) := by { intro j, refl, },
rw [fin.sum_univ_succ t],
have null : ∀ j : fin (n+1), t j.succ = 0,
{ intro j,
rw [def_t, comp_zsmul, ← zsmul_zero ((-1 : ℤ)^(j.succ : ℕ))],
apply congr_arg,
rw normalized_Moore_complex.obj_X,
rw ← factor_thru_arrow _ _
(finset_inf_arrow_factors finset.univ _ j (by simp only [finset.mem_univ])),
slice_lhs 2 3 { erw kernel_subobject_arrow_comp (X.δ j.succ), },
simp only [comp_zero], },
rw [fintype.sum_eq_zero _ null],
simp only [add_zero],
/- finally, we study the remaining term which is induced by X.δ 0 -/
let eq := def_t 0,
rw [show (-1 : ℤ)^((0 : fin (n+2)) : ℕ) = 1, by ring] at eq,
rw one_smul at eq,
rw eq,
cases n; dsimp; simp,
end)
@[simp]
lemma inclusion_of_Moore_complex_map_f (X : simplicial_object A) (n : ℕ) :
(inclusion_of_Moore_complex_map X).f n = (normalized_Moore_complex.obj_X X n).arrow :=
chain_complex.of_hom_f _ _ _ _ _ _ _ _ n
variables (A)
/-- The inclusion map of the Moore complex in the alternating face map complex,
as a natural transformation -/
@[simps]
def inclusion_of_Moore_complex :
(normalized_Moore_complex A) ⟶ (alternating_face_map_complex A) :=
{ app := inclusion_of_Moore_complex_map, }
end algebraic_topology
|
8b0c578bf6a14c57ae4c7c2ebf85202ad5ca7b33 | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/run/subst_heq.lean | c32b5a3489aa1752c27bb5e9f45f597f63373017 | [
"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 | 148 | lean | example (a b : nat) (h : a == b) : a + 1 = b + 1 :=
begin
subst h
end
example (a b : nat) (h : a == b) : a + 1 = b + 1 :=
begin
subst_vars
end
|
74e84927ae42ce0f99cae41dbcfed209640ff292 | f4bff2062c030df03d65e8b69c88f79b63a359d8 | /src/game/max/level06.lean | 1d5f74e3b607785bbe028d24af5d28e3f0f5a7c3 | [
"Apache-2.0"
] | permissive | adastra7470/real-number-game | 776606961f52db0eb824555ed2f8e16f92216ea3 | f9dcb7d9255a79b57e62038228a23346c2dc301b | refs/heads/master | 1,669,221,575,893 | 1,594,669,800,000 | 1,594,669,800,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,319 | lean | import game.max.level05 -- hide
open_locale classical -- hide
noncomputable theory -- hide
namespace xena -- hide
/-
# Chapter ? : Max and abs
## Level 6
In fact `max_le` can be beefed up to an iff statement.
-/
/- Hint : Tip : using `le_trans`
If your goal is `x ≤ z` and you have a hypothesis `h : y ≤ z`
then of course it will suffice to prove `x ≤ y` and then you
can use transitivity. Instead of `have hxy : x ≤ y,`, opening
a new goal and adding a new hypothesis to our list, you can
do
```
apply le_trans _ h
```
or
```
refine le_trans _ h
```
and this just reduces the goal to proving `x ≤ y` immediately.
-/
/- Lemma
If $a$, $b$, $c$ are real numbers,
then ($a\leq c$ and $b\leq c$) iff $\max(a,b)\leq c.$
-/
theorem max_le_iff {a b c : ℝ} : a ≤ c ∧ b ≤ c ↔ max a b ≤ c :=
begin
split,
{ intro h,
cases h with hac hbc,
exact max_le hac hbc
},
{ intro habc,
split,
{ apply le_trans _ habc,
apply le_max_left},
{ apply le_trans _ habc,
apply le_max_right
}
}
end
end xena --hide
/- Hint : Solution
split,
{ intro h,
cases h with hac hbc,
exact max_le hac hbc
},
{ intro habc,
split,
{ apply le_trans _ habc,
apply le_max_left},
{ apply le_trans _ habc,
apply le_max_right
}
}
-/
|
a12c6f7406d4bb97e9db6b22dda0c9eb86df7848 | 05f637fa14ac28031cb1ea92086a0f4eb23ff2b1 | /tests/lean/map.lean | db27d87871575a8db32803b24153aaec05ee36c6 | [
"Apache-2.0"
] | permissive | codyroux/lean0.1 | 1ce92751d664aacff0529e139083304a7bbc8a71 | 0dc6fb974aa85ed6f305a2f4b10a53a44ee5f0ef | refs/heads/master | 1,610,830,535,062 | 1,402,150,480,000 | 1,402,150,480,000 | 19,588,851 | 2 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 977 | lean | import tactic
variable list : Type → Type
variable nil {A : Type} : list A
variable cons {A : Type} : A → list A → list A
variable map {A B : Type} : (A → B) → list A → list B
axiom map_cons {A B : Type} (f : A → B) (a : A) (l : list A) : map f (cons a l) = cons (f a) (map f l)
axiom map_nil {A B : Type} (f : A → B) : (map f nil) = nil
add_rewrite map_cons map_nil
(*
local m = simplifier_monitor(function(s, e)
print("Visit, depth: " .. s:depth())
end,
function(s, e, new_e, pr)
print("Step: " .. s:depth())
end,
function(s, e, new_e, ceq, ceq_id)
print("Rewrite using: " .. tostring(ceq_id))
end
)
set_simplifier_monitor(m)
*)
theorem T1 : map (λ x, x + 1) (cons 1 (cons 2 nil)) = cons 2 (cons 3 nil)
:= by simp
|
b5e51471fa6c40f14b9d510cc453985fd805ea35 | 618003631150032a5676f229d13a079ac875ff77 | /src/order/iterate.lean | d558fcf95a40c9133bc622a634211d15c9dd005f | [
"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,551 | lean | /-
Copyright (c) 2020 Yury G. Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Yury G. Kudryashov
-/
import order.basic
import logic.function.iterate
import data.nat.basic
/-!
# Inequalities on iterates
In this file we prove some inequalities comparing `f^[n] x` and `g^[n] x` where `f` and `g` are
two self-maps that commute with each other.
Current selection of inequalities is motivated by formalization of the rotation number of
a circle homeomorphism.
-/
variables {α : Type*}
namespace function
namespace commute
section preorder
variables [preorder α] {f g : α → α}
lemma iterate_le_of_map_le (h : commute f g) (hf : monotone f) (hg : monotone g)
{x} (hx : f x ≤ g x) (n : ℕ) :
f^[n] x ≤ (g^[n]) x :=
nat.rec_on n (le_refl _) $ λ n ihn,
calc f^[n+1] x = (f^[n]) (f x) : iterate_succ_apply f n x
... ≤ (f^[n]) (g x) : hf.iterate n hx
... = g (f^[n] x) : h.iterate_left n x
... ≤ g (g^[n] x) : hg ihn
... = (g^[n+1]) x : (iterate_succ_apply' g n x).symm
lemma iterate_pos_lt_of_map_lt (h : commute f g) (hf : monotone f) (hg : strict_mono g)
{x} (hx : f x < g x) {n} (hn : 0 < n) :
f^[n] x < (g^[n]) x :=
flip (nat.le_rec_on hn) hx $ λ n ihn,
calc f^[n+1] x = (f^[n]) (f x) : iterate_succ_apply f n x
... ≤ (f^[n]) (g x) : hf.iterate n (le_of_lt hx)
... = g (f^[n] x) : h.iterate_left n x
... < g (g^[n] x) : hg ihn
... = (g^[n+1]) x : (iterate_succ_apply' g n x).symm
lemma iterate_pos_lt_of_map_lt' (h : commute f g) (hf : strict_mono f) (hg : monotone g)
{x} (hx : f x < g x) {n} (hn : 0 < n) :
f^[n] x < (g^[n]) x :=
@iterate_pos_lt_of_map_lt (order_dual α) _ g f h.symm hg.order_dual hf.order_dual x hx n hn
end preorder
variables [linear_order α] {f g : α → α}
lemma iterate_pos_lt_iff_map_lt (h : commute f g) (hf : monotone f)
(hg : strict_mono g) {x n} (hn : 0 < n) :
f^[n] x < (g^[n]) x ↔ f x < g x :=
begin
rcases lt_trichotomy (f x) (g x) with H|H|H,
{ simp only [*, iterate_pos_lt_of_map_lt] },
{ simp only [*, h.iterate_eq_of_map_eq, lt_irrefl] },
{ simp only [lt_asymm H, lt_asymm (h.symm.iterate_pos_lt_of_map_lt' hg hf H hn)] }
end
lemma iterate_pos_lt_iff_map_lt' (h : commute f g) (hf : strict_mono f)
(hg : monotone g) {x n} (hn : 0 < n) :
f^[n] x < (g^[n]) x ↔ f x < g x :=
@iterate_pos_lt_iff_map_lt (order_dual α) _ _ _ h.symm hg.order_dual hf.order_dual x n hn
end commute
end function
|
e4e4b378aab6857e58a8b0da4d65bff3f2933584 | 82e44445c70db0f03e30d7be725775f122d72f3e | /src/order/disjointed.lean | e38e805b67fa93bc677fb4a36931c62a4124dc1b | [
"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 | 3,420 | 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, Yaël Dillies
-/
import order.partial_sups
/-!
# Consecutive differences of sets
This file defines a way to make a sequence of sets into a sequence of disjoint sets.
## Main declarations
* `disjointed f`: Yields the sequence of sets `f 0`, `f 1 \ f 0`, `f 2 \ (f 0 ∪ f 1)`, ... This
sequence has the same union as `f 0`, `f 1`, `f 2` but with disjoint sets.
-/
variables {α β : Type*}
namespace set
/-- If `f : ℕ → set α` is a sequence of sets, then `disjointed f` is
the sequence formed with each set subtracted from the later ones
in the sequence, to form a disjoint sequence. -/
def disjointed (f : ℕ → set α) (n : ℕ) : set α := f n ∩ (⋂ i < n, (f i)ᶜ)
variables {f : ℕ → set α} {n : ℕ}
lemma disjoint_disjointed : pairwise (disjoint on disjointed f) :=
λ i j h, begin
wlog h' : i ≤ j; [skip, {revert a, exact (this h.symm).symm}],
rintro a ⟨⟨h₁, _⟩, h₂, h₃⟩, simp at h₃,
exact h₃ _ (lt_of_le_of_ne h' h) h₁
end
-- a more useful version might be `∀ i j x, x ∈ disjointed f i → x ∈ disjointed f j → i = j`
lemma disjoint_disjointed' :
∀ i j, i ≠ j → (disjointed f i) ∩ (disjointed f j) = ∅ :=
λ i j hij, disjoint_iff.1 $ disjoint_disjointed i j hij
lemma disjointed_subset : disjointed f n ⊆ f n := inter_subset_left _ _
lemma Union_lt_succ : (⋃ i < nat.succ n, f i) = f n ∪ (⋃ i < n, f i) :=
ext $ λ a, by simp [nat.lt_succ_iff_lt_or_eq, or_and_distrib_right, exists_or_distrib, or_comm]
lemma Inter_lt_succ : (⋂ i < nat.succ n, f i) = f n ∩ (⋂ i < n, f i) :=
ext $ λ a, by simp [nat.lt_succ_iff_lt_or_eq, or_imp_distrib, forall_and_distrib, and_comm]
lemma disjointed_induct {p : set α → Prop} (h₁ : p (f n)) (h₂ : ∀ t i, p t → p (t \ f i)) :
p (disjointed f n) :=
begin
rw disjointed,
generalize_hyp : f n = t at h₁ ⊢,
induction n,
case nat.zero { simp [nat.not_lt_zero, h₁] },
case nat.succ : n ih {
rw [Inter_lt_succ, inter_comm ((f n)ᶜ), ← inter_assoc],
exact h₂ _ n ih }
end
lemma disjointed_of_mono (hf : monotone f) :
disjointed f (n + 1) = f (n + 1) \ f n :=
have (⋂ i (h : i < n + 1), (f i)ᶜ) = (f n)ᶜ,
from le_antisymm
(infi_le_of_le n $ infi_le_of_le (nat.lt_succ_self _) $ subset.refl _)
(le_infi $ λ i, le_infi $ λ hi, compl_le_compl $ hf $ nat.le_of_succ_le_succ hi),
by simp [disjointed, this, diff_eq]
open_locale classical
lemma subset_Union_disjointed : f n ⊆ ⋃ i < n.succ, disjointed f i :=
λ x hx,
have ∃ k, x ∈ f k, from ⟨n, hx⟩,
have hn : ∀ (i : ℕ), i < nat.find this → x ∉ f i,
from λ i, nat.find_min this,
have hlt : nat.find this < n.succ,
from (nat.find_min' this hx).trans_lt n.lt_succ_self,
mem_bUnion hlt ⟨nat.find_spec this, mem_bInter hn⟩
lemma Union_disjointed : (⋃ n, disjointed f n) = (⋃ n, f n) :=
subset.antisymm (Union_subset_Union $ λ i, inter_subset_left _ _)
(Union_subset $ λ n, subset.trans subset_Union_disjointed (bUnion_subset_Union _ _))
lemma Union_disjointed_of_mono (hf : monotone f) (n : ℕ) :
(⋃ i < n.succ, disjointed f i) = f n :=
subset.antisymm (bUnion_subset $ λ k hk, subset.trans disjointed_subset $ hf $ nat.lt_succ_iff.1 hk)
subset_Union_disjointed
end set
|
2e77fd14f1dacfc3a4e7dbeeab2acc949721cd3b | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/data/fintype/card.lean | d95bdd1329bf98005e05889f32b6afd1679136da | [
"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 | 16,008 | lean | /-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import data.fintype.basic
import algebra.big_operators.ring
import algebra.big_operators.option
/-!
Results about "big operations" over a `fintype`, and consequent
results about cardinalities of certain types.
## Implementation note
This content had previously been in `data.fintype.basic`, but was moved here to avoid
requiring `algebra.big_operators` (and hence many other imports) as a
dependency of `fintype`.
However many of the results here really belong in `algebra.big_operators.basic`
and should be moved at some point.
-/
universes u v
variables {α : Type*} {β : Type*} {γ : Type*}
open_locale big_operators
namespace fintype
@[to_additive]
lemma prod_bool [comm_monoid α] (f : bool → α) : ∏ b, f b = f tt * f ff := by simp
lemma card_eq_sum_ones {α} [fintype α] : fintype.card α = ∑ a : α, 1 :=
finset.card_eq_sum_ones _
section
open finset
variables {ι : Type*} [decidable_eq ι] [fintype ι]
@[to_additive]
lemma prod_extend_by_one [comm_monoid α] (s : finset ι) (f : ι → α) :
∏ i, (if i ∈ s then f i else 1) = ∏ i in s, f i :=
by rw [← prod_filter, filter_mem_eq_inter, univ_inter]
end
section
variables {M : Type*} [fintype α] [comm_monoid M]
@[to_additive]
lemma prod_eq_one (f : α → M) (h : ∀ a, f a = 1) :
(∏ a, f a) = 1 :=
finset.prod_eq_one $ λ a ha, h a
@[to_additive]
lemma prod_congr (f g : α → M) (h : ∀ a, f a = g a) :
(∏ a, f a) = ∏ a, g a :=
finset.prod_congr rfl $ λ a ha, h a
@[to_additive]
lemma prod_eq_single {f : α → M} (a : α) (h : ∀ x ≠ a, f x = 1) :
(∏ x, f x) = f a :=
finset.prod_eq_single a (λ x _ hx, h x hx) $ λ ha, (ha (finset.mem_univ a)).elim
@[to_additive]
lemma prod_eq_mul {f : α → M} (a b : α) (h₁ : a ≠ b) (h₂ : ∀ x, x ≠ a ∧ x ≠ b → f x = 1) :
(∏ x, f x) = (f a) * (f b) :=
begin
apply finset.prod_eq_mul a b h₁ (λ x _ hx, h₂ x hx);
exact λ hc, (hc (finset.mem_univ _)).elim
end
/-- If a product of a `finset` of a subsingleton type has a given
value, so do the terms in that product. -/
@[to_additive "If a sum of a `finset` of a subsingleton type has a given
value, so do the terms in that sum."]
lemma eq_of_subsingleton_of_prod_eq {ι : Type*} [subsingleton ι] {s : finset ι}
{f : ι → M} {b : M} (h : ∏ i in s, f i = b) : ∀ i ∈ s, f i = b :=
finset.eq_of_card_le_one_of_prod_eq (finset.card_le_one_of_subsingleton s) h
end
end fintype
open finset
section
variables {M : Type*} [fintype α] [comm_monoid M]
@[simp, to_additive]
lemma fintype.prod_option (f : option α → M) : ∏ i, f i = f none * ∏ i, f (some i) :=
finset.prod_insert_none f univ
end
@[to_additive]
theorem fin.prod_univ_def [comm_monoid β] {n : ℕ} (f : fin n → β) :
∏ i, f i = ((list.fin_range n).map f).prod :=
by simp [fin.univ_def, finset.fin_range]
@[to_additive]
theorem finset.prod_range [comm_monoid β] {n : ℕ} (f : ℕ → β) :
∏ i in finset.range n, f i = ∏ i : fin n, f i :=
begin
fapply @finset.prod_bij' _ _ _ _ _ _,
exact λ k w, ⟨k, (by simpa using w)⟩,
swap 3,
exact λ a m, a,
swap 3,
exact λ a m, by simpa using a.2,
all_goals { tidy, },
end
@[to_additive]
theorem fin.prod_of_fn [comm_monoid β] {n : ℕ} (f : fin n → β) :
(list.of_fn f).prod = ∏ i, f i :=
by rw [list.of_fn_eq_map, fin.prod_univ_def]
/-- A product of a function `f : fin 0 → β` is `1` because `fin 0` is empty -/
@[to_additive "A sum of a function `f : fin 0 → β` is `0` because `fin 0` is empty"]
theorem fin.prod_univ_zero [comm_monoid β] (f : fin 0 → β) : ∏ i, f i = 1 := rfl
/-- A product of a function `f : fin (n + 1) → β` over all `fin (n + 1)`
is the product of `f x`, for some `x : fin (n + 1)` times the remaining product -/
@[to_additive
/- A sum of a function `f : fin (n + 1) → β` over all `fin (n + 1)`
is the sum of `f x`, for some `x : fin (n + 1)` plus the remaining product -/]
theorem fin.prod_univ_succ_above [comm_monoid β] {n : ℕ} (f : fin (n + 1) → β)
(x : fin (n + 1)) :
∏ i, f i = f x * ∏ i : fin n, f (x.succ_above i) :=
begin
rw [fintype.prod_eq_mul_prod_compl x, ← fin.image_succ_above_univ, prod_image],
exact λ _ _ _ _ h, x.succ_above.injective h
end
/-- A product of a function `f : fin (n + 1) → β` over all `fin (n + 1)`
is the product of `f 0` plus the remaining product -/
@[to_additive
/- A sum of a function `f : fin (n + 1) → β` over all `fin (n + 1)`
is the sum of `f 0` plus the remaining product -/]
theorem fin.prod_univ_succ [comm_monoid β] {n : ℕ} (f : fin (n + 1) → β) :
∏ i, f i = f 0 * ∏ i : fin n, f i.succ :=
fin.prod_univ_succ_above f 0
/-- A product of a function `f : fin (n + 1) → β` over all `fin (n + 1)`
is the product of `f (fin.last n)` plus the remaining product -/
@[to_additive
/- A sum of a function `f : fin (n + 1) → β` over all `fin (n + 1)`
is the sum of `f (fin.last n)` plus the remaining sum -/]
theorem fin.prod_univ_cast_succ [comm_monoid β] {n : ℕ} (f : fin (n + 1) → β) :
∏ i, f i = (∏ i : fin n, f i.cast_succ) * f (fin.last n) :=
by simpa [mul_comm] using fin.prod_univ_succ_above f (fin.last n)
@[to_additive sum_univ_one] theorem fin.prod_univ_one [comm_monoid β] (f : fin 1 → β) :
∏ i, f i = f 0 :=
by simp
@[to_additive] theorem fin.prod_univ_two [comm_monoid β] (f : fin 2 → β) :
∏ i, f i = f 0 * f 1 :=
by simp [fin.prod_univ_succ]
open finset
@[simp] theorem fintype.card_sigma {α : Type*} (β : α → Type*)
[fintype α] [∀ a, fintype (β a)] :
fintype.card (sigma β) = ∑ a, fintype.card (β a) :=
card_sigma _ _
@[simp] lemma finset.card_pi [decidable_eq α] {δ : α → Type*}
(s : finset α) (t : Π a, finset (δ a)) :
(s.pi t).card = ∏ a in s, card (t a) :=
multiset.card_pi _ _
@[simp] lemma fintype.card_pi_finset [decidable_eq α] [fintype α]
{δ : α → Type*} (t : Π a, finset (δ a)) :
(fintype.pi_finset t).card = ∏ a, card (t a) :=
by simp [fintype.pi_finset, card_map]
@[simp] lemma fintype.card_pi {β : α → Type*} [decidable_eq α] [fintype α]
[f : Π a, fintype (β a)] : fintype.card (Π a, β a) = ∏ a, fintype.card (β a) :=
fintype.card_pi_finset _
-- FIXME ouch, this should be in the main file.
@[simp] lemma fintype.card_fun [decidable_eq α] [fintype α] [fintype β] :
fintype.card (α → β) = fintype.card β ^ fintype.card α :=
by rw [fintype.card_pi, finset.prod_const]; refl
@[simp] lemma card_vector [fintype α] (n : ℕ) :
fintype.card (vector α n) = fintype.card α ^ n :=
by rw fintype.of_equiv_card; simp
@[simp, to_additive]
lemma finset.prod_attach_univ [fintype α] [comm_monoid β] (f : {a : α // a ∈ @univ α _} → β) :
∏ x in univ.attach, f x = ∏ x, f ⟨x, (mem_univ _)⟩ :=
fintype.prod_equiv (equiv.subtype_univ_equiv (λ x, mem_univ _)) _ _ (λ x, by simp)
/-- Taking a product over `univ.pi t` is the same as taking the product over `fintype.pi_finset t`.
`univ.pi t` and `fintype.pi_finset t` are essentially the same `finset`, but differ
in the type of their element, `univ.pi t` is a `finset (Π a ∈ univ, t a)` and
`fintype.pi_finset t` is a `finset (Π a, t a)`. -/
@[to_additive "Taking a sum over `univ.pi t` is the same as taking the sum over
`fintype.pi_finset t`. `univ.pi t` and `fintype.pi_finset t` are essentially the same `finset`,
but differ in the type of their element, `univ.pi t` is a `finset (Π a ∈ univ, t a)` and
`fintype.pi_finset t` is a `finset (Π a, t a)`."]
lemma finset.prod_univ_pi [decidable_eq α] [fintype α] [comm_monoid β]
{δ : α → Type*} {t : Π (a : α), finset (δ a)}
(f : (Π (a : α), a ∈ (univ : finset α) → δ a) → β) :
∏ x in univ.pi t, f x = ∏ x in fintype.pi_finset t, f (λ a _, x a) :=
prod_bij (λ x _ a, x a (mem_univ _))
(by simp)
(by simp)
(by simp [function.funext_iff] {contextual := tt})
(λ x hx, ⟨λ a _, x a, by simp * at *⟩)
/-- The product over `univ` of a sum can be written as a sum over the product of sets,
`fintype.pi_finset`. `finset.prod_sum` is an alternative statement when the product is not
over `univ` -/
lemma finset.prod_univ_sum [decidable_eq α] [fintype α] [comm_semiring β] {δ : α → Type u_1}
[Π (a : α), decidable_eq (δ a)] {t : Π (a : α), finset (δ a)}
{f : Π (a : α), δ a → β} :
∏ a, ∑ b in t a, f a b = ∑ p in fintype.pi_finset t, ∏ x, f x (p x) :=
by simp only [finset.prod_attach_univ, prod_sum, finset.sum_univ_pi]
/-- Summing `a^s.card * b^(n-s.card)` over all finite subsets `s` of a fintype of cardinality `n`
gives `(a + b)^n`. The "good" proof involves expanding along all coordinates using the fact that
`x^n` is multilinear, but multilinear maps are only available now over rings, so we give instead
a proof reducing to the usual binomial theorem to have a result over semirings. -/
lemma fintype.sum_pow_mul_eq_add_pow
(α : Type*) [fintype α] {R : Type*} [comm_semiring R] (a b : R) :
∑ s : finset α, a ^ s.card * b ^ (fintype.card α - s.card) =
(a + b) ^ (fintype.card α) :=
finset.sum_pow_mul_eq_add_pow _ _ _
lemma fin.sum_pow_mul_eq_add_pow {n : ℕ} {R : Type*} [comm_semiring R] (a b : R) :
∑ s : finset (fin n), a ^ s.card * b ^ (n - s.card) = (a + b) ^ n :=
by simpa using fintype.sum_pow_mul_eq_add_pow (fin n) a b
lemma fin.prod_const [comm_monoid α] (n : ℕ) (x : α) : ∏ i : fin n, x = x ^ n := by simp
lemma fin.sum_const [add_comm_monoid α] (n : ℕ) (x : α) : ∑ i : fin n, x = n • x := by simp
@[to_additive]
lemma function.bijective.prod_comp [fintype α] [fintype β] [comm_monoid γ] {f : α → β}
(hf : function.bijective f) (g : β → γ) :
∏ i, g (f i) = ∏ i, g i :=
fintype.prod_bijective f hf _ _ (λ x, rfl)
@[to_additive]
lemma equiv.prod_comp [fintype α] [fintype β] [comm_monoid γ] (e : α ≃ β) (f : β → γ) :
∏ i, f (e i) = ∏ i, f i :=
e.bijective.prod_comp f
/-- It is equivalent to sum a function over `fin n` or `finset.range n`. -/
@[to_additive]
lemma fin.prod_univ_eq_prod_range [comm_monoid α] (f : ℕ → α) (n : ℕ) :
∏ i : fin n, f i = ∏ i in range n, f i :=
calc (∏ i : fin n, f i) = ∏ i : {x // x ∈ range n}, f i :
((equiv.fin_equiv_subtype n).trans
(equiv.subtype_equiv_right (λ _, mem_range.symm))).prod_comp (f ∘ coe)
... = ∏ i in range n, f i : by rw [← attach_eq_univ, prod_attach]
@[to_additive]
lemma finset.prod_fin_eq_prod_range [comm_monoid β] {n : ℕ} (c : fin n → β) :
∏ i, c i = ∏ i in finset.range n, if h : i < n then c ⟨i, h⟩ else 1 :=
begin
rw [← fin.prod_univ_eq_prod_range, finset.prod_congr rfl],
rintros ⟨i, hi⟩ _,
simp only [fin.coe_eq_val, hi, dif_pos]
end
@[to_additive]
lemma finset.prod_to_finset_eq_subtype {M : Type*} [comm_monoid M] [fintype α]
(p : α → Prop) [decidable_pred p] (f : α → M) :
∏ a in {x | p x}.to_finset, f a = ∏ a : subtype p, f a :=
by { rw ← finset.prod_subtype, simp }
@[to_additive] lemma finset.prod_fiberwise [decidable_eq β] [fintype β] [comm_monoid γ]
(s : finset α) (f : α → β) (g : α → γ) :
∏ b : β, ∏ a in s.filter (λ a, f a = b), g a = ∏ a in s, g a :=
finset.prod_fiberwise_of_maps_to (λ x _, mem_univ _) _
@[to_additive]
lemma fintype.prod_fiberwise [fintype α] [decidable_eq β] [fintype β] [comm_monoid γ]
(f : α → β) (g : α → γ) :
(∏ b : β, ∏ a : {a // f a = b}, g (a : α)) = ∏ a, g a :=
begin
rw [← (equiv.sigma_preimage_equiv f).prod_comp, ← univ_sigma_univ, prod_sigma],
refl
end
lemma fintype.prod_dite [fintype α] {p : α → Prop} [decidable_pred p]
[comm_monoid β] (f : Π (a : α) (ha : p a), β) (g : Π (a : α) (ha : ¬p a), β) :
(∏ a, dite (p a) (f a) (g a)) = (∏ a : {a // p a}, f a a.2) * (∏ a : {a // ¬p a}, g a a.2) :=
begin
simp only [prod_dite, attach_eq_univ],
congr' 1,
{ convert (equiv.subtype_equiv_right _).prod_comp (λ x : {x // p x}, f x x.2),
simp },
{ convert (equiv.subtype_equiv_right _).prod_comp (λ x : {x // ¬p x}, g x x.2),
simp }
end
section
open finset
variables {α₁ : Type*} {α₂ : Type*} {M : Type*} [fintype α₁] [fintype α₂] [comm_monoid M]
@[to_additive]
lemma fintype.prod_sum_elim (f : α₁ → M) (g : α₂ → M) :
(∏ x, sum.elim f g x) = (∏ a₁, f a₁) * (∏ a₂, g a₂) :=
by { classical, rw [univ_sum_type, prod_sum_elim] }
@[to_additive]
lemma fintype.prod_sum_type (f : α₁ ⊕ α₂ → M) :
(∏ x, f x) = (∏ a₁, f (sum.inl a₁)) * (∏ a₂, f (sum.inr a₂)) :=
by simp only [← fintype.prod_sum_elim, sum.elim_comp_inl_inr]
end
namespace list
@[to_additive]
lemma prod_take_of_fn [comm_monoid α] {n : ℕ} (f : fin n → α) (i : ℕ) :
((of_fn f).take i).prod = ∏ j in finset.univ.filter (λ (j : fin n), j.val < i), f j :=
begin
have A : ∀ (j : fin n), ¬ ((j : ℕ) < 0) := λ j, not_lt_bot,
induction i with i IH, { simp [A] },
by_cases h : i < n,
{ have : i < length (of_fn f), by rwa [length_of_fn f],
rw prod_take_succ _ _ this,
have A : ((finset.univ : finset (fin n)).filter (λ j, j.val < i + 1))
= ((finset.univ : finset (fin n)).filter (λ j, j.val < i)) ∪ {(⟨i, h⟩ : fin n)},
by { ext j, simp [nat.lt_succ_iff_lt_or_eq, fin.ext_iff, - add_comm] },
have B : _root_.disjoint (finset.filter (λ (j : fin n), j.val < i) finset.univ)
(singleton (⟨i, h⟩ : fin n)), by simp,
rw [A, finset.prod_union B, IH],
simp },
{ have A : (of_fn f).take i = (of_fn f).take i.succ,
{ rw ← length_of_fn f at h,
have : length (of_fn f) ≤ i := not_lt.mp h,
rw [take_all_of_le this, take_all_of_le (le_trans this (nat.le_succ _))] },
have B : ∀ (j : fin n), ((j : ℕ) < i.succ) = ((j : ℕ) < i),
{ assume j,
have : (j : ℕ) < i := lt_of_lt_of_le j.2 (not_lt.mp h),
simp [this, lt_trans this (nat.lt_succ_self _)] },
simp [← A, B, IH] }
end
@[to_additive]
lemma prod_of_fn [comm_monoid α] {n : ℕ} {f : fin n → α} :
(of_fn f).prod = ∏ i, f i :=
begin
convert prod_take_of_fn f n,
{ rw [take_all_of_le (le_of_eq (length_of_fn f))] },
{ have : ∀ (j : fin n), (j : ℕ) < n := λ j, j.is_lt,
simp [this] }
end
lemma alternating_sum_eq_finset_sum {G : Type*} [add_comm_group G] :
∀ (L : list G), alternating_sum L = ∑ i : fin L.length, (-1 : ℤ) ^ (i : ℕ) • L.nth_le i i.is_lt
| [] := by { rw [alternating_sum, finset.sum_eq_zero], rintro ⟨i, ⟨⟩⟩ }
| (g :: []) :=
begin
show g = ∑ i : fin 1, (-1 : ℤ) ^ (i : ℕ) • [g].nth_le i i.2,
rw [fin.sum_univ_succ], simp,
end
| (g :: h :: L) :=
calc g + -h + L.alternating_sum
= g + -h + ∑ i : fin L.length, (-1 : ℤ) ^ (i : ℕ) • L.nth_le i i.2 :
congr_arg _ (alternating_sum_eq_finset_sum _)
... = ∑ i : fin (L.length + 2), (-1 : ℤ) ^ (i : ℕ) • list.nth_le (g :: h :: L) i _ :
begin
rw [fin.sum_univ_succ, fin.sum_univ_succ, add_assoc],
unfold_coes,
simp [nat.succ_eq_add_one, pow_add],
refl,
end
@[to_additive]
lemma alternating_prod_eq_finset_prod {G : Type*} [comm_group G] :
∀ (L : list G), alternating_prod L = ∏ i : fin L.length, (L.nth_le i i.2) ^ ((-1 : ℤ) ^ (i : ℕ))
| [] := by { rw [alternating_prod, finset.prod_eq_one], rintro ⟨i, ⟨⟩⟩ }
| (g :: []) :=
begin
show g = ∏ i : fin 1, [g].nth_le i i.2 ^ (-1 : ℤ) ^ (i : ℕ),
rw [fin.prod_univ_succ], simp,
end
| (g :: h :: L) :=
calc g * h⁻¹ * L.alternating_prod
= g * h⁻¹ * ∏ i : fin L.length, L.nth_le i i.2 ^ (-1 : ℤ) ^ (i : ℕ) :
congr_arg _ (alternating_prod_eq_finset_prod _)
... = ∏ i : fin (L.length + 2), list.nth_le (g :: h :: L) i _ ^ (-1 : ℤ) ^ (i : ℕ) :
begin
rw [fin.prod_univ_succ, fin.prod_univ_succ, mul_assoc],
unfold_coes,
simp [nat.succ_eq_add_one, pow_add],
refl,
end
end list
|
ed1e3583b823817098f629b5a1daf14da294213c | 30d8cd1892571165965a1f2200a47df0b8b44b7c | /_learning/lean/first_project/src/hello.lean | 76be0621e07f05e4f63779eda148d46c4e24699f | [] | no_license | cuckookernel/scratch | 744aed4cfdddbfb80ac8dc7118b5734f13e546f8 | 1e51a6aa9303fb7370072d970622875a657e9481 | refs/heads/master | 1,682,629,054,957 | 1,681,482,905,000 | 1,681,482,905,000 | 165,303,327 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 259 | lean | import init.data.bool
#check bool
#check true
#check true == false
#eval 0
#check 0
#check nat
theorem test( p q : Prop )(hp : p)(hq : q) : p ∧ q ∧ p :=
by apply And.intro
exact hp
apply And.intro
exact hq
exact hp
#check test
|
9cdce540e6411f16ce6ba2ca178552021b9f5548 | 32a2d1642d7519c99693bc1d3b24069e4853dd1f | /data/multiset.lean | fb25c2802b5fd5cdff2c5c0ddbb19a3f8bd49a2e | [
"Apache-2.0"
] | permissive | Cedric0099/mathlib | 7edb81d5d68e280b4d21f6c0377dad1f9b8c0d71 | a97101d2df5d186848075a2d0452f6a04d8a13eb | refs/heads/master | 1,584,201,847,599 | 1,524,979,632,000 | 1,524,979,632,000 | 131,690,350 | 0 | 0 | null | 1,525,162,341,000 | 1,525,162,341,000 | null | UTF-8 | Lean | false | false | 96,004 | lean | /-
Copyright (c) 2015 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Mario Carneiro
Multisets.
-/
import logic.function data.list.basic data.list.perm data.list.sort order.boolean_algebra
algebra.order_functions data.quot algebra.group_power algebra.ordered_group
open list subtype nat lattice
variables {α : Type*} {β : Type*} {γ : Type*}
local infix ` • ` := add_monoid.smul
instance list.perm.setoid (α : Type*) : setoid (list α) :=
setoid.mk perm ⟨perm.refl, @perm.symm _, @perm.trans _⟩
/-- `multiset α` is the quotient of `list α` by list permutation. The result
is a type of finite sets with duplicates allowed. -/
def {u} multiset (α : Type u) : Type u :=
quotient (list.perm.setoid α)
namespace multiset
instance : has_coe (list α) (multiset α) := ⟨quot.mk _⟩
@[simp] theorem quot_mk_to_coe (l : list α) : @eq (multiset α) ⟦l⟧ l := rfl
@[simp] theorem quot_mk_to_coe' (l : list α) : @eq (multiset α) (quot.mk (≈) l) l := rfl
@[simp] theorem quot_mk_to_coe'' (l : list α) : @eq (multiset α) (quot.mk setoid.r l) l := rfl
@[simp] theorem coe_eq_coe (l₁ l₂ : list α) : (l₁ : multiset α) = l₂ ↔ l₁ ~ l₂ := quotient.eq
instance has_decidable_eq [decidable_eq α] : decidable_eq (multiset α)
| s₁ s₂ := quotient.rec_on_subsingleton₂ s₁ s₂ $ λ l₁ l₂,
decidable_of_iff' _ quotient.eq
/- empty multiset -/
/-- `0 : multiset α` is the empty set -/
protected def zero : multiset α := @nil α
instance : has_zero (multiset α) := ⟨multiset.zero⟩
instance : has_emptyc (multiset α) := ⟨0⟩
instance : inhabited (multiset α) := ⟨0⟩
@[simp] theorem coe_nil_eq_zero : (@nil α : multiset α) = 0 := rfl
/- cons -/
/-- `cons a s` is the multiset which contains `s` plus one more
instance of `a`. -/
def cons (a : α) (s : multiset α) : multiset α :=
quot.lift_on s (λ l, (a :: l : multiset α))
(λ l₁ l₂ p, quot.sound ((perm_cons a).2 p))
notation a :: b := cons a b
instance : has_insert α (multiset α) := ⟨cons⟩
@[simp] theorem insert_eq_cons (a : α) (s : multiset α) :
insert a s = a::s := rfl
@[simp] theorem cons_coe (a : α) (l : list α) :
(a::l : multiset α) = (a::l : list α) := rfl
theorem singleton_coe (a : α) : (a::0 : multiset α) = ([a] : list α) := rfl
@[simp] theorem cons_inj_left {a b : α} (s : multiset α) :
a::s = b::s ↔ a = b :=
⟨quot.induction_on s $ λ l e,
have [a] ++ l ~ [b] ++ l, from quotient.exact e,
eq_singleton_of_perm $ (perm_app_right_iff _).1 this, congr_arg _⟩
@[simp] theorem cons_inj_right (a : α) {s t : multiset α} :
a::s = a::t ↔ s = t :=
quotient.induction_on₂ s t $ λ l₁ l₂, by simp [perm_cons]
@[recursor 5] protected theorem induction {p : multiset α → Prop}
(h₁ : p 0) (h₂ : ∀ ⦃a : α⦄ {s : multiset α}, p s → p (a :: s)) (s) : p s :=
quot.induction_on s $ λ l, by induction l with _ _ ih; [exact h₁, exact h₂ ih]
@[elab_as_eliminator] protected theorem induction_on {p : multiset α → Prop}
(s : multiset α) (h₁ : p 0) (h₂ : ∀ ⦃a : α⦄ {s : multiset α}, p s → p (a :: s)) : p s :=
multiset.induction h₁ h₂ s
theorem cons_swap (a b : α) (s : multiset α) : a :: b :: s = b :: a :: s :=
quot.induction_on s $ λ l, quotient.sound $ perm.swap _ _ _
section rec
variables {C : multiset α → Sort*}
/-- Dependent recursor on multisets.
TODO: should be @[recursor 6], but then the definition of `multiset.pi` failes with a stack
overflow in `whnf`.
-/
protected def rec
(C_0 : C 0)
(C_cons : Πa m, C m → C (a::m))
(C_cons_heq : ∀a a' m b, C_cons a (a'::m) (C_cons a' m b) == C_cons a' (a::m) (C_cons a m b))
(m : multiset α) : C m :=
quotient.hrec_on m (@list.rec α (λl, C ⟦l⟧) C_0 (λa l b, C_cons a ⟦l⟧ b)) $
assume l l' h,
list.rec_heq_of_perm h
(assume a l l' b b' hl, have ⟦l⟧ = ⟦l'⟧, from quot.sound hl, by cc)
(assume a a' l, C_cons_heq a a' ⟦l⟧)
@[elab_as_eliminator]
protected def rec_on (m : multiset α)
(C_0 : C 0)
(C_cons : Πa m, C m → C (a::m))
(C_cons_heq : ∀a a' m b, C_cons a (a'::m) (C_cons a' m b) == C_cons a' (a::m) (C_cons a m b)) :
C m :=
multiset.rec C_0 C_cons C_cons_heq m
variables {C_0 : C 0} {C_cons : Πa m, C m → C (a::m)}
{C_cons_heq : ∀a a' m b, C_cons a (a'::m) (C_cons a' m b) == C_cons a' (a::m) (C_cons a m b)}
@[simp] lemma rec_on_0 : @multiset.rec_on α C (0:multiset α) C_0 C_cons C_cons_heq = C_0 :=
rfl
@[simp] lemma rec_on_cons (a : α) (m : multiset α) :
(a :: m).rec_on C_0 C_cons C_cons_heq = C_cons a m (m.rec_on C_0 C_cons C_cons_heq) :=
quotient.induction_on m $ assume l, rfl
end rec
section mem
/-- `a ∈ s` means that `a` has nonzero multiplicity in `s`. -/
def mem (a : α) (s : multiset α) : Prop :=
quot.lift_on s (λ l, a ∈ l) (λ l₁ l₂ (e : l₁ ~ l₂), propext $ mem_of_perm e)
instance : has_mem α (multiset α) := ⟨mem⟩
@[simp] lemma mem_coe {a : α} {l : list α} : a ∈ (l : multiset α) ↔ a ∈ l := iff.rfl
instance decidable_mem [decidable_eq α] (a : α) (s : multiset α) : decidable (a ∈ s) :=
quot.rec_on_subsingleton s $ list.decidable_mem a
@[simp] theorem mem_cons {a b : α} {s : multiset α} : a ∈ b :: s ↔ a = b ∨ a ∈ s :=
quot.induction_on s $ λ l, iff.rfl
lemma mem_cons_of_mem {a b : α} {s : multiset α} (h : a ∈ s) : a ∈ b :: s :=
mem_cons.2 $ or.inr h
@[simp] theorem mem_cons_self (a : α) (s : multiset α) : a ∈ a :: s :=
mem_cons.2 (or.inl rfl)
theorem exists_cons_of_mem {s : multiset α} {a : α} : a ∈ s → ∃ t, s = a :: t :=
quot.induction_on s $ λ l (h : a ∈ l),
let ⟨l₁, l₂, e⟩ := mem_split h in
e.symm ▸ ⟨(l₁++l₂ : list α), quot.sound perm_middle⟩
@[simp] theorem not_mem_zero (a : α) : a ∉ (0 : multiset α) := id
theorem eq_zero_of_forall_not_mem {s : multiset α} : (∀x, x ∉ s) → s = 0 :=
quot.induction_on s $ λ l H, by rw eq_nil_of_forall_not_mem H; refl
theorem exists_mem_of_ne_zero {s : multiset α} : s ≠ 0 → ∃ a : α, a ∈ s :=
quot.induction_on s $ assume l hl,
match l, hl with
| [] := assume h, false.elim $ h rfl
| (a :: l) := assume _, ⟨a, by simp⟩
end
end mem
/- subset -/
section subset
/-- `s ⊆ t` is the lift of the list subset relation. It means that any
element with nonzero multiplicity in `s` has nonzero multiplicity in `t`,
but it does not imply that the multiplicity of `a` in `s` is less or equal than in `t`;
see `s ≤ t` for this relation. -/
protected def subset (s t : multiset α) : Prop := ∀ ⦃a : α⦄, a ∈ s → a ∈ t
instance : has_subset (multiset α) := ⟨multiset.subset⟩
@[simp] theorem coe_subset {l₁ l₂ : list α} : (l₁ : multiset α) ⊆ l₂ ↔ l₁ ⊆ l₂ := iff.rfl
@[simp] theorem subset.refl (s : multiset α) : s ⊆ s := λ a h, h
theorem subset.trans {s t u : multiset α} : s ⊆ t → t ⊆ u → s ⊆ u :=
λ h₁ h₂ a m, h₂ (h₁ m)
theorem subset_iff {s t : multiset α} : s ⊆ t ↔ (∀⦃x⦄, x ∈ s → x ∈ t) := iff.rfl
theorem mem_of_subset {s t : multiset α} {a : α} (h : s ⊆ t) : a ∈ s → a ∈ t := @h _
@[simp] theorem zero_subset (s : multiset α) : 0 ⊆ s :=
λ a, (not_mem_nil a).elim
@[simp] theorem cons_subset {a : α} {s t : multiset α} : (a :: s) ⊆ t ↔ a ∈ t ∧ s ⊆ t :=
by simp [subset_iff, or_imp_distrib, forall_and_distrib]
theorem eq_zero_of_subset_zero {s : multiset α} (h : s ⊆ 0) : s = 0 :=
eq_zero_of_forall_not_mem h
theorem subset_zero {s : multiset α} : s ⊆ 0 ↔ s = 0 :=
⟨eq_zero_of_subset_zero, λ xeq, xeq.symm ▸ subset.refl 0⟩
end subset
/- multiset order -/
/-- `s ≤ t` means that `s` is a sublist of `t` (up to permutation).
Equivalently, `s ≤ t` means that `count a s ≤ count a t` for all `a`. -/
protected def le (s t : multiset α) : Prop :=
quotient.lift_on₂ s t (<+~) $ λ v₁ v₂ w₁ w₂ p₁ p₂,
propext (p₂.subperm_left.trans p₁.subperm_right)
instance : partial_order (multiset α) :=
{ le := multiset.le,
le_refl := λ s, quot.induction_on s $ λ l, subperm.refl _,
le_trans := λ s t u, quotient.induction_on₃ s t u $ @subperm.trans _,
le_antisymm := λ s t, quotient.induction_on₂ s t $
λ l₁ l₂ h₁ h₂, quot.sound (subperm.antisymm h₁ h₂) }
theorem subset_of_le {s t : multiset α} : s ≤ t → s ⊆ t :=
quotient.induction_on₂ s t $ λ l₁ l₂, subset_of_subperm
theorem mem_of_le {s t : multiset α} {a : α} (h : s ≤ t) : a ∈ s → a ∈ t :=
mem_of_subset (subset_of_le h)
@[simp] theorem coe_le {l₁ l₂ : list α} : (l₁ : multiset α) ≤ l₂ ↔ l₁ <+~ l₂ := iff.rfl
@[elab_as_eliminator] theorem le_induction_on {C : multiset α → multiset α → Prop}
{s t : multiset α} (h : s ≤ t)
(H : ∀ {l₁ l₂ : list α}, l₁ <+ l₂ → C l₁ l₂) : C s t :=
quotient.induction_on₂ s t (λ l₁ l₂ ⟨l, p, s⟩,
(show ⟦l⟧ = ⟦l₁⟧, from quot.sound p) ▸ H s) h
theorem zero_le (s : multiset α) : 0 ≤ s :=
quot.induction_on s $ λ l, subperm_of_sublist $ nil_sublist l
theorem le_zero {s : multiset α} : s ≤ 0 ↔ s = 0 :=
⟨λ h, le_antisymm h (zero_le _), le_of_eq⟩
theorem lt_cons_self (s : multiset α) (a : α) : s < a :: s :=
quot.induction_on s $ λ l,
suffices l <+~ a :: l ∧ (¬l ~ a :: l),
by simpa [lt_iff_le_and_ne],
⟨subperm_of_sublist (sublist_cons _ _),
λ p, ne_of_lt (lt_succ_self (length l)) (perm_length p)⟩
theorem le_cons_self (s : multiset α) (a : α) : s ≤ a :: s :=
le_of_lt $ lt_cons_self _ _
theorem cons_le_cons_iff (a : α) {s t : multiset α} : a :: s ≤ a :: t ↔ s ≤ t :=
quotient.induction_on₂ s t $ λ l₁ l₂, subperm_cons a
theorem cons_le_cons (a : α) {s t : multiset α} : s ≤ t → a :: s ≤ a :: t :=
(cons_le_cons_iff a).2
theorem le_cons_of_not_mem {a : α} {s t : multiset α} (m : a ∉ s) : s ≤ a :: t ↔ s ≤ t :=
begin
refine ⟨_, λ h, le_trans h $ le_cons_self _ _⟩,
suffices : ∀ {t'} (_ : s ≤ t') (_ : a ∈ t'), a :: s ≤ t',
{ exact λ h, (cons_le_cons_iff a).1 (this h (mem_cons_self _ _)) },
introv h, revert m, refine le_induction_on h _,
introv s m₁ m₂,
rcases mem_split m₂ with ⟨r₁, r₂, rfl⟩,
exact perm_middle.subperm_left.2 ((subperm_cons _).2 $ subperm_of_sublist $
(sublist_or_mem_of_sublist s).resolve_right m₁)
end
/- cardinality -/
/-- The cardinality of a multiset is the sum of the multiplicities
of all its elements, or simply the length of the underlying list. -/
def card (s : multiset α) : ℕ :=
quot.lift_on s length $ λ l₁ l₂, perm_length
@[simp] theorem coe_card (l : list α) : card (l : multiset α) = length l := rfl
@[simp] theorem card_zero : @card α 0 = 0 := rfl
@[simp] theorem card_cons (a : α) (s : multiset α) : card (a :: s) = card s + 1 :=
quot.induction_on s $ λ l, rfl
@[simp] theorem card_singleton (a : α) : card ({a} : multiset α) = 1 :=
calc card ({a} : multiset α) = card (0 : multiset α) + 1 : multiset.card_cons a 0
... = 1 : by simp
theorem card_le_of_le {s t : multiset α} (h : s ≤ t) : card s ≤ card t :=
le_induction_on h $ λ l₁ l₂, length_le_of_sublist
theorem eq_of_le_of_card_le {s t : multiset α} (h : s ≤ t) : card t ≤ card s → s = t :=
le_induction_on h $ λ l₁ l₂ s h₂, congr_arg coe $ eq_of_sublist_of_length_le s h₂
theorem card_lt_of_lt {s t : multiset α} (h : s < t) : card s < card t :=
lt_of_not_ge $ λ h₂, ne_of_lt h $ eq_of_le_of_card_le (le_of_lt h) h₂
theorem lt_iff_cons_le {s t : multiset α} : s < t ↔ ∃ a, a :: s ≤ t :=
⟨quotient.induction_on₂ s t $ λ l₁ l₂ h,
subperm.exists_of_length_lt (le_of_lt h) (card_lt_of_lt h),
λ ⟨a, h⟩, lt_of_lt_of_le (lt_cons_self _ _) h⟩
@[simp] theorem card_eq_zero {s : multiset α} : card s = 0 ↔ s = 0 :=
⟨λ h, (eq_of_le_of_card_le (zero_le _) (le_of_eq h)).symm, λ e, by simp [e]⟩
theorem card_pos {s : multiset α} : 0 < card s ↔ s ≠ 0 :=
pos_iff_ne_zero.trans $ not_congr card_eq_zero
theorem card_pos_iff_exists_mem {s : multiset α} : 0 < card s ↔ ∃ a, a ∈ s :=
quot.induction_on s $ λ l, length_pos_iff_exists_mem
@[elab_as_eliminator] lemma strong_induction_on {p : multiset α → Sort*} :
∀ (s : multiset α), (∀ s, (∀t < s, p t) → p s) → p s
| s := λ ih, ih s $ λ t h,
have card t < card s, from card_lt_of_lt h,
strong_induction_on t ih
using_well_founded {rel_tac := λ _ _, `[exact ⟨_, measure_wf card⟩]}
@[elab_as_eliminator] lemma case_strong_induction_on {p : multiset α → Prop}
(s : multiset α) (h₀ : p 0) (h₁ : ∀ a s, (∀t ≤ s, p t) → p (a :: s)) : p s :=
multiset.strong_induction_on s $ assume s,
multiset.induction_on s (λ _, h₀) $ λ a s _ ih, h₁ _ _ $
λ t h, ih _ $ lt_of_le_of_lt h $ lt_cons_self _ _
/- singleton -/
@[simp] theorem mem_singleton {a b : α} : b ∈ a::0 ↔ b = a :=
by simp
theorem mem_singleton_self (a : α) : a ∈ (a::0 : multiset α) := mem_cons_self _ _
theorem singleton_inj {a b : α} : a::0 = b::0 ↔ a = b := cons_inj_left _
@[simp] theorem singleton_ne_zero (a : α) : a::0 ≠ 0 :=
ne_of_gt (lt_cons_self _ _)
@[simp] theorem singleton_le {a : α} {s : multiset α} : a::0 ≤ s ↔ a ∈ s :=
⟨λ h, mem_of_le h (mem_singleton_self _),
λ h, let ⟨t, e⟩ := exists_cons_of_mem h in e.symm ▸ cons_le_cons _ (zero_le _)⟩
/- add -/
/-- The sum of two multisets is the lift of the list append operation.
This adds the multiplicities of each element,
i.e. `count a (s + t) = count a s + count a t`. -/
protected def add (s₁ s₂ : multiset α) : multiset α :=
quotient.lift_on₂ s₁ s₂ (λ l₁ l₂, ((l₁ ++ l₂ : list α) : multiset α)) $
λ v₁ v₂ w₁ w₂ p₁ p₂, quot.sound $ perm_app p₁ p₂
instance : has_add (multiset α) := ⟨multiset.add⟩
@[simp] theorem coe_add (s t : list α) : (s + t : multiset α) = (s ++ t : list α) := rfl
protected theorem add_comm (s t : multiset α) : s + t = t + s :=
quotient.induction_on₂ s t $ λ l₁ l₂, quot.sound perm_app_comm
protected theorem zero_add (s : multiset α) : 0 + s = s :=
quot.induction_on s $ λ l, rfl
theorem singleton_add (a : α) (s : multiset α) : ↑[a] + s = a::s := rfl
protected theorem add_le_add_left (s) {t u : multiset α} : s + t ≤ s + u ↔ t ≤ u :=
quotient.induction_on₃ s t u $ λ l₁ l₂ l₃, subperm_app_left _
protected theorem add_left_cancel (s) {t u : multiset α} (h : s + t = s + u) : t = u :=
le_antisymm ((multiset.add_le_add_left _).1 (le_of_eq h))
((multiset.add_le_add_left _).1 (le_of_eq h.symm))
instance : ordered_cancel_comm_monoid (multiset α) :=
{ zero := 0,
add := (+),
add_comm := multiset.add_comm,
add_assoc := λ s₁ s₂ s₃, quotient.induction_on₃ s₁ s₂ s₃ $ λ l₁ l₂ l₃,
congr_arg coe $ append_assoc l₁ l₂ l₃,
zero_add := multiset.zero_add,
add_zero := λ s, by rw [multiset.add_comm, multiset.zero_add],
add_left_cancel := multiset.add_left_cancel,
add_right_cancel := λ s₁ s₂ s₃ h, multiset.add_left_cancel s₂ $
by simpa [multiset.add_comm] using h,
add_le_add_left := λ s₁ s₂ h s₃, (multiset.add_le_add_left _).2 h,
le_of_add_le_add_left := λ s₁ s₂ s₃, (multiset.add_le_add_left _).1,
..@multiset.partial_order α }
@[simp] theorem cons_add (a : α) (s t : multiset α) : a :: s + t = a :: (s + t) :=
by rw [← singleton_add, ← singleton_add, add_assoc]
@[simp] theorem add_cons (a : α) (s t : multiset α) : s + a :: t = a :: (s + t) :=
by rw [add_comm, cons_add, add_comm]
theorem le_add_right (s t : multiset α) : s ≤ s + t :=
by simpa using add_le_add_left (zero_le t) s
theorem le_add_left (s t : multiset α) : s ≤ t + s :=
by simpa using add_le_add_right (zero_le t) s
@[simp] theorem card_add (s t : multiset α) : card (s + t) = card s + card t :=
quotient.induction_on₂ s t length_append
@[simp] theorem mem_add {a : α} {s t : multiset α} : a ∈ s + t ↔ a ∈ s ∨ a ∈ t :=
quotient.induction_on₂ s t $ λ l₁ l₂, mem_append
theorem le_iff_exists_add {s t : multiset α} : s ≤ t ↔ ∃ u, t = s + u :=
⟨λ h, le_induction_on h $ λ l₁ l₂ s,
let ⟨l, p⟩ := exists_perm_append_of_sublist s in ⟨l, quot.sound p⟩,
λ⟨u, e⟩, e.symm ▸ le_add_right s u⟩
instance : canonically_ordered_monoid (multiset α) :=
{ lt_of_add_lt_add_left := @lt_of_add_lt_add_left _ _,
le_iff_exists_add := @le_iff_exists_add _,
..multiset.ordered_cancel_comm_monoid }
/- repeat -/
/-- `repeat a n` is the multiset containing only `a` with multiplicity `n`. -/
def repeat (a : α) (n : ℕ) : multiset α := repeat a n
@[simp] lemma card_repeat : ∀ (a : α) n, card (repeat a n) = n := length_repeat
theorem eq_of_mem_repeat {a b : α} {n} : b ∈ repeat a n → b = a := eq_of_mem_repeat
theorem eq_repeat' {a : α} {s : multiset α} : s = repeat a s.card ↔ ∀ b ∈ s, b = a :=
quot.induction_on s $ λ l, iff.trans ⟨λ h,
(perm_repeat.1 $ (quotient.exact h).symm).symm, congr_arg coe⟩ eq_repeat'
theorem eq_repeat_of_mem {a : α} {s : multiset α} : (∀ b ∈ s, b = a) → s = repeat a s.card :=
eq_repeat'.2
theorem eq_repeat {a : α} {n} {s : multiset α} : s = repeat a n ↔ card s = n ∧ ∀ b ∈ s, b = a :=
⟨λ h, h.symm ▸ ⟨card_repeat _ _, λ b, eq_of_mem_repeat⟩,
λ ⟨e, al⟩, e ▸ eq_repeat_of_mem al⟩
theorem repeat_subset_singleton : ∀ (a : α) n, repeat a n ⊆ a::0 := repeat_subset_singleton
theorem repeat_le_coe {a : α} {n} {l : list α} : repeat a n ≤ l ↔ list.repeat a n <+ l :=
⟨λ ⟨l', p, s⟩, (perm_repeat.1 p.symm).symm ▸ s, subperm_of_sublist⟩
/- range -/
/-- `range n` is the multiset lifted from the list `range n`,
that is, the set `{0, 1, ..., n-1}`. -/
def range (n : ℕ) : multiset ℕ := range n
@[simp] theorem range_zero (n : ℕ) : range 0 = 0 := rfl
@[simp] theorem range_succ (n : ℕ) : range (succ n) = n :: range n :=
by rw [range, range_concat, ← coe_add, add_comm]; refl
@[simp] theorem card_range (n : ℕ) : card (range n) = n := length_range _
theorem range_subset {m n : ℕ} : range m ⊆ range n ↔ m ≤ n := range_subset
@[simp] theorem mem_range {m n : ℕ} : m ∈ range n ↔ m < n := mem_range
@[simp] theorem not_mem_range_self {n : ℕ} : n ∉ range n := not_mem_range_self
/- erase -/
section erase
variables [decidable_eq α] {s t : multiset α} {a b : α}
/-- `erase s a` is the multiset that subtracts 1 from the
multiplicity of `a`. -/
def erase (s : multiset α) (a : α) : multiset α :=
quot.lift_on s (λ l, (l.erase a : multiset α))
(λ l₁ l₂ p, quot.sound (erase_perm_erase a p))
@[simp] theorem coe_erase (l : list α) (a : α) :
erase (l : multiset α) a = l.erase a := rfl
@[simp] theorem erase_zero (a : α) : (0 : multiset α).erase a = 0 := rfl
@[simp] theorem erase_cons_head (a : α) (s : multiset α) : (a :: s).erase a = s :=
quot.induction_on s $ λ l, congr_arg coe $ erase_cons_head a l
@[simp] theorem erase_cons_tail {a b : α} (s : multiset α) (h : b ≠ a) : (b::s).erase a = b :: s.erase a :=
quot.induction_on s $ λ l, congr_arg coe $ erase_cons_tail l h
@[simp] theorem erase_of_not_mem {a : α} {s : multiset α} : a ∉ s → s.erase a = s :=
quot.induction_on s $ λ l h, congr_arg coe $ erase_of_not_mem h
@[simp] theorem cons_erase {s : multiset α} {a : α} : a ∈ s → a :: s.erase a = s :=
quot.induction_on s $ λ l h, quot.sound (perm_erase h).symm
theorem le_cons_erase (s : multiset α) (a : α) : s ≤ a :: s.erase a :=
if h : a ∈ s then le_of_eq (cons_erase h).symm
else by rw erase_of_not_mem h; apply le_cons_self
@[simp] theorem card_erase_of_mem {a : α} {s : multiset α} : a ∈ s → card (s.erase a) = pred (card s) :=
quot.induction_on s $ λ l, length_erase_of_mem
theorem erase_add_left_pos {a : α} {s : multiset α} (t) : a ∈ s → (s + t).erase a = s.erase a + t :=
quotient.induction_on₂ s t $ λ l₁ l₂ h, congr_arg coe $ erase_append_left l₂ h
theorem erase_add_right_pos {a : α} (s) {t : multiset α} (h : a ∈ t) : (s + t).erase a = s + t.erase a :=
by rw [add_comm, erase_add_left_pos s h, add_comm]
theorem erase_add_right_neg {a : α} {s : multiset α} (t) : a ∉ s → (s + t).erase a = s + t.erase a :=
quotient.induction_on₂ s t $ λ l₁ l₂ h, congr_arg coe $ erase_append_right l₂ h
theorem erase_add_left_neg {a : α} (s) {t : multiset α} (h : a ∉ t) : (s + t).erase a = s.erase a + t :=
by rw [add_comm, erase_add_right_neg s h, add_comm]
theorem erase_le (a : α) (s : multiset α) : s.erase a ≤ s :=
quot.induction_on s $ λ l, subperm_of_sublist (erase_sublist a l)
@[simp] theorem erase_lt {a : α} {s : multiset α} : s.erase a < s ↔ a ∈ s :=
⟨λ h, not_imp_comm.1 erase_of_not_mem (ne_of_lt h),
λ h, by simpa [h] using lt_cons_self (s.erase a) a⟩
theorem erase_subset (a : α) (s : multiset α) : s.erase a ⊆ s :=
subset_of_le (erase_le a s)
theorem mem_erase_of_ne {a b : α} {s : multiset α} (ab : a ≠ b) : a ∈ s.erase b ↔ a ∈ s :=
quot.induction_on s $ λ l, list.mem_erase_of_ne ab
theorem mem_of_mem_erase {a b : α} {s : multiset α} : a ∈ s.erase b → a ∈ s :=
mem_of_subset (erase_subset _ _)
theorem erase_comm (s : multiset α) (a b : α) : (s.erase a).erase b = (s.erase b).erase a :=
quot.induction_on s $ λ l, congr_arg coe $ l.erase_comm a b
theorem erase_le_erase {s t : multiset α} (a : α) (h : s ≤ t) : s.erase a ≤ t.erase a :=
le_induction_on h $ λ l₁ l₂ h, subperm_of_sublist (erase_sublist_erase _ h)
theorem erase_le_iff_le_cons {s t : multiset α} {a : α} : s.erase a ≤ t ↔ s ≤ a :: t :=
⟨λ h, le_trans (le_cons_erase _ _) (cons_le_cons _ h),
λ h, if m : a ∈ s
then by rw ← cons_erase m at h; exact (cons_le_cons_iff _).1 h
else le_trans (erase_le _ _) ((le_cons_of_not_mem m).1 h)⟩
end erase
@[simp] theorem coe_reverse (l : list α) : (reverse l : multiset α) = l :=
quot.sound $ reverse_perm _
/- map -/
/-- `map f s` is the lift of the list `map` operation. The multiplicity
of `b` in `map f s` is the number of `a ∈ s` (counting multiplicity)
such that `f a = b`. -/
def map (f : α → β) (s : multiset α) : multiset β :=
quot.lift_on s (λ l : list α, (l.map f : multiset β))
(λ l₁ l₂ p, quot.sound (perm_map f p))
@[simp] theorem coe_map (f : α → β) (l : list α) : map f ↑l = l.map f := rfl
@[simp] theorem map_zero (f : α → β) : map f 0 = 0 := rfl
@[simp] theorem map_cons (f : α → β) (a s) : map f (a::s) = f a :: map f s :=
quot.induction_on s $ λ l, rfl
@[simp] lemma map_singleton (f : α → β) (a : α) : ({a} : multiset α).map f = {f a} := rfl
@[simp] theorem map_add (f : α → β) (s t) : map f (s + t) = map f s + map f t :=
quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe $ map_append _ _ _
@[simp] theorem mem_map {f : α → β} {b : β} {s : multiset α} :
b ∈ map f s ↔ ∃ a, a ∈ s ∧ f a = b :=
quot.induction_on s $ λ l, mem_map
@[simp] theorem card_map (f : α → β) (s) : card (map f s) = card s :=
quot.induction_on s $ λ l, length_map _ _
theorem mem_map_of_mem (f : α → β) {a : α} {s : multiset α} (h : a ∈ s) : f a ∈ map f s :=
mem_map.2 ⟨_, h, rfl⟩
@[simp] theorem mem_map_of_inj {f : α → β} (H : function.injective f) {a : α} {s : multiset α} :
f a ∈ map f s ↔ a ∈ s :=
quot.induction_on s $ λ l, mem_map_of_inj H
@[simp] theorem map_map (g : β → γ) (f : α → β) (s : multiset α) : map g (map f s) = map (g ∘ f) s :=
quot.induction_on s $ λ l, congr_arg coe $ map_map _ _ _
@[simp] theorem map_id (s : multiset α) : map id s = s :=
quot.induction_on s $ λ l, congr_arg coe $ map_id _
@[simp] theorem map_const (s : multiset α) (b : β) : map (function.const α b) s = repeat b s.card :=
quot.induction_on s $ λ l, congr_arg coe $ map_const _ _
@[congr] theorem map_congr {f g : α → β} {s : multiset α} : (∀ x ∈ s, f x = g x) → map f s = map g s :=
quot.induction_on s $ λ l H, congr_arg coe $ map_congr H
lemma map_hcongr {β' : Type*} {m : multiset α} {f : α → β} {f' : α → β'}
(h : β = β') (hf : ∀a∈m, f a == f' a) : map f m == map f' m :=
begin subst h, simp at hf, simp [map_congr hf] end
theorem eq_of_mem_map_const {b₁ b₂ : β} {l : list α} (h : b₁ ∈ map (function.const α b₂) l) : b₁ = b₂ :=
eq_of_mem_repeat $ by rwa map_const at h
@[simp] theorem map_le_map {f : α → β} {s t : multiset α} (h : s ≤ t) : map f s ≤ map f t :=
le_induction_on h $ λ l₁ l₂ h, subperm_of_sublist $ map_sublist_map f h
@[simp] theorem map_subset_map {f : α → β} {s t : multiset α} (H : s ⊆ t) : map f s ⊆ map f t :=
λ b m, let ⟨a, h, e⟩ := mem_map.1 m in mem_map.2 ⟨a, H h, e⟩
/- fold -/
/-- `foldl f H b s` is the lift of the list operation `foldl f b l`,
which folds `f` over the multiset. It is well defined when `f` is right-commutative,
that is, `f (f b a₁) a₂ = f (f b a₂) a₁`. -/
def foldl (f : β → α → β) (H : right_commutative f) (b : β) (s : multiset α) : β :=
quot.lift_on s (λ l, foldl f b l)
(λ l₁ l₂ p, foldl_eq_of_perm H p b)
@[simp] theorem foldl_zero (f : β → α → β) (H b) : foldl f H b 0 = b := rfl
@[simp] theorem foldl_cons (f : β → α → β) (H b a s) : foldl f H b (a :: s) = foldl f H (f b a) s :=
quot.induction_on s $ λ l, rfl
@[simp] theorem foldl_add (f : β → α → β) (H b s t) : foldl f H b (s + t) = foldl f H (foldl f H b s) t :=
quotient.induction_on₂ s t $ λ l₁ l₂, foldl_append _ _ _ _
/-- `foldr f H b s` is the lift of the list operation `foldr f b l`,
which folds `f` over the multiset. It is well defined when `f` is left-commutative,
that is, `f a₁ (f a₂ b) = f a₂ (f a₁ b)`. -/
def foldr (f : α → β → β) (H : left_commutative f) (b : β) (s : multiset α) : β :=
quot.lift_on s (λ l, foldr f b l)
(λ l₁ l₂ p, foldr_eq_of_perm H p b)
@[simp] theorem foldr_zero (f : α → β → β) (H b) : foldr f H b 0 = b := rfl
@[simp] theorem foldr_cons (f : α → β → β) (H b a s) : foldr f H b (a :: s) = f a (foldr f H b s) :=
quot.induction_on s $ λ l, rfl
@[simp] theorem foldr_add (f : α → β → β) (H b s t) : foldr f H b (s + t) = foldr f H (foldr f H b t) s :=
quotient.induction_on₂ s t $ λ l₁ l₂, foldr_append _ _ _ _
@[simp] theorem coe_foldr (f : α → β → β) (H : left_commutative f) (b : β) (l : list α) :
foldr f H b l = l.foldr f b := rfl
@[simp] theorem coe_foldl (f : β → α → β) (H : right_commutative f) (b : β) (l : list α) :
foldl f H b l = l.foldl f b := rfl
theorem coe_foldr_swap (f : α → β → β) (H : left_commutative f) (b : β) (l : list α) :
foldr f H b l = l.foldl (λ x y, f y x) b :=
(congr_arg (foldr f H b) (coe_reverse l)).symm.trans $ foldr_reverse _ _ _
theorem foldr_swap (f : α → β → β) (H : left_commutative f) (b : β) (s : multiset α) :
foldr f H b s = foldl (λ x y, f y x) (λ x y z, (H _ _ _).symm) b s :=
quot.induction_on s $ λ l, coe_foldr_swap _ _ _ _
theorem foldl_swap (f : β → α → β) (H : right_commutative f) (b : β) (s : multiset α) :
foldl f H b s = foldr (λ x y, f y x) (λ x y z, (H _ _ _).symm) b s :=
(foldr_swap _ _ _ _).symm
/-- Product of a multiset given a commutative monoid structure on `α`.
`prod {a, b, c} = a * b * c` -/
def prod [comm_monoid α] : multiset α → α :=
foldr (*) (λ x y z, by simp [mul_left_comm]) 1
attribute [to_additive multiset.sum._proof_1] prod._proof_1
attribute [to_additive multiset.sum] prod
@[to_additive multiset.sum_eq_foldr]
theorem prod_eq_foldr [comm_monoid α] (s : multiset α) :
prod s = foldr (*) (λ x y z, by simp [mul_left_comm]) 1 s := rfl
@[to_additive multiset.sum_eq_foldl]
theorem prod_eq_foldl [comm_monoid α] (s : multiset α) :
prod s = foldl (*) (λ x y z, by simp [mul_right_comm]) 1 s :=
(foldr_swap _ _ _ _).trans (by simp [mul_comm])
@[simp, to_additive multiset.coe_sum]
theorem coe_prod [comm_monoid α] (l : list α) : prod ↑l = l.prod :=
prod_eq_foldl _
@[simp, to_additive multiset.sum_zero]
theorem prod_zero [comm_monoid α] : @prod α _ 0 = 1 := rfl
@[simp, to_additive multiset.sum_cons]
theorem prod_cons [comm_monoid α] (a : α) (s) : prod (a :: s) = a * prod s :=
foldr_cons _ _ _ _ _
@[simp, to_additive multiset.sum_add]
theorem prod_add [comm_monoid α] (s t : multiset α) : prod (s + t) = prod s * prod t :=
quotient.induction_on₂ s t $ λ l₁ l₂, by simp
@[simp] theorem prod_repeat [comm_monoid α] (a : α) (n : ℕ) : prod (multiset.repeat a n) = a ^ n :=
by simp [repeat, list.prod_repeat]
@[simp] theorem sum_repeat [add_comm_monoid α] : ∀ (a : α) (n : ℕ), sum (multiset.repeat a n) = n • a :=
@prod_repeat (multiplicative α) _
attribute [to_additive multiset.sum_repeat] prod_repeat
@[simp, to_additive multiset.sum_map_add]
lemma prod_map_mul [comm_monoid γ] {m : multiset α} {f g : α → γ} :
prod (m.map $ λa, f a * g a) = prod (m.map f) * prod (m.map g) :=
multiset.induction_on m (by simp) (assume a m ih, by simp [ih]; cc)
lemma prod_map_prod_map [comm_monoid γ] (m : multiset α) (n : multiset β) {f : α → β → γ} :
prod (m.map $ λa, prod $ n.map $ λb, f a b) = prod (n.map $ λb, prod $ m.map $ λa, f a b) :=
multiset.induction_on m (by simp) (assume a m ih, by simp [ih])
lemma sum_map_sum_map [add_comm_monoid γ] : ∀ (m : multiset α) (n : multiset β) {f : α → β → γ},
sum (m.map $ λa, sum $ n.map $ λb, f a b) = sum (n.map $ λb, sum $ m.map $ λa, f a b) :=
@prod_map_prod_map _ _ (multiplicative γ) _
attribute [to_additive multiset.sum_map_sum_map] prod_map_prod_map
/- join -/
/-- `join S`, where `S` is a multiset of multisets, is the lift of the list join
operation, that is, the union of all the sets.
join {{1, 2}, {1, 2}, {0, 1}} = {0, 1, 1, 1, 2, 2} -/
def join : multiset (multiset α) → multiset α := sum
theorem coe_join : ∀ L : list (list α),
join (L.map (@coe _ (multiset α) _) : multiset (multiset α)) = L.join
| [] := rfl
| (l :: L) := congr_arg (λ s : multiset α, ↑l + s) (coe_join L)
@[simp] theorem join_zero : @join α 0 = 0 := rfl
@[simp] theorem join_cons (s S) : @join α (s :: S) = s + join S :=
sum_cons _ _
@[simp] theorem join_add (S T) : @join α (S + T) = join S + join T :=
sum_add _ _
@[simp] theorem mem_join {a S} : a ∈ @join α S ↔ ∃ s ∈ S, a ∈ s :=
multiset.induction_on S (by simp) $
by simp [or_and_distrib_right, exists_or_distrib] {contextual := tt}
@[simp] theorem card_join (S) : card (@join α S) = sum (map card S) :=
multiset.induction_on S (by simp) (by simp)
/- bind -/
/-- `bind s f` is the monad bind operation, defined as `join (map f s)`.
It is the union of `f a` as `a` ranges over `s`. -/
def bind (s : multiset α) (f : α → multiset β) : multiset β :=
join (map f s)
@[simp] theorem coe_bind (l : list α) (f : α → list β) :
@bind α β l (λ a, f a) = l.bind f :=
by rw [list.bind, ← coe_join, list.map_map]; refl
@[simp] theorem zero_bind (f : α → multiset β) : bind 0 f = 0 := rfl
@[simp] theorem cons_bind (a s) (f : α → multiset β) : bind (a::s) f = f a + bind s f :=
by simp [bind]
@[simp] theorem add_bind (s t) (f : α → multiset β) : bind (s + t) f = bind s f + bind t f :=
by simp [bind]
@[simp] theorem mem_bind {b s} {f : α → multiset β} : b ∈ bind s f ↔ ∃ a ∈ s, b ∈ f a :=
by simp [bind]; simp [-exists_and_distrib_right, exists_and_distrib_right.symm];
rw exists_swap; simp [and_assoc]
@[simp] theorem card_bind (s) (f : α → multiset β) : card (bind s f) = sum (map (card ∘ f) s) :=
by simp [bind]
lemma bind_congr {f g : α → multiset β} {m : multiset α} : (∀a∈m, f a = g a) → bind m f = bind m g :=
by simp [bind] {contextual := tt}
lemma bind_hcongr {β' : Type*} {m : multiset α} {f : α → multiset β} {f' : α → multiset β'}
(h : β = β') (hf : ∀a∈m, f a == f' a) : bind m f == bind m f' :=
begin subst h, simp at hf, simp [bind_congr hf] end
lemma map_bind [decidable_eq γ] (m : multiset α) (n : α → multiset β) (f : β → γ) :
map f (bind m n) = bind m (λa, map f (n a)) :=
multiset.induction_on m (by simp) (by simp {contextual := tt})
@[simp, to_additive multiset.sum_bind]
lemma prod_bind [comm_monoid β] (s : multiset α) (t : α → multiset β) :
prod (bind s t) = prod (s.map $ λa, prod (t a)) :=
multiset.induction_on s (by simp) (assume a s ih, by simp [ih, cons_bind])
/- product -/
/-- The multiplicity of `(a, b)` in `product s t` is
the product of the multiplicity of `a` in `s` and `b` in `t`. -/
def product (s : multiset α) (t : multiset β) : multiset (α × β) :=
s.bind $ λ a, t.map $ prod.mk a
@[simp] theorem coe_product (l₁ : list α) (l₂ : list β) :
@product α β l₁ l₂ = l₁.product l₂ :=
by rw [product, list.product, ← coe_bind]; simp
@[simp] theorem zero_product (t) : @product α β 0 t = 0 := rfl
@[simp] theorem cons_product (a : α) (s : multiset α) (t : multiset β) :
product (a :: s) t = map (prod.mk a) t + product s t :=
by simp [product]
@[simp] theorem product_singleton (a : α) (b : β) : product (a::0) (b::0) = (a,b)::0 := rfl
@[simp] theorem add_product (s t : multiset α) (u : multiset β) :
product (s + t) u = product s u + product t u :=
by simp [product]
@[simp] theorem product_add (s : multiset α) : ∀ t u : multiset β,
product s (t + u) = product s t + product s u :=
multiset.induction_on s (λ t u, rfl) $ λ a s IH t u,
by rw [cons_product, IH]; simp
@[simp] theorem mem_product {s t} : ∀ {p : α × β}, p ∈ @product α β s t ↔ p.1 ∈ s ∧ p.2 ∈ t
| (a, b) := by simp [product, and.left_comm]
@[simp] theorem card_product (s : multiset α) (t : multiset β) : card (product s t) = card s * card t :=
by simp [product, repeat, (∘), mul_comm]
/- sigma -/
section
variable {σ : α → Type*}
/-- `sigma s t` is the dependent version of `product`. It is the sum of
`(a, b)` as `a` ranges over `s` and `b` ranges over `t a`. -/
protected def sigma (s : multiset α) (t : Π a, multiset (σ a)) : multiset (Σ a, σ a) :=
s.bind $ λ a, (t a).map $ sigma.mk a
@[simp] theorem coe_sigma (l₁ : list α) (l₂ : Π a, list (σ a)) :
@multiset.sigma α σ l₁ (λ a, l₂ a) = l₁.sigma l₂ :=
by rw [multiset.sigma, list.sigma, ← coe_bind]; simp
@[simp] theorem zero_sigma (t) : @multiset.sigma α σ 0 t = 0 := rfl
@[simp] theorem cons_sigma (a : α) (s : multiset α) (t : Π a, multiset (σ a)) :
(a :: s).sigma t = map (sigma.mk a) (t a) + s.sigma t :=
by simp [multiset.sigma]
@[simp] theorem sigma_singleton (a : α) (b : α → β) :
(a::0).sigma (λ a, b a::0) = ⟨a, b a⟩::0 := rfl
@[simp] theorem add_sigma (s t : multiset α) (u : Π a, multiset (σ a)) :
(s + t).sigma u = s.sigma u + t.sigma u :=
by simp [multiset.sigma]
@[simp] theorem sigma_add (s : multiset α) : ∀ t u : Π a, multiset (σ a),
s.sigma (λ a, t a + u a) = s.sigma t + s.sigma u :=
multiset.induction_on s (λ t u, rfl) $ λ a s IH t u,
by rw [cons_sigma, IH]; simp
@[simp] theorem mem_sigma {s t} : ∀ {p : Σ a, σ a},
p ∈ @multiset.sigma α σ s t ↔ p.1 ∈ s ∧ p.2 ∈ t p.1
| ⟨a, b⟩ := by simp [multiset.sigma, and_assoc, and.left_comm]
@[simp] theorem card_sigma (s : multiset α) (t : Π a, multiset (σ a)) :
card (s.sigma t) = sum (map (λ a, card (t a)) s) :=
by simp [multiset.sigma, (∘)]
end
/- map for partial functions -/
/-- Lift of the list `pmap` operation. Map a partial function `f` over a multiset
`s` whose elements are all in the domain of `f`. -/
def pmap {p : α → Prop} (f : Π a, p a → β) (s : multiset α) : (∀ a ∈ s, p a) → multiset β :=
quot.rec_on s (λ l H, ↑(pmap f l H)) $ λ l₁ l₂ (pp : l₁ ~ l₂),
funext $ λ (H₂ : ∀ a ∈ l₂, p a),
have H₁ : ∀ a ∈ l₁, p a, from λ a h, H₂ a ((mem_of_perm pp).1 h),
have ∀ {s₂ e H}, @eq.rec (multiset α) l₁
(λ s, (∀ a ∈ s, p a) → multiset β) (λ _, ↑(pmap f l₁ H₁))
s₂ e H = ↑(pmap f l₁ H₁), by intros s₂ e _; subst e,
this.trans $ quot.sound $ perm_pmap f pp
@[simp] theorem coe_pmap {p : α → Prop} (f : Π a, p a → β)
(l : list α) (H : ∀ a ∈ l, p a) : pmap f l H = l.pmap f H := rfl
@[simp] lemma pmap_zero {p : α → Prop} (f : Π a, p a → β) (h : ∀a∈(0:multiset α), p a) :
pmap f 0 h = 0 := rfl
@[simp] lemma pmap_cons {p : α → Prop} (f : Π a, p a → β) (a : α) (m : multiset α) :
∀(h : ∀b∈a::m, p b), pmap f (a :: m) h =
f a (h a (mem_cons_self a m)) :: pmap f m (λa ha, h a $ mem_cons_of_mem ha) :=
quotient.induction_on m $ assume l h, rfl
/-- "Attach" a proof that `a ∈ s` to each element `a` in `s` to produce
a multiset on `{x // x ∈ s}`. -/
def attach (s : multiset α) : multiset {x // x ∈ s} := pmap subtype.mk s (λ a, id)
@[simp] theorem coe_attach (l : list α) :
@eq (multiset {x // x ∈ l}) (@attach α l) l.attach := rfl
theorem pmap_eq_map (p : α → Prop) (f : α → β) (s : multiset α) :
∀ H, @pmap _ _ p (λ a _, f a) s H = map f s :=
quot.induction_on s $ λ l H, congr_arg coe $ pmap_eq_map p f l H
theorem pmap_congr {p q : α → Prop} {f : Π a, p a → β} {g : Π a, q a → β}
(s : multiset α) {H₁ H₂} (h : ∀ a h₁ h₂, f a h₁ = g a h₂) :
pmap f s H₁ = pmap g s H₂ :=
quot.induction_on s (λ l H₁ H₂, congr_arg coe $ pmap_congr l h) H₁ H₂
theorem map_pmap {p : α → Prop} (g : β → γ) (f : Π a, p a → β)
(s) : ∀ H, map g (pmap f s H) = pmap (λ a h, g (f a h)) s H :=
quot.induction_on s $ λ l H, congr_arg coe $ map_pmap g f l H
theorem pmap_eq_map_attach {p : α → Prop} (f : Π a, p a → β)
(s) : ∀ H, pmap f s H = s.attach.map (λ x, f x.1 (H _ x.2)) :=
quot.induction_on s $ λ l H, congr_arg coe $ pmap_eq_map_attach f l H
theorem attach_map_val (s : multiset α) : s.attach.map subtype.val = s :=
quot.induction_on s $ λ l, congr_arg coe $ attach_map_val l
@[simp] theorem mem_attach (s : multiset α) : ∀ x, x ∈ s.attach :=
quot.induction_on s $ λ l, mem_attach _
@[simp] theorem mem_pmap {p : α → Prop} {f : Π a, p a → β}
{s H b} : b ∈ pmap f s H ↔ ∃ a (h : a ∈ s), f a (H a h) = b :=
quot.induction_on s (λ l H, mem_pmap) H
@[simp] theorem card_pmap {p : α → Prop} (f : Π a, p a → β)
(s H) : card (pmap f s H) = card s :=
quot.induction_on s (λ l H, length_pmap) H
@[simp] theorem card_attach {m : multiset α} : card (attach m) = card m := card_pmap _ _ _
@[simp] lemma attach_zero : (0 : multiset α).attach = 0 := rfl
lemma attach_cons (a : α) (m : multiset α) :
(a :: m).attach = ⟨a, mem_cons_self a m⟩ :: (m.attach.map $ λp, ⟨p.1, mem_cons_of_mem p.2⟩) :=
quotient.induction_on m $ assume l, congr_arg coe $ congr_arg (list.cons _) $
by rw [list.map_pmap]; exact list.pmap_congr _ (assume a' h₁ h₂, subtype.eq rfl)
section decidable_pi_multiset
variables {m : multiset α}
protected def decidable_forall_multiset {p : α → Prop} [hp : ∀a, decidable (p a)] :
decidable (∀a∈m, p a) :=
quotient.rec_on_subsingleton m (λl, decidable_of_iff (∀a∈l, p a) $ by simp)
instance decidable_dforall_multiset {p : Πa∈m, Prop} [hp : ∀a (h : a ∈ m), decidable (p a h)] :
decidable (∀a (h : a ∈ m), p a h) :=
decidable_of_decidable_of_iff
(@multiset.decidable_forall_multiset {a // a ∈ m} m.attach (λa, p a.1 a.2) _)
(iff.intro (assume h a ha, h ⟨a, ha⟩ (mem_attach _ _)) (assume h ⟨a, ha⟩ _, h _ _))
/-- decidable equality for functions whose domain is bounded by multisets -/
instance decidable_eq_pi_multiset {β : α → Type*} [h : ∀a, decidable_eq (β a)] :
decidable_eq (Πa∈m, β a) :=
assume f g, decidable_of_iff (∀a (h : a ∈ m), f a h = g a h) (by simp [function.funext_iff])
end decidable_pi_multiset
/- subtraction -/
section
variables [decidable_eq α] {s t u : multiset α} {a b : α}
/-- `s - t` is the multiset such that
`count a (s - t) = count a s - count a t` for all `a`. -/
protected def sub (s t : multiset α) : multiset α :=
quotient.lift_on₂ s t (λ l₁ l₂, (l₁.diff l₂ : multiset α)) $ λ v₁ v₂ w₁ w₂ p₁ p₂,
quot.sound $ perm_diff_right w₁ p₂ ▸ perm_diff_left _ p₁
instance : has_sub (multiset α) := ⟨multiset.sub⟩
@[simp] theorem coe_sub (s t : list α) : (s - t : multiset α) = (s.diff t : list α) := rfl
theorem sub_eq_fold_erase (s t : multiset α) : s - t = foldl erase erase_comm s t :=
quotient.induction_on₂ s t $ λ l₁ l₂,
show ↑(l₁.diff l₂) = foldl erase erase_comm ↑l₁ ↑l₂,
by rw diff_eq_foldl l₁ l₂; exact foldl_hom _ _ _ _ (λ x y, rfl) _
@[simp] theorem sub_zero (s : multiset α) : s - 0 = s :=
quot.induction_on s $ λ l, rfl
@[simp] theorem sub_cons (a : α) (s t : multiset α) : s - a::t = s.erase a - t :=
quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe $ diff_cons _ _ _
theorem add_sub_of_le (h : s ≤ t) : s + (t - s) = t :=
begin
revert t,
refine multiset.induction_on s (by simp) (λ a s IH t h, _),
have := cons_erase (mem_of_le h (mem_cons_self _ _)),
rw [cons_add, sub_cons, IH, this],
exact (cons_le_cons_iff a).1 (this.symm ▸ h)
end
theorem sub_add' : s - (t + u) = s - t - u :=
quotient.induction_on₃ s t u $
λ l₁ l₂ l₃, congr_arg coe $ diff_append _ _ _
theorem sub_add_cancel (h : t ≤ s) : s - t + t = s :=
by rw [add_comm, add_sub_of_le h]
theorem add_sub_cancel_left (s : multiset α) : ∀ t, s + t - s = t :=
multiset.induction_on s (by simp)
(λ a s IH t, by rw [cons_add, sub_cons, erase_cons_head, IH])
theorem add_sub_cancel (s t : multiset α) : s + t - t = s :=
by rw [add_comm, add_sub_cancel_left]
theorem sub_le_sub_right (h : s ≤ t) (u) : s - u ≤ t - u :=
by revert s t h; exact
multiset.induction_on u (by simp {contextual := tt})
(λ a u IH s t h, by simp [IH, erase_le_erase a h])
theorem sub_le_sub_left (h : s ≤ t) : ∀ u, u - t ≤ u - s :=
le_induction_on h $ λ l₁ l₂ h, begin
induction h with l₁ l₂ a s IH l₁ l₂ a s IH; intro u,
{ refl },
{ rw [← cons_coe, sub_cons],
exact le_trans (sub_le_sub_right (erase_le _ _) _) (IH u) },
{ rw [← cons_coe, sub_cons, ← cons_coe, sub_cons],
exact IH _ }
end
theorem sub_le_iff_le_add : s - t ≤ u ↔ s ≤ u + t :=
by revert s; exact
multiset.induction_on t (by simp)
(λ a t IH s, by simp [IH, erase_le_iff_le_cons])
theorem le_sub_add (s t : multiset α) : s ≤ s - t + t :=
sub_le_iff_le_add.1 (le_refl _)
theorem sub_le_self (s t : multiset α) : s - t ≤ s :=
sub_le_iff_le_add.2 (le_add_right _ _)
@[simp] theorem card_sub {s t : multiset α} (h : t ≤ s) : card (s - t) = card s - card t :=
(nat.sub_eq_of_eq_add $ by rw [add_comm, ← card_add, sub_add_cancel h]).symm
/- union -/
/-- `s ∪ t` is the lattice join operation with respect to the
multiset `≤`. The multiplicity of `a` in `s ∪ t` is the maximum
of the multiplicities in `s` and `t`. -/
def union (s t : multiset α) : multiset α := s - t + t
instance : has_union (multiset α) := ⟨union⟩
theorem union_def (s t : multiset α) : s ∪ t = s - t + t := rfl
theorem le_union_left (s t : multiset α) : s ≤ s ∪ t := le_sub_add _ _
theorem le_union_right (s t : multiset α) : t ≤ s ∪ t := le_add_left _ _
theorem eq_union_left : t ≤ s → s ∪ t = s := sub_add_cancel
theorem union_le_union_right (h : s ≤ t) (u) : s ∪ u ≤ t ∪ u :=
add_le_add_right (sub_le_sub_right h _) u
theorem union_le (h₁ : s ≤ u) (h₂ : t ≤ u) : s ∪ t ≤ u :=
by rw ← eq_union_left h₂; exact union_le_union_right h₁ t
@[simp] theorem mem_union : a ∈ s ∪ t ↔ a ∈ s ∨ a ∈ t :=
⟨λ h, (mem_add.1 h).imp_left (mem_of_le $ sub_le_self _ _),
or.rec (mem_of_le $ le_union_left _ _) (mem_of_le $ le_union_right _ _)⟩
/- inter -/
/-- `s ∩ t` is the lattice meet operation with respect to the
multiset `≤`. The multiplicity of `a` in `s ∩ t` is the minimum
of the multiplicities in `s` and `t`. -/
def inter (s t : multiset α) : multiset α :=
quotient.lift_on₂ s t (λ l₁ l₂, (l₁.bag_inter l₂ : multiset α)) $ λ v₁ v₂ w₁ w₂ p₁ p₂,
quot.sound $ perm_bag_inter_right w₁ p₂ ▸ perm_bag_inter_left _ p₁
instance : has_inter (multiset α) := ⟨inter⟩
@[simp] theorem inter_zero (s : multiset α) : s ∩ 0 = 0 :=
quot.induction_on s $ λ l, congr_arg coe l.bag_inter_nil
@[simp] theorem zero_inter (s : multiset α) : 0 ∩ s = 0 :=
quot.induction_on s $ λ l, congr_arg coe l.nil_bag_inter
@[simp] theorem cons_inter_of_pos {a} (s : multiset α) {t} :
a ∈ t → (a :: s) ∩ t = a :: s ∩ t.erase a :=
quotient.induction_on₂ s t $ λ l₁ l₂ h,
congr_arg coe $ cons_bag_inter_of_pos _ h
@[simp] theorem cons_inter_of_neg {a} (s : multiset α) {t} :
a ∉ t → (a :: s) ∩ t = s ∩ t :=
quotient.induction_on₂ s t $ λ l₁ l₂ h,
congr_arg coe $ cons_bag_inter_of_neg _ h
theorem inter_le_left (s t : multiset α) : s ∩ t ≤ s :=
quotient.induction_on₂ s t $ λ l₁ l₂,
subperm_of_sublist $ bag_inter_sublist_left _ _
theorem inter_le_right (s : multiset α) : ∀ t, s ∩ t ≤ t :=
multiset.induction_on s (λ t, (zero_inter t).symm ▸ zero_le _) $
λ a s IH t, if h : a ∈ t
then by simpa [h] using cons_le_cons a (IH (t.erase a))
else by simp [h, IH]
theorem le_inter (h₁ : s ≤ t) (h₂ : s ≤ u) : s ≤ t ∩ u :=
begin
revert s u, refine multiset.induction_on t _ (λ a t IH, _); intros,
{ simp [h₁] },
by_cases a ∈ u,
{ rw [cons_inter_of_pos _ h, ← erase_le_iff_le_cons],
exact IH (erase_le_iff_le_cons.2 h₁) (erase_le_erase _ h₂) },
{ rw cons_inter_of_neg _ h,
exact IH ((le_cons_of_not_mem $ mt (mem_of_le h₂) h).1 h₁) h₂ }
end
@[simp] theorem mem_inter : a ∈ s ∩ t ↔ a ∈ s ∧ a ∈ t :=
⟨λ h, ⟨mem_of_le (inter_le_left _ _) h, mem_of_le (inter_le_right _ _) h⟩,
λ ⟨h₁, h₂⟩, by rw [← cons_erase h₁, cons_inter_of_pos _ h₂]; apply mem_cons_self⟩
instance : lattice (multiset α) :=
{ sup := (∪),
sup_le := @union_le _ _,
le_sup_left := le_union_left,
le_sup_right := le_union_right,
inf := (∩),
le_inf := @le_inter _ _,
inf_le_left := inter_le_left,
inf_le_right := inter_le_right,
..@multiset.partial_order α }
@[simp] theorem sup_eq_union (s t : multiset α) : s ⊔ t = s ∪ t := rfl
@[simp] theorem inf_eq_inter (s t : multiset α) : s ⊓ t = s ∩ t := rfl
@[simp] theorem le_inter_iff : s ≤ t ∩ u ↔ s ≤ t ∧ s ≤ u := le_inf_iff
@[simp] theorem union_le_iff : s ∪ t ≤ u ↔ s ≤ u ∧ t ≤ u := sup_le_iff
instance : semilattice_inf_bot (multiset α) :=
{ bot := 0, bot_le := zero_le, ..multiset.lattice.lattice }
theorem union_comm (s t : multiset α) : s ∪ t = t ∪ s := sup_comm
theorem inter_comm (s t : multiset α) : s ∩ t = t ∩ s := inf_comm
theorem eq_union_right (h : s ≤ t) : s ∪ t = t :=
by rw [union_comm, eq_union_left h]
theorem union_le_union_left (h : s ≤ t) (u) : u ∪ s ≤ u ∪ t :=
sup_le_sup_left h _
theorem union_le_add (s t : multiset α) : s ∪ t ≤ s + t :=
union_le (le_add_right _ _) (le_add_left _ _)
theorem union_add_distrib (s t u : multiset α) : (s ∪ t) + u = (s + u) ∪ (t + u) :=
by simpa [(∪), union, eq_comm] using show s + u - (t + u) = s - t,
by rw [add_comm t, sub_add', add_sub_cancel]
theorem add_union_distrib (s t u : multiset α) : s + (t ∪ u) = (s + t) ∪ (s + u) :=
by rw [add_comm, union_add_distrib, add_comm s, add_comm s]
theorem cons_union_distrib (a : α) (s t : multiset α) : a :: (s ∪ t) = (a :: s) ∪ (a :: t) :=
by simpa using add_union_distrib (a::0) s t
theorem inter_add_distrib (s t u : multiset α) : (s ∩ t) + u = (s + u) ∩ (t + u) :=
begin
by_contra h,
cases lt_iff_cons_le.1 (lt_of_le_of_ne (le_inter
(add_le_add_right (inter_le_left s t) u)
(add_le_add_right (inter_le_right s t) u)) h) with a hl,
rw ← cons_add at hl,
exact not_le_of_lt (lt_cons_self (s ∩ t) a) (le_inter
(le_of_add_le_add_right (le_trans hl (inter_le_left _ _)))
(le_of_add_le_add_right (le_trans hl (inter_le_right _ _))))
end
theorem add_inter_distrib (s t u : multiset α) : s + (t ∩ u) = (s + t) ∩ (s + u) :=
by rw [add_comm, inter_add_distrib, add_comm s, add_comm s]
theorem cons_inter_distrib (a : α) (s t : multiset α) : a :: (s ∩ t) = (a :: s) ∩ (a :: t) :=
by simp
theorem union_add_inter (s t : multiset α) : s ∪ t + s ∩ t = s + t :=
begin
apply le_antisymm,
{ rw union_add_distrib,
refine union_le (add_le_add_left (inter_le_right _ _) _) _,
rw add_comm, exact add_le_add_right (inter_le_left _ _) _ },
{ rw [add_comm, add_inter_distrib],
refine le_inter (add_le_add_right (le_union_right _ _) _) _,
rw add_comm, exact add_le_add_right (le_union_left _ _) _ }
end
theorem sub_add_inter (s t : multiset α) : s - t + s ∩ t = s :=
begin
rw [inter_comm],
revert s, refine multiset.induction_on t (by simp) (λ a t IH s, _),
by_cases a ∈ s,
{ rw [cons_inter_of_pos _ h, sub_cons, add_cons, IH, cons_erase h] },
{ rw [cons_inter_of_neg _ h, sub_cons, erase_of_not_mem h, IH] }
end
theorem sub_inter (s t : multiset α) : s - (s ∩ t) = s - t :=
add_right_cancel $
by rw [sub_add_inter s t, sub_add_cancel (inter_le_left _ _)]
end
/- filter -/
section
variables {p : α → Prop} [decidable_pred p]
/-- `filter p s` returns the elements in `s` (with the same multiplicities)
which satisfy `p`, and removes the rest. -/
def filter (p : α → Prop) [h : decidable_pred p] (s : multiset α) : multiset α :=
quot.lift_on s (λ l, (filter p l : multiset α))
(λ l₁ l₂ h, quot.sound $ perm_filter p h)
@[simp] theorem coe_filter (p : α → Prop) [h : decidable_pred p]
(l : list α) : filter p (↑l) = l.filter p := rfl
@[simp] theorem filter_zero (p : α → Prop) [h : decidable_pred p] : filter p 0 = 0 := rfl
@[simp] theorem filter_cons_of_pos {a : α} (s) : p a → filter p (a::s) = a :: filter p s :=
quot.induction_on s $ λ l h, congr_arg coe $ filter_cons_of_pos l h
@[simp] theorem filter_cons_of_neg {a : α} (s) : ¬ p a → filter p (a::s) = filter p s :=
quot.induction_on s $ λ l h, @congr_arg _ _ _ _ coe $ filter_cons_of_neg l h
@[simp] theorem filter_add (s t : multiset α) :
filter p (s + t) = filter p s + filter p t :=
quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe $ filter_append _ _
@[simp] theorem filter_le (s : multiset α) : filter p s ≤ s :=
quot.induction_on s $ λ l, subperm_of_sublist $ filter_sublist _
@[simp] theorem filter_subset (s : multiset α) : filter p s ⊆ s :=
subset_of_le $ filter_le _
@[simp] theorem mem_filter {a : α} {s} : a ∈ filter p s ↔ a ∈ s ∧ p a :=
quot.induction_on s $ λ l, mem_filter
theorem of_mem_filter {a : α} {s} (h : a ∈ filter p s) : p a :=
(mem_filter.1 h).2
theorem mem_of_mem_filter {a : α} {s} (h : a ∈ filter p s) : a ∈ s :=
(mem_filter.1 h).1
theorem mem_filter_of_mem {a : α} {l} (m : a ∈ l) (h : p a) : a ∈ filter p l :=
mem_filter.2 ⟨m, h⟩
theorem filter_eq_self {s} : filter p s = s ↔ ∀ a ∈ s, p a :=
quot.induction_on s $ λ l, iff.trans ⟨λ h,
eq_of_sublist_of_length_eq (filter_sublist _) (@congr_arg _ _ _ _ card h),
congr_arg coe⟩ filter_eq_self
theorem filter_eq_nil {s} : filter p s = 0 ↔ ∀ a ∈ s, ¬p a :=
quot.induction_on s $ λ l, iff.trans ⟨λ h,
eq_nil_of_length_eq_zero (@congr_arg _ _ _ _ card h),
congr_arg coe⟩ filter_eq_nil
theorem filter_le_filter {s t} (h : s ≤ t) : filter p s ≤ filter p t :=
le_induction_on h $ λ l₁ l₂ h, subperm_of_sublist $ filter_sublist_filter h
theorem le_filter {s t} : s ≤ filter p t ↔ s ≤ t ∧ ∀ a ∈ s, p a :=
⟨λ h, ⟨le_trans h (filter_le _), λ a m, of_mem_filter (mem_of_le h m)⟩,
λ ⟨h, al⟩, filter_eq_self.2 al ▸ filter_le_filter h⟩
@[simp] theorem filter_sub [decidable_eq α] (s t : multiset α) :
filter p (s - t) = filter p s - filter p t :=
begin
revert s, refine multiset.induction_on t (by simp) (λ a t IH s, _),
rw [sub_cons, IH],
by_cases p a,
{ rw [filter_cons_of_pos _ h, sub_cons], congr,
by_cases m : a ∈ s,
{ rw [← cons_inj_right a, ← filter_cons_of_pos _ h,
cons_erase (mem_filter_of_mem m h), cons_erase m] },
{ rw [erase_of_not_mem m, erase_of_not_mem (mt mem_of_mem_filter m)] } },
{ rw [filter_cons_of_neg _ h],
by_cases m : a ∈ s,
{ rw [(by rw filter_cons_of_neg _ h : filter p (erase s a) = filter p (a :: erase s a)),
cons_erase m] },
{ rw [erase_of_not_mem m] } }
end
@[simp] theorem filter_union [decidable_eq α] (s t : multiset α) :
filter p (s ∪ t) = filter p s ∪ filter p t :=
by simp [(∪), union]
@[simp] theorem filter_inter [decidable_eq α] (s t : multiset α) :
filter p (s ∩ t) = filter p s ∩ filter p t :=
le_antisymm (le_inter
(filter_le_filter $ inter_le_left _ _)
(filter_le_filter $ inter_le_right _ _)) $ le_filter.2
⟨inf_le_inf (filter_le _) (filter_le _),
λ a h, of_mem_filter (mem_of_le (inter_le_left _ _) h)⟩
/- filter_map -/
/-- `filter_map f s` is a combination filter/map operation on `s`.
The function `f : α → option β` is applied to each element of `s`;
if `f a` is `some b` then `b` is added to the result, otherwise
`a` is removed from the resulting multiset. -/
def filter_map (f : α → option β) (s : multiset α) : multiset β :=
quot.lift_on s (λ l, (filter_map f l : multiset β))
(λ l₁ l₂ h, quot.sound $perm_filter_map f h)
@[simp] theorem coe_filter_map (f : α → option β) (l : list α) : filter_map f l = l.filter_map f := rfl
@[simp] theorem filter_map_zero (f : α → option β) : filter_map f 0 = 0 := rfl
@[simp] theorem filter_map_cons_none {f : α → option β} (a : α) (s : multiset α) (h : f a = none) :
filter_map f (a :: s) = filter_map f s :=
quot.induction_on s $ λ l, @congr_arg _ _ _ _ coe $ filter_map_cons_none a l h
@[simp] theorem filter_map_cons_some (f : α → option β)
(a : α) (s : multiset α) {b : β} (h : f a = some b) :
filter_map f (a :: s) = b :: filter_map f s :=
quot.induction_on s $ λ l, @congr_arg _ _ _ _ coe $ filter_map_cons_some f a l h
theorem filter_map_eq_map (f : α → β) : filter_map (some ∘ f) = map f :=
funext $ λ s, quot.induction_on s $ λ l,
@congr_arg _ _ _ _ coe $ congr_fun (filter_map_eq_map f) l
theorem filter_map_eq_filter (p : α → Prop) [decidable_pred p] :
filter_map (option.guard p) = filter p :=
funext $ λ s, quot.induction_on s $ λ l,
@congr_arg _ _ _ _ coe $ congr_fun (filter_map_eq_filter p) l
theorem filter_map_filter_map (f : α → option β) (g : β → option γ) (s : multiset α) :
filter_map g (filter_map f s) = filter_map (λ x, (f x).bind g) s :=
quot.induction_on s $ λ l, congr_arg coe $ filter_map_filter_map f g l
theorem map_filter_map (f : α → option β) (g : β → γ) (s : multiset α) :
map g (filter_map f s) = filter_map (λ x, (f x).map g) s :=
quot.induction_on s $ λ l, congr_arg coe $ map_filter_map f g l
theorem filter_map_map (f : α → β) (g : β → option γ) (s : multiset α) :
filter_map g (map f s) = filter_map (g ∘ f) s :=
quot.induction_on s $ λ l, congr_arg coe $ filter_map_map f g l
theorem filter_filter_map (f : α → option β) (p : β → Prop) [decidable_pred p] (s : multiset α) :
filter p (filter_map f s) = filter_map (λ x, (f x).filter p) s :=
quot.induction_on s $ λ l, congr_arg coe $ filter_filter_map f p l
theorem filter_map_filter (p : α → Prop) [decidable_pred p] (f : α → option β) (s : multiset α) :
filter_map f (filter p s) = filter_map (λ x, if p x then f x else none) s :=
quot.induction_on s $ λ l, congr_arg coe $ filter_map_filter p f l
@[simp] theorem filter_map_some (s : multiset α) : filter_map some s = s :=
quot.induction_on s $ λ l, congr_arg coe $ filter_map_some l
@[simp] theorem mem_filter_map (f : α → option β) (s : multiset α) {b : β} :
b ∈ filter_map f s ↔ ∃ a, a ∈ s ∧ f a = some b :=
quot.induction_on s $ λ l, mem_filter_map f l
theorem map_filter_map_of_inv (f : α → option β) (g : β → α)
(H : ∀ x : α, (f x).map g = some x) (s : multiset α) :
map g (filter_map f s) = s :=
quot.induction_on s $ λ l, congr_arg coe $ map_filter_map_of_inv f g H l
theorem filter_map_le_filter_map (f : α → option β) {s t : multiset α}
(h : s ≤ t) : filter_map f s ≤ filter_map f t :=
le_induction_on h $ λ l₁ l₂ h,
subperm_of_sublist $ filter_map_sublist_filter_map _ h
/- powerset -/
def powerset_aux (l : list α) : list (multiset α) :=
0 :: sublists_aux l (λ x y, x :: y)
theorem powerset_aux_eq_map_coe {l : list α} :
powerset_aux l = (sublists l).map coe :=
by simp [powerset_aux, sublists];
rw [← show @sublists_aux₁ α (multiset α) l (λ x, [↑x]) =
sublists_aux l (λ x, list.cons ↑x),
from sublists_aux₁_eq_sublists_aux _ _,
sublists_aux_cons_eq_sublists_aux₁,
← bind_ret_eq_map, sublists_aux₁_bind]; refl
def powerset_aux' (l : list α) : list (multiset α) := (sublists' l).map coe
theorem powerset_aux_perm_powerset_aux' {l : list α} :
powerset_aux l ~ powerset_aux' l :=
by rw powerset_aux_eq_map_coe; exact
perm_map _ (sublists_perm_sublists' _)
@[simp] theorem powerset_aux'_nil : powerset_aux' (@nil α) = [0] := rfl
@[simp] theorem powerset_aux'_cons (a : α) (l : list α) :
powerset_aux' (a::l) = powerset_aux' l ++ list.map (cons a) (powerset_aux' l) :=
by simp [powerset_aux']; refl
theorem powerset_aux'_perm {l₁ l₂ : list α} (p : l₁ ~ l₂) :
powerset_aux' l₁ ~ powerset_aux' l₂ :=
begin
induction p with a l₁ l₂ p IH a b l l₁ l₂ l₃ p₁ p₂ IH₁ IH₂, {simp},
{ simp, exact perm_app IH (perm_map _ IH) },
{ simp, apply perm_app_right,
rw [← append_assoc, ← append_assoc,
(by funext s; simp [cons_swap] : cons b ∘ cons a = cons a ∘ cons b)],
exact perm_app_left _ perm_app_comm },
{ exact IH₁.trans IH₂ }
end
theorem powerset_aux_perm {l₁ l₂ : list α} (p : l₁ ~ l₂) :
powerset_aux l₁ ~ powerset_aux l₂ :=
powerset_aux_perm_powerset_aux'.trans $
(powerset_aux'_perm p).trans powerset_aux_perm_powerset_aux'.symm
def powerset (s : multiset α) : multiset (multiset α) :=
quot.lift_on s
(λ l, (powerset_aux l : multiset (multiset α)))
(λ l₁ l₂ h, quot.sound (powerset_aux_perm h))
theorem powerset_coe (l : list α) :
@powerset α l = ((sublists l).map coe : list (multiset α)) :=
congr_arg coe powerset_aux_eq_map_coe
@[simp] theorem powerset_coe' (l : list α) :
@powerset α l = ((sublists' l).map coe : list (multiset α)) :=
quot.sound powerset_aux_perm_powerset_aux'
@[simp] theorem mem_powerset {s t : multiset α} :
s ∈ powerset t ↔ s ≤ t :=
quotient.induction_on₂ s t $ by simp [subperm, and.comm]
theorem map_single_le_powerset (s : multiset α) :
s.map (λ a, a::0) ≤ powerset s :=
quotient.induction_on s $ λ l, begin
simp [powerset_coe],
show l.map (coe ∘ list.ret) <+~ (sublists l).map coe,
rw ← list.map_map,
exact subperm_of_sublist
(map_sublist_map _ (map_ret_sublist_sublists _))
end
@[simp] theorem card_powerset (s : multiset α) :
card (powerset s) = 2 ^ card s :=
quotient.induction_on s $ by simp
/- countp -/
/-- `countp p s` counts the number of elements of `s` (with multiplicity) that
satisfy `p`. -/
def countp (p : α → Prop) [decidable_pred p] (s : multiset α) : ℕ :=
quot.lift_on s (countp p) (λ l₁ l₂, perm_countp p)
@[simp] theorem coe_countp (l : list α) : countp p l = l.countp p := rfl
@[simp] theorem countp_zero (p : α → Prop) [decidable_pred p] : countp p 0 = 0 := rfl
@[simp] theorem countp_cons_of_pos {a : α} (s) : p a → countp p (a::s) = countp p s + 1 :=
quot.induction_on s countp_cons_of_pos
@[simp] theorem countp_cons_of_neg {a : α} (s) : ¬ p a → countp p (a::s) = countp p s :=
quot.induction_on s countp_cons_of_neg
theorem countp_eq_card_filter (s) : countp p s = card (filter p s) :=
quot.induction_on s $ λ l, countp_eq_length_filter _
@[simp] theorem countp_add (s t) : countp p (s + t) = countp p s + countp p t :=
by simp [countp_eq_card_filter]
theorem countp_pos {s} : 0 < countp p s ↔ ∃ a ∈ s, p a :=
by simp [countp_eq_card_filter, card_pos_iff_exists_mem]
@[simp] theorem countp_sub [decidable_eq α] {s t : multiset α} (h : t ≤ s) :
countp p (s - t) = countp p s - countp p t :=
by simp [countp_eq_card_filter, h, filter_le_filter]
theorem countp_pos_of_mem {s a} (h : a ∈ s) (pa : p a) : 0 < countp p s :=
countp_pos.2 ⟨_, h, pa⟩
theorem countp_le_of_le {s t} (h : s ≤ t) : countp p s ≤ countp p t :=
by simpa [countp_eq_card_filter] using card_le_of_le (filter_le_filter h)
end
/- count -/
section
variable [decidable_eq α]
/-- `count a s` is the multiplicity of `a` in `s`. -/
def count (a : α) : multiset α → ℕ := countp (eq a)
@[simp] theorem coe_count (a : α) (l : list α) : count a (↑l) = l.count a := coe_countp _
@[simp] theorem count_zero (a : α) : count a 0 = 0 := rfl
@[simp] theorem count_cons_self (a : α) (s : multiset α) : count a (a::s) = succ (count a s) :=
countp_cons_of_pos _ rfl
@[simp] theorem count_cons_of_ne {a b : α} (h : a ≠ b) (s : multiset α) : count a (b::s) = count a s :=
countp_cons_of_neg _ h
theorem count_le_of_le (a : α) {s t} : s ≤ t → count a s ≤ count a t :=
countp_le_of_le
theorem count_le_count_cons (a b : α) (s : multiset α) : count a s ≤ count a (b :: s) :=
count_le_of_le _ (le_cons_self _ _)
theorem count_singleton (a : α) : count a (a::0) = 1 :=
by simp
@[simp] theorem count_add (a : α) : ∀ s t, count a (s + t) = count a s + count a t :=
countp_add
@[simp] theorem count_smul (a : α) (n s) : count a (n • s) = n * count a s :=
by induction n; simp [*, succ_smul', succ_mul]
theorem count_pos {a : α} {s : multiset α} : 0 < count a s ↔ a ∈ s :=
by simp [count, countp_pos]
@[simp] theorem count_eq_zero_of_not_mem {a : α} {l : list α} (h : a ∉ l) : count a l = 0 :=
by_contradiction $ λ h', h $ count_pos.1 (nat.pos_of_ne_zero h')
theorem count_eq_zero {a : α} {s : multiset α} : count a s = 0 ↔ a ∉ s :=
iff_not_comm.1 $ count_pos.symm.trans pos_iff_ne_zero
@[simp] theorem count_repeat (a : α) (n : ℕ) : count a (repeat a n) = n :=
by simp [repeat]
@[simp] theorem count_erase_self (a : α) (s : multiset α) : count a (erase s a) = pred (count a s) :=
begin
by_cases a ∈ s,
{ rw [(by rw cons_erase h : count a s = count a (a::erase s a)),
count_cons_self]; refl },
{ rw [erase_of_not_mem h, count_eq_zero.2 h]; refl }
end
@[simp] theorem count_erase_of_ne {a b : α} (ab : a ≠ b) (s : multiset α) : count a (erase s b) = count a s :=
begin
by_cases b ∈ s,
{ rw [← count_cons_of_ne ab, cons_erase h] },
{ rw [erase_of_not_mem h] }
end
@[simp] theorem count_sub (a : α) (s t : multiset α) : count a (s - t) = count a s - count a t :=
begin
revert s, refine multiset.induction_on t (by simp) (λ b t IH s, _),
rw [sub_cons, IH],
by_cases ab : a = b,
{ subst b, rw [count_erase_self, count_cons_self, sub_succ, pred_sub] },
{ rw [count_erase_of_ne ab, count_cons_of_ne ab] }
end
@[simp] theorem count_union (a : α) (s t : multiset α) : count a (s ∪ t) = max (count a s) (count a t) :=
by simp [(∪), union, sub_add_eq_max, -add_comm]
@[simp] theorem count_inter (a : α) (s t : multiset α) : count a (s ∩ t) = min (count a s) (count a t) :=
begin
apply @nat.add_left_cancel (count a (s - t)),
rw [← count_add, sub_add_inter, count_sub, sub_add_min],
end
lemma count_bind {m : multiset β} {f : β → multiset α} {a : α} :
count a (bind m f) = sum (m.map $ λb, count a $ f b) :=
multiset.induction_on m (by simp) (by simp)
theorem le_count_iff_repeat_le {a : α} {s : multiset α} {n : ℕ} : n ≤ count a s ↔ repeat a n ≤ s :=
quot.induction_on s $ λ l, le_count_iff_repeat_sublist.trans repeat_le_coe.symm
theorem ext {s t : multiset α} : s = t ↔ ∀ a, count a s = count a t :=
quotient.induction_on₂ s t $ λ l₁ l₂, quotient.eq.trans perm_iff_count
@[extensionality]
theorem ext' {s t : multiset α} : (∀ a, count a s = count a t) → s = t :=
ext.2
lemma bind_bind [decidable_eq γ] (m : multiset α) (n : multiset β) {f : α → β → multiset γ} :
(bind m $ λa, bind n $ λb, f a b) = (bind n $ λb, bind m $ λa, f a b) :=
by simp [multiset.ext, count_bind, multiset.sum_map_sum_map m n]
theorem le_iff_count {s t : multiset α} : s ≤ t ↔ ∀ a, count a s ≤ count a t :=
⟨λ h a, count_le_of_le a h, λ al,
by rw ← (ext.2 (λ a, by simp [max_eq_right (al a)]) : s ∪ t = t);
apply le_union_left⟩
instance : distrib_lattice (multiset α) :=
{ le_sup_inf := λ s t u, le_of_eq $ eq.symm $
ext.2 $ λ a, by simp [max_min_distrib_left],
..multiset.lattice.lattice }
instance : semilattice_sup_bot (multiset α) :=
{ bot := 0,
bot_le := zero_le,
..multiset.lattice.lattice }
end
/- disjoint -/
/-- `disjoint s t` means that `s` and `t` have no elements in common. -/
def disjoint (s t : multiset α) : Prop := ∀ ⦃a⦄, a ∈ s → a ∈ t → false
@[simp] theorem coe_disjoint (l₁ l₂ : list α) : @disjoint α l₁ l₂ ↔ l₁.disjoint l₂ := iff.rfl
theorem disjoint.symm {s t : multiset α} (d : disjoint s t) : disjoint t s
| a i₂ i₁ := d i₁ i₂
@[simp] theorem disjoint_comm {s t : multiset α} : disjoint s t ↔ disjoint t s :=
⟨disjoint.symm, disjoint.symm⟩
theorem disjoint_left {s t : multiset α} : disjoint s t ↔ ∀ {a}, a ∈ s → a ∉ t := iff.rfl
theorem disjoint_right {s t : multiset α} : disjoint s t ↔ ∀ {a}, a ∈ t → a ∉ s :=
disjoint_comm
theorem disjoint_iff_ne {s t : multiset α} : disjoint s t ↔ ∀ a ∈ s, ∀ b ∈ t, a ≠ b :=
by simp [disjoint_left, imp_not_comm]
theorem disjoint_of_subset_left {s t u : multiset α} (h : s ⊆ u) (d : disjoint u t) : disjoint s t
| x m₁ := d (h m₁)
theorem disjoint_of_subset_right {s t u : multiset α} (h : t ⊆ u) (d : disjoint s u) : disjoint s t
| x m m₁ := d m (h m₁)
theorem disjoint_of_le_left {s t u : multiset α} (h : s ≤ u) : disjoint u t → disjoint s t :=
disjoint_of_subset_left (subset_of_le h)
theorem disjoint_of_le_right {s t u : multiset α} (h : t ≤ u) : disjoint s u → disjoint s t :=
disjoint_of_subset_right (subset_of_le h)
@[simp] theorem zero_disjoint (l : multiset α) : disjoint 0 l
| a := (not_mem_nil a).elim
@[simp] theorem singleton_disjoint {l : multiset α} {a : α} : disjoint (a::0) l ↔ a ∉ l :=
by simp [disjoint]; refl
@[simp] theorem disjoint_singleton {l : multiset α} {a : α} : disjoint l (a::0) ↔ a ∉ l :=
by rw disjoint_comm; simp
@[simp] theorem disjoint_add_left {s t u : multiset α} :
disjoint (s + t) u ↔ disjoint s u ∧ disjoint t u :=
by simp [disjoint, or_imp_distrib, forall_and_distrib]
@[simp] theorem disjoint_add_right {s t u : multiset α} :
disjoint s (t + u) ↔ disjoint s t ∧ disjoint s u :=
disjoint_comm.trans $ by simp [disjoint_append_left]
@[simp] theorem disjoint_cons_left {a : α} {s t : multiset α} :
disjoint (a::s) t ↔ a ∉ t ∧ disjoint s t :=
(@disjoint_add_left _ (a::0) s t).trans $ by simp
@[simp] theorem disjoint_cons_right {a : α} {s t : multiset α} :
disjoint s (a::t) ↔ a ∉ s ∧ disjoint s t :=
disjoint_comm.trans $ by simp [disjoint_cons_left]
theorem inter_eq_zero_iff_disjoint [decidable_eq α] {s t : multiset α} : s ∩ t = 0 ↔ disjoint s t :=
by rw ← subset_zero; simp [subset_iff, disjoint]
@[simp] theorem disjoint_union_left [decidable_eq α] {s t u : multiset α} :
disjoint (s ∪ t) u ↔ disjoint s u ∧ disjoint t u :=
by simp [disjoint, or_imp_distrib, forall_and_distrib]
@[simp] theorem disjoint_union_right [decidable_eq α] {s t u : multiset α} :
disjoint s (t ∪ u) ↔ disjoint s t ∧ disjoint s u :=
by simp [disjoint, or_imp_distrib, forall_and_distrib]
lemma disjoint_map_map {f : α → γ} {g : β → γ} {s : multiset α} {t : multiset β} :
disjoint (s.map f) (t.map g) ↔ (∀a∈s, ∀b∈t, f a ≠ g b) :=
begin
simp [disjoint],
split,
from assume h a ha b hb eq, h _ ha rfl _ hb eq.symm,
from assume h c a ha eq₁ b hb eq₂, h _ ha _ hb (eq₂.symm ▸ eq₁)
end
/-- `pairwise r m` states that there exists a list of the elements s.t. `r` holds pairwise on this list. -/
def pairwise (r : α → α → Prop) (m : multiset α) : Prop :=
∃l:list α, m = l ∧ l.pairwise r
lemma pairwise_coe_iff_pairwise {r : α → α → Prop} (hr : symmetric r) {l : list α} :
multiset.pairwise r l ↔ l.pairwise r :=
iff.intro
(assume ⟨l', eq, h⟩, (list.perm_pairwise hr (quotient.exact eq)).2 h)
(assume h, ⟨l, rfl, h⟩)
/- nodup -/
/-- `nodup s` means that `s` has no duplicates, i.e. the multiplicity of
any element is at most 1. -/
def nodup (s : multiset α) : Prop :=
quot.lift_on s nodup (λ s t p, propext $ perm_nodup p)
@[simp] theorem coe_nodup {l : list α} : @nodup α l ↔ l.nodup := iff.rfl
@[simp] theorem forall_mem_ne {a : α} {l : list α} : (∀ (a' : α), a' ∈ l → ¬a = a') ↔ a ∉ l :=
⟨λ h m, h _ m rfl, λ h a' m e, h (e.symm ▸ m)⟩
@[simp] theorem nodup_zero : @nodup α 0 := pairwise.nil _
@[simp] theorem nodup_cons {a : α} {s : multiset α} : nodup (a::s) ↔ a ∉ s ∧ nodup s :=
quot.induction_on s $ λ l, nodup_cons
theorem nodup_cons_of_nodup {a : α} {s : multiset α} (m : a ∉ s) (n : nodup s) : nodup (a::s) :=
nodup_cons.2 ⟨m, n⟩
theorem nodup_singleton : ∀ a : α, nodup (a::0) := nodup_singleton
theorem nodup_of_nodup_cons {a : α} {s : multiset α} (h : nodup (a::s)) : nodup s :=
(nodup_cons.1 h).2
theorem not_mem_of_nodup_cons {a : α} {s : multiset α} (h : nodup (a::s)) : a ∉ s :=
(nodup_cons.1 h).1
theorem nodup_of_le {s t : multiset α} (h : s ≤ t) : nodup t → nodup s :=
le_induction_on h $ λ l₁ l₂, nodup_of_sublist
theorem not_nodup_pair : ∀ a : α, ¬ nodup (a::a::0) := not_nodup_pair
theorem nodup_iff_le {s : multiset α} : nodup s ↔ ∀ a : α, ¬ a::a::0 ≤ s :=
quot.induction_on s $ λ l, nodup_iff_sublist.trans $ forall_congr $ λ a,
not_congr (@repeat_le_coe _ a 2 _).symm
theorem nodup_iff_count_le_one [decidable_eq α] {s : multiset α} : nodup s ↔ ∀ a, count a s ≤ 1 :=
quot.induction_on s $ λ l, nodup_iff_count_le_one
@[simp] theorem count_eq_one_of_mem [decidable_eq α] {a : α} {s : multiset α}
(d : nodup s) (h : a ∈ s) : count a s = 1 :=
le_antisymm (nodup_iff_count_le_one.1 d a) (count_pos.2 h)
lemma pairwise_of_nodup {r : α → α → Prop} {s : multiset α} :
(∀a∈s, ∀b∈s, a ≠ b → r a b) → nodup s → pairwise r s :=
quotient.induction_on s $ assume l h hl, ⟨l, rfl, hl.imp_of_mem $ assume a b ha hb, h a ha b hb⟩
theorem nodup_add {s t : multiset α} : nodup (s + t) ↔ nodup s ∧ nodup t ∧ disjoint s t :=
quotient.induction_on₂ s t $ λ l₁ l₂, nodup_append
theorem disjoint_of_nodup_add {s t : multiset α} (d : nodup (s + t)) : disjoint s t :=
(nodup_add.1 d).2.2
theorem nodup_add_of_nodup {s t : multiset α} (d₁ : nodup s) (d₂ : nodup t) : nodup (s + t) ↔ disjoint s t :=
by simp [nodup_add, d₁, d₂]
theorem nodup_of_nodup_map (f : α → β) {s : multiset α} : nodup (map f s) → nodup s :=
quot.induction_on s $ λ l, nodup_of_nodup_map f
theorem nodup_map_on {f : α → β} {s : multiset α} : (∀x∈s, ∀y∈s, f x = f y → x = y) →
nodup s → nodup (map f s) :=
quot.induction_on s $ λ l, nodup_map_on
theorem nodup_map {f : α → β} {s : multiset α} (hf : function.injective f) : nodup s → nodup (map f s) :=
nodup_map_on (λ x _ y _ h, hf h)
theorem nodup_filter (p : α → Prop) [decidable_pred p] {s} : nodup s → nodup (filter p s) :=
quot.induction_on s $ λ l, nodup_filter p
@[simp] theorem nodup_attach {s : multiset α} : nodup (attach s) ↔ nodup s :=
quot.induction_on s $ λ l, nodup_attach
theorem nodup_pmap {p : α → Prop} {f : Π a, p a → β} {s : multiset α} {H}
(hf : ∀ a ha b hb, f a ha = f b hb → a = b) : nodup s → nodup (pmap f s H) :=
quot.induction_on s (λ l H, nodup_pmap hf) H
instance nodup_decidable [decidable_eq α] (s : multiset α) : decidable (nodup s) :=
quotient.rec_on_subsingleton s $ λ l, l.nodup_decidable
theorem nodup_erase_eq_filter [decidable_eq α] (a : α) {s} : nodup s → s.erase a = filter (≠ a) s :=
quot.induction_on s $ λ l d, congr_arg coe $ nodup_erase_eq_filter a d
theorem nodup_erase_of_nodup [decidable_eq α] (a : α) {l} : nodup l → nodup (l.erase a) :=
nodup_of_le (erase_le _ _)
theorem mem_erase_iff_of_nodup [decidable_eq α] {a b : α} {l} (d : nodup l) :
a ∈ l.erase b ↔ a ≠ b ∧ a ∈ l :=
by rw nodup_erase_eq_filter b d; simp [and_comm]
theorem mem_erase_of_nodup [decidable_eq α] {a : α} {l} (h : nodup l) : a ∉ l.erase a :=
by rw mem_erase_iff_of_nodup h; simp
theorem nodup_product {s : multiset α} {t : multiset β} : nodup s → nodup t → nodup (product s t) :=
quotient.induction_on₂ s t $ λ l₁ l₂ d₁ d₂, by simp [nodup_product d₁ d₂]
theorem nodup_sigma {σ : α → Type*} {s : multiset α} {t : Π a, multiset (σ a)} :
nodup s → (∀ a, nodup (t a)) → nodup (s.sigma t) :=
quot.induction_on s $ λ l₁,
let l₂ (a) : list (σ a) := classical.some (quotient.exists_rep (t a)) in
have t = λ a, l₂ a, from eq.symm $ funext $ λ a,
classical.some_spec (quotient.exists_rep (t a)),
by rw [this]; simpa using nodup_sigma
theorem nodup_filter_map (f : α → option β) {s : multiset α}
(H : ∀ (a a' : α) (b : β), b ∈ f a → b ∈ f a' → a = a') :
nodup s → nodup (filter_map f s) :=
quot.induction_on s $ λ l, nodup_filter_map H
theorem nodup_range (n : ℕ) : nodup (range n) := nodup_range _
theorem nodup_inter_left [decidable_eq α] {s : multiset α} (t) : nodup s → nodup (s ∩ t) :=
nodup_of_le $ inter_le_left _ _
theorem nodup_inter_right [decidable_eq α] (s) {t : multiset α} : nodup t → nodup (s ∩ t) :=
nodup_of_le $ inter_le_right _ _
@[simp] theorem nodup_union [decidable_eq α] {s t : multiset α} : nodup (s ∪ t) ↔ nodup s ∧ nodup t :=
⟨λ h, ⟨nodup_of_le (le_union_left _ _) h, nodup_of_le (le_union_right _ _) h⟩,
λ ⟨h₁, h₂⟩, nodup_iff_count_le_one.2 $ λ a, by rw [count_union]; exact
max_le (nodup_iff_count_le_one.1 h₁ a) (nodup_iff_count_le_one.1 h₂ a)⟩
@[simp] theorem nodup_powerset {s : multiset α} : nodup (powerset s) ↔ nodup s :=
⟨λ h, nodup_of_nodup_map _ (nodup_of_le (map_single_le_powerset _) h),
quotient.induction_on s $ λ l h,
by simp; refine list.nodup_map_on _ (nodup_sublists'.2 h); exact
λ x sx y sy e,
(perm_ext_sublist_nodup h (mem_sublists'.1 sx) (mem_sublists'.1 sy)).1
(quotient.exact e)⟩
@[simp] lemma nodup_bind {s : multiset α} {t : α → multiset β} :
nodup (bind s t) ↔ ((∀a∈s, nodup (t a)) ∧ (s.pairwise (λa b, disjoint (t a) (t b)))) :=
have h₁ : ∀a, ∃l:list β, t a = l, from
assume a, quot.induction_on (t a) $ assume l, ⟨l, rfl⟩,
let ⟨t', h'⟩ := classical.axiom_of_choice h₁ in
have t = λa, t' a, from funext h',
have hd : symmetric (λa b, list.disjoint (t' a) (t' b)), from assume a b h, h.symm,
quot.induction_on s $ by simp [this, list.nodup_bind, pairwise_coe_iff_pairwise hd]
theorem nodup_ext {s t : multiset α} : nodup s → nodup t → (s = t ↔ ∀ a, a ∈ s ↔ a ∈ t) :=
quotient.induction_on₂ s t $ λ l₁ l₂ d₁ d₂, quotient.eq.trans $ perm_ext d₁ d₂
theorem le_iff_subset {s t : multiset α} : nodup s → (s ≤ t ↔ s ⊆ t) :=
quotient.induction_on₂ s t $ λ l₁ l₂ d, ⟨subset_of_le, subperm_of_subset_nodup d⟩
theorem range_le {m n : ℕ} : range m ≤ range n ↔ m ≤ n :=
(le_iff_subset (nodup_range _)).trans range_subset
theorem mem_sub_of_nodup [decidable_eq α] {a : α} {s t : multiset α} (d : nodup s) :
a ∈ s - t ↔ a ∈ s ∧ a ∉ t :=
⟨λ h, ⟨mem_of_le (sub_le_self _ _) h, λ h',
by refine count_eq_zero.1 _ h; rw [count_sub a s t, nat.sub_eq_zero_iff_le];
exact le_trans (nodup_iff_count_le_one.1 d _) (count_pos.2 h')⟩,
λ ⟨h₁, h₂⟩, or.resolve_right (mem_add.1 $ mem_of_le (le_sub_add _ _) h₁) h₂⟩
section
variable [decidable_eq α]
/- erase_dup -/
/-- `erase_dup s` removes duplicates from `s`, yielding a `nodup` multiset. -/
def erase_dup (s : multiset α) : multiset α :=
quot.lift_on s (λ l, (l.erase_dup : multiset α))
(λ s t p, quot.sound (perm_erase_dup_of_perm p))
@[simp] theorem coe_erase_dup (l : list α) : @erase_dup α _ l = l.erase_dup := rfl
@[simp] theorem erase_dup_zero : @erase_dup α _ 0 = 0 := rfl
@[simp] theorem mem_erase_dup {a : α} {s : multiset α} : a ∈ erase_dup s ↔ a ∈ s :=
quot.induction_on s $ λ l, mem_erase_dup
@[simp] theorem erase_dup_cons_of_mem {a : α} {s : multiset α} : a ∈ s →
erase_dup (a::s) = erase_dup s :=
quot.induction_on s $ λ l m, @congr_arg _ _ _ _ coe $ erase_dup_cons_of_mem m
@[simp] theorem erase_dup_cons_of_not_mem {a : α} {s : multiset α} : a ∉ s →
erase_dup (a::s) = a :: erase_dup s :=
quot.induction_on s $ λ l m, congr_arg coe $ erase_dup_cons_of_not_mem m
theorem erase_dup_le (s : multiset α) : erase_dup s ≤ s :=
quot.induction_on s $ λ l, subperm_of_sublist $ erase_dup_sublist _
theorem erase_dup_subset (s : multiset α) : erase_dup s ⊆ s :=
subset_of_le $ erase_dup_le _
theorem subset_erase_dup (s : multiset α) : s ⊆ erase_dup s :=
λ a, mem_erase_dup.2
@[simp] theorem erase_dup_subset' {s t : multiset α} : erase_dup s ⊆ t ↔ s ⊆ t :=
⟨subset.trans (subset_erase_dup _), subset.trans (erase_dup_subset _)⟩
@[simp] theorem subset_erase_dup' {s t : multiset α} : s ⊆ erase_dup t ↔ s ⊆ t :=
⟨λ h, subset.trans h (erase_dup_subset _), λ h, subset.trans h (subset_erase_dup _)⟩
@[simp] theorem nodup_erase_dup (s : multiset α) : nodup (erase_dup s) :=
quot.induction_on s nodup_erase_dup
theorem erase_dup_eq_self {s : multiset α} : erase_dup s = s ↔ nodup s :=
⟨λ e, e ▸ nodup_erase_dup s,
quot.induction_on s $ λ l h, congr_arg coe $ erase_dup_eq_self.2 h⟩
theorem le_erase_dup {s t : multiset α} : s ≤ erase_dup t ↔ s ≤ t ∧ nodup s :=
⟨λ h, ⟨le_trans h (erase_dup_le _), nodup_of_le h (nodup_erase_dup _)⟩,
λ ⟨l, d⟩, (le_iff_subset d).2 $ subset.trans (subset_of_le l) (subset_erase_dup _)⟩
theorem erase_dup_ext {s t : multiset α} : erase_dup s = erase_dup t ↔ ∀ a, a ∈ s ↔ a ∈ t :=
by simp [nodup_ext]
theorem erase_dup_map_erase_dup_eq [decidable_eq β] (f : α → β) (s : multiset α) :
erase_dup (map f (erase_dup s)) = erase_dup (map f s) := by simp [erase_dup_ext]
/- finset insert -/
/-- `ndinsert a s` is the lift of the list `insert` operation. This operation
does not respect multiplicities, unlike `cons`, but it is suitable as
an insert operation on `finset`. -/
def ndinsert (a : α) (s : multiset α) : multiset α :=
quot.lift_on s (λ l, (l.insert a : multiset α))
(λ s t p, quot.sound (perm_insert a p))
@[simp] theorem coe_ndinsert (a : α) (l : list α) : ndinsert a l = (insert a l : list α) := rfl
@[simp] theorem ndinsert_zero (a : α) : ndinsert a 0 = a::0 := rfl
@[simp] theorem ndinsert_of_mem {a : α} {s : multiset α} : a ∈ s → ndinsert a s = s :=
quot.induction_on s $ λ l h, congr_arg coe $ insert_of_mem h
@[simp] theorem ndinsert_of_not_mem {a : α} {s : multiset α} : a ∉ s → ndinsert a s = a :: s :=
quot.induction_on s $ λ l h, congr_arg coe $ insert_of_not_mem h
@[simp] theorem mem_ndinsert {a b : α} {s : multiset α} : a ∈ ndinsert b s ↔ a = b ∨ a ∈ s :=
quot.induction_on s $ λ l, mem_insert_iff
@[simp] theorem le_ndinsert_self (a : α) (s : multiset α) : s ≤ ndinsert a s :=
quot.induction_on s $ λ l, subperm_of_sublist $ sublist_of_suffix $ suffix_insert _ _
@[simp] theorem mem_ndinsert_self (a : α) (s : multiset α) : a ∈ ndinsert a s :=
mem_ndinsert.2 (or.inl rfl)
@[simp] theorem mem_ndinsert_of_mem {a b : α} {s : multiset α} (h : a ∈ s) : a ∈ ndinsert b s :=
mem_ndinsert.2 (or.inr h)
@[simp] theorem length_ndinsert_of_mem {a : α} [decidable_eq α] {s : multiset α} (h : a ∈ s) :
card (ndinsert a s) = card s :=
by simp [h]
@[simp] theorem length_ndinsert_of_not_mem {a : α} [decidable_eq α] {s : multiset α} (h : a ∉ s) :
card (ndinsert a s) = card s + 1 :=
by simp [h]
theorem erase_dup_cons {a : α} {s : multiset α} :
erase_dup (a::s) = ndinsert a (erase_dup s) :=
by by_cases a ∈ s; simp [h]
theorem nodup_ndinsert (a : α) {s : multiset α} : nodup s → nodup (ndinsert a s) :=
quot.induction_on s $ λ l, nodup_insert
theorem ndinsert_le {a : α} {s t : multiset α} : ndinsert a s ≤ t ↔ s ≤ t ∧ a ∈ t :=
⟨λ h, ⟨le_trans (le_ndinsert_self _ _) h, mem_of_le h (mem_ndinsert_self _ _)⟩,
λ ⟨l, m⟩, if h : a ∈ s then by simp [h, l] else
by rw [ndinsert_of_not_mem h, ← cons_erase m, cons_le_cons_iff,
← le_cons_of_not_mem h, cons_erase m]; exact l⟩
lemma attach_ndinsert (a : α) (s : multiset α) :
(s.ndinsert a).attach =
ndinsert ⟨a, mem_ndinsert_self a s⟩ (s.attach.map $ λp, ⟨p.1, mem_ndinsert_of_mem p.2⟩) :=
have eq : ∀h : ∀(p : {x // x ∈ s}), p.1 ∈ s,
(λ (p : {x // x ∈ s}), ⟨p.val, h p⟩ : {x // x ∈ s} → {x // x ∈ s}) = id, from
assume h, funext $ assume p, subtype.eq rfl,
have ∀t (eq : s.ndinsert a = t), t.attach = ndinsert ⟨a, eq ▸ mem_ndinsert_self a s⟩
(s.attach.map $ λp, ⟨p.1, eq ▸ mem_ndinsert_of_mem p.2⟩),
begin
intros t ht,
by_cases a ∈ s,
{ rw [ndinsert_of_mem h] at ht,
subst ht,
rw [eq, map_id, ndinsert_of_mem (mem_attach _ _)] },
{ rw [ndinsert_of_not_mem h] at ht,
subst ht,
simp [attach_cons, h] }
end,
this _ rfl
@[simp] theorem disjoint_ndinsert_left {a : α} {s t : multiset α} :
disjoint (ndinsert a s) t ↔ a ∉ t ∧ disjoint s t :=
iff.trans (by simp [disjoint]) disjoint_cons_left
@[simp] theorem disjoint_ndinsert_right {a : α} {s t : multiset α} :
disjoint s (ndinsert a t) ↔ a ∉ s ∧ disjoint s t :=
disjoint_comm.trans $ by simp
/- finset union -/
/-- `ndunion s t` is the lift of the list `union` operation. This operation
does not respect multiplicities, unlike `s ∪ t`, but it is suitable as
a union operation on `finset`. (`s ∪ t` would also work as a union operation
on finset, but this is more efficient.) -/
def ndunion (s t : multiset α) : multiset α :=
quotient.lift_on₂ s t (λ l₁ l₂, (l₁.union l₂ : multiset α)) $ λ v₁ v₂ w₁ w₂ p₁ p₂,
quot.sound $ perm_union p₁ p₂
@[simp] theorem coe_ndunion (l₁ l₂ : list α) : @ndunion α _ l₁ l₂ = (l₁ ∪ l₂ : list α) := rfl
@[simp] theorem zero_ndunion (s : multiset α) : ndunion 0 s = s :=
quot.induction_on s $ λ l, rfl
@[simp] theorem cons_ndunion (s t : multiset α) (a : α) : ndunion (a :: s) t = ndinsert a (ndunion s t) :=
quotient.induction_on₂ s t $ λ l₁ l₂, rfl
@[simp] theorem mem_ndunion {s t : multiset α} {a : α} : a ∈ ndunion s t ↔ a ∈ s ∨ a ∈ t :=
quotient.induction_on₂ s t $ λ l₁ l₂, list.mem_union
theorem le_ndunion_right (s t : multiset α) : t ≤ ndunion s t :=
quotient.induction_on₂ s t $ λ l₁ l₂,
subperm_of_sublist $ sublist_of_suffix $ suffix_union_right _ _
theorem ndunion_le_add (s t : multiset α) : ndunion s t ≤ s + t :=
quotient.induction_on₂ s t $ λ l₁ l₂, subperm_of_sublist $ union_sublist_append _ _
theorem ndunion_le {s t u : multiset α} : ndunion s t ≤ u ↔ s ⊆ u ∧ t ≤ u :=
multiset.induction_on s (by simp) (by simp [ndinsert_le, and_comm, and.left_comm] {contextual := tt})
theorem subset_ndunion_left (s t : multiset α) : s ⊆ ndunion s t :=
λ a h, mem_ndunion.2 $ or.inl h
theorem le_ndunion_left {s} (t : multiset α) (d : nodup s) : s ≤ ndunion s t :=
(le_iff_subset d).2 $ subset_ndunion_left _ _
theorem ndunion_le_union (s t : multiset α) : ndunion s t ≤ s ∪ t :=
ndunion_le.2 ⟨subset_of_le (le_union_left _ _), le_union_right _ _⟩
theorem nodup_ndunion (s : multiset α) {t : multiset α} : nodup t → nodup (ndunion s t) :=
quotient.induction_on₂ s t $ λ l₁ l₂, list.nodup_union _
@[simp] theorem ndunion_eq_union {s t : multiset α} (d : nodup s) : ndunion s t = s ∪ t :=
le_antisymm (ndunion_le_union _ _) $ union_le (le_ndunion_left _ d) (le_ndunion_right _ _)
theorem erase_dup_add (s t : multiset α) : erase_dup (s + t) = ndunion s (erase_dup t) :=
quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe $ erase_dup_append _ _
/- finset inter -/
/-- `ndinter s t` is the lift of the list `∩` operation. This operation
does not respect multiplicities, unlike `s ∩ t`, but it is suitable as
an intersection operation on `finset`. (`s ∩ t` would also work as a union operation
on finset, but this is more efficient.) -/
def ndinter (s t : multiset α) : multiset α := filter (∈ t) s
@[simp] theorem coe_ndinter (l₁ l₂ : list α) : @ndinter α _ l₁ l₂ = (l₁ ∩ l₂ : list α) := rfl
@[simp] theorem zero_ndinter (s : multiset α) : ndinter 0 s = 0 := rfl
@[simp] theorem cons_ndinter_of_mem {a : α} (s : multiset α) {t : multiset α} (h : a ∈ t) :
ndinter (a::s) t = a :: (ndinter s t) := by simp [ndinter, h]
@[simp] theorem ndinter_cons_of_not_mem {a : α} (s : multiset α) {t : multiset α} (h : a ∉ t) :
ndinter (a::s) t = ndinter s t := by simp [ndinter, h]
@[simp] theorem mem_ndinter {s t : multiset α} {a : α} : a ∈ ndinter s t ↔ a ∈ s ∧ a ∈ t :=
mem_filter
theorem nodup_ndinter {s : multiset α} (t : multiset α) : nodup s → nodup (ndinter s t) :=
nodup_filter _
theorem le_ndinter {s t u : multiset α} : s ≤ ndinter t u ↔ s ≤ t ∧ s ⊆ u :=
by simp [ndinter, le_filter, subset_iff]
theorem ndinter_le_left (s t : multiset α) : ndinter s t ≤ s :=
(le_ndinter.1 (le_refl _)).1
theorem ndinter_subset_right (s t : multiset α) : ndinter s t ⊆ t :=
(le_ndinter.1 (le_refl _)).2
theorem ndinter_le_right {s} (t : multiset α) (d : nodup s) : ndinter s t ≤ t :=
(le_iff_subset $ nodup_ndinter _ d).2 (ndinter_subset_right _ _)
theorem inter_le_ndinter (s t : multiset α) : s ∩ t ≤ ndinter s t :=
le_ndinter.2 ⟨inter_le_left _ _, subset_of_le $ inter_le_right _ _⟩
@[simp] theorem ndinter_eq_inter {s t : multiset α} (d : nodup s) : ndinter s t = s ∩ t :=
le_antisymm (le_inter (ndinter_le_left _ _) (ndinter_le_right _ d)) (inter_le_ndinter _ _)
theorem ndinter_eq_zero_iff_disjoint {s t : multiset α} : ndinter s t = 0 ↔ disjoint s t :=
by rw ← subset_zero; simp [subset_iff, disjoint]
end
/- fold -/
section fold
variables (op : α → α → α) [hc : is_commutative α op] [ha : is_associative α op]
local notation a * b := op a b
include hc ha
/-- `fold op b s` folds a commutative associative operation `op` over
the multiset `s`. -/
def fold : α → multiset α → α := foldr op (left_comm _ hc.comm ha.assoc)
theorem fold_eq_foldr (b : α) (s : multiset α) : fold op b s = foldr op (left_comm _ hc.comm ha.assoc) b s := rfl
@[simp] theorem coe_fold_r (b : α) (l : list α) : fold op b l = l.foldr op b := rfl
theorem coe_fold_l (b : α) (l : list α) : fold op b l = l.foldl op b :=
(coe_foldr_swap op _ b l).trans $ by simp [hc.comm]
theorem fold_eq_foldl (b : α) (s : multiset α) : fold op b s = foldl op (right_comm _ hc.comm ha.assoc) b s :=
quot.induction_on s $ λ l, coe_fold_l _ _ _
@[simp] theorem fold_zero (b : α) : (0 : multiset α).fold op b = b := rfl
@[simp] theorem fold_cons_left : ∀ (b a : α) (s : multiset α),
(a :: s).fold op b = a * s.fold op b := foldr_cons _ _
theorem fold_cons_right (b a : α) (s : multiset α) : (a :: s).fold op b = s.fold op b * a :=
by simp [hc.comm]
theorem fold_cons'_right (b a : α) (s : multiset α) : (a :: s).fold op b = s.fold op (b * a) :=
by rw [fold_eq_foldl, foldl_cons, ← fold_eq_foldl]
theorem fold_cons'_left (b a : α) (s : multiset α) : (a :: s).fold op b = s.fold op (a * b) :=
by rw [fold_cons'_right, hc.comm]
theorem fold_add (b₁ b₂ : α) (s₁ s₂ : multiset α) : (s₁ + s₂).fold op (b₁ * b₂) = s₁.fold op b₁ * s₂.fold op b₂ :=
multiset.induction_on s₂
(by rw [add_zero, fold_zero, ← fold_cons'_right, ← fold_cons_right op])
(by simp {contextual := tt}; cc)
theorem fold_singleton (b a : α) : (a::0 : multiset α).fold op b = a * b := by simp
theorem fold_distrib {f g : β → α} (u₁ u₂ : α) (s : multiset β) :
(s.map (λx, f x * g x)).fold op (u₁ * u₂) = (s.map f).fold op u₁ * (s.map g).fold op u₂ :=
multiset.induction_on s (by simp) (by simp {contextual := tt}; cc)
theorem fold_hom {op' : β → β → β} [is_commutative β op'] [is_associative β op']
{m : α → β} (hm : ∀x y, m (op x y) = op' (m x) (m y)) (b : α) (s : multiset α) :
(s.map m).fold op' (m b) = m (s.fold op b) :=
multiset.induction_on s (by simp) (by simp [hm] {contextual := tt})
theorem fold_union_inter [decidable_eq α] (s₁ s₂ : multiset α) (b₁ b₂ : α) :
(s₁ ∪ s₂).fold op b₁ * (s₁ ∩ s₂).fold op b₂ = s₁.fold op b₁ * s₂.fold op b₂ :=
by rw [← fold_add op, union_add_inter, fold_add op]
@[simp] theorem fold_erase_dup_idem [decidable_eq α] [hi : is_idempotent α op] (s : multiset α) (b : α) :
(erase_dup s).fold op b = s.fold op b :=
multiset.induction_on s (by simp) $ λ a s IH, begin
by_cases a ∈ s; simp [IH, h],
show fold op b s = op a (fold op b s),
rw [← cons_erase h, fold_cons_left, ← ha.assoc, hi.idempotent],
end
end fold
theorem le_smul_erase_dup [decidable_eq α] (s : multiset α) :
∃ n : ℕ, s ≤ n • erase_dup s :=
⟨(s.map (λ a, count a s)).fold max 0, le_iff_count.2 $ λ a, begin
rw count_smul, by_cases a ∈ s,
{ refine le_trans _ (mul_le_mul_left _ $ count_pos.2 $ mem_erase_dup.2 h),
have : count a s ≤ fold max 0 (map (λ a, count a s) (a :: erase s a));
[simp [le_max_left], simpa [cons_erase h]] },
{ simp [count_eq_zero.2 h, nat.zero_le] }
end⟩
section sort
variables (r : α → α → Prop) [decidable_rel r]
[tr : is_trans α r] [an : is_antisymm α r] [to : is_total α r]
include tr an to
/-- `sort s` constructs a sorted list from the multiset `s`.
(Uses merge sort algorithm.) -/
def sort (s : multiset α) : list α :=
quot.lift_on s (merge_sort r) $ λ a b h,
eq_of_sorted_of_perm tr.trans an.antisymm
((perm_merge_sort _ _).trans $ h.trans (perm_merge_sort _ _).symm)
(sorted_merge_sort r to.total tr.trans _)
(sorted_merge_sort r to.total tr.trans _)
@[simp] theorem coe_sort (l : list α) : sort r l = merge_sort r l := rfl
@[simp] theorem sort_sorted (s : multiset α) : sorted r (sort r s) :=
quot.induction_on s $ λ l, sorted_merge_sort r to.total tr.trans _
@[simp] theorem sort_eq (s : multiset α) : ↑(sort r s) = s :=
quot.induction_on s $ λ l, quot.sound $ perm_merge_sort _ _
end sort
section pi
variables [decidable_eq α] {δ : α → Type*} [∀a, decidable_eq (δ a)]
open function
def pi.cons (m : multiset α) (a : α) (b : δ a) (f : Πa∈m, δ a) : Πa'∈a::m, δ a' :=
λa' ha', if h : a' = a then eq.rec b h.symm else f a' $ (mem_cons.1 ha').resolve_left h
def pi.empty (δ : α → Type*) : (Πa∈(0:multiset α), δ a) .
lemma pi.cons_same {m : multiset α} {a : α} {b : δ a} {f : Πa∈m, δ a} (h : a ∈ a :: m) :
pi.cons m a b f a h = b :=
dif_pos rfl
lemma pi.cons_ne {m : multiset α} {a a' : α} {b : δ a} {f : Πa∈m, δ a} (h' : a' ∈ a :: m) (h : a' ≠ a) :
pi.cons m a b f a' h' = f a' ((mem_cons.1 h').resolve_left h) :=
dif_neg h
lemma pi.cons_swap {a a' : α} {b : δ a} {b' : δ a'} {m : multiset α} {f : Πa∈m, δ a} (h : a ≠ a') :
pi.cons (a' :: m) a b (pi.cons m a' b' f) == pi.cons (a :: m) a' b' (pi.cons m a b f) :=
begin
apply hfunext, { refl }, intros a'' _ h, subst h,
apply hfunext, { rw [cons_swap] }, intros ha₁ ha₂ h,
by_cases h₁ : a'' = a; by_cases h₂ : a'' = a';
simp [*, pi.cons_same, pi.cons_ne] at *,
{ subst h₁, rw [pi.cons_same, pi.cons_same] },
{ subst h₂, rw [pi.cons_same, pi.cons_same] }
end
/-- `pi m t` constructs the Cartesian product over `t` indexed by `m`. -/
def pi (m : multiset α) (t : Πa, multiset (δ a)) : multiset (Πa∈m, δ a) :=
m.rec_on { pi.empty δ } (λa m (p : multiset (Πa∈m, δ a)), (t a).bind $ λb, p.map $ pi.cons m a b)
begin
intros a a' m n,
by_cases eq : a = a',
{ subst eq },
{ simp [map_bind, bind_bind (t a') (t a)],
apply bind_hcongr, { rw [cons_swap a a'] },
intros b hb,
apply bind_hcongr, { rw [cons_swap a a'] },
intros b' hb',
apply map_hcongr, { rw [cons_swap a a'] },
intros f hf,
exact pi.cons_swap eq }
end
@[simp] lemma pi_zero (t : Πa, multiset (δ a)) : pi 0 t = {pi.empty δ} :=
rfl
@[simp] lemma pi_cons (m : multiset α) (t : Πa, multiset (δ a)) (a : α) :
pi (a :: m) t = ((t a).bind $ λb, (pi m t).map $ pi.cons m a b) :=
rec_on_cons a m
lemma injective_pi_cons {a : α} {b : δ a} {s : multiset α} (hs : a ∉ s) :
function.injective (pi.cons s a b) :=
assume f₁ f₂ eq, funext $ assume a', funext $ assume h',
have ne : a ≠ a', from assume h, hs $ h.symm ▸ h',
have a' ∈ a :: s, from mem_cons_of_mem h',
calc f₁ a' h' = pi.cons s a b f₁ a' this : by rw [pi.cons_ne this ne.symm]
... = pi.cons s a b f₂ a' this : by rw [eq]
... = f₂ a' h' : by rw [pi.cons_ne this ne.symm]
lemma card_pi (m : multiset α) (t : Πa, multiset (δ a)) :
card (pi m t) = prod (m.map $ λa, card (t a)) :=
multiset.induction_on m (by simp) (by simp [mul_comm] {contextual := tt})
lemma nodup_pi {s : multiset α} {t : Πa, multiset (δ a)} :
nodup s → (∀a∈s, nodup (t a)) → nodup (pi s t) :=
multiset.induction_on s (assume _ _ , nodup_singleton _)
begin
assume a s ih hs ht,
have has : a ∉ s, by simp at hs; exact hs.1,
have hs : nodup s, by simp at hs; exact hs.2,
simp,
split,
{ assume b hb,
from nodup_map (injective_pi_cons has) (ih hs $ assume a' h', ht a' $ mem_cons_of_mem h') },
{ apply pairwise_of_nodup _ (ht a $ mem_cons_self _ _),
from assume b₁ hb₁ b₂ hb₂ neb, disjoint_map_map.2 (assume f hf g hg eq,
have pi.cons s a b₁ f a (mem_cons_self _ _) = pi.cons s a b₂ g a (mem_cons_self _ _),
by rw [eq],
neb $ show b₁ = b₂, by rwa [pi.cons_same, pi.cons_same] at this) }
end
lemma mem_pi (m : multiset α) (t : Πa, multiset (δ a)) :
∀f:Πa∈m, δ a, (f ∈ pi m t) ↔ (∀a (h : a ∈ m), f a h ∈ t a) :=
multiset.induction_on m
begin
assume f,
have : f = pi.empty δ, { funext a ha, exact ha.elim },
subst this,
split,
{ intros _ a ha, exact ha.elim },
{ intros, simp, exact mem_cons_self _ 0 }
end
begin
assume a m ih f,
simp [iff_def],
split,
{ intros b hb f' hf' eq a' ha',
subst eq,
rw [ih] at hf',
by_cases a' = a,
{ subst h,
rw [pi.cons_same],
exact hb },
{ rw [pi.cons_ne _ h],
exact hf' _ _ } },
{ assume hf,
refine ⟨f a (mem_cons_self a _), hf a (mem_cons_self a _), (λa ha, f a (mem_cons_of_mem ha)), _, _⟩,
{ rw [ih],
assume a' h', exact hf _ _ },
{ funext a' h',
by_cases a' = a,
{ subst h, rw [pi.cons_same] },
{ rw [pi.cons_ne _ h] } } }
end
end pi
end multiset
|
b1cb1b434206c98ad1e0bf088b2238439aa5bc6e | c3f2fcd060adfa2ca29f924839d2d925e8f2c685 | /tests/lean/run/basic.lean | f54dfcb7da7ce06b566f6e2e64e48ac0668ab37a | [
"Apache-2.0"
] | permissive | respu/lean | 6582d19a2f2838a28ecd2b3c6f81c32d07b5341d | 8c76419c60b63d0d9f7bc04ebb0b99812d0ec654 | refs/heads/master | 1,610,882,451,231 | 1,427,747,084,000 | 1,427,747,429,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,655 | lean | prelude
constant A.{l1 l2} : Type.{l1} → Type.{l2}
check A
definition tst.{l} (A : Type) (B : Type) (C : Type.{l}) : Type := A → B → C
check tst
constant group.{l} : Type.{l+1}
constant carrier.{l} : group.{l} → Type.{l}
definition to_carrier (g : group) := carrier g
check to_carrier.{1}
section
variable A : Type
check A
definition B := A → A
end
constant N : Type.{1}
check B N
constant f : B N
check f
constant a : N
check f a
section
variable T1 : Type
variable T2 : Type
variable f : T1 → T2 → T2
definition double (a : T1) (b : T2) := f a (f a b)
end
check double
check double.{1 2}
definition Prop := Type.{0}
constant eq : Π {A : Type}, A → A → Prop
infix `=`:50 := eq
check eq.{1}
context
universe l
universe u
variable {T1 : Type.{l}}
variable {T2 : Type.{l}}
variable {T3 : Type.{u}}
variable f : T1 → T2 → T2
definition is_proj2 := ∀ x y, f x y = y
definition is_proj3 (f : T1 → T2 → T3 → T3) := ∀ x y z, f x y z = z
end
check @is_proj2.{1}
check @is_proj3.{1 2}
namespace foo
section
variables {T1 T2 : Type}
variable {T3 : Type}
variable f : T1 → T2 → T2
definition is_proj2 := ∀ x y, f x y = y
definition is_proj3 (f : T1 → T2 → T3 → T3) := ∀ x y z, f x y z = z
end
check @foo.is_proj2.{1}
check @foo.is_proj3.{1 2}
end foo
namespace bla
section
variable {T1 : Type}
variable {T2 : Type}
variable {T3 : Type}
variable f : T1 → T2 → T2
definition is_proj2 := ∀ x y, f x y = y
definition is_proj3 (f : T1 → T2 → T3 → T3) := ∀ x y z, f x y z = z
end
check @bla.is_proj2.{1 2}
check @bla.is_proj3.{1 2 3}
end bla
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.